Q:

Omitting an 'optional' step in gaussian-elimination causes different result

I'm trying to invert a matrix using the gaussian-elimination method
This is my start matrix
+---------+--------+
| 1 -2 -2 | 1 0 0  |
| -2 1 -2 | 0 1 0  |
| -2 -2 1 | 0 0 1  |
+---------+--------+

Using the top left 1 as pivot I can eliminate the first column, the result is

+---------+--------+
| 1 -2 -2 | 1 0 0  |
| 0 -3 -6 | 2 1 0  |
| 0 -6 -3 | 2 0 1  |
+---------+--------+

Selecting the middle -3 as pivot, I eliminate the second column, the result is

+---------+--------+
| -3 0 -6 |  1 2 0 |
| 0 -3 -6 | 2 1 0  |
| 0 0 -9  | 2 2 -1 |
+---------+--------+

And finally selecting the bottom right -9as pivot, I eliminate the last column, the result is

+--------+----------+
| 9 0 0  |  1 -2 -2 |
| 0 -9 0 | -2 1 -2  |
| 0 0 -9 | 2 2 -1   |
+--------+----------+

Simplifying gives

+-------+---------------+
| 1 0 0 | 1/9 -2/9 -2/9 |
| 0 1 0 | 2/9 -1/9 2/9  |
| 0 0 1 | -2/9 -2/9 1/9 |
+-------+---------------+

But when checking the answer online, I found out my result is wrong, it should be
+-------+---------------+
| 1 0 0 | 1/9 -2/9 -2/9 |
| 0 1 0 | -2/9 1/9 -2/9 |
| 0 0 1 | -2/9 -2/9 1/9 |
+-------+---------------+

(difference on the middle row, the numbers on the second row on the right side should be multiplied by -1)
I checked on different sites and they all showed me to divide row 2 by -3 after step 1.
For example on another site

What I do not understand is why they divide the second row by -3. Isn't this an optional step? Shouldn't it make no difference when not dividing by -3 or are multiple answers possible?

A:

After step 3 before step 4, the result should be
$$\begin{align*}
\pmatrix{-3&0&-6&1&2&0\\
0&-3&-6&2&1&0\\
0&0&-9&2&2&-1}
&\xrightarrow{R_1\to -3R_1+2R_3}
\pmatrix{9&0&0&1&-2&-2\\
0&-3&-6&2&1&0\\
0&0&-9&2&2&-1}\\
&\xrightarrow{R_2\to3R_2-2R_3}
\pmatrix{9&0&0&1&-2&-2\\
0&-9&0&2&-1&2\\
0&0&-9&2&2&-1}
\end{align*}$$


Q:

Por que, quando mudo o tamanho da janela, os componentes desenhados somem?

Construí uma aplicação usando o windowbuilder do eclipse. Nela, ao clicar com o mouse, uma figura é desenhada de acordo com o último botão selecionado.
Porém, quando mudo o tamanho da janela, todos os desenhos somem.
Após ler essa pergunta, esse tutorial, e esse artigo; suponho que devo fazer um override do método paint(Graphics g) e adicionar campos a uma classe que armazene os desenhos.
Mas não está claro para mim onde eu faria isto. Porque eu realmente não entendo o quê está acontecendo nos bastidores do código.
Classe criada com windowbuilder
public class PintarFiguras {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    PintarFiguras window = new PintarFiguras();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public PintarFiguras() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBackground(Color.GRAY);
        frame.getContentPane().setBackground(Color.GRAY);
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel canvas = new JPanel();
        canvas.setBackground(Color.WHITE);
        canvas.setForeground(Color.BLACK);
        canvas.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // pegar coordenadas
                int x = e.getX();
                int y = e.getY();

                Graphics g = canvas.getGraphics();

                Artista.desenhar(g,x,y);
            }
        });
        frame.getContentPane().add(canvas, BorderLayout.CENTER);
        canvas.setLayout(new CardLayout(0, 0));

        JToolBar toolBar = new JToolBar();
        frame.getContentPane().add(toolBar, BorderLayout.NORTH);

        JButton btnQuadrado = new JButton("quadrado");
        btnQuadrado.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Artista.setModo(MODOS.QUADRADO);
            }
        });
        toolBar.add(btnQuadrado);

        Component horizontalStrut = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut);

        JButton btnCirculo = new JButton("circulo");
        btnCirculo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Artista.setModo(MODOS.CIRCULO);
            }
        });
        toolBar.add(btnCirculo);

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut_1);

        JButton btnNada = new JButton("nada");
        btnNada.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Artista.setModo(MODOS.NADA);
            }
        });
        toolBar.add(btnNada);

        Component horizontalStrut_2 = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut_2);

        JButton btnLimpar = new JButton("limpar");
        btnLimpar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Graphics g = canvas.getGraphics();
                g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
                frame.setBackground(Color.WHITE);
            }
        });
        toolBar.add(btnLimpar);
    }

}

Enum das figuras a desenhar
public enum MODOS {
QUADRADO, CIRCULO, NADA}

Classe artista, que faz os desenhos
public abstract class Artista {
    private static MODOS modo = MODOS.NADA;

    public static MODOS getModo() {
        return modo;
    }

    public static void setModo(MODOS modo) {
        Artista.modo = modo;
    }

    /**
     * pinta um objeto de acordo com o modo
     * https://docs.oracle.com/javase/tutorial/2d/basic2d/index.html
     */
    public static void desenhar(Graphics g, int x, int y) {
        switch(modo){

        case QUADRADO:
            pintarQuadrado(g,x,y);
            break;

        case CIRCULO:
            pintarCirculo(g,x,y);
            break;

        case NADA:
            break;
        }
    }

    private static void pintarQuadrado(Graphics g, int x, int y) {
        g.fillRect(x, y, 20, 10);
    }

    private static void pintarCirculo(Graphics g, int x, int y) {
        g.drawOval(x, y, 20, 20);
    }

}

A:

Os componentes estão sumindo pois eles estão sendo só adicionados e pintados uma vez no JPanel, mas não há o callback do método paint(Graphics g), que é chamado sempre quando é necessário pintar a tela novamente, como no seu caso em um resize. Então quando você muda o tamanho da tela, os objetos só irão aparecer novamente quando você, pelo que eu vi no método, clicar em algum lugar da tela.
Praticamente o Java faz todo o trabalho sujo atráves do método paint e ele certifica de que os objetos vão ser desenhados após alguma mudança no painel.
Uma solução seria fazer sua classe PintarFiguras extender de JPanel e assim fazer o override do método paint e colocar o método desenhar(Graphics g, int x, int y) dentro.
Assim, no MouseListener em mouseClicked apenas chame o repaint.
Para referencia do JPanel, não é preciso criar um novo objeto, apenas chame this (no escopo da classe, claro)
Agora, as variáveis x e y que foram criadas dentro do mouseClicked, é só fazer elas no escopo da classe e atribuir os valores normalmente.
A classe PintarFiguras ficaria assim:
public class PintarFiguras extends JPanel {

private int x, y;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                new PintarFiguras();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public PintarFiguras() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {

    final JFrame frame = new JFrame();
    frame.setBackground(Color.GRAY);
    frame.getContentPane().setBackground(Color.GRAY);
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setBackground(Color.WHITE);
    this.setForeground(Color.BLACK);
    this.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            // pegar coordenadas
            PintarFiguras.this.x = e.getX();
            PintarFiguras.this.y = e.getY();

            repaint();
        }
    });
    frame.getContentPane().add(this, BorderLayout.CENTER);
    this.setLayout(new CardLayout(0, 0));

    JToolBar toolBar = new JToolBar();
    frame.getContentPane().add(toolBar, BorderLayout.NORTH);

    JButton btnQuadrado = new JButton("quadrado");
    btnQuadrado.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Artista.setModo(MODOS.QUADRADO);
        }
    });
    toolBar.add(btnQuadrado);

    Component horizontalStrut = Box.createHorizontalStrut(20);
    toolBar.add(horizontalStrut);

    JButton btnCirculo = new JButton("circulo");
    btnCirculo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Artista.setModo(MODOS.CIRCULO);
        }
    });
    toolBar.add(btnCirculo);

    Component horizontalStrut_1 = Box.createHorizontalStrut(20);
    toolBar.add(horizontalStrut_1);

    JButton btnNada = new JButton("nada");
    btnNada.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Artista.setModo(MODOS.NADA);
        }
    });
    toolBar.add(btnNada);

    Component horizontalStrut_2 = Box.createHorizontalStrut(20);
    toolBar.add(horizontalStrut_2);

    JButton btnLimpar = new JButton("limpar");
    btnLimpar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            limparTela();
        }
    });
    toolBar.add(btnLimpar);

    frame.setVisible(true);
}

public void paint(Graphics g){
    super.paint(g);
    Artista.desenhar(g, this.x, this.y);
}

public void limparTela(){
    Graphics g = this.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, getWidth(), getHeight());
}

EDIT: como @diegofm indicou, declarei o JFrame como final dentro do escopo do método, pois assim ele poderá ser chamado normalmente dentro de classes anônimas, como usado pelo OP.


Q:

NSLog, comments and releasing app

Do I need to delete all NSLog commands and every comment lines ( /*  [...]  */ )before releasing my application and putting it on Appstore?

A:

You can open NSLog only in DEBUG building.
#ifdef DEBUG
        #define NSLog(fmt, ...)     NSLog((@"%@ [Line: %d] %s " fmt),[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__)
#else
        #define NSLog(fmt, ...)
#endif

put it to the global header file or Prefix.pch

A:

NSLog: They should be removed.  As pointed out by @sosborn, NSLog is slow and can cause and even hide subtle timing and concurrency bugs.  For basic debugging NSLog is fantastic, but after you're done debugging you really should remove them.  @Elf Sundae's answer is fantastic and shows you how to make it so NSLogs will be displayed ONLY when debugging and automagically hid when you release your application.
Comments: No


Q:

Can I upgrade to a newer Ubuntu version on a Ubuntu-based distribution?

I'm currently running elementary OS Luna, which is based on Ubuntu 12.04. Can I upgrade my installation to have a Ubuntu 13.04 base, but still use elementary OS's desktop environment and applications? Would elementary OS's packages break because they expect the dependency versions in Ubuntu 12.04? Would I be better off installing 13.04, building elementary OS's packages from source, and then reconfiguring all my preferences for everything?

A:

It might work. Then again, it might not. Upgrading a distribution is a risky process at the best of times, I would be very surprised if you did not run into trouble. A better question would be whether it is even worth attempting?
Upgrading just to have the latest version is rarely worth the effort. You should upgrade to fix security holes or to get new features that you need. The basic principle is if it ain't broke, don't fix it. So, if all you want to do is get a newer version of a specific piece of software, upgrade that, not your system.
In any case, what you are proposing means you basically want to replicate the work that the elementary OS devs are doing. Elementary is basically Ubuntu + Elementary stuff. You are suggesting that you should upgrade to a newer Ubuntu and then install the elementary packages. If that were as trivial as you seem to expect, there would be little point in releasing elementary as an OS.
However, one of the great features of Debian's package management system is that it deals with package dependencies for you. So, if you want to get a newer version of something, modify your /etc/apt/sources.list (which presumably already contains the Ubuntu repositories) and make it point to a newer version of Ubuntu. You can then run apt-get update to refresh your sources and have access to the newer versions:

Change your sources.list from this (or similar)
deb http://archive.ubuntu.com/ubuntu/ precise main restricted

to this
deb http://archive.ubuntu.com/ubuntu/ raring main restricted

Run sudo apt-get update and then install a newer version of your favorite software, vlc for example:
sudo apt-get install vlc

Elementary OS also provides a bleeding edge repository (which you use at your own risk, it will not be as stable as the released version), you can find it here.
Finally, if for whatever reason you really really want to risk this and upgrade your distribution (I stress there is very little point in doing this) you can try. However, there is no guarantee that the newer versions of the various core libraries you will install will be compatible with the Elementary packages. You will almost certainly end up having to tweak various things and I would bet it would take you longer than doing a fresh install.


Q:

AngularJS - Incorrect order in ng-repeat

I have chaps defined in my controller like this:
  $scope.chaps =  [{"id":"1","chap_no":"1","name":"chap 1"},
                  {"id":"2","chap_no":"2","name":"chap 2"},
                  ...
                  {"id":"14","chap_no":"14","name":"chap 14"},
                  {"id":"15","chap_no":"15","name":"chap 15"}];

and in the view, I have:

{{ch.name}}

but I'm getting the wrong order (10 after 1, 20 after 2, and so on)
chap 1, chap 10, chap 11, chap 12, chap 13, chap 14, chap 15, chap 2, chap 3, ...

Here's the plunkr: http://plnkr.co/edit/Pc84ooB6dp2zoHXeawYn?p=preview
Can anyone tell me what I'm doing wrong here

A:

Your chap_no property is a string so its ordered as a string.
You can create a custom filter like:
app.filter('customSort',function(){
    function sort (a, b) {
        if (a > b) { return 1; }
        if (a < b) { return -1; }

        return 0;
    }

    return function(arrInput, prop) {
        var arr = arrInput.sort(function(a, b) {
            return sort(+a[prop], +b[prop]);
        });
        return arr;
    }
})

So then in your html you can use the filter like this:

{{ch.name}}

Example: http://plnkr.co/edit/UWvinthK9r0zgRbHMCGd?p=preview


Q:

How to change the source code of minix in a local repository

I've been wondering how to solve the following problem. I'm currently learning how to modify an OS's source code to my liking, working example being A.S.Tanenbaum's minix.
Say I run minix with qemu and I redirect the ssh port to localhost:10022 (using -net user,hostfwd=tcp::10022-:22), so that I can ssh -p 10022 user@localhost to connect to the system that runs on qemu.
Now, minix's source code is located in /usr/src. I want to have this code locally on my machine -- best in a git repository -- and be able to modify it and then push it and build on the virtual machine.
To summarize, I want:

To have a copy of minix's /usr/src on my machine, in a git repository
To be able to git push it from my machine (or anything like that), so that if my changes break the system completely, I can start over from my base image of minix

I have tried making /usr/src into a git repository that I can clone to my local machine. However, apparently pushing to a non-bare repository is not advisable, and a bare git repository, which doesn't contain any uncommited files, doesn't seem like the way to go.
Also, I would prefer not to brute-force it by just pushing / pulling to another remote.
I would appreciate any hints on how to set up my repositories to create my desired workflow.

A:

Host: just one non-bare repository (+ backups).
VM: one bare and one non-bare repository in /usr/src.
Initial setup: create a non-bare repository in /usr/src in VM. Add and commit everything. Clone the not-bare repo to a bare repository somewhere. Clone from bare repo at VM to not-bare at the host.
Workflow: Edit sources at the host, add and commit. Push from host to the bare repo at VM. Pull from bare to not-bare at VM and compile.
Pulling from bare to not-bare can be made automatically using "remote deploy" hook (post-receive or post-update).


Q:

Dürr vs. trocken

Dictionaries show both as "dry, arid" etc., wiktionary shows them as synonyms. I asked in a chat, and got replies about liquids on the outside or inside, which confused me even further.
What's the difference between the two, if any? Are they interchangeable?

A:

trocken: dry or arid, used for objects, weather and land.
also: metaphorical dry as in dry wit or dry wine
noun: Trockenheit - dryness
comparative always means drier
dürr: dry or arid, used for land and soil, usually not single objects
also: very thin (plants or also persons), dried out (verdorrt)
noun: Dürre - drought
comparative means thinner


Q:

Debugging NSImage's failure to open a BMP image file

var fileManager:NSFileManager = NSFileManager()
var imagePath:String = "/Users/dumbledad/Documents/flower.bmp"
var msg:String = (fileManager.fileExistsAtPath(imagePath) ? " exists" : " does not exist")
print(imagePath + msg)
var imageNS = NSImage(named: imagePath)!

When I run the app I see

/Users/dumbledad/Documents/flower.bmp exists
fatal error: unexpectedly found nil while unwrapping an Optional value

and the error Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
How do I debug why NSImage is failing to open the image file? It does display correctly if I open the image in Preview from Finder.

A:

To use the NSImage(named:) initializer, the image file has to be embedded in your Xcode project.
Example for an image name "hello.jpg":
let img = NSImage(named: "hello")

This will only work if the image exists inside your app.
Also currently you're passing the path to the NSImage initializer, not just the file name as you should with this named initializer.
On the other hand, to load an image from the filesystem (this time, not included in your app), you can use NSImage(contentsOfFile:) with your path or NSImage(contentsOfURL:) with an NSURL of your path.


Q:

Equivalence of two antiderivatives involving trigonometric/hyperbolic functions

I am struggling to see how two antiderivatives of the same function—obtained in two different ways—are equivalent (what I mean by equivalent is that they differ from just a constant), if they even are equivalent.
The function in question is
$$
\begin{align}
f \colon \quad \{x\in\mathbb{R} \mid e^{2x} \ge 9\} &\to\mathbb{R}\\
x &\mapsto f(x) = \frac{1}{\sqrt{e^{2x} - 9}}
\end{align}\,.
$$
Wanting to find $I = \displaystyle\int f(x)\mathrm{d}x$, I proceeded as follows.
$$
\int \frac{1}{\sqrt{e^{2x} - 9}}\mathrm{d}x = \frac{1}{3} \int \frac{1}{\sqrt{\left(\dfrac{e^x}{3}\right)^2 - 1}}\mathrm{d}x\,.
$$
Since $\left(\frac{e^x}{3}\right)^2 \in[1,+\infty]$ and the image of $\cosh$ is $[1, +\infty)$,
$$\exists t \in \mathbb{R}\colon\quad \left(\dfrac{e^x}{3}\right)^2 = \cosh^2t\\
\Rightarrow \mathrm{d}x = \tanh t\ \mathrm{d}t\,.$$
Thus,
$$
I = \frac{1}{3} \int \frac{\tanh t}{\sqrt{\cosh^2 t - 1}}\mathrm{d}t = \frac{1}{3}\int \mathrm{sech}\ t\ \mathrm{d}t\,.
$$
Here is where the two different ways diverge. The first thing I tried was using the hyperbolic function's definition.
$$
I = \frac{1}{3}\int \frac{2e^t}{e^{2t} + 1}\ \mathrm{d}t\,;
\qquad\text{let}\quad
\begin{cases}
u = e^t\\
\mathrm{d}u = e^t\mathrm{d}t
\end{cases}\\ \\
\Rightarrow I = \frac{2}{3} \int \frac{1}{u^2 + 1}\ \mathrm{d}u = \frac{2}{3} \arctan u + C = \frac{2}{3} \arctan e^t + C = \\
= \frac{2}{3} \arctan e^{\text{arccosh} \frac{e^x}{3}} + C = \frac{2}{3} \arctan e^{\ln\left(\frac{e^x + \sqrt{e^{2x}-9}}{3}\right)} + C =\\
= \frac{2}{3} \arctan \left(\frac{e^{x} + \sqrt{e^{2x}-9}}{3}\right) + C\,.
$$
The alternative solution is
$$
I = \frac{1}{3}\int \mathrm{sech}\ t\ \mathrm{d}t = \frac{1}{3}\int \frac{\cosh t}{\cosh^2 t}\ \mathrm{d}t = \frac{1}{3}\int \frac{\cosh t}{1 +\sinh^2 t}\ \mathrm{d}t =\\
= \frac{1}{3}\arctan \left(\sinh t\right) + C = \frac{1}{3}\arctan \left(\sinh \left(\mathrm{arccosh} \frac{e^x}{3}\right)\right) + C = \frac{1}{3}\arctan \frac{\sqrt{e^{2x} - 9}}{3} + C\,.
$$
I don't see any obvious way in which $$\frac{2}{3} \arctan \left(\frac{e^x + \sqrt{e^{2x}-9}}{3}\right) + C$$ and $$\frac{1}{3}\arctan \frac{\sqrt{e^{2x} - 9}}{3} + C$$ are equivalent antiderivatives, although they do seem to be.

Update
Following Yuriy S's suggestion, I tried the following. Let
$$
s = \frac{\sqrt{e^{2x} - 9}}{3}\,.
$$
Thus,
$$
\arctan s = 2\arctan \frac{\sqrt{1+s^2}-1}{s} = 2\arctan \frac{\sqrt{1+\frac{e^{2x}-9}{9}}-1}{\frac{\sqrt{e^x - 9}}{3}} = 2\arctan \frac{3e^x-3}{\sqrt{e^x - 9}}\,.
$$
On the other hand, let
$$
r = \frac{e^x + \sqrt{e^{2x} - 9}}{3}\,,
$$
so that
$$
\frac{1}{r} = \frac{3}{e^x + \sqrt{e^{2x} - 9}} \cdot \frac{e^x - \sqrt{e^{2x} - 9}}{e^x - \sqrt{e^{2x} - 9}} = \frac{e^x - \sqrt{e^{2x} - 9}}{3}\,.
$$
I was striving to apply the formula
$$
\arctan x + \arctan \frac{1}{x} = \pm\frac{\pi}{2}
$$
but I got stuck here.

A:

Whenever you face this problem, you can check the answer by differentiating. If
$$
F(x)=\frac{2}{3} \arctan \left(\frac{e^{x} + \sqrt{e^{2x}-9}}{3}\right) + C
$$
then
\begin{align}
F'(x)
&=\frac{2}{3}\frac{1}{1+\left(\dfrac{e^{x} + \sqrt{e^{2x}-9}}{3}\right)^2}
  \frac{1}{3}\left(e^x+\frac{e^{2x}}{\sqrt{e^{2x}-9}}\right) \\[4px]
&=\frac{2}{9+e^{2x}+e^{2x}-9+2e^x\sqrt{e^{2x}-9}}
  \frac{e^x(e^x+\sqrt{e^{2x}-9}\,)}{\sqrt{e^{2x}-9}} \\[4px]
&=\frac{1}{\sqrt{e^{2x}-9}}
\end{align}
We can try differentiating the second function
$$
G(x)=\frac{1}{3}\arctan\frac{\sqrt{e^{2x}-9}}{3}+C
$$
and we get
\begin{align}
G'(x)
&=\frac{1}{3}\frac{1}{1+\left(\dfrac{\sqrt{e^{2x}-9}}{3}\right)^2}
  \frac{1}{3}\frac{e^{2x}}{\sqrt{e^{2x}-9}} \\[4px]
