Q:

What is the smallest action required to destroy all of reality?

Scenario:
The most feared evil scientist in the world, Sinister Norman Van Deathtoyou, is on a mission to destroy everything. Humans, Earth, The Universe, even the very fabric of space and time. But, being the cliche evil scientist that Sinister is, he must do this in a complex fashion that only he needs to understand.
First, he invents time travel. Yes, this is a bit far fetched but Sinister is an extremely intelligent guy with unparalleled motivation (So please blindly accept this as fact). This time travel has rules, and these rules are important and must be followed exactly:

Sinister has discovered that the Universe does everything possible to disregard paradoxes. This means that the predestination paradox that is often associated with time travel is completely irrelevant.
Also, none of that "uhhh but if he destroys reality in the past then he will never have been born to destroy reality" garbage. Sinister has found that the universe still runs linear even if he goes to a different point in time. If he destroys reality at any point in time then he will still have succeeded in destroying reality.
Time travel is extremely intrusive to a human's health and only one single trip can be survived.
I don't know all of the actual science behind what the destruction of the universe means in a technical sense and I don't really care all that much. Numbers are great but there are many more important things!

Goal:
Describe a method in which Sinister can make one trip and do the absolute minimum (in terms of the actual action) in order to destroy the very fabric of time and space, effectively annihilating everything.
Bonus points to creativity, thoughtfulness, and uniqueness of responses.

A:

How to Destroy the Universe with a Time Machine...
Change the initial conditions which are responsible for the Baryon Asymmetry.  All matter and anti-matter should have cancelled out, but it didn't (citation: reality).  All our scientist has to do is figure out why (note: this is one of the great unsolved problems in physics), then use the time machine to go back and alter initial conditions to make baryon annihilation symmetrical.
Or, travel to the inflation period (10^-32 seconds after the Big Bang) and make an alteration which would cause the Universe to choose a lower energy state than we currently (apparently) occupy, known as vacuum decay.
Or simply travel to the inflation period. The current large scale structure of the Universe is a result of small, chaotic motions in the very early Universe.  Introducing any sort of perturbation during this period, such as a suicidal human and their time machine, would likely radically alter the large scale structure of the present day Universe.  You'd still have stars and planets, but different ones in different places, and no Earth.
Look, I didn't say it would be easy.


Q:

Python speech recognition for Raspberry Pi 2

I am trying to find a Speech recognition library similar to PySpeech that will work on a Raspberry Pi 2.  I am new to this and have tried researching but there are so many applications I just need help choosing the correct one.
All I am trying to do is, when a user says something the program will recognize keywords and open up the correct part of my code which will just display information about that keyword.
Right now I am using Python 2.7 and PyQt4 to display what I want but am willing to change if there is something easier such as KivyPi, PyGame, etc.
I am up for any ideas or any help to push me into the right direction.
Thank You!

A:

I created a library called SpeakPython that helps Python developers do exactly this, and just released it under GPL3. The library is built upon pocketsphinx (sphinxbase) and gstreamer (for streaming recognition, which leads to fast results). It will allow you to attach python code to speech commands.
It's very accurate and dynamic for command parsing such as this, and I've tested it on the Pi already. Let me know if you have any issues.


Q:

How to Determine a Conditional Expectation of a RV w.r.t. a Sub-$\sigma$-Algebra

The Problem:
Let $(\Omega, \mathcal{F}, \mathbb{P}) = ((0,1], \mathscr{B}(0,1], \lambda)$ in which $\lambda$ represents Lebesgue measure on the unit interval. Define the random variable $X: \Omega \to \mathbb{R}$ by $X(\omega) = \omega$.
Define the sub-$\sigma$-algebra $\mathcal{G}_1 = \sigma((0,\frac{1}{2}])$. Determine $\mathbb{E}[X | \mathcal{G}_1]$.
Where I Am:
$\mathbb{E}[X | \mathcal{G}_1]$ is any $\mathcal{G}_1$-measurable random variable $Y: (0,1] \to \mathbb{R}$ such that
$$ \int_{G}Y d \lambda = \int_{G} X d \lambda = \int_{G} X(\omega)I_{G}(\omega) \lambda (d \omega) = \int_{G} \omega I_{G}(\omega) \lambda (d \omega) , $$
for each $G \in \mathcal{G}_1 = \left\{\emptyset, (0, \frac{1}{2}], (\frac{1}{2}, 1], (0, 1] \right\}$. This means that the following must be satisfied:
\begin{align*}
 G = \emptyset   &\implies \int_{G}Y d \lambda = \int_{G} \omega I_{G}(\omega) \lambda (d \omega) = 0, \\
 G = (0, 1/2]   &\implies \int_{G}Y d \lambda = \int_{0}^{1/2} x d x = \frac{1}{8}, \\
 G = (1/2, 1]   &\implies \int_{G}Y d \lambda = \int_{1/2}^{1} x d x = \frac{3}{8}, \quad \text{ and} \\
 G = (0, 1]   &\implies \int_{G}Y d \lambda = \int_{0}^{1} x d x = \frac{1}{2}.
\end{align*}
I assume, however, that there is more I am supposed to say about $Y$. I don't know if it is possible to write down a formula for $Y$ (I can't think of how one would do this), or what. My thought is to consider the measurability condition, which has me rather confused...
Indeed: Let $B \in \mathscr{B}$, where $\mathscr{B}$ is the Borel $\sigma$-algebra on $\mathbb{R}$. I'd like to verify that $Y^{-1}(B) \in \mathcal{G}_1$. Well, since intervals of the form $(a,b]$ generate $\mathscr{B}$, we may assume WLOG that $B= (a,b]$, for some $a, b \in \mathbb{R}$ with $a < b$. But is there anything I can really say here about $Y^{-1}(a,b]$ without any more information? My thought here was just to try the formula $Y(\omega) = \omega$ (since this obviously satisfies the integral conditions above). But then, e.g., $Y^{-1}(0,1/4]$ would just be $(0,1/4]$, which does not belong to $\mathcal{G}_1$. I'm really not sure what I'm supposed to do here...

A:

Hint: $E(X|\mathcal G)$ is of the form $aI_A+bI_B$ where $A=(0,\
\frac 1  2]$ and $B=[\frac 1  2 ,1]$. Compute $a$ and $b$ by integrating over $A$ and $B$. [You should get $a=\frac 1  4$ and $b=\frac  3 4 ].
In general if $\mathcal G$ is the sigma algebra generated by a partition $\{A_1,A_2,...,A_n\}$ the any measurable function w.r.t. $\mathcal G$ has the form $\sum a_iI_{A_i}$. In this case $\mathcal G$ is generated by $\{A,B\}$.


Q:

in der Jahrhunderte währenden Entflechtung

in der Jahrhunderte währenden Entflechtung

I am not able to connect the noun Jahrhunderte and Entflechtung meaningfully.
Could you explain the above phrase grammatically?
Here is the full quote:

Das „Reichsgesetz über die Beurkundung des Personenstands und die Eheschließung“ vom 6. Februar 1875 war ein Eckstein bürgerlicher Gesetzgebung in Deutschland – ein Höhepunkt in der Jahrhunderte währenden Entflechtung von Staat und Kirche.

A:

in der (Jahrhunderte währenden) Entflechtung - (...) serves as an adjective. It uses the Partizip I "währenden" -> (an)dauernden. So all-in-all it's: in der Entflechtung, die Jahrhunderte währte (= (an)dauerte).


Q:

Unique Groups for Game Tournament

I am trying to put together a Munchkin game tournament where I am assuming I will have 16 people coming to my tournament. As part of that, I want to have as many games as possible where people are not playing against the same player twice. (So, every combination is unique.)
I can easily come up with these groups for three rounds of the tournament. Is it possible to do more? If so, can you point me in the right direction? Unfortunately, I think I am confusing my combinations and permutations and it's leaving me stumped.

A:

Identify the players with elements of ${\bf Z}_2^4$ (that is, with ordered 4-tuples of zeros and ones, where addition of 4-tuples is done component-wise and using mod $2$ arithmetic). There are $5$ subgroups of $4$ elements each such that no two subgroups have any element in common other than $(0,0,0,0)$. Each subgroup, together with its cosets, gives you one round of your tournament, so this is a way to go $5$ rounds.

A:

This is nothing more than Gerry's answer made explicit. (I apologize if I've made any mistakes or typos...  Any mistakes are mine, not Gerry's!)
Label your 16 players with the letters A,B, ..., P. Then your rounds should have the following games of 4 players:
Round 1
{A,B,C,D}  {E,F,G,H}  {I,J,K,L}  {M,N,O,P}
Round 2
{A,E,I,M}  {B,F,J,N}  {C,G,K,O}  {D,H,L,P}
Round 3
{A,F,K,P}  {B,E,L,O}  {C,H,I,N}  {D,G,J,M}
Round 4
{A,J,O,H}  {B,I,P,G}  {C,L,M,F}  {D,K,N,E}
Round 5
{A,G,L,N}  {B,H,K,M}  {C,E,J,P}  {D,F,I,O}

A:

These kinds of problems can be difficult; see the discussion  Math Games: Social Golfer Problem about scheduling threesomes as well as foursomes playing concurrently, a topic called resolvable Steiner systems.  The case of 16 people in foursomes over 5 days is shown (both as a listing of 4-sets and as a strange diagram) in nearly the middle of that page/article.
Day 1: ABCD EFGH IJKL MNOP
Day 2: AEIM BFJN CGKO DHLP
Day 3: AFKP BELO CHIN DGJM
Day 4: AGLN BHKM CEJP DFIO
Day 5: AHJO BGIP CFLM DEKN


Q:

Fullhouse probability for first and third person

my goal is to calculate the probability of first and third person getting a fullhouse at the start of the game (5 people and 52 cards). I understand that for the first person it would be: $$\frac{\binom{13}{1}\binom{4}{3}\binom{12}{1}\binom{4}{2}}{\binom{52}{5}}$$
But I just can't figure out how to deal with the second person in between since he can get a lot of possible combinations, so the cards to choose from for the third person will change. (for example if he also gets a fullhouse, there is one less rank for the third person fullhouse).
Am I missing something? Right now I can't come up with any sollution, so some help would be really appreciated.

A:

