text:
Q: C# Is there a way to detect a mouse click from additional mouse buttons with hooks? I'm currently working on a personal project where I'm trying to create an APM calculator like. In order to realize it I need to be able to detect any key pressed and any mouse click. I'm using hooks to catch keyboard events and mouse events but I can't find any way to capture special mouse button click...
When I'm talking about special mouse button, I mean additional buttons like on gaming mice. Example : Logitech G600.
I would like to know if there is any way to detect mouse click from any mouse button or special mouse button ?
I already found how to do it for conventional buttons and even for the navigation buttons, but I can't seem to find anything about additional buttons.
Here is my code where I removed all the keyboard part :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Input;

namespace MouseHook
{
    static class Program
    {
        private const int WH_MOUSE_LL = 14;
        private static LowLevelMouseProc _procMouse = HookCallbackMouse;
        private static IntPtr _hookIDMouse = IntPtr.Zero;

        private enum MouseMessages
        {
            WM_LBUTTONDOWN = 0x0201,
            WM_LBUTTONUP = 0x0202,
            WM_MOUSEMOVE = 0x0200,
            WM_MOUSEWHEEL = 0x020A,
            WM_RBUTTONDOWN = 0x0204,
            WM_RBUTTONUP = 0x0205,
            WM_XBUTTONDOWN = 0x020B

            // MISSING ADDITIONAL BUTTONS
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

        private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            _hookIDMouse = SetHookMouse(_procMouse);

            Application.Run(new Form1());

            UnhookWindowsHookEx(_hookIDMouse);
        }

        private static IntPtr SetHookMouse(LowLevelMouseProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private static IntPtr HookCallbackMouse(int nCode, IntPtr wParam, IntPtr lParam)
        {
            // DEAL WITH ANY BUTTON OR ADDITIONAL BUTTON MOUSE

            return CallNextHookEx(_hookIDMouse, nCode, wParam, lParam);
        }
    }
}

Thanks.

A: If I understood you correct you want to find the WindowsMessages that are being send once you click your additional mouse buttons. In order to detect those I suggest you to create a custom MessageFilter, which implements the interface IMessageFilter.
class MessageFilter : IMessageFilter
{
    int[] msgToIgnore = new int[] {512, 799, 49632, 49446, 1847, 15, 96, 275, 160, 1848, 674 , 513, 675, 514, 280, 161, 274, 673, 515, 516, 517, 518, 519, 520, 521, 522, 163, 164, 167, 168, 169, 165, 166};

    public bool PreFilterMessage(ref Message m)
    {
        bool match = false;

        foreach (var msg in msgToIgnore)
        {
            if (m.Msg == msg)
                match = true;
        }

        if (!match)
        {
            MessageBox.Show(m.Msg.ToString());
            return true;
        }
        else
            return false;
    }
}

A MessageFilter filters every single WindowsMessage that is being send to your application. So I basically added the msgToIgnore array to ignore all the other basic WindowsMessages, like any normal mouse click, move, ... or anything that happens on the application start. (I tested it with an empty plain Form and clicked, doubleClicked, dragged, ... on every part of the Form) This ignores all those WindowsMessages, but once you send another WindowsMessage, so e.g. your click on the additional mouse button, the WindowsMessage will be shown in a MessageBox.
All you have to do to activate this MessageFilter is to add this one to your application, I suggest to do it in the constructor after InitializeComponent().
MessageFilter msgFilter = new MessageFilter();

Application.AddMessageFilter(msgFilter);


text:
Q: Exclude nested model field in django serializer So I have two django models but one of them has a field I need to exclude called code. I haven't found a way to exclude this field using the serializer class.
class ModelA(models.Model):
    modelBs = models.ManyToManyField('ModelB')

class ModelB(models.Model):
    # assume all sorts of fields here like name, location, etc..
    code = models.CharField(max_length=200)

My issue is I can't exclude the modelB code when serializing model A like so:
class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        exclude = ('modelBs__code')

The serializer above does not work. Anyone know how to go about this?
My current output is:
[
    {
        modelBs: [
                     {name: "Something", code: "XXXX"}
                 ]
    }
]

My desired output is:
    [
        {
            modelBs: [
                         {name: "Something"}
                     ]
        }
    ]

A: You need to put the exclude in ModelBSerializer.
class ModelASerializer(serializers.ModelSerializer):
    modelBs = ModelBSerializer(read_only=True, many=True)

    class Meta:
        ...

class ModelBSerializer(serializers.ModelSerializer):
    class Meta:
        ...
        exlude = ("code",)

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP can't delete MS Access table row I have a simple MS Access database to insert a single-column row. Here is the page:
<!DOCTYPE html>

    <title>Bell Sistemas - Site de Atividades Teste em PHP</title>

<?php
    include "session.php";
    include "header.php";
    include "connectSQL.php";

echo "
<form action='' method='POST'>

Atividade:
<input type='text' name='activity'>

<input type='submit' name='Cadastrar2' value='Cadastrar'>

</form>";

$activity = $_POST['activity'];

if(isset($_POST['Cadastrar2'])) {
    if($activity==''){
        echo "O campo está vazio.";
    }
    else{
        $sql = "Insert Into Atividades(Atividade) VALUES('$activity')";
        $result = $db->query($sql);
        echo "Atividade inserida.";
    //header("Location: ./menu.php"); /* Redirect browser */
    //exit();
    }}
?>

<?php
$sql  = "SELECT CdAtividade, Atividade FROM Atividades ORDER BY Atividade";

$result = $db->query($sql);
echo "\n
";
echo "

Atividade
";
while ($row = $result->fetch()) {
    echo "
".$row['Atividade']."	Editar	Excluir
";
}
echo "
";
?>
<?php
include "footer.php";
include "tableConfig.php";
?>

And I configured the delete_atividade.php like this:
<?php
 // connect to the database
 include "session.php";
 include "connectSQL.php";

 // get id value
 $cdatividade = $row['CdAtividade'];

 // delete the entry
 $sql  = "DELETE FROM Atividades WHERE CdAtividade='$cdatividade'";
 $result = $db->query($sql);

 // redirect back to the view page
 if($result){
 header("Location: atividades.php");
 }
 else
 // if id isn't set, or isn't valid, redirect back to view page
 {
 header("Location: atividades.php");
 }

?>

However, when I click to delete a row, it does not delete it. Have I forgot something?
I appreciate anyone who can help me.

A: I'm not sure that this will be the final solution, but for starters:
$cdatividade = $row['CdAtividade'];

The $row variable doesn't exist in this file. You're passing on the query string, so it should be:
$cdatividade = $_GET['CdAtividade'];

Also, generally speaking for numeric values it's not necessary to surround in quotes, so your current delete statement:
$sql  = "DELETE FROM Atividades WHERE CdAtividade='$cdatividade'";

...could be rewritten as:
$sql  = "DELETE FROM Atividades WHERE CdAtividade=$cdatividade";

Finally, it's worth noting as Marc B did that your current query is susceptible to SQL Injection attacks like the following:
http://yourdomain.com/delete_atividade.php?CdAtividade=0;DROP TABLE Atividade;
Will result in your SQL looking like this:
DELETE FROM Atividades WHERE CdAtividade=0;DROP TABLE Atividades;

When executed, your table will be dropped, and that's no fun.


text:
Q: How can I add a distance in meters to the latitude value in SQL Server 2014 Given
DECLARE @p1 geography
DECLARE @p2 geography
DECLARE @distance int

SET @distance = 10000 -- meters
SET @p1 = geography::Point(51.5001524, -0.1262362, 4326)

How can I set @p2 such that its latitude is @distance meters north or south of @p1?

A: I have no clue how well this will work in practice, but it can be done just using inbuilt functions.
DECLARE @Distance INT = 10000
DECLARE @latitude DECIMAL(20,10) = 51.5001524
DECLARE @longitude DECIMAL(20,10) = -0.1262362
DECLARE @OriginalPoint GEOGRAPHY = GEOGRAPHY::Point(@latitude, @longitude, 4326)
--This will create a point at the same longitude but at the south pole.
DECLARE @DueSouthPoint GEOGRAPHY = GEOGRAPHY::Point(-90, @longitude, 4326)

DECLARE @SouthLineWithLengthOfDistance GEOGRAPHY =
  @OriginalPoint.ShortestLineTo(@DueSouthPoint) --This is a line due south
  .STIntersection(                              --This will return the line segment inside the circle
    @OriginalPoint.STBuffer(@distance)          --This will draw a circle around the original point with a radius of @distance
  )

