PC/Switch (in one subnet) connect to Switch (in another subnet), but not to PC connected to the switch

Question: [UPDATE]
The problem/behavior described below was caused by the public network connection on the system -which had a default gateway. The unusual behavior was a result of the private network sending traffic through the public network. The issues disappear once the two are properly isolated.

Two subnets on the same vlan. Everything works fine within the subnets & can ping from PC/Switch in one subnet to the Switch in the other subnet. But, cannot ping from Switch/PCs in one subnet to PCs in other.
Subnet #1:
Switch1 IP: 10.20.78.1/26
PC1 IP: 10.20.78.10/26
Static route on PCs: route 10.20.78.0/26 10.20.78.1
Static route on Switch: ip route 0.0.0.0 0.0.0.0 "router 1"
Subnet #2:
Switch2 IP: 10.20.78.65/26
PC2A IP: 10.20.78.70/26
PC2B IP: 10.20.78.71/26
Static route on PCs: route 10.20.78.64/26 10.20.78.65
Static route on Switch: ip route 0.0.0.0 0.0.0.0 "router 2"
Switch #1:

Switch #2:

PC:

Since both switches can communicate with each other, I suppose that the routers in between & the routing on the switches are fine. Windows firewall for 'echo' is open (without any scope restrictions) on all PCs. Trace route from PC/switch in subnet #1 works fine up to the switch in subnet #2, but and then timeout (& vice-versa). Am I missing something obvious, or is this strange? Appreciate pointers on how to fix this.
Answer: There is more to this than I feel you've included in the screenshots, because as far as I see it you have some ping successes that really should be failing; PC2A to switch 1 from the config details you included should not be working, but for some reason your last screenshot shows replies.
The issue I can see right away is the routes on your PCs:
Subnet #1: (10.20.78.0/26)
...
Static route on PCs: route 10.20.78.0/26 10.20.78.1
...

Subnet #2: (10.20.78.64/26)
...
Static route on PCs: route 10.20.78.64/26 10.20.78.65
...

is incorrect. You need to route the other network through the local switch interface; ie. it should be as below:
Subnet #1: (10.20.78.0/26)
...
Static route on PCs: route 10.20.78.64/26 10.20.78.1
...

Subnet #2: (10.20.78.64/26)
...
Static route on PCs: route 10.20.78.0/26 10.20.78.65
...

I suspect changing this will probably fix your issue, but that ping from PC2A to switch 1 that is working does raise some skepticism.
Run the command route print -4 from cmd on your PCs and update your question with the output and you should be able to get a more confident answer.
Comment: I think you have not noticed the routing command on the switches (Switch 1: ```IP routing 0.0.0.0. 0.0.0.0 "router1"```) and hence your comment that it should not be working. The screenshots show what I get. Router 1 is connected to Switch #1 (and router 2 to switch 2, and there are a bunch of switches/routers in between Router 1 & Router 2. both routers and those in between have routing tables to direct traffic from my switch 1 to switch 2 & vice-versa). I am currently away & will get an route print -4 when get to these machines
Comment: @vasikan no the default route on the switches is fine, but on the PCs your config samples showed specific routes configured on the PCs; doesn't show what the default gateway on the PCs is. My comment that it shouldn't be working was going purely by the config that was included in the original question, assuming there was nothing else configured. Try the routing and see, if it doesn't fix, do the `route print -4` and post that output
Comment: These PCs are dual-homed (with this private IP & a public IP). In my attempt to keep the post not too long (which it already was) I missed mentioning that aspect.  I now recognize the error in the routing statement that you caught & understand why it still connected (the traffic was routed through the public IP address & the default gateway which is the public IP address of the same switch (which routed it to the same router). When I get to the site, I will try the new route and/or get route print -4
Comment: Newbie question: Is the proper thing here is for me to delete the question since it was based on an incomplete premise, or leave it since the [Update] explains the issue.
Comment: @vasikan I think you're safe to leave it up, that way if anyone is having a similar issue they might find this and be able to resolve it without opening a new question. If it was a problem I think the mods would have probably flagged and closed it already.


Homogeneous System of Linear equations proof

Question: I'm struggling to solve this proof:
Suppose that $\boldsymbol{u}_1, \boldsymbol{u}_2, . . . , \boldsymbol{u}_n$ are solutions of an homogeneous system of linear equations $\boldsymbol{Ax} = \boldsymbol{0}$, $\boldsymbol{x} \in \mathbb{R}^n$.
Suppose that $k_i \in \mathbb{R}$. Show that
$k_1\boldsymbol{u}_1 + k_2\boldsymbol{u}_2 + · · · + k_n\boldsymbol{u}_n$
is also a solution of the system $\boldsymbol{Ax}=\boldsymbol{0}$.
I know that I should use the proof for showing that if A is invertible then the only solution is $\boldsymbol{x}=\boldsymbol{0}$ when $\boldsymbol{Ax}=\boldsymbol{0}$, but am unsure about the most efficient way of doing this.
Any help is greatly appreciated.
Comment: Use linearity of matrix multiplication.
Answer: Hint: Let $\boldsymbol{x} = k_1\boldsymbol{u}_1+\ldots+k_n\boldsymbol{u}_n$
$$\boldsymbol{A}\boldsymbol{x}=\boldsymbol{A}(k_1\boldsymbol{u}_1+\ldots+k_n\boldsymbol{u}_n)=\sum_{i=1}^{n}\left[k_i\left(\boldsymbol{Au}_i\right)\right]$$
Remeber that all $\boldsymbol{u}_i$ are solutions to $\boldsymbol{A}\boldsymbol{x}=\boldsymbol{0}$. What can you conclude from this
Comment: Surely that the sum of the series is 0? Is this enough to prove this statement though as it seems very short
Comment: I would say that this is enough.


Drupal menu management seems lacking compared to WordPress: Am I missing anything?

Question: I'm trying to understand how to best add content links to menus. As far as I can tell, there are two limited ways:

In the content edit screen, click the "Provide a menu link" checkbox. Shortcoming: This will only add links to the main menu- you can't target other menus from the content edit interface?
In the menu edit screens, you can add links. Shortcoming:  You have to spell out the paths. Seems like it would be a lot easier if there was a content finder on this screen so that you could easily select the content, a la WordPress and every other CMS.

I'm coming from WordPress, which has a basic but robust menu management system. Is Drupal just lagging in this regard? Are there better ways of handling menu links?
Answer:
On node edit page, upon checking "Provide a menu link" populates a select box with menus and theirs items which are associated with this content type. To include other menus you need to edit your content type.
You are right in this regard but there can be some module.
Comment: You're catching everything I throw at ya ;)  thanks-


How can $z^\alpha$ for $\alpha>0$ be a conformal mapping?

Question: We know that $z^a = r^\alpha e^{i\alpha\theta}$ so that this function maps the wedge $\{z: \theta_1<Arg(z) <\theta_2\}$ to the wedge $\{z:\alpha\theta_1<Arg(z^\alpha)<\alpha\theta_2\}$.  For the mapping to be conformal it seems to me we need $\theta_2-\theta_1=\alpha\theta_2-\alpha\theta_1$ which would imply $\alpha=1$.  However, I've read that the only requirement necessary for the map to be conformal is $\alpha\theta_2-\alpha\theta_1\leq 2\pi$.
Answer: You are thinking about angle preservation at $0$; this is where the lines $\arg z = \theta$ meet. It is correct that the function $z^\alpha$ is not conformal at $0$, unless $\alpha=0$.   But the claim is that it is conformal in the domain $\{z: \theta_1<\operatorname{Arg}(z) <\theta_2\}$, and this domain does not include $0$.
The argument of $0$ is undefined, so any formula that specifies what the argument of $z$ should be automatically excludes $z=0$.
Answer: A complex map is conformal on an open set $U$ if and only if it is holomorphic and its derivative is nowhere vanishing on $U$.
These are easy enough to check for your map; the thing about your map is defining it.
We have $z^\alpha=\exp(\alpha\,\text{Ln}(z))$, so you must choose a suitable branch of the complex logarithm.
The idea is that $\theta_1$ and $\theta_2$ must be such that the domain does not cross the branch cut.


Converter string para static?

Question: E possível estar  convertendo string para static ?
    String prefix = getConfig().getString("prefix");
    String sufix = getConfig().getString("sufix");

Cannot make a static reference to the non-static field prefix

Existe uma maneira de converter essa String  para static?
Bukkit.getServer().broadcastMessage("" + prefix + "", 0);

(So posso pegar o "Prefix" usando string)
Codigo completo.
package space.plugin.automsg;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.conversations.PlayerNamePrompt;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;

import com.sun.media.jfxmediaimpl.platform.java.JavaPlatform;

import net.md_5.bungee.api.ChatColor;

public class Main extends JavaPlugin implements Listener{

    public static Automsg plugin;
    public final Logger logger = Logger.getLogger("Minecraft");
    public static int linhaAtual = 0;
    public static int tid = 0;
    public static int circulando = 1;

    String prefix = getConfig().getString("prefix");
    String sufix = getConfig().getString("sufix");

    @Override
    public void onDisable(){
        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " Versão " + pdfFile.getVersion() + " está desabilitado.");

    }

    @Override
    public void onEnable(){

        Bukkit.getPluginManager().registerEvents(this, this);
        this.saveDefaultConfig();

        String prefix = getConfig().getString("prefix");
        String sufix = getConfig().getString("sufix");
         String delay = getConfig().getString("intervalo");
         long d = Long.parseLong(delay);

        PluginDescriptionFile pdfFile = this.getDescription();
        this.logger.info(pdfFile.getName() + " Versão " + pdfFile.getVersion() + " está habilitado.");

    tid  = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
            public void run() {
                try{
                mensagens("plugins/Automsg/mensage.txt");
                } catch (IOException e){

                }

            }
        }, 0, d);

        }

    public static void mensagens(String fileName) throws IOException {
        {

        FileInputStream fs;
        fs = new FileInputStream(fileName);
        BufferedReader br = new BufferedReader(new InputStreamReader(fs));
        for(int i = 0; i < linhaAtual; ++i)
            br.readLine();
        String line = br.readLine();
        line = line.replaceAll("&4", ChatColor.DARK_RED + "");
        line = line.replaceAll("&c", ChatColor.RED + "");
        line = line.replaceAll("&6", ChatColor.GOLD + "");
        line = line.replaceAll("&e", ChatColor.YELLOW + "");
        line = line.replaceAll("&2", ChatColor.DARK_GREEN + "");
        line = line.replaceAll("&a", ChatColor.GREEN + "");
        line = line.replaceAll("&b", ChatColor.AQUA + "");
        line = line.replaceAll("&3", ChatColor.DARK_AQUA + "");
        line = line.replaceAll("&1", ChatColor.DARK_BLUE + "");
        line = line.replaceAll("&9", ChatColor.BLUE + "");
        line = line.replaceAll("&d", ChatColor.LIGHT_PURPLE + "");
        line = line.replaceAll("&5", ChatColor.DARK_PURPLE + "");
        line = line.replaceAll("&f", ChatColor.WHITE + "");
        line = line.replaceAll("&7", ChatColor.GRAY + "");
        line = line.replaceAll("&8", ChatColor.DARK_GRAY + "");
        line = line.replaceAll("&0", ChatColor.BLACK + "");
        line = line.replaceAll("&l", ChatColor.BOLD + "");
        line = line.replaceAll("&n", ChatColor.UNDERLINE + "");
        line = line.replaceAll("&o", ChatColor.ITALIC + "");
        line = line.replaceAll("&k", ChatColor.MAGIC + "");
        line = line.replaceAll("&m", ChatColor.STRIKETHROUGH + "");
        line = line.replaceAll("&r", ChatColor.RESET + "");

         //erro, pede que o prefix seja static
        Bukkit.getServer().broadcastMessage("" + prefix + "", 0);
        }

    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event)
    {
        Player player = event.getPlayer();
        player.sendMessage(this.getConfig().getString("entrada"));
    }

}

