Windows Update: Can not clean install fresh windows 2012 Essentials server

Question: Am attempting to install Windows 2012 Essentials on a Dell CS24-TY 1U Server, two disks, Raid1.
Note: Completely clean installation, for a small company, no existing domain controller, no other servers at all, original installation media, couldn't possibly be a more simple setup.
Am unable to get Windows 2012 server to install at all, if I allow it to try an update while installing - it just hangs on 0% at "Updating and preparing your Server".  I have tried installing via Dell Drac remotely mounted media, local USB key, and local usb-attached DVD drive.
If I set the server to install without processing updates, it will install, but if I then try to run Windows Update it just again hangs forever.  I have tried stopping the wuauserv service, and removing the Software Distrubtion folder etc, nothing appears to work.
I have also tried removing the RAID and installing just to a single disk: same result.
Nearly all references I find to "Windows Update not working" are based on an established machine that has somehow got corrupted etc - not on a brand new vanilla installation of Windows Server.
Does anyone have some pointers how I could go about solving this problem?
Note: This is a 100% clean and simple base setup - zero configuration or roles or services etc. Nothing has been done to the OS other than what is required during installation: setting server name and password etc.
Thankyou.
EDIT
Below are the last entries from WindowsUpdate.log, when it appears to hang.  Given that it was possible to install this exact OS Media on this exact Hardware before, is it possible that Microsoft have recently released an Update that breaks Windows Update?  Is it possible to translate the Update Guid to a KB number?
2017-01-18  15:11:14:840     412    1424    Agent   WARNING: Failed to evaluate Installable rule, updateId = {E66A6795-3E20-43ED-9C66-FE134EEEECBC}.200, hr = 80070057
2017-01-18  15:11:19:324     412    1424    Agent   Bundled update {FBEC0F80-9F87-4B42-BA14-2BBE7148322A}.203 is missing extended metadata
2017-01-18  15:11:19:324     412    1424    Agent   Bundle contains children which has no localextended metadata and thus is invalid.
2017-01-18  15:11:19:324     412    1424    Agent   Update {B27CF4B3-0B7D-475D-9129-883E6DED6182}.203 is not a valid bundle. Not returning it.

ipconfig /all
Windows IP Configuration

   Host Name . . . . . . . . . . . . : server1
   Primary Dns Suffix  . . . . . . . : FABLAB.local
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : FABLAB.local

Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Intel(R) 82576 Gigabit Dual Port Network Connection #2
   Physical Address. . . . . . . . . : C8-0A-A9-C8-3B-8A
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 192.168.1.4(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
   DNS Servers . . . . . . . . . . . : 127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Intel(R) 82576 Gigabit Dual Port Network Connection
   Physical Address. . . . . . . . . : C8-0A-A9-C8-3B-8B
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{468CFBC4-85E3-4EDA-96BC-6A3E4B842EA3}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{48398617-4417-4945-8A81-DE0F3BCC7D2B}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #3
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

nslookup google.com
Server:  localhost
Address:  127.0.0.1

Non-authoritative answer:
Name:    google.com
Addresses:  2607:f8b0:4006:80e::200e
          184.108.40.206
          188.8.131.52
          184.108.40.206
          126.96.36.199
          18.104.22.168
          184.108.40.206
          126.96.36.199
          184.108.40.206
          126.96.36.199
          22.214.171.124
          126.96.36.199
          18.104.22.168
          220.127.116.11
          22.214.171.124
          184.108.40.206
          18.104.22.168

Comment: One thing to try...do the install without updates...then make sure in IE under Lan Settings (connections) all are unchecked unless you absolutely do use a proxy.  Then try the updates.  That usually works.  There's also this Powershell option: https://blogs.technet.microsoft.com/heyscriptingguy/2012/11/08/use-a-powershell-module-to-run-windows-update/
Comment: Have you verified the IP configuration of the server? Does it have a valid IP address/subnet mask, default gateway and DNS server configured.
Comment: Thanks. No proxy server. Super simple network. Server accesses internet no problem. DNS is set to 127.0.0.1, havn't (yet) configured any DNS Server settings - as DNS works out of the box.
Comment: The server is configured to use itself for DNS. Do you have the DNS role installed on the server? Does the server have a valid ip address/subnet mask and default gateway?
Comment: Yes server can access internet, has valid ip etc. Tried with both DHCP and static assignments.  Have not installed DNS role (setup is **100% vanilla**), but DNS works and points to localhost, thus I can only assume that windows 2012 server installs DNS Server by default. I had also tried setting to 22.214.171.124, same issue.
Comment: Hmm... This doesn't quite make sense. The DNS server roles isn't installed by default. If the server is using 127.0.0.1 for DNS and the DNS server role is not installed then the server should not have DNS name resolution, and thus no internet connectivity (by DNS names). Dod you install AD AD and promote the server to a Domain Controller by any chance? Can you post a screenshot of Server Manager, ipconfig/all, and an nslookup query for google.com in your question?
Comment: Thanks Joe. Correct: I did not install DNS Server, yet (by default) it points to 127.0.0.1, and yes name resolution works, so clearly DNS Server role must be installed. To reiterate: I have done absolutly *zero* config, such as installing AD or promoting to a DC or activating DNS Server Role etc. Also reiterate: I am installing from original install media (no NTLite etc), and it is Server 2012 Essentials. (Perhaps it defaults to an AD controller by default?) Am offsite now, will post the information you have requested. P.S I am looking at slipstreaming all updates into the install using ntlite
Comment: Oh boy. My bad. I didn't pay attention to the fact that this is Windows Server Essentials. Yes, that will have installed AD DS and DNS as part of the install process, which explains why DNS resolution works. My apologies.
Comment: Nope, my bad actually. I initially omitted, by mistake, "Essentials" from the question. I had only added it later during an edit.  Apologies respectfully declined due to lack of any fault on your behalf.
Answer: I had the same issue:
- I attempted to update during installation and hung at 0%.
- I installed without updates, and after getting to desktop, attempted to run updates, which searches for updates indefinitely (18+ hours).
- I installed without updates, and tried to update using WSUS Offline Update, which hangs on "Listing IDs of Missing Updates" (13+ hours).
- I have attempted to install with the computer on an entirely different network/ISP to attempt to rule out DHCP/DNS server issues, with no change in behavior.

I managed to get Server 2012 Essentials installed and up to date using the following method:

Installed WSUS Offline Update version 10.9 (on a Win 10 x64 machine)*.
Downloaded updates for Server 2012 through WSUS Offline Update.
Installed NTLite (on a Win 10 x64 machine)*.
Followed this guide to package updates using NTLite - https://web.archive.org/web/20180129120711/http://www.v-strange.de/index.php/vmware/2-uncategorised/220-slipstream-windows-updates-to-server-2012r2-install-medium
Copied updated install.wim back onto the Server 2012 Essentials USB installation media
Installed Server 2012 Essentials on target machine, with the selection to install updates during installation checked.
After finalizing installation and rebooting, I was able to successfully pull down the remaining Windows Updates successfully.

*I mention the OS I worked from because Mtl Dev shared that he was unsuccessful following the guide linked in step 4 on a windows 7 machine.
(Partial credit goes to Mtl Dev for pointing me towards the WSUS Offline Update/NTLite solution to update the installation media prior to installing the OS.)


Maximizing discrete probability

Question: I'm stuck with the following problem:
Let's assume we have two buckets: bucket one contains $k$ white spheres and $l$ red spheres. Bucket two contains $n-k$ white spheres and $n-l$ red spheres (n a fixed constant).
The probability to pick a white sphere from any of the two buckets (assuming uniform  probability) is given by:

$$\mathbb{P}(\ White\  sphere)=\frac12\cdot\frac{k}{k+l}+\frac12\cdot\frac{n-k}{2n-(k+l)}$$

The question reads as follows: how to choose k and l such that the above proability is maximal?
The given hint is: "first consider $k+l=m$ fix"
The solution states: $k=1$ and $l=0$. I've tried applying Lagrange's multipliers without any apparent success... can someone help me out?
Thank you in advance
Comment: Please clarify. When you pick a sphere from one of buckets, you do it with equal 1/2 probability? Is this a prefixed strategy that cannot be changed?
Comment: exactly! The probability is the one given by the formula
Answer: We apply the hint: Fix $m=k+l$. Then the equation becomes
$$\frac{1}{2}\left(\frac{k}{m}+\frac{n-k}{2n-m}\right)=\frac{1}{2}\left(\frac{2nk-mk+nm-mk}{2nm-m^2}\right)=\frac{1}{2}\left(\frac{k(2n-2m)+nm}{2nm-m^2}\right)$$
This value increases as $k$ increases since all other values are fixed. Since $m=k+l$, for a given $m$, the maximum value of $k$ is $m$.
Letting $k=m$ in the above equation, we get
$$\frac{1}{2}\left(\frac{m(2n-2m)+nm}{2nm-m^2}\right)=\frac{1}{2}\left(\frac{2n-2m+n}{2n-m}\right)=\frac{1}{2}\left(\frac{3n-2m}{2n-m}\right)$$
This value increases as $m$ decreases. Hence the maximum value occurs when $m$ is at a minimum, that is, at $m=1$. In conclusion this gives us that the maximum occurs when $k=m=1$ and $l=0$.
Comment: Nice. However, I think it would be necessary to consider the case $m=0$ first (in your answer you considered that $1$ is the minimum of $m$, why?). If $m=0$ then $k=l=0$ and the considered probability is $P=1/4$. Now consider $m\ge 1$, then proceed with your arguments we get another maximum value of $P$. Comparing with the case $m=0$ we see that this value is actually the maximum one. Conclusion...
Comment: @Khue Yeah, I didn't consider the case $m=0$ because I didn't think we had defined what to do when one bucket was completely empty (for example, the fraction $\frac{k}{k+l}$ doesn't make sense). However if we take the probability of getting white in the case $m=0$ as $1/4$ (as might reasonably be interpreted from the question statement), then we can do exactly as you suggest.
Answer: If $k+l<n$, then the second denominator is greater than the first.  Any balls in the first bucket have a higher probability of being chosen than balls in the second bucket.  So, subject to $k+l$ being constant, you want all of the $k+l$ balls to be white - that is, $l=0$.
Now that $l=0$, how do you maximize the probability?
There is another solution if $k+l>n$.

Maximizing discrete probability


Searching/Replace attributes with the according getter/setters

Question: Problem:

Having a large number of classes which have attributes defined with
  names where the first character is uppercase.

Example:
class FirstClass {
  private Integer FirstValue;
  private Double SecondValue;
  private String ThirdValue;

  public Integer getFirstValue() {
    return FirstValue;
  }
  public Double getSecondValue() {
    return SecondValue;
  }
  public String getThirdValue() {
    return ThirdValue;
  }
  public void setFirstValue(Integer newVal) {
    FirstValue = newVal
  }
  ..
}

Currently I have setup a structural search template which looks like this:
class $class$ {
    private $FieldType$ $Field$;

    public $FieldType$ $MethodCallGet$() {
        return $Field$;
    }

    public void $MethodCallSet$($FieldType$ $parameter$) {
        $Field$ = $parameter$;
    }
}

I have setup the variables like the following:

$class$: text=^(XYZ|ABC).*
$FieldType$: all fields of the class
$Field$: [A-ZÄÖÜ][a-zA-Z0-9_ÄÜÖäüÖ]+
$MethodCallGet$: text=^get.*
$MethodCallSet$: text=^set.*

So first it will find the attributes which have the first character in uppercase, but unfortunately it will only find a single attribute in each class including it's getter/setter.
1. Question:
How can I find all attributes including it's getter/setter method?
2. Question:
How can I replace the attributes with it's change counterparts. Changed
the first character only to lowercase. Also within the getter/setters?
Answer: There is no good way to do this using Structural Search. What you can do is the "Java | Naming conventions | Field naming convention" inspection to find all instance fields with names not according to the specified naming convention and then use the inspection's quick fix to rename the fields one by one.
You may also want to vote for https://youtrack.jetbrains.com/issue/IDEA-12246


Trying to find specific words in textArea

Question: So what I am trying to do here is to get the text from the JTextArea ta by using the method String code = ta.getText(); ta is located in the class TextIDE and is declared as public static JTextArea ta = new JTextArea();
However, after that I have retrieved the text that is inputted by the user I want to make it into a char array, so I use the method code.toCharrArray(); After that in the method compileText I use the for-statement to look for the letter 'p' and if it is found I call the method p() and I send in where the counter i was and the actual character array, so I can continue my search for the letter 'r' and I do this till the class finds the word print. Whenever it does, It should append another JTextArea which works like a console, located in a class called Listener, so I use Listener.c.jt1.append(s); whereas s is equal to whatever comes after print up until the point where it finds a semicolon ';'.
But it doesn't work, I get no error, so I presume there is a logical error here...
Thanks for any help!! :)
public class Compiler {

    String code = TextIDE.ta.getText(); //Gets the text that was inputted by the user

    public Compiler(){ //Constructor

        if(!(code.endsWith("programEnd"))){
            Listener.c.jt2.append("Error - Code must end with line: programEnd on the last line");
        }else{
            compileText(code, 0);
        }
    }

    public void compileText(String code, int start){ //Starts the compiling
        char[] codeArray =  code.toCharArray();
        System.out.println(codeArray.length);

        for(int i = start; i < codeArray.length; i++){ //Looks for character 'p'
            switch(codeArray[i]){
                case 'p':   p(codeArray, ++i);
                            System.out.println("p");
                    break;
            }
        }
    }

    public void p(char[] codeArray, int start){
        for(int i = start; i < codeArray.length; i++){
            switch(codeArray[i]){
                case 'r':   r(codeArray, ++i);
                            System.out.println("r");
                    break;
            }
        }
    }

    public void r(char[] codeArray, int start){
        for(int i = start; i < codeArray.length; i++){
            switch(codeArray[i]){
                case 'i':   i(codeArray, ++i);
                            System.out.println("i");
                    break;
            }
        }
    }

    public void i(char[] codeArray, int start){
        for(int i = start; i < codeArray.length; i++){
            switch(codeArray[i]){
                case 'n': n(codeArray, ++i);
                            System.out.println("n");
                    break;
            }
        }
    }

    public void n(char[] codeArray, int start){
        for(int i = start; i < codeArray.length; i++){
            switch(codeArray[i]){
                case 't': t(codeArray, ++i);
                            System.out.println("t");
                    break;
            }
        }
    }

    public void t(char[] codeArray, int start){
            String s = "";
            for(int i = start; i < codeArray.length; i++){
                if(!(codeArray[i] == ';')){
                    s += codeArray[i];
                }else{
                    Listener.c.jt1.append(s);
                    compileText(code, ++i);
                    break;
                }
            }
    }
}

Comment: read Oracle tutorials about JTextComponents for working code example about How to search ....
Comment: you cant awaiting some help from this desciption, nor from code, you have to provide more details than that, for better help sooner post an SSCCE/MCVE, short, runnable, compilable
Comment: use set/getDocument (model for JTextComponents)
Comment: I want to find the word print in a char array, how do i do that? and then continue looking for maybe another word just as like it?
Comment: I want to find the word print in a char array because indexof(str) will only return me the first word that starts with print, I want all of them. For example in the text "asdhfuhadsufh print adhfuhadfuj print" there are two variables that is equal to "print"! :)
Answer:
I want to find the word print in a char array, how do i do that?