  --Now we have to return the lower point on the line.
  --It seems to be fairly inconsistent in which point is first in the line
  --I don't want to spend the time to figure it out, so I'm just using a case to determine which point to return.
  SELECT
    CASE
      WHEN @OriginalPoint.STDistance(@SouthLineWithLengthOfDistance.STPointN(1)) = 0
          THEN @SouthLineWithLengthOfDistance.STPointN(2)
      ELSE @SouthLineWithLengthOfDistance.STPointN(1)
    END


text:
Q: HTML-PDF using puppeteer in node I want to convert html to pdf. I have already tried phantomjs (which is giving timeout error all the time) and wkhtmltopdf (which is very slow,taking 10 mins to get downloaded) .
Now I tried puppeteer but I don't know how to do, first I tried installing puppeteer and its giving this error

ERROR: Failed to download Chromium r662092! Set
  "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variable to skip download.

Can someone please help me to get over this html to pdf conversion

A: In your .npmrc file you have to add the below line to get rid of this error,
puppeteer_skip_chromium_download=true

Hope this helps!


text:
Q: Does $\{f_n\}$ converges to $f$ in $L_2$? Definition We say that a sequence $\{f_n\}$ converges quadratically to $f$ in $L_2$ when $$\lim_{n \rightarrow \infty} \int_X[f_n(x)-f(x)]^2d\mu(x)=0$$
Let $f_n:[0,1] \rightarrow \mathbb{R}$ ($n=1,2,...$) defined by $$\begin{align*}
f(x) =
\begin{cases}
n^{\frac{4}{7}}\sin(\frac{1}{x^2}),  & \text{if $x \in [0,\frac{1}{n})$} \\
0, & \text{if $ x \in (\frac{1}{n},1)$}\\
1, & \text{if $x=0$}
\end{cases}
\end{align*}$$
Does $\{f_n\}$ converges converges quadratically in $L_2$?
Attempt We can see that $\{f_n\}$ converges to $\begin{align*}
f(x) =
\begin{cases}
0,  & \text{if $x \in [0,1)$} \\
1, & \text{if $ x=1$}
\end{cases}
\end{align*}$
So I can try to prove $\{f_n\}$ converges converges quadratically. But, $$\int_{[0,1]}[f_n(x)-f(x)]^2dx$= \int_0^{\frac{1}{n}}[n^{\frac{4}{7}}\sin(\frac{1}{x^2})-0]^2dx+\int_{\frac{1}{n}}^1[0-0]^2dx$$
But I can not calculate $\int_{0}^{\frac{1}{n}}n^\frac{8}{7}\sin^2(\frac{1}{x^2})dx$, so I suppose that $\{f_n\}$ doesn't converge quadratically but what I couldn't, but what I had is
$$\int_{0}^{\frac{1}{n}}n^\frac{8}{7}\sin^2(\frac{1}{x^2})dx \geq -\int_0^{\frac{1}{n}}n^{\frac{8}{7}}dx=-n^{\frac{1}{7}}$$ but it isn't enough, so could you help me?, please.

A: Functions $f_n$ converge pointwise to zero. Thus if the limit in $L^2$ existed it would have to be equal to zero almost everywhere. We shall prove this is not the case.
As Oliver pointed out, the change of variables reduces the problem to proving thath the expression
$$
n^{8/7}\int^\infty_{n^2}u^{-3/2}\sin^2(u)\,du
$$
diverges to infinity (then of course it doesn't converge to zero).
Note that
$$
\sin^2(u)>\frac{1}{2}, \qquad \textrm{for}\qquad u\in \bigcup_{k\in\mathbb{Z}}\Big((k+1/4)\pi,(k+3/4)\pi)\Big).
$$
Therefore
\begin{align*}
\int^\infty_{n^2}u^{-3/2}\sin^2(u)\,du&>\frac{1}{2}\sum_{k=\lfloor\frac{n^2}{\pi}\rfloor}^\infty \int_{(k+1/4)\pi}^{(k+3/4)\pi}u^{-3/2}du
>\frac{1}{2}\sum_{k=\lfloor\frac{n^2}{\pi}\rfloor}^\infty \frac{\pi}{2}((k+3/4)\pi)^{-3/2}du\\
&\simeq \sum_{k=n^2}^\infty k^{-3/2}\simeq \int_{k=n^2}^\infty x^{-3/2}\,dx\simeq \frac{1}{n},
\end{align*}
and finally
$$
n^{8/7}\int^\infty_{n^2}u^{-3/2}\sin^2(u)\,du\gtrsim n^{1/7}\rightarrow \infty, \qquad\textrm{as}\quad n\rightarrow \infty.
$$

A: We have
$\displaystyle \int\limits_0^1f_n^2(x)\,dx =n^{8/7}\int\limits_0^{1/n}\sin^2(x^{-2})\,dx$
Substituting, as in Oliver Diaz answer, $x=y^{-1/2}$ gives $2\,dx =-y^{-3/2}\,dy$ and
$$\displaylines{2\int\limits_0^{1/n}\sin^2(x^{-2})\,dx =\int\limits_{n^2}^\infty y^{-3/2}\sin^2(y)\,dy
\ge \int\limits_{n^2\pi}^\infty y^{-3/2}\sin^2(y)\,dy\\
=\sum_{k=n^2}^\infty \int\limits_{k\pi}^{(k+1)\pi}y^{-3/2}\sin^2y\,dy\ge \pi^{-3/2}\sum_{k=n^2}^\infty (k+1)^{-3/2}\int\limits_{k\pi}^{(k+1)\pi}\sin^2y\,dy \\
=\pi^{-3/2}\,{\pi\over 2}\,\sum_{k=n^2}^\infty (k+1)^{-3/2}\ge 2^{-1}\pi^{-1/2}\int\limits_{n^2+1}^\infty y^{-3/2}\,dy\\
=\pi^{-1/2}(n^2+1)^{-1/2}\ge \pi^{-1/2}2^{-1}n^{-1}}$$
On the way we have used $\int\limits_0^\pi \sin^2y\,dy ={\pi/2}, $ the formula which follows from $\sin^2y+\cos^2y=1.$ Finally
$$\int\limits_0^1f_n^2(x)\,dx \ge 4^{-1}\pi^{-1/2}n^{1/7} $$
Remark I have posted the answer, as it avoids searching for intervals, where $\sin^2x$ is bounded away from $0.$ I make use of the fact that the integral of $\sin^2x$ is equal $\pi/2$ on every interval of length $\pi.$

A: The answer to the OP's question is no, $(f_n:n\in\mathbb{N})$ does not converge in $L_2([0,\infty))$. Here is a sketch of a solution:

*

*Making the change of variables $u=\frac{1}{x^2}$ yields
$$
I_n:=n^{8/7}\int^{1/n}_0 \sin^2(x^{-2})\,dx = \frac{1}{2}n^{8/7}\int^\infty_{n^2}u^{-3/2}\sin^2(u)\,du
$$

*Let $k_n$ be the smallest integer such that $n^2\leq (6k_n+1)\frac{\pi}{6}$. Then
$$(n^2,\infty)\supset\bigcup_{k\geq k_n}\Big((6k+1)\frac{\pi}{6},(6k+5)\frac{\pi}{6}\Big)=(n^2,\infty)\cap\Big(\pi\mathbb{Z}+\big(\pi/6,5\pi/6\big)\Big)$$
On each $k\pi$ translate ($k\in\mathbb{Z}$) of the interval $(\frac{\pi}{6},\frac{5\pi}{6})$  we have that  $\sin^2u\geq \frac14$. Thus
$$\begin{align}
\int^\infty_{n^2}u^{-3/2}\sin^2u\,du&\geq\sum_{k\geq k_n}\int_{k+(\tfrac{\pi}{6},\tfrac{5\pi}{6})}u^{-3/2}\sin^2(u)\,du\\
&\geq\frac14\sum_{k\geq k_n}\int^{(6k+5)\pi/6}_{(6k+1)\pi/6}u^{-3/2}\,du\\
&>\frac{\sqrt{6}}{\sqrt{\pi}}\sum_{k\geq k_n}\frac{1}{\big(6k+1\big)^{3/2}}\\
&>\frac{1}{6\sqrt{\pi}}\sum_{k\geq k_n}\frac{1}{(k+1)^{3/2}}\\
&>\frac{1}{6\sqrt{\pi}}\int^\infty_{k_n}\frac{dx}{(x+1)^{3/2}}=\frac{1}{3\sqrt{\pi}}\frac{1}{\sqrt{k_n+1}}
\end{align}$$
Hence
$$n^{8/7}\int^\infty_{n^2}u^{-3/2}\sin^2u\,du>\frac{1}{3\sqrt{2\pi}}\frac{n^{8/7}}{(k_n)^{1/2}}=\frac{1}{3\sqrt{2\pi}}n^{1/7}\frac{n}{(k_n)^{1/2}}$$

*

*Notice that $(6k_n-5)\frac{\pi}{6}<n^2\leq (6k_n+1)\frac{\pi}{6}$; whence we obtain that $\lim_n\frac{n^2}{k_n}=\pi$. Consequently

$$I_n\xrightarrow{n\rightarrow\infty}\infty$$
All this shows that although $f_n(x)\xrightarrow{n\rightarrow\infty}0$ a.s. in $[0,\infty)$, $f_n$ fails to converge to $0$ in $L_2([0,\infty))$. In fact, $\{f_n:n\in\mathbb{N})$ is unbounded in $L_2([0,\infty))$.


text:
Q: Formatting numbers (decimal places, thousands separators, localization, etc) with CSS Is it possible to format numbers with CSS?
That is: decimal places, decimal separator, thousands separator, etc.

A: No, you have to use javascript once it's in the DOM or format it via your language server-side (PHP/ruby/python etc.)

A: If it helps...
I use the PHP function number_format() and the Narrow No-break Space ( ). It is often used as an unambiguous thousands separator.
echo number_format(200000, 0, "", " ");

Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN
echo "".number_format(200000, 0, "", "")."";

.number SPAN{
    padding: 0 1px;
}

A: Another solution with pure CSS+HTML and the pseudo-class :lang().
Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