.
String prefix = getConfig().getString("prefix");
  // pegar a configuração do prefix: .

config.yml
intervalo:
    -10
entrada: 'a'

mensagen:
    -
    -

prefix: '[AutoMsg]'

sufix: '<--'

Comment: static não é um tipo, não entendi sua duvida.
Comment: Não resolve botando `static` antes de String? `static String prefix = getConfig().getString("prefix");`
Comment: Preciso colocar o prefix em broadcastMessage... mas ali so aceita static, e  para pegar o prefix eu tenho que usar String p acessar o arquivo. pelo getConfig();
Comment: Diego, não. "Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin"
Comment: @NatanaelNicolas Precisamos do código do bloco pra entender o que você está falando.
Comment: Natanael o problema não tem a ver com tipo, e sim, escopo, mas esse trecho de código está vago para poder sugerir algo.
Comment: Este problema ocorre quando de dentro de um método estático você tenta referenciar uma variável não estática. Você poderia aumentar o trecho de código para termos uma noção melhor do que está tentando fazer?
Comment: Editei e coloquei o codigo completo
Comment: Pronto, jovem. Só olhar a minha resposta.
Answer: O seu problema é que o método que está usando a propriedade prefix é estático e este membro é não-estático.
Se você precisa acessar um membro não-estático (membro de instância) então o método que faz este acesso não pode ser estático.
Apenas tire o static da assinatura do método.
public void mensagens(String fileName) throws IOException {
    /* Todo seu código */

    Bukkit.getServer().broadcastMessage("" + prefix + "", 0);
}

Comment: Otimo funcionou, estava usando static poruqe o br da Resource leak: 'br' is never closed. usei br.close();
Comment: @NatanaelNicolas Mas deixar o método como `static` não é certo pra evitar _resource leak_. O correto mesmo é fechar o recurso, como você fez.
Comment: @Amadiu Instanciar uma string?

Converter string para static?


A simple question about quotient sets

Question: Let $V$ be a vector space over $\mathbb{R}$ and $W$ be a subspace of $V$. We know that the congruence module $W$ is an equivalence relation and that the quotient set $V/W$ is composed of equivalence classes.
Now if $W=\left \{ 0 \right \}$, then $\left [ v \right ]=\left \{ x\in V;x\equiv v,\textrm{mod}\: 0 \right \}=\left \{ v \right \}$, then $V/W=\left \{ \left \{ v \right \};v\in V \right \}$.
But I saw in a book that this result is written as $V/W=V$.
What is the reason to write that way?
The elements of the quotient set are not sets?
In my opinion this way of writing is incorrect.
Thanks for your help.
Answer: You are correct; the sets are not equal but isomorphic, so it should be $V/W \cong V$.

A simple question about quotient sets


Custom themes for Coda like there are TextMate

Question: Is there custom themes for CODA? as in preferences there is a export and import button. So i am guessing yes? But i am unable to locate any on the internet
Answer: I've created several: http://joebergantine.com/werkstatt/seestyle. If you search around the archives of the coda users group there's several listed there. I suggest the phrase "seestyle theme".
Comment: Yes thanks...i am using this now. i like it a lot, nice and easy on the eyes
Answer: Try this out: http://ipaintcode.com/coda-2-themes/
Also forkable on github: https://github.com/ipaintcode/Coda-2-Themes


Algorithm suggestions for distinguishing images of human faces

Question: I am looking to develop a facial algorithm that would take as input 2 images and calculates if the faces in the 2 images are of the same person or not. I have all the pre-processing of the images working using OpenCV. In the prepossessing steps I crop the face from the entire image, convert it to gray-scale, and resize it to a standard size. My problem is a bit different from facial recognition in the sense that I am not concerned with identifying the individual in the image, I just want to be able to say if they are the same person or not. Most facial recognition algorithms I looked at rely on training from sample faces of the same persons that will comprise the input. In my situation I can train with general faces but not exact faces that will be in the input.  Could you please suggest some methods that could work in my situation?
Comment: detection of a pair of same faces and face classification are simply two operational modes of face recognition. Most face recognition algorithms can be adapted to operate in both modes (giving different performances); therefore, the algorithms you found will still be useful to your project.
Answer: Typically you would measure distances between features.
If you can't control the position/size/angle of the image - ie it's a real world image, not someone sitting in front of a face scanner - then you need to think about how to make these all ratios.
Try finding the eyes (easy) and the mouth or nose and get the sides/angle of the triangle.
You can then also do percentage of face area covered by hair, width/length ratio of nose etc.
Answer: For your problem, perceptual hashing along with edit distance might be more proper.
Check out