Completely ignore the second person!  Begin by dealing the cards to the first person and immediately after continue by dealing the cards to the third person.  The cards that the second person and any other people receive are completely and totally irrelevant to the problem and the calculations surrounding it.
Recall that $Pr(A\cap B) = Pr(A)Pr(B\mid A)$
Now, in calculating $Pr(B\mid A)$, you might want to consider two cases.  Either the pair of cards in our third player's hand match the pair of cards in our first player's hand, or not.  In either case, there are $\binom{47}{5}$ equally likely hands that our third player could have given a particular hand that our first player has.
For the third player to have the same pair as the first player, those two cards must be in his hand.  Pick what remaining three cards are used.  There are $11$ untouched ranks remaining, pick what the unused suit for our triple is.  there are thus $11\times 4 = 44$ possible continuations where our third player gets a full house sharing the pair for the first player.
For the third player to not have the same pair as the first player, we calculate very similarly to before.  There are $11\times 4$ ways to pick the triple for the third player and $10\times \binom{4}{2}$ ways to pick the pair for the third player.
This gives a probability of $\dfrac{11\times 4 + 11\times 4\times 10\times 6}{\binom{47}{5}}$ for $Pr(B\mid A)$ giving a final probability of
$$\frac{13\times 4\times 12\times 6}{\binom{52}{5}}\times \frac{11\times 4 +11\times 4\times 10\times 6}{\binom{47}{5}}$$


Q:

Concatenating Dynamic SQL commands with UNION returns inconsistent results

I'm testing a report that I've written in T-SQL and I'm having some issues with the results that are being returned. Here is the section of the code that I'm having issues with;
CREATE TABLE #Tables
    (   ID      INT IDENTITY (1,1),
        TenantId        nvarchar(10),
        TaskTable   nvarchar(50),
        RecordTable nvarchar(50),
        RecordColumn    nvarchar(50)    )

SELECT @TSQL AS SQLCommand
    INTO #Commands

INSERT INTO #Tables
    select schema_name(t.schema_id) as TenantId,
                t.[name] TaskTable,
                t2.[name] RecordTable,
                c.[name] RecordColumn
    from sys.tables t, sys.tables t2
    join sys.columns c on t2.object_id = c.object_id
    where t.[name] in ('Task', 'Tasks')
    and t2.[name] in ('TimeRecord', 'TimeRecords')
    and schema_name(t.schema_id) >= 50
    and schema_name(t.schema_id) <> 275     -- Exclude this because it's missing tables
    and c.[name] like 'FK_Task%'
    group by (schema_name(t.schema_id)), t.[name], t2.[name], c.[name]

        union

    select schema_name(t.schema_id) as TenantId,
                t.[name] TaskTable,
                t2.[name] RecordTable,
                c.[name] RecordColumn
    from sys.tables t, sys.tables t2
    join sys.columns c on t2.object_id = c.object_id
    where t.[name] in ('Tasks_NEW', 'Task_NEW')
    and t2.[name] in ('TimeRecord_NEW', 'TimeRecords_NEW')
    and schema_name(t.schema_id) >= 50
    and c.[name] like 'FK_Task%'
    group by (schema_name(t.schema_id)), t.[name], t2.[name], c.[name]

        union

    select schema_name(t.schema_id) as TenantId,
                t.[name] TaskTable,
                t2.[name] RecordTable,
                c.[name] RecordColumn
    from sys.tables t, sys.tables t2
    join sys.columns c on t2.object_id = c.object_id
    where t.[name] in ('Tasks_WOM', 'Task_WOM')
    and t2.[name] in ('TimeRecord_WOM', 'TimeRecords_WOM')
    and schema_name(t.schema_id) >= 50
    and c.[name] like 'FK_Task%'
    group by (schema_name(t.schema_id)), t.[name], t2.[name], c.[name]

SET @MaxRownum = (SELECT MAX(id) FROM #Tables)
SET @Iter = (SELECT MIN(id) FROM #Tables)

WHILE @Iter <= @MaxRownum
BEGIN
     SELECT @TenantId = TenantId, @TaskTable = TaskTable, @RecordTable = RecordTable, @RecordColumn = RecordColumn
        FROM #Tables
             WHERE id = @Iter

SET @TSQL =     N'SELECT '+@TenantId+' AS TenantId, COUNT(*) AS IntegrationDates, (SELECT COUNT(*) FROM [Dynamic].['+@TenantId+'].['+@TaskTable+']  WHERE SystemId NOT IN (SELECT '+@RecordColumn+' FROM [Dynamic].['+@TenantId+'].['+@RecordTable+'])) AS MissingTimeRecords FROM [Dynamic].['+@TenantId+'].['+@TaskTable+']  WHERE IntegrationDate IS NULL'

INSERT INTO #Commands
SELECT @TSQL AS SQLCommand

SET @Iter = @Iter + 1

END

SELECT @TSQLFinal = IsNull(@TSQLFinal + '
UNION
', '' ) + SQLCommand
FROM #Commands

CREATE TABLE #Results   (   ApplicationId INT,
                                                IntegrationDates INT,
                                                MissingTimeRecords INT)
INSERT INTO #results
EXEC (@TSQLFinal)

If I SELECT * FROM #Commands I get to see all of the commands built by my Dynamic Statement, which is 275 rows in this case.
This is perfect, but if I then SELECT * FROM #results I do not get 275 rows. I sometimes get 30 rows, sometimes 100, but it's never consistent.
What I'm expecting here, is that all of my commands in the #Commands temp table, get executed and the results of these commands are put into the #results table (hence the UNION)
Can anything spot what might be going wrong here at all?
Thanks in advance!
Tom.

A:

As EzLo said: Don't use variable assignment through SELECT to aggregate values. You do this when setting @TSQLFinal. Try with STRING_AGG() if you have SQL Server 2017+ or FOR XML PATH('') on lower versions.


Q:

add click event to many control

I have many controls in my form. for example 120 labels in one panel. and i want when user clicked on each label just call same function with same parameter.
Now i used like this :
        private void label67_Click(object sender, EventArgs e)
    {
        ChangeToTextbox(sender);
    }

    private void label66_Click(object sender, EventArgs e)
    {
        ChangeToTextbox(sender);
    }

    private void label65_Click(object sender, EventArgs e)
    {
        ChangeToTextbox(sender);
    }

    private void label64_Click(object sender, EventArgs e)
    {
        ChangeToTextbox(sender);
    }

now can i make easy way to call ChangeToTextbox function when user clicked in any label?

A:

Add the same OnClick handler for all labels on the panel:
private void Form1_Load(object sender, EventArgs e)
{
    panel1.Controls.OfType<Label>().ToList().ForEach(l => l.Click += label_Click);
}

private void label_Click(object sender, EventArgs e)
{
    ChangeToTextbox(sender);
}


Q:

Ordenar consulta de forma intercalada

Estou tentando listar uma determinada categoria de produto. exemplo.
$consulta = $pdo->prepare("SELECT * FROM msg where tema = :tema;");
$s = 'mensagens-de-aniversario';
$consulta->bindParam(":tema", $s, PDO::PARAM_STR);
$consulta->execute();
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)){

if($linha['voz'] == 'vozfeminina'){
 echo "
".$linha['voz']." A
";
}

if($linha['voz'] == 'vozmasculina'){
 echo "
".$linha['voz']." B
";
}

}

Esta listando assim:
vozfeminina A, vozfeminina A, vozmasculina B, vozmasculina B

Teria uma forma de quando fazer essa consulta listar todos os produtos na ordem:
"vozfeminina A"  |  "vozmasculina B"  |  "vozfeminina A"   |  "vozmasculina B"...

Estou usando conexão PDO do mysql.

A:

É possivel ordernar utilizando uma sub-consulta e variáveis:
SELECT voz, produto, outra_coluna
FROM (
    SELECT voz, produto, outra_coluna
    , IFNULL(@orderA, @orderA := 0)
    , IFNULL(@orderB, @orderB := 0)
    , IF(voz = 'vozfeminina', @orderA := @orderA + 1, IF(voz = 'vozmasculina', @orderB := @orderB + 1, null)) AS idx
    FROM msg
    WHERE tema = :tema
) AS a
ORDER BY idx, voz;

Exemplo funcionando: http://sqlfiddle.com/#!9/663f3/4


Q:

Finding a basis for the nullspace

$A$=\begin{bmatrix}-2 & 5 & 3 & -1\\ 0 & 1 & -4 & 2\\ 6 & -14 & -13 & 1\\ 0 & 0 &0 &0\end{bmatrix}
I need to find the null space for this matrix. After performing row operations $R_3 + 3R_1$, then $R_{new row 3}$ + $R_2$, I got the reduced row echelon form. (the variable I chose were $x$, $y$, $z$, $w$). I identified the pivot variables as $x$ and $y$, after expressing both of these in terms of the free variables $z$ and $w$, I got $$\begin{bmatrix}
x\\
y\\
z\\
w\\
\end{bmatrix} = z \begin{bmatrix}
23/2\\
4\\
1\\
0\\
\end{bmatrix} + w\begin{bmatrix}
-11/2\\
-2\\
0\\
1\\
\end{bmatrix}$$, and then chose both the column vectors alongside $z$ and $w$ as the basis for the nullspace. However the answer given is $$\begin{bmatrix}
23\\
8\\
2\\
0\\
\end{bmatrix}\begin{bmatrix}
9\\
4\\
0\\
2\\
\end{bmatrix}$$. What am I doing wrong?

A:

If matrix
$$
\begin{bmatrix}-2 & 5 & 3 & -1\\ 0 & 1 & -4 & 2\\ 6 & -14 & -13 & 1\\ 0 & 0 &0 &0\end{bmatrix}
$$
Row reduced form of matrix is
$$
\begin{bmatrix}1 & 0 & -\frac{23}{2} & 0\\ 0 & 1 & -4 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 &0 &0\end{bmatrix}
$$
So basis is
$$
\begin{bmatrix}23 \\ 8 \\ 2 \\ 0\end{bmatrix}
$$
If matrix is
$$
\begin{bmatrix}-2 & 5 & 3 & -1\\ 0 & 1 & -4 & -2\\ 6 & -14 & -13 & 1\\ 0 & 0 &0 &0\end{bmatrix}
$$
Row reduced form of matrix is
$$
\begin{bmatrix}1 & 0 & -\frac{23}{2} & -\frac{9}{2}\\ 0 & 1 & -4 & -2\\ 0 & 0 & 0 & 0\\ 0 & 0 &0 &0\end{bmatrix}
$$
So basis is
$$
\begin{bmatrix}23 \\ 8 \\ 2 \\ 0\end{bmatrix}
\begin{bmatrix}9 \\ 4 \\ 0 \\ 2\end{bmatrix}
$$


Q:

How do I troubleshoot possible drive issues on ESXi 6.7?

