Flutter: Getting "Null check operator used on a null value" error creating MaterialColor

Question: I'm creating a custom MaterialColor object but it's throwing that error.
colors.dart (where I'm creating the MaterialColor object)
import 'package:flutter/material.dart';

class JarsColors {
  static const MaterialColor palette = MaterialColor(
    0xFF276678,
    <int, Color> {
      0: Color(0xFFF6F5F5),
      100: Color(0xFFD3E0EA),
      400: Color(0xFF1687A7),
      500: Color(0xFF276678),
    }
  );
}

main.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: JarsColors.palette,
      ),
      home: JarsHome(title: 'Hello'),
    );
  }
}

Error output:
The following _CastError was thrown building MyApp(dirty):
Null check operator used on a null value

The relevant error-causing widget was
MyApp
When the exception was thrown, this was the stack
#0      new ThemeData
#1      MyApp.build
#2      StatelessElement.build
#3      ComponentElement.performRebuild
#4      Element.rebuild

flutter doctor output
λ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.3, on Microsoft Windows [Version 10.0.19042.928], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] VS Code (version 1.55.2)
[√] Connected device (3 available)

• No issues found!

Comment: JarsColors.palette look null from error, can you print to see if outputs anything
Comment: @flakerimi it outputs `I/flutter ( 6706): MaterialColor(primary value: Color(0xff276678))
`
Answer: I managed to make it work by adding more shades to the MaterialColor swatch argument:
class JarsColors {
  static const MaterialColor palette = MaterialColor(
    0xFF276678,
    <int, Color> {
      50: Color(0xFFF6F5F5),
      100: Color(0xFFD3E0EA),
      200: Color(0xFFD3E0EA),
      300: Color(0xFFD3E0EA),
      400: Color(0xFF1687A7),
      500: Color(0xFF276678),
      600: Color(0xFFD3E0EA),
      700: Color(0xFF1687A7),
    }
  );
}

With the help of: https://api.flutter.dev/flutter/material/MaterialColor-class.html
Nonetheless I can't find an explanation to this. It'd be great to know.
Answer: To keep answer short and straight forward, when defining MaterialColor you must start from 50, then 100 and increments in interval of 100 to 800 is enough to allow you to use it without null check errors, check this one how they did it here
How to define and use custom MaterialColor in flutter
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: According to the documentation of MaterialColor class:

Defines a single color as well a color swatch with ten shades of the color.
The color's shades are referred to by index. The greater the index, the darker the color. There are 10 valid indices: 50, 100, 200, ..., 900. The value of this color should the same the value of index 500 and shade500.

So, this error is not prompted only when the following two conditions are satisfied:

There should be ten items on the list.
The items should be indexed as 50,100,200, ..., 900.
Missing any of these two above points will cause the aforesaid error.
We can fill in some dummy colours in order to make a list of 10.

Thus, we can correct your colors.dart file as follows:
class JarsColors {
  static const MaterialColor palette = MaterialColor(
    0xFF276678,
    <int, Color> {
      0: Color(0xFFF6F5F5),
      100: Color(0xFFD3E0EA),
      200: Color(0x235C6C),
      300: Color(0xFF6894A1),
      400: Color(0xFF1687A7),
      500: Color(0xFF276678),
      600: Color(0xFFFFFFFF), //white (no relation with specified shade)
      700: Color(0xFF000000), //black (no relation with specified shade)
      800: Color(0xFFA1A1A1), //random (no relation with specified shade)
      900: Color(0xFF2A2A2A), //random (no relation with specified shade)
    }
  );
}

Comment: Could you clarify what you mean by, *"…is not prompted only when…"*?


Create dictionary with count of values from list

Question: I'm trying to figure out how to create a dictionary with the key as the school and values the wins-losses-draws, based on each item in the list. For example, calling my_dict['Clemson'] would return the string "1-1-1"
"
team_score_list =[['Georgia', 'draw'], ['Duke', 'loss'], ['Virginia Tech', 'win'], ['Virginia', 'loss'], ['Clemson', 'loss'], ['Clemson', 'win'], ['Clemson', 'draw']]

The output for the above list should be the following dictionary:
{'Georgia': 0-0-1, 'Duke': 0-1-0, 'Virginia Tech': 1-0-0, 'Virginia': 0-1-0, 'Clemson': 1-1-1}

For context, the original data comes from a CSV, where each line is in the form of Date,Opponent,Location,Points For,Points Against.
For example: 2016-12-31,Kentucky,Neutral,33,18.
I've managed to wrangle the data into the above list (albeit probably not in the most efficient manner), however just not exactly sure how to get this into the format above.
Any help would be greatly appreciated!
Comment: can you explain your output? how does `Georgia` map to `0-0-1` and `Duke` to `0-1-0`? what of `clemson`? What is the logic?
Comment: Thanks for the response, and sorry if I didn't make that clearer. The first value should be the number of wins, the second should be losses, and the 3rd the number of draws.

So for the above list, Georgia only occurs once, and the value is "draw". So the dictionary key should be the school name (Georgia), with the values 0-0-1, meaning 0 wins, 0 losses and 1 draw.

Duke on the other hand again appears only once, but the associated value is a loss, therefore it gets coded as 0-1-0 e.g. 0 wins, 1 loss, zero draws.

Clemson occurs 3 times, with 1 win, 1 draw and 1 loss, therefore 1-1-1
Comment: You have not explained how you get the value '0-0-1'. Why is it 0-0-1  instead of 1-0-0??
Comment: Sorry was editing while you replied ;)
Answer: Not beautiful but this should work.
team_score_list = [
    ["Georgia", "draw"],
    ["Duke", "loss"],
    ["Virginia Tech", "win"],
    ["Virginia", "loss"],
    ["Clemson", "loss"],
    ["Clemson", "win"],
    ["Clemson", "draw"],
]

def gen_dict_lst(team_score_list):
    """Generates dict of list based on team record"""
    team_score_dict = {}
    for team_record in team_score_list:
        if team_record[0] not in team_score_dict.keys():
            team_score_dict[team_record[0]] = [0, 0, 0]
        if team_record[1] == "win":
            team_score_dict[team_record[0]][0] += 1
        elif team_record[1] == "loss":
            team_score_dict[team_record[0]][1] += 1
        elif team_record[1] == "draw":
            team_score_dict[team_record[0]][2] += 1
    return team_score_dict

def convert_format(score_dict):
    """formats list to string for output validation"""
    output_dict = {}
    for key, value in score_dict.items():
        new_val = []
        for index, x in enumerate(value):
            if index == 2:
                new_val.append(str(x))
            else:
                new_val.append(str(x) + "-")
        new_str = "".join(new_val)
        output_dict[key] = new_str
    return output_dict

score_dict = gen_dict_lst(team_score_list)
out_dict = convert_format(score_dict)
print(out_dict)

Comment: you sir, are a champion. Thank you so much for this! Super helpful to be able to see how to do this. Greatly appreciated :)
Answer: You can first make a dictionary and insert/increment values of wins,loss and draw while iterating over the dictionary values. Here I have shown a way using variable name same as the string used for win,loss and draw and then increased corresponding value in dictionary using global()['str'] (from another answer)
dct={}
for i in team_score_list:
draw=2
win=0
loss=1
if i[0] in dct:
    dct[i[0]][globals()[i[1]]]+=1
else:
    dct[i[0]]=[0,0,0]
    dct[i[0]][globals()[i[1]]]=1

You can then convert your list to string by using '-'.join(...) to get it in a format you want in the dictionary.
Answer: I now get what you mean:
You could do
a = dict()
f = lambda x,s: str(int(m[x]=='1' or j==s))
for (i,j) in team_score_list:
    m = a.get(i,'0-0-0')
    a[i] = f"{f(0,'win')}-{f(2,'draw')}-{f(4,'loss')}"

{'Georgia': '0-1-0',
 'Duke': '0-0-1',
 'Virginia Tech': '1-0-0',
 'Virginia': '0-0-1',
 'Clemson': '1-1-1'}

Now this is an answer only for this example. If you had many data, it would be good to use a list then join at the end. Eg
b = dict()
g = lambda x,s: str(int(m[x]) + (j==s))
for (i,j) in team_score_list:
    m = b.get(i,[0,0,0])
    b[i] =[g(0,"win"),g(1,"draw"),g(2,"loss")]

{key:'-'.join(val) for key,val in b.items()}
{'Georgia': '0-1-0',
 'Duke': '0-0-1',
 'Virginia Tech': '1-0-0',
 'Virginia': '0-0-1',
 'Clemson': '1-1-1'}

Comment: Thank you also for the reply also :) this is super helpful!


Set table rows height to character height

Question: I want to use a good ol'
 as a striped "canvas" to draw an ascii chart ... Erm. like this:

How can I go from left to right ?
For the optic illusion to work, I need the table rows height to equals char heights so there is no visible vertical space between chars.
I have tried following css tweaking with no success (this code gives the left result) :

______┌

______│

____┌─┤

____│ ⋮

with css:
.row-mini {
    padding:0px; margin:0;
}
.div-mini {
   height: 10 px;
   overflow: hidden;
}

Comment: instead of height you can use line-height with no border spacing-- demo https://jsfiddle.net/b78nhw3y/
Comment: @Tasos Because it's bootstrap styled, I had to remove the (badly named?) table-condensed class to make it work. If you repost your comment as answer (+ my edit), I'll accept it. jsfiddle is updated.
Answer: you can use line-height with no border spacing and remove table-condensed class
Demo
http://jsfiddle.net/81wu4cp8/
Html

______┌

______│

____┌─┤

____│ ⋮

Css
.row-mini {
    padding:0px; margin:0;
}
.div-mini {
   line-height: 11px;
   overflow: hidden;
}
table {
  border-spacing: 0px;
}

Result


Convert list inside pandas dataframe to list variable

Question: I have a .csv file structured as well:
    chan_id   spacecraft                           anomaly_sequences
      P-1       SMAP                 [[2149, 2349], [4536, 4844], [3539, 3779]]

I need to convert the list of list inside the cell anomaly_sequences to a variable, so I can loop inside it. I did it so:
list_labels = df['anomaly_sequences'].values.tolist()