&=\frac{1}{9+e^{2x}-9}\frac{e^{2x}}{\sqrt{e^{2x}-9}} \\[4px]
&=\frac{1}{\sqrt{e^{2x}-9}}
\end{align}
Good job in both cases.
You can easily compute the constant difference by the limits at $\infty$ (with $C=0$ in both cases):
$$
\lim_{x\to\infty}F(x)=\frac{2}{3}\frac{\pi}{2}=\frac{\pi}{3}
\qquad
\lim_{x\to\infty}G(x)=\frac{1}{3}\frac{\pi}{2}=\frac{\pi}{6}
$$
Alternative solution: substitute $\sqrt{e^{2x}-9}=3t$, so
$$
x=\frac{1}{2}\log(9(t^2+1))
$$
and
$$
dx=\frac{t}{t^2+1}\,dt
$$
so the integral becomes
$$
\int\frac{1}{t^2+1}\,dt=\arctan t+C=\arctan\frac{\sqrt{e^{2x}-9}}{3}+C
$$


Q:

Multithreading working perfectly until I hit the com object

I'm using com interop to talk to some physical piece of hardware.
When I need the current reading from the hardware I have a nice elaborate piece of threading code that keeps it off my UI thread so that I don't lock up the UI while I query the hardware since sometimes it can take as much as 1-2 minutes (although usually more like 1-5 seconds).
So once I step into the com object it bounces back to the main UI thread and the UI becomes busy during the duration of the reading.
The main app is a .net WPF app, so it STA by default.
The COM object is created on the main thread, but it's created my a singleton factory, so all of these objects are created by the same few lines of UI.
I'd love to show some code, but it's not like the stuff is in just a few lines of code.
What kind of work arounds are there for this behavior?
I'd also love to be able to read from multiple com object simultaneously.
If were to create background threads to spin up these com objects inside my object facotry.  How do I keep them alive to handle the work that gets marshaled back to them?

A:

I have it working.
Previously my constructor worked like:
internal class Device
{
    private ComDeviceLibrary.UberDevice myDevice;

    internal Device(DeviceInitObject myInitOptions)
    {
        myDevice = new ComDeviceLibrary.UberDevice();
    }
}

Now if I do this:
internal class Device
{
    private ComDeviceLibrary.UberDevice myDevice;

    internal Device(DeviceInitObject myInitOptions)
    {

        AutoResetEvent createHandle = new AutoResetEvent(false);
        Thread creationThread = new Thread(CreateDevice);
        creationThread.IsBackground = false;
        creationThread.SetApartmentState(ApartmentState.MTA);
        creationThread.Start(createHandle);
        createHandle.WaitOne();
    }

    private void CreateDevice(object objWaitHandle)
    {

        myDevice = new ComDeviceLibrary.UberDevice();
        ((AutoResetEvent)objWaitHandle).Set();
    }
}

It works!


Q:

Where do these nan come from?

EDIT :
I had some nan in my data but the anwser is correct, you have to initialize your weight with some noise !
Thanks !
I'm doing my first script with tensorflow. I had some problem printing value but now i got it.
I wanted to try a simple Logistic regression to start, i'm working on kaggle titanic dataset.
My problem is that i don't know why but i got some nan in my Weight and Bias so in my y (prediction) vector too ...
EDIT :
My weight was initialized at 0 so i was a null gradient i guess.
According to the answer provided i add
W = tf.truncated_normal([5, 1], stddev=0.1)

instead of
 W = tf.Variable(tf.zeros([5, 1])) #weight for softmax

But i still got some issues. My b variable a y variable are still nan and when i tried the same thing for b i got the following error :
ValueError: No variables to optimize
I tried several way to assign my biais of a tensor [1, 1] but it looks like i'm missing something
looks like y is nan because cross entropy is nan because b is nan... :(
END - EDIT
i read this post (Why does TensorFlow return [[nan nan]] instead of probabilities from a CSV file?) who give me an hint, during my cross entropy calcul 0*log(0) return nan so i applied the solution given, that is to add 1e-50 like :
cross_entropy = -tf.reduce_sum(y_*tf.log(y  + 1e-50))
unfortunatly it wasn't the problem i guess, i still got nan everywhere :(
this is the interisting (i guess) part of my very simple model :
x = tf.placeholder(tf.float32, [None, 5]) #placeholder for input data

W = tf.truncated_normal([5, 1], stddev=0.1)

b = tf.Variable(tf.zeros([1])) # no error but nan
#b = tf.truncated_normal([1, 1], stddev=0.1) Thow the error descript above
#b = [0.1] no error but nan

y = tf.nn.softmax(tf.matmul(x, W) + b) #our model -> pred from model

y_ = tf.placeholder(tf.float32, [None, 1])#placeholder for input

cross_entropy = -tf.reduce_sum(y_*tf.log(y)) # crossentropy cost function

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
init = tf.initialize_all_variables() # create variable

sess = tf.InteractiveSession()
sess.run(init)

testacc = []
trainacc = []
for i in range(15):
    batch_xs = train_input[i*50:(i + 1) * 50]
    batch_ys = train_label[i*50:(i + 1) * 50]

    result = sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(y,y_)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run([accuracy, W, y] , feed_dict={x: test_input, y_: test_label}))

It returns me a 0.0 accuracy of course and after 2 array of nan
I tried to print values everywhere but nan everywhere :'(
Do somebody has an idea ? I may forgot something or doing it wrong
The thing is that i tried a similar script with mnist (google tutorial) with included data and it's works (no nan). I get my data with panda reading the csv file.
Thanks for reading !

A:

You are getting a division by zero in tf.nn.softmax since your weight matrices are zero. Use a different normalization method, like truncated_normal from the MNIST example


Q:

File name Invalid character reading from txt file

Hello following this post Read a text file line by line to make multiple plots, I created a latex code to read a file that contains the names of eps files I want to plot.
My code is:
\documentclass[]{article}

\usepackage{url}
\usepackage[T1]{fontenc}

\newcommand\noblankfileline{\expandafter\noblankaux\fileline\relax}
\def\noblankaux#1 \relax{#1}

\begin{document}
 \newread\file
 \openin\file=accretion.txt
 \loop\unless\ifeof\file
  \read\file to \fileline % Reads a line of the file into \fileline
  \if\relax\fileline\relax\else
    \begin{figure}[!ht]
    \centering
    \includegraphics[width=10cm,height=10cm]{"./pictures/\noblankfileline"}
    \end{figure}
  \fi
 \repeat
 \closein\file
\end{document}

and the txt file is something like this:

run20150131_Sediment_Accretion_Erosion_2015-01-31_23h-30m.eps
  run20150228_Sediment_Accretion_Erosion_2015-02-28_23h-30m.eps
  run20150331_Sediment_Accretion_Erosion_2015-03-31_23h-30m.eps
  run20150430_Sediment_Accretion_Erosion_2015-04-30_23h-30m.eps

When I compile it I obtain this error:
! Text line contains an invalid character.
<read 1> r
           u n 2 0 1 5 0 1 3 1 _ S e d i m e n t _ A c c r e t i o n _ E r o...
l.22         \repeat

it likes the code doesn't recognise the input from the file as a single word.
Do you have any idea how to fix it?
Thanks!
Ciccio

A:

daleif's answer is best, but I thought it worthwhile to explain why your approach failed on compile.  It is an expansion issue.  It would seem that the \includegraphics searches the filename in search of a file extension.  The problem is that the search occurs before \noblankfileline was expanded, and so no extension is noted.  Then, when \includegraphics finally gets around to expanding \noblankfileline, it doesn't know what to do with the extension attached to the filename.
The fix provided in the MWE, is to expand \noblankfilename in an \edef and use that expanded macro as the argument to \includegraphics.  Alternately, as I said in an earlier comment, you could modify \noblankaux to strip file extensions from the list, since \includegraphics will search all valid extensions looking for a fit.  One would do that with the following redefinition: \def\noblankaux#1.#2 \relax{#1}.
But as I said, daleif's answer is better for your set of conditions, because you supply the file extension in your list, and therefore a spurious space never appears between the filename and the file extension.  So the whole \noblankfilename is not really necessary in your case.
\documentclass[]{article}
\usepackage{graphicx}
\usepackage{filecontents}
\begin{filecontents*}{accretion.txt}
run20150131_Sediment_Accretion_Erosion_2015-01-31_23h-30m.png
%run20150228_Sediment_Accretion_Erosion_2015-02-28_23h-30m.eps
%run20150331_Sediment_Accretion_Erosion_2015-03-31_23h-30m.eps
%run20150430_Sediment_Accretion_Erosion_2015-04-30_23h-30m.eps
\end{filecontents*}

\usepackage{url}
\usepackage[T1]{fontenc}

\newcommand\noblankfileline{\expandafter\noblankaux\fileline\relax}
\def\noblankaux#1 \relax{#1}

\begin{document}
 \newread\file
 \openin\file=accretion.txt
 \loop\unless\ifeof\file
  \read\file to \fileline % Reads a line of the file into \fileline
  \if\relax\fileline\relax\else
    \begin{figure}[!ht]
    \centering
    \edef\tmp{./pictures/\noblankfileline}
    \includegraphics[width=3cm,height=3cm]{\tmp}
    \end{figure}
  \fi
 \repeat
 \closein\file
\end{document}


Q:

How to solve "Class not found" issue in WSO2 ESB REST API deployed from CARs?

This is know issue, please refer.
https://wso2.org/jira/browse/ESBJAVA-3246
Currently, I create Sequences and refer this Sequences in outSequence. from my testing, this solved issue when I deployed from CARs. But I don't know, does this is a good way to solve it?

A:

This has been fixed in ESB 4.9.0 and most probably 4.9.0 will be release within this week.


Q:

Is restricting endorsement using author's name compatible with GPL?

I would like to link a GPL project to another project with the following clause in its license:

The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

Is this software compatible with GPL v2 or v3?

A:

The modified BSD license (also called BSD 3-Clause License) contains the exact same sentence:

(3)The name of the author may not be used to
      endorse or promote products derived from this software without
      specific prior written permission.

The Free Software Foundation lists the modified BSD license as GPL compatible.


Q:

Plotting and finding roots of bessel functions