  Spanish: 1200000.50

Use the lang pseudo-class to format the number.
/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen:
https://codepen.io/danielblazquez/pen/qBqVjGy

A: The CSS working group has publish a Draft on Content Formatting in 2008.
But nothing new right now.

A: Unfortunately, it's not possible with CSS currently, but you can use Number.prototype.toLocaleString(). It can also format for other number formats, e.g. latin, arabic, etc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

A: I don't think you can. You could use number_format() if you're coding in PHP. And other programing languages have a function for formatting numbers too.

A: Well, for any numbers in Javascript I use next one:
var a = "1222333444555666777888999";
a = a.replace(new RegExp("^(\\d{" + (a.length%3?a.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();

and if you need to use any other separator as comma for example:
var sep = ",";
a = a.replace(/\s/g, sep);

or as a function:
function numberFormat(_number, _sep) {
    _number = typeof _number != "undefined" && _number > 0 ? _number : "";
    _number = _number.replace(new RegExp("^(\\d{" + (_number.length%3? _number.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();
    if(typeof _sep != "undefined" && _sep != " ") {
        _number = _number.replace(/\s/g, _sep);
    }
    return _number;
}

A: You cannot use CSS for this purpose. I recommend using JavaScript if it's applicable. Take a look at this for more information: JavaScript equivalent to printf/string.format
Also As Petr mentioned you can handle it on server-side but it's totally depends on your scenario.

A: Probably the best way to do so is combo of setting a span with a class denoting your formatting then use Jquery .each to do formatting on the spans when the DOM is loaded...

A: Not an answer, but perhpas of interest. I did send a proposal to the CSS WG a few years ago. However, nothing has happened. If indeed they (and browser vendors) would see this as a genuine developer concern, perhaps the ball could start rolling?

A: You could use Jstl tag Library for formatting for JSP Pages
JSP Page
//import the jstl lib
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<c:set var="balance" value="120000.2309" />

Formatted Number (1): <fmt:formatNumber value="${balance}"
        type="currency"/>

Formatted Number (2): <fmt:formatNumber type="number"
        maxIntegerDigits="3" value="${balance}" />

Formatted Number (3): <fmt:formatNumber type="number"
        maxFractionDigits="3" value="${balance}" />

Formatted Number (4): <fmt:formatNumber type="number"
        groupingUsed="false" value="${balance}" />

Formatted Number (5): <fmt:formatNumber type="percent"
        maxIntegerDigits="3" value="${balance}" />

Formatted Number (6): <fmt:formatNumber type="percent"
        minFractionDigits="10" value="${balance}" />

Formatted Number (7): <fmt:formatNumber type="percent"
        maxIntegerDigits="3" value="${balance}" />

Formatted Number (8): <fmt:formatNumber type="number"
        pattern="###.###E0" value="${balance}" />

Result
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3

A: Another js solution to improve the work of Skeeve:

<input type="text" onkeyup="this.value=this.value.toString().replaceAll(/[^\d]/g, '').replaceAll(/(\d)(?=(?:\d\d\d)+$)/g, '$1\u202f')" pattern="[0-9\s]*">

A: Example as inline-JavaScript in an input[type=number]-Html field, using Intl vanilla JS:
<input class="form-number"
       type="number"
       id="bar"
       name="foo"
       value=""
       step="any"
       min="0"
       size="20"
       onfocusout="this.value = (new Intl.NumberFormat('de-DE').format(this.value));">

A: The closest thing I could find is the <input type="number" /> tag, which does do formatting in plain HTML but is also an input field. To make it look like plain text, you could use a bit of CSS.
Unfortunately I don't know how to fix the right margin without JavaScript or using a monospace font and set the width attribute server side.
HTML:

In <input type="number" value="1.223" readonly="readonly" size="1" /> line

CSS:
p {font-family: verdana;}
input {
  font-family: verdana;
  font-size: 16px;
}
input[readonly] {
  border: 0;
  padding: 0;
  margin: 0;
  min-width: 3em;
  font-size: 16px;
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
/* Firefox */
input[type=number] {
  -moz-appearance: textfield;
}

A: as for thousand separators this is what I found on Wikipedia, in the code of this page. Below is the number 149597870700 with .15em margins as thousand separators:

    149
    597
    870
    700


text:
Q: Add a way for a beginner to edit a HTML site that is already created? Some kind of CMS? There is a site that is currently created, and it is written in pure HTML.
Here's my question: how would I implement some kind of backend so a beginner with NO HTML experience could log in and just edit the text, change tables, add pictures, very easy stuff.
Ideas?
I'm pretty goot with HTML, CSS, Javascript, and could learn a PHP scripty-cms-thing quickly.
Thanks very much!

A: Wouldn't it be easier to just "port" the site into an existing cms like yoomla, drupal, umbraco (.net) or any similar cms?

A: If I have a client who wants to be able to edit the content on their site without having to code or do ftp uploads, I've been setting them up with a free Blogger account so that the person can sign in and edit/publish posts. Then I use php to parse the RSS feed of that blog, and print out the parts I want on my client's website. It can get involved if you want to create a separate page for each post in the RSS feed, or if you want to customize how the content is displayed, but in general it's pretty doable. If you're worried about having duplicate content on the Blogger site, just display:none everything in the custom CSS area in the Blogger settings.
In this very simple example, I want to publish the title, date, and content for every post on the home page of my client's website. I'll paste this code right where I want that content to print out in index.php:
<?php
class BlogPost {
    var $date;
    var $link;
    var $title;
    var $text;
}
// load the feed
$xml_source = file_get_contents('URL OF RSS FEED');
$x = simplexml_load_string($xml_source);
// cancel if the feed is empty
if(count($x) == 0)
    return;
// look through the posts and save the content you want
foreach($x->channel->item as $item){
    $post = new BlogPost();
    $post->date = (string) $item->pubDate;
    $post->link = (string) $item->link;
    $post->title = (string) $item->title;
    $post->text = (string) $item->description;
    // truncate the date because it comes from Blogger with a bunch of crap on the end
    $pubDate = substr($post->date, 0, 17);
    // print the content. modify as needed.
    print('
' . $post->title . '

' . $pubDate . '

' . $post->text . '
');
}
?>

Now, any time a change is published from the Blogger account, it will immediately be reflected on this site.


text:
Q: Put the text of a row of a listview in a variable In the application I'm doing, I'm trying to make it do something different depending on the text so I have a code which supposedly retrieves the texto of the row I clicked and then with an if else it tells the program to do something different depending on the code.
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    int selectionRowID = (int) this.getSelectedItemId();
    String selectedFileString = this.directoryEntries.get(selectionRowID);
    if (selectedFileString.equals(".")) {
        this.browseToSD();
    } else if(selectedFileString.equals("..")) {
        this.upOneLevel();
    } else {
        File clickedFile = null;
        clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(selectionRowID));
        if(clickedFile != null)
            this.browseTo(clickedFile);
        }
}

But it doesn't work, this: "selectedFileString.equals(".")" is always TRUE so it always does browseToSD, but sometimes the text is ".." and most of the times it's something completely different so the app doesn't do what it's suppose to do. I tried to change the code to this:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    ListView lv = getListView();
    ListAdapter list_adapter = lv.getAdapter();
    TextView var_x = (TextView) list_adapter.getView(0,null,null);
    if (var_x.equals(".")) {
        this.browseToSD();
    } else if(var_x.equals("..")) {
        this.upOneLevel();
    } else {
        File clickedFile = null;
        clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(selectionRowID));
        if(clickedFile != null)
            this.browseTo(clickedFile);
        }
}

But this doesn't work either, "var_x.equals(".")" and "var_x.equals("..")" are always false. I'm really new to programming with Java and Android so I don't have a clue why it doesn't work, any ideas?

A:

"selectedFileString.equals(".")" is always TRUE

It could mean that
String selectedFileString = this.directoryEntries.get(selectionRowID)

is not working properly fine. That's the first thing you have to review.

"var_x.equals(".")" and "var_x.equals("..")" are always false

That's normal. var_x is a Widget (TextView), not a String. So it won't be equal ever. Try this:
var_x.getText().toString().equals(".")

And do this:
TextView var_x = (TextView) list_adapter.getView(position,null,null);


text:
Q: Overlapping Divs while zooming (html,css animation) I am trying to zoom in on a div but it keeps overlapping with the adjacent div.

* {
 box-sizing: border-box;
}

.zoom {
 /* padding: 50px; */
 background-color: green;
 transition: transform .2s;
 width: 100%;
 height: 200px;
 margin: 0 auto;
}

.zoom:hover {
 -ms-transform: scale(1.5); /* IE 9 */
 -webkit-transform: scale(1.5); /* Safari 3-8 */
 transform: scale(1.5);
}

.nopadding {
 padding: 0 !important;
 margin: 0 !important;
}

What I want to achieve is on hover the div should pop up and not overlap.

A: To your css, add:
.box1{
overflow: hidden;
height: 200px;
}

and also edit .zoom:
.zoom{
    background-color: green;
    transition: transform .2s;
    width: 100%;
    height: 100%;
    margin: 0 auto;
}


text:
Q: Define trace-like function (e.g. cyclically invariant) involving operators without built-in meaning I am interested in defining a function, say $\mathrm{Tra}$, that imply operators without build-in meaning, say it involves products with the $\cdot$ (Esc . Esc), not assumed commuatative.
I want to mimic a trace for it, the main property being cyclic invariance, which I expect to use to simplify expressions. Now I face a syntax problem: the last two operators being the same, as is in general, when one wants to impose some invariance.
esq[A_CenterDot] := RotateLeft@A (*rotates to the CenterDot-product*)
Tra[A_Plus] :=Tra[#] & /@ A (*make Tra additive*)
Tra[A_CenterDot] := Tra[esq[A]]

Second line I've learnt from this answer by Jules Lamers, mutatis mutandis.
With last command I was expecting $ \mathrm{Tra}(x\cdot y\cdot y\cdot x\cdot y\cdot x) $ to yield $  \mathrm{Tra}(x\cdot x \cdot y\cdot y\cdot x\cdot y)$ (with only one left shift, but see below the aimed lexicographic order).
But this of course gives a loop instead. In general,

*

*how does one correct this?

*if possible: how to deal with situations when "the two last arrows of the commutative diagram are the same operation"?

*is there an way out to defining relations at the level of the algebra just before evaluating this "trace"? What is meant is: assuming that $\mathrm{Tra}: A \to \mathbb k$, for any $n$, here there is a commuting pentagon (joining the first and last $A^n$ at the same node)
$A^n \stackrel{left-shift}{\to} A^n \stackrel{\cdot}{\to} A \stackrel{Tra}{\to} \mathbb k\stackrel{Tra}{\leftarrow } A  \stackrel{\cdot}{\leftarrow}  A^n  $
Edit: After the comment(s): I wish the routine to stop, say, after the lexicographic-like order is reached. All x before y and the highest power of x showing up first, independently of what happens thereafter. So, inside the Tra-operator:

*

*$ x \cdot y\cdot x \cdot x \to  x\cdot x \cdot x \cdot y  $  (cyclicity allows here to group all the x together)

*$ y \cdot y\cdot y \cdot x \to  x\cdot y \cdot y\cdot y  $

*$ x\cdot y \cdot x\cdot y\cdot y \cdot x \cdot x \to x \cdot x \cdot x\cdot y \cdot x\cdot y\cdot y  $   (this cannot be tested with OrderedQ, will almost always false)

Output example is then:
$\mathrm{Tra}[ y \cdot y\cdot y \cdot x +  x\cdot y \cdot y\cdot y ]  \to  2\mathrm{Tra}[x\cdot y \cdot y\cdot y]$
since the second line above makes Tra additive, but need not be. It suffices that
$\mathrm{Tra}[ y \cdot y\cdot y \cdot x]$ is replaced by $ \mathrm{Tra}[x\cdot y \cdot y\cdot y]$ in order to simplify.
The issue with the lexicographic for the non-commutative product order is that the test in the given answer will be always false, unless there is no interlaced y's and x's, but that's the exception.

A: Perhaps something like:
ClearAll[esq, Tra]

esq[A_CenterDot] :=  NestWhile[RotateLeft, A, Not @* OrderedQ, 1, Length[A] - 1]

Tra[Y_Plus] := Tra[#] & /@ Y

Tra[A_CenterDot] := esq @ A

Examples:
Tra[x·y·y·x·y·x]

 x·x·y·y·x·y

Tra[x·y·y·y]

 x·y·y·y

 Tra[y·x·y·y·y]

  x·y·y·y·y

Tra[y·y·y·x +  x·y·y·y]

 2 x·y·y·y


text:
Q: Can we get onClickListener functionality of buttons defined in Layout from onOptionsItemSelected() click This is the most simplified version in which I could entitled my question.
Problem: Suppose two buttons are working fine with their functionality in an Activity. What i want is that if we click an item from menu items, how could we (if possible) integrate it one of the the buttons onClickListener so that it would perform the same functionality as one of those buttons are performing already.
Scenario: Lets assume we have two buttons in XML files implementing onCLickListener interface. While clicking the menu item, the inner class constructor has been initialized but it doesn't go further which makes sense. Can anyone guide me what are the options here to work with the logic I want to embed here.
 cameraButton.setOnClickListener(new MyButtonClickListener(MyConstants.OPEN_CAMERA));
 mediaButton.setOnClickListener(new MyButtonClickListener(MyConstants.OPEN_MEDIA));

where MyButtonClickListener is an inner class
private class MyButtonClickListener implements View.OnClickListener {

    private int preference;

    public MyButtonClickListener(int preference) {
        this.preference = preference;
        Log.e("Pref in Constructor:", String.valueOf(preference));

    }

    public MyButtonClickListener() {
    }

    @Override
    public void onClick(View v) {
        Log.e("Pref in onClick:", String.valueOf(preference));
        startScan(preference);
    }
}

and the method startScan is :
public void startScan(int preference) {
    Log.e("Pref: StartScan Method:", String.valueOf(preference));

    Intent intent = new Intent(this, MyActivity.class);
    intent.putExtra(MyConstants.OPEN_INTENT_PREFERENCE, preference);
    startActivityForResult(intent, REQUEST_CODE);
}

onOptionsItemSelected:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {

    case R.id.gallery:
    new MyButtonClickListener(MyConstants.OPEN_MEDIA);
    //return true;

A: As your startScan() method belongs to your activity/fragment class, you can call it directly in the required case block of your onOptionsItemSelected() method. You do not need to go via an interface for that.


text:
Q: JPA find() works, persist no exceptions no results, remove shows query and throw Removing a detached instance exception I don't know what should I add to make it works.
Here is my Entity class:
@Entity
public class Student {

@Id
@GeneratedValue
private int id;
private String name;
private int age;

//setters and getters
}

my application-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config />
<context:component-scan base-package="orm" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="wisla666"/>
</bean>

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="orm.entity" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
        </bean>
    </property>
</bean>

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf" />
</bean>

<tx:annotation-driven transaction-manager="txManager"/>

and this is my Dao class:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import orm.entity.Student;

@Repository
public class StudentDaoImpl implements StudentDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Student loadStudent(int id) {
        return entityManager.find(Student.class, id);
    }

    @Override
    public void saveStudent(Student student) {
        entityManager.persist(student);
    }

    @Override
    public void deleteStudent(Student student) {
        entityManager.remove(entityManager.merge(student));
    }
}

First I load Student object from DB and it works and then I try to remove this object from DB and it doesn't work. During removing the sql syntax is visible:
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?

and an exception is thrown:
java.lang.IllegalArgumentException: Removing a detached instance orm.entity.Student#2

During persisting Student object nothing happens.
The question is what can I do to make it works?

A: the code:
@Repository
public class StudentDaoImpl implements StudentDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    @Override
    public Student loadStudent(int id) {
        return entityManager.find(Student.class, id);
    }
}

the main method:
public static void main(String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
     StudentServiceImpl ssi = context.getBean("studentServiceImpl", StudentServiceImpl.class);
}

the exception: Error creating bean with name 'studentServiceImpl': Injection of autowired dependencies failed
here is my question: if @Transactional can't be with the same plce as @PersistenceContext? Why can't I assign this bean?

A: Once you call loadStudent(int id), the returned Student entity is detached - means no longer attached to hibernate Session.
As it is no longer in session, it is not possible to perform remove operation. To solve the problem, you can wrap your call in transactional method, so that find and remove operations will be performed in one transaction.
Assuming you have StudentService, you can have something like
@Service
public StudentServiceImpl implements StudentService {

     @Autowired
     private StudentDao studentDao;

     @Transactional
     public void remove(int id) {
           Student student = studentDao.loadStudent(id);
           studentDao.remove(student);
     }

}


text:
Q: Jquery add parameter to function in for loop I have this:
$.ajax({
url: "blah.php?something",
dataType: "json"
....
success: function(x){
    for(i in x.artists) {
    addbutton.text(x.artists[i].name).click(function(){
    load(x.artists[i].name)
});
}
});

It's for a music player, and this is a suggestions engine. It loads artist names through AJAX, in JSON format from the PHP file, as you can see.
The problem is with the click() function which is supposed to load songs related to that artist. When the function gets called (ie the button gets clicked), instead of passing the artist's name as a string to load(), it passes x.artists[i].name, which of course is invalid outside of the ajax success function.
How would I go about solving this?
Thanks, Fela

A: Replace
load(x.artists[i].name)

with
load($(this).text())

A: Change your addButton click handler to:
addbutton.text(x.artists[i].name).click(function(){
   load($(this).text())
 });

or change the for loop to as follows(in case the text of the button is changed by some other code before the button is clicked.):
for(i in x.artists) {
  var artistName = x.artists[i].name;
  addbutton.text(artistName ).click(function(){
   load(artistName) ;
  });
}

A: Seeing as how you are setting the text value first - you can just re-use that if you like:
addbutton.text(x.artists[i].name).click(function(){ load($(this).text()) })


text:
Q: mysql CREATE USER I am logged into mysql...
mysql -u root -pmypass

And I have run the following command to remove the database user which worked succesfully
mysql> FLUSH PRIVILEGES; DROP USER 'myuser_shop';

I can then add user successfully using the following command, again this works successfully
mysql> FLUSH PRIVILEGES; CREATE USER 'myuser_shop' IDENTIFIED BY 'mypass';

The above command create a user with the host as a wildcard (%) The issue I am having is if I was to create a user with the host being say localhost or an external IP i get the following error:
mysql> FLUSH PRIVILEGES; DROP USER 'myuser_shop';
mysql> FLUSH PRIVILEGES; CREATE USER 'myuser_shop'@'localhost' IDENTIFIED BY 'mypass';

Query OK, 0 rows affected (0.00 sec)

ERROR 1396 (HY000): Operation CREATE USER failed for 'myuser_shop'@'localhost'

Any suggestions?
Thanks in advance

A: Check following 2 tables if user is still there after DROP USER command:
mysql.user and mysql.db.
Delete user from both, then run FLUSH PRIVILEGES and then you can recreate the user.

A: This is a bug reported here - http://bugs.mysql.com/bug.php?id=28331
See if your user exists after you drop it.

A: drop user 'username@localhost
'

A: i will suggest you to use phpmyadmin its very esey do do with that.
steps:

*

*open phpmyadmin

*go to admin section

*hit on add user account

*put user name and password

*set privileges

that's all
see in action on youtube [ click here  ]

A: You have to manualy remove records with from mysql.tables_priv also.


text:
Q: Metropolis-Hasting algorithm: Proving that $X_n \sim \pi \implies X_{n+1} \sim \pi$ I have a problem about Metropolis-Hasting algorithm that I understand intuitively, but find it difficult to write a clear proof.
Let $X$ be a finite set and $\pi : X \to [0,1]$ be the (difficult to sample) probability measure. For every $x \in X$ we have the proposal $Q_{X_n}$ with probability measure $q_{x} : X \to [0,1]$.
Define the acceptance probability of candidate $n+1$ by $$p(x,y) := \min\bigg\{\frac{\pi(y)}{\pi(x)} \frac{q_y(x)}{q_x(y)}, 1\bigg\} $$ and let $X_n, Y_n$ be two random variables such that $Y_n \sim Q_{X_n}$ (i.e we draw the next candidate according to $Q_{X_n}$) and $X_{n+1} := Y_n$ with probability $p(x,y)$ while $X_{n+1} := X_n$ (i.e rejection) with probability $1 - p(x,y)$
I want to prove that first $\mathbb{P}(Y_n = y|X_n = x) = q_x(y)$ and then show (using the law of total probability) that $$X_n \sim  \pi \implies X_{n+1} \sim  \pi$$
Both statements seem intuitively clear, since first $Y_n \sim Q_{X_n}$ and we can write
$$\mathbb{P}(Y_n = y|X_n = x) = \frac{\mathbb{P}(Y_n = y,X_n = x)}{\mathbb{P}(X_n = x)} $$
but $X_n$ and $Y_n$ are not independent, their dependance is already "encoded" in $Q_{X_n}$ so this should definitely be equal $q_x(y)$, but I am not sure how to show that and also how to translate the second statement. Any help/hint would be great!

A: I think $P(Y_n = y \mid X_n = x)$ is defined as $q_x(y)$ (at least, that is how I interpret what "$Y_n \sim q_{X_n}$" means), so I am not sure there is anything that needs to be proved there.

Law of total probability:
$$P(X_{n+1}=y) = \sum_{x \in X} P(X_n = x) P(X_{n+1}=y \mid X_n=x)$$

Hint 1: Show that
$$P(X_{n+1} = y \mid X_n=x)
= \begin{cases}q_x(y)p(x,y) & x \ne y
\\
q_y(y) p(y,y) + \sum_{y' \ne y} q_y(y')(1-p(y,y'))
& x = y
\end{cases}$$

Plugging this in yields
$$P(X_{n+1}=y)
= \left(\sum_{x \ne y } \pi(x) q_x(y) p(x,y)\right)
+ \pi(y) q_y(y) p(y,y)
+ \pi(y) \sum_{y' \ne y} q_y(y') (1-p(y,y'))$$
Use the definition of $p(\cdot, \cdot)$ to cancel terms until you are left with $\pi(y)$.


text:
Q: Can not run jar file on xubuntu I'm trying to run a jar file that I created on windows. And I would like to test if the my demo app will run as well on ubuntu. I tried by issuing java -jar Rfidtest.jar in the termnal, but I have the following results.

odroid@odroid:~/Documents/RFID$ java -jar RfidTest.jar
eglGetDisplay returned EGL_NO_DISPLAYGraphics Device initialization failed for :  es2
Error initializing QuantumRenderer: no suitable pipeline found
java.lang.RuntimeException: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
    at com.sun.javafx.tk.quantum.QuantumRenderer.getInstance(QuantumRenderer.java:300)
    at com.sun.javafx.tk.quantum.QuantumToolkit.init(QuantumToolkit.java:243)
    at com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:178)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:210)
    at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:637)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:345)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:304)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:754)
Caused by: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.init(QuantumRenderer.java:98)
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:128)
    at java.lang.Thread.run(Thread.java:724)
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:754)
Caused by: java.lang.RuntimeException: No toolkit found
    at com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:190)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:210)
    at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:637)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:345)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:304)
    ... 5 more