I have a Dell Poweredge R630 with 4 drives in a RAID. I'm not sure if it's RAID 10 or RAID 5 because I didn't order or set up the server originally and I'm just the default network admin, it's not my primary job. The server is running vSphere Essentials ESXi 6.7 and it hosts half a dozen VMs.
I use Altaro VM backup running in a VM on another host to backup this host as well as an ESXi 6.5 host. When I started backing up the VMs on this host I found that the backups would randomly fail. Any given night 2 or 3 of the 5 VMs I'm backing up would fail but not the same VMs each night. A couple weeks ago they started to always fail.
In working with Altaro support to find out why it was failing they found this in the Altaro logs:
2019/09/24 00:11:31.034: DISKLIB-LINK : "san://snapshot-155[Storage] VMName/VMName.vmdk@192.168.1.1:443?User@domain.local/XXX" : failed to open (Unknown error).
2019/09/24 00:11:31.034: DISKLIB-CHAIN : "san://snapshot-155[Storage] VMName/VMName.vmdk@192.168.1.1:443?User@domain.local/XXX" : failed to open (Unknown error).
2019/09/24 00:13:18.446: VixDiskLib: Detected DiskLib error 2338 (NBD_ERR_NETWORK_CONNECT).
2019/09/24 00:13:18.446: VixDiskLib: VixDiskLib_Read: Read 437 sectors at 19619760 failed. Error 14009 (The server refused connection) (DiskLib error 2338: NBD_ERR_NETWORK_CONNECT) at 5235.

Their support says these log entries, I assume the last line in particular, came directly from the host.
Not being an ESXi expert I'm not totally sure which log files to look at in ESXi to try to figure out what is going wrong, to confirm it's a drive problem on the host, and to determine which drive it is so I can replace it. So far the vCenter is not raising any alerts or warnings about a drive problem and the host is not indicating a problem with the array.
Another data point: Most of these VMs are running Windows. Each of those is running Windows backup internally to a separate drive and those all complete with no errors. I find it interesting that Windows is able to backup its drives from inside the VM but there is a read error when ESXi is making the backup from outside.

A:

It's not a host hard drive problem. The log file is telling you that it failed to open the virtual hard drive of the VM because of a network error.
My guess is that the backups of the VM's that are on the same host as the Altaro backup probably don't fail. Is that right?


Q:

How to extend String.Space similar to String.Empty in c#?

I am trying to extend the System.String and add one more static field String.Space which represents a single space " " just like how Microsoft implemented String.Empty in the namespace Using System;. I am not able to implement this extension please help.

I wanted to implement a kind of field extension...

wanted the result like

A:

You could have a static class like so;
public static class Strings
{
    public const string Space = " ";
}

And use it in your code like;
FullName = FirstName + Strings.Space + MiddleName + Strings.Space + LastName;

However, the ultimate goal is to make the code maintainable, be reasonably efficient and reduce the likelihood of errors. With that in mind, it's best to reduce the number of concatenations and supply just the values that are needed. To that end a simple format string would be a cleaner approach; (pre C#6);
FullName = string.Format("{0} {1} {2}", FirstName, MiddleName, LastName);

And if C#6+;
FullName = $"{FirstName} {MiddleName} {LastName}";

Why would you use those last two approaches? Well, it comes down to separation of concerns. Leave the string formatting to string.Format() and simply supply the values you need. You reduce the likelihood of errors by having fewer components in the mix, decrease maintenance overhead by the same and increase efficiency by reducing the number of strings involved to perform the concatenation.
EDIT
As for "Why doesn't c# support extension properties?", I'd extract a quote from Lindos Pechos's link from the C# language development team;

It was of course immediately obvious that the natural companion to extension methods is extension properties. It's less obvious, for some reason, that extension events, extension operators, extension constructors (also known as "the factory pattern"), and so on, are also natural companions. But we didn't even consider designing extension properties for C# 3; we knew that they were not necessary and would add risk to an already-risky schedule for no compelling gain.

Basically it boils down to "There wasn't a compelling need" for extension properties to allow you to create something like string.Space. Maybe in future versions.

A:

Unfortunately the framework (v4.7 at the time of this writing) does not currently support extension properties/fields. See a good write up of this here "Why No Extension Properties?"
Which means you are limited to using an extension method.
One such example:
namespace System.String
{
    public static class Extensions
    {
        public static string Space(this string s)
        {
            return " ";
        }
    }
}

Extension methods require an instance of an object. So it can be used as such:
// Returns " "
var space = "".Space();

Or
// Returns " "
var space = String.Empty.Space();

This falls into one of those "It's not pretty, but it works" categories.


Q:

Why should I never ever use "Convert Premul" on Cycles renders?

On this question, When trying to overlay images using Alpha Over for green screen work , I used premultiply Alpha, it was the only option that would give me clean key without the background bleeding over. A comment states Never use that "Convert Premul" option on Cycles renders. Ever.
Why?

A:

You misread the answer, and my suggestion wasn't terribly clear. Any imager should be "pro" associated (aka crap term "premultiplied") alpha.
There is a good reason, and I will expand this answer when I find some time later.
The bottom line is that only associated alpha models a real-world correlation, where unassociated doesn't.
Only associated alpha manages to model both occlusion and emission. Glows, convolutions,  motion blurs, and a plethora of other transparent / translucent effects can only be modeled with associated alpha.
Think of alpha as selecting the over operation. The Alpha over node actually assumes associated alpha and performs the correct over operation, which is FG+(1-FG.a)BG.RGB.
Unassociated alpha can do none of these things. This is at least one of the reasons that PNGs are never used in a post production pipeline as they are incapable of using associated alpha. From the EXR Technical Introduction:

Calling the color channels “premultiplied” does not mean that the
  color values in an image have actually been multiplied by alpha at
  some  point  during the creation of the image, or that pixels with
  zero alpha and non-zero color channels are  illegal. Non-zero color
  with zero alpha is legal; such a pixel represents an object that emits
  light even though it is completely transparent, for example, a candle
  flame or a lens flare.
In  the  visual  effects  industry  premultiplied  color  channels
  are  the norm, and  application  software packages typically use
  internal image representations that are also premultiplied.

http://www.openexr.com/TechnicalIntroduction.pdf
From the actual TIFF specification, regarding TIFFTAG_EXTRASAMPLES tag that denotes what type of samples are stored:

The difference between associated alpha and unassociated alpha is not just a matter of taste or a matter of maths.
Associated alpha is generally interpreted as true transparency information.

http://www.awaresystems.be/imaging/tiff/tifftags/extrasamples.html
Again, never, ever, use unassociated (crap term "straight" or "key") alpha, and instead associate it. This is what the unfortunately named "Convert Premul" does in the Alpha Over node. However, on direct Cycles renders, it is already associated and is never needed.
There is exactly one edge case that you must unassociate alpha before processing, and that is on colour corrections. To do so, you must be careful and divide all zero regions by a very small number as zero alpha with RGB nonzero is entirely valid, and represents an emission without occlusion.
The only time "Convert Premul" should ever be used is if the imager knows she is feeding it unassociated alpha, but like a good imager, she would never be using anything except the One True Alpha, associated alpha.
Further reading:
Zap Anderssen of Autodesk now:
http://forums.cgsociety.org/archive/index.php?t-278718.html
Larry Gritz of OpenImageIO and Sony Pictures imaging team:
http://oiio-dev.openimageio.narkive.com/aaTdld9U/handling-unassociated-alpha#post2
Jeremy Selan, two time Academy Award winning imager behind OpenColorIO, now at Valve:
https://groups.google.com/forum/m/#!topic/ocio-dev/ZehKhUFqhjc
The Infamous Adobe Photoshop thread. Pay key attention to the names, as there are many imaging legends in it, including Zap Anderssen dismantling one of the head developers of Photoshop, only to have Florian Kainz of ILM back up Zap's take on it:
http://forums.adobe.com/thread/369637
EXR Technical Introduction:
http://www.openexr.com/TechnicalIntroduction.pdf
I likely misspoke in the original question as, from memory, I can't remember exactly what that goofy keying node delivers in terms of alpha. I suspect it is unassociated, which makes the "Convert Premul" option work. Generally however, to avoid oopsies in the code etc., it is prudent to manually associate your alpha and control the merging to prevent data loss in the RGB channels. I still stand by the advice, however; always try to maintain a consistent state of alpha, and when you deviate, do so under scrutiny.


Q:

How to replace characters in a file utf8 in perl?

I have something like this (it works):
perl -C -MText::Unidecode -n -i -e'print unidecode( $_)' unicode_text.txt

and now i want to do the same in the script:
#!/usr/bin/perl -w -CSA

use utf8;
use Text::Unidecode;

while(<>)
{
    print unidecode($_);
}

but it doesn't work.

A:

You should have got the error message
Too late for "-CSA" option

which is what makes the program read the input file as UTF-8-encoded.
Instead you need to put
use open qw( :std :utf8 );

before the while loop, which does the same as -CS on the command line, i.e. to set the STDIN, STDOUT and STDERR handles to UTF-8 encoding


Q:

График справа от cgridview?

Справа от GridView хочу изобразить график с помощью HighchartsWidget. У грида ставлю
'htmlOptions' => array('style' => 'width: 80%'),

Как заставить график рисоваться не после таблицы, а в той же строке? Чую, что проблема в css GridView, так как простой текст тоже отображается строго ниже таблицы.

A:

Надо обернуть грид в див. Грид сам растянется по ширине дива. Например так

<?php $this->widget('CGridView'/* тут вызываем грид */); ?>


Q:

LibGDX: is there a way to check if the window is in focus?

I'm really not sure if this is the solution to my problem, but it's the only thing I can think of.  I'm designing a simple platforming engine in LibGDX, but whenever you drag the game window (or hold the left mouse button over the window pane) for a certain period of time, when you let go the character will fall through the floor due to a build up of acceleration (the longer you hold it the further he'll teleport down after letting go). For some reason the act of dragging the window prevents the ground from stopping the acceleration buildup.  The only solution I can think of is to pause the game when the window is out of focus, but that might be completely wrong.
Thanks.

A:

I solved it by only updating the position if deltaTime is small enough, since deltaTime increases while the window is being dragged.


Q:

Generating a mathematical model of a pattern

Does there exist some algorithm that allows for the creation of a mathematical model given an inclusive set?
I'm not sure I'm asking that correctly... Let me try again...
Given some input set...
int Set[] = { 1, 4, 9, 16, 25, 36 };

Does there exist an algorithm that would be able to deduce the pattern evident in the set? In this case being...
Set[x] = x^2

The only way I can think of doing something like this is some GA where the fitness is how closely the generated model matches the input set.
Edit:
I should add that my problem domain implies that the set is inclusive. Meaning, I am finding the closest possible function for the set and not using the function to extrapolate beyond the set...

A:

The problem of curve fitting might be a reasonable place to start looking. I'm not sure if this is exactly what you're looking for - it won't really identify the pattern so much as just produce a function which follows the pattern as closely as possible.
As others have mentioned, for a simple set there can easily be infinitely many such functions, so something like this may be what you want, rather than exactly what you have described in your question.
Wikipedia seems to indicate that the Gauss-Newton algorithm or the Levenberg–Marquardt algorithm might be a good place to begin your research.

A:

A mathematical argument explaining why, in general, this is impossible:

There are only countably many computer programs that can be written at all.
There are uncountably many infinite sequences of integers.
Therefore, there are infinitely many sequences of integers for which no possible computer program can generate those sequences.