Why are you using a character array? You can just search the text String:
String text = textArea.getText();
System.out.println( text.indexof( "print" );


Calculate exit point from inside a circle using radius, position and direction

Question: I want to calculate the exit point of a circle (in this case centered at 0,0) from any position within the circle in any direction.
So to clarify.
Circle A is centered at 0,0 and has a radius of 10.
Point B is at 4,4 and is "facing" right (90 degrees).
Assuming "forward" movement from B (i.e moving right), how do you calculate the exit point of the circle?
Comment: Please comment why if you downvote
Answer:
Parametric representation
of the point $P$ on the line
through the point $B$
in direction $\vec{D}$
in terms of $t\in\mathbb{R}$
is
\begin{align}
P&=B+t\cdot \vec{D}
,\\
\end{align}
which is in fact two equations
\begin{align}
 P_x&=B_x+t\cdot {D_x}
 ,\\
 P_y&=B_y+t\cdot {D_y}
 .\\
\end{align}
If the point $B$ is internal,
this line intersects the circle boundary in two points,
$C_1$ for some $t_1>0$,
and $C_2$ for some $t_2<0$.
Coordinates of the point on a circle boundary
can be represented parametrically as
\begin{align}
C_x&=R\cos\phi
,\\
C_y&=R\sin\phi
,\quad \phi\in[0,2\pi]
.
\end{align}
Now we can get rid of $\phi$
and obtain a quadratic equation for $t$:
\begin{align}
R^2\cos^2\phi+
R^2\sin^2\phi
&=
(B_x+t\cdot {D_x})^2+(B_y+t\cdot {D_y})^2
,\\
(D_x^2+D_y^2)\,t^2+2\,(B_xD_x+B_yD_y)\,t-(R^2-(B_x^2+B_y^2)
&=0
,
\end{align}
which gives
\begin{align}
t_1&=\frac{-(B_x\,D_x+B_y\,D_y)+\sqrt{(B_x\,D_x+B_y\,D_y)^2+(D_x^2+D_y^2)\,(R^2-(B_x^2+B_y^2))}}
{D_x^2+D_y^2}
,\\
t_2&=\frac{-(B_x\,D_x+B_y\,D_y)-\sqrt{(B_x\,D_x+B_y\,D_y)^2+(D_x^2+D_y^2)\,(R^2-(B_x^2+B_y^2))}}
{D_x^2+D_y^2}
,\\
\end{align}
and the sought point $C_1$ is found as
\begin{align}
C_1&=B+t_1\,D
.
\end{align}
Comment: I want to understand, but some parts are confusing to me. What exactly does R cosϕ mean in this case? As in what does R and theta stand for (I have seen them mean really different things).
And in the last step, the function for getting t1 and t2 looks identical, shouldn't they differ somehow?
Comment: @webejaxx: It's a standard parametric form of [the equation of the circle](https://en.wikipedia.org/wiki/Circle)
which express the $x,y$ coordinates of the point in terms of the parameter $\phi$.
In this case a nice thing is that we don't really need to worry about $\phi$,
since we eliminate it anyway. And yes, $t_1$ and $t_2$ are different,
they are the two roots of the quadratic equation above, which in fact,
also works when the point $B$ is not internal.
Just when it is internal, there are always two real roots,
otherwise there could be two, one or no real roots.
Comment: I'm trying to get this to work, but I can't turn this into working code (for a game I am making). I get that a point on the boundry is worked out with `x = radius * Cos(angle* PI / 180)) + point.X` and `y = radius * Sin(angle* PI / 180)) + point.Y`. I don't understand the next steps well enough to write a function for it. Do you know how to help with that?
Comment: @webejaxx: You have the radius $R$,
the point $B=(B_x,B_y)$
and the direction $D=(D_x,D_y)$,
the formula to get $t_1$.
The point $C_1=B+t_1\cdot D$.
That's all.
Comment: Ohh, I get it now! Thank you, it worked perfectly.


Erro na criação de api rest em Javascript

Question: O erro que esta retornando é C:\Users\Eric Vitta\Documents\documentos cursos\javascript\src>node index.js TypeError: Cannot read property 'map' of undefined at router.post (C:\Users\Eric Vitta\Documents\documentos cursos\javascript\src\app\controller\projectController.js:37:31) at process._tickCallback (internal/process/next_tick.js:68:7)
Eu estou criando uma API para fazer testes no Jmeter, Estou usando o insomnia para fazer os testes e passar informações para o cadastro.
Esse é o link do github com todo o código https://github.com/ericvitta/apiteste
É uma API para testar os métodos REST, somente com intuito de estudo e aprimoramento nas linguagem.
Eu não sei o porque não esta retornando valores no comando req.body pois passo as informações no formato JSON.

const mongoose = require('../../database');
const bcrypt = require('bcryptjs');

const ProjectSchema = new mongoose.Schema({
  title: {
    type: String,
    require: true,
  },
  description: {
    type: String,
    require: true,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    require: true,
  },
  tasks: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Task',
  }],
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

const Project = mongoose.model('Project', ProjectSchema);

module.exports = Project;

const mongoose = require('../../database');
const bcrypt = require('bcryptjs');

const TaskSchema = new mongoose.Schema({
  title: {
    type: String,
    require: true,
  },
  project: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project',
    require: true,
  },
  assignedTo: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    require: true,
  },
  completed: {
    type: Boolean,
    require: true,
    default: false,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

const Task = mongoose.model('Task', TaskSchema);

module.exports = Task;

const express = require ('express');
const authMiddleware = require('../middlewares/auth');

const Project = require('../models/Project');
const Task = require('../models/Task');

const router = express.Router();

router.use(authMiddleware);

router.get('/', async (_req, res) => {
   try {
       const projects = await Project.find().populate(['user', 'tasks']);
       return res.send({ projects});

   }catch (err) {
       return res.status(400).send({ error: 'Erro ao carregar projetos.'});
   }
});

router.get('/:projectId', async (req, res) => {
    try {
        const project = await Project.findById(req.params.projectId).populate(['user', 'tasks']);
        return res.send({ project});

    }catch (err) {
        return res.status(400).send({ error: 'Erro ao carregar projetos.'});
    }
});

router.post('/', async (req, res) => {
    try {
        const { title, description, tasks } = req.body;

        const project = await Project.create({ title, description, user: req.userId });

      await Promise.all(tasks.map(async task => {

          const projectTask = new Task({...task, project: project._id});

          await projectTask.save();

         project.tasks.push(projectTask);
    }));

        await project.save();

      return res.send({ project });
    } catch (err) {
        console.log(err);
      return res.status(400).send({ error: 'Erro ao criar novo projeto.' });
    }
});

router.put('/:projectId', async (req, res) => {
    try {
        const { title, description, tasks } = req.body;

        const project = await Project.findByIdAndUpdate(req.params.projectId , {
            title,
            description
        }, {new: true});

        project.tasks = [];

        await Task.remove({ project: project._id});

      await Promise.all(tasks.map(async task => {

          const projectTask = new Task({...task, project: project._id});

          await projectTask.save();

         project.tasks.push(projectTask);
         console.log({ tasks });
    }));

        await project.save();

      return res.send({ project });
    } catch (err) {
        console.log(err);
      return res.status(400).send({ error: 'Erro ao criar novo projeto.' });
    }
});

router.delete('/:projectId', async (req, res) => {
    try {
        await Project.findByIdAndRemove(req.params.projectId);
        return res.send({ Message:'Projeto removido com sucesso.'});

    }catch (err) {
        return res.status(400).send({ error: 'Erro ao deletar projeto.'});
    }
});

module.exports = app => app.use('/projects', router);
Answer: Amigo, altere no INSONIA a sua requisição http a chave "tarefas" para "tasks" como esta no seu código. (como mencionado pelo amigo Christian Luã Lemos)
 const { title, description, tasks } = req.body;

Fora isso, reparei que você utiliza no seguinte código:
app.use(bodyParser.urlencoded({ extended: false}));

Altere para:
app.use(bodyParser.urlencoded({ extended: true}));

Isso porque com a opção true vai fazer o body-parser utilizar a biblioteca qs, esta biblioteca consegue trabalhar com nested objects.
Falei sobre ela nesse outro link: O que significa na prática o urlencoded do Expressjs?
Comment: Fiz as alterações mas o erro ainda acontece
Comment: O erro `Cannot read property 'map' of undefined` é claro, ele não encontra o método map porque a variável que esta tentando utiliza-lo é undefined. Copiei seu projeto do github e funciona, somente acerte os nomes conforme seu código. Se você diz ao programa 'const { title, description, tasks } = req.body;' ele espera que no corpo da requisição tenha as tags title, description e tasks. Revise sua requisição no insónia novamente e compare se os nomes estão exatamente iguais ao do seu código. Este erro que você informou na pergunta é exatamente isso. Confirme se não esta dando outro erro agora.
Comment: Muito obrigado pela ajuda e atenção, eu baixei o projeto na maquina de um amigo e funcionou...
Comment: Que bom que deu certo! uma dica, não se esqueça de marcar o extended como true como disse ali na minha resposta, isso vai fazer com que você possa trabalhar com objetos aninhados, o que é importante como você esta trabalhando com JSON, caso contrário se você responder com um JSON que tenha aninhamento ele não vai sair. Se a resposta te ajudou de alguma maneira, marque como certa para ajudar outras pessoas.
Answer: Você está pegando os atributos title, description e tasks do objeto req.body neste linha:
const { title, description, tasks } = req.body;

O erro que está ocontecendo no projeto está indicando que a variável tasks é undefined, isto é, não existe req.body.tasks.
Este efeito pode ser observado no código abaixo:

let obj = {title : "foo", description : "bar"}
let {title, description, tasks} = obj

console.log(title) //foo
console.log(description) //bar
console.log(tasks) //undefined
Comment: EU imaginei isso mas na parte de criação da Schema do mongo eu coloquei tasks e ja conferi o nome várias vezes mas não consegui entender o porque não esta trazendo os dados
Comment: Confere se a sua requisição HTTP possui o parâmetro tasks.
Comment: Verifiquei e na imagem eu tinha trocado o nome do parâmetro para tarefa para ver se era algum conflito com o nome  mas o erro continua igual, tentei colocar  um console.log para retornar o valor mas não retorna nada
Comment: Eu ia tentar usar um cliente http como o Postman (https://www.getpostman.com), criando manualmente uma requisição POST com os parâmetros title, description e tasks.
Comment: Esse insomnia que estou usando faz o mesmo processo, você cria sua requisição , no formato que precisar e passar o localhost + porta que definiu no código e você faz esse processo de testar, eu fiz um outro cadastro para usuario e funcionou , gravou no banco mongo e tudo mas essa parte do projeto e das tasks esta com esse problema


How to allow users to attribute accumulating points to nodes?

Question: I would want to make a thing in priori simple: allow users to attribute (grant) a selectable amount of accumulating points to nodes.
I tried various modules (Fivestar, etc.), but these modules are about a note (or a score like '4/5') and not of a number of accumulative points.
It would be necessary from a field (for example list of selection), make increase or decrease the value of another field.
Anybody has an idea?
Notes:

Fivestar allows to give a note (for example: 4 on 5), while I wish to give points which accumulate. Points: simple value. Give X points to this node. For example: I give 5 points to this node because I find this a good node.
Multiple users could give a different number of points. The functioning would be close to Fivestar, except that instead of having an overall average there would be a total number of points.
There would be a field of a node which stores the accumulation of points, and possibly one other to give points.
Comment: Fivestar allows to give a note (for example: 4 on 5), while I wish to give points which accumulate. Points: simple value. Give X points to this node. For example: I give 5 points to this node because that I find him good.
Comment: OK, that helps a bit to better understand. More questions: who would trigger such increase or decrease of points to a node? Should it be possible for multiple users to do so (possibly each of them a different amount of points)? About that "other field": is that like a field of a node, which stores the accumulation (= the sum) of all the points attributed to some node? After you confirm / clarify my comment, I might be able to solve your question ...
Comment: Yes, multiple users could give a different number of points. The functioning would be close of fivestar, except that instead of having an overall average there would be a total number of points. For fields: yes, there would be a field of a node who stores the accumulation of points, and possibly one other to give points. Thanks pierre.vriens for your help
Comment: And thus, you know a solution? I thought in flag + rules, but the problem is that flags is independent, if I have several flags (ex: +1, +2, +3) I can click these three flags and not only one
Comment: How many points would one user typically give? You can use a flag whose unflag text is the same as its flag text, and use rules to +1 the integer field on each. For low numbers, it works well as the user clicks once for each point they give.
Answer: Step 1 - Use the Flag module
I'd definitely use the Flag module for what you're trying to achieve. To allow authorized users (to use such flag) to flag relevant nodes. Maybe you want to limit them to only selected content types also.
Step 2 - Add a field to a Flag to specify the points
However, to also implement those points to nodes that get flagged, you should configure the flag (you only need 1 flag!) by attaching a field to such flag. Such field can then be used to enter, or select, any of the allowed values of points you want to be granted (appointed) to a node that gets flagged by such flag.
However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

Step 3 - Add some 'Total points' field to your nodes
Define some other field in the content types for the nodes you want to use these points for, which will contain the total number of points. And which will get updated each time a node gets flagged with '+X' (or '-Y') points, as explained in the next step.
Step 4 - Use the Rules module to maintain the value of the 'Total points'
The Rules module integrates extremely well with the Flag module. So it should be fairly simple to create a rule to maintain the value of the 'Total points'. Here is a blueprint (to avoid writing an entire manual ...) of this rule:

Rules Event: when a node is flagged (with the flag you created in step 1)
Rules Conditions: whatever you might need (if anything), on top of what is not yet covered by the way you configured the flag.
Rules Action(s): Perform some Rules Actions that use the value of the points as specified by the user who flagged the node, and then adds that to the current value of the 'Total points' field. For an example of such calculation, refer to this answer to the question about "How to add up all items of a field collection field using Rules?". In your case here, you don't need the 'loop' (you're not processing a field collection, only 2 fields for which you want to calculate the sum of it).

Summary
Using Flag (with 1 extra field) and Rules, and by adding a field (for 'Total points') to relevant content types, the above is how you can create something similar to what User Points can do, though with a summary like so:

provides a technique an API for nodes users to gain or lose points for selected nodes performing certain actions on your site.

And btw ... zero custom code involved ...


Common LISP addition program

Question: I was trying to write a program that takes in a list of numbers and adds 1 to each element in the list. Similarly if the list is 0 it will return NIL. I tried doing it recursively but it shows me no output. I know it's simple but I am a beginner and its really hard for me to think about the problem recursively. Thanks!
Comment: When you say "trying to write a _program_" do you really mean "trying to write a _function_"? Further,  you said that you tried something that didn't work... if you want help with respect to _your_ solution you'd better post your current solution, otherwise no one is possibly going to give you _their_ ready-made solution.
Comment: "I tried doing it recursively but it shows me no output."  I dont' see this in your question.  Please note that **Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.**
Comment: "it's simple but I am a beginner and its really hard for me to think about the problem recursively. "  Why do it recursively at all?  What's the matter with `(defun add-1 (list) (mapcar '1+ list))`?  You don't need to know how mapcar is implemented (it *could* be recursive, but that's an implementation detail).   But you could just as well `(loop for x in list collect (1+ x))`.  That's seems non-recursive (though the implementation *could* be recursive), and it works just as well.  It sounds like you're either assuming requirements, or you've got requirements that you're not stating.
Answer: A list is made of cons. It has the first value and a list consisting of the rest of the list except the first value. Thus you should check if your list is null (or endp which is the same) and if it isn't you make a cons with the calculation you have with the first and the recursive call using the rest. as argument.
(add-1 '(1 . (2 . (3 . ())))) ; ==> (2 . (3 . (4 . ())))

Or more commonly written:
(add-1 '(1 2 3)) ; ==> (2 3 4)

Answer: If your assignment requires you to define a recursive function (say my-fun for generality) to do something on every element of a list you could use this idiom
(cons (do-something-on (car my-list)) (my-fun (cdr my-list)))

where you

modify the 1st element
apply the function that you're defining to the rest of the list
return a list constructed joining the modified 1st element and the result of applying the function you're defining to the rest of the list

That's not all, you have to take into account what happens when you exaust the list... but that's easy, you can write a conditional that returns the default value (see above) if the list is not empty and nil otherwise.
(if my-list (...) nil)

or, using the default behavior of a else-less if,
(if my-list (...))

Common LISP addition program


What is the name of this sequence/progression?

Question: Does the following sequence form some special sequence/progression (such as arithmetic progression, geometric progression, hypergeometric progression, and more):
$$
p_k: = \frac{\lambda^k}{k!} e^{-\lambda}, k \in \{0, 1, 2, \dots, \}?
$$
For example, does the ratio $$\frac{p_{k+1}}{p_k} = \frac{\lambda}{k+1}$$
imply what sequence/progression it might be?
note:
$p_k$ is the probability mass function  (pmf) of the Poisson distribution with rate parameter $\lambda$.
Thanks!
Comment: what do you mean by "special series or progression"?
Comment: E.g., arithmetic progression, geometric progression, hypergeometric progression, and more.
Answer: The most notable fact about Poisson distribution is the following:
Consider $g_X(t) = \log E \exp (tX) = \sum_{n=1}^\infty m_n t^n$,
which defines the cumulants $m_n$.
Then if $X\sim Poisson(\lambda)$:
$$
m_n = \lambda
$$
Comment: "$\log E \exp t X$" might benefit from some parentheses.
Comment: this is done. the other ones are useless, and I don't like useless parentheses :-)


Prove that $\|Q\mathbf{v}\|=\|\mathbf{v}\|$

Question:
Prove that if $Q$ is a real $n\times n$ orthogonal matrix and $\mathbf{v}$ is in $\mathbb{R}^{n}$, then $$\|Q\mathbf{v}\| = \|\mathbf{v}\|.$$  Be sure to set out your arguments clearly and logically, giving full reasons.

Hello all,
To solve this do I try and show that $1$ is an eigenvalue? Or is there some rule I'm missing.
Comment: Taking the square on both sides would be a start.
Answer: That wouldn't be enough, since this needs to be true for any $\mathbf{v}$, not just for the eigenvector.  Instead, consider $||Q\mathbf{v}||^2 = \mathbf{v}^T Q^T Q \mathbf{v}$, and see what you'd get.
Answer: Notice that for all $x$ and $y$ column vectors of $\mathbb{R}^n$, one has:
$$\langle x,y\rangle={}^\intercal xy.$$
Therefore, for all $v\in\mathbb{R}^n$, one has:
$$\|Qv\|^2=\langle Qv,Qv\rangle={}^\intercal v{}^\intercal QQv={}^\intercal vv=\|v\|^2,$$
since $Q$ is orthogonal i.e. ${}^\intercal QQ=I_n$. Whence the result.
Comment: That was very concrete, thanks a lot


Dovecot, IMAP outlook reports error 0x800CCC0E cannot synchronize subscribed folders

Question: I have recently some issues with people using my email server.
They have problems with synchronizing folders on outlook, and I can't figure out what to do.
I found somewhere that I could extend a setting for imap connections:
<code>mail_max_userip_connections = 20
</code>
which didn't really help, I was thinking about extending timeout of connection or something, but really can find anything like that.
In Thunderbird it seems to be OK.
here is dovecot -p result:
http://snipt.org/AAig5
if anything could help please let me know what should provide.
Answer: RE: "0x800CCC0E cannot synchronize subscribed folders"
Had this happen today. I knew it had to be a client side error as dovecot logs had nothing but good news.
Resolved by doing the following:

Close Outlook.
Run the SCANPST.EXE utility on the particular imap account PST file in question. (Make a backup as well - trash it after you verify you are synced properly).
Open Outlook.

...Fixed (for me at least.)
As a side note, I noticed I could not view my "Sent" items folder before I fixed error. It was the "Sent" folder in my case -> "Outlook cannot display folder" (if clicked/opened).
I can now see/browse the 'Sent' folder properly, too.
To find location of scanpst.exe or the 'inbox repair tool' for all version of Outlook, consult:
http://support.microsoft.com/kb/272227
EDIT (JAN2017):
https://support.microsoft.com/en-us/kb/2534513
Answer: I'm not sure what the problem could be but the Dovecot wiki is definitely worth a look.

Client issues and configuration

Dovecot 1.x
http://wiki1.dovecot.org/Clients
Dovecot 2.x
http://wiki2.dovecot.org/Clients
Comment: have dovecot 2 and there is no workaround for outlook for imap
Comment: Could you describe the problem in a bit more detail? Is there an error message or does the connection times out?
Comment: 0x800CCC0E cannot synchronize subscribed folders
Comment: 0x800CCC0E means the connection to the server failed. Most likely it's a local problem on the client's machine / network. The problem could be anything really. A misconfigured outlook, firewall blocking, antivirus... The list goes on.
Comment: The thing is that this occurs on few different machines.
Comment: is there any max connections for dovecot or something like that? So when there is too many connections at moment, it will deny to connect?
Comment: Did you check the logs if the maximum number of connections are exceeded?
Comment: not sure where I can check that


Swinging eighths on the piano

Question: When I play jazz on the saxophone, I use a technique I was taught called "Jazz Articulation" (I'm sure that's not its only name) which is basically an articulation where you slur every other note with a tongue in between while playing straight eighth-notes to give your sound a swing feeling.
I was also taught that "faking" swinging eighth-notes, which is basically intentionally shortening and lengthening the notes to give it a swing feel, is bad practice and should be avoided
This jazz articulation works all fine on the saxophone but on the piano, this isn't really possible as my air flow isn't controlling the sound coming out of the piano. How do I swing eighth-notes on the piano and not make it sound like I'm trying to create a "fake" swing sound?
And/or, is the advice I was told incorrect/inaccurate?
Comment: What do great swing-jazz pianists do? Pianists can articulate and create different kinds of flow, too, and all the good ones do.
Comment: "swing" and "slur" on the piano is partly rhythm and partly overlapping notes so as to hide the attack on the second note.
Comment: I'm looking forward to reading an Answer to this!  My son studies with a jazz pianist, and your concern has never come up -- he just plays the swing eighth notes as triplet (quarter - eighth) and I've never heard any complaints, and it sounds great to my (non-expert) ear.  However, when I hear him practice saxophone, his school instrument, something's been sounding all wrong with his jazz articulation.
Comment: Question with related answers: [How to notate groove/ swing/ shuffle rhythms](https://music.stackexchange.com/questions/38790/how-to-notate-groove-swing-shuffle-rhythms)
Answer: I've honestly never had to explain swing other than, "Hear that? That's swing. DO THAT."
You could try by starting with your 16th note vocalization:
1 e + a | 2 e + a | 3 e + a | 4 e + a
Now get rid of all e's. Then push the "a" closer to the down beat, further away from the +.
1 x +   a|2 x +  a|3 x +  a|4 x +  a
That's a rough outline of what swinged 8ths sound like. If you're European you probably use hemi demi semi quaver instead of 1e+a.
Now I know you said that you heard this method is bad practice, but that's literally what's going on. I'll refer to my Harvard dictionary of music when I have a chance to see what it says.
It would help to practice swing using other percussion instruments that are not chromatic. Even if it's just clapping or thigh slaps.
Comment: You're first line is just perfect: "Hear that? That's swing. DO THAT."
Answer: The concept of a "swing feel" is very much more about timing and dynamics than it is about articulation, though you clearly can accomplish an approximation of the feel by tonguing a note.
Comment: Could you elaborate? I like the path that you are going on so far.

Swinging eighths on the piano


Is there any relation between SVDs of two matrices with same range?

Question: Let $A$ and $B$ be two symmetric and positive semidefinite matrices with the same size.
Further, assume that $A$ and $B$ share the same column space (i.e., $\mathcal R (A) = \mathcal R (B)$ ).
Is there any relation (even in terms of strong inequalities) between the SVD of $A$ and $B$?
Answer: Yes.  The number of singular values will be the same and the left singular vectors corresponding to those singular values will match.  This is clear since if $A = U\Sigma V^T$ then $$Ax = \sum_{i} u_i (\lambda_i v_i^T x), $$  which shows that the column space of $A$ is the same as the span of the columns of $U$.  Since the column space of $A$ and $B$ are the same, the span of their left singular vectors will be the same (and since they have the same range, the rank will be the same).  They may be different up to reordering however.
While the result above is true in general, note that since $A$ and $B$ are symmetric positive-semidefinite, this implies that they have the exact same singular value decomposition (except for singular values/eigenvalues).  That is $A = U\Sigma U^T$ and the columns of $U$ are the same as the corresponding columns of the eigendecomposition for $B$.  Indeed, since they are both psd, their svd's will be the same as their eigendecomposition.
Comment: Sorry, I didn't mean exactly what I wrote.  If $A = U_1 \Sigma_1 U_1^T$ and $B = U_2 \Sigma_2 U_2^T$, since $R(A) = R(B)$, the columns of $U_1$ and $U_2$ corresponding to the nonzero eigenvalues must span the same space.  Yes, $U_1 \neq U_2$ in general as you noted.  I'm just pointing out that their eigendecompositions and svd's are (essentially) the same so that their eigenvectors must span the same space.  You also will know that their ranks will be the same.
Comment: Let $A = U_1 \Sigma_1 U_1^T$ and $B = U_2 \Sigma_2 U_2^T$.
I understand that the column space of $U_1$ and $U_2$ is the same. But, generally $U_1\not = U_2$.


Terminal não inicia pelo Visual studio code

Question: Erro recebido ao tentar abrir o terminal: O processo de terminal falhou ao iniciar o caminho para o executável (zsh) do shell não é um arquivo de um symlink.
O SO é Ubuntu.
Answer: Um dica, acessa qualquer pasta via terminal e executa o comando:
code .

Assim o teminal vai tentar abri o Visual Studio Code e se estiver precisando de alguma dependência ou configuração ele vai "printar" no terminal.


Understanding Sutton's definition of the Projected Bellman Error

Question: I am reading Richard Sutton's textbook Reinforcement Learning, chapter $11.4$, and I am confused by his definition of the Projected Bellman Error.
He defines a norm on value functions $v: S \mapsto \mathbb{R}$ where $S$ is the set of states, as
$$||v||_{\mu} = \sum_{s \in S} \mu(s) v(s)^2$$
Then assuming linear value functions for state vectors $x(s) \in \mathbb{R}^d$ given by $ v(s) = w^T x(s)$ for some vector $w \in \mathbb{R}^d$, a projection operation is defined for an arbitrary value function $v$ as
$$ \Pi v = \operatorname{argmin}_{w} ||v(s)-v_w(s)||^2$$
Further the Bellman Error at state $s$ for a value function $v_w$ from $v_\pi$ (value function given by policy $\pi$) as  $$\overline{\delta_w}(s) = (\sum_{a} \pi(a|s) \sum_{(s', r)}p(s', r|s, a)[r+\gamma v_w(s')]) - v_w(s)$$ where $a$ is an action. The mean squared bellman error is defined as $\overline{BE}(w) = ||\overline{\delta_w}||^2_{\mu}$ (the norm of the Bellman Error vector).
Now I am trying to understand the definition of the Mean Squared Projected Bellman Error given by $$\overline{PBE}(w) = ||\Pi \overline{\delta_w}||^2_{\mu}$$
Here I am not sure how to interpret this. Is this then something like
$$\operatorname{argmin}_{w'} ||\overline{\delta_w} - v_{w'}||$$ for some other value function parametrized by $w'$, where I guess you can intepret the bellman error vector itself as a value function? I'm confused by this definition and am looking for a simple English interpretation.
Further the author states that with linear function approximation, there always exists an approximate value function (within the subspace of functions parametrized by $w$), with zero $\overline{PBE}$, the fixed $TD$ (temporal difference) point $w_{TD}$, where I am not sure why this is the case. Any insights much appreciated.
Answer: $\def\wmax{\mathrm{max}}$
$\DeclareMathOperator*{\argmin}{arg\,min}$
$\def\mnorm#1{\lVert #1 \rVert^2_\mu}$
$\def\calS{\mathcal{S}}$
$\def\calW{\mathcal{W}}$
$\def\qty#1{\left( #1 \right)}$
The definition of the projection operator $\Pi$ for the policy function $v$ is,
$$
\Pi v := v_w  \text{  where  } w = \argmin_w \lVert v - v_w \rVert^2_\mu
$$
The Bellman operator $B$ has the property,
$$
v = Bv
$$
so $\overline{\delta}_v=Bv-v=0$. Then,
$$
\Pi \overline{\delta} = Bv_w - v_w \text{  where  }    w = \argmin_w \lVert Bv-v - (Bv_w - v_w) \rVert^2_\mu
= \argmin_w \lVert Bv_w - v_w \rVert^2_\mu
$$
If we denote the solution to the $\argmin$ as $\hat w$ then the Mean Square Projected Bellman Error is,
$$
\overline{\mathrm{PBE}} = \mnorm{Bv_{\hat w} - v_{\hat w}}
$$
From the definition of $\Pi$ it is clear that if $v(s)$, the policy function for a discrete set
of states $\calS$, is written as a vector $\pmb{v}$ and then for a subspace of $\calS$,
$\calW$, we define a linear map $\xi: \calW \rightarrow \calS$ we can
represent $v_w$ as $\pmb{X} \pmb{w}$ where $\pmb{X}$ is the $\dim \calS \times \dim \calW $ matrix
that represents $\xi$. Then,
$$
\lVert v -  v_w \rVert^2_\mu \quad : \quad \qty{\pmb{v} - \pmb{X} \pmb{w}}^T \pmb{D} \qty{\pmb{v} - \pmb{X} \pmb{w}}
$$
where $\pmb{D}$ is a diagonal $\dim \calS \times \dim \calS $ matrix whose diagonal elements
consist of the discrete conversion of $\mu(s)$ to a vector $\boldsymbol{\mu}$. This is a
generalized least-squares problem and has a solution given by,
$$
\hat{\pmb{w}}=\qty{\pmb{X}^{T}\pmb{D}\pmb{X}}^{-1} \pmb{X}^T \pmb{D}
\pmb{v}
$$
It follows that the projection operator can be written as,
$$
\boldsymbol{\Pi} = \pmb{X}\qty{\pmb{X}^T\pmb{D}\pmb{X}}^{-1} \pmb{X}^T \pmb{D}
$$
which is a $\dim \calW \times \dim \calS$ matrix.
Since,
$$
(Bv)(s) := \sum_a \pi(a|s) \sum_{s',r} p(s',r|s,a)[r + \gamma v(s')]
$$
we can follow the same steps to express the transformation using matrices and vectors. First,
$$
\rho(s)=\sum_a \pi(a|s) \sum_{s',r} p(s',r|s,a) r
$$
can be converted into a $\dim \calS \times 1$ vector $\boldsymbol{\rho}$. Then we can convert,
$$
\sum_a \pi(a|s) \sum_{s',r} p(s',r|s,a) v(s')
$$
into a matrix equation,
$$
\pmb{P} \pmb{v}
$$
where $\pmb{P}$ is a $\dim \calS \times \dim\calS$ matrix. So $B$ can be represented by the following affine transformation:
$$
Bv \quad : \quad \boldsymbol{\rho} +  \gamma \pmb{P} \pmb{v}
$$
Since $v_w = \pmb{X} \pmb{w}$ we can write $Bv_{w} - v_{w}$ as,
$$
\boldsymbol{\rho} +  \gamma \pmb{P} \pmb{X} \pmb{w} - \pmb{X} \pmb{w} = \boldsymbol{\rho} + \qty{ \gamma\pmb{P}-\pmb{I}} \pmb{X} \pmb{w}
$$
This is equal to the zero vector if,
$$
\hat{\pmb{w}} = \qty{\qty{\pmb{I} -  \gamma\pmb{P}} \pmb{X}}^{-1} \boldsymbol{\rho}
$$
and hence $\overline{\mathrm{PBE}}=0$.
Comment: The notation in Sutton is the Projected Belled Error (PBE), but you have written BPE, is this just a different term/typo?
Comment: Typo;  corrected.


Exibir dados no modal pelo angular ui

Question: Olá
Ao clicar no link:

abre um modal (bootstrap) e deve exibir os dados contidos no cliente.
Estou usando angular ui
Segue o $scope
$scope.editarCliente = function($cliente) {

    $scope.clienteEdit = {
        CliNome: $cliente.cli_nome,
        CliTelefone: $cliente.cli_telefone,
        CliEmail: $cliente.cli_email,
        CliDescricao: $cliente.cli_descricao
    };

     var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'clienteController',
      //size: size,
      resolve: {
        cliente: function () {
          return $scope.clienteEdit;
        }
      }
    });

Obs: abre o modal sem problemas:

        <input type="button" value="Show modal" ng-click="showModal()"/>

Exibir dados no modal pelo angular ui


Enter OG audience to a node with Rules

Question: How to add a specific Organic Group to a node in the action-step with rules (7.2)?
I can't figure out which action and which options i should use. Now i've something like
<code>**action**
Set a data value
Parameter: Data: [node:og-group-ref:0]
</code>
But this isn't correct. How can i give the og-group-ref the correct value (the OG is in this case nid 180).
Comment: I hesitate to post it as an actual answer (I might convert my comment to it if it helps) ... But instead of using "Set a data value", you could try to use "Add to list" instead ... The reason why I think this alternative should work, is because of the ":0" part at the end of "node:og-group-ref:0" (which indicates "node:og-group-ref" is an array of values).
Answer: This is not the correct answer, but i found a different way. If the og_group_ref is set to checkboxes (these checkboxes are essential) (look at admin/structure/types/manage/[YOURCONTENTTYPE]/fields/og_group_ref), you can set the default audience.
Now i just hide the field 'audience' for certain roles and new nodes are saved to the right OG.
Again, this isn't the way i asked to do it with rules. When someone knows the right answer how to do it, i'm eager to hear it.

Enter OG audience to a node with Rules


How to know what scale to use for filler licks in a chord progression?

Question: I learned about secondary dominants recently, and I found that this particular progression in the key of C major sounds quite nice:
C - E7 - Am
I - V/vi - vi
I am playing it in the following voicings:
<code>    C  E7  Am
E|--8---7--5--
B|--8---9--5--
G|--9---7--5--
D|--10--9--7--
A|--10--7--7--
E|--8------5--
</code>
With the following strumming pattern:
<code>  C   |E7|    Am
D-DUDU-DD-D--DUDD-D-D

C: D-DUDU
E7: DD
Am: D--DUDD-D-D
</code>
After I run through this progression one time, I want to play a little filler lick before repeating to spice things up, but I can't quite figure one out. I have tried playing around with the C major/A minor pentatonic scales but nothing really sticks out. How can I know which scales to target for nice licks within a chord progression? Is it not as cut and dry as an entire "scale" but rather look for certain notes to embellish the chords with? If this is so, from which chords do I take notes from to embellish? On Youtube or Instagram, most lessons I see just use major pentatonic or the relative minor pentatonic of the tonic. Am I just not looking hard enough in Cmaj/Am penatonic for a good lick? An example lick would be awesome.
Bonus question:
When I play through the progression the second time, my ears want to repeat with variation very badly. By this, I mean that I want to play something other than an Am the second time around. I conceptualize it as a higher pitched chord, so something further down the neck than Am. I tried just different voicings of Am but that didn't quite capture what my brain is feeling. I tried Fmaj7 in the 8th fret barre shape, that kind of got there, but not quite what I wanted. What are other chords E7 resolves to nicely in the context of C major?
Please forgive any blunders I may have made regarding terminology. I am still learning all of this music stuff :) thanks!
Comment: Your "bonus question" perhaps should be asked as a separate question...
Answer: There are whole books written about how to compose melody to a chord progression, don't expect an answer at SE to be complete. Also it is a question about creative choices, and there is no single good answer how to make them. What I present below is only a simplified example of a workflow.
Starting with the chord tones is typically a good idea. Let's write them down:

C: C-E-G
E7: E-G#-B-D
Am: A-C-E

At first it's worth checking if the chords are written correctly – in your case they seem to be (so e.g. E7 seems correct, rather than e.g. Fb7).
You correctly identified E7 as V/vi, a secondary dominant. This gives the first clue: secondary dominant is a chord from another key (in this case from the key of vi, Am), so it is not diatonic in the original key. You don't necessarily should/need to use the same scale over all three chords.
There is also a hint in the chord tones: in C there is G, but in E7 there is G#. As western scales typically use 7 notes, one for each letter, this suggests a different scale to be used over each of these chords.
Next, in order to connect chords smoothly (which is not always what you want to do), you may choose the consecutive scales which share. We can start by writing down all notes from the three chords (if the song has already a vocal melody written, include its notes too):

C D E G/G# A B

We may find choose to use the following scales:
<code>- C ionian:      C D E F G  A B
- E phryg.dom.:      E F G# A B C D
- A aeolian: A B C D E F G
</code>
In classical music, dominants to minor chords typically use b9, this supports use of F with E7.
But we could also choose:
<code>- C lydian:        C D E F# G  A B
- E mixolydian b6.:    E F# G# A B C D
- A dorian:    A B C D E F# G
</code>
These are just examples, don't get discouraged to try other scales. In particular, the dominant chords often go well with many other scales, e.g., superlocrian, lydian b9, half/whole tone.
Comment: @piiperiReinstateMonica when I was writing this answer I knew someone is going to comment that it's incomplete. I know it's incomplete, because you'd need to write a book to make it complete. And books are written. If it helps I can state here: scales are not the only important building block in music, moreover, certainly not the most important one. But the question was about scales, and I tried to answer the best I could.
Comment: I got the idea that the OP isn't necessarily trying to play a melody but a "fill". Something, anything to go between the comping chords to create a sense of variation. It could be a bunch of chords or intervals. The OP just assumed that when people come up with fills and variations to their chord comping, they must be thinking about scales, because all youtube videos talk about scales.
Comment: I did not say your answer is incomplete, I tried to say that the OP seems to be asking, "how do people come up with fills between chords, is it scales or chord tones or what." I would assume that _most_ guitarists don't think about scales at all when adding variations and embellishments to chordal comping. At least people who learned to play before Youtube.
Comment: @piiperiReinstateMonica Well, I'm saying it's incomplete!
Answer: There's no absolute answer here. But a rule of thumb is to use a note common to both chords (C&E) to start the quite short run into Am, and that run would finish on a note common to both E & Am.
Bearing that in mind, the common note between C&E is E, so the lick would start with an E. A few notes on (really belonging to the E scale) it would end on E - in the Am bar. Another idea would be to end the lick on G♯, as that's the leading note for the following Am harmony, setting it up beautifully.
Having said all that, there's no better way than that we always used to (and still) use - don't work it out using theory, but try several different ideas, to come up with some things that sound good. I think you're trying to put the cart before the horse - theory tells what has happened, therefore could re-occur, and I'm sure if you come up with something sounding good, someone will be able to theorise as to why...
Answer: I strummed through it, and immediately went to what turns out to be a Mixolydian mode in C major for my lead experiments.
(I had to look it up, quite honestly, matching what I played to whatever scale seemed to fit that intuitive fingering.)
It's all subjective, of course, as other have pointed out.
What sounds good to me may or not fit the notions in your head.


Does Hilbert space intuition carry over to Banach space?

Question: Given a Banach space $X$ and its dual space $X^*$. Suppose $a$ and $b$ are two unit norm vectors in $X$. $a^*$  and $b^*$ be unit norm elements in dual space $X^*$ such that $a$ and $a^*$ as well as $b$ and $b^*$ are aligned. Is $\langle a,b^*\rangle = \langle b,a^*\rangle$? If yes please present a proof else a counter example.
Note:$\langle x,x^*\rangle$ is used to denote the action of dual space elements($x^*\in X^*$) on the elements in the original space($x\in X$).
$a$ aligned with $a^*$ $\Rightarrow \langle a,a^*\rangle = \|a\|\|a^*\| = 1$. Similarly $\langle b,b^*\rangle = \|b\|\|b^*\| = 1$.
According to me in a Hilbert space setting $\langle a,b^*\rangle = \langle b,a^*\rangle$ is equivalent to $\langle a,b\rangle = \langle b,a\rangle$ or equivalently $a^Tb = b^Ta$. Thus it holds for Hilbert spaces owing to the symmetric nature of inner product in a Hilbert space. So I believe that the result might hold in a Banach space.
Comment: I suggest using \langle and \rangle in place of < and > for inner products. It is much easier on the eyes.
Comment: Thanks @Cameron Williams . Suggestion has been implemented.
Comment: You write that $a^{*}$ is *the* element of $X^{*}$ of unit length aligned with $a$. I don't think there's necessarily only one. For example, consider $a = (1,1)$ in $\mathbf{R}^2$ with the sup norm. Any line through $(1,1)$ with negative slope corresponds to an $a^{*}$ that is aligned with $a$.
Comment: You are correct about the fact that there could be multiple $a^*$ possible. Even if you consider any one of them does the condition $ = $ hold.
Answer: Consider $\mathbf{R}^2$ with the sup norm. Define $a=(1,0)$, $a^{*}(x,y) = x$, $b=(1,1)$, $b^{*}(x,y) = y$. Then $a$ and $a^{*}$ are aligned, as well as $b$ and $b^{*}$. However $\langle a,b^{*} \rangle = 0$ and $\langle b,a^{*} \rangle = 1$
Comment: Could you also think of a counter example using other norms apart from the sup norm? Also any comments on conditions under which the result would hold is of great help.
Comment: I don't know. You could ask the same question again in the case of a strictly convex space. Also, what are sufficient conditions for $a^{*}$ to be unique?


Logstash unable to index into elasticsearch because it can't parse date

Question: I am getting a lot of the following errors when I am running logstash to index documents into Elasticsearch
[2019-11-02T18:48:13,812][WARN ][logstash.outputs.elasticsearch] Could not index event to Elasticsearch. {:status=>400, :action=>["index", {:_id=>nil, :_index=>"my-index-2019-09-28", :_type=>"doc", :_routing=>nil}, #<LogStash::Event:0x729fc561>], :response=>{"index"=>{"_index"=>"my-index-2019-09-28", "_type"=>"doc", "_id"=>"BhlNLm4Ba4O_5bsE_PxF", "status"=>400, "error"=>{"type"=>"mapper_parsing_exception", "reason"=>"failed to parse field [timestamp] of type [date] in document with id 'BhlNLm4Ba4O_5bsE_PxF'", "caused_by"=>{"type"=>"illegal_argument_exception", "reason"=>"Invalid format: \"2019-09-28 23:32:10.586\" is malformed at \" 23:32:10.586\""}}}}}

It clearly has a problem with the date being formed but I don't see what that problem could be.  Below are excerpts from my logstash config and the elasticsearch template.  I include these because I'm trying to use the timestamp field to articulate the index in my logstash config by copying timestamp into @timestamp then formatting that to a YYY-MM-DD format and use that stored metadata to articulate my index
Logstash config:
input {
      stdin { type => stdin }
}
filter {
  csv {
     separator => " "   # this is a tab (/t) not just whitespace
     columns => ["timestamp","field1", "field2", ...]
     convert => {
       "timestamp" => "date_time"
       ...
     }
  }
}

filter {
  date {
    match => ["timestamp", "yyyy-MM-dd' 'HH:mm:ss'.'SSS'"]
    target => "@timestamp"
  }
}

filter {
  date_formatter {
    source => "@timestamp"
    target => "[@metadata][date]"
    pattern => "YYYY-MM-dd"
  }
}

filter {
  mutate {
    remove_field => [
      "@timestamp",
      ...
    ]
  }
}

output {
   amazon_es {
     hosts =>
         ["my-es-cluster.us-east-1.es.amazonaws.com"]
     index => "my-index-%{[@metadata][date]}"
     template => "my-config.json"
     template_name => "my-index-*"
     region => "us-east-1"
  }
}

Template:
{
    "template" : "my-index-*",
    "mappings" : {
      "doc" : {
        "dynamic" : "false",
        "properties" : {

          "timestamp" : {
            "type" : "date"
          }, ...
    },
    "settings" : {
      "index" : {
        "number_of_shards" : "12",
        "number_of_replicas" : "0"
      }
    }
}

When I inspect the raw data it looks like what the error is showing me and that appears to be well formed so I'm not sure what my issue is
Here is an example row, it's been redacted but the problem field is untouched and is the first one
2019-09-28 07:29:46.454 NA  2019-09-28 07:29:00 someApp 62847957802 62847957802

Comment: Share a sample of your data so people can try to replicate your pipeline. Also, any particular reason to remove the `@timestamp` field? If you don't remove logstash can use its date to create the index name.
Comment: @leandrojmp added a redacted row to help reproduce the issue.  question about removing the `@timestamp` field, the main reason was just that I was already getting it from my file and didn't need to have two so just seemed logical to remove it
Comment: What is the purpose of the single quote at the end of the `'.'SSS'"`?
Comment: @JesseC.Slicer I found one post suggesting that that was how it was supposed to be but I can't remember where.  I've tried both with and without and still get the error unfortunately
Comment: @JesseC.Slicer found the post https://www.elastic.co/guide/en/logstash/current/plugins-filters-date.html . It's for non formatting syntax.  But I don't think that's the problem because I'm using that to create metadata which appears to be working.  It's the raw value itself that can't go into the `timestamp` field so the file can't be indexed
Answer: Turns out the source problem was the convert block.  logstash is unable to understand the time format specified in the file.  To address this I changed the original timestamp field to unformatted_timestamp and apply the date formatter I was already using
filter {
  date {
    match => ["unformatted_timestamp", "yyyy-MM-dd' 'HH:mm:ss'.'SSS'"]
    target => "timestamp"
  }
}

filter {
  date_formatter {
    source => "timestamp"
    target => "[@metadata][date]"
    pattern => "YYYY-MM-dd"
  }
}

Answer: You are parsing your lines using the csv filter and setting the separator to a space, but your date is also split by a space, this way your first field, named timestamp only gets the date 2019-09-28 and the time is on the field named field1.
You can solve your problem creating a new field named date_and_time with the contents of the fields with the date and the time, for example.
csv {
    separator => " "
    columns => ["date","time","field1","field2","field3","field4","field5","field6"]
}
mutate {
    add_field => { "date_and_time" => "%{date} %{time}" }
}
mutate {
    remove_field => ["date","time"]
}

This will create a field named date_and_time with the value 2019-09-28 07:29:46.454, you can now use the date filter to parse this value into the @timestamp field, the default for logstash.
date {
    match => ["date_and_time", "YYYY-MM-dd HH:mm:ss.SSS"]
}

This will leave you with two fields with the same value, date_and_time and @timestamp, the @timestamp is the default for logstash so I would suggest keeping it and removing the date_and_time that was created before.
mutate {
    remove_field => ["date_and_time"]
}

Now you can create your date based index using the format YYYY-MM-dd and logstash will extract the date from the @timestamp field, just change your index line in your output for this one:
index => "my-index-%{+YYYY-MM-dd}"

Comment: I will definitely try this approach but am skeptical given the error `"Invalid format: \"2019-09-28 23:32:10.586\" is malformed at \" 23:32:10.586\""`.  It seems like it's actually getting the entire date and time but is just saying it's malformed
Comment: Also forgot to mention that my separator isn't just white space, it's a tab, and the file is showing that special character.  I have edited the post to make that more clear


Erro em gerar Gráfico de pizza "pie" em highchart ASP.NET MVC

Question: Estou tendo problemas para gerar um gráfico de pizza no estilo de Highcharts. Eu tenho o seguinte código para gerar a série:
if (vlrTot1 >= 0)
        {
            Dictionary<string, object> aSeries = new Dictionary<string, object>();
            aSeries["data"] = new List<object[]>();
            aSeries["name"] = "TIR <= " + vlrLimInf.ToString();

            object[] values = new object[2];
            decimal vlr1 = Math.Round(((vlrTot1 / (vlrTot1 + vlrTot2 + vlrTot3)) * 100),  1 );
            values[0] = "TIR <= " + vlrLimInf.ToString();
            values[1] = vlr1;
            ((List<object[]>)aSeries["data"]).Add(values);
            dataResult.Add(aSeries);

        }
        if (vlrTot2 >= 0)
        {
            Dictionary<string, object> aSeries = new Dictionary<string, object>();
            aSeries["data"] = new List<object[]>();
            aSeries["name"] = vlrLimInf.ToString() + " > TIR <= " + vlrLimSup.ToString();

            object[] values = new object[ 2 ];
            decimal vlr2 = Math.Round(((vlrTot2 / (vlrTot1 + vlrTot2 + vlrTot3)) * 100),  1);
            values[0] = vlrLimInf.ToString() + " > TIR <= " + vlrLimSup.ToString();
            values[1] = vlr2;
            ((List<object[]>)aSeries["data"]).Add(values);
            dataResult.Add(aSeries);

        }
        if (vlrTot3 >= 0)
        {
            Dictionary<string, object> aSeries = new Dictionary<string, object>();
            aSeries["data"] = new List<object[]>();
            aSeries["name"] = "TIR > " + vlrLimSup.ToString();

            object[] values = new object[2];
            decimal vlr3 = Math.Round(((vlrTot3 / (vlrTot1 + vlrTot2 + vlrTot3)) * 100),  1);
            values[0] = "TIR > " + vlrLimSup.ToString();
            values[1] = vlr3;
            ((List<object[]>)aSeries["data"]).Add(values);
            dataResult.Add(aSeries);
        }

Que está gerando este gráfico:

As duas séries estão aparecendo com 100%.
Mas o gráfico correto teria que ser este:

Abaixo está a saída para gerar o gráfico com json:
var data = ServiceGraf.GetValuesByGrafPie(....PARAMETERS....);

                return Json(data, JsonRequestBehavior.AllowGet);

Eu não sei onde está errado. Abaixo encontra-se o valor do Json de saída:

function (data) {
                 var chart = new Highcharts.Chart({
                        chart: {
                            renderTo: 'container',
                            ignoreHiddenSeries: false,
                            type: graf,
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false

                        },
                        title: {
                            text: 'Gráfico do Levantamento de ' + levant
                        },
                        tooltip: {
                            pointFormat: '{series.name}: {point.percentage:.1f}%'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                },
                                showInLegend: true
                            }
                        },
                        series: data
                    });
                   }