but it converted all the cell in a single list, in fact if I try to print it I see it as:
['[[2149, 2349], [4536, 4844], [3539, 3779]]']

How can I correct it?
Comment: what output do you expect?
Comment: Can you also provide the output of `print(df.dtypes)`?
Comment: @TomerS a list where its first element is [2149, 2349], its second element is [4536, 4844] etc..
Comment: @Cimbali chan_id              object
spacecraft           object
anomaly_sequences    object
dtype: object
Comment: Hmmm I asked the wrong question, that doesn't tell me if they're strings or lists… If the objects are lists, `df['anomaly_sequences'].explode()` should work, if they are strings look at this recent question: https://stackoverflow.com/questions/69397259 , then do `.explode()`
Comment: @Cimbali It prints: 0    [[2149, 2349], [4536, 4844], [3539, 3779]]
Name: anomaly_sequences, dtype: object
Comment: I missed why dont you use only `df['anomaly_sequences'].values`. It should already give you a nested list in an array.
Comment: @OnurOdabaşı It gives me the same output, a list with one element corresponding to the entire cell
Comment: Looks to me it's more about the type right? So you can do
`from ast import literal_eval` and `df["anomaly_sequences"] = df["anomaly_sequences"].apply(literal_eval)`. Edit: Just saw that @Cimbali already linked this answer.
Answer: Not sure how you want to present your output, but if you want to convert your string into list of integers list, just do:
import json
var = "[[2149, 2349], [4536, 4844], [3539, 3779]]"
var = json.loads(var)
var

[[2149, 2349], [4536, 4844], [3539, 3779]]

And if you want to flatten the list of list, just use:
flat_list = [item for sublist in var for item in sublist]
flat_list

[2149, 2349, 4536, 4844, 3539, 3779]


"autoreconf: not found" error during making qemu-1.4.0

Question: I was ./configure'd the qemu-1.4.0 and during make it cause:
(cd /home/amin/Simulate/qemu-1.4.0/pixman; autoreconf -v --install)
/bin/sh: 1: autoreconf: not found
make: *** [/home/amin/Simulate/qemu-1.4.0/pixman/configure] Error 127

Now, I can't find how to pass this error.
Thanks.
Comment: this exact question came up at a hackathon I went to a few months ago. It was useful not just online. idk, im feeling nostalgic.
Answer: I just had this problem myself, and the solution I found in reading the autoconf manual which states autoreconf runs autoconf which I did not have installed.
sudo apt-get install autoconf

and the autogen script I am using now works.
Comment: I've been surprised how many folks this has helped. I was at a hacker conference last week, where I met a kid with this exact question, and this same solution. unbelievable.
Answer: Try installing autoconf package.
sudo apt-get install autoconf

Comment: in 13.04 it seems to be `sudo apt-get install autoconf` (without the "re")
Comment: All you need it `autoreconf`, `dh-*` packages are only needed when using debhelper (for packaging `.deb`s)
Comment: `autoconf` in 14.04 also !
Comment: Can confirm this works in 16.04
Comment: @einSelbst Thanks a lot! Your comment is very useful for 13.04 :D
Comment: `autoconf` in Debian 9.x "stretch" also !
Comment: In Ubuntu 20.04, should install `dh-autoreconf` : `sudo apt install dh-autoreconf`
Answer: I used to search for package first:
# apt-cache search autoreconf
   autoconf2.13 - automatic configure script builder (obsolete version)
   dh-autoreconf - debhelper add-on to call autoreconf and clean up after the build

Then install what I need:
# apt-get install dh-autoreconf

Comment: This should be the answer.
Comment: Actually, you need both autoconf and then , in case you do not have both of em'.
Comment: soufrk, any details ? Here is guide: http://qemu-buch.de/de/index.php?title=QEMU-KVM-Buch/_QEMU%2BKVM_unter_Linux , nothing about necessity to install autoconf


How to define a prediction function in keras for NER system?

Question: I am creating a NER system following some tutorials using Keras. After the training and the first prediction, I'd like to use it to identify the NEs in a single string or in a list of strings of unseen data.
I can't seem to find the way to pass such string, or list of strings to the model.predict() and get an appropriate prediction.
This is the prediction for the test data in my code, so I was trying to adjust it to accept strings of unseen data and print the token + prediction:
i = np.random.randint(0, x_test.shape[0])
print("This is sentence:",i)
p = model.predict(np.array([x_test[i]]))
p = np.argmax(p, axis=-1)

print("{:15}{:5}\t {}\n".format("Word", "True", "Pred"))
print("-" *30)
for w, true, pred in zip(x_test[i], y_test[i], p[0]):
    print("{:15}{}\t{}".format(words[w-1], tags[true], tags[pred]))

This piece of code predicts and print each token with the NE Tag, but I don't really understand how it works
This code prints something like:
Word           True      Pred
------------------------------
The            O        O
British        B-gpe    B-gpe
pharmaceutical O        O
company        O        O
GlaxoSmithKlineB-org    O

I'd like to pass for example:
sentence = "President Obama became the first sitting American president to visit Hiroshima"

and being able to see the identified NEs. Any advise on how to do this?
A copy of the full code is here and the dataset is used is here.
Answer: You can make a prediction on a list of sentences like this:
my_sentences = ["President Obama became the first sitting American president to visit Hiroshima",
                "Jack is a good person and living in Iran"]

my_sentences_idx = [[word2idx[w] for w in s.split(" ")] for s in my_sentences]

my_sentences_padded = pad_sequences(maxlen=max_len, sequences=my_sentences_idx, padding="post", value=num_words-1)
preds = np.argmax(model.predict(np.array(my_sentences_padded)), axis=-1)

for idx, p in enumerate(preds):
    print("-" *30)
    print(my_sentences[idx])
    print("-" *30)
    for w, pred in zip(my_sentences[idx].split(" "), preds[idx]):
        if tags[pred]!="O":
            print("{:15} {} ".format(w, tags[pred]))
    print()

Output:
------------------------------
President Obama became the first sitting American president to visit Hiroshima
------------------------------
President       B-per
Obama           I-per
American        B-gpe
Hiroshima       B-geo

------------------------------
Jack is a good person and living in Iran
------------------------------
Jack            B-per
Iran            B-geo

Comment: When trying to run your code I get the following error:
KeyError: 'President'.
I will add it as an answer to the question as comments won't let me format it correctly.
Comment: @StivenLancheros: Don't add it as answer. Edit your question. It is because `President` word is not in your  `word2idx` dictionary. I ran your code, and it returned no error with the above sentences. I recommend once again run your code from first cell in order. You may somewhere amended the `word2idx` variable.


Use Laplace's method with $\int_{0}^{\infty} e^{x(3u-u^3)}du$ as $x\rightarrow \infty$

Question: Use Laplace's method with $\int_{0}^{\infty} e^{x(3u-u^3)}du$ as $x\rightarrow \infty$.
I'm confused about how to taylor expand about u=1? How do I continue? Obviously first of all I have converted it to:
$$\int_{1-\epsilon}^{1+\epsilon}e^{x(3u-u^3)}du$$
but what now?
Comment: What do you understand by "Laplace's method"? Laplace had made contributions in several areas of mathematics, it is not clear which one you have in mind.
Comment: http://en.wikipedia.org/wiki/Laplace%27s_method
Comment: You are asked for the limit $x \to \infty$, right? Also, you are integrating with respect to $u$, not $t$, right? Please correct these little mistakes in order to be able to help you better.
Comment: The limit is obviously $\infty.$ Probably an error in the statement.
Answer: Laplace's method has integrals of the form
$$\int_a^b du \, f(t) e^{x g(u)} $$
be analyzed from the point of view of critical points such that $g'(u) = 0$.  In this case, this means that $u=1$.  We then Taylor expand $g(u) = g(1) + \frac12 g''(1) (u-1)^2$.  With exponential error, we may express the leading behavior of the integral as $x \to \infty$ as
$$e^{2 x} \int_{-\infty}^{\infty} du \, e^{-3 x (u-1)^2} = e^{2 x} \sqrt{\frac{\pi}{3 x}}$$
Comment: @martycohen: $\operatorname{erf}(x) \to 1$ as $x \to \infty$.
Comment: This answer and Demoreno's answer differ by a factor of 2.
Comment: I also got this answer
Comment: @Ron: Thanks. I was thinking of erfc.
Answer: Let's see the where the usual reasoning for Laplace's method leads us.
Let me write the integral as $\exp{(x f(u))}$, where $f(u)$ has a global maximum at $u_* = 1$. We could anticipate that the major contribution to the integral is coming from the neighbourhood of $u = u_*$ as $x \to \infty$. If we expanded the argument of the exponential about $u = u_*$ we would find:
$$ I(x) = \int^\infty_0 \mathrm{e}^{xf(u)} \, \mathrm{d}u \approx \int^\infty_0 \mathrm{e}^{x \left[ f(u_*) + \frac{1}{2}f''(u_*)(u-u_*)^2 \right] } \, \mathrm{d}u, $$ where $f(u_*) = 2$ and $f''(u_*) = -6$ (of course, $f'(u_*)=0$). Now, we call Mathematica to solve the last integral to come up with:
$$I(x) \sim \sqrt{\frac{\pi }{12 x}} \mathrm{e}^{2 x} \left(1+\text{erf}\left( \sqrt{3x}\right)\right), \quad x \to \infty $$ where $\mathrm{erf}$ is the error function. We have obtained two terms in the asymptotic expansion of $I(x)$.
Hope this helps

Note that if you do not retain the second order in the expansion of $f$ you end up with a non-convergent integral for $u$ leading to the value of $I$ at $x \to \infty$, which is not precisely what we desire.

Here's a comparison between the numerical integration of $I(x)$ (black solid line) and the two-term asymptotic expansion (dashed line):
Comment: Is the maximum not at $u=1$ and also, I just need to work out the first term in the approximation.
Comment: You are right. I'm trying to figure out the leading order with Mathematica. I'll let you know what's going on with the integral!


Async call in background task doesn't work

Question: In my app I need to scan for Wi-Fi access point in the background. I am able to start the task and initialise Wi-Fi adapter, but next async call "await scanner.ScanForNetworks()" to perform scan seem to never complete the task. Could it be the result of numerous nested async calls? If so, what could be possible workaround?
ScanningTask.cs
namespace BackgroundTaskLibrary
{
    public sealed class ScanningTask : IBackgroundTask
    {
        private BackgroundTaskDeferral deferral;
        private WiFiScanner scanner = new WiFiScanner();
        private Windows.Storage.ApplicationDataContainer localSettings;
        private DispatcherTimer timer;

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;
            await scanner.InitializeFirstAdapter();
            ShowToastNotification("Hi", "Hello from background"); //notification is shown

            await scanner.ScanForNetworks();
            ShowToastNotification("Hi", "Hello from background1"); //this one never gets shown
            deferral.Complete();
        }

        private void TaskInstance_Canceled(IBackgroundTaskInstance sender,
            BackgroundTaskCancellationReason reason)
        {
            deferral.Complete();
        }

        private void ShowToastNotification(string title, string stringContent)
        {
            ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier();
            Windows.Data.Xml.Dom.XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            Windows.Data.Xml.Dom.XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");
            toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(title));
            toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(stringContent));
            Windows.Data.Xml.Dom.IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
            Windows.Data.Xml.Dom.XmlElement audio = toastXml.CreateElement("audio");
            audio.SetAttribute("src", "ms-winsoundevent:Notification.SMS");

            ToastNotification toast = new ToastNotification(toastXml);
            toast.ExpirationTime = DateTime.Now.AddSeconds(10);
            ToastNotifier.Show(toast);
        }
    }
}