Accordingly, this is impossible in the general case. Sorry!
Hope this helps!


Q:

Warning: non-variable type argument in type pattern is unchecked since it is eliminated by erasure

I'm using Scala 2.10.6 due to corporate restrictions. How can I get rid of the warning:
warning: non-variable type argument Market in type pattern () => Market is unchecked
         since it is eliminated by erasure

in the following definition:
case (payoff: Payoff, mktFun: (() => Market)) => {
    val mkt = mktFun()
    // ...
}

A:

You can, for instance, make a dedicated datatype case class Foo(p: PayOff, f: () => Market) which you can use as a pattern, instead of a generic tuple.
case Foo(payoff, mktFun) => {
    val mkt = mktFun()
    // ...
}


Q:

Angular: Is there any way to add rupee prefix to bootstrap input field?

Here's my html file. I want to add  ₹ prefix to my input field. I'm working on an angular project and using botstrap for html pages.
product.component.html
<form>

        Title
        <input id="title" type="text" class="form-control">

            Price   <==Want to add here
            <input id="price" type="number" class="form-control">

            Category
            <select id="category"class="form-control">
                <option value=""></option>
            </select>

            Image Url
            <input id="imageUrl" type="text" class="form-control">

    <button class="btn btn-primary">Save</button>
</form>

A:

I guess you're looking for this.

Use input-group class to prepend and append text/icon.
Code:

    Price

₹

        <input id="price" type="number" class="form-control">

Reference
Bootstrap 4 Input group


Q:

Are Anti DDoS server farms really effective?

I'm looking to host a web app in a datacenter and I'm considering a few options. All of them seem reputable and claim to offer Anti-DDoS protection.
If just about every hosting provider is offering Anti-DDoS protection, does that mean that a) DDoS attacks are less of a threat because Anti-DDoS technology has caught up or that b) many of these claims are not as solid as advertised and if so, how can I tell if a web hosting company is really DDoS protected?
Thanks.

A:

In my experience, there is no such thing as 100% DDoS protection. The largest DDoS cyber-attacks ever recorded have reached and exceed 1Tbps. Even if some company claims that they can protect you against such an attack, that would be a false statement.  The Internet of Things is perhaps the best mean an attacker can use since the level of security on those devices is extremely low. Therefore, the attackers have all the means to launch extremely large DDoS attacks nowadays.
In principle, the quality of the DDoS protection services you get, depends heavily on how much money you are willing to spend. Most of the ISPs that offer Internet Breakouts to web hosting companies, bundle some sort of DDoS protection. Some Web hosting companies might not choose to do the “washing” of the traffic on the cloud though, and might prefer on-premise devices (for example there are basic DDoS mechanisms on some firewalls or some load balancers).
If you are concerned about having good DDoS protection, I would suggest you to talk to the Web Hosting companies you are interested in, get answers in writing on what kind of DDoS protection they are using and evaluate which one is the best. I would strongly suggest picking a company that has a hybrid DDoS protection environment, meaning that they do traffic “washing” on the cloud first using some 3rd party vendor, and at the same time they also have a second layer of protection using on-premise devices which also acts as a detection mechanism. In general, I would stick with a company that uses well-known vendors in the DDoS protection field such as Incapsula, Arbor, CloudFlare, F5 Networks (ASM Module on Load Balancers), etc.


Q:

How can Searle's Chinese Room argument refute to this argument?

I'm a relatively new student studying philosophy and became interested in the computer models of mind.
I've read John Searle's CR experiment and had a quick thought.
How can CR experiment refute to the below?
If a computer is fed with bunch of data that it actually learns or correctly answers untaught problem, is it not being intelligent?
Say for instance, a system is given a multiplication table from 1 to 100.
It is taught formally and knows how to read the table and give correct outputs of multiplication.
Let's say the computer "learns" how to multiply (say the data above is enough for the computer to actually learn multiplication).
If a user asks "101 x 101?" and the computer correctly answers it, this displays learning and thus capability to think?

A:

If the instructions in the Chinese room were so abstruse that one could actually follow them without indirectly acquiring the ability to read Chinese, the person in there would not learn Chinese.  The problem here is that odds are that over time he actually would learn Chinese, to the point that he only occasionally had to refer to the instructions.  We all know this, because the actual process of speaking Chinese is simpler in human terms, than any description of it.  We are information-based, meaning-seeking animals.  Our language performance ability outstrips our ability to form lexicons and usable grammars by many orders of magnitude.  From the point of view of someone like Winograd in his simplification of Maturana, it is this kind of built-in process that renders finding meaning more natural to us than performing tasks that forms the content of understanding.
But that is not true for a machine.  Instructions are instructions and following them is what the mechanism does.  If those instructions are a heuristic for learning the pattern behind a process, they may uncover that pattern.  But then that heuristic is the program.  The data about multiplication is not the program in your example, and the machine is not learning multiplication, it is displaying its program's ability to recognize and reproduce patterns of behavior.  It has no bias toward finding meaning.  It may borrow ours through simulations of ourselves that we create, but it does not have and understanding  (in the above sense) of its own.
Basically, you are cheating: you are giving the machine a great deal more information than a human starts with, and then ignoring the fact it is there.  So this is not a challenge to the argument, once you include the setup of the machine.  And you are assigning that borrowed power to the machine itself, as if it did not come from outside.


Q:

Post-save callback?

How do I execute a function every time a node is being updated? I tried to use hook_nodeapi, but it looks like that the hook is removed from Drupal 7.
What I want to do is,

add a new field to my content type called 'main image (bool)' to let the admin set a main image.
I am going to use Views module to display nodes, but order nodes by 'main image' field and added date.
so that the first node is always the main image.

to do this, I need to make sure that there is always only one node with 'main image' set to true.

A:

Currently Drupal core does not offer any hook to do actions after a node/entity is inserted/updated/deleted in Database. For example, you can not send an email mentioning the node after the node is inserted because Drupal uses SQL transactions and the node is not yet fully written to database when hook node presave is called so if for any reason the transaction is rolled back, users will receive a false mail.
So Hook Post Action module introduces several new Drupal hooks to overcome this limitation:

hook_entity_postsave
hook_entity_postinsert
hook_entity_postupdate
hook_entity_postdelete
hook_node_postsave
hook_node_postinsert
hook_node_postupdate
hook_node_postdelete

https://drupal.org/project/hook_post_action

A:

The hook has not been removed but splitted up into separate hooks for each $op.
See: http://api.drupal.org/api/search/7/hook_node
For post-save, you want hook_node_insert() and hook_node_update()

A:

I suppose hook_entity_presave could be the hook you're looking for, if you want to act before your node is updated :

Act on an entity before it is about to
  be created or updated.

Or, if you prefer acting after it's updated, take a look at hook_entity_update :

Act on entities when updated.


Q:

How to set the label background image scale to fit in Swift?

I have a label that is used for showing some message. I have created an image that I'd like to set it as my label background. Following is the way I have done it:
challengeCell.message.text = "    You have taken  \(historyArray[indexPath.row]) in this week"

challengeCell.message.backgroundColor = UIColor(patternImage: UIImage(named: "challengeMessage")!)

    //this is a suggested attempt
    challengeCell.message.systemLayoutSizeFitting(UILayoutFittingCompressedSize)

I'd like to have the background image stretch and fill the whole label instead of getting duplicated. Any idea how can I accomplish that?

A:

You can't use a pattern color for this. Use UIImageView to show the background image. Add a property to your custom cell class to hold a reference to the image view:
class ChallengeCell: UITableViewCell {
    let messageBackgroundView = UIImageView()

    override func layoutSubviews() {
        if messageBackgroundView.superview != message.superview {
            message.superview.insertSubview(messageBackgroundView, belowSubview: message)
            messageBackgroundView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                messageBackgroundView.leadingAnchor.constraint(equalTo: message.leadingAnchor),
                messageBackgroundView.trailingAnchor.constraint(equalTo: message.trailingAnchor),
                messageBackgroundView.topAnchor.constraint(equalTo: message.topAnchor),
                messageBackgroundView.bottomAnchor.constraint(equalTo: message.bottomAnchor),
            ])
            messageBackgroundView.contentMode = .scaleToFill
        }

        super.layoutSubviews()
    }

    ...
}

When you want to set the message background, set the image view's image:
challengeCell.messageBackgroundView.image = UIImage(named: "challengeMessage")


Q:

Is it possible to simulate Brownian motion in Blender?

https://en.wikipedia.org/wiki/File:Translational_motion.gif
I want to simulate some molecular dynamics. For that I want some area to fill up with some lipids. All these lipids would be considered as a cylinder object standing vertical in a space. In the best case, all objects should be hanging in the defined area and are wobbling (inner dynamics: like atomic motion) and are colliding with other residues like in the link above.
Any hints or suggestions. Particle physics provide collision but they are not holding objects in the space.

A:

You can use particles to control your object's vertices, and induce Brownian motion in these particles:

Download blendfile here
To achieve this, you need to make sure every vertex of your particle controlled object is assigned a particle. These are the settings I've used for the example above:

You also need to turn off gravity in the Scene tab in the tools panel:

Then, once you have a particle per vertex, you need to run this code to make sure the vertices coordinates are linked to the particle locations:
import bpy

def update_particles( scene ):
    ''' This function runs before every frame change, and it updates the cube's
        vertices' coordiantes with the location values of its particles
    '''

    cube = bpy.data.objects['Cube']
    for vert, particle in zip( cube.data.vertices, cube.particle_systems[0].particles ):
        vert.co = particle.location

# Add vertex --> particle function to frame change app handlers
bpy.app.handlers.frame_change_pre.append( update_particles )

This example isn't a direct solution for what you're aiming for, but rather a direction. To adapt it to your needs, you actually need to manipulate the lipid through some mesh skeleton (or you can rig it and control the pose bones' locations the same way I've manipulated the vertices). This would be easiest and most directly translatable if your lipids are actually simple wireframes with a Skin modifier (you'll need to make sure the Skin modifier is below the particle system modifier though).
Since your scene probably has a lot of molecules, it will likely be more feasible to write a script that automates the generation and setup of particle systems. You'll also need to include all these objects in the frame change handler function.
Not a trivial project, but not unattainable :)

A:

I was able to achieve an effect very similar to the GIF you linked by using the Molecular Script addon. First, download and install Molecular from here: Molecular Script Download (Instructions how to install here).