I'm new to linux/ubuntu, hope anyone can help.
thanks in advance.

A: Quote from similar question on StackOverflow

You should have a look at this related bug (free registration required) for help on how to troubleshoot your issue.
  In summary, the recommendations are:

*

*run the application with the -Dprism.verbose=true flag

*check the detailed log that is produced

*it may point to a missing garphics library: GTK 2.18 is required to run JavaFX on linux


text:
Q: Error: The streaming job failed: Stream Analytics job has validation errors: Multiple input columns to the end point is not currently supported For the project I have 2 ML models. In the input stream, in stream analytics I get my data and the type of data. I have deployed an Azure Machine Learning Endpoint with ACI. This contains both my models. I followed this link for the multiple models deployment :
https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/deployment/deploy-multi-model/multi-model-register-and-deploy.ipynb
And I used this link to have a second input in my run function, and also my web service for that matter. Here I want to provide the type of data so I can choose the right model for prediction for that data.I used the offical Microsoft documentation for this.
https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-advanced-entry-script#power-bi-compatible-endpoint
When I try to run the Stream, I get this error:
The streaming job failed: Stream Analytics job has validation errors: Multiple input columns to the end point is not currently supported.
The last link also provides information as to how to generate swagger files automatically, which is something needed for my project as well.
If you know how to get around this issue, or if you know a way to switch between models easily, either in the run function, or in the Stream Analytics Query. Please let me know.
For the choosing a model in the Query, the issue is that only one ML function is allowed per query step.