Comment: O Highcharts, a priori, aceita um array de object (`object[]`). O que você está passando é uma lista de arrays de object, o que pode fazer o script se perder.
Comment: Para o gráfico de linha, eu fiz praticamente a mesma coisa, e funcionou muito bem para ter varias séries, mas com este não sei o que esta ocorrendo.
Comment: A diferença é que o grafico de linha aceita series enquanto o grafico de pizza não.
Comment: Descobri o que estava dando de errado.
Answer: Colocando desta forma resolve o problema.
       var dataResult = new List<List<Object>>();
        dataResult.Add(new List<object>(new object[] { leg1.ToString(), vlr1 }));
        dataResult.Add(new List<object>(new object[] { leg2.ToString(), vlr2 }));
        dataResult.Add(new List<object>(new object[] { leg3.ToString(), vlr3 }));


Redirect output to /dev/tty1 outside chroot jail?

Question: I couldn't figure out exactly how to word this in my searching; if someone could tell me what this is called and point me to a resource I would greatly appreciate it.
TL;DR: For a CentOS installation, I want users to be able to watch the %post section of the kickstart file operate on the physical screen so it can be monitored.  A person will hit enter on a keyboard to kick off an installation, and the same person will watch the install work on a monitor in front of them.  I want them to see what it's doing.
My understanding of the structure is this:

The CentOS installation reads a kickstart file.
The %pre section of the kickstart runs in the "root" context of the
installer live image.
The %post section runs in the "root" context of the installing
system, allowing me to perform things like "yum -y update" etc to
affect the installed system.

In a normal environment, I know I can redirect the output of a command to a terminal with:
cat "file.txt" > /dev/tty3

The problem is that this command redirects output to the chroot jail's version of /dev/tty3, which does not show on the install screen.  I want it to output directly to the "parent" installation's screen, so if it somehow recognized the parent directory, it would be something like
cat "file.txt" > ../../../dev/tty3

Or something.
Can anyone help?
Comment: For clarity, is this for monitoring when connected to the console (ie a human sitting there in realtime) or something more automated. If it's a human at the console then doesn't the virtual console show the messages you want (`ALT-F3`)?
Comment: It's for a human to look at the physical screen, or an IPMI window which are equivalent for this scenario.  I'll alter the original question, thanks!
Answer: It turns out I'm actually just a moron.  Terminal redirection in %post works just fine; although I don't understand why.
Here is the relevant section of my kickstart; the problem was that I was redirecting output of each command with ">>" and forgot that it does not display to screen; you need to use "|tee -a" for that.  I was so caught up in terminal redirection logic that I missed the obvious error.
The following works in a CentOS 7.3 kickstart file for doing what I wanted:
%post --interpreter /bin/bash --log=/root/post_section.log
#Take note of our current tty
c=`tty`
#Set the file descriptors of our shell to the input and output of
#tty 6
exec < /dev/tty6 > /dev/tty6
#Change the visible terminal to terminal 6
chvt 6
#Clear the screen on TTY6
clear