Start a new blender file and make sure that Object: Molecular Script is enabled under Addons in the User Preferences.
In Object Mode, scale the default cube to .025 along the Z axis (S > Z > .025), then, in Edit Mode, delete the top and bottom faces.
In Object Mode, add a new cube (Shift + A > Mesh > Cube) and scale it to 1.5 along the X and Y Axes (S > Shift + Z > 1.5) and .053 along the Z Axis (S > Z > .053).
Under Display on the Object Properties tab, set both cubes to a Maximum Draw Type of Wire.
With the larger outside cube selected, enable Collision on the Physics tab.
Select the smaller inside cube with the deleted faces and under the Particles tab create a new particle system. (You should also notice the Molecular Script panel added to this tab).
Under Emission set the Number to 25, the End to 1, and Lifetime to 250. Enable Size Deflect under Physics. Also make sure Emit From is set to Faces. Under the Velocity panel, set Random to 0.250 (this is not shown below but it helps with particle motion).
Add a new Cylinder mesh and move it to layer 2 (Shift + A > Mesh > Cylinder > M > 2).
Back on the particle settings for your inside cube, under Render, set the method to Object and set the Dupli Object to your cylinder. The object Size should be 0.050.
Still on the Particles tab, scroll down to the Molecular Script panel and enable Molecular Script. The fundamental function of this addon (in a nutshell) is to allow particle collisions.
Under Density, check Calculate particles weight by density; under Collision, check Activate Self Collision and set both Friction and Damping to 0 (unless you want your molecule motion to decay.)
Now scroll down and click Start Molecular Simulation (Icon with radioactive symbol) - in the top view you should already see the result you want.

You now have a basic simulation running. Just remember a couple things:

Before rendering, need to turn off Emitter under the Render tab of your particle system so that the emitter does not show up in your render, and you will also have to restrict rendering on the collision object by unchecking its camera in the Outliner.
To change the initial motion, play around with the particle Velocity Random value that we set earlier, and also the Friction and Damping under the Molecular Script panel.

Here is a final .Blend file for you to play with as well:


Q:

how to select the certain properties from object?

please help solve the problem.
i have follow object:
  defaults = {
    title: undefined,
    yMax: undefined,
    yMin: undefined,
    yPeriod: undefined,
    xMax: undefined,
    xMin: undefined,
    xPeriod: undefined,
    dots: {}
  }

I need to get an array of properties that are of type "not object".
i.e. i need get follow:
[title, yMax, yMin, yPeriod, xMax, xMin, xPeriod]

A:

You can check type of each property with typeof

var defaults = {
   title: undefined,
   yMax: undefined,
   yMin: undefined,
   yPeriod: undefined,
   xMax: undefined,
   xMin: undefined,
   xPeriod: undefined,
   dots: {}
 }

 var a = [];
 for (prop in defaults) {
   if (typeof defaults[prop] != 'object') a.push(prop);
 }

 console.log(a);


Q:

Is it reasonable to use different Start Levels to manage the dependencies between OSGi bundles?

My team are trying to develop a new system based on OSGi, and now we have more than 50 bundles and counting. The problem is, there is dependency between bundles. For example, when bundle A startup, it will register a service to OSGi, and when bundle B startup, it will use that service. Therefore I need bundle A startup earlier than bundle B. To make this happen, I set the start level of bundle A less than bundle B.
We tried to use ServiceTracker to avoid setting start levels, but when the services count growing up, it become difficult to manage and to understand the whole system.
However, I found this article on the internet: OSGi and Start Levels. I'm not sure with two sentences in it:

Start order within the start level is indeterminate!
On the whole, when working with start levels, never depend on start order. Think about start levels as a management issue, not a development time issue.

Does it mean that start level will not decide the start order? Then when should I use it?
Is it reasonable to use different Start Levels to manage the dependencies between OSGi bundles?
It is possible to make all the bundles being a dynamic module(use ServiceTracker to track all the services it use), but it takes more time and demand senior developers, and the system become difficult to debug.

A:

My answer is similar to Bertrand: you should consider using a higher-level component-based abstraction for your solution: SCR, iPOJO, Blueprint, etc.
Using start levels to control dependencies is a little like using thread priorities in Java to fix race conditions.  Sure, you might make things work, sort of, for a while, but you'll go insane in the process--and you'll eventually lose anyway.
Start levels are useful.  The canonical example is if you need to display a splash screen while starting your OSGi-based GUI application by putting the code for it in a bundle.  Without start levels there's no way to ensure the splash screen would end up displayed when it's supposed to be, but using start levels this becomes trivial.
That said, I've used start levels to resolve dependency ordering bugs found in third-party bundles (e.g., Spring), though this didn't involve service ordering but assumptions about finding resources (with Spring, an XSD for the Spring Integration custom namespace).

A:

Using start levels to manage dependencies between services is a bad idea - the Services Component Runtime (SCR) is a much better way of managing that, and if done right will take care of all the dependencies, startup order, restarting components when their required services are restarted, etc.
If you're using Maven, the Apache Felix SCR plugin ( http://felix.apache.org/site/scr-annotations.html ) makes it easy to create SCR-managed services using just a few Java annotations. Apache Sling's code ( http://sling.apache.org ) is full of examples using this.


Q:

Did the Brotherhood really exist?

In George Orwell's 1984, there is a mention of a secretive organization named Brotherhood whose main aim is to rebel against the Big Brother, and the Party in general.
In the later part of the prose, we find out that O' Brien was actually working for the Party the whole time in order to find and capture rebels like the protagonist. Does that mean Goldstein's Book, and the Brotherhood itself, were just made up by the Party to achieve the task of separating out the rebels? Or did the Brotherhood really exist at some point?

A:

The only evidence of the existence (or non-existence) of the Brotherhood comes directly from the Party itself. As such, its existence (or non-existence) may simply be part of the mystique of Big Brother and the party apparatus.
Winston is told about the Brotherhood on a daily basis.

A day never passed when spies and saboteurs acting under his directions were not unmasked by the Thought Police. He was the commander of a vast shadowy army, an underground network of conspirators dedicated to the overthrow of the State. The Brotherhood, its name was supposed to be.

Whereas Julia is entirely unaware of the Brotherhood's supposed existence, implying that that knowledge of the Brotherhood-mythos is restricted to lower echelon Party members.

He noticed that she never used Newspeak words except the ones that had passed into
everyday use. She had never heard of the Brotherhood, and refused to believe in its existence. Any kind of organized revolt against the Party, which was bound to be a failure, struck her as stupid.

With that in mind, since the Brotherhood is used as a tool to entrap would-be rebels like Winston (just like the fake bric-a-brac shop) it seems more likely than not that the Brotherhood doesn't exist or else the risk would be that by promoting it, the Party could inadvertently strengthen resistance to Big Brother.

That all being said, we shall let O'Brien have the final word.

‘Does the Brotherhood exist?’
‘That, Winston, you will never know. If we choose to set
you free when we have finished with you, and if you live to
be ninety years old, still you will never learn whether the
answer to that question is Yes or No. As long as you live it
will be an unsolved riddle in your mind.’

And that goes for you too, dear reader.


Q:

oracle update value with two inner joins

Hello i'm trying to update the value of a column in a table with the value of another table with two inner joins.
But my query keeps giving an error, is this even possible with Oracle to update a table with two inner joins.
update finaltbl1
(
select table1.old_val, table3.new_val
from
table1
inner join
table2
on table1.id = table2.id
inner join
table3.name = table2.name
) finaltable1
set
x.old_val = y.new_val

Or would it have to be done with a "merge into"
Thanks,

A:

You can update like that:
update table1 t1
set old_val = (
   select table3.new_val
   from table2 inner join table3 on table3.name = table2.name
   where table2.id = t1.id
)
where exists (
   select table3.new_val
   from table2 inner join table3 on table3.name = table2.name
   where table2.id = t1.id
)


Q:

Looking for a common word meaning hands and feet as well

I am looking for a word that describes/means the appendices at the ends of limbs (namely hands and feet), meaning a singular one of them.
Bonus: a word that describes/means all of them

A:

For the plural, consider extremities.  Its singular is extremity.
From en.wiktionary, extremity has a sense (among others) of “A hand or foot”.
(It also has a sense of “A limb”, ie an arm or leg, so may be imperfect for your needs.)
As noted in tunny's comment, collinsdictionary.com shows similar definitions, for extremities and extremity respectively, with emphasis added:

• (formal) hands and feet
  • a limb, such as a leg, arm, or wing, or the part of such a limb farthest from the trunk

The terms appendage and appendages are relevant too, although rather less specific to hands and feet than are extremity and extremities.   From en.wiktionary, appendage means “an external body part that projects from the body”.  Most humans have five main appendages, ie head, arms, legs.  Typical human males have another appendage, or member, sense 4.  I don't know if breasts count as appendages.  If we count fingers and toes as minor appendages, I suppose noses and ears should count as well.


Q:

Unity pong game ball physics slowing issue

In my game for pong, the ball is supposed to bounce and never become slower. However, the ball is steadily slowing down over time. I will put an image of the ball object and the scripts.
 Here is the ball properties on the left

Here is the ball script
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour
{
    public float ballVelocity = 3000;

    Rigidbody rb;
    bool isPlay;
    int randInt;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
        randInt = Random.Range(1,3);
    }

    void Update()
    {
        if (Input.GetMouseButton(0) && isPlay == false)
        {
            transform.parent = null;
            isPlay = true;
            rb.isKinematic = false;
            if (randInt == 1)
            {
                rb.AddForce(new Vector3(ballVelocity, ballVelocity, 0));
            }
            if (randInt == 2)
            {
                rb.AddForce(new Vector3(-ballVelocity, -ballVelocity, 0));
            }
        }
    }
}

and here is the bounce physics image

and since I have no idea why it won't work, here is my physics project settings

A:

The reason why this is happening is because of the randomness being added. All it takes is it to hit harder in one direction one than the opposite direction. Eventually, idk after how long of a time, but it will finally settle at a velocity of 0. To fix this, you need to remove the drag coefficient if you haven't already. Next, you need to clear whatever the current velocity is from the ball. "rigidbody.velocity = Vector3.zero;" should do it for you. After that, you can either generate a new velocity directly using some maths that I do not know off of my head, or add a new force that is no longer dependent on the previous condition of the ball. I hope this helps, and if not, leave a comment and let's see if we can't find a better solution :)


Q:

How can I remove asset metadata and compress the original rendition in a workflow?

I am trying to strip off the metadata from the original rendition of a uploaded image in DAM or compress it to reduce the size.
Are there any AEM out of the box APIs to accomplish this? I am trying to put the behaviour in a workflow process step in AEM 6.2.

A:

The recommended way for modifying DAM metadata is to use custom workflows.
If you are trying to modify the meta-data persisted within the file (for example some image files have location and copyright information) then you will need to use one of many API's available in the libraries shipped with AEM or use 3rd party libraries.
Alternatively, if you want to change the meta data persisted with you DAM asset, you will need to use your custom workflow to update/modify the meta data that is extracted from the DAM assets.
Either way, a lot of this depends on what metadata you are planning to extract or modify and this will have an impact on whether you can use builtin libs or 3rd party libs.


Q:

According to the Westminster Confession, what is the Biblical basis for the belief that the guilt of Adam and Eve was imputed to all mankind?

As a recent answer observes, the Westminster Confession of Faith explains:

Our first parents, being seduced by the subtilty and temptation of Satan, sinned, in eating the forbidden fruit. This their sin, God was pleased, according to His wise and holy counsel, to permit, having purposed to order it to His own glory.
II. By this sin they fell from their original righteousness and communion with God, and so became dead in sin, and wholly defiled in all the parts and faculties of soul and body.
III. They being the root of all mankind, the guilt of this sin was imputed; and the same death in sin, and corrupted nature, conveyed to all their posterity descending from them by ordinary generation.*

What Biblical basis does the Westminster Confession imply or state supports the statement, "the guilt of this sin was imputed"?  If the Confession itself makes no such support, are there authoritative commentaries on the Confession (and only on the Confession) that provide such basis, and, if so, what is claimed?
Please don't answer the more general question, "What is the Biblical basis for the belief that the guilt of Adam and Eve was imputed to all mankind?"  That is not what is being asked here.  (Thank you.)

* VI.1-3

A:

The closest things we have to an "authoritative" commentary on the Westminster Confession are the two catechisms that were published alongside it.1  Both the Confession and those catechisms have attached to them "scripture proofs" that were appended somewhat hastily after the original writing of the documents, and which are sometimes criticized as being incomplete and/or too simple.
But these are the best we have available with which to answer your question.  On the clause "They being the root of all mankind, the guilt of this sin was imputed," the Confession lists the following passages as proofs: Genesis 1:27–28; Genesis 2:16–17; Acts 17:26; Romans 5:12, 15–19; and 1 Corinthians 15:21–22, 45, 49.  Of these, only the Romans and Corinthians passages are relevant to the second half of the phrase.  In the Confession, they read:

Romans 5
12 Wherefore, as by one man sin entered into the world, and death by sin; and so death passed upon all men, for that all have sinned. 15 But not as the offence, so also is the free gift. For if through the offence of one many be dead, much more the grace of God, and the gift by grace, which is by one man, Jesus Christ, hath abounded unto many. 16 And not as it was by one that sinned, so is the gift: for the judgment was by one to condemnation, but the free gift is of many offences unto justification. 17 For if by one man's offence death reigned by one; much more they which receive abundance of grace and of the gift of righteousness shall reign in life by one, Jesus Christ.) 18 Therefore as by the offence of one judgment came upon all men to condemnation; even so by the righteousness of one the free gift came upon all men unto justification of life. 19 For as by one man's disobedience many were made sinners, so by the obedience of one shall many be made righteous.
1 Corinthians 15
21 For since by man came death, by man came also the resurrection of the dead. 22 For as in Adam all die, even so in Christ shall all be made alive. 45 And so it is written, The first man Adam was made a living soul; the last Adam was made a quickening spirit. 49 And as we have borne the image of the earthy, we shall also bear the image of the heavenly.

The verses in italics above (Romans 5:12, 19) are cited in answer 25 of the Larger Catechism, the one that most closely deals with this subject.

Some denominations do have commentaries on the Confession that they regard as authoritative; the RPCNA is one such example.  But the broader body of Reformed theology does not hold that any specific commentator's viewpoint is authoritative, though some are clearly more respected than others.  Commonly cited commentaries include Robert Shaw's (1845) and A. A. Hodge's (1869).


Q:

"Access denied" exception is thrown, though the account has access

I'm using a service account to delegate domain wide security in order to pull a user listing from our Google Apps for Education instance via the Directory API and the PHP client library.
I'm fairly certain my service account has all the correct security because it's able to pull a listing using the API reference's "try it" feature.
So, at this point, everything is pointing toward an issue with my code but I can't seem to figure out where:
<?php
require 'vendor/autoload.php';

$clientEmail = '<>@developer.gserviceaccount.com';
$privateKey = file_get_contents(__DIR__ . '/access.p12');
$scopes = array(
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
);

$credentials = new Google_Auth_AssertionCredentials($clientEmail, $scopes, $privateKey);
$credentials->sub = 'service.account@my.domain';

$client = new Google_Client();
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired())
{
    $client->getAuth()->refreshTokenWithAssertion();
}

$directory = new Google_Service_Directory($client);

$result = $directory->users->listUsers(array('domain' => 'my.domain'));

var_dump($result);

The code above throws the following error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: ' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358

Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{
  "error" : "access_denied",
  "error_description" : "Requested client not authorized."
}' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358

Call Stack:
    0.0010     132792   1. {main}() C:\wamp\www\quick\index.php:0
    0.0260    1060248   2. Google_Auth_OAuth2->refreshTokenWithAssertion() C:\wamp\www\quick\index.php:18
    0.9230    1163560   3. Google_Auth_OAuth2->refreshTokenRequest() C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php:309

A:

The call stack should identify the specific line where this error occurred. Note that the second line in the stack seems to point to line 18 of your script, where the code indeed relates to OAuth verification:
$client->getAuth()->refreshTokenWithAssertion();

In other words, when you try to refreshTokenWithAssertion, Google says "access_denied because Requested client not authorized". If you're trying to identify where in your script you hit the error, I think that should answer your question.
If you want to figure out why it got an error, I'd do some google searches for refreshTokenWithAssertion plus that error message and see if you find any other developers working through a similar problem. For example by doing that google search I found this other page on SO that may help you.
Good luck!


Q:

Accessing clipboard in Electron

I would like to monitor whether the user has copied something to the clipboard while using another application and then save what he or she has copied in my nodejs (electron) application. How could I do this?
As an example:
The user uses his/her browser and selects a URI and then copies the URL to the clipboard. I then want to copy the selected URL from the browser window and use it in my nodejs application.
I am using nodejs with electron on OSX.

A:

Electron exposes a (partly experimental) clipboard API that should serve your needs.
Strangely, there seems to be no callback method available to react on new content, you may have to keep polling clipboard.read and diff its content.


Q:

Performance counter for Clojure (using core.async)