A: Stream Analytics today expects the swagger to be of a particular format (example). The link shows the version of dependencies that must be used in the yml file to generate the swagger in that specific format.
The team is very close to supporting the new swagger format (shown in the link you shared) and when this does become available, you will be able to choose the model from the dropdown in ASA and it will work.


text:
Q: Is .NET 4.0 Compatible with Windows XP SP2 or below? I have read here http://www.microsoft.com/downloads/en/details.aspx?FamilyID=5765d7a8-7722-4888-a970-ac39b33fd8ab that to instal .NET 4.0 CP (client profile) you must have WinXP SP3 or above. This is somewhat worrying to me as there are many people on SP2 or below.
Is there any way I can run a .NET 4.0 app on any version of Windows xp and above? (without worrying about which service packs they have)?
If not, what about .NET 3.5, 3.0 or 2.0?
My questions are the following:

*

*How low do I need to go in my .NET Framework version choice to ensure compatibility for WinXP SP2 or above?

*How low  do I need to go in my .NET Framework version choice  to ensure compatibility for WinXP (no service packs) or above?

A: *

*.NET 4.0 requires XP SP3, Win2k3 SP2, Vista, 7, or 2008(R2)

*.NET 3.5 requires XP SP2 or newer.

*.NET 2.0 requires Win2K SP(3?) or newer.

Incidentally, XP SP2 is no longer supported. (also; all versions of Win2K, and Vista XP1)

A: .NET 3.5 will give you compatibility with XP SP2.  If you want compatibility with any level of XP, you need to go all the way back to .NET 2.0.
.NET 3.5 requirements can be found here:
http://msdn.microsoft.com/en-us/library/cc160717(VS.90).aspx
.NET 3.0 requirements can be found here:
http://msdn.microsoft.com/en-us/library/aa480198.aspx

A: As far as I know, 3.5 was the last version to support WinXP SP2.


text:
Q: Get a filtered list from two lists I have a listbox where all my factories are loaded into. I also have a selected factories in listbox(1).
Binding Code for all factories in listbox right.
protected void fillWerke()
{
    //BindingListPersistable<Liebherr.Hau.Erp.Client> bl = new BindingListPersistable<Liebherr.Hau.Erp.Client>();
    AllFactory = new BindingListPersistable<Liebherr.Hau.Erp.Client>();
    AllFactory = Manager.LoadClients();
    BetroffeneWerkeAll.DataSource = from allF in AllFactory select allF.ClientCode;
    BetroffeneWerkeAll.DataBind();
}

What I tried is,
protected void fillWerke()
{
    //BindingListPersistable<Liebherr.Hau.Erp.Client> bl = new BindingListPersistable<Liebherr.Hau.Erp.Client>();
    AllFactory = new BindingListPersistable<Liebherr.Hau.Erp.Client>();
    AllFactory = Manager.LoadClients();
    var selectedFac;
    var filteredFac;
    if(SelectedWerke.Items.Count > 0)
    {
        selectedFac = SelectedWerke.Items;
        filteredFac = AllFactory.Except(selectedFac);
    }
    BetroffeneWerkeAll.DataSource = from allF in AllFactory select allF.ClientCode;
    BetroffeneWerkeAll.DataBind();
}

however, i hope u know what i mean, sorry for my bad english

A: Try instead of:
BetroffeneWerkeAll.DataSource = from allF in AllFactory select allF.ClientCode;

This:
 BetroffeneWerkeAll.DataSource = from allF in filteredFac select allF.ClientCode;

When you perform Except it returns the "input list except items in second list" and not sets the first list.

Not sure but it seems to me that selectedFac is of the type of ClientCode and not of an item in AllFactory. If that is the case you should use:
var result = AllFactory.Where(item =>
        !selectedFac.Any(filteredValue => filteredValue == item.ClientCode)).ToList();


text:
Q: Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function? A while ago I came across some code that marked a member variable of a class with the mutable keyword.  As far as I can see it simply allows you to modify a variable in a const method:
class Foo
{
private:
    mutable bool done_;
public:
    void doSomething() const { ...; done_ = true; }
};

Is this the only use of this keyword or is there more to it than meets the eye?  I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.

A: Well, yeah, that's what it does. I use it for members that are modified by methods that do not logically change the state of a class - for instance, to speed up lookups by implementing a cache:
class CIniWrapper
{
public:
   CIniWrapper(LPCTSTR szIniFile);

   // non-const: logically modifies the state of the object
   void SetValue(LPCTSTR szName, LPCTSTR szValue);

   // const: does not logically change the object
   LPCTSTR GetValue(LPCTSTR szName, LPCTSTR szDefaultValue) const;

   // ...

private:
   // cache, avoids going to disk when a named value is retrieved multiple times
   // does not logically change the public interface, so declared mutable
   // so that it can be used by the const GetValue() method
   mutable std::map<string, string> m_mapNameToValue;
};

Now, you must use this with care - concurrency issues are a big concern, as a caller might assume that they are thread safe if only using const methods. And of course, modifying mutable data shouldn't change the behavior of the object in any significant fashion, something that could be violated by the example i gave if, for instance, it was expected that changes written to disk would be immediately visible to the app.

A: Mutable is used when you have a variable inside the class that is only used within that class to signal things like for example a mutex or a lock. This variable does not change the behaviour of the class, but is necessary in order to implement thread safety of the class itself. Thus if without "mutable", you would not be able to have "const" functions because this variable will need to be changed in all functions that are available to the outside world. Therefore, mutable was introduced in order to make a member variable writable even by a const function.

The mutable specified informs both the compiler and the reader that it
  is safe and expected that a member variable may be modified within a const
  member function.

A: Use "mutable" when for things that are LOGICALLY stateless to the user (and thus should have "const" getters in the public class' APIs) but are NOT stateless in the underlying IMPLEMENTATION (the code in your .cpp).
The cases I use it most frequently are lazy initialization of state-less "plain old data" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption.

A: Your use with boost::mutex is exactly what this keyword is intended for. Another use is for internal result caching to speed access.
Basically, 'mutable' applies to any class attribute that does not affect the externally visible state of the object.
In the sample code in your question, mutable might be inappropriate if the value of done_ affects external state, it depends on what is in the ...; part.

A: mutable is mainly used on an implementation detail of the class. The user of the class doesn't need to know about it, therefore method's he thinks "should" be const can be. Your example of having a mutex be mutable is a good canonical example.

A: Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.

A: Mutable changes the meaning of const from bitwise const to logical const for the class.
This means that classes with mutable members are longer be bitwise const and will no longer appear in read-only sections of the executable.
Furthermore, it modifies type-checking by allowing const member functions to change mutable members without using const_cast.
class Logical {
    mutable int var;

public:
    Logical(): var(0) {}
    void set(int x) const { var = x; }
};

class Bitwise {
    int var;

public:
    Bitwise(): var(0) {}
    void set(int x) const {
        const_cast<Bitwise*>(this)->var = x;
    }
};

const Logical logical; // Not put in read-only.
const Bitwise bitwise; // Likely put in read-only.

int main(void)
{
    logical.set(5); // Well defined.
    bitwise.set(5); // Undefined.
}

See the other answers for more details but I wanted to highlight that it isn't merely for type-saftey and that it affects the compiled result.

A: It allows the differentiation of bitwise const and logical const.  Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example.  Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):
int x = 0;
auto f1 = [=]() mutable {x = 42;};  // OK
auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda

A: Mutable is for marking specific attribute as modifiable from within const methods. That is its only purpose. Think carefully before using it, because your code will probably be cleaner and more readable if you change the design rather than use mutable.
http://www.highprogrammer.com/alan/rants/mutable.html

So if the above madness isn't what
  mutable is for, what is it for? Here's
  the subtle case: mutable is for the
  case where an object is logically
  constant, but in practice needs to
  change. These cases are few and far
  between, but they exist.

Examples the author gives include caching and temporary debugging variables.

A: It's useful in situations where you have hidden internal state such as a cache.  For example:

class HashTable
{
...
public:
    string lookup(string key) const
    {
        if(key == lastKey)
            return lastValue;

        string value = lookupInternal(key);

        lastKey = key;
        lastValue = value;

        return value;
    }

private:
    mutable string lastKey, lastValue;
};
And then you can have a const HashTable object still use its lookup() method, which modifies the internal cache.

A: The mutable keyword is very useful when creating stubs for class test purposes. You can stub a const function and still be able to increase (mutable) counters or whatever test functionality you have added to your stub. This keeps the interface of the stubbed class intact.

A: The mutable can be handy when you are overriding a const virtual function and want to modify your child class member variable in that function. In most of the cases you would not want to alter the interface of the base class, so you have to use mutable member variable of your own.

A: The mutable keyword is a way to pierce the const veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way except when and how it is marked mutable.
With your const reference or pointer you are constrained to:

*

*only read access for any visible data members

*permission to call only methods that are marked as const.

The mutable exception makes it so you can now write or set data members that are marked mutable. That's the only externally visible difference.
Internally those const methods that are visible to you can also write to data members that are marked mutable.  Essentially the const veil is pierced comprehensively.  It is completely up to the API designer to ensure that mutable doesn't destroy the const concept and is only used in useful special cases. The mutable keyword helps because it clearly marks data members that are subject to these special cases.
In practice you can use const obsessively throughout your codebase (you essentially want to "infect" your codebase with the const "disease").  In this world pointers and references are const with very few exceptions, yielding code that is easier to reason about and understand.  For a interesting digression look up "referential transparency".
Without the mutable keyword you will eventually be forced to use const_cast to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately const_cast is significantly more destructive than mutable because it forces the API client to destroy the const protection of the objects (s)he is using. Additionally it causes widespread const destruction: const_casting a const pointer or reference allows unfettered write and method calling access to visible members.  In contrast mutable requires the API designer to exercise fine grained control over the const exceptions, and usually these exceptions are hidden in const methods operating on private data.
(N.B. I refer to to data and method visibility a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed here.)