WiFiAdapter.cs
namespace BackgroundTaskLibrary
{
    class WiFiScanner
    {
        //WiFi adapter instance
        public WiFiAdapter WiFiAdapter { get; private set; }
        public Geolocator _geolocator = new Geolocator();
        public Geoposition Location { get; set; }

        ///
        /// Find the fisrts available WiFi adapter and initialise it
        ///
        /// <returns></returns>
        public async Task InitializeFirstAdapter()
        {
            var access = await WiFiAdapter.RequestAccessAsync();
            if (access != WiFiAccessStatus.Allowed)
            {
                throw new Exception("WiFiAccessStatus not allowed");
            }
            else
            {
                var wifiAdapterResults =
                await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
                if (wifiAdapterResults.Count >= 1)
                {
                    this.WiFiAdapter =
                    await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id);
                }
                else
                {
                    var dialog = new MessageDialog("WiFi Adapter not found.");
                    await dialog.ShowAsync();

                    throw new Exception("WiFi Adapter not found.");
                }
            }
        }

        public async Task ScanForNetworks()
        {
            if (WiFiAdapter != null)
            {
                await WiFiAdapter.ScanAsync();
            }
            else
            {
                throw new Exception("No Wi-Fi adapter");
            }

            Location = await _geolocator.GetGeopositionAsync();

            List<AccessPoint> accessPoints = new List<AccessPoint>();
            foreach(var network in WiFiAdapter.NetworkReport.AvailableNetworks)
            {
                AccessPoint ap = new AccessPoint()
                {
                    SSID = network.Ssid,
                    Mac = network.Bssid,
                    SignalStrength = network.NetworkRssiInDecibelMilliwatts,
                    Open = (int)network.SecuritySettings.NetworkAuthenticationType
                };

                accessPoints.Add(ap);
            }
            await SaveData(accessPoints);

        }

        public async Task SaveData(List<AccessPoint> accessPoints)
        {
            string info = DateTime.Now + "|" + Location.Coordinate.Point.Position.Latitude
                    + "|" + Location.Coordinate.Point.Position.Longitude + "|";
            for (int i = 0; i < accessPoints.Count; i++)
            {
                info += accessPoints[i].ToString();
            }

            info += Environment.NewLine;

            // Get the logical root folder for all external storage devices.
            StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;

            // Get the first child folder, which represents the SD card.
            StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();

            StorageFile infoFile;

            if (sdCard != null)
            {
                //check if info file exists
                try
                {
                    infoFile = await sdCard.GetFileAsync("wifiScanInfo.txt");
                }
                catch
                {
                    infoFile = await sdCard.CreateFileAsync("wifiScanInfo.txt");
                }

                await FileIO.AppendTextAsync(infoFile, info);
            }
        }
    }
}

In case you need the whole project: https://www.dropbox.com/sh/1v9mbr3xhgr3283/AACDbB7skZUI7Z5fiu0HT8r4a?dl=0
EDIT:
By subsequently simplifying ScanningTask I was able to determine, the problem is in the call "await WiFiAdapter.ScanAsync();"
I finally managed to catch an exception from "await WiFiAdapter.ScanAsync();", here is the stack trace:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

   at BackgroundTaskLibrary.WiFiScanner.<ScanForNetworks>d__10.MoveNext()

However the scan was completed and the results were save in the text file as expected. What permissions might I be missing? I have declared Internet, Location and Removable Storage permissions.
Comment: which call excatly doesn't complete? Do you get any errors?
Comment: await scanner.ScanForNetworks(); and I do not get any errors
Comment: Any chance its your save thats not working? if you drop the save down to a simple just write "complete" to a file in temp, does it work? Where is it trying to write wifiscaninfo.txt to?
Comment: @BugFinder wifiscaninfo.txt is saved to SD card which is present on my testing device. Moreover, when the whole code was not in a background task, but in a Click Command for the button, it worked totally fine.
Using your suggestion I was managed to determine that it is "await WiFiAdapter.ScanAsync();" that prevents the task from completion
Comment: It wouldn't hurt to put a try/catch in that `async void`, it might even help you find the problem.
Comment: @HenkHolterman I've just tried to catch any error, but no exceptions are thrown
Comment: @Liam I was finally able to catch Access Denied exception during the scan, however the scan was performed correctly and I got the results saved in a text file. Any ideas, what permissions I might be missing? I have selected Intrenet, Location and Removable Storage capabilities in VS.
Comment: AccessDenied could also refer to the GeoLocator, I see no RequestAccessAsync call for it.
Comment: `sdCard = (...).FirstOrDefault();` seems a little haphazard. Do you have any control on which folders are on the card, in which order, do you have access to all? Do yourself a favour and create a SdCard/WiFi folder.
Comment: You don't mention `` here. Check that out.
Comment: I checked, it is present in the manifest
Answer: It think the exception comes from the use of GeoLocator without requestAccessAsync call :

Starting in Windows 10, call the RequestAccessAsync before accessing the user's location. At that time, your app must be in the foreground and RequestAccessAsync must be called from the UI thread. Until the user grants your app permission to their location, your app can't access location data.

Source : https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.aspx?f=255&MSPPError=-2147217396
Comment: Do you have unhandled-exception handlers in place? Because "the app is working like it should" is indeed strange.
Comment: I moved access requests for wifi and location to the button click command but nothing changed. And I am 100% sure exception is thrown at `await WiFiAdapter.ScanAsync();`, because that is where I put try/catch block. What surprises me is that the app is working like it should despite the exception being thrown
Comment: @HenkHolterman I surrounded 'await WiFiAdapter.ScanAsync()' with try/catch and save the stack trace to the txt file. Eventually, I end up having both the stack trace and the scan information in the text file.
Comment: I was thinking Scheduler.Unhandled, and maybe AppDomain / TaskScheduler too. Your results seem to come from  2 parallel calls.
Comment: Do you mean I have to implement custom app level exception handlers?


How to load external static HTML page with script tags in react?

Question: I want to load a static html file which has script tags in it as a react component. I tried html-loader approach but this is converting the html file to a string but that string is not correctly rendered in the react DOM.
Below is my Sample html file.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.css" type="text/css" />

Test

In webconfig.js I had added the below code
    {
    test: /\.html$/,
    exclude: /node_modules/,
    use: {loader: 'html-loader'}
    },

This is how i am rendering in react
import Page from "./Sample.html";
var htmlDoc = { __html: Page };

The problem is it is not showing the graph. But i can see the
 Tag populated on top of the page but not the graph.