#Do DevOps shit
yum -y install python epel-release python-pip git
echo ""
echo "Cloning deploy_devops..."
cd /root
git clone http://<REMOVED>devops.git
cd deploy-devops
echo "Kicking off deploy_devops.py..."
time python devops.py
echo "All done."

#Change the visible terminal back to #1
chvt 1
#Put our file descriptors back to the original terminal
exec < $c > $c
%end


What are the difference between FM synthesis and Additive synthesis?

Question: To my limited understanding, additive synthesis adds "simpler" sound waves together to create a more rich and complex sound wave.
I've read that FM synthesis uses another sound wave to manipulate another waveform to create a more complex sound.
I cant grasp the difference, doesn't both methods fundamentally add sound waves together to create a more complex sound? Whats separates them?
Very grateful for any answers!
Answer: FM and additive synthesis have almost nothing in common. The only common aspect I can think of is that many FM synths allow using several oscillators or "operators" summed i.e. mixed together in adjustable mixture ratios, which is not in principle even a part of FM synthesis. The thing that FM synthesis conceptually does not do is add waves together, even though real-life FM synthesizers allow for that to some extent.
In FM synthesis, the frequency of an oscillator is modulated by another audio rate signal.
https://en.wikipedia.org/wiki/Frequency_modulation_synthesis
Think about the tuning knob of a guitar. Pluck a string and start turning its tuning knob back and forth - the string's pitch goes up and down. You are modulating a frequency. If you could do this up/down tuning at a rate of, say, 1000 times a second, and if the guitar could actually do this, you could say that you're doing frequency modulation. Or actually, if one string's oscillating wave motion could turn the tuning knob of another string, you would have an FM guitar.
The set of frequencies created by the modulation depends on the accuracy of the oscillators and operations involved, and the precision needs to be very high so that it creates the same frequencies reliably enough for musical applications. That's why in practice, frequency modulation got very popular only when it was done with digital circuits which allow for mathematically perfect accuracy and timing. By perfect I mean that digital calculations always produce exactly the same numerical output for the same input, and with discrete timing, so the operations produce stable results that are not subject to the analog world's tuning instability.
The sound created in FM, when you can modulate an oscillator at an audio rate is not at all intuitive. I don't think anyone could imagine the sounds created by FM synthesis - they're very surprising, rich and complex, and the amount of overtones added can be very large. Small changes of parameters and "algorithms" in FM synthesis can change the sound dramatically like in quantum leaps. This is why some people see FM synthesizers as wild beasts they can't control.
In additive synthesis, sine waves are added together. https://en.wikipedia.org/wiki/Additive_synthesis
It's a bit like a Hammond organ or church organ where you can create a mix of overtones/partials/multiples of a fundamental base frequency. This is a very intuitive and simple way of molding sounds. You can dial in more or less highs and lows etc.
Comment: Scary memories!! You've just reminded me of my first forays into DX7 programming… totally non-intuitive until Steinberg started making their editor software. Years later, in a quite bizarre coincidence, I got Dave Bristow's job when he left Yamaha for Emu. In the early DX7 years, the Bristow presets were known for being able to use lower case in the titles. The onboard editor couldn't do that.
Comment: @Tetsujin So did you learn to make sounds with FM? :) Some people are able to handle the beast. For example this guy creates all sorts of sounds with FM synthesis https://www.youtube.com/watch?v=P6CgLXrkMXI    https://www.youtube.com/watch?v=eLTJlesVBhk    I think that's completely insane!
Comment: I was a 'poker' never an expert. I was better with the 'berg editor, but never anything like Dave B was. he could 'imagine' a waveform & build it.
Comment: "In practice, frequency modulation can only be done with digital circuits which allow for mathematically perfect precision and timing." That's incorrect. Analog FM implementations (including audio synthesis applications) are very common, not sure where you got the idea that it can only be done digitally. It is less expensive to implement a system that includes several operators (modulators + carriers) digitally, but where did you get the idea that "in practice frequency modulation can only be done with digital circuits which allow for mathematically perfect precision and timing"?
Comment: @VonHuffman Better now? I think you knew perfectly well what I was trying to say.
Comment: @piiperiReinstateMonica There's floating point arithmetic involved, so your current  paragraph is still incorrect. Neither the precision nor timing are "mathematically perfect", I'm not sure what you are trying to convey with the digital observation. It became more popular because it was way cheaper to manufacture, not because it can only be done digitally, and not because it's "mathematically more perfect".
Comment: @VonHuffman It is mathematically perfect in the sense that it will always produce exactly the same output from the same input and is not subject to variations of the analog world. And timing is perfect in the sense that it's discrete. This answer is good enough for the question. Write your own correct answer, use the vote buttons, etc.
Answer:
To my limited understanding, additive synthesis adds "simpler" sound waves together to create a more rich and complex sound wave.