A: mutable does exist as you infer to allow one to modify data in an otherwise constant function.
The intent is that you might have a function that "does nothing" to the internal state of the object, and so you mark the function const, but you might really need to modify some of the objects state in ways that don't affect its correct functionality.
The keyword may act as a hint to the compiler -- a theoretical compiler could place a constant object (such as a global) in memory that was marked read-only. The presence of mutable hints that this should not be done.
Here are some valid reasons to declare and use mutable data:

*

*Thread safety. Declaring a mutable boost::mutex is perfectly reasonable.

*Statistics. Counting the number of calls to a function, given some or all of its arguments.

*Memoization. Computing some expensive answer, and then storing it for future reference rather than recomputing it again.

A: In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major "state" of the class.  This is most often where I see mutable used.  Without mutable, you'd be forced to sacrifice the entire const-ness of your design.
It feels like a hack most of the time to me as well.  Useful in a very very few situations.

A: The classic example (as mentioned in other answers) and the only situation I have seen the mutable keyword used in so far, is for caching the result of a complicated Get method, where the cache is implemented as a data member of the class and not as a static variable in the method (for reasons of sharing between several functions or plain cleanliness).
In general, the alternatives to using the mutable keyword are usually a static variable in the method or the const_cast trick.
Another detailed explanation is in here.