I am trying to plot roots of a function that is composed of multiple bessel functions being added and multiplied in Matlab.  The equation is Jm(omega)*Ik(omega)+Im(omega)*Jk(omega) where Jm is the bessel function of the first kind of order m (besselj). Im is the modified bessel function of the first kind of order m (besseli).  For each mode m=o,1,2,...and n=1,2,3...  The frequency omega(mn) is the corresponding root of the listed equation. m=0,1,2 n-1,2,3,4.  I need to solve the equation for the 12 roots.  I am new to Matlab and this is a little out of my league. So far I have this code but I wasn't sure if I needed the variable omega in the script or not.  I have also looked at other people's questions on the suject but didn't see any quite like this.  The plots I have seen look nothing like mine which tells me I am probably wrong.  Thanks for any help.
m=(0:2); k=(1:3); n=(1:4);
Jm=besselj(m,n');
Ik=besseli(k,n');
Jk=besselj(k,n');
Im=besseli(m,n');
g=Jm.*Ik+Im.*Jk
plot(g)

A:

Plotting
besselj and besseli take what you call omega as their second parameter, so to plot your function you should try something like
m=0; k=1; omega=0:0.02:10;
Jm=besselj(m,omega);
Ik=besseli(k,omega);
Jk=besselj(k,omega);
Im=besseli(m,omega);
g=Jm.*Ik+Im.*Jk;
plot(omega,g);
hold all;
plot(omega,0,'k');
axis([min(omega) max(omega) -100 100]);

This shows you that for m=1, k=1 the first zeros are around 3.2, 6.3 and 9.4:

Finding the roots numerically
You could implement Halley's method for your function g, similar to how the roots of besselj are determined in the MatlabCentral file linked by Cheery.


Q:

What is the difference between "apart", "except", "other than" and "besides"?

Do the following phrases have the same meaning or are there differences?

Fortunately, apart from a broken toe, she was not badly hurt after the car accident.
Fortunately, except for a broken toe, she was not badly hurt after the car accident.
Fortunately, other than a broken toe, she was not badly hurt after the car accident.
Fortunately, besides a broken toe, she was not badly hurt after the car accident.

A:

Fortunately, apart from a broken toe, she was not badly hurt after the car accident.
-- while apart itself is acceptable, it is awkward in this particular example.
Fortunately, except (for) a broken toe, she was not badly hurt after the car accident.
-- best option that conveys the meaning appropriately in the context.
Fortunately, other than a broken toe, she was not badly hurt after the car accident.
-- fine; can be an alternative to except, which is the right word in this case.
Fortunately, besides a broken toe, she was not badly hurt after the car accident.
-- inappropriate: avoid besides when showing an exception.


Q:

How to encourage coworkers to engage in knowlege-transfer?

We are a small company, with projects requiring 1 to ~5 coworkers at a time, that are nearly never in our own offices. In short, we are highly distributed and have very rare chances to spread knowledge internally.
Now we want to change that and achieve some progress in knowledge management, firstly by using our centralised wiki, using internal articles, reports and themed topics related to the fundamentals of our work, that should be written and reviewed by our coworkers.
The wiki has been there for a long time already. It does not look very nice and usabilty could be far better, but it is usable. As it was an expensive piece of software there is currently no chance to replace it with another.
The point of this question is, how can we motivate our coworkers to contribute to the wiki? What kind of incentives (other than money) can be practical?

A:

You can hold an online knowledge sharing session,in each session a team member will present a topic in his/her areas of expertise and then s/he uploads it to the wiki then the other team members share their feedback on the wiki page.
If the time difference will make it hard to meet online then, the team can agree on reading an article or watch a video on a specific topic (e.g.flat design), then share their thoughts in the same post (shouldn't be long)
At first, you may want to make knowledge sharing time from the official working hours to emphasis the importance of it.
Generally they need to see the value of their contribution to be excited about the idea of knowledge sharing, for example if a team member posted an article it would be great to hold a meeting with the team,even for 30 mins to give their feedback and share their thoughts :)

Once the team members feel that they have an audience that is looking forward for what they'll share, they will be more interested in researching and sharing their knowledge.
Hope this helps!


Q:

Build project using LibGit2Sharp, have it run on .NET & Mono (Windows, Linux, Mac)

Using LibGit2Sharp 0.22.0-pre20150606092322 (with NuGet), when I build my project on Windows, the NativeBinaries folder only includes .dll files, which I assume don't work on Linux (unless they're .NET libraries). Attempting to run the project on Linux causes an exception:

System.TypeInitializationException: An exception was thrown by the type initializer for LibGit2Sharp.Core.NativeMethods ---> System.DllNotFoundException: git2-ff8d635

I assume if I tried to build my project on Linux, it would contain the correct libraries, though no Windows ones. Is there a way I can build the project on one system and provide a download that works on all systems?
edit: Actually, I just built the project on Linux using MonoDevelop. The output does include a "packages" folder which contains a .so file in some sub-folder, but I still get the same exception if I just run it like that.

A:

Since you're using the latest prerelease LibGit2Sharp package, then you should also have a LibGit2Sharp.NativeBinaries package, which includes the native git2 libraries that LibGit2Sharp needs. In that package we include the following versions:

32-bit Windows (dll)
64-bit Windows (dll)
32 & 64-bit Mac (dylib), one file supports both architectures
64-bit Linux (so)

If you're trying to run on 32-bit linux, then there isn't a pre-built library included for that. What distro/architecture are you running?
When you install the LibGit2Sharp package, an MSBuild properties file is added to your project, and that is what handles copying the native binaries to the correct location as part of the build process.
If you're building on linux, then the build output should contain libgit2-ff8d635.so in the same directory as LibGit2Sharp.dll.
As long as your project isn't doing something that requires shadow copying your assemblies, that should be enough for mono to find and load the linux library.
If you are, for example if it's an asp.net project, then you have to make sure that the native linux library loader can find .so file, either by setting the LD_LIBRARY_PATH, or actually installing it.
As far as building it once goes, since all of the pre-build native images are already sitting in the NativeBinaries package, your release process could include them directly from there.


Q:

Backbone View without model not rendering Handlebars Template

I am trying to render handlebars template in backbone view but its not rending in both chrome and firefox. Please help me on this. I am not finding errors is console as well.All sources are loading fine.I am alerting during rendering thats works fine.I am not using any model here, only Backbone View, Handlebar Template and HTML,
Code:
<!DOCTYPE html>

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="loginStyle.css">

A:

Try adding the var next to the View constructor then use a different variable name to create the View instance.
$(document).ready(function(){
    var compile = $("#landingpageTemplate").html();
    var LandingpageView = Backbone.View.extend({
        template: Handlebars.compile(compile),
        initialize: function() {
          this.render();
        },
        render: function() {
            alert ("hello");
            this.$el.html(this.template(this.model));
            return this;
        }
    });
    var landingpageView = new LandingpageView();
});


Q:

Does it matter in which ability you put a mutagen?

Is the the mutagen always active, or only active when the ability with it is in use?

A:

Mutagens are passive increases to character abilities. It does not matter what ability you mutate with a mutagen, as all mutagen bonuses are always active, all the time.


Q:

How many subsets $T$ of $X$ are such that the sum of the elements of $T$ is divisible by 5?

Let the $X = \{1,2,\ldots,2000\}$. How many subsets $T$ of $X$ are such that the sum of the elements of $T$ is divisible by 5?

A:

I compute the number as:
22962613905485090484656664023553639680446354041773904009552854736515325227847406277133189726330125398368919292779749255468942379217261106628518627123333063707825997829062456000137755829648008974285785398012697248956323092729277672789463405208093270794180999311632479761788925921124662329907232844394066536268833781796891701120475896961582811780186955300085800543341325166104401626447256258352253576663441319799079283625404355971680808431970636650308177886780418384110991556717934409897816293912852988275811422719154702569434391547265221166310540389294622648560061463880851178273858239474974548427800576

I found this as follows:
Let $S_j(n)$ be the number of subsets of $\{1,2,\ldots,n\}$ whose sum is congruent to $j$ modulo $5$.
When $n \geq 5$, since any subset of $\{1,2,\ldots,n\}$ is the union of a unique pair of subsets, one subset of $\{1,2,\ldots,n-5\}$ and one subset of $\{n-4,n-3,n-2,n-1,n\} \equiv \{0,1,2,3,4\} \pmod 5$, we have the recurrence $$S_j(n) = \sum_{i=0}^4 S_i(n-5)S_k(5)$$ where $k$ is the solution to the congruence $i+k \equiv j \pmod 5$.
I implemented this in GAP using the following code (note: GAP uses indices starting at 1):
S:=List([1..5],i->List([1],j->Number(Combinations([1,2,3,4,5]),S->Sum(S) mod 5=i mod 5)));

The above initialises S with the boundary conditions, i.e., when $n=5$.
M:=[ [ 5, 1, 2, 3, 4 ],
     [ 4, 5, 1, 2, 3 ],
     [ 3, 4, 5, 1, 2 ],
     [ 2, 3, 4, 5, 1 ],
     [ 1, 2, 3, 4, 5 ] ];

The matrix M gives the solutions to $i+k \equiv j \pmod 5$.
for r in [2..400] do
  for j in [1..5] do
    S[j][r]:=Sum([1..5],i->S[i][r-1]*S[M[i][j]][1]);
  od;
od;

The above just implements the recurrence.
As some quick sanity checks:  (a) the code below checks that the counts sum to $2^n$ for any given $n$ (i.e. the number of subsets of $\{1,2,\ldots,n\}$).
for r in [2..400] do
  s:=Sum(List([1..5],i->S[i][r]));
  t:=2^(5*r);
  if(s<>t) then Print(r," failed!\n"); fi;
od;

(b) we check that the answer is divisible by $2^{400}$ (as pointed out by Ross Millikan).
gap> S[5][400] mod (2^400);
0


Q:

need help using dll in Visual Studio (C#)

I am trying to use an dll, i added a reference to it and then tried to use it in my project, but it says that it doesnt recognize the name space. Sorry i am not really experienced.

A:

The using directive requires a namespace. Namespaces are separated by dots, making Fasm.NET two namespaces where NET would be a child of Fasm, which I guess is not the case for the library. The IntelliSense menu should show you examples of existing namespaces once you type the first character(s).
Though, judging from the Fasm library's sources it seems the complete namespace is:
Binarysharp.Assemblers.Fasm

Try that in your using statement and it should work.


Q:

SQL: Working With Columns That You've Just Created in SQL Server

Sorry if this question has already been posted, but I'm fairly new to SQL server and can't find the answer I'm looking for. (Maybe I'm just unable to word it properly.. oh well)
So basically, I'm trying to work with a column that's just been created in my query
as a very simple example:
SELECT q.Account, q.Quantity, q.Price,

CASE
    WHEN q.Account = '49661B' THEN (q.Quantity * q.Price)

END AS [USD Total Value],

[USD Total Value] * 1.34 as [CDN Value]

FROM Quote as q

I am trying to use that column I just named [USD Total Value] to convert in CDN as a new column.  But I'm getting an error [Invalid column name 'USD Total Value']
This is obvioulsy very basic, but I'd really appreciated some help on that.
Many Thanks!

A:

You need to do it as a subquery
select *,

[USD Total Value] * 1.34 as [CDN Value]

from (

      SELECT q.Account, q.Quantity, q.Price,

         CASE
         WHEN q.Account = '49661B' THEN (q.Quantity * q.Price)

         END AS [USD Total Value]

      FROM Quote as q

)x

This should give you what you require
UPDATE
As UUerdo said
Aliases from SELECT expressions may not be referenced anywhere within the query (at that level... aliases in the SELECTs of a subquery may be referenced in the outer query)


Q:

Emacs HTML Export Options (Post- and Preamble)

Is there a way I can declare some HTML pre- and post-amble content in a buffer (and only applying to that buffer) itself without needing to create a new org-publish-project-alist project or customizing the default org-html-preamble and org-html-postamble?

A:

The variables org-html-preamble and org-html-postamble (and org-html-postamble-format) are available to allow you to modify these components. This is explained in the org mode manual node (org) HTML preamble and postamble
If you set these variables as 'local variables', the changes will only apply to the current buffer. i.e., append the following to your .org file:
# Local Variables:
# org-html-preamble: "MY PREAMBLE \
#  which can span multiple lines, if we escape the newlines!\
#  literal newlines need to be inserted like this:\n Next line."
# End:

You will need to reload the file, or call M-x normal-mode, for this to take effect.


Q:

Making views accessible through URL - Drupal

I have configured the standard "frontpage" view in order to display a list of nodes, just by displaying a field (the banner image).

Unfortunately the URL /frontapge does not return the previewed template, but the same page that would get displayed before the views module was installed.

Help would be much appreciated.

A:

How have you configured the url for the page in the view?
You can make the url to whatever you like. All you need to do, to make it the actual front page, is to write the same url in the front page setting.
Also when it comes to urls and changes in the url system, it's a good idea to clear cache, as it sometimes can be the source to such problems.


Q:

What I/O function should I use to write to a .bmp file?

The example code I've seen for this seems to use standard C file output functions, but I'd like to make it in C++.
I tried using fsteam functions to do it, but no data is written to the .bmp file at all.
So far, I have tried the standard <<, put, and write, and none of these work. If I open it up with a hex editor, the file is still empty.
It's odd, since the input functions work fine.
Here's a piece of the code I used to test to see if it was working:
output.open("WHITE.bmp");
output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
output.put('M');

And the rest of the code:
#include <iostream>
#include <fstream>

using namespace std;
typedef unsigned char  byte;
typedef unsigned short dbyte;

struct BMPINFO
{
    int width;
    int height;
};

int main()
{
    ifstream sourcefile;
    ofstream output;

    int threshold = 150;

    sourcefile.open("RED.bmp");

    if(sourcefile.fail())
    {
        cout << "Could not open RED.bmp" << endl;
        return 1;
    }

    if(sourcefile.get() == 'B')
    {
        if(sourcefile.get() == 'M')
        {
            cout << "RED.bmp is a valid .bmp file" << endl;
        }
    }

    else
    {
        cout << "RED.bmp is not a valid .bmp file" << endl;
        return 1;
    }

    BMPINFO image;

    // seeks to bitmap width, this file is little end in.

    sourcefile.seekg (0x12, ios::beg);

    unsigned int i = (unsigned)sourcefile.get();
    i += (unsigned)sourcefile.get() << 8;

    image.width = i;

    cout << "The width of the image is: " << image.width << endl;

    sourcefile.seekg (0x16, ios::beg);

    i = sourcefile.get();
    i += (unsigned)sourcefile.get() << 8;

    image.height = i;

    cout << "The height of the image is: " << image.height << endl;

    int loc_pixels;

    sourcefile.seekg (0x0A, ios::beg);

    loc_pixels = sourcefile.get();

    cout << "Location of pixel array is: " << loc_pixels << endl;

    output.open("WHITE.bmp");

    output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
    output.put('M');

    if(output.bad())
    {
        cout << "the attempt to output didn't work" << endl;
        return 1;
    }

    sourcefile.seekg(loc_pixels, ios::beg);

    char data[30000];

    output.close();

    return 0;
}

Is there a special function I should be using to output to this .bmp file?
EDIT - added more code, though most of it doesn't have to do with file output

A:

You have a buffer overflow bug in this code:
char data[30000];    // Prepare file for usage -- just copy one thing from the file to the other
sourcefile.read(data, image.height * image.width );

You are reading in image.height*image.width bytes, and trying to fit them into 30000 bytes. You should structure your code so that those two numbers are related.
Try this:
std::vector<char> data(image.height * image.width);
sourcefile.read(&data[0], data.size());


Q:

How to get past the pond in the cave?

See this screenshot:

I suspected that I had to go back and grab the rope:

But I cannot reach it.
Can you give me a clue?

A:

Okay, I got it. You have to jump onto the dead ... children.


Q:

Movement prediction for non-shooters

I'm working on an isometric 2D game with moderate-scale multiplayer, approximately 20-30 players connected at once to a persistent server. I've had some difficulty getting a good movement prediction implementation in place.
Physics/Movement
The game doesn't have a true physics implementation, but uses the basic principles to implement movement. Rather than continually polling input, state changes (ie/ mouse down/up/move events) are used to change the state of the character entity the player is controlling. The player's direction (ie/ north-east) is combined with a constant speed and turned into a true 3D vector - the entity's velocity.
In the main game loop, "Update" is called before "Draw". The update logic triggers a "physics update task" that tracks all entities with a non-zero velocity uses very basic integration to change the entities position. For example: entity.Position += entity.Velocity.Scale(ElapsedTime.Seconds) (where "Seconds" is a floating point value, but the same approach would work for millisecond integer values).
The key point is that no interpolation is used for movement - the rudimentary physics engine has no concept of a "previous state" or "current state", only a position and velocity.
State Change and Update Packets
When the velocity of the character entity the player is controlling changes, a "move avatar" packet is sent to the server containing the entity's action type (stand, walk, run), direction (north-east), and current position. This is different from how 3D first person games work. In a 3D game the velocity (direction) can change frame to frame as the player moves around. Sending every state change would effectively transmit a packet per frame, which would be too expensive. Instead, 3D games seem to ignore state changes and send "state update" packets on a fixed interval - say, every 80-150ms.
Since speed and direction updates occur much less frequently in my game, I can get away with sending every state change. Although all of the physics simulations occur at the same speed and are deterministic, latency is still an issue. For that reason, I send out routine position update packets (similar to a 3D game) but much less frequently - right now every 250ms, but I suspect with good prediction I can easily boost it towards 500ms. The biggest problem is that I've now deviated from the norm - all other documentation, guides, and samples online send routine updates and interpolate between the two states. It seems incompatible with my architecture, and I need to come up with a better movement prediction algorithm that is closer to a (very basic) "networked physics" architecture.
The server then receives the packet and determines the players speed from it's movement type based on a script (Is the player able to run? Get the player's running speed). Once it has the speed, it combines it with the direction to get a vector - the entity's velocity. Some cheat detection and basic validation occurs, and the entity on the server side is updated with the current velocity, direction, and position. Basic throttling is also performed to prevent players from flooding the server with movement requests.
After updating its own entity, the server broadcasts an "avatar position update" packet to all other players within range. The position update packet is used to update the client side physics simulations (world state) of the remote clients and perform prediction and lag compensation.
Prediction and Lag Compensation
As mentioned above, clients are authoritative for their own position. Except in cases of cheating or anomalies, the client's avatar will never be repositioned by the server. No extrapolation ("move now and correct later") is required for the client's avatar - what the player sees is correct. However, some sort of extrapolation or interpolation is required for all remote entities that are moving. Some sort of prediction and/or lag-compensation is clearly required within the client's local simulation / physics engine.
Problems
I've been struggling with various algorithms, and have a number of questions and problems:

Should I be extrapolating, interpolating, or both? My "gut feeling" is that I should be using pure extrapolation based on velocity. State change is received by the client, client computes a "predicted" velocity that compensates for lag, and the regular physics system does the rest. However, it feels at odds to all other sample code and articles - they all seem to store a number of states and perform interpolation without a physics engine.
When a packet arrives, I've tried interpolating the packet's position with the packet's velocity over a fixed time period (say, 200ms). I then take the difference between the interpolated position and the current "error" position to compute a new vector and place that on the entity instead of the velocity that was sent. However, the assumption is that another packet will arrive in that time interval, and it's incredibly difficult to "guess" when the next packet will arrive - especially since they don't all arrive on fixed intervals (ie/ state changes as well). Is the concept fundamentally flawed, or is it correct but needs some fixes / adjustments?
What happens when a remote player stops? I can immediately stop the entity, but it will be positioned in the "wrong" spot until it moves again. If I estimate a vector or try to interpolate, I have an issue because I don't store the previous state - the physics engine has no way to say "you need to stop after you reach position X". It simply understands a velocity, nothing more complex. I'm reluctant to add the "packet movement state" information to the entities or physics engine, since it violates basic design principles and bleeds network code across the rest of the game engine.
What should happen when entities collide? There are three scenarios - the controlling player collides locally, two entities collide on the server during a position update, or a remote entity update collides on the local client. In all cases I'm uncertain how to handle the collision - aside from cheating, both states are "correct" but at different time periods. In the case of a remote entity it doesn't make sense to draw it walking through a wall, so I perform collision detection on the local client and cause it to "stop". Based on point #2 above, I might compute a "corrected vector" that continually tries to move the entity "through the wall" which will never succeed - the remote avatar is stuck there until the error gets too high and it "snaps" into position. How do games work around this?

A:

The only thing to say is that 2D, isometric, 3D, they're all the same when it comes to this problem.  Because you see many examples of 3D and you're only using a 2D octant-limited input system with instantaneous velocity doesn't mean that you can throw out networking principles that have evolved over the last 20+ years.
Design principles be damned when game play is compromised!
By throwing out previous and current you're discarding the few pieces of information that could solve your problem.  To those data I would add time-stamps and calculated lag so the extrapolation can better predict where that player will be and the interpolation can better smooth out velocity changes over time.
The above is a big reason why servers seem to send out a lot of state information and not control inputs.  Another big reason is based on what protocol you're using.  UDP with accepted packet loss and out of order delivery?  TCP with assured delivery and retries?  With any protocol you're going to get packets at weird times, delayed or piled on top of each other in a flurry of activity.  All of those weird packets need to fit into a context so the client can figure out what's going on.
Finally, even though your inputs are very limited to 8 directions the actual change can happen at any time - enforcing a 250ms cycle will just frustrate quick players.  30 players is nothing big for any server to handle.  If you're talking about thousands... even then groups of them are split across multiple boxen so individual servers are only carrying a reasonable load.
Have you ever profiled a physics engine like Havok or Bullet running?  They're really quite optimized and very, very fast.  You may be falling into the trap of assuming operation ABC will be slow and optimizing something that doesn't need it.


Q:

Why does this expression not work as expected in Common Lisp?

A newcomer to Lisp. I know that
(mapcar #'list '(1 2) '(3 4))

will give
'((1 3) (2 4))

and based on my understanding of how apply works, I expect
(apply #'(lambda (&rest x) (mapcar #'list x)) '((1 2) (3 4)))

to return the same result. Instead, I am getting
'(((1 2)) ((3 4)))

I am confused because
(apply #'append '((1 2) (3 4)))

gives me
'(1 2 3 4)

as expected. What is going on?

A:

Simplify it. Suppose you used A instead of (1 2), and B instead of (3 4):
(apply #'(lambda (&rest x) (mapcar #'list x)) '(A B))

Because &rest x takes all the arguments and packs them up as a list, so x has the value
(A B).
Then mapcar iterates twice, passing A to list, producing (A), then it does the same with B. Then mapcar makes a list of those, producing ( (A) (B) )
It's useful to put print statements in there to see what's going on.


Q:

error while saving video file using open cv

program:
import numpy as np
import cv2

cap = cv2.VideoCapture(1)
fourcc = cv2.VideoWriter_fourcc(*'VID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    out.write(frame)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

error:
Traceback (most recent call last):
  File "D:/ANIKET/python projects/img_process.py", line 5, in <module>
    fourcc = cv2.VideoWriter_fourcc(*'VID')
TypeError: Required argument 'c4' (pos 4) not found

i m trying to save the video file.
but i m getting this error.
plz tell me what i am doing wrong

A:

you can also use -1 as an default argument. It had worked in my case.
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',-1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)

        out.write(gray)

        cv2.imshow('frame', gray)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()


Q:

Selecionar múltiplos checkbox com foreach, vindo do banco em laravel?

Estou populando um checkbox com as informações do banco, estou tentando fazer com que ele leia todos os checkbox selecionados.
Controller
    public function store(RequestProduto $request)
{
    $data = new Produtos;
    $data->nome_visivel = $request->nome_visivel;
    $data->nome = $request->nome;
    $data->pdf = $request->pdf;
    $data->keywords = $request->keywords;
    $data->save();

    return Redirect::to('adm/produto')->with('return', 'Dados salvos com sucesso');
}

View
@foreach($atributos as $key => $value)
        <input type="checkbox" name="nome[]" value="{{$value->nome}}">{{$value->nome}}
@endforeach

A:

O parâmetro é recebido como array, basta dar um implode() nos dados para     concatenar:
public function store(RequestProduto $request)
{
    $data = new Produtos;
    $data->nome_visivel = $request->nome_visivel;
    $data->nome = implode(' - ', $request->nome); // onde o primeiro parâmetro é o separador dos itens
    $data->pdf = $request->pdf;
    $data->keywords = $request->keywords;
    $data->save();

    return Redirect::to('adm/produto')->with('return', 'Dados salvos com sucesso');
}


Q:

How to use 3D matrices with CULA on a GPU?

In a CPU version of some Code, I have many things that look like the following:
for(int i =0;i<N;i++){

    dgemm(A[i], B[i],C[i], Size[i][0], Size[i][1], Size[i][2], Size[i][3], 'N','T');

}

Where A[i] will be a 2D matrix of some size.
I would like to be able to do this on a GPU using CULA (I'm not just doing multiplies, so I need the Linear ALgebra operations in CULA), so for example:
 for(int i =0;i<N;i++){
        status = culaDeviceDgemm('T', 'N', Size[i][0], Size[i][0], Size[i][0], alpha, GlobalMat_d[i], Size[i][0], NG_d[i], Size[i][0], beta, GG_d[i], Size[i][0]);
}

However, I would like to store my B's on the GPU in advance at the start of the program as they don't change, but I have no idea how to go about doing that. Or how I could store my arrays in general so that this is possible.
I've seen various things online about using 3D matrices with CUDA, but they don't seem very applicable to being able to then make a function call to the CULA functions.
From the example in the answer below I have this:
extern "C" void copyFNFVecs_(double **FNFVecs, int numpulsars, int numcoeff){

  cudaError_t err;
 err = cudaMalloc( (void ***)&GlobalFVecs_d, numpulsars*sizeof(double*) );
 checkCudaError(err);

    for(int i =0; i < numpulsars;i++){
         err = cudaMalloc( (void **) &(GlobalFVecs_d[i]), numcoeff*numcoeff*sizeof(double) );
         checkCudaError(err);
       //  err = cudaMemcpy( GlobalFVecs_d[i], FNFVecs[i], sizeof(double)*numcoeff*numcoeff, cudaMemcpyHostToDevice );
        // checkCudaError(err);
        }

}

Where I have declared double **GlobalFVecs_d to be a global. But I get a seg fault when it hits the line
 err = cudaMalloc( (void **) &(GlobalFVecs_d[i]), numcoeff*numcoeff*sizeof(double) );

Yet it seems to be exactly what is in the other example?
I realised it wasn't the same, so I now have code that compiles, with:
double **GlobalFVecs_d;
double **GlobalFPVecs_d;

extern "C" void copyFNFVecs_(double **FNFVecs, int numpulsars, int numcoeff){

  cudaError_t err;
  GlobalFPVecs_d = (double **)malloc(numpulsars * sizeof(double*));
 err = cudaMalloc( (void ***)&GlobalFVecs_d, numpulsars*sizeof(double*) );
 checkCudaError(err);

    for(int i =0; i < numpulsars;i++){
         err = cudaMalloc( (void **) &(GlobalFPVecs_d[i]), numcoeff*numcoeff*sizeof(double) );
         checkCudaError(err);
         err = cudaMemcpy( GlobalFPVecs_d[i], FNFVecs[i], sizeof(double)*numcoeff*numcoeff, cudaMemcpyHostToDevice );
         checkCudaError(err);
        }

         err = cudaMemcpy( GlobalFVecs_d, GlobalFPVecs_d, sizeof(double*)*numpulsars, cudaMemcpyHostToDevice );
         checkCudaError(err);

}

However, if I now try and access it with:
 dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
 dim3 dimGrid;//((G + dimBlock.x - 1) / dimBlock.x,(N + dimBlock.y - 1) / dimBlock.y);
 dimGrid.x=(numcoeff + dimBlock.x - 1)/dimBlock.x;
 dimGrid.y = (numcoeff + dimBlock.y - 1)/dimBlock.y;

 for(int i =0; i < numpulsars; i++){
    CopyPPFNF<<<dimGrid, dimBlock>>>(PPFMVec_d, GlobalFVecs_d[i], numpulsars, numcoeff, i);
 }

It seg faults here instead, is this not how to get at the data?

A:

Allocate memory for B with cudaMalloc()
Copy it from host to device with cudaMemcpy()
Pass the device pointer in the kernel argument list

Finally you use it from the kernel with the argument you have passed!
Example:
  1     //  Kernel definition, see also section 4.2.3 of Nvidia Cuda Programming Guide
  2     __global__  void vecAdd(float* A, float* B, float* C)
  3     {
  4        // threadIdx.x is a built-in variable  provided by CUDA at runtime
  5        int i = threadIdx.x;
  6        A[i]=0;
  7        B[i]=i;
  8        C[i] = A[i] + B[i];
  9     }
  10
  11     #include  <stdio.h>
  12     #define  SIZE 10
  13     int  main()
  14     {
  15         int N=SIZE;
  16         float A[SIZE], B[SIZE], C[SIZE];
  17         float *devPtrA;
  18         float *devPtrB;
  19         float *devPtrC;
  20         int memsize= SIZE * sizeof(float);
  21
  22         **cudaMalloc((void**)&devPtrA, memsize);**
  23         cudaMalloc((void**)&devPtrB, memsize);
  24         cudaMalloc((void**)&devPtrC, memsize);
  25         **cudaMemcpy(devPtrA, A, memsize,  cudaMemcpyHostToDevice);**
  26         cudaMemcpy(devPtrB, B, memsize,  cudaMemcpyHostToDevice);
  27         // __global__ functions are called:  Func<<< Dg, Db, Ns  >>>(parameter);
  28         **vecAdd<<<1, N>>>(devPtrA,  devPtrB, devPtrC);**
  29         cudaMemcpy(C, devPtrC, memsize,  cudaMemcpyDeviceToHost);
  30
  31         for (int i=0; i<SIZE; i++)
  32          printf("C[%d]=%f\n",i,C[i]);
  33
  34          cudaFree(devPtrA);
  35         cudaFree(devPtrA);
  36         cudaFree(devPtrA);
  37     }

The ** areas are the important part for you. Example taken from here. You may want to look at this question.
EDIT#1:
First of all to declare a kernel function you need to place the keyword __global__ before the returning type, e.g.
__global__ void copyFNFVecs_(double **FNFVecs, int numpulsars, int numcoeff).
Moreover, I would use just one pointer to the first element of the matrix you have.
double *devPtr.
Allocate it with
cudaMalloc((void*)&devPtr, size)
and then copy
cudaMemcpy(devPtr, hostPtr, size, hostToDevice).
Note that to calculate the size your structure you need the dimensions (say X and Y) and the size of the underlying type of elements (say double).
size_t size = X*Y*sizeof(double).
sizeof(double *) means size of pointer to a double which is incorrect (In 32bit machines the size of a pointer is 4 bytes but the size of double is 8 bytes).


Q:

P/Invoke Marshalling an Out void*

I have the following C function definition:
EXPORT CreateWindow(const wchar_t* applicationTitle, void* windowHandle) {
    // Some preconditions & other stuff here

    windowHandle = RENDER_COMPONENT.Window.CreateNew(cstr_to_wstring(applicationTitle));
    return true;
}

The function is called via P/Invoke. The P/Invoke function definition is as follows:
[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "CreateWindow", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _CreateWindow([MarshalAs(UnmanagedType.LPWStr)] string applicationTitle, [Out] out IntPtr windowHandle);

The usage of this function is:
IntPtr windowHandle;
bool windowCreationSuccess = _CreateWindow(Engine.ApplicationTitle, out windowHandle);

My problem is that windowHandle is always equal to IntPtr.Zero in the C# code, which I guess means that it isn't being 'copied' from the C++ to C# side somehow. It is being set in the C function (I looked with the debugger)- it is actually a HWND.
P/Invoke never ceases to confuse me - I'm sure I've done something wrong with copying a struct rather than a reference to it or something, but I can't quite see what/where.

A:

C uses pass by value exclusively. This means that your assignment to windowHandle can never be seen by the caller. That is so for any caller, not just a managed pinvoke.
You need to change the C function to receive the address of the window handle variable. Like this:
EXPORT CreateWindow(const wchar_t* applicationTitle, HWND* windowHandle) {
    // Some preconditions & other stuff here
    *windowHandle = RENDER_COMPONENT.Window.CreateNew(cstr_to_wstring(applicationTitle));
    return true;
}

The C# code in the question then matches.
However your C code is odd. Why do you return true unconditionally? Why bother returning a bool if it is always true. Frankly it would be cleaner to return the HWND.


Q:

Casting an object to a IList with an abstract type parameter

In my code, I have an object:
object obj = ...

Which I know is of type MyListType, where MyListType is a subclass of IList and T is a subclass of MyAbstractClass. The type parameter of MyListType is constrained so that it is always a subclass of MyAbstractClass.
However, trying to cast obj
MyListType<MyAbstractClass> myList = (MyListType<MyAbstractClass>)obj;

gives a runtime error.
I tried to define an explicit operator
public static explicit operator MyListType<MyAbstractClass>(MyListType<T> list)
{
    MyListType<MyAbstractClass> newList = new MyListType<MyAbstractClass>();
    foreach(T t in list)
        newList.Add((MyAbstractClass) t);
    return newList;
}

However, this operator doesn't get used by the cast since obj is an object, not a MyListType. Is there a workaround to successfully perform this cast?
I've looked at this question, but their the list was of an unknown type.

A:

I ended up reworking my code so that I wouldn't have to do this, but the solution is to first cast it to an IEnumerable, and then add the IEnumerable to a list.
MyListType<MyAbstractClass> list = new MyListType<MyAbstractClass>();
IEnumerable<MyAbstractClass> enumerable = obj as IEnumerable<MyAbstractClass>;
list.AddRange(enumerable);


Q:

How to display image URLs being returned in JSON as thumbnails of UITableViewCell

I have Parse cloud code that returns JSON to my iOS app. As can be seen in the JSON below, every item has an Image URL property. What I want to do is set the thumbnail of every UITableViewCell to the item's respective Image URL.
I know that this involves dealing with asynch behavior, so the cells have to wait for the images to load before displaying them. I've googled how to do this task, and I'm having trouble understanding how to go about it.
My attempt below using
 NSData *imageData = [NSData dataWithContentsOfURL:[NSURL [*matchCenterDictionary objectForKey:@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];

gives me an error stating expected identifier.
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>

@interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *matchCenter;
@end

@implementation MatchCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
    self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-200);
    _matchCenter.dataSource = self;
    _matchCenter.delegate = self;
    [self.view addSubview:self.matchCenter];

    self.matchCenterArray = [[NSArray alloc] init];
}

- (void)viewDidAppear:(BOOL)animated
{
    self.matchCenterArray = [[NSArray alloc] init];

    [PFCloud callFunctionInBackground:@"MatchCenter"
                       withParameters:@{
                                        @"test": @"Hi",
                                        }
                                block:^(NSDictionary *result, NSError *error) {

                                    if (!error) {
                                         self.matchCenterArray = [result objectForKey:@"Top 3"];

                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            [_matchCenter reloadData];
                                        });

                                        NSLog(@"Test Result: '%@'", result);
                                    }
                                }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return [self.matchCenterArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Initialize cell
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        // if no cell could be dequeued create a new one
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // populate dictionary with results
    NSDictionary *matchCenterDictionary= [self.matchCenterArray objectAtIndex:indexPath.row];

    // title of the item
    cell.textLabel.text = [matchCenterDictionary objectForKey:@"Title"];
    // price of the item
    cell.detailTextLabel.text = [matchCenterDictionary objectForKey:@"Price"];

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL [*matchCenterDictionary objectForKey:@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

JSON being returned:
{
    "Top 3" =     (
                {
            "Image URL" = "http://thumbs1.ebaystatic.com/m/m43q-_-W_kKrSuwWbIO7msg/140.jpg";
            "Item URL" = "http://www.ebay.com/itm/New-AT-T-Moto-X-XT1058-Android-Smartphone-Black-16GB-/141304035108?pt=Cell_Phones";
            Price = "289.95";
            Title = "New AT&T Moto X XT1058 Android Smartphone Black 16GB";
        },
                {
            "Image URL" = "http://thumbs2.ebaystatic.com/m/mP5Gx55JuDEVZlmFodzuUow/140.jpg";
            "Item URL" = "http://www.ebay.com/itm/New-AT-T-Moto-X-XT1058-Android-Smartphone-White-16GB-/141302889485?pt=Cell_Phones";
            Price = "289.95";
            Title = "New AT&T Moto X XT1058 Android Smartphone White 16GB";
        },
                {
            "Image URL" = "http://thumbs2.ebaystatic.com/m/mDMiorn4BLSRBcU1EpbFPaA/140.jpg";
            "Item URL" = "http://www.ebay.com/itm/New-Motorola-Moto-X-16GB-White-10MP-AT-T-Branded-Unlocked-Android-Smartphone-/131194435025?pt=Cell_Phones";
            Price = "339.99";
            Title = "New Motorola Moto X 16GB White 10MP AT&T Branded Unlocked Android Smartphone";
        }
    );
}

A:

This code:
[NSURL [*matchCenterDictionary objectForKey:@"Image URL"]]

Looks like the culprit to me... I would try:
[NSURL URLWithString:[matchCenterDictionary objectForKey:@"Image URL"]]

This does not cover the asynchronous network call you mentioned though... For that I would suggest using a PFImageView supplied by Parse instead of the built in imageView in the UITableViewCell.  But there are a few ways to accomplish this task...


Q:

coerce a specific sublist of a list to a matrix / data frame with base R

I needed to create a data frame from a specific sublist of a list. I know the data structure in this particular sublist is constant. For a single list I found do.call()  would do the trick:
lst<-list(l1="aa", l2="ab", l3="ac")
fun.sublst1<-function(n) {
    a<-c("a",1,n)
    return(a)
 }
lstoflst<-lapply(lst, fun.sublst1)
do.call(rbind,lstoflst) # create a data frame from a list

However, If I have a list with lists and I want to iterate over a specific sublist, I am not able use do.call(rbind,lstoflst$A) to create the data frame.
# section list of list
fun.sublst2<-function(n) {
    a<-c("a",1,n)
    b<-c("b",2)
    return(list(A=a,B=b))
}
lstoflst<-lapply(lst, fun.sublst2)
# result should create a dataframe consisting of all sublists $A
t(cbind(lstoflst$l1$A,lstoflst$l2$A,lstoflst$l3$A))

With clumsy code it would look like that.
dat<-t(as.data.frame(lstoflst[[1]][[1]]))
for(i in 2:length(lstoflst)) {
     dat<-rbind(dat,t(lstoflst[[i]][[1]]))
}

Is there an elegant way to do it with the base R? I guess do.call(rbind,lstoflst, ???) with some other parameters will do. I suppose I need to pass the index or an indexing function. Any help?
I searched but I had no luck with my search term. Probably it has been solved already. Hope you can guide me anyway. Thanks
EDIT: changed headline because my examples only produce matrices as a result.

A:

If you know the name of the list component you want (in this case "A"), you can subset each of the lists within a list:
lsSub <- lapply(lstoflst, "[[", "A")

and then rbind that
do.call(rbind, lsSub)
#    [,1] [,2] [,3]
# l1 "a"  "1"  "aa"
# l2 "a"  "1"  "ab"
# l3 "a"  "1"  "ac"

But as Joran pointed out, that's not a data.frame


Q:

Cannot power on a VM vSphere "The operation is not allowed in the current state"

I have a server that looks like this

Server1
Server2
Server3 (inaccessible)
Server4

When I try to power it on, it says "The operation is not allowed in the current state." I have checked the host and the VM itself and haven't seen any pending or failed tasks. What else can I check?
EDIT:
I was able to browse to the VM files in the datastore.

A:

Verify that the server is not in maintenance mode.
It is required for shutdown/restart that the server first be put in maintenance mode and VM's will not start up in this state.

A:

I was able to get it to boot. Here are the steps I followed:

Locate the .vmx file (remember which data store)
Remove the vm for inventory
Browse to the datastore and re-add the VM (right click the .vmx
file)


Q:

System i command line RPG CALL with packed numeric - how to format

If an RPG programs parameter is defined as PACKED(11,0)
CALL MYPGM parm(x'12345678901f')

gives a decimal data error.
Message ID MCH1202
Cause . . . . . :   The sign or the digit codes of the packed or the zoned
  decimal operand is in error.  Valid signs are hex A-F, valid digit range is
  hex 0-9.
In the program dump the parameter appears as:
PACKED(11,0)         12345678901.
VALUE IN HEX         '12345678901F'X

Have googled but cannot find a simple explanation of format of a packed field.

A:

It would probably be better to write a wrapper program that takes the parameter as numeric or character and convert it to packed.


Q:

Issue with Ember.js child route not rendering and parent route being called at the same time

I'm having an issue getting the template to display after the route changes. The log states that I've transitioned into form.newrecord but the template isn't rendering.
Routers:
App.Router.map(function(){
    this.resource('home', { path: '/' });
    this.resource('form', { path: '/forms/:form_id' }, function() {
        this.route('newrecord', { path: '/newrecord' });
    });
});

App.FormNewRecordRoute = Ember.Route.extend({
    renderTemplate: function() {
        this.render("form/newrecord", {
            into: "application",
            outlet: "newrecord"
     })}
});

Templates:

A:

Yep, it's definitely a capitalization issue.  Just switch to this and you should be fine : App.FormNewrecordRoute
JSBin : http://jsbin.com/ucanam/1100/edit


Q:

Memory usage keep growing with Python's multiprocessing.pool

Here's the program:
#!/usr/bin/python

import multiprocessing

def dummy_func(r):
    pass

def worker():
    pass

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=16)
    for index in range(0,100000):
        pool.apply_async(worker, callback=dummy_func)

    # clean up
    pool.close()
    pool.join()

I found memory usage (both VIRT and RES) kept growing up till close()/join(), is there any solution to get rid of this? I tried maxtasksperchild with 2.7 but it didn't help either.
I have a more complicated program that calles apply_async() ~6M times, and at ~1.5M point I've already got 6G+ RES, to avoid all other factors, I simplified the program to above version.
EDIT:
Turned out this version works better, thanks for everyone's input:
#!/usr/bin/python

import multiprocessing

ready_list = []
def dummy_func(index):
    global ready_list
    ready_list.append(index)

def worker(index):
    return index

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=16)
    result = {}
    for index in range(0,1000000):
        result[index] = (pool.apply_async(worker, (index,), callback=dummy_func))
        for ready in ready_list:
            result[ready].wait()
            del result[ready]
        ready_list = []

    # clean up
    pool.close()
    pool.join()

I didn't put any lock there as I believe main process is single threaded (callback is more or less like a event-driven thing per docs I read).
I changed v1's index range to 1,000,000, same as v2 and did some tests - it's weird to me v2 is even ~10% faster than v1 (33s vs 37s), maybe v1 was doing too many internal list maintenance jobs. v2 is definitely a winner on memory usage, it never went over 300M (VIRT) and 50M (RES), while v1 used to be 370M/120M, the best was 330M/85M. All numbers were just 3~4 times testing, reference only.

A:

I had memory issues recently, since I was using multiple times the multiprocessing function, so it keep spawning processes, and leaving them in memory.
Here's the solution I'm using now:
def myParallelProcess(ahugearray)
 from multiprocessing import Pool
 from contextlib import closing
 with closing( Pool(15) ) as p:
    res = p.imap_unordered(simple_matching, ahugearray, 100)
 return res

I ❤ with

A:

Use map_async instead of apply_async to avoid excessive memory usage.
For your first example, change the following two lines:
for index in range(0,100000):
    pool.apply_async(worker, callback=dummy_func)

to
pool.map_async(worker, range(100000), callback=dummy_func)

It will finish in a blink before you can see its memory usage in top. Change the list to a bigger one to see the difference. But note map_async will first convert the iterable you pass to it to a list to calculate its length if it doesn't have __len__ method. If you have an iterator of a huge number of elements, you can use itertools.islice to process them in smaller chunks.
I had a memory problem in a real-life program with much more data and finally found the culprit was apply_async.
P.S., in respect of memory usage, your two examples have no obvious difference.

A:

Simply create the pool within your loop and close it at the end of the loop with
pool.close().


Q:

Python and Selenium - Installation not working

Using-Python 2.5
OS-Windows Vista
There was an error when i tried to install Selenium 2.13 using

pip install -U Selenium

C:\Users\User>pip install -U Selenium
Downloading/unpacking Selenium
Downloading selenium-2.13.1.tar.gz (3.3Mb): 3.3Mb downloaded
Running setup.py egg_info for package Selenium
warning: no files found matching 'docs\api\py\index.rst'
c:\Python25\lib\distutils\dist.py:263: UserWarning: Unknown distribution option: 'src_root'
  warnings.warn(msg)
Downloading/unpacking rdflib==3.1.0 (from Selenium)
Downloading rdflib-3.1.0.tar.gz (249Kb): 249Kb downloaded
Running setup.py egg_info for package rdflib
Installing collected packages: Selenium, rdflib
Found existing installation: selenium 2.13.1
Uninstalling selenium:
  Successfully uninstalled selenium
Running setup.py install for Selenium
warning: no files found matching 'docs\api\py\index.rst'
c:\Python25\lib\distutils\dist.py:263: UserWarning: Unknown distribution option: 'src_root'
  warnings.warn(msg)
c:\Python25\Lib\site-packages\selenium\webdriver\remote\webdriver.py:668: Warning: 'with' will  become a reserved keyword in Python 2.6
File "c:\Python25\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 668 with  open(filename, 'wb') as f:
            ^
SyntaxError: invalid syntax

Found existing installation: rdflib 3.1.0
Uninstalling rdflib:
Successfully uninstalled rdflib
Running setup.py install for rdflib
Successfully installed Selenium rdflib
Cleaning up...

So downloaded the Selenium 2.13 package manually and copied the selenium.py file into c:/python25/lib/. However, when I try to import webdriver from within python it gives me the following error:
C:\Users\User>python F:\Selenium\localtest2.py
Traceback (most recent call last):
  File "F:\Selenium\localtest2.py", line 1, in <module>
    from selenium import webdriver
ImportError: cannot import name webdriver

Is there a problem with the selenium install or is there something wrong that I am doing? Maybe copying just the selenium.py file is stupid? Newbie, bear with me. Followed the tutorial given here.
In the above tutorial i didnt understand how to do this : "Add to your test’s path the file selenium.py"

A:

That installation manual seems a bit awkward to me. First, remove all files (try pip uninstall Selenium, or if that doesn't work just remove the selenium folder from your site-packages folder). Also, delete the single selenium.py file you copied.
Then, try again by running pip install -U selenium. If you can then open your python prompt and do the following without errors, you're good.
from selenium import webdriver

Note that you'll also need the Selenium server, installing it as follows:
java -jar selenium-server-standalone-2.13.0.jar

If all this doesn't work, clean your site-packages as before, and just download and install the files found on the Python package index. Once extracted, open a command prompt where you extracted the files and run python setup.py install. Then, try to import selenium from the command prompt again as specified above.

A:

Apparently Selenium 2.13 has a requirement of Python 2.6, given the syntax error (dependency: 'with').
You have an option to possibly install an earlier version of Selenium or, probably better, upgrade to Python 2.6 on your Windows machine.


Q:

plumbum: How to send a variable to stdin?

I currently do:
(local['echo'][var] | sth)()

Which seems inelegant and inefficient.

A:

I found the solution in the plumbum documentation:
You can use the shift-left operator <<.
from plumbum import local

if __name__ == '__main__':
    var = "some text in a python variable"

    sth = local["cat"]

    x = (local['echo'][var] | sth)()
    print(x)

    print("alternative:")
    x = (sth << var)()
    print(x)


Q:

applet not installing when using javacardx.framework.math.BigNumber

I've encountered a problem while declaring a BigNumber datatype in my javacard applet. The applet loads properly into the simulator if i just comment the declaration. The problem to be precise is while loading the import.cap file
(jcshell: Error code: 6a80 (Wrong data))
java card kit 2.2.2 using
  import javacard.framework.APDU;
  import javacard.framework.Applet;
  import javacard.framework.ISO7816;
  import javacard.framework.ISOException;
  import javacard.framework.JCSystem;
  import javacardx.framework.math.BigNumber;

 public class LargeBal extends Applet {

 // CLA byte
public static final byte BANK_CLA = (byte) 0x80;

// INS byte
public static final byte INS_GET_BALANCE = 0X02;
public static final byte INS_CREDIT = 0X04;
public static final byte INS_DEBIT = 0X06;

/**
 * SW bytes for Arithmetic exception
 */
final static short INVALID_NUMBER_FORMAT = 0x6308;

/**
 * Initial account balance
 */
final static byte[] INITIAL_ACCOUNT_BALANCE = { (byte) 0x01, (byte) 0x00,
        (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };

// Amount of money in user's account

private BigNumber accountBalance;

// Big number for temporary calculation
BigNumber tempBigNum;

// temporary buffer used as scratch space

byte[] scratchSpace;

private LargeBal() {

     accountBalance = new BigNumber((byte) 8);

    // initialize account balance to 100,000.00
     accountBalance.init(INITIAL_ACCOUNT_BALANCE, (byte) 0,
     (byte) INITIAL_ACCOUNT_BALANCE.length, BigNumber.FORMAT_BCD);

    // initialize the temporary big number
     tempBigNum = new BigNumber(BigNumber.getMaxBytesSupported());

    // initialize the scratchSpace
    scratchSpace = JCSystem.makeTransientByteArray((short) 10,
            JCSystem.CLEAR_ON_DESELECT);
    register();
}

public static void install(byte[] bArray, short bOffset, byte bLength) {
    // GP-compliant JavaCard applet registration
    new LargeBal();
}

public void process(APDU apdu) {
    // Good practice: Return 9000 on SELECT
    if (selectingApplet()) {
        return;
    }

    byte[] buf = apdu.getBuffer();
    switch (buf[ISO7816.OFFSET_INS]) {
    case INS_GET_BALANCE:
         getBalance(apdu, buf);
        break;
    case INS_CREDIT:

        break;
    case INS_DEBIT:

        break;
    default:
        // good practice: If you don't know the INStruction, say so:
        ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    }
}

private void getBalance(APDU apdu, byte[] buffer) {

    if (buffer[ISO7816.OFFSET_P1] == BigNumber.FORMAT_BCD) {
        accountBalance.toBytes(buffer, (short) 0, (short) 8,
                BigNumber.FORMAT_BCD);
    } else if (buffer[ISO7816.OFFSET_P1] == BigNumber.FORMAT_HEX) {
        accountBalance.toBytes(buffer, (short) 0, (short) 8,
                BigNumber.FORMAT_HEX);
    } else
        ISOException.throwIt(INVALID_NUMBER_FORMAT);

    apdu.setOutgoingAndSend((short) 0, (short) 8);
}

}

A:

javacardx.framework.math is an optional package. Thus, not all cards/emulators implement this. In your case, it seems that the card does not implement javacardx.framework.math.BigNumber. Consequently it refuses to load/install the applet.
From the Runtime Environment Specification, Java Card Platform, Version 2.2.2 (section 9.7):

Optional Extension Packages
Some API packages in the Java Card technology are designated as extension
  packages and may be optionally supported by an implementation. But, if supported,
  all the classes in the package and its subpackages must be implemented by the
  platform and reside on the card.
The following are optional Java Card technology extension packages:

javacardx.apdu [...]
javacardx.biometry [...]
javacardx.crypto [...]
javacardx.external [...]
javacardx.framework [...] If implemented, this package must include all the contained subpackages - util, math, and tlv.


Q:

How can I pass struct(not a pointer to struct) to Win32API call in ruby?

I am trying to pass structure to Win32API call in ruby.
How can I do this?
A structure is not a pointer. So I can't code like following:
require 'win32api'
get_std_handle = Win32API.new('kernel32.dll',"GetStdHandle",['I'],'I')
h = get_std_handle.call(-11) # STD_OUTPUT_HANDLE

# ['I','P'] is wrong. COORD is not a pointer. it's a structure.
set_console_cursor_position = Win32API.new('kernel32.dll',"SetConsoleCursorPosition",['I','P'],'I')
p = [10,10].pack('S*')
set_console_cursor_position.call(h,p)
puts "hello" # since above code is wrong, this will not printed at position 10,10

So the question is: How to pass structure (not a pointer) to Win32API call?

A:

The folks at RubyDoc have listed code for the source of their Win32Console gem, which uses this, as
def SetConsoleCursorPosition( hConsoleOutput, col, row )
  @SetConsoleCursorPosition ||= Win32API.new( "kernel32", "SetConsoleCursorPosition", ['l', 'p'], 'l' )
  dwCursorPosition = (row << 16) + col
  @SetConsoleCursorPosition.call( hConsoleOutput, dwCursorPosition )
end

Reading How to pass structures as parameters to Win32API in Ruby (Array#pack and Array#unpack) may also shed some light for you.
Unfortunately I'm not sure about the answer to your follow-up comment, maybe you could ask that as another question, or someone that knows could add another answer or comment here or indeed, feel free to edit this answer to add that information.


Q:

Options for servicing Speedplay Zero pedals

I have used Speedplay pedals for ages and I think I am on my third set of pedals. I have the new aero walkable cleats and at the weekend I replaced my old knackered cleats with a new set.
Now that I am on the new set of cleats my left leg (the one I un-click at lights) is popping out of the pedal. It also doesn't feel right and is not a very solid click feeling when I click in and out.
When pedalling it occasionally feels like it half pops out. My foot then feels like it is at an angle. After this happens I can fairly easily just pull my foot off the pedal without twisting.
On my old cleats I had similar issues but I assumed it was because the cleats were knackered.
I have only had these pedals since January last year so I've only done about 6000 miles on them. I have not had to replace the bearings or anything in there. This is 6,000 miles of commuting through London so many stops at lights.
I am going to buy a new set of pedals but I Was wondering if I have any options for fixing my existing set as a spare. I have looked but can't seem to find any replacement pedal bodies for Zero pedals.
Is there anywhere I can post the pedals to that will service them?
I am in the UK.

A:

There are various rebuild kits available on the web, the site Excel Sports has various options, from replacing just the bowties if the main pedal is sound, or the entire pedal surface.
I have custom length spindles to accommodate foot splay, so I have used both a couple times to avoid the big outlay on replacement.


Q:

Finding mangled C++ link error

There are two link errors in this project.
The first, pointed out by @Steve, is the lack of
void *__gxx_personality_v0;
If anyone can explain why a C++ project compiled with clang++3.5 under cygwin  would create a reference to this, I would like to understand. Anyway, I defined the symbol as a workaround.
The other problem appears to be references to 32-bit relative addressing in 64-bit.  I am looking for a way to tell clang++ to compile 32 bit or 64 bit.  I will try on native linux as well, but again, if anyone can explain why this is happening, I would like to understand.
I am thinking it might be a static variable, located down low in the address space, being accessed by something on the stack, but again, clang is generating everything so as far as I can see, this is a bug in the compiler.
clang++ -std=c++11 -O2 -g -I include/ -pthread -c RequestHandler.cc
clang++ -std=c++11 -O2 -g Config.o Logger.o RequestHandler.o FileSys.\
o Buffer.o server.o CspServlet.o -pthread -o server
RequestHandler.o:fake:(.debug_info+0x54bd): relocation truncated to f\
it: R_X86_64_32 against `.debug_ranges'
...
FileSys.o:fake:(.eh_frame$_ZNSt10_HashtableISsSt4pairIKSsP2FLESaIS4_E\
NSt8__detail10_Select1stESt8equal_toISsESt4hashISsENS6_18_Mod_range_h\
ashingENS6_20_Default_ranged_hashENS6_20_Prime_rehash_policyENS6_17_H\
ashtable_traitsILb1ELb0ELb1EEEE21_M_insert_unique_nodeEmmPNS6_10_Hash\
_nodeIS4_Lb1EEE+0x13): undefined reference to `__gxx_personality_v0'
FileSys.o:fake:(.eh_frame$_ZNSt8__detail16_Hashtable_allocISaINS_10_H\
ash_nodeISt4pairIKSsP2FLELb1EEEEE16_M_allocate_nodeIJRKS6_EEEPS7_DpOT\
_+0x13): more undefined references to `__gxx_personality_v0' follow
collect2: error: ld returned 1 exit status

A:

Ok, it turns out that on cygwin, when I installed clang, it doesn't fully use the clang toolchain.  clang is compiling, but g++ is linking (I think).  Bear in mind all these tools could be aliased to something else, but it's very suspicious.
I built on Unix and it worked.  Same makefile.
So the problem is that when I wrote clang, it wasn't using clang to link.  And that is weird.