Yes - specifically, additive synthesis is about adding sine waves together to create a more complex resultant waveform.

I've read that FM synthesis uses another sound wave to manipulate another waveform to create a more complex sound.

Yes - specifically, it uses one wave to control the frequency of another wave. In some implementations of FM these waves are only sine waves; in other implementations, each of these waves might themselves be more complex waves.
So as piiperi Reinstate Monica's answer says, at the simplest level, the techniques are different.
Let's take a look at the algorithms in the Yamaha DX7, the best-known FM synth:

The blocks (operators) at the bottom represent carriers - the 'initial' waves being modulated. In the DX7, each of these is a sine wave. If we look at algorithm 32, and ignore the fact that operator 6 can modulate its own frequency, you could use that as a simple 6-sine additive synthesizer. So there is a degree of similarity there, even though the techniques are entirely different.
Answer: I have a different take. Additive is about building up a target frequency spectrum and specifying how it evolves. It is a broad class of techniques.
FM is a more narrow set of techniques for building static or evolving spectra. You can approach FM patch building in different ways. One approach is to build up a target spectrum as in additive synthesis.
Many FM synthesizers allow multiple voice layers for building rich and complex sounds. This kind of patch lends itself to an additive approach particularly.
Some people who study music place additive and FM together as very closely related. Others see additive as particularly about summing sine waves and see less connection.