A: One of the best example where we use mutable is, in deep copy. in copy constructor we send const &obj as argument. So the new object created will be of constant type. If we want to change (mostly we won't change, in rare case we may change) the members in this newly created const object we need to declare it as mutable.
mutable storage class can be used only on non static non const data member of a class. Mutable data member of a class can be modified even if it's part of an object which is declared as const.
class Test
{
public:
    Test(): x(1), y(1) {};
    mutable int x;
    int y;
};

int main()
{
    const Test object;
    object.x = 123;
    //object.y = 123;
    /*
    * The above line if uncommented, will create compilation error.
    */

    cout<< "X:"<< object.x << ", Y:" << object.y;
    return 0;
}

Output:-
X:123, Y:1

In the above example, we are able to change the value of member variable x though it's part of an object which is declared as const. This is because the variable x is declared as mutable. But if you try to modify the value of member variable y, compiler will throw an error.

A: The very keyword 'mutable' is actually a reserved keyword.often it is used to vary the value of constant variable.If you want to have multiple values of a constsnt,use the keyword mutable.
//Prototype
class tag_name{
                :
                :
                mutable var_name;
                :
                :
               };


text:
Q: Caldigit TS3 Plus, Ethernet slot always showing cable unplugged, my OS Catalina I purchased Caldigit TS3 Plus today and try to use it's network function on my 2018 mbp. Ethernet slot always showing cable unplugged.
I confirm my network is normal (I connected this cable to other computer and it works).
Tried below procedures but not working.
A. Restart
B. Download official drive from Caldigit (though not necessary),installed and restarted
C. In network setting, hardware, set it to be manually according to some googled articles
I am supposing is it possible that not compatible with new OS Catalina?
What can I do now?

A: I had a similar problem. I'm not sure the cause for the issue, but I agree that it seems to be related to the Catalina update. I can provide what worked for me, but I can't really explain why it worked -- I honestly can't even be sure that this was the cause for things to start working again. Given this, if I should move what I wrote to be a comment under the OP's question, then please let me know, or feel free to go ahead and do so.
I managed to get things working again by removing the Thunderbolt bridge and Thunderbolt ethernet slot(s) from the Network settings. I then installed the support driver (found here: https://archive.caldigit.com/KB/index.asp?KBID=179&viewlocale=1 ) It says that it's the Ethernet driver, but the part that I needed was the Support driver; in fact, the Ethernet driver install failed several times for reasons that are unclear to me. Once I got the USB Hub Support file installed, and I rebooted, the network preferences gave the option of a Thunderbolt Ethernet Slot, which I installed and it seems to work.
I recall that there was a Thunderbolt bridge before, but it doesn't seem to be needed now, so I wonder if something that was added/changed with the last OS update is the culprit. I will have to leave this those with more expertise than I have.
Good luck


text:
Q: group values in csv file and save them in another csv file Hello I am trying to group my csv file only using the csv module and input the result in another csv file.
The problem that I am having is that the other fields get appended to the first field which is manufacturer and I want this to be done in the correct fields.
in row[3] the car_details are saved and in row[4] the car.
import csv
result = {}
fields=['test','name','object']

with open('work.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    writer = csv.writer(open("art1.csv",'w',newline=''), delimiter=';')
    for row in csvreader:
        if row[0] in result:
          result[row[0]].append(row[3])
        else:
            result[row[0]] = [row[1]]
with open('art1.csv', 'w') as csvfile:
   # writer.writerow(fields)
    csvwriter = csv.writer(csvfile)
    for row in result.items():
        csvwriter.writerow(row)

reader = csv.reader(open("art1.csv", "r",newline=''), delimiter=',')
writer = csv.writer(open("artgain2.csv",'w',newline=''), delimiter=';')
writer.writerow(fields)
writer.writerows(reader)

the csv file:
toyota         fast           Prius
toyota         slow           yaris
toyota         fast           corolla
toyota         slow           sunshine
mercedes       fast           benz
mercedes       fast           something
mazda          fast           bus

the result I want
manufacturer   car_details    car
toyota         fast           Prius
               slow           yaris
               fast           corolla
               slow           sunshine
mercedes       fast           benz
               fast           something
mazda          fast           bus

the result I get:
manufacturer                      car_details    car
toyota,fast,Priusslow,yaris,fast,corolla,slow,sunshine,
mercedes,fast,benz,fast,something
mazda,fast,bus

Everything is in the manufacturer column and I dont know how to split this correctly in the corresponding fields
I feel that I am pretty close to the solution and I am probably forgetting something
Can someone help me out ?

A: I'm assuming you open your .CSV files with MS excel and you have a European language setting? The reason for this assumption is, that you seem to use ";" as separator in your output file.
So it seems reasonable that excel won't interpret your "," in your result files as separators. Additionally, it seems like you have no proper line breaks in your result file.
In all your files, I can't see any row with index 3 or 4. This seems to bee to high an index...
Proposed solution
import csv

class ExcelEuropeDialect(csv.Dialect):
        delimiter      = ';'
        lineterminator = '\r\n'
        quotechar      = '"'
        quoting        = csv.QUOTE_MINIMAL
csv.register_dialect('excel_eu', ExcelEuropeDialect)

result = []
item_occured = [] # list with all items already occured
fields=['test','name','object']

with open('work.csv', 'r', newline='') as csvfile:
    csvreader = csv.reader(csvfile, dialect='excel')
    for row in csvreader:
        if row[0] in item_occured:
            row[0] = ''                     # empty first cell
        else:
            item_occured.append(row[0]) # add item to item_occured
        row = [s.strip() for s in row]
        result.append(row)                  # append whole row
with open('art1.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, dialect=csv.get_dialect('excel_eu'))
    csvwriter.writerow(fields)
    csvwriter.writerows(result)


text:
Q: GROUP BY timestamp every 15 minutes including missing entries I want to group all reports from a given table named 'reports' by every 15 minutes, including intervals where no reports where filled. Example:
id      timestamp
---------------------------
1        2015-04-16 20:52:04
2        2015-04-16 20:53:04
3        2015-04-16 20:54:04
4        2015-04-16 19:52:04
5        2015-04-17 22:24:56
6        2015-04-17 22:27:09
7        2015-04-18 06:48:41

After the select query I should have:
timestamp       count
----------------------
20:52:04         3
21:07:04         0
21:22:04         0
21:37:04         0
21:52:04         0
22:07:04         0
22:22:04         2
22:37:04         0
22:52:04         0
......
06:52:04         1
07:07:04         0

What I tried is the following query but this doesn't include the missing 15-minute-intervals:
select created_at , count(id) AS count
from `reports`
where `company_id` = '3'
group by UNIX_TIMESTAMP(created_at) DIV 900
order by `created_at` asc

A: If you really want to do it in mysql, this should work to some extent - depending on how you want to organise your 15 minute intervals. I've given the output as time from | time to | number of reports because i think its meaningless and even a little deceptive to output a specific timestamp and associate a count of a time range with it.
SELECT CONCAT (
        lpad(hours.a, 2, "0"),
        ":",
        lpad(minutes.a * 15, 2, "0"),
        ":00"
        ) AS 'from',
    CONCAT (
        lpad(hours.a, 2, "0"),
        ":",
        lpad((minutes.a * 15) + 14, 2, "0"),
        ":59"
        ) AS 'to',
    count(r.id)
FROM (
    SELECT 0 AS a

    UNION

    SELECT 1 AS a

    UNION

    SELECT 2 AS a

    UNION

    SELECT 3 AS a

    UNION

    SELECT 4 AS a

    UNION

    SELECT 5 AS a

    UNION

    SELECT 6 AS a

    UNION

    SELECT 7 AS a

    UNION

    SELECT 8 AS a

    UNION

    SELECT 9 AS a

    UNION

    SELECT 10 AS a

    UNION

    SELECT 11 AS a

    UNION

    SELECT 12 AS a

    UNION

    SELECT 13 AS a

    UNION

    SELECT 14 AS a

    UNION

    SELECT 15 AS a

    UNION

    SELECT 16 AS a

    UNION

    SELECT 17 AS a

    UNION

    SELECT 18 AS a

    UNION

    SELECT 19 AS a

    UNION

    SELECT 20 AS a

    UNION

    SELECT 21 AS a

    UNION

    SELECT 22 AS a

    UNION

    SELECT 23 AS a
    ) hours
INNER JOIN (
    SELECT 0 AS a

    UNION

    SELECT 1 AS a

    UNION

    SELECT 2 AS a

    UNION

    SELECT 3 AS a
    ) minutes
LEFT JOIN reports r ON hours.a = hour(r.t)
    AND minutes.a = floor(minute(r.t) / 15)
GROUP BY hours.a,
    minutes.a;


text:
Q: How to send an email to requester only if the build is triggered manually? I would like to configure a project in Jenkins to send emails to the recipients group for regular scheduled builds, but only to the requester in case the build is triggered manually. Is this possible?

A: You should be able to accomplish this by using the "Script - After Build" trigger of the Editable Email Notification post-build action. You can run a groovy script, with the last line evaluating to a Boolean, which determines whether or not to send the email. The screenshot below shows the trigger section that checks to see if the build was initiated by a user (manually).

This script will only tell you whether or not the IMMEDIATE cause of the build was a manual user action, though. Depending on how your build pipeline is setup, one of your upstream jobs may have been initiated manually, so I'm not sure if you want an email sent in that case. If you do, you will have to iterate through all the build causes and look for a manual cause.
def boolean wasStartedManually(causes) {
    boolean manuallyStarted = false
    causes.each { cause ->
        if (cause.class == hudson.model.Cause$UserIdCause) {
            manuallyStarted = true
        }

        if (!manuallyStarted) {
            if (cause.class == hudson.model.Cause$UpstreamCause) {
                manuallyStarted = wasStartedManually(cause.upstreamCauses)
            }
        }

    }
    return manuallyStarted
}

wasStartedManually(build.getCauses())

You will need to add 2 post-build Email actions to your job, one for when the job is triggered manually, and then another if the job was not submitted manually. For the latter, you would run the same script, but just negate the results.


text:
Q: Nodejs returning from try...catch I'm running the following from node 9.5:
const { lstatSync, readdirSync } = require('fs');
const { resolve } = require('path');

const isDirectory = source => lstatSync(source).isDirectory();
const getDirectories = source =>
  readdirSync(source).map(name => resolve(source, name)).filter(isDirectory);

try {
    const apiRoutes = getDirectories(__dirname + '/api');

    if (apiRoutes.length === 0) {
        throw new Error('API root must contain directories');
    }

    console.log(apiRoutes);

    return apiRoutes;

} catch (e) {
    console.error(`${e.name}: ${e.message}`);
}

//Why don't these fire?
console.log(apiRoutes);
console.log('foo');

Assuming there are two directories in api, the first console.log(apiRoutes) in the try block logs:
[/basedir/api/dir1,/basedir/api/dir2]

However, I can't get anything after the try block to run. If I don't return apiRoutes in the try block I get an undefined error.
How do I return a value from the try block?
Why doesn't foo get logged?

A: The apiRoutes constant is scoped within the try block.
Refactor the code to either move the console.logs within the try block, or change to defining apiRoutes with let in the outer scope; and setting its value within the try block by calling getDirectories.

This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

A: You may need to declare apiRoutes outside of the try/catch. Once the try/catch completes you lose scope of the variable.


text:
Q: Triangulation to find distance to the object- Image to world coordinates              Localization of an object specified in the image.

I am working on the project of computer vision to find the distance of an object using stereo images.I followed the following steps using OpenCV to achieve my objective
 1. Calibration of camera
 2. Surf matching to find fundamental matrix
 3. Rotation and Translation vector using svd as method is described in Zisserman and Hartley book.
 4. StereoRectify to get the projection matrix P1, P2 and Rotation matrices R1, R2. The Rotation matrices can also be find using Homography R=CameraMatrix.inv() H Camera Matrix.
Problems:
i triangulated point using least square triangulation method to find the real distance to the object. it returns value in the form of [ 0.79856 , .354541 .258] . How will i map it to real world coordinates to find the distance to an object.
http://www.morethantechnical.com/2012/01/04/simple-triangulation-with-opencv-from-harley-zisserman-w-code/
Alternative approach:
Find the disparity between the object in two images and find the depth using the given formula
Depth= ( focal length * baseline ) / disparity
for disparity we have to perform the rectification first and the points must be undistorted. My rectification images are black.
Please help me out.It is important
Here is the detail explanation of how i implemented the code.

*

*Calibration of Camera using Circles grid to get the camera matrix and Distortion coefficient. The code is given on the Github (Andriod).
2.Take two pictures of a car. First from Left and other from   Right. Take the sub-image and calculate the -fundmental matrix- essential matrix- Rotation matrix- Translation Matrix....
3.I have tried to projection in two ways.

*Take the first image projection as identity matrix and make a second project 3x4d through rotation and translation matrix and perform Triangulation.

*Get the Projection matrix P1 and P2 from Stereo Rectify to perform Triangulation.
My object is 65 meters away from the camera and i dont know how to calculate this true this based on the result of triangulation in the form of [ 0.79856 , .354541 .258]
Question: Do i have to do some extra calibration to get the result. My code is not based to know the detail of geometric size of the object.

A: So you already computed the triangulation? Well, then you have points in camera coordinates, i.e. in the coordinate frame centered on one of the cameras (the left or right one depending on how your code is written and the order in which you feed your images to it).
What more do you want? The vector length (square root of the sum of the square coordinates) of those points is their estimated distance from the same camera. If you want their position in some other "world" coordinate system, you need to give the coordinate transform between that system and the camera - presumably through a calibration procedure.


text:
Q: Rails 3.2 assets:precompile Permission denied 123 I'm trying to precompile my rails app but get this weird error that I don't know how to follow?
rake assets:precompile --trace
** Invoke assets:precompile:all (first_time)
** Execute assets:precompile:all
** Invoke assets:precompile:primary (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
** Invoke tmp:cache:clear (first_time)
** Execute tmp:cache:clear
** Execute assets:precompile:primary
rake aborted!
Permission denied - /123
/Users/philip/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/fileutils.rb:247:in `mkdir'

A: You are creating your app on /123/ which is likely a protected directory. You should really be creating your apps within your home folder.
However, if you want to force /123 then you can run sudo rake assets:precompile and it will work.


text:
Q: Printing 'box' in array So I am facing hair loss day by day because of this sub-task required for my first year assignment.
I need to print a 'box' around the number at coordinate [5][5] / i.e center of the board during the initialization stage of the program.
The 'box' consists of "|" covering the sides and "_" on top and bottom of the number at coordinate [5][5].
When I execute this program, the board shows but the 'box' doesn't. Why is this happening??
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

//FUNCTION: Draw the Board
int drawBoard()
{
    //Declare array size
    int board[9][9];

    //initialize variables
    int rows, columns, randomNumber, flag;

    //random number seed generator
    srand(time(NULL));

        for ( rows = 0 ; rows < 9 ; rows++ )
        {

            for ( columns = 0 ; columns < 9 ; columns++ )
            {
                flag = 0;

                do
               {
                    //generate random numbers from 2 - 8

                    randomNumber = rand() %7 + 2;

                    board[rows][columns] = randomNumber;

                        //Display the 'box' if rows and columns == 5 / i.e - board[5][5]
                        if ( rows == 5 && columns == 5 )
                        {   //Checks for 2 adjacent numbers
                            if  ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
                            {
                                flag = 0;
                                continue;
                            }
                            else
                            {
                                flag = 1;

                                //Print 'box'
                                marker( rows, columns );
                            }
                        }

                    //Checks for 2 adjacent numbers.
                    if  ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
                        {
                            flag = 0;
                            continue;
                        }

                    else
                    //Prints the correct board
                         {
                                flag = 1;
                                printf( "  %d  ", board[rows][columns] );
                         }

                } while ( flag == 0 ); //end outer do-while

            }//end inner for-loop

            printf("\n\n");

        }//end outer for-loop

}//end FUNCTION drawBoard

//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int x, int y, int** board )
  {
    board[x][y-1] == "\n _ ";
    board[x][y+1] == "\n _ ";
    board[x-1][y] == " |";
    board[x+1][y] == "| ";
  }

int main()
{
    drawBoard();
}

TI

A: void marker( int x, int y, int** board )
  {
    board[x][y-1] == "\n _ ";
    board[x][y+1] == "\n _ ";
    board[x-1][y] == " |";
    board[x+1][y] == "| ";
  }

This won't work. The '==' is for comparing, not assigning. You need a '='.
However, board is an array of int, you can't assign a const char* (because that's what "something" is) in an array of int. Your board should be an array of char, and then you can assign like this:
void marker( int x, int y, char** board )
  {
    board[x][y-1] = '_';
    board[x][y+1] = '_';
    board[x-1][y] = '|';
    board[x+1][y] = '|';
  }

Another problem is that the center of the board is at index [4][4], the fifth element of a table of size 9. But that is a smaller problem...

A: I see what you want to do here, this isn't the way I usually think, so I may be not helpfull :s
first, a mistake:
in "drawboard": marker( rows, columns )
prototype of "marker": void marker( int x, int y, int** board ). I don't think compilation with flag will work (and yes, flags ARE helpfull, try "gcc -Wall -Wextra -Werror")
Moreover, I think you should re-think your function "marker", it can't work.
I think board[x][y-1] = "\n _ " would do the trick, if you return(board[x][y-1]) but again, I would have work with a char**, not an integer tab,  and with many short functions (and used write instead of printf :p)

A: #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

//FUNCTION: Draw the Board
char tochar(int i)
{
    return i+'0';
}
void marker( int x, int y, char board[][19] );
int check(int x, int y, char board[][19])
{
    if(x>1&&board[2*x+1][2*y+1]==board[2*x-1][2*y+1])
        return 1;

    if(y>1&&board[2*x+1][2*y+1]==board[2*x+1][2*y-1])
        return 1;
   return 0;
}
int drawBoard()
{
    //Declare array size
    char board[19][19];

    memset(board,32, sizeof(board));
    //initialize variables
    int rows, columns, randomNumber, flag;

    //random number seed generator
    srand(time(NULL));

        for ( rows = 0 ; rows < 9 ; rows++ )
        {

            for ( columns = 0 ; columns < 9 ; columns++ )
            {
                flag = 0;

                do
               {
                    //generate random numbers from 2 - 8

                    randomNumber = rand() %7 + 2;
                    board[2*rows+1][2*columns+1] = tochar(randomNumber);

                        //Display the 'box' if rows and columns == 5 / i.e - board[5][5]
                        if ( rows == 4 && columns == 4 )
                        {   //Checks for 2 adjacent numbers
                            if  ( check(rows, columns, board))
                            {
                                flag = 0;
                            }
                            else
                            {
                                flag = 1;

                                marker( 2*rows+1, 2*columns+1, board );
                                //Print 'box'
                            }
                        }
                    else
                    {
                    //Checks for 2 adjacent numbers.
                    if  ( check(rows, columns, board))
                        {
                            flag = 0;
                        }

                    else
                    //Prints the correct board
                         {
                            flag = 1;
//                            printf( "  %c  ", board[2*rows+1][2*columns+1] );
                         }
                    }
                } while ( flag == 0 ); //end outer do-while

            }//end inner for-loop

            printf("\n\n");

        }//end outer for-loop
    for(rows=0;rows<19;rows++)
    {
        for(columns=0;columns<19;columns++)
        {
            printf("%c",board[rows][columns]);
        }
        printf("\n");
    }
}//end FUNCTION drawBoard

//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int x, int y, char board[][19] )
  {
    board[x][y-1] = '|';
    board[x][y+1] = '|';
    board[x-1][y] = '_';
    board[x+1][y] = '_';
   /*
192
191
217
218
*/
  }

int main()
{
    drawBoard();
}


text:
Q: Auto execute shell script during bootup (Ubuntu) Are there any folder like /etc/cron.d/, so when I put a script inside this folder, it will get automatically executed during the bootup time?

A: Call your script from /etc/rc.local .

A: Make it an Upstart script

A:
That would require edit the file rc.local, any other way?

If you don't have sudo permission, you can create a cron job with something like this:
@reboot /path/to/your/script


text:
Q: If Then Select From List In JavaScript, is there a way to select if then from a list. I remember doing it in Visual Basic.
So instead of
if (id == "category1") {i = 1};
if (id == "category2") {i = 2};
if (id == "category3") {i = 3};

Is there something like
if.select (

  category1 = 1
  category2 = 2
  category3 = 3

A: Use a dictionary (works similarly to enum):
var dictionary = {"category1": 1, "category2": 2, "category3": 3};
i = dictionary[id]

JSFiddle
Here is a switch case example:
switch(id){
  case 'category1':
    i = 1;
    break;
  case 'category2':
    i = 2;
    break;
  case 'category3':
    i = 3;
    break;
}

I prefer the dictionary approach over the switch-case approach because it's a bit less code to write every time you add a new category.

A: You can think outside the box:
var i = id.split('category')[1];

You can make it a function:
function getCategoryId(id){
    return id.split('category')[1];
}

And then just call it like:
var i = getCategoryId('category1');

You can also use substr, it will perform the best (talking about nanoseconds, though).

See it live here:

var id = 'category2';
function getCategoryId(id){
    return id.split('category')[1];
}
alert(getCategoryId(id));

Or just use switch:
switch(id){
  case 'category1':
    i = 1;
    break;
  case 'category2':
    i = 2;
    break;
  case 'category3':
    i = 3;
    break;
}


text:
Q: Recursion Formula Euler Numbers I am trying to derive the formula
$$\displaystyle\sum_{k=0}^{n}{2n\choose 2k}E_k = \displaystyle\sum_{k=0}^{n}{n\choose k}^2E_k=0$$
Where $E_k$ are the Euler Numbers.
The approach that I have taken is to first prove that ${2n\choose 2k} = {n\choose k}^2$.  I looked into applying Pascal's Rule, but that got me nowhere.
I also have already proven that $E_{2n+1} = 0$ for $n=1,2,...$  I feel like this will come into play when I attempt to prove that the sequence is equal to $0$.


text:
Q: Fire button event manually I have a search text box on my WPF Windows. Whenever, the user presses enter key after writing some query in the textBox, the process should start.
Now, I also have this Search button, in the event of which I perform all this process.
So, for a texBox:
<TextBox x:Name="textBox1" Text="Query here" FontSize="20" Padding="5" Width="580" KeyDown="textBox1_KeyDown"></TextBox>

private void queryText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                //how do I fire the button event from here?
            }
        }

A: It is possible but rather move your search logic into a method such as DoSearch and call it from both locations (text box and the search button).

A: Are you talking about manually invoking buttonSearch_onClick(this, null);?

A: You can Create a Common Method to do search for ex
public void MySearch()
{
     //Logic
}

Then Call it for diffetnt places you want like...
private void queryText_KeyDown(object sender, KeyEventArgs e)
     {
         if (e.Key == Key.Return)
         {
                      MySearch();
         }
     }

private void buttonSearch_onClick(object sender, EventArgs e)
{
     MySearch();
}

A: A event can not be fired/raised from outside the class in which it is defined.(Using reflection you can definitely do that, but not a good practice.)
Having said that, you can always call the button click event handler from the code as simple method call like below
private void queryText_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        OnSearchButtonClick(SearchButton, null);
    }
}


text:
Q: Ubuntu stuck in fallback after attempting to install cinnamon Running Ubuntu 14.03 dual booting along Windows 7. I have about 64gb of source code I really don't want to have to download again. So I installed the cinnamon PPA like this:
sudo add-apt-repository ppa:gwendal-lebihan-dev/cinnamon-nightly
sudo apt-get update
sudo apt-get install cinnamon

But I forgot to add the mint repository before hand. Long story Ubuntu got stuck in fallback mode. So being a newb I did this:
sudo apt-get --purge autoremove cinnamon

My thought process was that I would remove cinnamon and the default desktop environment would be still there. So I guess is there any way to reinstall desktop environment or fix this without reformatting and starting over? I humbling call myself and newb and ask your guys' advice. Thanks in advance !
***EDIT*** It also needs to be noted that I can't connect to WIFI, either the drivers aren't coming up or I just don't know the correct way to bring them "up." My computer also doesn't have an Ethernet or DVD drive, so its a wireless card and usb only. The machine boots up until the lock screen, then it errors out if you try to log in. Thanks again!

A: I cannot reply as comment because I don't have enough reputation so I'm going ahead and answer, just giving you some options to try, that I hope will be useful.
First, you will need some way to download from the net. Since you are asking here I assume you have that.
From your problem PC press Ctrl-Alt-F1, login and type:
apt-get install --reinstall --print-uris -qq unity ubuntu-desktop

Hopefully, you will get the URIS of the packages you need, that you can download elsewhere and transfer via USB to your problem PC. I'll post the ones that I got:
http://archive.ubuntu.com/ubuntu/pool/main/u/ubuntu-meta/ubuntu-desktop_1.325_i386.deb
http://archive.ubuntu.com/ubuntu/pool/main/u/unity/unity_7.2.6+14.04.20151021-0ubuntu1_i386.deb
Let's say you copied them to your home folder, then (as before) from the terminal:
sudo dpkg -i ubuntu-desktop*.deb unity*.deb

EDITED: I added you need to change runlevel.


text:
Q: Removing background-color with php I'm trying to remove the background-color from a string with PHP, and for that I want to use a regular expression (which is, in my opinion, the fastest way to achieve that).
Here's what I have:
Parabéns! Você recebeu um pouco de sorte!

I simply want to remove "background-color: {color value}" from the style attribute. However, backgrounds can have different colors, and it can be either hexadecimal or RGB() (In this case).
Here's the expression I have created, which didn't work, unfortunately:
 /background-color: ?(\#[a-fA-F0-9]{3,6}|rgb\([0-9]{2,3},[0-9]{2,3},[0-9]{2,3}\))\;/

I tryed to search over the web and in stackoverflow, but I couldn't find an answer to this specific problem.
Thanks for your attention.

A: Use preg_replace() and regular expressions.
$string = "background-color: #ffffff;";
$expression = "/background-color:(.*?);/";
$string = preg_replace($expression, '', $string);
var_dump($string);

Outputs:
string '' (length=0)

Yes, this will get rid of your string with the rgb(...) value. It matches anything between background-color: and the semicolon.
Recognize the limitation to this however. it will only replace
background-color: value;

If the HTML code perhaps uses background: #ffffff it will fail.

A: Code:
$s = 'text';
$s = preg_replace('~background-color:.+?;\s*~', '', $s);
echo $s;

Output:
text


text:
Q: C# Application deployment with unmanaged dlls from a PHP server I want to deploy a C# application from my website which is hosted in Linux/PHP Apache. It has a couple of managed and unmanaged dlls as dependencies. Can someone please tell if I can use ClikcOnce on Apache server, and if yes how I will be able to do it. thanks in advance

A: click once only produce static files.
just check if the server will correctly serve all files (as content).
[edit] to conclude the comments, the 1&1 hosting provider php offer does not block files for a click once setup

A: Don't forget to set the MIME types correctly.
http://robindotnet.wordpress.com/2010/06/12/mime-types-for-clickonce-deployment/


text:
Q: Ajax submit form and validate / email via PHP I am working on a html contact form and using the javascript code below to validate the form when the submit button is clicked:
function leftValue(e, t, n) {
$(this).text(t.parent()[0].style.left)
}
$(document).ready(function() {
required = ["name", "email"];
email = $("#email");
errornotice = $("#error");
emptyerror = "Required Field";
emailerror = "Required Field";
$("#contact-us").submit(function() {
for (i = 0; i < required.length; i++) {
    var e = $("#" + required[i]);
    if (e.val() == "" || e.val() == emptyerror) {
        e.addClass("form-error");
        e.val(emptyerror);
        errornotice.fadeIn(750)
    } else {
        e.removeClass("form-error")
    }
}
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-  Z0-9]{2,4})+$/.test(email.val())) {
    email.addClass("form-error");
    email.val(emailerror)
}
if ($(":input").hasClass("form-error")) {
    return false
} else {
    errornotice.hide();
    return true
}
});
$("input").focus(function() {
if ($(this).hasClass("form-error")) {
    $(this).val("");
    $(this).removeClass("form-error")
}
})
});

HTML
<form action="" method="post" name="contact-us" id="contact-us">
<input type="text" id="name" name="name"/>
<input type="text" id="email" name="email"/>
</form>

Thank you for your message!

Once the validation is passed and the submit button is clicked again, the data is posted via PHP and emailed using this code:
<?php
if(isset($_POST['submit']))
{
$to="test@test.com";
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$body="Name: $name \n\n Email Address: $email \n\n";
$sent=mail($to, $body);
}
?>

I am trying to now using ajax to carry out these functions and display a confirmation message on the same page without reloading. I have tried the code below which allows the form to be validated but when the validation passes and submit is clicked again, the page just reloads and doesn't display the confirmation message contained in the #success div?
$(document).ready(function() {
$("#contact-us").submit({
submitHandler: function() {
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
        $("#contact-us").serialize(),
        function(data){
          if (data == 'Sent') {
            $("#success").fadeIn();

        }
        //
    });
    return false;
}
});
});

A: Did you try this: event.preventDefault();
$(document).ready(function() {
$("#contact-us").submit(function(event) {

event.preventDefault();

$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
        $("#contact-us").serialize(),
        function(data){
          if (data == 'Sent') {
            $("#success").fadeIn();

        }
    });
    return false;
});
});


text:
Q: How can I pass self reference to object in dart I have a class Field and has a copy() method, I want to pass self reference to new object but Dart editor seem not allow. How can I pass self reference to new object like java?
class Field
   Field copy() {
       return new Field(this);
   }
}

A: There's no problem to do such things :
class Field {
  String name;
  Field(Field other) {
    // init current with other
  }
  Field copy() => new Field(this);
}

A: You seem to be missing an opening curly brace and you don't have a constructor. Other than that, there's no reason why this shouldn't work:
class Field {
  Field ref;

  Field(this.ref);

  Field copy() {
    return new Field(this);
  }
}

Field a = new Field(null);
Field b = a.copy();
print(identical(a, b.ref)); // true