How can resolve this issue?
Any help is appreciated
Thanks
Comment: 30000 chars - next time try a [mcve] ;)
Comment: @mplungjan updated the sample html to less chars.
Answer: you can use dangerouslySetInnerHTM prop. this question is already answered on stackoverflow. check it out React: how to load and render external html file?
this will solve your promblem
Comment: If you see my question i am already using `dangerouslySetInnerHTML` and gone through the link that you specified. The problem is it is not reading the content in `


How to Determine the Size of a TimescaleDB Table?

Question: To determine the size of my TimescaleDB table my_table (which has a hypertable created previously), I ran the SQL query
pg_size_pretty( pg_total_relation_size('my_table') );

However, despite having 10k rows in this table, the size returned from this query is 24 kB.
Querying for the size of the database gave a more reasonable size of 34 MB, using the SQL query
SELECT pg_size_pretty( pg_database_size('database_development') );

Question: What is the correct way for calculating the size of a TimescaleDB table?
Using PostgreSQL 11.5, TimescaleDB 1.5.1
Answer: We typically recommend using TimescaleDB-specific functions:
https://docs.timescale.com/latest/api#hypertable_relation_size
https://docs.timescale.com/latest/api#hypertable_relation_size_pretty
If you are interested in getting information about each/specific chunk:
https://docs.timescale.com/latest/api#chunk_relation_size
https://docs.timescale.com/latest/api#chunk_relation_size_pretty
Comment: with 2.0 its:  SELECT hypertable_size()
Comment: links are out of date
Comment: To have a value in human readable form: `SELECT pg_size_pretty( hypertable_size('.'))`;


$x^2-px+p^2-4<0$ for at least one $x<0$

Question: Find the set of all values of $p$, for which $x^2-px+p^2-4<0$ for at least one $x<0$.
My work:
Let $x=k<0$ be a root of this inequality. So our inequality becomes $$k^2-pk+p^2-4<0$$
Here $k^2$ is $>0$, $-pk$ is $>0$ So for the inequality to hold $p^2-4$ has to be $<0$.
After solving I got the range as, $p\in(-2,2)$. Now consider a quadratic equation $$f(y)=y^2-py+p^2-4=0$$ where $f(x)<0$ So here the $\triangle\ge0$ So $$p^2-4p^2+16\ge0$$ or $$p\in\left(-\infty,\frac{-4}{\sqrt{3}}\right]\cup\left[\frac{4}{\sqrt{3}},\infty\right)$$ Doing the intersection we get $$p\in\phi$$ But the answer is given as $p\in\left(\frac{-4}{\sqrt{3}},2\right)$ And I'm not sure about the correctness of the answer
But if it is correct, Where did I go wrong$?$
Comment: @barrycarter I think I messed up everything
Comment: Why is `-pk` positive? If `p` is negative, `-pk` is also negative. Minor request: it took me some time to figure out `+ve` meant `positive`. Just use `>0` please.
Comment: Doing the intersection? It's a union. $\cup.$
Comment: @DanielWainfleet intersection of both intervals
Comment: For a start, $x^2-px+p^2-4=(x-p/2)^2+3p^2/4-4\ge 0$ if |$p|\ge 4/\sqrt 3.$
Answer:
Your function is positive for very large $x$, so you never have the case where the quadratic is always negative. That means you require to have two real roots. If you have only one root, the value of the quadratic is never negative (always positive, except at the root, where it is $0$).
$\Delta=p^2-4p^2+16\gt 0$means $p\in\left(-\frac4{\sqrt 3},\frac4{\sqrt 3}\right)$ (you got the wrong interval)
If you want the quadratic to be negative for at least one $x<0$, it means you have the position of the vertex of the parabola at a value $\le 0$, or the value of the quadratic evaluated at $0$ is negative. The position of the vertex is at $p/2$. So one possibility is $p\le 0$. The other is $0^2-0p+p^2-4<0$, which means $p\in(-2,2)$. Since $2<4/\sqrt 3$, it means that $$p\in \left(-\frac4{\sqrt 3},2\right)$$
Answer:
Find the set of all values of $p$, for which $x^2-px+p^2-4<0$ for at least one $x<0$.

In other words, we want the solution set of $$\text{for some negative } x, \:\:x^2-px+p^2-4 \text{ is negative}.\tag1$$
Since $x^2-px+p^2-4$ is an upwards-facing the parabola, we require

two $x$-intercepts, and
either a symmetry-axis with a nonpositive $x$-value or a negative $y$-intercept,

that is,

$(-p)^2-4(1)(p^2-4)>0,\;$ and
$-\frac{-p}{2(1)}\le0\quad$ or $\quad p^2-4<0,$

which is equivalent to

$-\frac4{\sqrt3}<p<\frac4{\sqrt3},\;$ and
$p\le0\quad$ or $\quad -2<p<2,$

which is equivalent to

$-\frac4{\sqrt3}<p<\frac4{\sqrt3},\;$ and
$p<2,$

which is equivalent to $$p\in\left(-\frac4{\sqrt3},2\right).$$

$x^2-px+p^2-4<0$ for at least one $x<0$


I keep getting the error "Node is not generic; it cannot be parametized with arguments E" and "front cannot be resolved"

Question: I'm making a linked implementation of a queue in Java. The problem is, it only displays the errors when I place it in a package (I'm using the default package) along with the other .java files needed (Queue, QueueDriver, etc.). It works fine outside the package. I'm using Eclipse.
    public class LinkedQueue<E> implements Queue<E>{

/**
 * Initialize the pointers
 */
private Node<E> front;
private Node<E> rear;

/**
 * Initialize size of list
 */
private int size;

/**
 * Initialize the linked queue
 */
public LinkedQueue() {
    front = null;
    rear = null;
    size = 0;
}

/* (non-Javadoc)
 * @see Queue#isEmpty()
 */
@Override
public boolean isEmpty() {
    return (front == null);
}

/* (non-Javadoc)
 * @see Queue#dequeue()
 */
@Override
public E dequeue() throws QueueEmptyException {
    if (isEmpty())
        throw new QueueEmptyException("Queue is empty!");
    else{
        E temp = (E) front.getElement();
        front = front.getNext();
        size--;
        return temp;
    }
}

/* (non-Javadoc)
 * @see Queue#enqueue()
 */
@Override
public void enqueue(E element) {
    Node<E> x = new Node<E>(element);
    if(front == null){
        front = rear = x;
    }
    else{
        rear.setNext(x);
        rear = x;
    }
    size++;
}

/* (non-Javadoc)
 * @see Queue#size()
 */
@Override
public int size() {
    return size;
}

/* (non-Javadoc)
 * @see Queue#front()
 */
@Override
public E front() throws QueueEmptyException {
    if (isEmpty())
        throw new QueueEmptyException("Queue is empty!");

    return (E) front.getElement();
}

}
Comment: Check your imports. Verify that you're not importing some other JDK class or interface like org.w3c.dom.Node.
Comment: Maybe you should post the code for `Node` as well.
Comment: @RaviThapliyal I only have three imports now. Queue.java, QueueEmptyException.java and QueueFullException.java
Comment: Move your classes to some package and either add `import your.package.Node;` yourself or use Ctrl+Shift+O to Organize Imports (in Eclipse) and selecting your class.
Comment: I already tried that and it didn't work. What's weird is I also declared rear to be Node but it doesn't show any error.
Answer: The message is telling you that Node is not generic. It needs to be like
public class Node<E> {
    // your code here, using E as the data in the node
}


Python markdown footnote backlink text change

Question: I am facing a very simple problem on changing the backref text in python footnote. I read the doc of footnote at here . The site clearly says BACKLINK_TEXT could be overwritten to allow other character.
So I tried following code:
import markdown.extensions.footnotes
import markdown
markdown.markdown(some_text,extensions=['footnotes'], BACKLINK_TEXT ="Δ")

The above code doesn't produce the Backref text specified as ← but gave the default value as ↩ .
Is above code the correct way of initializing the config for footnote?
Answer: After reading documentation about extensions I think you need
extensions=['footnotes(BACKLINK_TEXT=&#916)']

because BACKLINK_TEXT is option for footnotes extension.
See: Markdown#extensions
Comment: This works too, but I figured there is error in python-markdown also. If you check class FootnoteExtension in footnotes.py , you can see they have error which I have answered above myself.
Comment: @Sarvagya Pant I put `print configs` in that file and I get `[(u'BACKLINK_TEXT', u'Δ')]` when I use `extensions=['footnotes(BACKLINK_TEXT=Δ)']` but I get empty list `[]` when I use `extensions=['footnotes'], BACKLINK_TEXT ="Δ"` - so there is no mistake in code - only you expect too much using `extensions=['footnotes'], BACKLINK_TEXT ="Δ"` :)
Comment: furas, your code worked too, but I was expecting to remove footnote by using BACKLINK_TEXT as "". The code you provided did so, but there was also a link that could point to the footnote area in text. Also if you look at FootnoteExtension class inside footnotes.py in markdown, you can see error in for key,val in configs. The line should have configs.iteritems(). They had missed it.
Comment: They didn't miss `iteritems()` because `configs` is not dictionary (which needs  `iteritems()`) but list of tuples like this `[(u'BACKLINK_TEXT', u'Δ')]` (which don't have `iteritems()`)
Answer: I figured out the problem, there is error in footnotes.py code of python-markdown. They have used
for key,val in configs:

instead of:
for key,val in configs.iteritems().

This was the problem. Hope they fix this in another version.


Error in model.frame.default(object, data, xlev = xlev) : variable lengths differ (found for 'k')

Question: Don't know what should I put inside model.matrix. I want to put the name inside the name list a to model.matrix
<code>a <- row.names(bbb)
a <- noquote(a)
a

for(k in a){
  y <- election_data_train$Obama_margin_percent
  x <- model.matrix( Obama_margin_percent ~ .-k-Obama_wins-Obama_margin-FIPS-ElectionDate-TotalVote-Clinton-Obama, data = election_data_train )
  d <- election_data_train[["k"]]

  gg_k <- glm(y~d+x)
  print(summary(gg_k)$coef['d',])
}
</code>
Answer: Solved. Just add [-1] at the end of the second line of code below:
model.matrix( Obama_margin_percent ~ .-k-Obama_wins-Obama_margin-FIPS-ElectionDate-TotalVote-Clinton-Obama, data = election_data_train )


Tensorflow use pretrained model in offline

Question: I'm using mobilenet from Tensorflow with below code.
When I run this code from my local pc, it downloads the weight file.
However, I can not download this online when is uploaded to server.

Is there any way I can use MobileNetV2 with tensorflow 2.0.
Or, I have my own weight file trained with MobielNetV2, then is it possible to use below without weights option
mobilenet = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224, 224, 3),
                                                               include_top=False,
                                                               weights='imagenet')
And I want to use supervisord from linux server.
It seems I need to use absolute path not relative path.
Could anyone help me to use MobileNetV2 with supervisord in offline environment
Answer: You could first use:
mobilenet = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')

Then save the weights somewhere:
mobilenet.save_weights('somefolder/mobilenetweights.h5')

Then when you're offline, you could first call:
mobilenet = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights=None)

Notice the None in weights argument. After that, you could load the weights from your file, where you saved previously:
mobilenet.load_weights('somefolder/mobilenetweights.h5')

This should work.
When you call the mobilenet model, if you ask it to give you imagenet weights by using weights='imagenet', it requires internet connection to download those weights. So it won't work offline. The method explained here should get it working.
Comment: Thanks, 1 more question.
If I have my own weight called abc.h5
Then can I use like this from first time? (i mean it is no need to download Tensorflow imagenet weight?)

mobilenet = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights=None)
mobilenet.load_weights('somefolder/mobilenetweights.h5')
Comment: Yes, if you have saved the weights using the same model, you can use it to load the weights back from your abc.h5 file.


I am not authenticated on minecraft.net!

Question: Basically, I changed my display name in launcher_profiles.json and then
when I tried to play on a server it says not authenticated to minecraft.net can somebody help me!
Comment: How about changing it back
Comment: [Related](https://gaming.stackexchange.com/questions/250128/i-changed-my-minecraft-username-and-nothing-works)
Answer: Fix: Change your name back!
You should not be changing your name in the launcher_profiles.json. Ever.
If you want to change your name  do this:

Go to Minecraft's official website
Log in with your original name (The one you had before you changed it)
Next to your name click on change
Put in your new name, and then your password underneath
Press change!

This will change your name to the new name that you want to use :D
Edit:
If you have followed the steps above and your name does not change, log in and out of the Minecraft Launcher. It may take some time to process the change


A triangular grid of side $n$ is formed from $n^2$ equilateral triangles with sides of length $1$. Determine the number of parallellograms.

Question: So here is Question :-
A triangular grid of side $n$ is formed from $n^2$ equilateral triangles with
sides of length $1$.Determine the number of parallellograms.
First of all , by reading the question I can understand that the answer should be evaluated by some kind of counting or combinatorial shortcut . But I really don't know what formula I can use to find the no. of parallelograms of a triangular grid of side $n$. Can anyone help with some explanation
?
Comment: I think the parallelograms come in three different orientations, so the answer is three times the number of parallelograms in your favourite orientation (say with the point corners pointing up and down).
Answer: Separate the parallelograms into the 3 directions that they point in. Focus on a single direction.
Hint: Extend the setup by 1 more row.
For a given parallelogram, extend the 4 edges till they hit the extended row. This determines 4 unique points.
This is illustrated by the red parallelogram, whose edges are extended.

Conversely, given these 4 points, we can reconstruct the parallelogram by following the edges.
E.g. For the 4 yellow dots, which parallelogram do they determine?
Hence, there are $ 3 \times { n + 2 \choose 4 } $ parallelograms.
Comment: Sorry to say this but this is an artificial solution. Why did you extend it, I mean, how you think about it?
Comment: @Aqua This is a "well-known elegant one-liner approach". Extending the sides of the parallelogram isn't that artificial, and after that we're forcing out the ${n+ 2 \choose 4 }$ and also the uniqueness of the bijection. I agree it's not the first approach one would take to the counting, since the brute force approaches work really well here.
Comment: And what make you thinking about extending it?
Comment: Honestly speaking, because I saw it done that way before. Though, if you look at it, the "parallelograms where one vertex doesn't touch the base" gives 4 distant points, so that's ${ n + 1 \choose 4}$, and the "parallelograms where one vertex touches the base" gives 3 distinct points (with the middle repeated) so that's ${n+1 \choose 3}$, and the sum gives us ${ n + 2 \choose 4}$. The extension of the base then just "tidies" up the accounting.
Answer: So we have $1+2+...+n+(n+1)= {n+2\choose 2}$ vertices determined by this grid.
Any pair, which is not on the same line determined by this grid, determine opposite vertices of some paralellogram and any parallelogram is determined by exactly one such pair.
The number of bad pairs is $$3\cdot \Big({1\choose 2} + {2\choose 2}+...+{n+1\choose 2}\Big) = {n(n+1)(n+2)\over 2}$$
So the number of good pairs is = the number of paralleograms $$ {{n+2\choose 2}\choose 2} - {n(n+1)(n+2)\over 2} =\boxed{{(n-1)n(n+1)(n+2)\over 8}} $$
Comment: Nice , clear and simple answer . Thanks
Answer:
The parallelograms can be built in three orientations choosing (see picture) segments lying on blue-red, red-black or black-blue pairs of lines. From symmetry it is enough to count the number of parallelograms for one coloring (say blue-red).
Start the counting with the upmost red line of length 1. There is only one way to choose a pair ob blue lines and $n-1$ ways to choose the other red line. All together we have $(n-1)$ ways to construct a parallelogram. Taking the next red line (with the length 2) we have $\binom 32$ ways to choose the blue lines and $n-2$ ways to choose the other (lower-lying) red line.
Continuing in this way we find that the overall number of blue-red parallelograms is:
$$
\sum_{k=1}^{n-1} \binom{k+1}2(n-k)=\frac{(n-1)n(n+1)(n+2)}{24}.
$$
The total number of the parallelograms is triple of this:
$$\frac{(n-1)n(n+1)(n+2)}{8}.
$$


How to seal joints in ductwork when tape is not an option

Question: The duct-work in the basement for my forced air heating system has been modified at various points over its long history and as a result had quite a few leaks when I moved in recently. I used foil tape to fix most of them, but I'm having trouble with the biggest leak:

The red arrow is the main branch from the furnace, showing the direction of airflow.
Blue shows the branch leading to the register. This register is the second one on this branch, and the most "direct" (the other leads through a section of smaller duct-work). The register is located directly above the floor joists shown.
Green shows where the leak is -- the duct (blue) butts against this joist, and where it meets the main branch (red) there is a gap about 1/4" (0.5 cm) wide, for the width of the duct. Between the joist (green) and the main branch (red) there is just enough space to get my fingers. This is the space that needs to be filled or sealed to stop the leak.

Since I have failed to get tape in to seal this joint, how else can I seal it? I'm thinking of getting a piece of foam insulation or perhaps tube wrap to shove in the gap, but would this be wise?
Some additional details:

Moving the main branch to get better access is probably more trouble than it's worth.
Location is an unfinished basement.
The space is already warm enough given the small size and the fact that the furnace and lots of duct work is radiating enough heat to keep it warm.
Comment: Can you try mastic? Get a long paint brush, and shove/gob it in there.
Answer: I've used duct sealer in the past to seal up my attic air handler, it applies like a paste and dries hard. You can try that, but you options of globbing it on may be limited.
Is this duct in a basement or crawlspace?
The handler and ducts in my unfinished basement leak a bit, but I don't bother sealing them up as it helps keep the temp in the basement that much more liveable.
Comment: The system is poorly designed -- there's only one poorly placed cold air return on the whole second floor. I'm trying to get the pressure up to the second floor boosted, then I'll use vents off of other branches to supply the basement with heat. I'll give the duct sealer a shot.
Answer: A 1/4 " gap is way to wide to fix with even metal tape. I would cut a hole large enough in the side of the trunk line so I could add a piece of sheet metal on the inside held in with some Silicone and a couple of screws. Then patch the access hole. I have had to do similar where folks have shut to many registers off and the main trunk split due to the large area and increased pressure.
Answer: A good duct-sealer with fibers can be applied thickly with an old paintbrush. It also strengthens tape that covers gaps. If needed, a metal patch can be screwed on from the outside, then duct-sealed. If you want you can add duct-seal to the back of the patch, but the thick product forms a membrane on top of almost anything. Give it 6 hours to dry before pressurizing the ductwork.
Comment: I wasn't familiar with duct sealer -- I'll give that a shot.


Objective C: How to check if application is currently active (i.e. user is using it)?

Question: I am implementing an APNS push for my app with the following behaviours
1) If app is not active i.e. in background or not launched yet:
User will receive a pop up message and on click will bring him/her to the 3rd tab in the app (see code below)
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

    self.tabController.selectedIndex = 3;

}

2) If app is launch and currently active
No popup alert will be shown and the number of new notifications will show as a number on the 3rd tab

My question is how can I determine if the user's app is active?
How and where can I implement the check so that I can set the 2 different behaviours?
Answer: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (application.applicationState == UIApplicationStateActive) {
        // update the tab bar item
    }
    else {
        self.tabController.selectedIndex = 3;
    }
}

Answer: My answer for new modern visitors...
Swift variable : Simply put this any where outside classes to check for app active state .
var isApplicationActive:Bool {
    get {return UIApplication.sharedApplication().applicationState == .Active}
}

so your code in swift will be
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if isApplicationActive {
        //Change badge number ...
    } else {

    }
}


Problem with statically linking hunspell library in visual studio 2010

Question: I can't statically link hunspell library to my C++ project in Visual Studio 2010.
I downloaded hunspell and went to hunspell-1.3.1\src\win_api folder. I opened libhunspell.vcproj file in visual studio 2010 and converted project. I built solution in Realease configuration and it generated "libhunspel.lib" file in hunspell-1.3.1\src\win_api\Release\libhunspell folder.
In my simple C++ console program that use hunpell:

I added this folder with libhunspel.lib file in Property Pages/Configuration Properties/VC++ Directories/Library Directories
I added "hunspell-1.3.1\src\" folder to Property Pages/Configuration Properties/VC++ Directories/Include Directories
and "libhunspell.lib" to Property Pages/Linker/Input/Additional Dependancies.

But it still gives me unresolved external symbol error:
Error   2   error LNK2019: unresolved external symbol "__declspec(dllimport) public: int __thiscall Hunspell::spell(char const *,int *,char * *)" (__imp_?spell@Hunspell@@QAEHPBDPAHPAPAD@Z) referenced in function _main   C:\Users\Me\Documents\Visual Studio 2010\Projects\hunspell_learning\hunspell_learning\main.obj  hunspell_learning
Error   3   error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall Hunspell::Hunspell(char const *,char const *,char const *)" (__imp_??0Hunspell@@QAE@PBD00@Z) referenced in function _main   C:\Users\Me\Documents\Visual Studio 2010\Projects\hunspell_learning\hunspell_learning\main.obj  hunspell_learning
Error   1   error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall Hunspell::~Hunspell(void)" (__imp_??1Hunspell@@QAE@XZ) referenced in function _main C:\Users\Me\Documents\Visual Studio 2010\Projects\hunspell_learning\hunspell_learning\main.obj  hunspell_learning
Error   4   error LNK1120: 3 unresolved externals   C:\Users\Me\Documents\Visual Studio 2010\Projects\hunspell_learning\Debug\hunspell_learning.exe 1   1   hunspell_learning

I don't have idea what can be wrong. I also tries with dynamic library. Built Hunspell solution in Release_dll configuration and just changed Include Directories in my app to hunspell-1.3.1\src\win_api\Release_dll\libhunspell and it compiles. I only need to copy libhunspell.dll where my executable program is so dll will be loaded.
Answer: You need to put "#define HUNSPELL_STATIC"  somewhere in your stdafx.h.


Npe while moving a figure on the game field (java)

Question: I'm a beginner in Java and I'm trying to make my own very simple game "BomberMan".
Here are classes I've created:
public class GameField {

    private Figure[][] gameField;

    public Figure[][] getGameField() {
        return gameField;
    }

    public void createField(int size) {
        this.gameField = new Figure[size][size];
        setBomberMan();
    }

    private void setBomberMan() {
        int cellX = new Random().nextInt(gameField.length);
        int cellY = new Random().nextInt(gameField.length);
        Bomberman hero = new Bomberman(cellX, cellY, "Bomberman");
        this.gameField[cellX][cellY] = hero;
    }
}

The result of code above looks like:
[ ] [ ] [ ] [ ] [ ]
[B] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]

B is our Bomberman, and [ ] - empty cells of 2D array.
Abstract class for figures:
abstract class Figure {

    private int x;
    private int y;
    private String name;
    protected GameField gameField;

    protected Figure(int x, int y, String name) {
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public String getFigureName() {
        return name;
    }

    abstract void move(int x, int y);
}

The Bomberman I'm trying to make a step:
public class Bomberman extends Figure {

    protected Bomberman(int x, int y, String name) {
        super(x, y, name);
    }

    @Override
    void move(int x, int y) {
        StepMaker step = new StepMaker();
        Integer[] newPosition = step.getDestination(x, y, null);

        //The problem is in the line below:
        gameField.getGameField()[x][y] = null;

        int a = newPosition[0];
        int b = newPosition[1];
        gameField.getGameField()[a][b] = new Bomberman(a, b, "Bomberman");
    }
}

Class to get Integer[] coordinate to make a step:
public class StepMaker {

    private final EnumMap<Step, Integer[]> steps = new EnumMap<>(Step.class);

    private void fillEnumMap() {
        this.steps.put(Step.UP, new Integer[]{-1, 0});
        this.steps.put(Step.DOWN, new Integer[]{1, 0});
        this.steps.put(Step.LEFT, new Integer[]{0, -1});
        this.steps.put(Step.RIGHT, new Integer[]{0, 1});
    }

    public Integer[] getDestination(int x, int y, Step step) {
        fillEnumMap();
        int destX, destY;
        Integer[] way;
        if (step != null) {
            way = this.steps.get(step);
            destX = x + way[0];
            destY = y + way[1];
        } else {
            way = this.steps.get(choose());
            destX = x + way[0];
            destY = y + way[1];
        }
        return new Integer[]{destX, destY};
    }

    private Step choose() {
        return Step.values()[ThreadLocalRandom.current().nextInt(Step.values().length)];
    }

    private enum Step {
        /**
         * Possible ways to make step.
         */
        UP, DOWN, LEFT, RIGHT;
    }
}

And a class where I'm running my code:
public class Run {
    public static void main(String[] args) {
        GameField gameField = new GameField();
        gameField.createField(5);

        int p = 0;
        while (p != 1) {
            for (int i = 0; i < gameField.getGameField().length; i++) {
                for (int j = 0; j < gameField.getGameField()[i].length; j++) {
                    if (gameField.getGameField()[i][j] != null) {
                        gameField.getGameField()[i][j].move(i, j);
                    }
                }
            }
            gameField.printField(gameField.getGameField());
            p++;
        }
    }
}

The problem is that I'm having NPE here (Bomberman's move method):
gameField.getGameField()[x][y] = null;

On that coordinate we should have our Bomberman. I make this null and then create a new figure on a new coordinate. Each figure has x and y coordinate equals to our 2D array (gamefield) first and second coordinate. But in Run I say:
if (gameField.getGameField()[i][j] != null)

(That means we must have a figure there which can move).
So that cell should not be null and should not throw a NPE. What is wrong?
Comment: The `GameField` object you have in your `main` method is not the same object as the one in `Figure`, the second one is never initialized and is `null` .
Answer: It seems that gameField is not set for your BomberMan. You can extend the BomberMan's and Figure's constructors (add gameField as an arg) like that:
protected Bomberman(int x, int y, String name, Figure[][] gameField) {
    super(x, y, name, gameField);
}

And:
protected Figure(int x, int y, String name, Figure[][] gameField) {
    this.x = x;
    this.y = y;
    this.name = name;
    this.gameField = gameField;
}

And then create a new BomberMan with an additional arg:
Bomberman hero = new Bomberman(cellX, cellY, "Bomberman", gameFieldValue);


C++0x T operator+(const T&, T&&) pattern, still needs move?

Question: Some time ago I was told, that the usual pattern to implement two-ary operators needs a final move in the return.
Matrix operator+(const Matrix &a, Matrix &&b) {
    b += a;
    return std::move(b);
}

But now there is the special rule that in a return the compiler may treat the return value as a temporary, and then this would not be necessary -- a simple return b would suffice.
But then again, b has a name in this function, therefore, its an LValue -- which hinders the compiler to m consider it being a temp, and the move is required.
Is this still the case in the most recent version of the C++0x Standard? We need the move to implement the above pattern?
Comment: According to [this answer](http://stackoverflow.com/questions/6009004/are-value-parameters-implicitly-moved-when-returned-by-value/6009012#6009012), the `std::move` is not necessary.
Comment: Although it could make a difference that the parameter is a `Matrix&&` instead of a `Matrix`...
Comment: It *is* complicated, yes. And yes, I think you are right. If its a *value parameter* like `Matrix` then you have a pristine copy for you alone -- a temp. The compiler knows that you can grab from it. With `Matrix&&` I am not *that* sure-
Answer: You need the explicit std::move in this example because b is not the name of a non-volatile automatic object.  Reference 12.8 [class.copy] /p31/b1:

in a return statement in a function with a class return type, when
  the expression is the name of a non-volatile automatic object (other
  than a function or catch-clause parameter) with the same cv-
  unqualified type as the function return type, the copy/move operation
  can be omitted by constructing the automatic object directly into the
  function's return value
Comment: Ah, and references aren't objects. I think you should emphasize "object" instead of "automatic" (or both).
Comment: I think **automatic** is the right \em here, because it translates (roughly? exactly?) to "local variable".
Answer: I'm not sure why this function returns by value. Shouldn't this function return a Matrix&& like the following?
Matrix&& operator+(const Matrix &a, Matrix &&b) {
  b += a;
  return std::move(b);
}

This has the added advantage that x1 + x2 + x3 + ... + xn creates at most one temporary, which is important if Matrix happens to be stack allocated (as it then gains nothing from moves).
I think the signatures should be like the following:
Matrix&& operator+(Matrix &&a,      Matrix &&b     );
Matrix&& operator+(const Matrix &a, Matrix &&b     );
Matrix&& operator+(Matrix &&a,      const Matrix &b);
Matrix   operator+(const Matrix &a, const Matrix &b);

Comment: @towi: Also, what evidence have you got that the `(&&, &&)` overload is not needed? I believe http://ideone.com/qf3Rn shows that it is needed.
Comment: No. You should not return a `&&`. This would mean, that you return a reference to one of the arguments, where you do not have the control of where it is coming from ("dont pick up whats lying on the street"). If you return a `Matrix` you can just `move` in the content from one of the arguments and you accomplish the same effect with perfect performance. Also, you dont need to overload on `(&&, &&)`: The code you would write there would be the same as in either `(&,&&)` or `(&&,&&)`. If you spare the `(&&,&&)` overload, one of those will be selected by the compiler. You need only 3 overloads.
Comment: towi: What's wrong with returning a reference to one of the arguments? I thought only returning a reference to a temporary was an issue.
Comment: You are right, I think. It *is* correct, that a `&&` can bind to a `&` parameter, if there is no overload (there are of course many places which this is needed). But I missed, that, if you provide the overloads `(&,&&)` and `(&&,&)` for your/our example the compiler can not decide which one is better. I But it would be nice if there would be a "better" solution that adding an overload here, just to "deconfuse" the compiler. Feel free to edit here http://ideone.com/9ZhO3
Comment: No, you can also create issues returning a reference from an argument. Consider (modulo some `const`s) `Value& get(map &d, Value &dfault) { if(not-found) return dfault;}`. And then use it with `Value &v = get(..., Value{}); cout << v;` your program will crash, because `v` is a reference to the *temp* you created for `dfault`. And that will disappear at the `;`. When you `cout << v` it, it's gone.


data-target not working as expected

Question: I'm trying to implement the bootstrap modal, when I click on the add Icon.
But by default data-target="#undefined" is getting set.Only after clicking, data-target is getting changed to data-target="#myModal".
I want to set myModal to data-target by default and based on the condition I want to change data-target to myModal or alertModal.
Image Reference
I'm stuck here. Please help

public checkUnassigned() {
  let eArray = this.pListComponent.evtNumber;
  if (eArray.length > 0) {
    this.modalName = "alertModal";
  } else {
    this.modalName = "myModal";
  }
}

Comment: this is Angular 2
Comment: That is Typescript
Comment: Try [attr.data-target="{{'#' + modalName}}" or use two
Comment: not working getting error like Can't bind to '[attr.data-target' since it isn't a known property of 'i'. ("== '01')" class="npt-icon-add icon-states" aria-hidden="true"
                data-toggle="modal" [ERROR ->][attr.data-target="{{'#' + modalName}}"  (click)="checkUnassigned()">
Comment: I forgget a "]"
Answer: You can do it in the following way. Yet you have to check the pListComponent.evtNumber value constantly. I cannot do that part(by the lack of your total code) but suggest you to use 'ngDoCheck' (explanation) in a way that whenever pListComponent.evtNumber is changed, it has to trigger the checkUnassigned() function.
Goodluck!
isAlertModal:boolean = false;
public checkUnassigned() {
  let eArray = this.pListComponent.evtNumber;
  if (eArray.length > 0) {
    this.isAlertModal = true;
  } else {
    this.isAlertModal = false;
  }
}

Comment: i got an error like this [ts] '=' expected.
[ts] Cannot find name 'checkUnassigned'.
any
Comment: You can declare a variable in the class and store the result in it then make a check. I will edit the code now
Comment: got an error - Unexpected token # at column 1 in [#myModal]
Comment: Were you able to open the modal even before? Because I open it in this way-> (click)="myModal.openModal()" so you have to arrange the code accordingly. I have showed you the way how to give a default value and show the 'i' tag accordingly. The rest is kind of up to you.
Comment: You're code is working, but the problem is this line is not getting added [attr.data-target]="myModal"
Comment: try it without the #, I dont know
Comment: I fixed, i've removed the [attr.data-target] to just data-target="#modal" and it worked

data-target not working as expected


Database for mobile application in .NET

Question: I would write a mobile application in Visual Studio 2012,I would make it cross-platform using Portable Class Library,but I'm not really sure which technology I should use for the database behind the application. The users of my application should not edit the data in the database,my app would only display some data,and I don't want to refresh data very often..so I thought I could make updates,I don't want internet connection to be needed while using the application. For mobile phones LINQ to SQL would work?
Comment: sqlite is the way to go
Comment: thanks :) I've heard before that it works very well on anrdoid and ios,but I wasn't sure if it's the best solution for windows too
Answer: SQLite is a very good approach and you can use LINQ for querying and also can be used in different platforms. As you said, in your situation having a local database is a very good idea instead of using internet.

Database for mobile application in .NET


@media print css not formatting table on printing

Question: I have a simple table with a button below it. This is in the body section of my jsp as below:

                    One
                    Two
                    Three

                    1
                    2
                    3

                    4
                    5
                    6

        <button onclick="printDiv()">Print</button>

Below is the CSS with @media rule which is supposed to format the table. The CSS is in head section of my jsp:

    @media print,screen{
        table.t1 {
                margin: 1em auto;
                border-collapse: collapse;
                font-family: Arial, Helvetica, sans-serif;
                }

            .t1 th, .t1 td {
                padding: 4px 8px;
                }

            .t1 thead th {
                background: #4f81bd;
                text-transform: lowercase;
                text-align: left;
                font-size: 15px;
                color: #fff;
                }

            .t1 tr {
                border-right: 1px solid #95b3d7;
                }

            .t1 tbody tr {
                border-bottom: 1px solid #95b3d7;
                }

            .t1 tbody tr:nth-child(odd) {
                background: #dbe5f0;
            }

            .t1 tbody th, .t1 tbody tr:nth-child(even) td {
                border-right: 1px solid #95b3d7;
            }

            .t1 tfoot th {
                background: #4f81bd;
                text-align: left;
                font-weight: normal;
                font-size: 10px;
                color: #fff;
                }

            .t1 tr *:nth-child(3), .t1 tr *:nth-child(4) {
                text-align: right;
            }
        }
    </style>

Below is the javascript function to print the div containing my table. It is in the body section of my jsp:

The page comes nicely formatted on screen. However, when I click on the print button and print the page as an xps document, all the CSS formatting is lost and just the content of the table gets printed which looks really bad.
What am I doing wrong ? I am using IE8 and that I can not move to other browser or newer version of IE.
Answer: You can use different styles for screen and print media in your style sheet, i.e.
@media screen
{
    table.test {
        font-family:"Times New Roman",Georgia;
        font-size:10px;
        // more
    }
}

@media print
{
    table.test {
        font-family:Verdana, Arial;
        font-size:10px;
        // more
    }
}

When you'll print the table only styles defined in print media will be applied.
Click This for more


mySQL: Insert query value in Insert query

Question: I am trying to insert a new tag into my table. Tags have a column called type which is an int. I also have a table that maps type from a string to an int.
let sql = `INSERT INTO tag (name, type) VALUES (${tag.name}, SELECT id FROM tag_type WHERE type=${tag.type});`

This gives me a syntax error. What is the correct way to insert a value from another table?
Answer: There are a couple of issues with your query. Firstly, since tag.type and tag.name are strings, they must be enclosed in single quotes in the SELECT. Secondly, subqueries must be enclosed in parentheses (). This should work:
let sql = `INSERT INTO tag (name, type) VALUES ('${tag.name}', (SELECT id FROM tag_type WHERE type='${tag.type}'));`

It's cleaner to write this sort of query using an INSERT ... SELECT query, adding the value as a constant to the SELECT:
let sql = `INSERT INTO tag (name, type) SELECT '${tag.name}', id FROM tag_type WHERE type='${tag.type}';`

Comment: I don't quite understand the structure of the second example. When I run the query I think it is trying to use `tag.name` as a column. For example if `name = english` and `type = language` I get the error `Error: ER_BAD_FIELD_ERROR: Unknown column 'english' in 'field list'`. Is there a special way to add it as a constant?
Comment: @BoneJones sorry about that I accidentally omitted the quotes around `${tag.name}` in each of the queries. See my edit.
Comment: Is there a way I can conveniently throw an error if the type in `SELECT '${tag.name}', id FROM tag_type WHERE type='${tag.type}'` is not in the tag_type table?
Comment: @BoneJones in the first form, if you make the `type` column `NOT NULL` you will get an error if the `SELECT` fails as you would be trying to insert a `NULL` value into a `NOT NULL` column. For the second form, you can check the for the number of affected rows being 0 (in `node.js` you would use `result.affectedRows == 0`)


(Java Minecraft 1.14.2) How to use a target selector to determine if the executing position is in an entities hitbox?

Question: I am writing a datapack with an item which functions like a sniper rifle - you can shoot it and a particle beam created by a recursive raycasting function will shoot out and any entities it encounters should die. However, entity detection is a big problem, because I can shoot right through a creeper's head and it doesn't die. You can download the datapack here if you want to test it out. Use /function rituals:give/sniper_rifle to get the item.
I noticed that this is true for almost every mob in the game greater than an endermite or silverfish: if you shoot it through the feet, it dies, but anywhere above that or else than that, it doesn't. Pigs, cows, zombies, evokers, drowned, wither skeletons, anything, only die when shot through the feet. I don't intend for it to kill bosses so they are not a problem, luckily.
I've been detecting mobs by having every iteration of the recursive function run kill @e[distance=..0.1], and it moves ahead by 0.25 blocks each iteration. I have tried to get around this difference in @e detection, mob hitboxes, and visible mob sizes (which for some reason are all different) by using scoreboards to give every mob a value equal to their approximate height, and then changing the distance based on what type of mob it is: kill @e[scores={mobHeights=2},distance=..2], but that is at best buggy and at worst making it so you can shoot next to a mob and kill it.
As you can see in this image, the cursor is well over the pig, yet it insta-dies because of this imprecision.

If anyone knows a better way to detect mobs a raycasting function is moving through that would be great, because right now it is really frustrating to have to try to manually implement a fix which is really imprecise. Also, if anyone knows why the function only recognizes entities by their feet, that would also help a lot. I know that coordinates are also calculated at an entities feet, so maybe that has something to do with it.
Comment: Maybe summon an arrow? I haven't looked at your code, but maybe you could replace the entire logic with a `NoGravity` arrow with a high `damage` value.
Comment: Yeah actually I originally tried that, but in the linked datapack there is another item called a fire staff. If you give yourself one of those, you should also get an item called a fire hose. Using this item will show you the issue: the item projected does not have a consistent and smooth trajectory, like shot from a bow, but instead is jerky and lags out the game. I would prefer to try to solve this raycasting issue than resort to using a physical projectile, because then I can also make the ray go through "soft" blocks (like cacti) to add some realism, too. Thanks for the suggestion, though.
Comment: Maybe only summon an arrow when you're nearby a mob and then check if it's hit, otherwise kill it one tick later?
Answer: distance tests if the target coordinates are less than some distance away, not if the nearest part of the mob is under the given distance. I'd suggest using the 3d bounding box selection (x,dx,y,dy,z,dz,), because it selects hitboxes. It would kill any mobs in an area similar to the bounding box of an entity - meaning you are now tracking a point using a box, instead of the ideal tracking a box using a point.
Here's an example command:
kill @e[x=~,y=~-1.5,z=~,dx=0.1,dy=1.6,dz=0.1]

This would still not work, let's say, for an Ender Dragon. Also, you would kill everything on the way, including items.
Comment: But this (if I'm understanding correctly) still has a margin of error (1.5 blocks?) for where the entity could be vertically, so it would assume the ray went through the head, and would also not be super accurate, not more so than my current method, which works basically the same: adjusting for the height of the mob. Is it possible to somehow track if a function is executed at a position inside an entity's hitbox?
Comment: @Nik3141 It's just a partial solution, but IMO more convenient to use, as it would better simulate the entity hitbox shapes. Teleporting levitating arrows in combination to your particles is a great idea, as it uses already present mechanics to solve the problem. But, it would also use box-shaped detection areas, not spheres.
Comment: So I was reading a different post https://gaming.stackexchange.com/questions/352682/detect-if-the-player-is-at-a-specific-y-level-in-1-14 and saw that dx, dy, and dz track the hitbox, but distance doesn't. I think you said that in your answer but I just didn't understand, because I have never used dx, dy, and dz before. I edited your answer and my question to make it about detecting hitboxes, because that is really the essence of my question. If I change anything and it becomes incorrect, please change it.
Comment: Also, the wiki on selecting targets by volume at https://minecraft.gamepedia.com/Commands#Target_selector_arguments is very confusing when it says "`@e[x=1,y=2,z=3,dx=0,dy=0,dz=0]` — targets only entities whose hitbox collects with the block region (1,2,3)." What does it mean by 'hitbox collects'? Does the whole hitbox have to be inside the volume or only part of it?


What does the Comedy Specs extra do?

Question: The first extra that you can unlock is called Comedy Specs.  However, turning on this extra does not appear to make any changes to the game.  What does this extra actually do?
Answer: When you get the Spectre Specs (sp?) they will be the slinky eyeball glasses instead. Same function though (a silly prop replacement like Carrot Wands).

What does the Comedy Specs extra do?


Printing type-casted types in C

Question: <code>#include <stdio.h>

int main(void) {
    int nr = 5;
    char castChar = (char)nr;
    char realChar = '5';
    printf("The value is: %d\n", castChar);
 }
</code>
If the above code is compiled, the output will be:
<code>The value is: 5
</code>
But if the code below is compiled, the console will output the value 53 instead. Why doesn't it print the same as the when the "castChar" is printed?
<code>#include <stdio.h>

int main(void) {
    int nr = 5;
    char castChar = (char)nr;
    char realChar = '5';
    printf("The value is: %d\n", realChar);
}
</code>
Comment: Because `5` and `'5'` are not the same. The cast isn't even necessary: you could do `char castChar = 5;` and get the same results.
Comment: any character enclosed in single quotes will have the ascii value for that character. consult an ascii table.
Comment: Please could I suggest you read the [Markdown editing help](https://stackoverflow.com/editing-help)? The `pre` tags you're putting on all your posts are unnecessary and make the code blocks much bigger than they need to be.
Answer: It is showing the ASCII value of the character as you are using %d with a character.Use %c instead.
<code> #include

int main(void) {
    int nr = 5;
    char castChar = (char)nr;
    char realChar = '5';
    printf("The value is: %c\n", realChar);
}
</code>

Printing type-casted types in C


iphone : on receiving message, launch another app without user interaction

Question: Before I dive into development, I want to know if this is possible at all.
I'm a developer, but haven't developed an app. before, so sorry if the question sounds dumb..
Here is the use case -
User buys the app. and enables badges/alerts/sounds in the settings.
At certain point of time, my applications server sends a message to all users who have this app.
On the iphone, when the app. receives this notification, it launches a third party app. automatically. e.g. launch calendar to a certain date or start a game.
The main point being the user doesn't want to interact when this notification is received on the phone.
I want to know if this is allowed/possible at all. Should work on non-jailbroken phones.
Answer: Doesn't work at all. At least not in a allowed way.
Comment: Fact. This would work fine on Android. Apple restricts programs to just it's own sandbox. You could only launch the email client or the browser.
Answer: You can launch any app that publishes a custom URL scheme, where you know the scheme.  Several of the built-in apps have well-known schemes, and some (e.g. Facebook app) have well known documented schemes as well.
You launch an app using the UIApplication openURL method, passing a url with the custom scheme.
I'm not certain this is permitted / allowed when an app receives a push notification, but it's quite possible.
Comment: Seems this will get a POC out of me 8-) Thanks Tom.


Subpanel has neutral and ground bonded in detached structure - should I isolate?

Question: I have a detached garage built in 1979 with a Cutler Hammer subpanel with a 3-wire 8AWG feeder (hot/hot/neutral) on 40A breaker from the main house panel.  Subpanel has a dedicated ground rod installed.
The neutral is tied to the ground.  Shouldn't this be separate for a subpanel?
I think I need to install a second block to isolate the feeder neutral and building neutral.  Does that sound right?
Comment: This would have been a legal install at the time. Standards have moved on, but technically you don't have to do anything unless you are doing work that would require updating to current code.
Answer: This is grandfathered in
The NEC, up until reasonably recently, did not require an equipment grounding conductor in a feeder to an outbuilding, treating it by analogy to a service, where the fault path is through the neutral.  This is problematic from a shock risk perspective if the feeder neutral opens, though, which is why the Code was recently changed to require all feeders to carry an equipment grounding conductor with them.
As you are dealing with an existing install though, the NEC explicitly grandfathers the three-wire feeder to an outbuilding in via 250.32(B)(1) Exception 1:

Exception No.1: For installations made in compliance
  with previous editions of this Code that permitted such connection, the grounded conductor run with the supply to the
  building or structure shall be permitted to serve as the
  ground-fault return path if all of the following requirements
  continue to be met:
(1) An equipment grounding conductor is not run with the
  supply to the building or structure.
(2) There are no continuous metallic paths bonded to the
  grounding system in each building or structure involved.
(3) Ground-fault protection of equipment has not been installed on the supply side of the feeder(s).
If the grounded conductor is used for grounding in accordance with the provision of this exception, the size of the grounded conductor shall not be smaller than the larger of either of the following:
(1) That required by 220.61
(2) That required by 250.122

Changing it would be a good idea, but...
The 2014 NEC introduced a provision in 250.130(C) that allowed branch circuits to be grounded by tapping off of other EGCs.  This is handy for branch circuit retrofits, but sadly, does not apply to feeders; nor can you run the ground wire separately, as it reverts to 250.32(B)(1)'s verbiage which prohibits that.
This leaves you with three options.  The cheapest and simplest one is to install a GFCI breaker in-line with the feeder at the garage end.  This can get tricky though, as many small subpanels rely on a backfed main breaker, and you cannot backfeed GFCI breakers -- you'll fry the GFCI's trip solenoid if you try it.  Your best bet is to mount a unit mount/cable-in cable-out GFCI breaker in a single-breaker disconnect box and wire it up so that the feeder comes into LINE, and a short 4-wire feeder jumper connects LOAD on the breaker to the subpanel's main lugs.
You'll also need to unbond the subpanel, install a ground bar in it, and move the GEC over to be commoned with the LINE-side neutral of the GFCI via the disconnect box's neutral bar, which serves as the neutral/ground bond for the garage.
Making this a real service
An alternative is to snag a dry-type distribution transformer (5 kVA is a common size for this type of application, but might be slightly small for your 40A feeder) and install it at the outbuilding, creating a separately derived system.  The primary needs to be jumpered for 240V and connected to the feeder hots with the feeder neutral capped off as it's useless now, while the secondary is jumpered for 240V as well and feeds the existing garage panel, which is now a main panel from the Code's point of view.
While this sounds costly, transformers sometimes turn up used for reasonable prices -- they are fairly heavy critters though, so it's probably best to check Craigslist to see if one is coming out of a building demolition/remodel job or something like that in your area.
Redoing it
Of course, you can simply re-run the feeder as well, which will let you incorporate an equipment grounding conductor -- this is practical for a short feeder like yours, but can get costly for long feeders.
Comment: @kenchilada -- re-running the feeder as a proper 4-wire feeder works as well, of course
Comment: The unit mount GFCI breaker looks good, but very expensive!  I'm wondering if I am better off running new 4-wire feeder (its only 30 feet) and isolating the ground and neutral in the subpanel?  Thanks, great info.
Answer: That ground rod for the garage is called a grounding electrode system.  It's not enough.
The garage is not grounded, unless it is
First look to see if you have all-metal conduit coming over from the house to the garage's panel or grounding electrode system. If it is Rigid type conduit, you're all set.  Other types can be fairly marginal as corrosion has ways of eating them.  If you do not have all-metal conduit you are confident in, then your garage is not grounded.
Why is the grounding electrode system not sufficient? Because copper mines exist. If dirt conducted electricity all that well, they would just make wires out of dirt.  Way cheaper than copper.
Electricity flows in loops.  One loop is from the earth to the clouds back to earth (as lightning).  The other loop is from your power company, to "hot", to your tools, to neutral (or ground in case of a fault), back to the power company.
Your grounding electrode will take care of the lightning.  But for man-made electricity, the dirt will be unable to return meaningful amounts of ground-fault current to the service panel.  Without that return path, a ground fault will "light up" everything that is supposed to be grounded. Yowch!
Treat it like ungrounded service
Your best bet is to treat it like ungrounded service, and fit ground-fault detectors on every load, or as a master on the subpanel.  Like this European is doing.
I would separate neutral from ground in the panel, otherwise a neutral wire break will be lethal to you, again lighting up everything that is supposed to be grounded.
At this point your grounding system will be good for lightning and ESD protection but pretty worthless for shock/ground fault suppression. That's what the GFCI's are for.
Comment: 250.130(C) sadly doesn't apply to his case (it's only good for branch circuits, not feeders)
Comment: Thanks, I was misunderstanding the purpose of the electrode.


nexus 7 onboard keyboard issues

Question: when i start up ubuntu on my nexus 7, i am greeted with the first time setup screen. However, I cannot type into text fields using the onscreen keyboard. The keyboard does not seem to be outputting anything; none of the mouse click emulations nor text enrty are working. I can click on buttons and the keyboard is responding to taps (animations/options screens ect.) but is not giving any output into other windows. i got it working once but it stopped working right before i could confirm my password...
Answer: Just reboot your device by keeping the power button pressed. After this reboot it will work.

nexus 7 onboard keyboard issues


Codenameone, How can i call or load android native progress dialog?

Question: How can i use the android native progress dialog instead of the default cn1 one when i do network requests.
I have tried using native Interfaces i cant quite get them right
I know this is possible because i saw when i use the BrowserComponent it uses the progress dialog preloader
I want to replace the below InfiniteProgress with android one.
        InfiniteProgress prog = new InfiniteProgress();
        Dialog dlg = prog.showInifiniteBlocking();
        r.setDisposeOnCompletion(dlg);
        NetworkManager.getInstance().addToQueueAndWait(r);

Answer: BrowserComponent is implemented natively so you will have to use native interfaces if you want to do that although there is no reason I can think of for you to do that.
http://www.codenameone.com/how-do-i---access-native-device-functionality-invoke-native-interfaces.html
Comment: Thanks Shai, I get your point. Its Just that i dont like that cn1 loading spinner generated by InfiniteProgress , unless theres a ways to style it.
Comment: You can style anything in Codename One, how would you like it to look?
Comment: Maybe similar to the one i attached but without the Title. Just the rotating gif and  "Please wait text".
Comment: `Dialog dlg = new Dialog(new BorderLayout()); dlg.add(BorderLayout.CENTER, new InfiniteProgress()); dlg.showModless();`


How to teleport seamlessly?

Question: So I'm trying to make one of those "infinite hallways" things, and when I teleport the player there is a short frame of something every time. I am teleporting relative the player shouldn't be able to notice it, but every time I teleport it makes a weird blink and is noticeable. How do I fix this? I tried 1.9 and 1.12, both of which did not work. The command I am trying to use is
tp @a[x=-299,y=56,z=-559,r=1] ~ ~7 ~

Comment: Like I said, I tried doing it in both 1.9 and 1.12 and nether of them work. Should I try versions?
Comment: It doesn't do that for me. In fact, I clearly remember that there was a bug report about this and it was fixed long ago. What version are you playing in?
Comment: Oh, I didn't notice that. I tried 1.14.4 and it works, but 1.12 should also work.
Comment: This bug was originally fixed a while ago (a long time ago) but then it was broken again. Now, for version 1.14 and later, it is fixed again.
Answer: This is something that has worked on and off for a while - it was originally fixed, then it broke again and more recently has apparently been fixed.
The bug: MC-4686 was fixed in minecraft version 18w43a which is the first snapshot for Minecraft 1.14
Under the list of fixes for that version: MC-4686 – Client movement when teleported
So as long as you use Minecraft Java Edition 1.14 or later you should be able to use seamless teleportation without issue.
However, with later versions of minecraft you should familiarise yourself with the new command formats before trying the same old commands - the process of teleportation others using relative coordinates is slightly different now.

How to teleport seamlessly?