I am wondering what is the best way to implement performance counters in Clojure for a particular task that runs concurrently.
I usually end up having something like this:
(defn -main [& args]
  (let [c (async/chan)]
    (doseq [_ (range 50)]
      (async/thread
        (async/>!! c

              (doseq [r (chunk-of-work)]
                (println r)
                (doall (pmap #(work %) r))))

        )
      )
    )

 (while true
      (async/<!! c))
  )
)

What would be the best way of counting how many messages I am getting through the channel every second? The code is indented for better readability.

A:

Have you considered ztellman's Narrator. It's a package for

"analyzing and aggregating streams of data"

There's plenty of examples, including one for the rate of messages over a period.
I haven't actually used it, just remembered reading its docs and it having this kind of aggregation build in.


Q:

kinect v2 grey screen in kinect studio. Likely USB controller issue? Are there any work arounds for this issue?

So I've got a few Kinect v2s and am hoping to set up an array of them to get a 3D recording of an area in space (Eventual goal is to build a 360 image from multiple point clouds) But at the moment I can't even get one working on a machine.
I've installed the official SDK onto a windows 10 device and when opening the kinect studio I get nothing but a grey screen when connected to the kinect. Running the kinect configuration verfier says the USB controller is unknown and the system is waiting for the kinect to respond. The kinect itself does not light up, and it's cooling fan does not turn on.
I have reinstalled the SDK, tried 3 different kinects, tried various drivers and troubleshooting guides, and still cannot get anything out of the kinect.
The best answer I've found is that only some controllers are compatible, but every PC I have tried (currently 5 machines) have "Intel(R) USB 3.0 eXtensible Host Controller - 1.0 (Microsoft)" So basically do I really have to get a PCI USB controller or another machine, or is there any way to get the current system to work with the kinect v2 at all.
Also if I do need to buy a new device or PCI card are there any recommended for a setup that would idealy run 4-5 kinects?

A:

Unfortunately, the Kinect V2 prevents you from simultaneously running more than one Kinect on a system:

Sensor Acquisition and Startup
  Kinect for Windows supports one sensor, which is called the default sensor. The KinectSensor Class has static members to help configure the Kinect sensor and access sensor data.

Kinect API Overview
A workaround that I've used in the past is to have 1 computer for every Kinect (doesn't have to be fancy, just enough to run it) and then network all the machines together with a router. Designate one machine to be the controlling machine (handles turning on/off of other Kinects). Depending on what you plan on doing to the data, it may be helpful to have those other machines perform some pre-processing and leave the stitching off all the Kinects' feeds up to the controlling machine.
As far as the USB controller goes, I'm running Kinect v2 on that exact one, so other than that malfunctioning, I think you're fine. Have you tried running the "Kinect v2 Configuration Verifier" to see what it suggests? Kinect v2 Configuration Verifier


Q:

RESTful API - Serialization vs 'parsing'

I'm currently developing a RESTful API in Java using Jersey for an old, quite complex system. We are looking to support two forms of input - JSON and XML.
At this point I'm considering two ways of implementing the API - the first is to create a series of annotated POJOs to which the incoming request can be mapped to.
The second would be to convert any XML requests to JSON and parse the JSON manually.
Personally, the second way seems more flexible to me at this point, especially since some of the objects in the system are very complicated.
Basically I'm wondering if there are any benefits towards the first options (or drawbacks from the second) that I should consider?
EDIT: To elaborate a bit more, in my case, there are tons of classes which can't be annotated at this stage (this application has been actively developed for over ten years). If I'm going to go down the POJO route, I'm going to have to create a whole bunch of new 'serialization' objects whose purpose is to basically just to serialize to and from XML/JSON.
These classes will need to be managed to be kept up to do date with the actual model classes (of which there may be multiple representing the same object) which is why I'm thinking of going down the 'manual' method.
Were this a new project, I would definitely consider the use of annotations, but given the current situation, I'm unsure as to whether it is the best option.

A:

Both the benefit of the first and the drawback of the second is that  there's very little work for you to do with the first method. POJOs with JAXB annotations are definitely the way to go with Jersey unless you just can't make it work--like if you just can't get it to represent the XML/JSON that you want it to. In general, though, you get XML and JSON input and output virtually for free.


Q:

Combinatorial Proof: $n! = 1+\sum\limits_{r=1}^{n-1}( r\cdot r!)$

To show it is true $r\times r!$ can be algebraically decomposed as $(r+1)!-r!$
But I am trying to think of a combinatorial proof. If $S$ is the set of all permutations of $\{1,2,\cdots ,n\}$ then I need a definition for the mutually non overlapping subsets $S_r$ whose union is $S$. So I will have $|S|=\sum|S_r|$. I am unable to think of such a decomposition.

A:

Hint: We are splitting up into the permutations which do not fix $1$, (There are ($(n-1)\times (n-1)!$) of these), and the ones that do (everything else).  To count the ones which fix $1$, we split into the $(n-2)\times(n-2)!$ permutations that do not fix $2$, and the left over number which do fix $2$.  Continuing in this way we get your sum.  (The one comes from the identity permutation)


Q:

Angular AOT build error - Maximum call stack size exceeded, resolving symbol XXX in Path

I have create an Angular library contains the services in my project
and I have imported the library inside the project and test it without any problems.
But when I am trying to make an AOT build for my angular project
this error appear
Error: Maximum call stack size exceeded, resolving symbol SimpleAuthService in C:/i.rabeea/workspaces/hero/fulfillment_angular/node_modules/zwp-modules/auth/index.d.ts, resolving symbol SimpleAuthService in C:/i.rabeea/workspaces/hero/fulfillment_angular/node_modules/zwp-modules/auth/index.d.ts, ...
at syntaxError (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:1699:2)
at simplifyInContext (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:24949:17)
at StaticReflector.simplify (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:24961:7)
at StaticReflector.annotations (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:24388:38)
at NgModuleResolver.resolve (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:14720:34)
at CompileMetadataResolver.getNgModuleMetadata (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:15372:58)
at addNgModule (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24268:58)
at C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24279:14
at Array.forEach (<anonymous>)
at _createNgModules (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:24248:8)
at analyzeNgModules (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24153:14)
at analyzeAndValidateNgModules (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\@angular\compiler.es5.js:24133:19)
at AotCompiler.analyzeModulesAsync (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\compiler\bundles\compiler.umd.js:23797:46)
at CodeGenerator.codegen (C:\i.rabeea\workspaces\hero\fulfillment_angular\packages\compiler-cli\src\codegen.ts:41:10)
at C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\src\main.ts:19:84
at Object.main (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\@angular\tools\@angular\tsc-wrapped\src\main.ts:136:12)
at Object.runInternal (C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\src\main.ts:24:10)
at C:\i.rabeea\workspaces\hero\fulfillment_angular\node_modules\src\plugin.ts:64:21
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at Function.Module.runMain (module.js:667:11)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:607:3

And this is the script that make the problem
"build:aot:prod:base"
When I remove this token "cross-env BUILD_AOT=1" from script it work will, but I need this when run the app in prodution.
"scripts": {
"build:aot:prod:base": "npm run clean:dist && npm run clean:aot && cross-env BUILD_AOT=1 npm run webpack -- --config config/webpack.prod.js  --progress --profile --bail",
"build:aot:dev-conf": "cross-env CONF_FILE=./config.dev.json npm run build:aot:prod:base",
"build:aot:prod-conf": "cross-env CONF_FILE=./config.prod.json npm run build:aot:prod:base",
"build:aot:prod": "cross-env CONF_FILE=./config.dev.json npm run build:aot:prod:base",
"build:aot": "npm run build:aot:prod",
"build:dev": "npm run clean:dist && npm run webpack -- --config config/webpack.dev.js --progress --profile",
"build:docker": "npm run build:prod && docker build -t angular2-webpack-start:latest .",
"build:prod": "npm run clean:dist && npm run webpack -- --config config/webpack.prod.js  --progress --profile --bail",
"build": "npm run build:dev",
"ci:aot": "npm run lint && npm run test && npm run build:aot && npm run e2e",
"ci:jit": "npm run lint && npm run test && npm run build:prod && npm run e2e",
"ci:nobuild": "npm run lint && npm test && npm run e2e",
"ci:testall": "npm run lint && npm run test && npm run build:prod && npm run e2e && npm run build:aot && npm run e2e",
"ci:travis": "npm run lint && npm run test && npm run build:aot && npm run e2e:travis",
"ci": "npm run ci:testall",
"clean:all": "npm run rimraf -- doc coverage dist compiled dll",
"clean:dll": "npm run rimraf -- dll",
"clean:aot": "npm run rimraf -- compiled",
"clean:dist": "npm run rimraf -- dist",
"clean:install": "npm set progress=false && npm install",
"clean": "npm cache clean --force && npm run rimraf -- node_modules doc coverage dist compiled dll",
"deploy:prod": "npm run clean:all && npm prune --force && npm install && npm version patch",
"deploy:test": "npm run clean:all && npm prune --force && npm install && npm test && npm run build:aot:prod",
"docker": "docker",
"docs": "npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/",
"docs:compodoc": "compodoc -p tsconfig.json",
"docs:compodoc:serve": "compodoc -p tsconfig.json -s",
"docs:compodoc:serve:watch": "compodoc -p tsconfig.json -s -w",
"e2e:live": "npm-run-all -p -r server:prod:ci protractor:live",
"e2e:travis": "npm-run-all -p -r server:prod:ci protractor:delay",
"e2e": "npm-run-all -p -r server:prod:ci protractor",
"github-deploy:dev": "npm run webpack -- --config config/webpack.github-deploy.js --progress --profile --env.githubDev",
"github-deploy:prod": "npm run webpack -- --config config/webpack.github-deploy.js --progress --profile --env.githubProd",
"github-deploy": "npm run github-deploy:dev",
"lint": "npm run tslint \"src/**/*.ts\"",
"node": "node",
"postinstall": "npm run webdriver:update",
"postversion": "git push && git push --tags",
"preclean:install": "npm run clean",
"preversion": "npm test",
"protractor": "protractor",
"protractor:delay": "sleep 3 && npm run protractor",
"protractor:live": "protractor --elementExplorer",
"rimraf": "rimraf",
"server:dev:hmr": "npm run server:dev -- --hotOnly",
"server:dev:hmr:browser": "npm run server:dev:browser -- --hotOnly",
"server:dev": "npm run rimraf -- .awcache && npm run webpack-dev-server -- --config config/webpack.dev.js --progress --profile --watch --content-base src/",
"server:dev:browser": "npm run server:dev -- --open",
"server:prod": "http-server dist -c-1 --cors",
"server:prod:ci": "http-server dist -p 3001 -c-1 --cors",
"server": "npm run server:dev",
"start:hmr": "npm run server:dev:hmr",
"start:hmr:browser": "npm run server:dev:hmr:browser",
"start": "npm run server:dev",
"test": "npm run lint && karma start",
"tslint": "tslint",
"typedoc": "typedoc",
"version": "npm run build:aot:prod",
"watch:dev:hmr": "npm run watch:dev -- --hot",
"watch:dev": "npm run build:dev -- --watch",
"watch:prod": "npm run build:prod -- --watch",
"watch:aot:prod": "npm run build:aot:prod -- --watch",
"watch:test": "npm run test -- --auto-watch --no-single-run",
"watch": "npm run watch:dev",
"webdriver-manager": "webdriver-manager",
"webdriver:start": "npm run webdriver-manager start",
"webdriver:update": "webdriver-manager update",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"
}

A:

I would search your code for references to SimpleAuthService.
Credit to Igor regarding the circular dependency concern e.g. be careful how barrels are used e.g. fileA imports SimpleAuthService which also imports an index.ts which imports SimpleAuthService or such other circular relations. In such a scenario, one approach could be to explicity import certain items instead of via a barrel.
Note: you will generally catch more compilation issues during AOT and that is a good thing! i.e. its good practice to run with AOT compilation during your dev cycle now and then to ensure it's ready for PROD build. AOT catches legitimate problems.


Q:

glut32.dll is missing error . A way to get rid of it on non-administrative access machines

I'm using visual studio 2012 on my university machines. On creating a project, saving glut.h, glut32.lib, and glut32.dll to my project folder and making sure it is in same directory as my .cpp files, i then add glut.h to my header files and glut32.lib to resource files and include glut.h as #include "glut.h" in my source folder i get an error glut32.dll is missing. I didn't change any directory path. How to resolve this.

A:

The DLL needs to be in your working directory at run-time.
You can set this as a project/debugger option in Visual Studio (probably the better solution if you have shaders, etc.) or you can do the lazy thing and copy the DLL into your Debug/, Release/, etc. directory.
As a rule of thumb, I always have my projects run with a working directory of /NothingInc/Dev/ this is my base path for all resources including DLLs, shaders, textures, etc. It would be a good idea to adopt a similar policy for your projects, since they will probably share shaders and other resources, and they will certainly all need glut32.dll.


Q:

How to Eloquent not persist certain attributes in the table?

I have a model with table attributes: protein, carbohydrate and fat.
I want to add the model an attribute 'calorie' which must be calculated based on the previous three standing on the table, however this 'calorie' is not to be persisted.
My doubt is whether the Eloquent does it automatically verifies that the field is not in the table or I have to inform in any way?
In other languages I would use a annotation to inform you that should not persist this attribute, but Eloquent simply ignores any attribute that is not on the table fly away When I print the output of a model.
class Alimento extends Model
{

    const CALORIA_PROTEINA = 4;
    const CALORIA_CARBOIDRATO = 4;
    const CALORIA_GORDURA = 9;

    protected $table = "alimentos";
    protected $fillable = ["nome", "proteina", "gordura", "carboidrato", "tabela", "forte"];

    public $timestamps = false;
    public $caloria = 0; // <= This is an attribute that should not be persisted
    public $qtde = 100; // <= This is an attribute that should not be persisted

    public static $rules = [
        "nome" => "required",
    ];

    public function calculaCaloria()
    {
        if ($this->qtde == 100) {
            $this->caloria = ($this->proteina * self::CALORIA_PROTEINA) +
                ($this->carboidrato * self::CALORIA_CARBOIDRATO) +
                ($this->gordura * self::CALORIA_GORDURA);
        } else {
            $this->caloria = $this->regraDeTres($this->proteina * self::CALORIA_PROTEINA) +
                $this->regraDeTres($this->carboidrato * self::CALORIA_CARBOIDRATO) +
                $this->regraDeTres($this->gordura * self::CALORIA_GORDURA);
        }
    }

    private function regraDeTres($_valor)
    {
        return ($_valor * $this->qtde) / 100;
    }

}

And in my test controller I do this:
public function novoAlimento()
    {
        $al = new Alimento();
        $al->nome = "Teste";
        $al->proteina = 20;
        $al->carboidrato = 15;
        $al->gordura = 8;
        $al->qtde = 50;
        $al->forte = "C";

        $al->calculaCaloria();

        $al->save();
        return $al;
    }

And this is my controller's return:
{"nome":"Teste","proteina":20,"carboidrato":15,"gordura":8,"forte":"C"}

Thanks!

A:

You want to place caloria property into returned JSON?
Try to override toArray() method
public function toArray()
{
   $array = parent::toArray();
   $this->calculaCaloria();
   $array['caloria'] = $this->caloria;
   return $array;
}


Q:

SQL Query Issue in PostgreSQL

I have three tables for users and users access rights as below:
create table users (id int, login varchar, organization varchar);
create table groups (id int, name varchar);
create table user_groups (gid int, uid int,
constraint fk_users_groups foreign key(gid) references groups(id),
constraint fk_users_users foreign key(uid) references users(id)
);

Lets insert some records:
insert into groups values(1, 'Data Entry'), (2, 'Sender'), (3, 'Receiver'),
(4, 'Reviewer'), (5, 'Checker'), (6, 'Approver'), (7, 'Nothing'), (8,
'Everything'), (9, 'HR Systems'), (10, 'Check System'), (11, 'Final');
insert into users (1, 'Ahmad'), (2, 'Sam'), (3, 'John'), (4, 'Smith'),
(5, 'Roy');
insert into user_groups values (1, 1), (2, 1), (3, 1), (8, 1), (9, 1), (4, 2),
(5, 2), (10, 2), (11, 2), (6, 3), (7, 4);

Now I want to fetch the user id, login and user type as such if the user ha ("data entry", "sender", "receiver") groups, then "HR" should be printed (we do not care for other groups if he has or not for ex: here he has the other groups as well rather than we need for the "HR" user type) for him as user type, if he/she is in ("reviewer", "checker") groups then "Check" should be printed else "Any" should be printed for any other groups.
The desired output is:
User ID      Login       UserType
   1         Ahmad         HR
   2         Sam           Check
   3         John          Any
   4         Smith         Any

A:

You could use max(case( to find the top group someone is in.  Here I've defined the order by prefixing the usertype with 1, 2 or 3:
select  u.id
,       login
,       substring(max(case
            when name in ('Data Entry', 'Sender', 'Receiver') THEN '3 HR'
            when name in ('Reviewer', 'Checker') THEN '2 Check'
            else '3 Any'
            end) from 3)
from    users u
left join
        user_groups ug
on      ug.uid = u.id
left join
        groups g
on      g.id = ug.gid
group by
        u.id
,       login

Example at DBFiddle.


Q:

How to set page title in blazor?

As Blazor being a SPA framework, I would like to know is it possible to set a page title for each individual page in Blazor?
I am currently working on Blazor webassembly project and cannot figure out a way how to add a page title since there is only one index.html as it should be in SPA, but would be really useful if it can be achieved to set title for each  "page".

A:

Provide following script in your index.html (or in an included .js file):
<script>
     setTitle = (title) => { document.title = title; };
</script>

In each page inject the jsinterop:
@inject IJSRuntime JSRuntime;

After each render, set the document title to the value of your choice:
@code
{
   protected override async Task OnAfterRenderAsync(bool firstRender)
   {
      await JSRuntime.InvokeVoidAsync("setTitle", "this is the new title"); ;
   }
}


Q:

HTML Not displaying when DIV's are a different order to Javascript

I have a AJAX timer That uses the GET command to retrieve a JSON encoded MySQL query via PHP...
The timer is working correctly & the information is also being retrieved...
To be able to store the results so that i can display them in DIV I have made a VAR called LIST and EVALUATED the xmlhttp.responseText
Then I have created a list of documentgetelementbyid to hold the results so they can be used in the DIV's around the site
Everything works perfectly if I display the data in order within HTML, but as soon as I attempt to display the data not to the order in my JavaScript file the display goes blank..
Im guessing that it is because of the way i am attempting to store the results within JavaScript..
How is it possible to store these results within JavaScript and then call them in HTML but not to the order they are within JavaScript..
I hope what I have explained makes sense, any advice would be greatly appreciated...
THE JAVASCRIPT CODE:
function getPlaylist()
{
     var xmlhttp, timer;

     if (window.XMLHttpRequest)
     {
        xmlhttp = new XMLHttpRequest();
     }
     else
     {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.onreadystatechange = function ()
     {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
       {

          var list = eval ('('+xmlhttp.responseText+')');

          document.getElementById("list0.artist").innerHTML=list[0].artist;
          document.getElementById("list0.title").innerHTML=list[0].title;
          document.getElementById("list0.label").innerHTML=list[0].label;
          document.getElementById("list0.albumyear").innerHTML=list[0].albumyear;
          document.getElementById("list0.picture").innerHTML='';

          document.getElementById("list1.artist").innerHTML=list[1].artist;
          document.getElementById("list1.title").innerHTML=list[1].title;
          document.getElementById("list1.label").innerHTML=list[1].label;
          document.getElementById("list1.albumyear").innerHTML=list[1].albumyear;
          document.getElementById("list1.picture").innerHTML='';

          document.getElementById("list2.artist").innerHTML=list[2].artist;
          document.getElementById("list2.title").innerHTML=list[2].title;
          document.getElementById("list2.label").innerHTML=list[2].label;
          document.getElementById("list2.albumyear").innerHTML=list[2].albumyear;
          document.getElementById("list2.picture").innerHTML='';

          document.getElementById("list3.artist").innerHTML=list[3].artist;
          document.getElementById("list3.title").innerHTML=list[3].title;
          document.getElementById("list3.label").innerHTML=list[3].label;
          document.getElementById("list3.albumyear").innerHTML=list[3].albumyear;
          document.getElementById("list3.picture").innerHTML='';

          document.getElementById("list4.artist").innerHTML=list[4].artist;
          document.getElementById("list4.title").innerHTML=list[4].title;
          document.getElementById("list4.label").innerHTML=list[4].label;
          document.getElementById("list4.albumyear").innerHTML=list[4].albumyear;
          document.getElementById("list4.picture").innerHTML='';
       }
    };

    xmlhttp.onerror = function()
    {
      clearTimeout(timer);
    };

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
    xmlhttp.send();

    timer = setTimeout(getPlaylist, 1000);
}

THE HTML CODE:
(This works in the order below but if i were to change the first DIV to look for "list1.artist" instead of "list0.artist" the page will not display.)
<!DOCTYPE html>

Now Playing

Last Played

History

A:

Sounds like you are doing something like this:

Now Playing

Last Played

?
If so, your screen is going blank because when you try to access the div with id="list1.artist", javascript finds two instances of the element with that id and throws an error. Because of this error, javascript aborts the remainder of the code where you are inserting the values into the divs using .innerHTML.
Open up your javascript console: right-click > Inspect Element > Console, and check to see whether you are getting a javascript error. This is likely your problem.
To answer your question about how to display the HTML in a different order...one implementation is to use knockout.js, which is an awesome data-binding library that makes doing things like this a snap (trust me, trust me, trust me). It'll take a little learning, but they have a great tutorial, and if you've never used it, it will successfully blow your mind :]
http://knockoutjs.com/
Good luck friendo.


Q:

Release resources in .Net C#

I'm new to C# and .NET, ,and have been reading around about it.
I need to know why and when do I need to release resources? Doesn't the garbage collector take care of everything? When do I need to implement IDisposable, and how is it different from destructor in C++?
Also, if my program is rather small i.e. a screensaver, do I need to care about releasing resources?
Thanks.

A:

The garbage collector is only aware of memory. That's fine for memory, because one bit of memory is pretty much as good as any other, so long as you've got enough of it. (This is all modulo cache coherency etc.)
Now compare that with file handles. The operating system could have plenty of room to allocate more file handles - but if you've left a handle open to a particular file, no-one else will be able to open that particular file for writing. You should tell the system when you're done with a handle - usually by closing the relevant stream - as soon as you're finished, and do so in a way that closes it even if an exception is thrown. This is usually done with a using statement, which is like a try/finally with a call to Dispose in the finally block.
Destructors in C++ are very different from .NET finalizers, as C++ destructors are deterministic - they're automatically called when the relevant variable falls out of scope, for example. Finalizers are run by the garbage collector at some point after an object is no longer referenced by any "live" objects, but the timing is unpredictable. (In some rare cases, it may never happen.)
You should implement IDisposable yourself if you have any clean-up which should be done deterministically - typically that's the case if one of your instance variables also implements IDisposable. It's pretty rare these days to need to implement a finalizer yourself - you usually only need one if you have a direct hold on operating system handles, usually in the form of IntPtr; SafeHandle makes all of this a lot easier and frees you from having to write the finalizer yourself.

A:

Basically, you need to worry about releasing resources to unmanaged code - anything outside the .NET framework. For example, a database connection or a file on the OS.
The garbage collector deals with managed code - code in the .NET framework.
Even a small application may need to release unmanaged resources, for example it may write to a local text file. When you have finished with the resource you need to ensure the object's Dispose method is called. The using statement simplifies the syntax:
using (TextWriter w = File.CreateText("test.txt"))
{
    w.WriteLine("Test Line 1");
}

The TextWriter object implements the IDisposable interface so as soon as the using block is finished the Dispose method is called and the object can be garbage collected. The actual time of collection cannot be guaranteed.
If you create your own classes that need to be Disposed of properly you will need to implement the IDisposable interface and Dispose pattern yourself. On a simple application you probably won't need to do this, if you do this is a good resource.


Q:

How to access HLS video transport segments (.ts) from Android player?

We have an Android player that plays an m3u8 stream. This m3u8 stream contains numerous transport segments of video that are played sequentially. Usually the player buffers a few transport segments.
If the user clicks a button, I would like to store the existing buffer of transport segments in an array (or other data structure) and immediately merge them to be an mp4. So, if the buffer has:
chunk123.ts
chunk124.ts
chunk125.ts
I would like to merge them to be a chunks.mp4
The second part of the task - the merging is something I am acquainted with. However, I am not sure how I can retrieve the transport segments in the video player buffer on Android (the video player handles the download). I supposed one would need an open source video player for this? What part of the code would I need to modify to make it accessible from within my app?
Thank you!

A:

Check the ExoPlayer. It handle m3u8 stream and persisten caching. You can easily add your custom logic because app is notified every time a chunck (ts file) is downloaded by the class ChunkSampleSource.


Q:

How does the size of a toric code torus affect its ability to protect qubits?

The Toric code Hamiltonian is:
$\sum_{x,y}\left( \prod_{i\in p(x,y)} Z_{ixy} + \prod_{i\in v(x,y)} X_{ixy}   \right),$
where the $v$ and $p$ are defined according to this picture (courtesy of James Wooton's contribution to Wikipedia):

At the moment we have an infinite 2D lattice:
$x\rightarrow \pm \infty$
$y\rightarrow \pm \infty$.
But if we set periodic boundary conditions such that (and feel free to edit the question if I am incorrect about this):
$p(x+10,y)=p(x,y)$
$v(x,y+10)=v(x,y)$,
We get the follownig torus (image courtesy of James Wooton's contribution to Wikipedia) :

Now in my periodic boundary conditions, I chose to add $+10$ but could have added some other number instead. How does this "size of the torus" affect the function of the toric code?

A:

The Toric code is an error correcting code. The distance of the code (I.e. the number of local operations required to convert one logical state into an orthogonal one) is equal to $N$, where the Toric code is defined on an $N\times N$ grid.
One of the places that the performance of the Toric code really wins out is that although it is only distance $N$, the vast majority of sets of $N$ single qubit errors can be corrected, and it is only once you get $O(N^2)$ errors that you get killed. That means that as $N\rightarrow\infty$, those $O(N)$ terms vanish, and you get a finite per-qubit error rate as a threshold for error correction. For finite $N$, the error correcting threshold will be lower.