merge row values in two consecutive rows using pandas

Question: i am using pandas and have a data frame where I would like to merge two of the rows together and append the values in each cell separated by a symbol. The cells contain text or integers.
The original data frame looks like this
index         1         2          3
0           2010      2011       2012
1           First     Second     Third
2            98%        99%        99%
3            77%        87%        77%

I would like to achieve this :
index         1                 2                   3
    0    2010 | First      2011 | Second       2012 | Third
    2        98%               99%                 99%
    3        77%               87%                 77%

What's the best way to achieve this?
Answer: Let's try this:
df.loc[0] = df[:2].apply(lambda x: ' | '.join(x.astype(str)))
df = df.drop(1).reset_index()
df

Output:
   index             1              2             3
0      0  2010 | First  2011 | Second  2012 | Third
1      2           98%            99%           99%
2      3           77%            87%           77%

Comment: `df.drop([0, 1]).append(df.loc[[0, 1]].apply(' | '.join).rename(0)).sort_index()`... w/e  I like yours better.  `b.drop([0, 1]).append(b.loc[[0, 1]].astype(str).apply(' | '.join).rename(0)).sort_index()` Just in case, years are ints.
Comment: @piRSquared That is a lot more pythonic and elegant.   Thank you.
Comment: Thank you very much for this solution. It's just what I need.
Answer: Or maybe you can try this by using T
df=df.T
df[0]=df[0].astype(str)+'|'+df[1]
df.drop(1,1).T

                1            2           3
index
0      2010|First  2011|Second  2012|Third
2             98%          99%         99%
3             77%          87%         77%


Using Webclient on Windows Ce;

Question: im trying to develop an app for a win CE mobile device that downloads an exe file from an ftp server,and the problem is,i cant seem to reach webclient class and i am using system.net library...Any ideas?
Answer: The class simply doesn't seem to be supported.  See: MSDN documentation. If you need to use FTP, you could try using the FTP class linked here.
Answer: Confusingly, the WebClient class is a member of the System assembly, not System.Net
Source: http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.90).aspx
Comment: `Confusing is subjective` That's true. It makes perfect sense to not include webclient in `System.Web` - Otherwise it would not be available on the Client Profile.

Using Webclient on Windows Ce;


Printing date with custom format

Question: I want to print "event_info_date" Date (Unix timestamp) field with custom format in node.tpl.php.
I'm using this code:
<?php print date("Y/m/d h:i:s", $node->event_info_date['und'][0]['value']); ?>

And it prints: 1970/01/01 01:00:00, but it isn't value from my field.
I've also tried this:
<?php print format_date($node->event_info_date['und'][0]['value'], 'custom', 'Y/m/d h:i:s'); ?>

But it doesn't print anything. Any ideas?
Comment: So, based on what I see here, it's not the date() function, but the value in the second argument. It must not be returning a valid date because it's printing essentially the first date. Any more code to assist? Are you doing this in a hook? Also, pedantically, I recommend LANGUAGE_NONE rather than 'und'
Answer: Try this:
print date("Y/m/d h:i:s", strtotime($node->event_info_date['und'][0]['value']));
Hope this will help you.
Comment: This code is printing this: **1970/01/01 01:00:00**, while the value of the field is: **2015/09/30 00:56:00**
Comment: can you send me the exact value you are getting in this: "$node->event_info_date['und'][0]['value']".
you can do this by :
drupal_set_message($node->event_info_date['und'][0]['value']); or direct print.
Comment: One more thing if you're not getting any value in this that means either you array structure is not proper, so try this one to get the structure:

drupal_set_message(print_r($node->event_info_date,1));

Printing date with custom format


How do I render faces properly in 3d?

Question: I am trying to render the faces of a cube properly in 3d. This is my code:
import pygame, sys, math

def rotate2d(pos,rad): x,y=pos; s,c=math.sin(rad),math.cos(rad); return x*c-y*s,y*c*+x*s

class Cam:
    def __init__(self,pos=(0,0,0), rot=(0,0)):
        self.pos = list(pos)
        self.rot = list(rot)

    def events(self,event):
        if event.type == pygame.MOUSEMOTION:
            x,y = event.rel
            x/=200; y/=200
            self.rot[0]+=y; self.rot[1]+=x

    def update(self,dt,key):
        s = dt*10
        if key[pygame.K_q]: self.pos[1]+=s
        if key[pygame.K_e]: self.pos[1]-=s
        x,y = s*math.sin(self.rot[1]), s*math.cos(self.rot[1])
        if key[pygame.K_w]: self.pos[0]+=x;self.pos[2]+=y
        if key[pygame.K_s]: self.pos[0]-=x;self.pos[2]-=y
        if key[pygame.K_a]: self.pos[0]-=y;self.pos[2]+=x
        if key[pygame.K_d]: self.pos[0]+=y;self.pos[2]+=x

class Cube:
    verticies = (-1,-1,-1),(1,-1,-1),(1,1,-1),(-1,1,-1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1)
    faces = (0,1,2,3),(4,5,6,7),(0,1,5,4),(2,3,7,6),(0,3,7,4),(1,2,6,5)
    def __init__(self,pos=(0,0,0)):
        x,y,z = pos
        self.verts = [(x+X/2,y+Y/2,z+Z/2) for X,Y,Z in self.verticies]

pygame.init()
w,h = 400,400; cx,cy = w//2,h//2
screen=pygame.display.set_mode((w,h))
clock = pygame.time.Clock()

cam = Cam((0,0,-5))

pygame.event.get; pygame.mouse.get_rel()
pygame.mouse.set_visible(0); pygame.event.set_grab(1)

cubes = [Cube((0,0,0)),Cube((-2,0,0)),Cube((2,0,0))]

while True:
    dt = clock.tick()/1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT: pygame.quit(); sys.exit()
        cam.events(event)
    screen.fill((255,255,255))
    for obj in cubes:
        vert_list = []; screen_coords = []
        for x,y,z in obj.verts:
            x-=cam.pos[0]; y-=cam.pos[1]; z-=cam.pos[2]
            x,z = rotate2d((x,z), cam.rot[1])
            y,z = rotate2d((y,z), cam.rot[0])
            vert_list += [(x,y,z)]
            if z == 0: z = 0.001
            f=200/z
            x,y = x*f, y*f
            screen_coords+=[(cx+int(x), cy+int(y))]

        face_list = []; face_color = []; depth = []
        for f in range(len(obj.faces)):
            face = obj.faces[f]
            on_screen = False
            for i in face:
                x,y = screen_coords[i]
                if vert_list[i][2]>0 and x>0 and x<w and y>0 and y<h: on_screen = True; break

            if on_screen:
                coords = [screen_coords[i] for i in face]
                face_list +=[coords]
                face_color += (128,128,128)
                depth += [sum(sum(vert_list[j][i] for j in face)**2 for i in range(3))]
        order = sorted(range(len(face_list)),key=lambda i: depth[i], reverse=0)
        for i in order:
            try:
                pygame.draw.polygon(screen, face_color[i], face_list[i])
            except: pass
    pygame.display.flip()
    key = pygame.key.get_pressed()
    cam.update(dt,key)

This renders to the screen, but not properly. What am I doing wrong? There should be three cubes, visible to the user, and the user should be able to move around them freely. Instead, the program renders the faces improperly at the wrong coordinates. Maybe this is something to do with the rotate2d() function? Though this seems to be working properly. I think I am processing the vertexes properly too. What am i doing wrong?
Comment: There is a typo in `rotate2d`. It has to be `x*c-y*s,y*c+x*s` rather than `x*c-y*s,y*c*+x*s` (focus on `*+`). Further more `pygame.event.get()` rather than `pygame.event.get` (before the application loop)
Answer: Aside from the comment Rabbid76 made, the only thing out of whack is that you put the face_list = []; face_color = []; depth = [] line inside the for loop. Instead of this:
for obj in cubes:
    […]
    face_list = []; face_color = []; depth = []
    […]

your for loop should look like this:
face_list = []; face_color = []; depth = []
for obj in cubes:
    […]
    […]

Also, here are some code suggestions made by Rabbid76 to improve various things about this exact code:

Depth issue with 3D graphics
Close range 3d display messed up

How do I render faces properly in 3d?


How to use C# to display Registry results on Rich Text Box?

Question: I have a program which is able to retrieve various registry values using C# codes which was compiled and created using VS 2010.
However the problem arises when I tried to display the results retrieved from the Windows Registry into a rich text box within a form.
The form only shows 1 line which is the last value in the Array that contains the results.
Please do give some advice on the codes. Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Syscrawl
{
public partial class FTK_Menu_Browsing_History : Form
{
    public FTK_Menu_Browsing_History()
    {
        InitializeComponent();
    }

    private void buttonFileHistory_Click(object sender, EventArgs e)
    {
        this.Hide();
        FTK_Menu_File_History mfh = new FTK_Menu_File_History();
        mfh.ShowDialog();
        this.Close();
    }

    private void buttonEncryptedFiles_Click(object sender, EventArgs e)
    {
        this.Hide();
        FTK_Menu_Encrypted_Files mef = new FTK_Menu_Encrypted_Files();
        mef.ShowDialog();
        this.Close();
    }

    private void buttonRecentlyAccessedFiles_Click(object sender, EventArgs e)
    {
        this.Hide();
        FTK_Menu_Recently_Accessed_Files mraf = new FTK_Menu_Recently_Accessed_Files();
        mraf.ShowDialog();
        this.Close();
    }

    private void buttonRegistryHistory_Click(object sender, EventArgs e)
    {
        this.Hide();
        FTK_Menu_Registry_History mrh = new FTK_Menu_Registry_History();
        mrh.ShowDialog();
        this.Close();
    }

    private void buttonMainMenu_Click(object sender, EventArgs e)
    {
        this.Hide();
        Menu m = new Menu();
        m.ShowDialog();
        this.Close();
    }

    private void buttonLogOut_Click(object sender, EventArgs e)
    {
        this.Hide();
        Syscrawl_Login sl = new Syscrawl_Login();
        sl.ShowDialog();
        this.Close();
    }

    private void FTK_Menu_Browsing_History_Load(object sender, EventArgs e)
    {
        try
        {
            RegistryKey rk = Registry.CurrentUser;

            rk = rk.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TypedURLs",
    false);
            PrintKeys(rk);
            rk.Close();
        }
        catch (Exception MyError)
        {
            richTextBoxBrowsing.Text="An error has occurred: " + MyError.Message;
        }
    }

    void PrintKeys(RegistryKey rk)
    {
        if (rk == null)
        {
            richTextBoxBrowsing.Text="Couldn't open the desired subkey.";
            return;
        }

        richTextBoxBrowsing.Text = "Subkeys of " + rk.Name;

        try
        {
            string[] valnames = rk.GetValueNames();
            int i = 0;

            foreach (string s in valnames)
            {
                string val = (string)rk.GetValue(valnames[i++]);

        richTextBoxBrowsing.Text="-----------------------------------------------";
                richTextBoxBrowsing.Text=s + " contains " + val;
            }
        }

        catch (Exception MyError)
        {
            richTextBoxBrowsing.Text = "An errors has occurred: " + MyError.Message;
        }
    }

    private void richTextBoxBrowsing_TextChanged(object sender, EventArgs e)
    {

    }
   }
 }