Why doesn't C# have lightweight exceptions?

Question: It's often said that you shouldn't use exceptions for regular error handling because of bad performance.  My guess is that that bad performance is caused by having to instantiate a new exception object, generate a stack trace, etc.  So why not have lightweight exceptions?  Code like this is logically sound:
string ageDescription = "Five years old";
try {
    int age = int.Parse(ageDescription);
}
catch (Exception) {
    // Couldn't parse age; handle parse failure
}

And yet we're recommended to use TryParse instead to avoid the overhead of the exception.  But if the exception were just a static object that got initialized when the thread started, all the code throwing the exception would need to do is set an error code number and maybe an error string.  No stack trace, no new object instantiation.  It would be a "lightweight exception", and so the overhead for using exceptions would be greatly reduced.  Why don't we have such lightweight exceptions?
Answer: The exception object instantiation is the smallest problem in the whole case. The real performance killer is that the control flow must stop executing your program and has to look up the call stack for possible handlers (catch blocks) that can catch the thrown exception, then it has to execute the correct ones (and their finally blocks), rethrow exceptions when told so and then continue executing the program on the right place, i.e. after the last handler. Your idea of "lightweight" exceptions would change nothing of this, it would even slow down creation of threads, because it would have to create and store the exception object, and would prevent exception filtering by type, which is now possible.
By using TryParse, you avoid all this by a simple conditional clause, also you actually write less code and it is much easier to read and reason about.
Exceptions are for exceptional cases and in such scenarios, they provide lots of useful information for logs/debugger.
Comment: Not sure I agree with the "would prevent exception filtering by type" part.  The static object could surely store "exception type" which would maybe be an enum value.
Comment: @Jez: Maybe you could contrive a less functional type of exception which you could use in parallel with C#'s exception handling.  But to do so would mean having two exception types which would be quite inconsistent and confusing for programmers, each with differing capabilities.  And what, then, would be the point of creating two ways of doing the same thing, splintering the language functionality in the name of optimization if you could just use a best practices and use things like Int32.TryParse() when performance really *is* important?
Comment: When would you set what exception is being "thrown"? How would you add custom exceptions? Also it would often end up with a `switch` of some sort in the catch clause. Check out **[exception filters](http://msdn.microsoft.com/en-us/library/8a9f2ew0%28v=vs.80%29.aspx)** in VB, they are also an interesting example, what these exceptions can do
Comment: @HonzaBrestan 1) In the `throw` statement.  2) By setting the exception "type" to whatever value you want that will be meaningful to your `catch`ing code.  3) Why would it end up with a `switch`?
Comment: 1) Fair enough, but I can see no way of specifying the type without creating an instance of something. 2) So you want to have dynamic exception? Or a string? 3) What if my code can throw 4 different exceptions and I want to react differently to each one?
Comment: @DaveMarkle: Consider the following scenarios: (1) `SomeCollection.Add()` fails with `InvalidOperationException` because the item already exists (2) `SomeCollection.Add` calls some method which *unexpectedly* throws `InvalidOperationException`.  I would suggest there should be some value in allowing the code which calls `SomeCollection.Add` to distinguish between the exception which passed through a caller that wasn't "expecting" it, versus the one that never did.  If I had my druthers, the first situation would be a "checked" exception, but...
Comment: ...rather than forcing extra baggage on method callers that aren't prepared to handle checked exceptions the way Java does, I would specify that code which doesn't catch a checked exception thrown by a method must declare (concisely) whether such exceptions should be passed through, or propagate as unchecked exceptions.  Checked-ness would not be a function of the exception type, but rather the throw site and catch site.  Note that a method which throws a checked exception need not use exception-handling mechanisms; it could simply have the exception as an extra part of its return value.
Comment: Code is WAY simpler and more effective when a function either returns the expected result or throws an exception.  If a method, for example, that's supposed to return an object, accepts three identifiers....  it's easier to parse all three, throwing an exception on any failure, than it is to accumulate three tryparses, examine all three results, and then complicate the return value of the function to include success or failure.  It's a much simpler programming model to have functions return a valid result or throw, and have callers handle the throw.  Enough about 'exceptional' circumstances.
Answer: The performance hit isn't just because you're creating a new Exception object.  A lot of it has to do with the conditional unwinding of the stack that needs to be done when an exception occurs.
For example, think about the work that would have to be done when you have exception handlers that catch different kinds of exceptions.  At each point in the stack, as it's unwound from callee to caller, the language must do a type check to see not only if the exception can be handled, but what the most appropriate handler is.  That's a significant amount of overhead in its own right.
If you really want to be lightweight, you should return a result from your functions -- that's what Int32.TryParse() does.  No stack unwinding, no type checking, just a simple condition which can easily be optimized for.
EDIT: One somewhat interesting thing to note is that C# was created after Java.  Java has a couple of interesting constructs which cause exception handling to be more complicated than what we see in C#, namely checked exceptions and the throws keyword.  Kind of interesting reads.  I'm (personally) glad that C# didn't include this "feature".  My guess is that they bifurcated their exception handlers to boost performance.  In the real world, as I understand it, a LOT of developers just end up specifying throws exception in their function declarations.
Comment: Like I said as an comment to Honza's excellent answer, the C# language designers could have done a number of things.  The core answer to why something isn't in the language, and I suspect the answer to your question is, "though it could be possible, the inconsistency isn't worth it when there's another, simpler way of achieving the same result (high performance)".
Comment: @user3339997: Yes, it does mean that.  The pattern of returning error codes should be generally be avoided in C# code.
Comment: That type check is using reflection, no?  With a "lightweight exception", instead of checking the type of the exception instantiation, you could just use an enum to specify the "type" of exception and compare with that.
Comment: We have to catch exceptions from components, even those that return error codes, because at any time they might throw due to unforeseen errors. Doesn't this mean that the benefit from returning error codes is now lost?
Comment: Just want to chime in a few years later and state that this answer is now outdated in its performance claims. Lightweight exceptions *can* be fast - [OCaml's lightweight exceptions are faster than even a `setjmp` in C.](https://stackoverflow.com/questions/8564025/ocaml-internals-exceptions) It just requires a specialized calling convention that supports lightweight exceptions (and they use caller-saved registers exclusively, which simplifies their end).
Answer: The problem with exceptions isn't just generating the exception itself, that's honestly not even the most time consuming part.  When you throw an exception (after it has been created) it needs to unwind the stack going through each scope level, determining if that scope is a try/catch block that would catch this exception, update the exception to indicate it went through that section of the stack, and then tearing down that section of the stack.  And then of course there are all of the finally blocks that may need to be executed.  Making the Exception itself store less information wouldn't really simplify any of that.
Comment: I don't think the stack unwinding is expensive in comparison to the stack trace collection. After all, collecting the stack trace requires visiting *every* stack frame and possibly do symbol lookups; not just visit and have a condition or two on each try in between the throw site and catch site.
Answer: You should use int.TryParse in your case. And it is faster and more readable to test some conditions then to throw and catch exception. Use exceptions for exceptional situations not for regular validation.
Comment: @Jez: I think the part "Use exceptions for exceptional situations" answers your question as to why it is the way it is.
Comment: For god's sake, this answer doesn't even attempt to answer my question.  -1.  The fact that people are voting this up shows that they probably haven't read the question either.
Comment: For god's sake, if you want to shot in your foot, you can do it, but i don't recommend. But there are some useful mechanics for regular error handling other than throwing exceptions. Use it.
Comment: @m-y What, write some oft-repeated platitude and watch a bunch of people click the upvote button without even considering whether it actually answers the question?  Sigh.
Answer: Because the utility offered by the "heavyweight" exceptions is exceptionally (ha ha) useful. I can't tell you how often I've wanted the ability to dump something like a stack trace in C land without having to ask people to yank out a debugger.
Generating things like the stack trace after the fact (i.e. after the exception has been caught on demand) are infeasible because once the exception has been caught, the stack has been unwound -- the information is gone. You want information about the point of failure; so the data must be collected at the point of failure.
As for the "new object instantiation" -- that is so cheap in comparison to other expensive exception features (unwinding the stack, stack trace, multiple function exit points, etc.) that it isn't worth worrying about.
Comment: But I'm not talking about doing away with regular exceptions; I'm talking about adding a new form of lightweight exception to address the performance issue in cases where you'd rather write your code like my example, instead of checking return values all over the place.
Comment: @Jez: The only use case for your proposed "lightweight exceptions" is in the rare case that an exception is thrown and intended to be handled by a function's immediate caller. In such cases, the propsed "lightweight exceptions" would be functionally equivalent to error codes; and provide little in the way of benefit there. That defeats the point of exceptions. Exceptions are useful when the point where an error must be handled is far from where the error actually occurs.
Answer: You're not recommended to use TryParse instead of Parse because of performance. If there's any chance a parse can fail (because it's user generated input for example) then the failure to parse is not exceptional, it's to be expected. As the name implies, exceptions are for exceptional circumstances. For stuff that should have been caught earlier, but wasn't, so unexpected that you can't really continue.
If a function expects an object but instead null is passed in, then it's up to the designer of the method what the right thing to do is in this case. If the parameter is an optional override for a default, the program ca continue and use the default or ignore the parameter. But otherwise, the program should simply throw a ArgumentNullException.
Performance shouldn't be a consideration at all when deciding to use exceptions or not. It's a matter of intent and purpose. They're not even that slow, sure they're many times slower than adding two integers, but I can still throw 50,000 exceptions per second on my aging Core 2 Duo. If the use of exceptions ever becomes a bottleneck, you're not using them in the right way.
Comment: "If the use of exceptions ever becomes a bottleneck, you're not using them in the right way." Nice! But does that apply in C++ too?


Erro "Cannot make static reference to the non-static fiel

Question: Estou a fazer um exercício  com uma classe Carro e subclasses Familiar Citadino e Jipe... Só que ao fazer uma classe Testabuzinar1 que instancia cada uma das subclasses e depois chama o método buzinar (que está na classe Carro) e aparece me um erro

Cannot make astatic reference to the non-static field...

Segue o codigo da classe Testa buzina
public class TestaBuzinar1 {
    public Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public Familiar familiar = new Familiar();
    public Jipe jipe = new Jipe();

    public static void main(String[] args) {

        citadino.buzinar();
        familiar.buzinar();

    }

}

Answer: O erro é claro, você está tentando acessar campos não estáticos dentro do main, que é estático.
Se precisa mesmo que sejam campos de classe adicione static para que os campos possam ser acessados diretamente no main:
public class TestaBuzinar1 {
    public static Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public static Familiar familiar = new Familiar();
    public static Jipe jipe = new Jipe();

    public static void main(String[] args) {

        citadino.buzinar();
        familiar.buzinar();

    }

}

Ou também você pode simplesmente criar uma instancia da classe TestaBuzinar1:
public class TestaBuzinar1 {
    public Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public Familiar familiar = new Familiar();
    public Jipe jipe = new Jipe();

    public static void main(String[] args) {

        TestaBuzinar1 testb = new TestaBuzinar1();
        testb.citadino.buzinar();
        testb.familiar.buzinar();

    }

}

Como foi bem lembrado pelo @Anderson, há uma solução mais simples, que é tornar os campos locais dentro do main:
public class TestaBuzinar1 {

    public static void main(String[] args) {

        Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
        Familiar familiar = new Familiar();
        Jipe jipe = new Jipe();

        citadino.buzinar();
        familiar.buzinar();

    }

}

Leitura recomendada:
Qual o uso de uma variável estática ou final em java?
Comment: Ou inclui as instâncias das classes no método `main`, fazendo-os locais.
Comment: @AndersonCarlosWoss tinha me esquecido dessa possibilidade
Comment: Obrigada pela ajuda