http://phash.org/
Looks Like It
TinEye Reverse Image Search
Comment: TinEye does a good job indexing images on the web. I think what we have here is quite different. I tested that with a reasonable image that doesn't come straight off the web. I took a screenshot of John Lennon's face from this interview on YouTube (http://www.youtube.com/watch?v=iREKEWdjAUU) and TinEye found no matches, honestly declaring: "TinEye looks for the specific image you uploaded, not the content of the image. TinEye does not identify people or objects in an image." See for yourself, the query is cached upto 72 hrs http://www.tineye.com/search/a4981f401b2596a641f3e514103724b5bff3b9fd/
Answer: Face recognition from a single image per person: A survey
Answer: If you haven't already, look into Wavelet methods.  See this paper for example.


What was the worst result for a president's trophy winner in the playoffs?

Question: The Columbus Blue Jackets defeated the Tampa Bay Lightning in a sweep in the 1st round of the 2018-2019 NHL playoffs. Outside of this occurrence, what was the worst result for a President's Trophy winner in the playoffs?
There must have been some that got outed in the first round, but if so, what was the game score? 4-3? 4-1?
Answer: There have been eight NHL teams thus far to win the President's Trophy but be eliminated in the first round of the Stanley Cup Playoffs.
The worst Stanley Cup finish by a President's Trophy winner was in 2018-19 by the Tampa Bay Lightning, who were eliminated in the first round by the Columbus Blue Jackets, in a 4-0 series.
Other President's Trophy winners eliminated in the first round are

1991 Chicago Blackhawks by Minnesota North Stars in a 4-2 series.

2000 St Louis Blues by San Jose Sharks in a 4-3 series.

2006 Detroit Red Wings by Edmonton Oilers in a 4-2 series.

2009 San Jose Sharks by Anaheim Ducks in a 4-2 series.

2010 Washington Capitals by Montreal Canadiens in a 4-3 series.

2012 Vancouver Canucks by Los Angeles Kings in a 4-1 series.

2023 Boston Bruins by Florida Panthers in a 4-3 series.
Answer: As of the 2023 playoffs, The 2022-23 Boston Bruins now holds the worst result as a presidents trophy winner. Had a record breaking regular season only for them to lose in the first round to the Florida Panthers in 7 game. The Bruins blew a 3-1 series lead
Comment: 1st round  0-4 has already been given by an existing answer, how does 1st round 3-4 form a worse playoff record?
Comment: Welcome to Sports SE. Please add a source to your answer


When does travel become residency?

Question: Where are the boundaries between travel and residency?
If I go on a one-month work holiday, do I ask here or at Travel?
If I go on a 5-month Erasmus Exchange project, do I ask here or at Travel?
If I spend ⅓rd of my time abroad for family reasons, are those regular visits travel, or might related question fit better here?
Comment: I think question is also fit for the non-meta site
Answer: Travel vs. Residency isn't so much a legal distinction as it is a practical one.
For Travel.SE, the distinction is fairly simple: Is the question relevant to someone who is only traveling?
Regardless of the length of one's stay at a vacation destination, there are only certain questions that are likely to come up.  How to apply for a residency visa, how to open a bank account, and how to establish good credit with the local electric company are obviously not among them.
However, whether you're staying for 1 week or 15 years, how to not get ripped off by a taxi driver* is a relevant "travel" question.
I think we can apply a similar standard here, and say that a question is within the scope of "Expatriatism" if it is about how to living outside of your "home country."  "Living" is purposely a vague term.  How long must one be somewhere to say they "live" there?  It's a judgment call.  But certainly questions about setting up a bank account, or not being ripped off by taxi drivers* are relevant.  How to find the best price on airfare to visit your family back home would not be appropriate here, and should go to Travel.SE.
*I intentionally chose an example that I think ought to be on topic both here and on Travel.SE.
Comment: +1 Travel.SE has quite clear rules on what is being on-topic there and what is "too expats". However, still there are questions which are truly bordeline, for instance [this one which I just moved from there to here](https://expatriates.stackexchange.com/questions/90/getting-a-mutuelle-in-france-with-eu-health-insurance).
Comment: *For Travel.SE, the distinction is fairly simple: Is the question relevant to someone who is only traveling?* Isn't that begging the question?
Comment: @tohecz: There's nothing wrong with "border-line." In fact, it's best if there is an overlap--that prevents questions from falling between the cracks.
Comment: Yep, but being borderline means a risk of little-to-no popularity of your question. And minimizing the width of the border is helfpul to prevent cross-posting (just see how many questions have been asked on all of SO, SU, SF and Unix).
Answer: In my opinion this would be determined by whether or not you have to go through the same things that somebody moving to the country would. Examples I can think of are:

Setting up a bank account
Getting an ID number (Social Security, National Insurance, Municipal Service Number, etc.)
Registering your address with the local authority
Setting up utilities

These are the types of things every new resident has to go through, and so do many short-term travellers. I've known some Erasmus students who go through the process of registering locally and setting up a bank account, and some who just use their home bank and leave next to no paper-trail when they leave.
Come to think of it, I suppose it's that paper-trail that makes most of the difference in my mind. Tourists don't leave a permanent record, but expats do.
Answer: The intent really separates the two. If you're going somewhere to visit, it's travel, to live, it's residency. By live I mean (any / all below)

You pay monthly rent / mortgage
You open a bank account
You need something beyond a tourist visa
You are obligated to remit taxes for money earned there
You work there
You put your kid(s) in school(s) there
You've had to go buy clothes there more than once or twice

.. the list can really go on. When your location has become an integral part of your life, you probably belong here.
But, avoid "as an expat" as a qualifier to ask questions that probably belong on other sites, where the place that you currently live has little to no bearing. If I want to book a trip by ship to Malaysia and then off by train to Singapore - I need to go to Travel.
Comment: I like this informal activity-based approach to the definition. Ultimately the divisions between sites are meant to ensure that questioners connect with experts who have the answers they seek, and I think this allows in just enough of the grey area (exchange students, contractors, aid workers, snowbirds, etc.) that they will be in the place where their expat-like questions can be answered, even if they are not the canonical this-is-my-only-home-now sort of expat.
Answer: Both within the EU and elsewhere it's not unusual for people to split residence between countries for part of each year, especially if retired.
In North America, they're called snowbirds - those who head south for the winter.  Probably similar in Europe for the warmer places like the Canaries, many would have a seasonally-occupied home (especially Scandavians and Germans).
In many cases, these people have the same questions as expats (except possibly working).  They own property, need to have a local bank account, might need some special visa category that allows longer stays, have problems registering cars as non-residents, and so on.  (in many ways the problems are often tougher, as they're living there but might be considered non-residents).
So regular season residence (3-6 months every year, probably with an owned property) has more in common with expat issues that with travel.
Maybe a reasonable definition of expat would be one who is at a "home" (or work) outside their own country.
Answer: I think the boundary between travel and residency is governed by the laws of the country you are visiting.
The authorities in the country you visit have a strict definition of what is legitimate travel  and what is residency (legal or not). For example, you can travel to the USA on the visa waiver program for 90 days, on a business visa for longer periods if you perform certain types of jobs and are not paid as an employee in the USA.  This is travel.
Once you start exceeding the bounds of such limited permissions - in duration, or income, then this starts to become residency.  The strict terms for this will be determined by the regulations of the country you visit.
Comment: That may not be so easy to determine inside the EU/Schengen, where anyone can travel anywhere for any time.
Comment: @gerrit travel, yes, but you still have to take up residence somewhere.
Answer: A simple definition?
You become an expatriate when you declare a new residency, primary or secondary, outside of the country of your citizenship, with the intention of creating a home and base of living there.
Travel is being away from your home without creating a new one.
Comment: By this definition, someone working abroad on a 2-year contract in Dubai might not qualify as an expat because they have "no intention of creating a permanent home and base of living there." Yet they will face all the things an expat faces.
Comment: @JonathanVanMatre I don't think someone would go to Dubai for 2-years and not build a base of living there. I think your example falls together with types such as military or missionary work abroad. These are very specific types of expat-life, where your life-style is primarily defined by your work and not your surroundings.
Comment: Yes, but that base is not permanent and the person knows it is temporary from day one. In some cases they may even do long-term work abroad while spouse and children remain at home. It's that word "permanent" that I think is too restrictive.
Comment: @JonathanVanMatre removed the "permanent" : )

When does travel become residency?


calculate the derivative of a function containing factorial

Question: I got an expression for free energy F in a book as:
$$F(N_1) = \frac{N_1N_2}{N}W-kT(\log N!-\log N_1!-\log N_2!),\tag1\label1$$
where $N=N_1+N_2$. As what the book later introduced, the derivative of $\eqref1$ is:
$$F'(N_1)=\frac{N_1-N_2}{N}W-kT\log\frac{N_1}{N_2}.\tag2\label2$$
Can anyone tell me the steps needed to derive $\eqref2$ from $\eqref1$?
Answer: You need to use Stirling's Approximation:
$$\ln n!=n\ln n-n$$
Then
$$F(N_1) = \frac{N_1N_2}{N}W-kT(\log N!-\log N_1!-\log N_2!)$$
becomes
$$F(N_1) = \frac{N_1N_2}{N}W-kT(N\log N-N-N_1\log N_1+N_1-N_2\log N_2+N_2)$$
$$\Rightarrow F(N_1) = \frac{N_1N_2}{N}W-kT(N\log N-N_1-N_2-N_1\log N_1+N_1-N_2\log N_2+N_2)$$
$$\Rightarrow F(N_1) = \frac{N_1N_2}{N}W-kT(N\log N-N_1\log N_1-N_2\log N_2)$$
See if this helps.


Como criar uma tarefa agenda com laravel

Question: Galera estou tentando trabalhando com cron pela primeira vez e tentando criar uma tarefa agendada bem simples.
estava olhando o documentação e vi que este comando precisa ser executado
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

executei ele no terminal assim:
* * * * * php /var/www/html/mail-with-cron schedule:run >> /dev/null 2>&1

com o diretorio do meu projeto e depois dei um php artisan serve
mas ele não executou o comando de inspire
Comment: Como esta o arquivo mail-with-cron/app/console/Kernel.php dentro?
Answer: Isso não é um comando que é executado no terminal. Você precisa colocar esse comando no cron do seu server. Para isso execute no terminal crontab -e
Será aberto um arquivo. Aqui sim você coloca a definição do crontab.
* * * * * php /var/www/html/artisan schedule:run >> /dev/null 2>&1

Isso irá executar todos os comandos definidos no método schedule em app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('inspire')
             ->hourly();
}

Answer: Faltou o artisan no final do diretorio, então fica assim:
* * * * * php /var/www/html/mail-with-cron/artisan schedule:run >> /dev/null 2>&1

Comment: Não é um comando esse cron


Exploring shifts in response to dichotomous dependent variable

Question: I have one dichotomous dependent variable (buried with grave goods or not) and a series of categorical and continuous independent variables (age at death, year of death, sex, socioeconomic status) for a dataset of c.5000 individuals. Therefore, I have used binary logistic regression in SPSS to explore how each of the independent variables impact the likelihood of the individual being buried with grave goods.
However, in my preliminary analysis, I found that the proportion of individuals buried with grave goods seemed to increase until around the age of 10-12 and then plateaued. I have two questions related to how I can explore this trend:

I performed a binary logistic regression for individuals aged 1-12 and another for individuals 13-30 and found age was a significant contributing factor in the first regression and not in the second. While this does demonstrate that the pattern is likely there, I am unhappy with this approach and have not been able to find good examples of how these patterns are normally tested for significance (while controlling for the other variables). Any suggestions or examples of how this has been done would be greatly appreciated.

I am interested in identifying the age at which this trend shifts so that I can then see if there are differences between the socioeconomic groups however I do not have a statistics background and am unsure how best to go about this.
Comment: That's very kind of you to offer. Your suggestion of looking at interactions was a good one. I think that is a great way to approach this problem
Comment: Did you advance? If you want I can have a look at your data, but then you need to share a link ...
Comment: Hi again, I have looked into splines and interactions and I think I understand how to go forward but would like to check my understanding.
1. To incorporate both splines and interactions, it seems easier to complete this analysis in R rather than SPSS
2. I then construct a full model with all my variables including splines for age as well as interaction variables between socioeconomic status and the splines for age
3. To probe the interaction between socioeconomic status and age, I then compute predicted probabilities that the individual received grave goods for different ages
Comment: *my apologies. Compute the predicted probabilities that the individual received grave goods for different ages within different socioeconomic classes (ie. age 5 at low, medium, high status; age 10 at low medium, high status; age 15 at low, medium, high status etc.)
Answer:
It is usually best to use a model with all the data, and then include interactions. I discussed this at Separate Models vs Flags in the same model, see also How to test a curvilinear relationship in a logistic regression.
For your data I would try a generalized additive model (see tag gam), a very good and flexible implementations is mgcv R (there might be something in SPSS, but I do not know about that). In reality, gam's as implemented in mgcv can be seen as a modern, flexible implementation of glm's (generalized linear models), and what I show here could be done, more or less, with glm plus some spline packages. But the modern, flexible way is shown below. So, something like
library(mgcv)
yourdf <- data.frame(grave_goods=, age_at_death=,
                     year_of_death=, sex=,
                     ses=, ...)
mod0 <- mgcv::gam( grave_goods ~ sex + ses +
                    s(age_at_death) +
                    s(year_of_death),
                    family=binomial, data=yourdf,
                     ... )
summary(mod0)

Here I assume that grave_goods, sex, ses are factors, and that ses has few levels (probably 2?). The above is then a base model, with smooth effects, but without interactions. Interactions can be modeled using terms such as
s(age_at_death, by=sex)

or
s(age_at_death, by=ses)
or even
s(age_at_death, by=interaction(sex,ses))

(same with year_of_death).  For interactions between the two numerical variables we have to be careful, since they will have very different ranges ... but something like the following:
s(age_at_death) + s(year_of_death) +
ti(age_at_death, year_of_death)

Here is some useful material on mgcv made available by ith author Simon Wood.
Comment: This is great thank you! I just have a couple of follow up questions. What is the benefit of ti(age_at_death, year_of_death) and would this include an interaction of the two variables with their splines? Also I am curious about the comment that two continuous variables with different ranges should be treated carefully. I have not seen this concern come up before looking into interactions
Comment: `ti` (read as "tensor interaction" is made for an anova-like interpretation, so is assuming the main effects are already in the model (and taking care of that). Different ranges is important, because using a term like `s(age_at_death, year_of_death)` is using an isotropic thin-plate spline, while `ti` is using a tensor product,not assuming isotropic
Comment: Ah understood. That makes sense, thanks again!
Comment: I do hope you don't mind me posing one more question. In my case, the number of burials with grave goods is disproportionate to those without (c.10% are buried with goods). It seems brglm can implement Firth's correction for this but I cannot see whether splines can also be included. Do you happen to know the answer to this?
Comment: I doubt that 10% rate is lowe enough to matter, but you could always try&see ... see https://stats.stackexchange.com/questions/88734/seeking-a-theoretical-understanding-of-firth-logistic-regression. Then `brglm` seems to use the same interface as `glm`, so you could always use regression splines (with package `splines`. But that will not (easily) match the spline interaction modeling of mgcv ...  Maybe you could look into `brms`
Comment: I see. OK thank you, I will look into brms as an option


How to get a name with random prefixes and suffixes

Question: I have a semi unique problem and I have no clue where to start. I'm using python
So im trying to get a bunch of info about items off two API's and these API uses two different id methods
Name and ID
The Name will look something like: Helmet of Divan
The ID will look like: DIVAN_HELMET
This is easy for me connect the two in a dictionary. My problem is sometimes the names will have suffixes and prefixs. Such as:
Wise Helmet of Divan or Clean Helmet of Divan or even have Unicode like ✪ Helmet of Divan ✪.
I want to get the ID DIVAN_HELMET from these names, but I can't know how many characters the prefix is or even if there is a suffix/prefix. I need to do this in mass for over 3 thousand items with dozens of suffixes and prefixes.
Comment: I have no idea what "semi unique" means. Something is either unique or it isn't. Also, you forgot to post the code you're struggling with https://stackoverflow.com/help/minimal-reproducible-example
Comment: If the base name is always present, then you can use a loop with `if looking_for in new_name:`.  It's going to take time
Comment: `"Helmet of Divan" in "Wise Helmet of Divan"` will return you true if first is part of second. Is it solves your problem?
Comment: Have you tried regex? It will be better if you share your code
Answer: So you want to get such output: DIVAN_HELMET
From such inputs: Wise Helmet of Divan or Clean Helmet of Divan or ✪ Helmet of Divan ✪
First you can remove all non-ASCII characters, e.g. like this answer :
import string
printable = set(string.printable)
str_input = ''.join(filter(lambda x: x in printable, str_input))

Then you need to convert them to all lowercase like str_input = str_input.lower()
Then, you need to tokenize the input; the easiest way is just to split it by space, e.g.: arr_str_input = str_input.split(" ")
Then you need to remove the stopwords like 'of' or 'the'. For this step you can use publicly available stopword list like this or just hardcode removal of word 'of' if that's all the stopword in your input text. e.g.: arr_str_input.remove("of")
Then you need to remove the prefix or suffix. In this step you can just supply the list of all prefix/suffix yourself or use readily made one like this (be careful since it can be very big list)
After all that, you should have a list/array of only 2 word like ['helmet','divan']. Last step should be just arranging them and making them uppercase, e.g.:
result = ['helmet','divan']
result.reverse()
print('_'.join(result).upper())
# outputs DIVAN_HELMET


Is there a name for this topology?

Question: First off, I want to  point out a popular topology for the real line. We know it commonly as the Michael line. It is given by
$\mathfrak{T}_M =\{U \cup I: U$ is open under usual topology, $I \subset \mathbb{R} \setminus \mathbb{Q} \}$.
But is there a name for the topology given by
$\mathfrak{T} =\{U \cup Q: U$ is open under usual topology, $Q \subset  \mathbb{Q} \}$?
Answer: This is defined in Counterexamples in Topology as space #70, Discrete rational extension of $\mathbb R$.
Comment: Interestingly we don't have "Michael Line" as an alias of [S63](https://topology.pi-base.org/spaces/S000063); this should be fixed.
Comment: Thanks! I appreciate the feedback!

Is there a name for this topology?


Show that the equality is true

Question: If $f$ is a Completely multiplicative function and $g$ is an arithmetic function such as $g(1) \neq 0$ prove that:
$$(f\cdot g)^{-1} = f\cdot g^{-1}$$
Any function with the -1 as exponent is the Dirichlet Inverse.
My try:
Applying the Dirichlet inverse definition to the LSH we have:
$$ \Large (f\cdot g)^{-1}(n) = \frac{-1}{(f\cdot g)(1)} \sum_{d|n \atop d<n}(f\cdot g)\left(\frac{n}{d}\right)\cdot (f\cdot g)^{-1}(d) \quad $$
Is there any definition that can help me to separate them?
Comment: But $\cdot$ is not the Dirichlet convolution, but simple multiplication?
Comment: Im not sure!! But i guess is simple product because in classes we use * for Dirichlet convolution.
Answer: The recursive formula for the Dirichlet inverse is just going to complicate matters. It's best to approach these things directly:
To show $f.g^{-1}$ is $(f.g)^{-1}$, you have to prove $ (f.g^{-1})*(f.g) = e$, where $e(1)=1$ and $e(n)=0$ for $n>1$. So let's calculate:
$$ ((f.g^{-1})*(f.g))(n) = \sum_{d|n} (f.g^{-1})(d).(f.g)(n/d)$$
$$=\sum_{d|n}f(d)g^{-1}(d)f(n/d)g(n/d).$$
Now use the fact that $f$ is completely multiplicative to collect the $f$ terms appearing inside the sum and factor them outside. Then use the fact that $g*g^{-1}=e$ to show the result is 0 for $n>1$ and for $n=1$ equal to $f(1)$. Now show $f(1)=1$ and you're done.
Comment: Yes, its true!!! Thank you!! i´m practicing for my Number theory test....
Comment: Understood.. but why you affirm that $(f \cdot g^{-1})(d) = f(d)\cdot g^{-1}(d)$
Comment: This is the definition, isn't it? $(f.g)(n) = f(n).g(n)$, with $.$ denoting ordinary multiplication, for any functions $f$, $g$.

Show that the equality is true


Iterating over a JSON object to add values to FormData in jquery

Question: I have a JSON object in jquery like this :-
userObj =
{
 "loginId":"abc123",
 "class":"5",
 "email":"firstname.lastname@example.com",
 "level":"1"
}

I have to send a POST request to the server with multipart/form-data. I have created a FormData object :-
var fd = new FormData();

What I need to do is to iterate over each element in the JSON and append them to my variable fd. This is what I want :-
fd.append('loginId','abc123');
fd.append('class',5);
fd.append('email','email@example.com');

Any idea how to achieve this?
Answer: You can iterate the object using for
for (var key in userObj) {
  fd.append(key, userObj[key]);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Comment: Thank you. I get the data on the server side. But the last element was a nested JSON element :-"userRole":{
  "role":"STU",
  "level":"1"
 }, which doesn't go through. UserRole is null on the server-side whereas it should have been {"role":"STU", "level":"1"}
Answer: You can do it like this:
let userObj = {
 "loginId":"abc123",
 "class":"5",
 "email":"firstname.lastname@example.com",
 "level":"1"
};

let fd = new FormData();

for (let key in userObj){
    fd.append(key, userObj[key])
}

Answer: var userObj = {
    "loginId": "abc123",
    "class": "5",
    "email": "email@example.com",
    "level": "1"
};
var keys = Object.keys(userObj);
var values = Object.values(userObj);
var fd = new FormData();
for (var i = 0; i < keys.length; i++) {
    fd.append(keys[i], values[i]);
}

Answer:

var userObj =
{
 "loginId":"abc123",
 "class":"5",
 "email":"email@example.com",
 "level":"1"
}
var fd = new FormData();
$.each(userObj, function(i, val) {
  console.log(i + " " + val);
  fd.append(i, val);
});

Try something like this.
Answer:

let userObj = {
 "loginId":"abc123",
 "class":"5",
 "email":"email@example.com",
 "level":"1"
};

var newdata= new FormData();

 $.each(userObj, function (key, value) {
    newdata.append(key, userObj[key]);
    console.log(key, userObj[key])
})


Get the value from module to template

Question: I want to pass the value from module to page tpl file in drupal.I have created a custom module 'one_time_popup'.I have created a sample soutput and tried to pass it and print in page.tpl.php after footer section.but doesn't shows any thing.What I did wrong.I'm a newbie
function one_time_popup_menu(){
$items['oneTimePopupData'] = array(
'title' => 'One time Popup',
'page callback' => 'one_time_popup_user_login',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
);
return $items;
}
function one_time_popup_user_login(&$edit, $account){
 ...
$output='value from one time popup module!';
return theme('photo_order',array('results' => $output));
}
function one_time_popup_theme() {
 return array(
'photo_order' => array(
  'template' => 'page',
  'variables' => array(
    'results' => NULL,
  ),
 ),
 );
}

Tpl file(page.tpl)
<?php echo $results; ?>

Answer: <?php
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items = array(
      'custom_menu_item' => array(
        'title' => 'Hello world',
        'page callback' => '_page_hello_world',
        'access callback' => TRUE,
      ),
    );
  return $items;
}

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme = array();
  $theme['mymodule_template'] = array(
    'template' => 'mymodule-template',
  );
  return $theme;
}

/**
 * Preprocessor function for 'mymodule_template'.
 */
function template_preprocess_mymodule_template(&$vars) {
  $vars['hello'] = 'hello!';
}

/**
 * Page callback.
 */
function _page_hello_world() {
  return theme('mymodule_template');

}

A $hello variable is available in your template at path /custom_menu_item
Comment: can you explain this

Get the value from module to template


How to show order total components in a block?

Question: I would like to create a block that shows the current user's order totals including all components, as follows:

<code> - Subtotal
 - Discount or coupon
 - Sales tax
 - Total
</code>

I would be happy with a block that simply renders the footer of the shopping cart view. I've played around with commerce-line-item-summary.tpl.php, but it only renders the number of items in the cart and the total amount. It doesn't have to be a form, just a summary of the shopping cart totals.
I would like to show this block during the checkout process in a sidebar region.
Any ideas how to create this?
Comment: Which e-commerce module are you using?
Comment: Commerce has a "Commerce Order: Order total" component that can be used in Views-  it does exactly what you're looking for
Comment: Drupal Commerce Kickstart
Comment: Thank you @Clive - that was exactly what I was looking for. Unbelievable how I completely overlooked that solution when it was right in front of me! :)
Comment: @Tinto I spent about half an hour looking for the same thing last week ;)
Answer: Quoting @Clive from the comments above:

Commerce has a "Commerce Order: Order total" component that can be used in Views- it does exactly what you're looking for.

Thank you!


Last known location and current location cannot be retrieved on some devices

Question: We have launched an Android app that utilizes GPS information and a minority of our users report that GPS is not working for them. Although we have invested a lot of time to improve the codebase we still have not been able to provide relevant improvements to the affected users. We are now looking for fresh ideas from the community to make a step forward and resolve this. Thanks for your feedback in advance!
Approach
In our Android app we are identifying the users location in three sequential steps:

Current GPS location (GPS_PROVIDER)
Current network location (NETWORK_PROVIDER)
Last known GPS location (GPS_PROVIDER)

If one step fails, the next step is attempted. If none of the steps succeed an GPS-errormessage is shown to the user.
Issues
A minority of users report they always receive the GPS-errormessage. Together with the users we have tried the following actions but without any success:

Ensuring that GPS is enabled on the device
Ensuring that GPS permissions are given to the app (fine grained location)
Closing the app, getting current location on Google Maps, then restarting the app

Code
This is the code that we have in place. The app calls GeoRepository.getCurrentLocation(..).
<code>public class GeoRepository {
private static final String TAG = GeoRepository.class.getSimpleName();

public GeoRepository() {
}

public class GeoNoPermissionException extends RuntimeException {
    public GeoNoPermissionException(String message, Throwable cause) {
        super(message, cause);
    }
}
public class GeoNoLocationException extends RuntimeException {
    public GeoNoLocationException(String message, Throwable cause) {
        super(message, cause);
    }
}

public interface GeoLocationListener {
    void onCompleted(Location location);
    void onFailed(RuntimeException ex);
}

public void getCurrentLocation(Context context, GeoLocationListener listener) {
    // The permissions for this is already being requested in the SplashActivity
    boolean hasPermission = !(ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        listener.onFailed(new GeoNoPermissionException("Missing permissions", null));
        return;
    }

    // try initially with precise GPS provider
    requestLocationOnce(context, LocationManager.GPS_PROVIDER, new GeoLocationListener() {
        @Override
        public void onCompleted(Location location) {
            listener.onCompleted(location);
        }

        @Override
        public void onFailed(RuntimeException ex) {
            Log.e(TAG, "Could not find location on first attempt", ex);
            requestLocationOnce(context, LocationManager.NETWORK_PROVIDER, new GeoLocationListener() {
                @Override
                public void onCompleted(Location location) {
                    listener.onCompleted(location);
                }

                @Override
                public void onFailed(RuntimeException ex) {
                    Log.e(TAG, "Could not find location on second attempt", ex);

                    Location location = null;
                    try {
                        location = requestLastKnownLocation(context, LocationManager.GPS_PROVIDER);
                    } catch(RuntimeException ex2) {
                        Log.e(TAG, "Could not find location on third attempt", ex2);
                        /* !!! this is where we hit the wall and return a GPS-errormessage to the user !!! */
                        listener.onFailed(ex);
                        return;
                    }
                    if(location == null) {
                        Log.e(TAG, "Could not find location on third attempt, location is null");
                        listener.onFailed(ex);
                        return;
                    }

                    listener.onCompleted(location);
                }
            });
        }
    });
}

private void requestLocationOnce(Context context, String provider, GeoLocationListener listener) {
    // The permissions for this is already being requested in the SplashActivity
    boolean hasPermission = !(ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        listener.onFailed(new GeoNoPermissionException("Missing permissions", null));
        return;
    }

    Object syncObj = new Object();
    CountDownLatch completedSignal = new CountDownLatch(1);

    LocationManager locationManager = (LocationManager) FlourishApp.getContext().getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // this method may never get called hence we need a watchdog later on
            // this happens for example if GPS permissions are there but GPS is turned off
            synchronized(syncObj) {
                if (completedSignal.getCount() > 0) {
                    completedSignal.countDown();
                    listener.onCompleted(location);
                }
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    locationManager.requestSingleUpdate(
            provider,
            locationListener,
            Looper.getMainLooper());

    new Handler(Looper.getMainLooper()).postDelayed(() -> {
        // cleanup event subscription
        locationManager.removeUpdates(locationListener);

        // watchdog to raise error if we don't get a callback within reasonable time
        boolean receivedLocationUpdate = true;
        synchronized (syncObj) {
            if (completedSignal.getCount() > 0) {
                completedSignal.countDown();
                receivedLocationUpdate = false;
            }
        }

        if(!receivedLocationUpdate) {
            GeoNoLocationException ex = new GeoNoLocationException("No location could be determined", null);
            listener.onFailed(ex);
        }
    }, Constants.LOCATION_MAX_WAIT); // LOCATION_MAX_WAIT = 50000
}

private Location requestLastKnownLocation(Context context, String provider) {
    // The permissions for this is already being requested in the SplashActivity
    boolean hasPermission = !(ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        throw new GeoNoPermissionException("Missing permissions", null);
    }

    LocationManager locationManager = (LocationManager) FlourishApp.getContext().getSystemService(Context.LOCATION_SERVICE);
    return locationManager.getLastKnownLocation(provider);
}

public interface GetCountryCodeByCurrentLocationListener {
    void onCompleted(String countryCode);
    void onFailed(RuntimeException ex);
}
}
</code>
Devices
The affected users have been using one of these devices:

Huawei P8
Oppo CPH1723
Galaxy Note4

Thoughts

Could it be that the users simply were offline which caused this issue? No this should have been ruled out by testing with Google Maps and by utilizing last-known-location as well.
Could it be that device settings are to be blame? No this has been ruled out by testing with Google Maps.
Could it be that app permissions are to be blame? No this has been clarified with the users.
Could it be that our code is bugy? Maybe but we cannot identify any obvious flaws.
Did you try some alternative providers? Yes we tried the newer Fused Location Provider API as well and the very same issues happened.

Any ideas? Thanks for your help!
Comment: Can you post the details of the GPS-errorMessage you are talking about?
Comment: Hey there, this is an error that we Display to the user. The point where this error is raised is shown in the code, please see the following comment in the code: /* !!! this is where we hit the wall and return a GPS-errormessage to the user !!! */
Answer: LastKnownLocation almost always fails.  It only works if the location service was previously turned on by another app (or your own) recently enough that the value was cached.  The phone doesn't actively track location at all times.  99% of the time when you call it, you will get null returned.  So if 1 and 2 failed, there is zero chance that 3 is going to work.
Answer: I don't know the exact reason for this. Kindly check for the below points too.

Are you following GPS request Guidelines for Android 8 See this link
Battery Saving Mode is Turned Off?
Is the target device updated with current google support library?

Also increase number of times you request for location update, in some devices i have experienced this since the first one or two times the location data is null.


Spring MVC 3.1: Trouble with url mapping

Question: I'm new to Spring MVC framework, having some trouble with basic URL mapping using two different controllers. I'm using @Controller and @RequestMapping.
The following results in 404 error for both /people and /accounts.
Here is my Spring MVC 3.1 setup:
index.jsp
<!DOCTYPE html>

    <title>t-diggity</title>

integration

    Contact List

    Account List

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     version="2.5">

<display-name>t-diggity</display-name>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

<servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/people/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/assets/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/accounts/*</url-pattern>
    </servlet-mapping>

</web-app>

controller # 1: PersonController.java
@Controller
@RequestMapping("/people/")
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/")
    public String listPeople(Map<String, Object> map)
    {
        map.put("person", new Person());
        map.put("peopleList", personService.listPeople());
        return "people";
    }

    @RequestMapping(value = "/addPerson", method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("person") Person person, BindingResult result
    {
        personService.addPerson(person);
        return "redirect:/people/";
    }

    @RequestMapping("/delete/{personId}")
    public String deletePerson(@PathVariable("personId") String personId)
    {
        personService.removePerson(personId);
        return "redirect:/people/";
    }
}

controller #2: AccountController.java
@Controller
@RequestMapping("/accounts")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/")
    public String listAccounts(Map<String, Object> map)
    {
        map.put("account", new Account());
        map.put("accountList", accountService.listAccounts());
        return "accounts";
    }

    @RequestMapping(value = "/addAccount", method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("account") Account account,
                            BindingResult result)
    {
        accountService.addAccount(account);
        return "redirect:/accounts/";
    }

    @RequestMapping("/delete/{accountId}")
    public String deleteAccount(@PathVariable("accountId") String accountId) {
        accountService.removeAccount(accountId);
        return "redirect:/accounts/";
    }

}

I am hoping my error is a minor one, I'm new to URL mapping so it likely is minor...  I'd appreciate any coaching, thanks in advance.
Answer: Change index.jsp to:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>

    <title>t-diggity</title>

integration

    <a href="<c:url value="/people/"/>">Contact List

    <a href="<c:url value="/accounts/"/>">Account List

The anchor URLs were not including the root context. The c:url tag will handle this for you.
Change the web.xml mapping to:
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

There is usually no need to map your controllers separately if everything in your web app is controlled by Spring MVC.
And map your @Controllers like this:
@Controller
@RequestMapping("/people")
public class PersonController {

    @RequestMapping("/")
    public String listPeople(Map<String, Object> map) {
        ...
        return "people";
    }

}

All I've done here is to lose the trailing / on the @RequestMapping for /people.


grub rescue prompt

Question: Had win7 and ubuntu installed on laptop and inadvertently selected the recovery option in boot menu - exited and now all I get is
error: no such partition
grub rescue>
set returns:
<code>prefix=(hd,0,msdos6)/boot/grub
root=hd0,msdos6
</code>
ls returns:
<code>(hd0) (hd0,msdos5) (hd,0,msdos3) (hd0,msdos2) (hd0,msdos1)
</code>
'normal' not available and I dearly love to not have to stick my oem recovery disc in any other info I can give please ask...
any help would be muchly appreciated.
Comment: By recovery, you probably mean your OS recovery partition, not Ubuntu, right?
Comment: well - I'm hoping everything is still there - hoping its just borked grub settings but if re_installing ubuntu is the solution then thats not such a massive bind
Comment: Hmm... what I'd do... at the Grub prompt, type "root=(hd0,xxx)", where "xxx" is the partition you want -- if you don't know it, just hit `Tab` twice after the comma and you'll get recommendations. Once you've set the root, you can `ls` to inspect the file system, and then set `linux=/boot/vmlinuz` or whatever it is, plus root parameters, and try booting (`boot`).
Comment: no optins on tabbing and get Unknown command 'boot'
Comment: This question has come up twice on SuperUser in the past two days alone: [one](http://superuser.com/questions/305322/) [two](http://superuser.com/questions/305830/)  Is it the fashion to delete one's Ubuntu partition, this week, or something? ☺
Answer: If you still have your Ubuntu (and hopefully it is the live disk), boot off that. Browse through the file systems on both your Windows and Linux partitions. If you can get to both, you're fine; you just need to reinstall grub.
Just remember a couple of things:

In linux, partition numbers start at 1 and disk starts with letters. With grub, they both are numbers and start from 0.
Worse, sometimes BIOS "lies" to grub about the device mapping. You will need to verify your mapping in device map file under /boot directory
Make sure to find out the location of your windows partition and boot loader. Fortunately, it probably still exists under /boot/grub, so you probably won't have to make any changes - just reinstallation.

Here are a couple of things that will help you out.
http://www.dedoimedo.com/computers/grub.html
http://www.howtogeek.com/howto/ubuntu/reinstall-ubuntu-grub-bootloader-after-windows-wipes-it-out/
Comment: stuck the live disk in - ubuntu partition had been completely wiped out by the windows recovery effort (even though I exited without doing anything!) just free space remained to format an install on. Did that and I assume grub was fixed as linux was now 'back' although will concede it prob re-installed grub too
Comment: Ouch. I didn't realize that the recovery actually wiped out the Ubuntu partition (although having it not touch the windows partition seems odd).

grub rescue prompt


Transformations of Random Variables Question

Question: I've been given the following problem:
If a random variable $X$ has probability density function $f_X (x)$ and cumulative distribution function $F_X (x)$, prove that $U = F_X (x) \sim$ uniform$(0,1)$
Ordinarily to solve a problem like this, I'd use the following method:

$F_U (u) = Pr(U\leq u) = Pr(g(X) \leq u) = Pr(x \leq g^{-1} (u)) = F_X (g^{-1} (u))$

And then differentiate w.r.t $u$ to get $f_U (u)$. However in this case, I am not sure whether I can find $g^{-1}$ because $F_X (x)$ doesn't seem to necessarily be 1-to-1 even over the range of values $X$ can take. (I can see that $F_X (x)$ is increasing but not necessarily strictly increasing)
How should I choose $g^{-1}$ in this case? Or is there a better method to solve this specific problem?
Answer: You don't need $\ F_X\ $ to be strictly increasing for the result to hold, but you do need it to be continuous, which it will be if it has a density function.  If $\ F_X\ $is continuous, then $\ P\big(F_X(X)\le y\big)=P\big(F_X(X)<y\big)\  $, because $\ \big\{x\ \big|\ F_X(x)=y\big\}=[a, b]\ $ for some $\ a,b\ $ with $\ b\ge a\ $, and $\ P\big(F_X(X)=y\big)=$$P(a\le X\le b)=$$F_X(b)-F_X(a)=$$0\ $.  But $\ F_X(X)<y\Leftrightarrow X\in F_X^{-1}\big([0, y)\big)\ $, and $\ F_X^{-1}\big([0, y)\big)\ $ is an interval of the form $\ (-\infty,a)\ $ where $\ F_X(a)=y\ $.  Putting all this together, we have
\begin{align}
P(U\le y)&=P\big(F_X(X)\le y\big)\\
&=P\big(X\in (-\infty, a)\big)\\
&=F_X(a)\\
&=y\ .
\end{align}


Will a more expensive electric guitar be more consistently harmonious?

Question: I'm learning on a Fender Squier Mini.
I'm still not at all clear on what you're paying for when you buy a more expensive guitar.
But I notice some chords that sound pretty dissonant seemingly by virtue of some strange physical resonance with other strings. And I wonder if maybe fancier guitars come with strings and bodies manufactured with lower error tolerance and that that maybe makes chords sound more "normal" like they do on say a Steinway D?
Answer: First of all, mini guitars are notorious for bad intonation.
The most important step to obtaining a 'harmonious' guitar (ie one that plays in tune all over the neck) is a good setup.
Theses are the main factors that affect how 'good' a guitar sounds (tone aside):
Nut height- nut slots that are too high will cause the first few frets to sound sharp as the strings are further from the frets they require more force which increases tension and sharpens notes. Nut slots that are too low will produce fret buzz when open strings are played.
Intonation- Each string must have the correct length to play in tune up the neck. As each string is a different thickness each individual string will require a different adjustment to achieve this correction.
Action- Effect is similar to nut height but applies to the entire neck, high action will require more fretting force which increases tension and sharpens notes. Low action will produce fret buzz.
Neck relief- The forward bow of the neck which allows for the greater amplitude of the vibrating string at it's mid point. Affects all other areas.
All of these things are interrelated and compromises must be made eg lower action will improve intonation but will increase fret buzz and decrease sustain.
There are myriad other factors but those are the most important.
A more expensive guitar does not necessarily have a better setup, Gibson are well known for having poor setups on $5k guitars. Most guitars in stores have not been set up at all bar minor adjustments at the factory.
Your best bet is to chose a guitar you like the look and tone of and take it to a reputed luthier and get it setup for your intended purpose, a good luthier will know how to set it up best for you based on your style and technique.


How can I deploy with Terraform cdktf via python script?

Question: I'm already using cdktf for python to make my provider & resources configuration, I can also deploy via cdktf cli tool with cdkft deploy and it works well, but i need to make an deploy or detroy via python script python deploy.py, how can I achive this?
# main.py

from constructs import Construct
from cdktf import App, TerraformStack
from imports.proxmox.provider import ProxmoxProvider
from imports.proxmox.lxc import Lxc
from imports.proxmox.vm_qemu import VmQemu

class MyStack(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        ProxmoxProvider( self, id="proxmox",
            ...
        )

        Lxc(self, id_="test",
            ...
        )

app = App()
MyStack(app, "terraform_test")
app.synth()

The only option I can think is to execute the commands via os module like this:
# deploy.py
import os
os.system('cdktf deploy')

But I don't know if it's the best approach
Answer: The only option I can think is to execute the commands via os module like this:

This is currently the best approach. There is this idea of exposing the API commands in a package that can be consumed across languages, but it's unclear if we are going to proceed with this idea anytime soon or not.


declaring multiple objects in one property

Question: I've noticed that many people are declaring multiple properties separately in models. Like this, for example:
<code>@property ( strong , nonatomic ) NSMutableString *name;
@property ( strong , nonatomic ) NSMutableString *surname;
@property ( strong , nonatomic ) NSMutableString *fatherName;
</code>
I understand in case of ViewControllers we define them separately because every outlet is connected to its own object. For example:
<code>@property ( weak , nonatomic ) IBOutlet UIView *view;
@property ( weak , nonatomic ) IBOutlet UIImageView *imageView;
@property ( weak , nonatomic ) IBOutlet UITextfield *textfield;
</code>
I'm wondering why everybody defines them separately. It might be because of memory management, where you'd want to declare some properties as weak and some as strong. Still, even when that isn't the case, I've never seen a single person declare properties like this:
<code>@property ( strong , nonatomic ) NSMutableString *name , *surname , *fatherName ;
</code>
What is the reasoning behind this? I've tested the both examples I gave and they work fine. Is there something I'm missing or not understanding?
Comment: Does this answer your question? [Multiple property declarations in the same line in Objective-C](https://stackoverflow.com/questions/23034691/multiple-property-declarations-in-the-same-line-in-objective-c)
Answer: The syntax to declare multiple (non-outlet) properties of the same type in one line is perfectly fine. The functionality is exactly the same as the standard way to declare one property per line.


Is there any difference between Integer and Int32 in VB.NET?

Question: In VB.NET, is there any difference between Integer and Int32?
If yes, please explain.
Comment: OK, Int32 and Integer are different. Which would you recommend using in projects where there is no pre-existing standard - and why? Presumably this thought was behind @Vikram's question.
Comment: @MitchWheat...Google gave me confusing answers for this. So, thought of asking over here. I know how to search.
Answer: Functionally, there is no difference between the types Integer and System.Int32. In VB.NET Integer is just an alias for the System.Int32 type.
The identifiers Int32 and Integer are not completely equal though.  Integer is always an alias for System.Int32 and is understood by the compiler. Int32 though is not special cased in the compiler and goes through normal name resolution like any other type. So it's possible for Int32 to bind to a different type in certain cases.  This is very rare though; no one should be defining their own Int32 type.
Here is a concrete repro which demonstrates the difference.
Class Int32

End Class

Module Module1
    Sub Main()
        Dim local1 As Integer = Nothing
        Dim local2 As Int32 = Nothing
        local1 = local2 ' Error!!!
    End Sub
End Module

In this case local1 and local2 are actually different types, because Int32 binds to the user defined type over System.Int32.
Comment: @JaredPar, Thanks for explanation and thanks a lot for not putting some comment like "your google broken?" or something. :)
Comment: @MitchWheat i googled the question and didn't find a suitable explanation. Most links just say "no difference" which is incorrect.  There is one answer on the msdn website which had a decent explanation but it was fairly far down in my google results
Comment: @Mitch that's the post I originally saw when I Googled. SO prevails.
Comment: There is no difference. Your answer states "Fuctionally there is no difference between the types"
Comment: @MitchWheat I used to work on the .Net compiler team. I've seen this bug pop up several times (in both C# and VB.Net). As I said, people run into this in generated code or in certain nested type situations.  It's not a fictional issue
Comment: @MitchWheat it's a contrived example to concretely demonstrate the problem. As I said, the most common way this comes up is in generated code.
Comment: I agree with JaredPar. That was the same reason I asked the question over here. I always believe that SO is the platform I can trust...of course, one has to face some rude comments! But, I ignore for gaining knowledge.
Comment: @MitchWheat there is a difference in how the compiler interprets the names.  This is an often overlooked difference and can bite people (especially in generated code).  You see the same effect in C# with `int` and `Int32`
Comment: When was the last time you saw Int32 not equal to System.Int32?
Comment: That's cool. Glad I stuck around to see this answer. I'm surprised you can do that without brackets i.e. `Class [Int32]`. Thanks
Comment: @DanVerdolino that's very much related.  `Int32` isn't a keyword in Vb.Net although many believe it to be.  It's just another name that's interpreted like anything else
Comment: @Jared: you might want to have a word with one of your colleagues! : http://social.msdn.microsoft.com/forums/en-US/vblanguage/thread/2912adc7-6d11-4d2d-aa8b-60ddf7c3a3e5
Comment: @MitchWheat yes that answer is incorrect. Those forums are apparently closed and I cannot offer another answer. I will sent Matt an email.
Comment: Bit of a contrived example. If people are defining there own Int32 they reap what they sow.
Comment: So if the question was "Is there a difference between `Integer` and `System.Int32`, then the answer would be no. Generated code *should* specify the namespace to prevent this problem from ever happening.


Random Playing Card Generator with vanilla javascript

Question: I have Five Cards for the Player and Five Cards for the Dealer
Which on click or touch it generates random card from the playing card deck.
I currently have Five different functions for a same function for each card because I have trouble making the functions into a Class that can be shared among all the cards.
This is the sample code for the function that is repeated for all the cards.
Please help me simplify my coding into One Class That can be shared for all the cards.
'''
function drawCard5() {

  var randomCard = Math.round(Math.random()* 52);
  if (randomCard === 0) {
    document.getElementById("card5").innerHTML = "A ♠";
  }

  else if (randomCard === 1) {
    document.getElementById("card5").innerHTML = "2 ♠";
  }

  else if (randomCard === 2) {
    document.getElementById("card5").innerHTML = "3 ♠";
  }

  else if (randomCard === 3) {
    document.getElementById("card5").innerHTML = "4 ♠";
  }

  else if (randomCard === 4) {
    document.getElementById("card5").innerHTML = "5 ♠";
  }

  else if (randomCard === 5) {
    document.getElementById("card5").innerHTML = "6 ♠";
  }

  else if (randomCard === 6) {
    document.getElementById("card5").innerHTML = "7 ♠";
  }

  else if (randomCard === 7) {
    document.getElementById("card5").innerHTML = "8 ♠";
  }

  else if (randomCard === 8) {
    document.getElementById("card5").innerHTML = "9 ♠";
  }

  else if (randomCard === 9) {
    document.getElementById("card5").innerHTML = "10 ♠";
  }

  else if (randomCard === 10) {
    document.getElementById("card5").innerHTML = "J ♠";
  }

  else if (randomCard === 11) {
    document.getElementById("card5").innerHTML = "Q ♠";
  }

  else if (randomCard === 12) {
    document.getElementById("card5").innerHTML = "K ♠";
  }

  else if (randomCard === 13) {
    document.getElementById("card5").innerHTML = "A ♥";
  }

  else if (randomCard === 14) {
    document.getElementById("card5").innerHTML = "2 ♥";
  }

  else if (randomCard === 15) {
    document.getElementById("card5").innerHTML = "3 ♥";
  }

  else if (randomCard === 16) {
    document.getElementById("card5").innerHTML = "4 ♥";
  }

  else if (randomCard === 17) {
    document.getElementById("card5").innerHTML = "5 ♥";
  }

  else if (randomCard === 18) {
    document.getElementById("card5").innerHTML = "6 ♥";
  }

  else if (randomCard === 19) {
    document.getElementById("card5").innerHTML = "7 ♥";
  }

  else if (randomCard === 20) {
    document.getElementById("card5").innerHTML = "8 ♥";
  }

  else if (randomCard === 21) {
    document.getElementById("card5").innerHTML = "9 ♥";
  }

  else if (randomCard === 22) {
    document.getElementById("card5").innerHTML = "10 ♥";
  }

  else if (randomCard === 23) {
    document.getElementById("card5").innerHTML = "J ♥";
  }

  else if (randomCard === 24) {
    document.getElementById("card5").innerHTML = "Q ♥";
  }

  else if (randomCard === 25) {
    document.getElementById("card5").innerHTML = "K ♥";
  }

  else if (randomCard === 26) {
    document.getElementById("card5").innerHTML = "A ♣";
  }

  else if (randomCard === 27) {
    document.getElementById("card5").innerHTML = "2 ♣";
  }

  else if (randomCard === 28) {
    document.getElementById("card5").innerHTML = "3 ♣";
  }

  else if (randomCard === 29) {
    document.getElementById("card5").innerHTML = "4 ♣";
  }

  else if (randomCard === 30) {
    document.getElementById("card5").innerHTML = "5 ♣";
  }

  else if (randomCard === 31) {
    document.getElementById("card5").innerHTML = "6 ♣";
  }

  else if (randomCard === 32) {
    document.getElementById("card5").innerHTML = "7 ♣";
  }

  else if (randomCard === 33) {
    document.getElementById("card5").innerHTML = "8 ♣";
  }

  else if (randomCard === 34) {
    document.getElementById("card5").innerHTML = "9 ♣";
  }

  else if (randomCard === 35) {
    document.getElementById("card5").innerHTML = "10 ♣";
  }

  else if (randomCard === 36) {
    document.getElementById("card5").innerHTML = "J ♣";
  }

  else if (randomCard === 37) {
    document.getElementById("card5").innerHTML = "Q ♣";
  }

  else if (randomCard === 38) {
    document.getElementById("card5").innerHTML = "K ♣";
  }

  else if (randomCard === 39) {
    document.getElementById("card5").innerHTML = "A ♦";
  }
  else if (randomCard === 40) {
    document.getElementById("card5").innerHTML = "2 ♦";
  }

  else if (randomCard === 41) {
    document.getElementById("card5").innerHTML = "3 ♦";
  }
  else if (randomCard === 42) {
    document.getElementById("card5").innerHTML = "4 ♦";
  }
  else if (randomCard === 43) {
    document.getElementById("card5").innerHTML = "5 ♦";
  }

  else if (randomCard === 44) {
    document.getElementById("card5").innerHTML = "6 ♦";
  }
  else if (randomCard === 45) {
    document.getElementById("card5").innerHTML = "7 ♦";
  }
  else if (randomCard === 46) {
    document.getElementById("card5").innerHTML = "8 ♦";
  }
  else if (randomCard === 47) {
    document.getElementById("card5").innerHTML = "9 ♦";
  }
  else if (randomCard === 48) {
    document.getElementById("card5").innerHTML = "10 ♦";
  }
  else if (randomCard === 49) {
    document.getElementById("card5").innerHTML = "J ♦";
  }
  else if (randomCard === 50) {
    document.getElementById("card5").innerHTML = "Q ♦";
  }
  else if (randomCard === 51) {
    document.getElementById("card5").innerHTML = "K ♦";
  }
  else if (randomCard === 52) {
    document.getElementById("card5").innerHTML = "JK ";
    audio2.play();
    audio3.play();
    document.getElementById("playercard").innerHTML = "Player Wins!"
    document.addEventListener("click", handler, true);
    restartGame();
  }
}

Comment: When you copy and paste the same code over and over again, you need to say o yourself.... is there a better way to do this.
Comment: Yes Please suggest a better way to do this. Especially if there is a way to do it with using classes.
Comment: https://stackoverflow.com/questions/66199167/javascript-blackjack-multiple-deck-creation-shuffling
Comment: Thanks for the reply I will take a careful look
Answer: You can create list of card first. And then get the card by index of the list.

const createCardList = () => {
    let cardList = []
    let suits = "♠♥♣♦"
    let number = "A123456789JQK"

    for (let i=0; i<suits.length; i++) {
        for (let j=0; j<number.length; j++) {
            let card = ""
            card += suits[i] + " " + number[j]
            cardList.push(card)
        }
    }
    return cardList
}

const getCard = () => {
    let cardList = createCardList()
    let random = Math.round(Math.random() * 52);

    return cardList[random]
}

console.log(getCard())


How to know when to play what note on what string on the violin?

Question: I'm teaching myself to play the violin and only just starting on the notes and how to read the music, but I am getting a little stuck on knowing what note to play on what string from reading the sheet music?
Example: how to know to play the D note on the D string or the D note on the A string?
From what I'm gathering the sheet music will tell you what finger you'll be playing and therefore with no notes repeating on the one finger, you will know what note to play on what string?
But I have seen sheet music with no numbers in reference to 1st, 2nd finger etc. so that's confusing me.
I just want confirmation if I'm close or if I'm totally off.
Comment: Surely the string instruments as violin are among those, where a teacher is essential. There is so much to get wrong (concerning posture) and it is horrendous effort to unlearn that later.
Comment: Are you experimenting with positions or are you speaking of 1st position? In 1st position there is nor ambiguity. The D on the G string is not the same pitch as the D on the A string. So in this case the answer is: google for a fingering chart. The only ambiguity is 4th or empty string in 1st position.
Answer: The answer is: don't.  Please don't.  If you fail to take lessons from a qualified teacher, even if you do manage to place your fingers in the correct locations,  you are at grave risk of developing incorrect mechanics (fingers, wrists, elbows) which will be very difficult to fix later on, not to mention risking tendinitis or other injury.
The choice of which string to use for a given pitch depends on the tone you wish to produce, the feasibility of reaching the desired finger position from the previous and following notes, etc.  Again, without a teacher available you risk learning bad fingering patterns.
Answer: Basically, when you read a book of starting level, it would usually show you the fingerings, so you will know which string to play the note. It is not uncommon to include the name of the string as well.
After you've played quite a few novice exercises, you'll have figured out on which string to play what note, according to the passage. There are some exercises/songs that might require the D note to be played on the G string because the next notes are close by, or similarly to have the D note played on the A string.
If there are no fingerings and you still don't know which string to use, just try out the possibilities. Play the note on both strings and see which one fits better for that exercise. This is also a good way to learn your way around the violin (see where the notes are on different strings).
Answer: Look at the treble clef staff. There are two D notes: one at the more top of the staff, on the 4th line, and a lower D, which hangs from the first line. These notes have the same name(D), but they are different octaves/pitches. The first I mentioned is higher than the other. This is how to tell whether you should play D on the D string (hanging from first line) or on the A string (note on the fourth line).
If you can, you should try to find a private teacher to help you develop your skills and answer your questions more in-depth. Having a teacher really helps a lot, and can help to correct any bad habits you might make along your way.
Comment: Thank you Andy! I've edited my answer.
Answer: I believe that this question is not about what fingering is best for a certain exact pitch; I believe the OP is confused about the difference between "D" in different octaves. Meredith's answer addresses this best. One detail that isn't addressed yet:
If you're reading traditional staff notation, then it's clear which exact pitch is intended. This note:  is D5, with a frequency of 587.33 Hz; meanwhile this one :  is D4, 293.66 Hz.
But if you're reading from a page that just contains the letter D, then you don't have this information. This often comes up if you're reading from chord notation. For example, you could see this:
These "G, C, G" letters aren't really intended for a melodic instrument. They're intended for a chordal instrument like a guitar or piano, and when they see "G" they'll actually play a combination of G, B, and D; and there's no saying which octave each note will be in; they get to pick. If you're reading from a chord chart like this on a melodic instrument, you can pick as well. Later you can be more adventurous, but playing the letter that's printed is not a bad way to start.
But sometimes, especially for beginners, letter notation is used for a melody:

In this example, it does matter which octave you play each note in. As you go from C to G at the beginning, the tune goes up, not down to a lower G. Here's the important part: this notation doesn't tell you that. The only way you're supposed to know is either that you already know the tune by ear, or perhaps you're playing on an instrument that can only play very few notes (like an ocarina), or you have only been taught a small subset of notes so far. If you're not in this situation, then you can either choose which octave you want—or better yet, throw that notation away and find something more clear (like learning staff notation). If you change the octave of pitches in a tune willy-nilly, it's no longer the same tune.
Finally, there is a notation that uses letter names and specifies which octave to play; that's "ABC notation". In this case, the octave is indicated by Helholtz notation, using upper-case or lower-case letters and tick marks.
Answer: Certainly at beginner level, you play the note, which may have two alternative places, at the place closest to where the previous and next notes will be. That makes sense, as  being a beginner, you won't want to move far from where you know is safe. It's bad enough fingering exactly the right pitch with a finger, given that another finger is anchored already, so moving as little as possible - be that up, down or to another string, seems to be the best option.
Later, you'll want to experiment moving further, but keep it safe for now!
Answer: I have noticed that if there is a descending chord progression it can be easier to take the notes higher up on the neck. Either based on "fret 7" on the string below or "fret 14" two strings below. In case the question was about choosing which unison D to play.
Comment: Welcome! I think the original poster's question was more basic: when told to "play a D," they weren't sure which octave to play. And of course violins don't have frets and beginners don't really play chords, but maybe that's why you put them in quote marks.
Comment: Yes, I mean P5 or "tone near 700c relative to open string" with "fret 7". The only times I have seen fingerings is in very tricky pieces which you might look at and dream of playing fluently. I have always assumed the fingerings were "position-agnostic", but maybe I am wrong.


Weak convergence in $W^{2, p}_{loc}(R^{N})$

Question: If $(u_{n})$ is a sequance in $W^{2, p}_{loc}(R^{N})$ ($1< p < \infty$) such that $u_{n}(x)=0$ if $|x|\geqslant n$, $u_{n} = u_{n+1}$ in $B(0,n)$, $u_{n}\in C_{0}^{2}(B(0,n))$ and $\|u_{n}\|_{W^{2, p}(B(0,m))}\leqslant K(m)$, where $K$ is a constant dependent on $m$. Can we say that $(u_{n})$ has a subsequence $(u_{n_{k}})$ converging weakly to some $u\in W^{2, p}_{loc}(R^{N})$?
What I understand is that if $Q_{1}$ and $Q_{2}$ are two unequal compact subsets of $R^{N}$ then there will be two sequnce $(n_{k})$ and $(m_{k})$ such that $u_{n_{k}}$ converges weakly to some $u_{1}\in W^{2, p}(Q_{1})$ and $u_{m_{k}}$ converges weakly to some $u_{2}\in W^{2, p}(Q_{2})$. And by the conditions, I understand that we can take a common function $u\in W^{2, p}(Q_{1})\cap W^{2, p}(Q_{2})$ and a common sequence $n_{k}$ such that $u_{n_{k}}$ converges weakly to $u$ in $W^{2, p}(Q_{1})$ and in $W^{2, p}(Q_{2})$. But, I don't understand how to get a common function $u$ and a common subsequence $(u_{n_{k}})$ in $W^{2, p}_{loc}(R^{N})$.
The above question came to mind when I was reading about the existence of a viscosity solution of a Hamilton-Jacobi equation with the Dirichlet condition from the book- Generalized Solutions of Hamilton-Jacobi Equations by P.L. Lions (page 99). And I don't even know if my question is right or wrong.
Answer: You start from $B(0,1)$ and find a subsequence that converges weakly to some $v_1$ in $W^{2,p}(0,1)$. Then you take that subsequence and consider $B(0,2)$ and find a sub sub sequence that converges weakly to some $v_2$ in $W^{2,p}(B(0,2))$. As you said, $v_1=v_2$ in $B(0,1)$. Inductively, assume that you selected a sub sub sub sub… sequence that converges weakly in $W^{2,p}(0,m)$ to some function $v_m$ and find a further subsequence that converges weakly to some $v_{m+1}$ in $W^{2,p}(0,m+1)$. As before, $v_{m+1}=v_m$ in $B(0,m)$.
Given $x$, find $m$ such that $|x|<m$ and define $u(x)=v_m(x)$. Now you have to use a Cantor diagonal argument similar to the one in the proof of Ascoli Arzela theorem.


Retirar data de EditText e somar cinco anos

Question: Gostaria de fazer uma captação de uma data com um EditText, e a partir dela criar uma outra data somando mais 5 anos.  Como poderia fazer isso?
Comment: O seu texto está confuso, mas acho que você quer pegar o texto de um `EditText`, converter ele em uma data e somar 5 anos a isso. Entendi corretamente?
Comment: Olá amigo, é exatamente isso! Obrigado!
Comment: Neste caso, a minha resposta abaixo deve te servir, né?
Answer: Usando Date, GregorianCalendar e SimpleDateFormat:
EditText seuEdit = ...;
String texto = seuEdit.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse(texto);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(Calendar.YEAR, 5);
String daquiHaCincoAnos = sdf.format(gc.getTime());

Usando LocalDate e DateTimeFormatter:
EditText seuEdit = ...;
String texto = seuEdit.getText().toString();
DateTimeFormatter fmt = DateTimeFormatter
    .ofPattern("dd/MM/uuuu")
    .withResolverStyle(ResolverStyle.STRICT);
LocalDate ld1 = LocalDate.parse(texto, fmt);
LocalDate ld2 = ld1.plusYears(5);
String daquiHaCincoAnos = ld2.format(fmt);

Comment: Olá amigo, muito obrigado! funcionou perfeitamente
Comment: É possível utilizar essas ferramentas utilizando somente o mês e o Ano?
Comment: SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Comment: @FelipeSzulcsewski Nesse caso, você iria querer construir uma data sem dia, o que não funciona. Você precisa apenas do mês e do ano?


Distributional Fourier Transform of $f(x)=\frac{e^{ix\cdot \xi_0}}{\vert x-x_0\vert}$ where $x\in\mathbb R^2$ and $\xi_0,x_0\in\mathbb R^2$ fixed

Question: Problem: Find the Fourier transform of $f:\mathbb R^2\to\mathbb C$ given by
$$f(x)=\frac{e^{ix\cdot \xi_0}}{\vert x-x_0\vert}\quad\text{where }\xi_0,x_0\in\mathbb R^2\text{ are fixed.}$$
My Attempt: Note that $f\notin L^1(\mathbb R^2)$ and also $f\notin L^2(\mathbb R^2)$. Therefore, we compute the Fourier transform of $f$ in the distributional sense since $f\in L^1_{\operatorname{loc}}(\mathbb R^2)$. Let $\psi\in\mathcal C_c^\infty(\mathbb R^2)$. Then
\begin{align*}
\widehat{f}(\psi)&=f(\widehat{\psi})=\int_{\mathbb R^2}f(x)\widehat\psi(x)\,dx\\
&=\frac{1}{2\pi}\int_{\mathbb R^2}\frac{e^{ix\cdot \xi_0}}{\vert x-x_0\vert}\int_{\mathbb R^2}\psi(\xi)e^{-ix\cdot\xi}\,d\xi\,\,dx\\
&=\frac{1}{2\pi}\int_{\mathbb R^2}\psi(\xi)\int_{\mathbb R^2}\frac{e^{ix\cdot(\xi_0-\xi)}}{\vert x-x_0\vert}\,dx\,d\xi.
\end{align*}
Therefore, it suffices to evaluate the integral
$$I=\frac{1}{2\pi}\int_{\mathbb R^2}\frac{e^{ix\cdot(\xi_0-\xi)}}{\vert x-x_0\vert}\,dx.$$
The one thing that is confusing me about the problem is the multidimensionality, if on the other hand we were in $\mathbb R$, then some manipulations with the Heaviside function and the delta distribution would most likely do the trick. Also, the integral above is not absolutely convergent and the integrand is not nonnegative, whence we cannot even apply polar coordinates, as stated in Folland's book.

Therefore, my question is: how does one deal with the integral above, or is there a different and more efficient way to go about this problem?
Thank you for your time and appreciate any feedback.
Answer: Here's an evaluation that should provide some hints as to what the correct answer is.
Consider the Fourier integral
$$F_{\epsilon}(\xi)=\int_{\mathbb{R}^2}d^2x~\frac{e^{-i(\xi-\xi_0)x}}{|x-x_0|}e^{-\epsilon |x-x_0|}$$
where $\epsilon$ is a positive number (can be readily generalized to a complex number with $\text{Re}( \epsilon)>0$). This regulated Fourier transform does converge absolutely, in  contrast to it's unregulated counterpart. This allows for an easy evaluation of the integral as follows. It suffices to consider the simpler integral
$$I(p)=\int_{\mathbb{R}^2}d^2x~\frac{e^{-ipx}}{|x|}e^{-\epsilon |x|}$$
since of course
$$F_{\epsilon}(\xi)=e^{-i(\xi-\xi_0)x_0}I(\xi-\xi_0)$$
One can evaluate $I$ in spherical coordinates in various ways. Here's one of them
$$I(p)=\int_{0}^{2\pi}d\theta\int_{0}^{\infty}dr~e^{-\epsilon r-i|p|r\cos\theta}=\int_{0}^{2\pi}\frac{1}{\epsilon+i|p|\cos\theta}d\theta=\frac{2\pi}{\sqrt{|p|^2+\epsilon^2}}$$
where the last integral can be easily performed with a standard contour integration trick. It would appear that one can easily take the limit $\epsilon\to 0^+$ to get that the requested FT is given by
$$\hat{f}(\xi)=\frac{e^{-i(\xi-\xi_0)x_0}}{|\xi-\xi_0|}$$
and that the limit is quite regular, despite the fact that actually if it wasn't for the cutoff parameter we wouldn't have been able to evaluate the double integral in the order we did. One may worry that this procedure is misleading, since the integral diverges if evaluated with $\epsilon=0$ directly step by step as above. However it turns out that the cutoff and distributional considerations are not needed if the right order of integration is employed since
$$I_0(p)=\int_{0}^{\infty}dr\int_{0}^{2\pi}d\theta~e^{-i|p|r\cos\theta}=2\pi\int_0^{\infty}J_0(|p|r)dr=\frac{2\pi}{|p|}$$
where the last step can be derived from the Laplace transform of a Bessel function
$$\int_{0}^{\infty}J_0(px)e^{-sx}dx=\frac{1}{\sqrt{p^2+s^2}}$$
In summary, this integral exists and is well defined but poses computational difficulties due to the lack of absolute covergence, which also precludes the free use of Fubini's theorem. If the integral exists, evaluating with a regulator is enough to calculate it's value if it makes the evaluation easier, but eventually one has to prove its existence somehow. In this example there is a way to do that without resorting to distributional results. Let us note, however, that this integral can also be shown to have the value above by using the following distributional identity(calculation is left to the reader)
$$\int_{0}^{\infty}dx~e^{-ipx\cos\theta}=\pi\delta(|p|\cos\theta)-i ~PV\left(\frac{1}{p\cos\theta}\right)$$


Find IP address from a MAC address

Question: Is there anyway to find the IP address of a MAC address using a command? I was thinking something like arping might work but can't seem to find much information on it.
Answer: Could be a few ways. If on a DHCP server and the client in question is getting an address, the mac will be listed in the lease information in the DHCP console or database.
If the client is attached to a Cisco switch, you could check the sh arp output on the switch and see if the mac is listed.
6509-Access-1#sh arp
Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  192.168.1.105           0   0017.59ae.fd42  ARPA   GigabitEthernet1/2
Internet  192.168.1.106           -   001d.e6e4.2400  ARPA   GigabitEthernet1/2
Internet  192.168.1.97            1   0022.0dce.e442  ARPA   GigabitEthernet1/1
Internet  192.168.1.98            -   001d.e6e4.2400  ARPA   GigabitEthernet1/1

Answer: If the NIC owning the MAC is on the same network: Yes.
ArpPing will work.
Listing the arp cache (on windows via arp -a) might also work, but only if your PC has communicated with the other NIC in the last minute. It has the advantage that you do not need to install extra software.
If the PC is not only the local network it gets a lot trickier. You might need to log into  switches. What you can do and which commands you need for that differ per device.

Find IP address from a MAC address


hibernate mapping of 2 column table

Question: I have a table with 2 varchar columns key,value used to store config for an application. (key column is aso the primary key) Is there any other way to use it in hibernate than native sql queries? Can one do any object mapping that would expose this values?
thanks
Answer: Sure. Create class ConfigurationItem with two properties: String key, String value. Map them to the appropriate fields with the key mapped as the id column. Then to load them just session.createQuery("from ConfigurationItem").list()

hibernate mapping of 2 column table