Comment: One suggestion: when you post code, include only the relevant parts (the Click events weren't related to the textbox issue)
Answer: By saying:
richTextBoxBrowsing.Text=

in each iteration of your loop, you keep on overwriting the text. So only the last call to the Text property gets printed.
You need to set the richTextBoxBrowsing.TextMode property to multiline, and then instead call:
richTextBoxBrowsing.AppendText(s + " contains " + val + "\n");

Oh, and by the way, use: string val = rk.GetValue(s).ToString();
so you can remove the int i = 0; declaration
Answer:
Confirm that you set
richTextBoxBrowsing.TextMode to
MultiLine
Change richTextBoxBrowsing.Text+=s + " contains " + val; in foreach loop
Use Debug.WriteLine to debug return
value
Comment: Could you provide some codes for the multiline? and debug? Thanks.
Comment: @JavaNoob I've updated the post and link Debug.WriteLine. This might be helpful. And I think if you do first two steps from above your problem will be resolved.
Answer: You should use richTextBoxBrowsing.AppendText(...)
Answer: You're changing the entire contents with each call, instead of appending to it:
richTextBoxBrowsing.Text=s + " contains " + val;

should be
richTextBoxBrowsing.AppendText(s+" contains " + val+Environment.NewLine);

Comment: It shows all the results now but its all clumped up...How can I make to show line by line? Thanks.
Comment: @JavaNoob: edited to add the newline code: You add Environment.NewLine at the end of the string you want to append, and that will use the system's new line character
Answer: I think your loop is not correct.
In _void PrintKeys()_ your Loop overwerites your RichTextBox.Text-Value try something like:
String temp = "-----------------------------------------------";
foreach (string s in valnames)
{
    String val = (String)rk.GetValue(valnames[i++]);
    temp=temp+s + " contains " + val;
}

RichTextBox.text = temp;

Comment: You should use a StringBuilder rather than repeatedly appending text to a string.
Comment: I know, but as it was often discussed before, I depends on how much Strings you really concatinating. In this little example, I think it shouldn't matter.


XML is document oriented. What does it mean?

Question: I read somewhere XML is document oriented and JSON is object oriented. What does that mean?
Comment: Has your question been answered to your satisfaction?  If not, please ask in the comments for further clarification.   If so, please [**accept**](https://meta.stackexchange.com/q/5234/234215) an answer.  Thank you.
Answer: XML was designed, as SGML before it, to represent documents.  Later, it became adopted in web-based remote procedure calls and configuration files as a data rather than document oriented format.
JSON was designed to represent JavaScript data.  It has flourished in the data-oriented areas into which XML had previously expanded and is a better fit there.
XML has retained its original advantage as a document format.  It has numerous schema definition languages (XSD, Relax NG, Schematron, and DTD) developed across many sectors, powerful selection (XPath) and transformation (XSLT) tools, and it supports mixed markup needed in document representation.
JSON has ridden the JavaScript wave and is now used for data exchange and persistence across many other languages and platforms.  It is lighter weight and closer in syntactic form to programming data structures.
They both have their place in modern systems and application development.


Secret-Santa: Probability of two people drawing each other.

Question: When playing Secret Santa this year, where a group of $n$ people buy presents and these $n$ presents get randomly distributed to the other people, excluding the possibility of someone getting his or her own present (we did it with a online-distributer, so this possibility really is excluded), someone in this round asked the question about the probabilty of two people giving presents to each other. Since then I've been thinking about this problem, but I didnt get very far. The only thing that comes to my mind is working with the symmetric group $S_{n}$, and considering the possibilities $S_{n}\setminus F$, with $F$ being the set of all permuations with at least one fixpoint, as this is not possible in the game of Secret Santa. The probabilty I'm interested in now can be calculated by coming up with the cardinality of the set $\{\pi \in S_{n}\setminus F\ \mid \pi $ contains at least a two-cycle$\}$. Any futher ideas?
Answer: Here's a fun fact: you might know that the probability that a random permutation has no fixed points is approximately $e^{-1}$ (and approaches this value quite rapidly). This generalizes: the probability that a random permutation has no cycles of length $\le \ell$ is approximately
$$e^{-H_{\ell}} = e^{- \left( 1 + \frac{1}{2} + \dots + \frac{1}{\ell} \right)}$$
where $H_{\ell}$ is the $\ell^{th}$ harmonic number. So the probability that a random permutation has no $2$-cycles given that it has no fixed points is approximately $e^{-\frac{1}{2}}$, which means the probability you want is the complement of this, namely
$$\boxed{ 1 - e^{- \frac{1}{2} } \approx 0.393 \dots }.$$
This can be proven using a result called the permutation form of the exponential formula, which implies that for fixed $\ell$ the sequence $f(n, \ell)$ counting the number of permutations of $n$ elements with no cycles of length $\le \ell$ has exponential generating function
$$\sum_{n \ge 0} f(n, \ell) \frac{t^n}{n!} = \exp \left( \sum_{k \ge \ell+1} \frac{t^k}{k} \right) = \frac{\exp \left( - \sum_{k=1}^{\ell} \frac{t^k}{k} \right)}{1 - t}.$$
The result follows (with very good error terms) from looking at the pole at $t = 1$. You can plug this generating function into a computer algebra system like WolframAlpha to compute specific coefficients and it will tell you, for example, that when $n = 8$ there are exactly $14833$ permutations without fixed points and $8988$ permutations without cycles of length $\le 2$, so the exact probability for $n = 8$ is
$$\frac{14833 - 8988}{14833} = 0.394 \dots$$
so the above is quite a close approximation already for this small value of $n$. We have $14833 = \left[ \frac{8!}{e} \right]$ where $[x]$ denotes the closest-integer function (this is a well-known formula for the number of derangements); we might hope that $8988$ is equal to $\left[ \frac{8!}{e^{1 + \frac{1}{2}}} \right]$ but this is actually equal to $8987$. So close but not quite! Probably a very slight adjustment to this will produce an exact formula for all but possibly very small $n$.
Comment: Wow, this generalization is an awesome result, thank you very much!
Answer: Define an $r$-derangement to be a permutation whose smallest cycle has length strictly greater than $r$. Let $D_{n,r}$ denote the number of $r$-derangements in $S_n$. It is a standard result that for fixed $r$, we have that $\frac{D_{n,r}}{n!} \sim e^{-H_{r}}$ where $H_r$ is the $r$-th Harmonic number. This is proven, for instance, in Analytic Combinatorics by Flajolet and Sedgewick.
The probability that two people do not give presents to each other should thus be approximately $\frac{e^{-H_{2}}}{e^{-1}} = e^{-1/2}$.
Comment: Thank you very much, I will check out this book!
Answer: The numbers of ways to distribute $n$ gifts according to the rules are OEIS A000166. The numbers of those ways where two people give gifts to each other (i.e. there is a $2$-cycle) is OEIS A158243. The probability you seek is then an entry of the first sequence divided by that of the second.
Asymptotically, as given in the formulas section of both sequences, the numerator tends to $n!(e^{-1}-e^{-3/2})$ and the denominator to $n!(e^{-1})$, leading to a limiting probability of $1-\frac1{\sqrt e}=0.393469\dots$


Survey on large deviation bounds of queuing delay in CSMA scheduling

Question: I am trying to do some literature survey on the theoretical guarantees in uplink scheduling algorithms. I found there exist a series of papers from UIUC and UC Berkeley by L.Jiang, J. Walrand, R. Srikant and others. These works mostly analyse the stability and sometimes delay of CSMA\adaptive CSMA in large scale networks using Markov chain and Mixing time techniques. The most exciting work seems to be $[1]$, where the authors derive polynomial upper bound  on the average queue length in large scale networks. But the large deviation bounds are not present in their work. Any direction to the latest literature in this specific area will help me proceed quickly with my research. Thanks in advance.
$[1]$ Jiang, Libin, et al. "Fast mixing of parallel Glauber dynamics and low-delay CSMA scheduling." Information Theory, IEEE Transactions on 58.10 (2012): 6541-6555.
Answer: I am not aware of any result on the large deviation bounds you mention, but you may want to start digging in the following article (and references therein), which offers a survey of the various model that have been introduced in literature to study the performance of CSMA-like algorithms:
<code>S.-Y. Yun, Y. Yi, J. Shin, and D.Y. Eun. Optimal CSMA: A survey. In 2012
IEEE International Conference on Communication Systems (ICCS), pages
199–204. IEEE, 2012.
</code>
Another starting point for your research could be the PhD thesis of Niek Bouman "Queue-based random access in wireless networks" and/or his publications (and references therein) co-authored with S.C. Borst and J.S.H. van Leeuwaarden.


Can a classical computer count beyond a finite number?

Question: It seems since a classical computer has a finite number of transistors, it can only represent numbers up to a finite value. So a classical computer couldn't start at 1 and then count up to an arbitrary number. Can anyone confirm this or provide reasons otherwise?
Comment: How does this differ from our brains, which are made of a finite number of neurons (even atoms, if you wish)? Also, counting up to an arbitrary number (from text of your question) is not the same as counting beyond a finite number (from title of your question).
Comment: The term you used is not right - you mean to ask "can a computer count to any given finite number as large as we wish?" Actually, in some way turing demonstrated that a machine can work for ever. The challenge will be the input the number first - and it will be in parts. Than you will need to write a special program to do the counting.
Comment: It depends what you mean by counting up. Is it bits that you count, or is it what the bits represent that you count. Is the increment 1, does every step have to be stored etc. Related: https://stackoverflow.com/questions/3708461/biggest-number-in-computer-ever
Comment: An individual computer has a very limited "lifetime" of only a few years.  And inasmuch as the amount of energy in the universe is finite, no computer or set of computers can "count" forever.  Finally, the universe will likely end in 50 billion years or so.  So, there's that.
Answer: The counting limitation for a classical computer results from available memory, not from available processing power. For example, there are simple algorithms that can sequentially read the digits of an arbitrarily long binary number N and simultaneously write the digits of the number N+1. Rinse and repeat and your computer can count forever (in principle). There is no need to store the whole of N in the computer's memory so processing the algorithm is not limited by the 'size' or complexity of the computer itself.
Where the limitation is, is in the space required to store the 'written' digits. If you had unlimited external memory then in principle the computer could read and write (count) forever, but in practice there is a limit in the external memory based on how much data you can store in all the matter you have available.
So, in practice, the limitation is not in the computer itself - but in the storage limit of the visible universe.
Comment: It depends too if you use symbolic programs that have the notion of limit.
Comment: An individual computer has a very limited "lifetime."  And inasmuch as the amount of energy in the universe is finite, no computer or set of computers can "count" forever.
Finally, the universe will likely end in 50 billion years or so.  So, there's that.
Comment: I'm not sure I agree that there is no need to store the whole number. One can store a truncated version of the number and keep incrementing it, but I think this would be cheating. It doesn't seem there would be a use of counting. If I wanted to obtain the full number after a certain amount of time had passed, I wouldn't be able to. One could store parts of the number and operate on it, and then operate on other parts of the number, but where would the other parts of the number be stored?
Answer: Yes, for any actual physical computer, there is a finite number beyond which it will not be able to count, because there's only finitely many physical states it can be in.
I'm assuming you're also, at least a little bit, asking a different question:

If all physical computers are finite, why do we model them with things like Turing machines, which have infinite amounts of memory?

That's because at the stage when we're using mathematical models like Turing machines, the memory size of physical computers is irrelevant. Generally:

The first constraint on what computers can do is that some problems are undecidable: even a Turing machine will never be able to tell you the answer.
Many actual decidable problems are more limited by time than space.
Usually, algorithms scale, so that the same idea works on problems of any size, even if some problems can't be solved on physical computers today.

We do sometimes consider memory limitations. (For example, PSPACE is the set of all problems for which the memory needed to solve a length-$n$ instance is bounded by some polynomial in $n$.) But even then, we can just take a model with infinite memory, and then once it's done solving a problem, ask: how much memory did it use?
Comment: An individual computer has a very limited "lifetime" of only a few years. And inasmuch as the amount of energy in the universe is finite, no computer or set of computers can "count" forever. Finally, the universe will likely end in 50 billion years or so. So, there's that. –
Comment: I think there's a general principle at work that it's easier to say "there is no upper bound" than to say "there is an upper bound, but it's situational and not precisely known". We work with real numbers, which have unlimited precision, even though all our measurements can only give us so many decimal digits.


Como eu crio um método showOptionDialog que o valor padrão seja "não"?

Question: Eu quero com que as mensagens de confirmação de meu sistema se comportem com o valor padrão "não". Eu consegui isso fazendo desta forma:
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Object[] options = {"Yes", "No"};
    JOptionPane.showOptionDialog(rootPane, "Deseja Excluir o Usuário?",
    "Titulo", 0, 3, null, options, options[1]);

Só que eu quero criar um método para reutilizar esse trecho de código e não estou conseguindo. Eu tenho que sobrescrever o método showOptionDialog do java?
Eu quero passar como parâmetro a mensagem a ser exibida e quero que me retorne a opção selecionada pelo usuário.
Como faria isso?
Answer: Você pode fazer isso:
    private static boolean perguntar(
            Component c,
            String mensagem,
            String titulo,
            boolean defaultOpt)
    {
        Object[] options = {"Sim", "Não"};
        int resposta = JOptionPane.showOptionDialog(
                c,
                mensagem,
                titulo,
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[defaultOpt ? 0 : 1]);
        return resposta == 0;
    }

Para chamar esse método:
boolean aceitou = perguntar(rootPane, "Deseja excluir o usuário?", "Título", false);

Ele vai retornar true se o usuário clicar no botão "Sim" e vai retornar false se ele clicar no "Não", fechar a janela, apertar Esc ou apertar Enter imediatamente após a janela abrir.


Convert search string from UISearchBar to MK MapView Address

Question: Add a UISearchBar to my MK- MapView and obtain an address on a map using the search string written in the UISearchBar.
Later I have to be able to convert the address indicated on the map in NSString!
Can you help me please? I searched on google but I did not understand anything! Please help me.. I used this project, but when I run the search, the map remains the same point: project that I used
Comment: I used this project, but when I run the search, the map remains the same point: https://github.com/digdog/MapKitDragAndDrop
Comment: Please scuse me, the link is this  https://github.com/infolock/eLBeeMKLocalSearch
Comment: please show your effort for better answers.
Comment: what you have tried so far ?
Answer: You can refer following link to find a sample code for map view search a/c to the places.....
https://developer.apple.com/library/ios/samplecode/MapSearch/Introduction/Intro.html#//apple_ref/doc/uid/DTS40013332
hope this will help you..


Equivalent metrices on unit ball of von Neumann algebra

Question: Let $\rho$ and $\sigma$ be two faithful, normal states on a von Neumann algebra $M$. Let us define two metrices on the unit ball $M_1$ of $M$ as follows:
\begin{align*}
d_1(x,y):= \rho((x-y)^*(x-y))^{\frac{1}{2}} \\
d_2(x,y):= \sigma((x-y)^*(x-y))^{\frac{1}{2}}
\end{align*}
How do we show that the metrices defined above are equivalent ?
N.B. We know that both the metrices induces the strong operator topology on the unit ball. Hence they are topologically equivalent.
Comment: What do you mean by equivalent metrics if you don't mean topological equivalence?
Comment: On a metric space $X$ two metrices $d_1$ and $d_2$ are considered to be equivalent if there exists $c_1 >0$ and $c_2 >0$ such that $c_1 d_1(x,y) \leq d_2(x,y) \leq c_2 d_1(x,y)$ for all $x,y \in X$.
Answer: They aren't. Let $M=B(H)$. Define trace-class positive injective operators $R,S$ by fixing an orthonormal basis $\{e_n\}$ and putting
$$
Re_n=\tfrac1{n^2}\,e_n,\qquad Se_n=\tfrac1{n^4}\,e_n.
$$
Then define
$$
\rho(x)=\operatorname{Tr}(Rx),\qquad \sigma(x)=\operatorname{Tr}(Sx).
$$
As $R,S$ are positive an injective, $\rho$ and $\sigma$ are faithful positive linear functionals (that we could normalize to normal states if we needed to). Consider the sequence $\{x_n\}$ given by
$$
x_n=E_n,
$$
where $E_n$ is the orthogonal projection onto $\mathbb C e_n$.
Then
$$
d_1(x_n,0)=\operatorname{Tr}(RE_n)^{1/2}=\frac1{n},
$$
while
$$
d_2(x_n,0)=\operatorname{Tr}(SE_n)^{1/2}=\Big(\frac1{n^4}\Big)^{1/2}=\frac1{n^2}.
$$
So the two metrics are not equivalent, since $$\frac{d_1(x_n,0)}{d_2(x_n,0)}=n.$$
Comment: Thanks a lot for your answer. In the above example, $d_1(x_n,0) $ and $d_2(x_n,0)$  should be equal to $Tr(Rn^4E_n)^{1/2}$ and $Tr(Sn^4E_n)^{1/2}$ respectively, and for that reason the trace class operators should be changed accordingly. But, I think this example does not fit into my question. The metrics $d_1$ and $d_2$ are defined on the unit ball of $M$. But, the operators $x_n$'s are not in there.
Comment: You are right, but the two metrics are still not equivalent in the unit ball.
Comment: Yeah right.. Thanks.. Thanks for you time..


Clarification on SKLearn's 'neg_root_mean_squared_error' score

Question: If I'm running some RFECV runs with various regressors, using neg_root_mean_squared_error as the scoring metric, when I executed the score = rfe.score(X_train, y_train) line, I get scores that look like this:

So, which of these would be a "better" score? I thought neg_root_mean_squared_error would produce a negative number? So if these are positive, would I want to aim for the LOWER numbers?
Thanks!
Answer: The RFECV's score method is still just a delegate to its model's score method, and so for these probably the R2 score, not your negative rmse. The negative rmse is being used to determine which number of features to select; you can also see some of those scores in the grid_scores_ or cv_results_ attribute, and can use the mean_squared_error metric function to find those scores for the refit estimator.


Como criar um TextView e uma ImageView via código?

Question: Gostaria de saber como cria via código um TextView e uma ImageView e destrui-lo via código.
Answer: Para criar uma view qualquer em memória é simples, mas a maioria dos problemas é quando não aparece nada no ecra, portanto asegure-se que ela fique visível como no caso da ImageView se não tiver uma imagem não ira aparecer nada, e se não adicionar a nenhuma layout é totalmente impossivel aparecer.
Então no caso da TextView:
TextView textView = new TextView(this);
textView.setText("Alguma coisa");

//Suponhamos que temos uma layout com um id layoutVertical
LinearLayout linear = (LinearLayout)findViewById(R.id.layoutVertical);
linear.addView(textView);

No caso da imageView seria algo parecido menos a parte de que se tem de adicionar uma imagem:
ImageView imagem = new ImageView(this);
imagem.setBackgroundResource(R.drawable.imagemqualquer);

No caso de apagar o que teria de fazer seria remover as views da layout em que estavam, no caso do exemplo anterior para remover a textView teriamos de fazer:
linear.removeView(textView);

Desde o momento em que já não é utilizada ou chamado o objeto TextView o garbage Collector o limpa e não ocupa mais a memória. Mas ainda se quiser pode também esconder a view sem a apagar:
textView.setVisibility(View.GONE);


If $f(x)+g(x)+h(x)=f(y)+g(y)+h(y)$ then for every $n$, $f(n)+g(n)+h(n)$=constant

Question: We deal quite often with situations in which we have something like $a_1b_1=a_2b_2$ and then we say that the product $ab$ is constant.
A similar situation arose when I was seeing  the derivation of Bernoulli's principal (physics) in which the second last step looks like $$\frac{P_1}{\rho}+gh_1+\frac{v_1^2}{2}=\frac{P_2}{\rho}+gh_2+\frac{v_2^2}{2}$$
Here $h$ denotes the height, $P$ denotes pressure and $v$ denotes the velocity. $\rho, g$ are constant terms density and acceleration due to gravity.
Then next step is $\frac{P}{\rho}+gh+\frac{v^2}{2}=$ Constant.
Now a question popped up in my mind.
The terms $\frac{P}{\rho}$, $gh$ and $\frac{v^2}{2}$ are dependent to the variables $P,h,v$ and thus each term can be considered as a function.
So the second last step in Derivation is similar to:
$$f(x)+g(x)+h(x)=f(y)+g(y)+h(y)$$ And last step is $f(n)+g(n)+h(n)=$constant.
That's what I want to prove, that $f(x)+g(x)+h(x)=f(y)+g(y)+h(y)$ then for every $n$ $f(n)+g(n)+h(n)=$constant. Further, If this thing is not true then why we use the similar argument in derivation of principal??
I am a beginner at function so please forget me if I am asking something very-very easy. Provide as much as information as you can. Thanks.
Comment: In general a function F(x) that satisfies F(x)=F(y) for two arbitrary x,y does not need to be constant (think about a parabola for instance). If it holds *for all* x,y then it indeed is constant, as it is in this case.
Comment: Do you mean $f(x)+g(x)+h(x)=f(y)+g(y)+h(y)$ for all $x,y$ or just for a couple of values?
Comment: I mean $F(x)=f(x)+g(x)+h(x)$ implicitly.
Comment: The parameters in Bernoulli's principle are not considered functions of $P,h,v$ but rather as functions of position $x$ along a streamline. The first equation is really saying that $f(x_1)=f(x_2)$ for all $x_1,x_2$ along the steamline. Fixing $x_1$ and varying $x_2$ allows you to conclude $f(x)$ is constant along the streamline for example.
Answer: Define
$F(x)=f(x)+g(x)+h(x)$.
Then your problem can be restated as if
$F(x)=F(y)$ for all $x,y$ in the domain of the function (this part is misleading in the question but very relevant), then $F(x)$ is constant.
To show it we are going to apply that if $F'(x)=0$ then $F(x)$ is constant. From the definition of derivative we have
$F'(x)=lim_{h\rightarrow 0}\frac{F(x+h)-F(x)}{h}=0$
where the last step is due to the fact that $F(x)=F(y)$ for all $x,y$.
Comment: $F(x) = F(y)$ for all pairs in the domain sounds like the definition of constant to me, not sure there is anything to prove.


how to restart an application in qt?

Question: I do this works for restarting my game but program has error .I want to show a QDialog when user losses .In this QDilag i put two pushbutton for retry and exit.also i have a QDialog for beginning of game.Where is my mistake? (I read similar questions and do according these but yet i have problem)
extern  int const EXIT_CODE_REBOOT;
mydialog_end::mydialog_end(QWidget *parent) :
QDialog(parent
{
  retry=new QPushButton(this);
  exit=new QPushButton(this);
  retry->setText("RETRY");
  exit->setText("EXIT");
  connect(retry,SIGNAL(clicked()),this,SLOT(on_retry_clicked()));
  connect(exit,SIGNAL(clicked()),this,SLOT(on_exit_clicked()));
 }
 void mydialog_end::on_retry_clicked()
 {
   qApp->exit(EXIT_CODE_REBOOT);
   accept();
  }
  void mydialog_end::on_exit_clicked()
  {
    //what do i do for end of game?
    reject();
  }
  //////////////in class myenemy///////
  public slots:
  void loss();
  void Myenemy1::loss()
  {
    if(this->collidesWithItem(_mario))
    {
      //do something....
      mydialog_end dialog;
      dialog.exec();
     }
    }
    //////////////in main////////////
 extern int const RESTART_CODE;
 int main(int argc, char *argv[])
{
  Mydialogstart dlg;//a dialog for beginning game
  int state= dlg.exec();
  int return_from_event_loop_code=0;
 do
{
    QApplication a(argc, argv);
    MainWindow w;
    if( state==QDialog::Accepted)
    {
        w.show();
        qDebug()<<"accepted";
    }
    else if(state==QDialog::Rejected)
    {
        qDebug()<<"rejected";
        dlg.close();
        return 0;
    }
    return_from_event_loop_code = a.exec();

} while(return_from_event_loop_code==RESTART_CODE);

  return return_from_event_loop_code;
}

Answer: You can use QProcess::startDetached to run an instance of your application in a new process and detach from it. After that you should exit the application :
QProcess process;
process.startDetached("myApp",QStringList());

qApp->quit();

Here myApp is the name of the executable file of the application. On Windows it can be myApp.exe.
Comment: You can put it anywhere you want to restart. Try it in your code and see if it helps.
Answer: On this one, I would make a little inception... let's say your main application is called A then you should run A in a global B application. When A crashes, B throws the QDialog. If the use click on Retry then kill the old instance of A and start a new one.
Comment: now what do i do in my code?i am beginner in qt.if possible put a sample code.
Answer: There is a Qt Wiki entry that explains what you need to do in quite a lot of detail.
As it seems you have at least partially taken inspiration from there, but from what you post here, you seem to have never initialized the values for EXIT_CODE_REBOOT and RESTART_CODE in your code sample, or at least linked them to one another (which I would expect you'd want to do in some way)

how to restart an application in qt?


Eigenvectors of hermitian matrix are not coming out to be orthogonal

Question: I have the following hermitian matrix before me:
\begin{pmatrix}2 &1+i\\ 1-i& 3\end{pmatrix}
I calculated its characteristic polynomial as $k^2-5k+4$ which has $1$ and $4$ as its roots.
Eigenvectors corresponding to these two eigenvalues are \begin{pmatrix}-(1+i) &1 \end{pmatrix} and \begin{pmatrix}1 &1-i\end{pmatrix}
But these are not orthogonal. Why is it so? Am I doing something wrong?
Comment: make sure you are considering in the complex inner product  i.e.  $=v \bar{w}$
Comment: @Moo The second eigenvector of yours can be obtained by multiplying mine one by $1+i$. Even then the vectors are not orthogonal.
Comment: @Brozovic Could you please elaborate on complex inner product? I have no knowledge about it.
Answer: Check Eigen values are $4,1$ and eigenvectors are $V_1=\begin{bmatrix} 1+i \\2 \end{bmatrix}$ and $V_2=\begin{bmatrix} -1-i \\ 1 \end{bmatrix}$, then
$V_1^{\dagger} V_2=0$, $\dagger$ means conjugate and transpose.


How to add a tooltip popup containing social share widgets in a views table

Question: I have a views table containing a number of columns, one contains a small icon.
I would like to have a tool tip open (containing the usual share widgets: twitter & facebook) when the image is clicked.
Could anyone suggest a way to achieve this?
Answer: There are a lots of modules providing tooltip functionality.
If you are familar with php coding:
1. Install Views PHP (https://drupal.org/project/views_php)
2. Install BeatuyTips (https://drupal.org/project/beautytips)
3. Create a PHP-field in your view and add the following code (Best is to include in your own module)
<code>
function render_socials($data = NULL){

  //if the links and icons are displayed inside the view, you can use $data

  $output .= l(theme('image', array('path' => 'PATH_TO_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_SECOND_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_THIRD_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_ANYOTHER_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
 }

$options['socials_' . $data->nid] = array(
         'cssSelect' => 'a.row-' . $data->nid . '-socials-popup',
         'text' => _render_socials($data),
         'trigger' => array(0 => 'mouseover', 1 => 'click'),
         'width' => 350,
       );
 print beautytips_add_beautytips($options);
</code>
Comment: Thank you for such a detailed answer. I will use your answer to get this working and report back.


Calculadora em javascript+ Html não Sai resultado

Question: Não sei o que fiz de errado, estou iniciando nisso e segui a apostila, mas da erro: alguem pode me ajudar?
    <!DOCTYPE html>

    <title>Calculadora Basica</title>

            <form>

                    Calculadora Basica

                    <input type="number" name="n1" id="n1">
                    <input type="button" value="+" onclick="soma();">
                    <input type="button" value="-" onclick="subs();">
                    <input type="button" value="x" onclick="multi();">
                    <input type="button" value="/" onclick="divis();">
                    <input type="number" name="n2" id="n2">
                    =
                    <input type="number" name="resultado" id="result" >

            </form>

Não sei o que pode ser, já faz 30min que já mudei o código e nada
Comment: Você esta pegando "values" o correto seria usar o método Value;
Answer: Cara, você apenas escreveu errado a propriedade value, você deixou como values.
O correto é assim:
var numero1 = parseInt(document.getElementById('n1').value);
var numero2 = parseInt(document.getElementById('n2').value);

Comment: Obg tb amigo....
Answer:    <!DOCTYPE html>

    <title>Calculadora Basica</title>

            <form>

                    Calculadora Basica

                    <input type="number" name="n1" id="n1">
                    <input type="button" value="+" onclick="soma();">
                    <input type="button" value="-" onclick="subs();">
                    <input type="button" value="x" onclick="multi();">
                    <input type="button" value="/" onclick="divis();">
                    <input type="number" name="n2" id="n2">
                    =
                    <input type="number" name="resultado" id="result" >

            </form>

Foi necessário apenas tirar o s no fim de alguns dos value, veja se consegue agora.
Comment: Nossa não acredito que era isso, Valeu amigo hehe


Berry-Esseen inequality for the event $a<S_n<b$

Question: Suppose that $X_i$ are independent identically distributed with finite variance and $S_n=X_1+\cdots+X_n$. One can use the Central Limit Theorem to estimate (a) $P(S_n \leq b)$ and (b) $P(a<S_n \leq b)$.
The Berry-Esseen theorem estimates the maximum possible error for the first case (a). The error is not greater than $C\frac{\rho}{\sigma^3\sqrt{n}}$.
Using the fact that $P(a<S_n \leq b)=P(S_n \leq b)-P(S_n \leq a)$ I may obtain a trivial bound for the error in the case (b): $2C\frac{\rho}{\sigma^3\sqrt{n}}$.
Is it the best possible bound for the error in the second case (b)? Or there is something better?
Answer: One cannot hope for anything smaller than $C\rho/(\sigma^3\sqrt{n})$, otherwise a strictly better bound than Berry-Esseen's bound would hold in case (a) (take the limit of (b) when $a\to-\infty$).
So the trivial bound is off by at most the prefactor $2C$ instead of $C$. In the cases I know, this has zero consequence.


Paired t-test in testing difference between two classifiers

Question: While reading the paper "Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms", I am confused at Section 3.3 when the authors claim that the paired t-test is not suitable to use to compare two classifiers $A$ and $B$, because the observed proportion of test examples misclassified $p_A$ and $p_B$ by $A$ and $B$ during trial $i$ are not independent. However, according to my understanding, the paired t-test assumes that the samples are paired, thus dependent.
What I reckon is that the test mentioned in the paper is the unpaired t-test. However, I think there is no motivation to consider unpaired t-test to compare two classifiers.
Thank you in advance!
Answer: We use a paired t-test when we have two measurements on the same sampling unit (dependent observations) AND when sampling units are independent of one another. Observations are paired, not samples.
In the situation in Section 3.3, the sampling units are NOT independent of one another because sampling units are created artificially by resampling the sample dataset (S). A paired t-test is therefore not appropriate.
The test mentioned in the paper uses a formula based on differences (p(i)), so it is referring to a paired t-test.
Comment: The part I agree with the paper is that $p^{(i)}$'s are not independent, because the test sets overlap.The confusing part is "... because $p_A$ and $p_B$ are not independent". I am confused since because they are not independent, paired t-test is used in the first place.
Comment: Thank you for your input. However, I reckon you were mistaken between random sampling and independent/dependent observations.


What is a normal singing range for children?

Question: What is considered a normal singing range for children?
That is, when choosing a key for a song for children to sing, what range should the melody fall within?
Alternatively, what is an expected full range, and where is the comfortable range (tessitura?)?
If it differs for different ages, please specify!
Please indicate your source if possible.
I'm mainly interested in the singing range for untrained children, but the range for schooled children singers, if different, would also be of interest.
I've searched my books and the web, but haven't found a well defined consensus answer such as you pretty much can for SATB.
Answer: In my experience of leading amateur kids choirs, the comfortable range for most 4-8 year olds would be around middle C (or possibly as low as the B flat just below that) up to around D or E -- that is, just over an octave.  Many kids would struggle with a low A or a high F, I think.
Answer: I am a preschool teacher with a love for music and I assume that each normal hearing child can learn to sing. Regarding maths, you won't kick off by teaching a 3 year old multiplication and division. For the same reason one should introduce singing using age appropriate songs. Considering range is very important, otherwise they will produce an undesirable chest sound or throat sound, or they will just sing or shout off tune.
If your group is 3 and younger, start off with songs ranging from D above middle C up to B below the next C. Challenge them later in the year with higher notes, as they expand their range upwards at this stage. Songs for 3 - 6 year olds can range over an octave from D above middle C to the next D or from E above middle C to the next E. 7 - 8 year olds can sing as low as middle C. By 10 - 12 years some might expand their range up to the second G above middle C, while others might be able to sing down to G below middle C.
Unfortunately CDs and YouTube songs which stay within a preschoolers' range are almost non-existing. It's therefore better to introduce the songs without help (if you could call it help!) while you sing within the appropriate range. With very young children or children who can't sing in tune yet, start off with songs consisting only of soh and me, then expand to soh - me - lah - soh - me (the kindergarten chant) and then songs including the whole pentatonic scale.
Young kids are still developing proprioception of the intrinsic muscles of their vocal cords and half tones do not come easy - that's why songs within the pentatonic scale (doh, re, me, soh and lah) is wise to begin with, e.g. "Old MacDonald had a farm".
Answer: They are most comfortable in the octave starting on Bb below middle C.
In Annie, the song Hard Knock Life requires a strong F# above this.  When I worked on a tour of the show, picking up five 'orphans' in each town, there were two non-negotiable requirements - ability to hit that note, and not being taller than our current 'Annie'.  Some of the 'dancing-school mums' had difficulty in accepting that we WEREN'T going to make exceptions.  And some, despite clear advertising for five GIRLS, insisted 'there were boys in the movie'.
OK, some of them placed that F# in a less than optimal part of their voice.  But it was only six performances over one week.  I don't think we did any of them serious, permanent vocal damage.
Answer: Usually they just sing an octave above a male singer in the baritone range. I did.
Comment: Yes, although if YOU are the one teaching them (and you are an adult male) it can be incredibly helpful to have access to their singing range in your falsetto.  Occasionally a child will try to match you at your octave and it just takes a second to say, "no, I want you to sing up here like this" and model in your falsetto.  I wouldn't recommend singing the whole song with them up there - I find it's much better to model for them but not sing along with them when they are learning - but sometimes the deeper male voice will make the kids try to sing too low!


Mysql Compare Two Database Tables and Fields

Question:
I have to compare two database tables and fields ( Not their DATA) .
Say Live DB and Development DB. In live DB there are 200 tables and
in development DB there are 218 Tables With some new column fields
added in old tables too.
During the final stage i have to update the Live DB by adding the new
columns and tables taken from the development DB .
I should not loss and data in the old DB.
I tried many ways to do this but it is taking a very long time for me
to finish. One of the tool i used is mysql workbench.

Is there any queries to perform this using information schema ?
To make the things easier i imported the development DB from development server and uploaded in the live db with different name . Now both the DB are in the same server but with diff name. E.g. sitedb , sitedevdb
Answer: Whenever you update the development DB with changes that will eventually be put live, you should write a .sql script that will repeat the changes on the live database.
Otherwise this operation is super-tricky.. you may have to manually figure out the added columns yourself, or you may be able to use each INFORMATION_SCHEMA.COLUMNS to compare the old tables.
For the new tables SHOW CREATE **table_name** is really useful.
Comment: I am trying to do this with PHP coding.
Comment: @Raaga, unless you are building some mad DB versioning system, this is hopefully gonna be a one-off. I'd probably end up using a mixture of SQL snippets, manual investigation and in extreme cases possibly PHP to fetch the information I need to build a script. Much easier to build the change script as you go along however.


Subpixel edge detection for almost vertical edges

Question: I want to detect edges (with sub-pixel accuracy) in images like the one displayed:

The resolution would be around 600 X 1000.
I came across a comment by Mark Ransom here, which mentions about edge detection algorithms for vertical edges. I haven't come across any yet.  Will it be useful in my case (since the edge isn't strictly a straight line)? It will always be a vertical edge though. I want it to be accurate till 1/100th of a pixel at least. I also want to have access to these sub-pixel co-ordinate values.
I have tried "Accurate subpixel edge location" by Agustin Trujillo-Pino. But this does not give me a continuous edge.
Are there any other algorithms available? I will be using MATLAB for this.
I have attached another similar image which the algorithm has to work on:

Any inputs will be appreciated.
Thank you.
Edit:
I was wondering if I could do this:
Apply Canny / Sobel in MATLAB and get the edges of this image (note that it won't be a continuous line). Then, somehow interpolate this Sobel edges and get the co-ordinates in subpixel. Is it possible?
Comment: Well, I've tried that. Primarily, this is not a contour. It's not enclosed, it's only a line. Secondly, it's extremely slow.
Comment: What about using active contours? (just a random idea)
Comment: Yup. You are probably rigth.
Answer: A simple approach would be to project your image vertically and fit the projected profile with an appropriate function.
Here is a try, with an atan shape:
% Load image
Img = double(imread('bQsu5.png'));

% Project
x = 1:size(Img,2);
y = mean(Img,1);

% Fit
f = fit(x', y', 'a+b*atan((x0-x)/w)', 'Startpoint', [150 50 10 150])

% Display
figure
hold on
plot(x, y);
plot(f);
legend('Projected profile', 'atan fit');

And the result:

I get x_0 = 149.6 pix for your first image.
However, I doubt you will be able to achieve a subpixel accuracy of 1/100th of pixel with those images, for several reasons:

As you can see on the profile, your whites are saturated (grey levels at 255). As you cut the real atan profile, the fit is biased. If you have control over the experiments, I suggest you do it again again with a smaller exposure time for instance.
There are not so many points on the transition, so there is not so many information on where the transition is. Typically, your resolution will be the square root of the width of the atan (or whatever shape you prefer). In you case this limits the subpixel resolution at 1/5th of a pixel, at best.

Finally, your edges are not stricly vertical, they are slightly titled. If you choose to use this projection method, to increase the accuracy you should look for a way to correct this tilt before projecting. This won't increase your accuracy by several orders of magnitude, though.
Best,
Comment: Thanks for the detailed explanation. But isn't there a simpler method? I mean my image has high contrast, so it should be simple to just trace the edge, right? And Sobel / Canny (MATLAB) gives me good results, except that it's not at subpixel level. Please see the last part of my edited question.
Comment: I don't really see why edge detection would be a simpler method than a fit. Anyway yes, indeed, you can perform edge detection, but as you noticed it's not giving you subpixel resolution. And unfortunately it won't because edge detection reduces the information. And again, if you are interested in precision, you should start by unsaturate your images because this shifts the real position of the edge.
Comment: Umm......the unsaturation part actually wouldn't be possible. The dark region is an object (one of the edges of a cylinder) in front of light (this light is the white saturated region). I just have to know at what pixel co-ordinates the edge of this object starts. No other information is required.
Comment: By unsaturate I mean play on the parameters of the acquisition itself, like the exposure time or the intensity of the light. This implies that you take a new set of data. With the present data, the saturation can shift the actual position of the edge of a few pixels, which is very bad with respect to the resolution you want.
Comment: Oh I understand your point. You are right, if the intensity is too high, the edge pixel shifts (as per my observations earlier). I have tried that. I have tried varying the back light's intensity and lens's exposure time. This is the optimum in image shown above. Btw, it works perfectly fine with pixel level accuracy (i.e., +/- 1 pixel), I get the desired edges on all sides well. Also, if I decrease the lighting it's more prone to noise.
Answer: There is a problem with your image. At pixel level, it seems like there are four interlaced subimages (odd and even rows and columns). Look at this zoomed area close to the edge.
In order to avoid this artifact, I just have taken the even rows and columns of your image, and compute subpixel edges. And finally, I look for the best fitting straight line, using the function clsq whose code is in this page:
%load image
url='https://i.stack.imgur.com/bQsu5.png';
image = imread(url);
imageEvenEven = image(1:2:end,1:2:end);
imshow(imageEvenEven, 'InitialMagnification', 'fit');

% subpixel detection
threshold = 25;
edges = subpixelEdges(imageEvenEven, threshold);
visEdges(edges);

% compute fit line
A = [ones(size(edges.x)) edges.x edges.y];
[c n] = clsq(A,2);
y = [1,200];
x = -(n(2)*y+c) / n(1);
hold on;
plot(x,y,'g');

When executing this code, you can see the green line that best aproximate all the edge points. The line is given by the equation c + n(1)*x + n(2)*y = 0
Take into account that this image has been scaled by 1/2 when taking only even rows and columns, so the right coordinates must be scaled.
Besides, you can try with the other tree subimages (imageEvenOdd, imageOddEven and imageOddOdd) and combine the four straigh lines to obtain the best solution.


Changing KVM VM listening on 5901 to some other port

Question: OK this is rather silly, but real problem.
vncserver keeps binding on 5902 port. That is because qemu is listening on 5900 and 5901:
% netstat -lntup
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:5900          0.0.0.0:*               LISTEN      1090/qemu-system-x8
tcp        0      0 127.0.0.1:5901          0.0.0.0:*               LISTEN      1137/qemu-system-x8
tcp        0      0 0.0.0.0:5902            0.0.0.0:*               LISTEN      7163/Xtightvnc
tcp        0      0 0.0.0.0:6002            0.0.0.0:*               LISTEN      7163/Xtightvnc

I suspect this has to do with me setting display to VNC in VM configurations. Believe it or not, otherwise the keyboard in VM's console does not work (at least before actual OS boot commences). Found it on Stack, it's real.
So the question is can I change VNC port that VMs are listening on? Otherwise Xtightvnc always gets sets desktop to examplehost:2 which gets in the way of my other scripts.
I run these VMs with virt-manager.
Comment: Certainly possible, Qemu has the command line parameter that sets the port, or even allows its VNC server to listen on an unix domain socket (useful to secure access via SSH). Exactly how do you run these Qemu processes?
Comment: @NikitaKipriyanov I just created VMs on a new host using `virt-manager`. Then, as I wrote, set display to VNC. That's it. And now they listen on 5901+ ports. P.S. I've done this on Bookworm host. A bug?
Comment: That's normal default behaviour. Why suspecting "bug" in the first place, did you read something in the manual and observed it worked in some undocumented way? Also, as this information is essential, I put it into the question for you. Next time do it yourself (from the very beginning), please.
Answer: This technology is called libvirt, and virt-manager you mentioned is just one of its clients.
That's normal default behaviour. Let's look at the documentation:

...
<devices>
  ...
  <graphics type='vnc' port='5904' sharePolicy='allow-exclusive'>
    <listen type='address' address='22.214.171.124'/>
  </graphics>
  <graphics type='rdp' autoport='yes' multiUser='yes' />
  ...
</devices>
...

...
vnc
Starts a VNC server. The port attribute specifies the TCP port number (with -1 as legacy syntax indicating that it should be auto-allocated). The autoport attribute is the new preferred syntax for indicating auto-allocation of the TCP port to use. The passwd attribute provides a VNC password in clear text. If the passwd attribute is set to an empty string, then VNC access is disabled. The keymap attribute specifies the keymap to use. It is possible to set a limit on the validity of the password by giving a timestamp passwdValidTo='2010-04-09T15:51:00' assumed to be in UTC. The connected attribute allows control of connected client during password changes. VNC accepts keep value only since 0.9.3. NB, this may not be supported by all hypervisors.

So, if autoport feature is used (the default with virt-manager), when VM starts it gets assigned first available port starting with 5900: first one gets 5900, next 5901, etc. If you start them in a different order, they "swap" ports. If you bind it to some port, it will try to use that port, and if it's busy, the VM won't start.
I don't know whether t's possible to change the port using virt-manager, but it's not the only libvirt control client available. Using virsh you can directly edit the VM definition in XML format. On the server:
virsh list -all
virsh edit <name>

First command lists all your VMs, second one will will open a default editor (probably, vi; you can set EDITOR environment variable to use something else, for example try running EDITOR=nano virsh edit <name>). After save and editor quit you need to stop and then start the VM for changes to take effect; the restart is not sufficient as it doesn't restart the Qemu process:
virsh shutdown <name>
virsh start <name>

(or from virt-manager GUI).
It should bind on the specified port only. Also it's possible to make it listen to the unix domain socket; read the linked libvirt documentation page further to learn, how. This will have the benefit of using the file name so to guarantee there will be nothing occupying the binding space for the VNC server. I never tried it myself (didn't use libvirt for 10+ years) and I don't know if virt-manager is able to connect to a socket.


Number to UTF-8 char

Question: In Node.js I'm able to print to the console a Japanese character like this:
console.log('\u3041');

If I have 3041 as a number, for instance because it is randomly generated, how do I print the corresponding UTF-8 sigil?
const charNumber = 3041;

// of course this doesn't work, but I need something like that:
console.log(`\u${charNumber}`);

Answer: You can use the HEX representation with .fromCharCode by replacing \u with 0x:

const charNumber = 3041;
console.log(String.fromCharCode(`0x${charNumber}`));

Number to UTF-8 char


Should I add an extra date column?

Question: TL;DR: I have a column with a timestamp column. I want to filter by a particular date. Should I add a date coulmn?
id(AI/PK)    some    fields    timestamp    *date?*

So the query with only a timestamp colum would be something like
SELECT ?
FROM [TABLE]
WHERE YEAR(timestamp) = '2015' AND MONTH(timestamp) = '04' AND DAY(timestamp) = '1'

vs a query with an additional date column
SELECT ? FROM [TABLE] WHERE date = date('04-01-2015')?

I'm currently in a planning and design phase of my project. But it will be a very huge table in production. So the cons of having a date column are obviously the increased size of the table. I guess the con of not having a date column would be decreased performance. No?
Well I'm not sure if it's that easy.
Answer: I don't think so.  You can do:
SELECT ?
FROM [TABLE]
WHERE date(timestamp) = '2015-04-01'

Or, if you want the query to use an index:
SELECT ?
FROM [TABLE]
WHERE timestamp >= '2015-04-01' AND
      timestamp < date_add('2015-04-01', interval 1 day);

Should I add an extra date column?


Vuejs3 + Axios + Express - Display data from array/object

Question: I am trying to output a single post from an express API using Vue.
Problem is that the object/array returned (post.value) does not display the values that I declare in the template (post.title & post.body).
Any help would be greatly appreciated.
<template>

{{ post.title }}

{{ post.body }}

</template>

Just for reference:
console.log(params.value) got no errors, and outputs the following:
Proxy {0: {…}}[[Handler]]: Object[[Target]]: Array(1)[[IsRevoked]]: false

UPDATE
I was able to output the variables, but with the help of a v-for loop. Just wondering if there's another way to output it without using a loop. I was able to make it work using Vue + firebase, but not on this stack.
Comment: Why do you await a promise and additionally use then()?
Comment: It's valid for catching the error.
Comment: @AidenDean just an ugly habit that I'm still not used to (using axios).
Comment: @OFRBG I think not, even if I remove the catch block it still outputs the same console log
Answer: Since your API is returning an array with one post, you can just store the post without the array around it.
<template>

{{ post.title }}

{{ post.body }}

</template>


Java Script, ASP.NET

Question: I need some help,
<asp:Image ID="imgCaptcha" CssClass="Captcha" ImageUrl="/ashx/captcha.ashx" runat="server" />
<button id="refreshcaptcha" type="button" class="btn btn-default btn-lg" aria-label="Refresh">  </button>

JScript
$("#refreshcaptcha").click(function (parameters) {
    $.ajax({
        type: "POST",
        url: "contactus.aspx/RefreshCaptcha",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var src = $('#<%= imgCaptcha.ClientID %>').attr("src");
            if (endsWith(src, "ashx")) {
                $('#<%= imgCaptcha.ClientID %>').attr("src", src + "?" + Math.random());
            } else {
                src = src.substring(0, src.indexOf('?'));
                $('#<%= imgCaptcha.ClientID %>').attr("src", src + "?" + Math.random());
            }
        },
        failure: function (response) {}
    });
    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
});

Above JS is on .aspx page and it's working OK,
How can I move this block of JS code into a separate but linked .js file?
What do I need to change into the JS code?
Comment: Why are you making a POST request and claiming that the content-type o the data you are sending is JSON when you have no `data:` attribute in the config object?
Comment: depends of the structure you're using but in general, just create a new js file then use it as reference like `` in your page
Comment: @Dumisani — Won't work. `$('#<%= imgCaptcha.ClientID %>')` would break in a static js file.
Comment: @ElmerDantas — Won't work. `$('#<%= imgCaptcha.ClientID %>')` would break in a static js file.
Comment: Please don't use comments to give answers. Give real answers if you are going to answer the question.
Answer: Add the ClientIDMode attribute to your <asp:Image> and set it to Static then use that id to access it in your javascript file.
For example:
<asp:Image ID="imgCaptcha" ClientIDMode="Static" CssClass="Captcha" ImageUrl="/ashx/captcha.ashx" runat="server" />

$('#imgCaptcha').attr("src", src + "?" + Math.random());

Comment: "Add the ClientIDMode attrivute to your and set it to" — This is riddled with so many grammar and spelling mistakes that I don't know what you are trying to say.
Comment: An explanation as to what setting that "attrivute" (attribute?) to Static actually means would probably make this a better answer too.
Comment: It would make the control's id on the DOM the same as the server side's control Id
Comment: louk thanks a lot for your help  "ClientIDMode attribute" was missing :)
Answer: Think of how you would do this in a NON ASP environment. What 'changes' do you have to make there? ASP is no different in that respect. Include the JS file in the ASP page. Generally this is done with some sort of standard header for your pages.
Comment: The JS includes ID values which are generated by ASP.NET. Simply writing the code as if ASP.NET didn't exist wouldn't fill in those gaps.

Java Script, ASP.NET


What is the distribution of the ratio of two t-distributed random variables?

Question: x is t-distributed;
y is t-distributed.
How is x/y distributed?
Does it have a closed-form formula?
Comment: Are these standard $t$, or location-scale family $t$?
Answer: Yes, your question has been answered in the affirmative in the following 1969 JASA paper. You can find there the formulas for the pdf and cdf of $W=X/Y$ with $X$ and $Y$ following a t-distribution.

S. James Press, "The t-Ratio Distribution", 1969, Journal of the
  American Statistical Association, Vol. 64, No. 325, pp. 242-252.


How should this rhythm be notated? (syncopated 6/8 bar)

Question: Although it looks like this rhythm would best be notated in 12/16, the drums play a straight 6/8 beat with accents on 3 and 6.
The first option is visually simpler, but it doesn't represent the beat clearly. The second one would have a tie across two beamed notes of the same value, and I'm not sure which is more appropriate.
Comment: Given that standard accents of 6/8 are on 1 and 4, should not the beginning of the bar be moved? Your second attempt is not better in respect to separating beats 3 and 6, so I would keep the simpler version. Its difficult to see from this small snippets, whether duplets could help.
Comment: What I meant is that though the metric accent is on 1 and 4, there's also a noticeable dynamic accent on 3 and 6. I don't know how drum notation works, but the bass hits on 1, the snare on 4, and the hi-hat on every beat but with a stronger pulse on 3 and 6.
Answer: On the contrary, I think the first option does a fine job of representing the two beats, and it's also how I would expect to see those rhythms in band or orchestra music. I would not want to sight read the second example. IMO, the correct notation is always going to be whatever will most easily get your players to perform the way you want.
You needn't show the drum's accent pattern in what (I assume) is a different instrument's music, especially when the accent is on the 3rd and 6th eighth notes of the bar, and your music has no attacks on those divisions of the beat (and therefore nothing to accent -- you wouldn't generally put an accent mark under the second note in a tie).
Answer: I would write duples.  Sorry I don't have any tool at hand to create an example image, but, using duples, in this case a pair of eighth-notes with a "2" above, you would write
first beat:  eighth note, then under the "2", there'll be a "3" to indicate a triplet, consisting of an eighth note and a sixteenth.
Second beat: two eighth notes under the "2" to indicate duplet.
Comment: Nested tuplets? That seems even more difficult to sight-read, especially because it's not immediately obvious that the triplets inside the duplet are supposed to be the same length as a normal sixteenth note.
Comment: @Ash  the triplet inside a duplet is not something I made up -- I've seen that and similar constructions several times.  An experienced musician will have no problem interpreting this depiction.
Answer: Here's my solution:
I don't like writing this in 6/8. 6/8 makes it hard to show the beat division, and 12/8 really shows the beat without weird beaming.
Comment: I think you will lose the "2 major beats" intent of 6/8 if you do this.
Comment: OP says the hi-hat hits on every beat (of the 6/8) -- that's an argument for keeping 6/8.
Answer: Try this. It's a combination of your two options.
Comment: This could be improved by swapping the last two notes. That way the last note (which is tied from the previous one) falls on "6".
Comment: @RosieF Good idea, Thanks for the suggestion, updated image.


Request referer gets cached

Question: I need to grab referer and save it for the first time (I save it to sessions) and when the user gets to a specific page forward it. My problem is that after opening page with the same referer few times, I am not getting referer anymore. I tried it with few different browsers in private/incognito mode but after a few tries it gets cached and does not return anymore. My Code :
function HOOK_template_preprocess_default_variables_alter(&$variables)
{
    $request = Drupal::request();

    var_dump($request->headers->get('referer')); //stops dumping after few times

    $_SESSION['referer']['url'] = $request->headers->get('referer');
    $variables['#cache']['contexts'][] = 'headers:referer';
}

Is there a way to save referer for every anonymous user that comes to website?
Comment: For anonymous traffic you need to disable the page cache. Add this line to your code `\Drupal::service('page_cache_kill_switch')->trigger();` or if this is for all pages you can uninstall the module *Internal Page Cache*. I agree with the answer from @Kevin that the code placement could be improved, because the hook you are using is executed multiple times per request (one time for every template), as long as the template is not cached, which will happen eventually for all templates. So better choose one and disable the caching of that specific template.
Comment: Of course, when you process each anonymous request individually this will slow down your site. But this problem is not Drupal specific. This is why most times such tasks are realized client side in javascript.
Comment: I think you can do it all client side until the user clicks on the link for leaving the site, then you can add the referer as query parameter, for which the page cache varies by default.
Comment: @4k4 well I need it for any page anonymous user lands on first, so I need to uninstall internal page cache, but will that affect speed of website?
Comment: @4k4 so maybe it would be better if I create client javascript code that would send referer over ajax to a custom module and then in the module I just save it to the session, then I won't have to disable internal cache. thank you very much
Comment: I transferred it to client javascript and saved with SessionStorage, and when on form page just use it with javascript, it is working without a problem, thank you @4k4 again.
Answer: For doing this, i won't use a hook but the drupal eventSubscriber :
First your need to make a custom module with the file for declare to drupal your new service :

myModule.services.yml

services:
  myModule.services:
    class: Drupal\myModule\EventSubscriber\MyServiceSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

Then in the file :

myModule/src/EventSubscriber/MyServiceSubscriber.php

<?php

namespace Drupal\myModule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

    /**
     * Class myServiceSubscriber.
     *
     * @package Drupal\myModule
     */
    class MyServiceSubscriber implements EventSubscriberInterface {

        public function onRequest(GetResponseEvent $event) {
           // here your code, this method ll be call on every call request
           // so you can code your logic here
        }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {

          $events[KernelEvents::REQUEST][] = ['onRequest', 900];

          return $events;
      }

    }

Comment: I tried this also but my priority was 30, and I see you used 900, can maybe that make a difference?
Comment: No its because higher priority numbers get executed first and i paste this code from my module where i have more than one event
Comment: You need to clear the cache after enable the module
Comment: as @4k4 mentioned in comments above I would still need to `\Drupal::service('page_cache_kill_switch')->trigger();` or uninstall internal cache module completely what would slow down the website, I transferred logic to client javascript code, thank you for suggestion @Kevin
Comment: The page cache is a middleware, request event subscribers are *not* called on a page cache hit. You can register your own middleware and act before/after the page cache on every request (except when when you also use an external cache like Varnish) but yes, it's quite possible that whatever needs to be done in such a case is better done in JS.

Request referer gets cached


Undefined offset: 6 while reading fopen

Question: <code>           foreach($posts as $post)
    {
        $words = preg_split("/\|/", $post);
        $author     = trim($words[0]) . ' ' . trim($words[1]);
        $title      = trim($words[2]);
        $comment    = trim($words[3]);
        $priority   = trim($words[4]);
        $filename   = trim($words[5]);
        $postedTime = $words[6];
</code>
I'm passing a .txt file into an html form, the file is missing some information that I am not supposed to display. When reading it I get an undefined offset 6 on $postedTime, the file is missing the value. Any ideas how to avoid the message?
Comment: What about `isset($words[6])` prior to actually using it?
Comment: if(isset($words[6]))
Comment: Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/q/4261133/6521116)
Answer: To avoid the message You can do something like this:
<code>$postedTime = isset($words[6]) && !empty($words[6]) ? $words[6] : '';
</code>
Answer: try this:
<code>$postedTime = (isset($words[6]))?$words[6]:'';
</code>
Comment: Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context  would significantly improve its long-term value. Please [edit] your answer to add explanation, including what limitations and assumptions apply.

Undefined offset: 6 while reading fopen


Reconstruction of Species Distribution based on poorly-sampled data

Question: cross-posted to Signal Processing, World Building, and Biology Stack Exchange
Problem: After reading a series of fantasy novels, I noticed that the biosphere in that world made no sense. To clarify, this is a world where despite magical occurrences, the world itself is almost entirely non-magical. 'Alternate history magical realism,' perhaps. i.e., unlike, for example, Harry Potter, in which almost all plant and animal species mentioned are fictitious and magical, this series uses real flora and fauna. This allows me to extract information about the fictional world's environment based on the distribution of these animals, by assuming that similar animals will live in similar climates on Earth and in the fictional world.
Ignoring the likelihood that the original author did not put enough thought into worldbuilding to make this a necessarily reasonable endeavor, my idea for how to proceed was as follows:
As maps exist of the fictional world, and the path of the characters can be plotted, I hoped to mark every mention of a specific plant or animal in the text, along with the location of the characters when it occurred, and from this reconstruct a plausible distribution for each species. I've created a theoretical example (in photoshop), for illustration:

where the red dotted line represents the paths of various characters, the orange, green, and blue splotches represent the true distribution of the species; the stars, triangles, and circles represent the locations at which a species is mentioned; and the brown, green, and blue lines represent the reconstructed contours of the distribution.
Is there a method to do such a reconstruction? It sounds a bit like a Monte Carlo analysis, but I figured I should check... (It also sounds rather like the magical programs detective shows use to plot serial killers' locations)
Note: It should be clear from the problem statement that just because a species is not mentioned at a specific location does not mean that it does not exist there. i.e., a sample at a specific location returning only 'A' - 'Bill and Jeff saw a lemur.' - does not exclude the possibility of 'B' and 'C' also at that location, but not sampled. Just because the text may specifically say that Bill and Jeff saw a lemur, and doesn't mention any other flora or fauna doesn't mean we should assume that they are in a universe devoid of anything but the occasional lemur.
Final Thoughts: Ideally, the analysis method would further:

take into account the coverage of the paths, and not assume that (in
the example above) nothing exists in Mexico or northern Canada, just
because there are no samples taken there. Remember that samples can
only be taken along paths.
take into account edges, in this case coastlines. If A, B, and C are
land animals, it does not make sense that a reconstruction of their
distribution would include water, even if their range surrounds a
lake or something.

Sorry for the long-winded explanation. Any thoughts?
Comment: Yes, this is presence only species distribution modelling.  It is a growing field.  I'll write a proper answer later. Totally awesome question. Will you have any environmental data?
Comment: I think the two big stumbling blocks are
a) Do you have environmental data? I guess you will have latitude. Maybe some idea of altitude and broad habitat? You could go totally overboard and aim for climate modelling like this.
http://www.theguardian.com/environment/blog/2013/dec/06/jrr-tolkien-climate-lord-of-the-rings
b) Sample size. You need at very, very least 10 datapoints for each animal species you are interested in. 50-100 is better. How many locations do you have?

Finally, what books? I'm intrigued.
Answer: This paper is pretty relevant (pdf).  The authors try to predict where various species can live, given a set of observations but no explicit information about where they weren't observed.  As @timcdlucas mentioned, there's a whole subfield devoted to this kind of "presence-only" data analysis for species distribution mapping.  I'll let him give a broad introduction to the field.
The wrinkle that makes the paper I linked to especially relevant to your situation is that the sampling wasn't randomly distributed across the landscape and we have some information about where the sampling took place.
In the case of the paper I linked to, most of the observations were in southern Ontario because that's where the observers were (not because that's where the species were).  They suggest one approach for accounting for this sort of bias.  Ideally, your method could use a similar re-weighting scheme based on the number of pages in each part of the country or the total number of species mentioned in each area.
Once you've accounted for that sort of bias, you could use a variety of techniques from the presence-only literature for mapping species' ranges.
reference: Sample selection bias and presence-only distribution models: implications for background and pseudo-absence data. Phillips et al. 2009, Ecological Applications
Answer: I've posted an answer at BioSE, but will add a brief version here as well.
The problem of how to infer species distributions from scattered species occurrences is standard in ecology, and there exists a number of methods to construct distribution maps. As a start, you should have a look at Species Distribution Models (SDMs) using regressions models or Maxent, and the paper by Elith et al (2009) is a good starting point and a standard reference. SDMs using maxent is now a very common approach, which integrates species occurrences as point data along with environmental layers (e.g. temperature, moisture and topography) to predict species distribution maps, and this can also include real absence data or "pseudo-absence" data (randomly sampled data from a region of interest). The maxent software is described and can be downloaded here: http://www.cs.princeton.edu/~schapire/maxent/
In your "Note", you get into the issue of detectability, which has received much attention recently. This problem is largest when you only have presence data, and to have real presence/absence data is preferable. Even if you don't have real absenses (the species has been searched for but not found), an estimate of sampling effort in different areas is still very useful, since this means that you can at least evaluate whether absenses is due to "real" absense or lack of sampling. The movement paths of the characters that you describe can be used to estimate the "sampling" effort in different areas. The main issue with detectability (and why it can be problematic to not take detectability into account) is if there are trends or biases in detectability, which means that apparent changes over time or space might be due to differences in detectability and not real differences between areas or over time. This could for instance be the case if observers are more likely to spot a species in one type of habitat (open savannah) then in another type of habitat (closed forest). Useful starting points for issues of detectability are Dorazio (2014) and Kery et al (2010).
Comment: I think the movement paths are of the characters, not the species. So Mark-recapture is not appropriate unless there's more information not given by OP.
Comment: @timcdlucas Yes, you are most likely correct. I misunderstood the  OP on this part - this is however a minor part in my answer, but I have modified this part now.


Cannot start SQL Server PowerShell

Question: Have you guys had this problem where, when you start PowerShell from SQL Server, it throws an exception like the following?

Cannot resolve alias 'cd' because it
  refers to term
  'Microsoft.PowerShell.Manag
  ement\Set-Location', which is not
  recognized as a cmdlet, function,
  operable pr ogram, or script file.
  Verify the term and try again. At
  line:1 char:140
  + &{[System.Console]::Title = 'SQL Server Powershell';Convert-UrnToPath
  'Server
  [@Name=''AIMLESS'']/Database[@Name=''AdventureWorks2008'']'|cd
  <<<< }

I cannot navigate around with some common aliases like pwd, cd, etc.. even though get-alias clears shows that cd is set-location and pwd is get-location.

[UPDATE] Alias cannot be set either
Answer: I'm pretty sure I ran across this several months ago, but can't find it anymore after a quick search.  I believe the user's GAC some how got corrupted/mixed up.
Are you able to start a regular PowerShell session OK?
How you updated .NET versions?
Comment: I had a SQL 2008 VM, and just loaded the latest .NET 4.0 without any problems.  One thing that seems odd is the error refers to "...ManagementWSet-Location...".  I don't the "W".  That should at least be a black-slash, I'm thinking.
Comment: Yes, I have no problem with regular PowerShell on the same machine---I actually installed Visual Studio 2010 Professional Beta 1 installed on my machine and it also installed .NET v4.0.20506
Comment: So...  Did this problem start after you installed .NET 4?  The SQL minishell may have some hardcoded configs that cause it to break here.

How about trying the regular PowerShell console, then loading the SQL snapins.  If that works, then there may be an issue with the SQL minishell itself.
Comment: @Marco Shaw: I am not sure if the problem has started after installing .NET 4.0 since I never tried SQL PowerShell before installing it.  But if I were to speculate that seems to be case, since that "developer" machine is the only one with VS2010 and has the trouble.  From "Get-PSSnapIn", i can see that SQL snapins are loaded but let me try it again.
Answer: It definitely sounds like a profile issue to me. I found an article(a) that talks about a similar problem caused by Powershell version 1 beta being installed at one time.
I would look through each of the files in the profile chain to see which one is remapping those aliases on you. You could then rename the profile file to test if it was the problem. I am not exactly sure how you are starting Powershell, but if SQL Server is starting Powershell, you will want to look at it's user account's profile.
This should do it...
notepad '$env:windir\system32\WindowsPowerShell\v1.0\profile.ps1'
notepad '$env:windir\system32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1'
notepad '$env:UserProfile\My Documents\WindowsPowerShell\profile.ps1'
notepad '$env:UserProfile\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'

(a) Profile.msh possible errors:
If you load the profile.msh file, and
  you have previously installed an
  earlier version of Monad, then on
  startup you may see a series of errors
  like:
set-alias : The AllScope option cannot
  be removed from the alias 'cat'. At
  C:\Documents and Settings\All
  Users\Documents\msh\profile.msh:9
  char:10
  + set-alias <<<< cat get-content
To fix this, either delete the file
  named ("C:\Documents and Settings\All
  Users\Documents\msh\profile.msh" in
  this example), or remove all the
  "set-alias" lines from it. Aliases
  defined in profile.msh in earlier
  versions of Monad are now defined
  internally by Monad before the profile
  is run; therefore, the definitions in
  profile.msh will generate an error
  attempting to redefine the alias.
http://www.latenighthacking.com/archives/reference/PowerShellDocumentationPack_rc1/Windows%20PowerShell%20RC1%20release%20notes.htm
Comment: Actually, now that I look at your error again, the problem is likely the script that is being ran when you click "Start Powershell". You will need to find and fix him.
Answer: Are you using PowerShell Community Extensions? Unfortunately they use the default profile.ps1 file instead of Microsoft.PowerShell_profile.ps1. IF this is the case all you need to do is rename your Profile.ps1 to Microsoft.PowerShell_profile.ps1. SQLPS will not load the Microsoft.PowerShell_profile.ps1 profile only the host agnostic profile profile.ps1. There is work item for it here
http://www.codeplex.com/Pscx/WorkItem/View.aspx?WorkItemId=18417
Comment: I don't have PSCX installed on my machine.  And actually, I don't even have a profile location - PS C:\Users\dance2die> ii (split-path $profile -Parent)
Invoke-Item : Cannot find path 'C:\Users\dance2die\Documents\WindowsPowerShell' because it does not exist.
At line:1 char:3
+ ii <<<<  (split-path $profile -Parent)

Cannot start SQL Server PowerShell


Where exactly in the C++14 Standard does it allow the use of a user-defined conversion function in a direct-initialization?

Question: For example, in the snippet below the user-defined conversion function C::operator A() is implicitly invoked to convert an lvalue of type C into a prvalue of type A, which copy-initializes the variable a in a direct-initialization.
struct A {};
struct C { operator A() { return A(); }; };

int main()
{
     C c;
     A a(c);
}

I just want to know where this is described in the C++14 Standard. I have a feeling that the answer is in [over.match.copy]/1 bullet point (1.2), but I'm having a problem with the section title Copy-initialization by user-defined conversion.
Comment: [over.match.ref]. You are actually converting `c` for binding to the copy constructor's parameter.
Comment: [over.match.copy]. You are copy-initializing the `D` parameter from `c`. You can read the standard as well as I do.
Comment: I think that _copy-initialization by user-defined conversion_ refers to a constructor of the type `A(const C &)`, but that is not what your code uses. Your code just calls the copy constructor `A(const A&)` with an argument that happens to be the result of a user-defined conversion.
Comment: @rodrigo  That's exactly what I tried to describe in my question, i.e., the code is using the default copy-constructor to direct-initialize the variable `a` from `c`, using the conversion function `C::operator A()´.
Comment: @T.C. Then, what would you say about the presence of this sentence in [over.match.copy]/1 (1.2): `When initializing a temporary to be bound to the first parameter of a constructor where the parameter is of type "reference to possibly cv-qualified T" and the constructor is called with a single argument in the context of direct-initialization of an object of type "cv2 T", explicit conversion functions are also considered.`
Comment: s/copy/move/ in my previous comment. But I suspect that there's a defect here.
Comment: @T.C. Let's assume you are right. Take a look at [this snippet](http://coliru.stacked-crooked.com/a/0b887e9ab708bd35). Which paragraph does allow for the calling of the user-defined function in this second example?
Comment: @T.C. I'm referring to the apparent contradiction between the section title **Copy initialization by user-defined conversion** and the fact that `A a(c);` is a **direct-initialization**.
Comment: It's direct-initialization for `a`. Not for the parameter of `A`'s constructor.
Answer: There are two constructors on A that can be invoked with a single argument:
A(A const&); // copy constructor
A(A&& );     // move constructor

In either case, [dcl.init.ref] explains how we can initialize the reference:

A reference of type "cv1 T1" is initialized by an expression of type "cv2 T2" as follows:
  — If the reference is an lvalue reference and the initializer expression
    — is an lvalue (but is not a bit-field), and "cv1 T1" is reference-compatible with "cv2 T2", or
    — has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be converted to an lvalue of type "cv3 T3", where "cv1 T1" is reference-compatible with "cv3 T3" (this conversion is selected by enumerating the applicable conversion functions ([over.match.ref]) and choosing the best one through overload resolution),
    then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object).

We have references of type A or A const being initialized by an expression of type C, which is a class type not reference-related to A. To check if it can be converted to a reference-compatible type cv3 T3, we check [over.match.ref]:

The conversion functions of S and its base classes are considered. Those non-explicit conversion functions that are not hidden within S and yield type "lvalue reference to cv2 T2" (when initializing an lvalue reference or an rvalue reference to function) or "cv2 T2" or "rvalue reference to cv2 T2" (when initializing an rvalue reference or an lvalue reference to function), where "cv1 T" is reference-compatible with "cv2 T2", are candidate functions. For direct-initialization, [...]

Hence, for the copy constructor, we consider those conversion functions that yield A& and for the move constructor, we consider those conversion functions that yield A or A&&. We don't have the former, but we do have the latter: operator A().
This makes the move constructor of A a viable constructor, but not the copy constructor of A. Since we only have one viable candidate, it is trivially the best viable candidate.


Are there any limitations to # of columns in a SnappyData column table?

Question: As an example, Cassandra has a 2 billion column limit for a "row key".  Some high volume IoT apps could push that boundary and you should therefore, design accordingly, if using Cassandra.
Is there any size limitations similar to that with SnappyData's column table that I should "design" around as well?
Answer: No, there is no such design limit with Snappy column tables.
Answer: There is such limit:

we are not going to support anything more than a thousand columns for any of the table types for coming releases

https://github.com/SnappyDataInc/snappydata/issues/769#issuecomment-321240734


Positive Functions in $C_c(G)$

Question: Here is an excerpt from the book Principles of Harmonic Analysis by Deitmar and Echterhoff:

Write $C_c^+(G)$ for the set of all positive functions $f \in C_c(G)$ [Note that $G$ is a locally compact group]. For any two functions $f,g \in C_c^+(G)$ with $g \neq 0$ there are finitely many elements $s_j \in G$ and positive numbers $c_j$ such that for every $x \in G$ one has $f(x) \le \sum_{i=1}^n c_j g(s_j^{-1}x)$.

My first question is, how is it possible to have $g \neq 0$ on $G$, unless $G$ is compact, since $g$ is a function with compact support? Secondly, how do I prove the claim? I could use a/some hint(s).
Comment: For the first question, $g\neq 0$ just means $g$ is nonzero at *some* point, not necessarily every point.
Answer: The second part is a standard sort of compactness argument. Let $U=\{x:g(x)>0\}$.
This is an open subset of $G$. Then for $s\in U$, $sU=\{x:g(s^{-1}x)>0\}$
is also open.
Let $K$ be the support of $f$. It is compact, by hypothesis. So there are finitely
many $s_i$ such that $K\subseteq s_1U\cup\cdots\cup s_n U$. Define $h(x)=\sum_{i=1}^n
g(s_i^{-1}(x))$. Then $h(x)>0$ on $K$, and another compactness argument gives
some $c>0$ such that $f(x)\le cg(x)$ on $K$, and so on all of $G$.
Comment: For completeness, probably should say "This is a *nonempty* open subset..."
Comment: I don't see how $\{sU \mid s \in U \}$ forms an open cover of $K$. Perhaps you could clarify this.
Comment: If $x_0 \in G$ is such that $g(x_0) > 0$, then I believe $\{xx_0^{-1}U \mid x \in K \}$ forms an open cover of $K$.

Positive Functions in $C_c(G)$