How to get drive information by volume id

Question: I have a txt file with volume id's in it.
I need to get drive info (drive letter, drive size, etc.) from the drive volume id (Windows):
the volume id is in the following format:
\\?\Volume{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}

The drive can be Removable/local disk
It doesn't matter how the info is retrieved (it could be script, cpp ,c#, java code).
EDIT:
I tried to use DriveInfo, Win32_LogicalDisk, Win32_Volume, Win32_PnpDevices - but I couldn't find this weird id... in all cases the id has a differrent format
UPDATE:
Found out how to do it.
you can enumerate Win32_Volume like this:
ManagementObjectSearcher ms = new ManagementObjectSearcher("Select * from Win32_Volume");
foreach(ManagementObject mo in ms.Get())
{
    var guid = mo["DeviceID"].ToString();

    if(guid == myGuid)
        return mo["DriveLetter"];
}

Comment: How did u get that id in txt file. Reverse Engineer it to reach the results.
Comment: I am trying to track where "File History" (new feature in windows 8) is savingi its backup files. I found that the target device name is saved in an xml file, it also saves the drive letter and name, but this is not enough because these parameters are not unique and can be changed: somene can eject the device and then in the next time it will have a different letter assigned, etc... so I found that microsoft also saves something that looks like the following: " \\?\Volume{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} <\TargetVolumePath>" which is unique id.
Answer: Volume size, etcetera is easy. Just use the normal Win32 methods. Any function that accepts "C:" as a drive will also accept the volume GUID path (because that's what a \\?\Volume{XXX} is properly called).
The "drive letter" is a bit trickier as there may be 0, 1 or more drive letters. You need to call FindFirstVolumeMountPoint / FindNextVolumeMountPoint / FindVolumeMountPointClose to get all of them.
Comment: Can you adda code sample using WMI? I used GetVolumeNameForVolumeMountPoint and it works, but I couldn't make it work using wmi.
Comment: See the example at http://msdn.microsoft.com/en-us/library/windows/desktop/aa394515(v=vs.85).aspx
Answer: Try use this
System.Management.ManagementObjectSearcher ms =
new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject mo in ms.Get())
{
    //Find by ID
}

For details reed this Win32_DiskDrive class
Answer: There is an API function for this:
GetVolumePathNamesForVolumeName
It returns a null terminated array, to allow for multiple mount points. If you have only one mount point (typical), then you can read it as a regular null terminated string.
This is more efficient that enumerating disks/volumes, which could cause idle disks to spin up.
Answer: You can use DriveInfo.GetDrives Method to get drive info. Here is the sample code from MSDN
DriveInfo[] allDrives = DriveInfo.GetDrives();

foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("  File type: {0}", d.DriveType);
    if (d.IsReady == true)
    {
        Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
        Console.WriteLine("  File system: {0}", d.DriveFormat);
        Console.WriteLine(
            "  Available space to current user:{0, 15} bytes",
            d.AvailableFreeSpace);

        Console.WriteLine(
            "  Total available space:          {0, 15} bytes",
            d.TotalFreeSpace);

        Console.WriteLine(
            "  Total size of drive:            {0, 15} bytes ",
            d.TotalSize);
    }
}

Comment: While this code does list the drives currently installed on the computer, unfortunately it does not answer the question (i.e., how to access drives by GUID), there is no property in `DriveInfo` that relates to the GUID of a drive.


Universal width when using freeform

Question: I used the freeform option on my scrollview and parent view so that I can use the storyboard builder to add labels and textfields. Now I am having trouble getting everything entered horizontally when simulating. It's different on every device.
I enabled the auto-layout option, and size classes. Also I have added the constraint for horizontal alignment on each object inside the scroll controller. The last screenshot is from the simulator. As you can see; the width of the freeform view is too large. I can scroll horizontally and vertically. The first one (horizontal scrolling) should not exist.
Answer: I believe you should deactivate Use Size Classes
Open StoryBoard and select your Controller. On the right side select the first Icon (Show the File Inspector) and then deactivate Use Size Classes
Not realy sure but I would also change Freeform to Fixed Size
Comment: That means I have to chose between iPhone and iPad. But I want to use both devices.
Comment: @user2014780 in your Project Settings (General -> Deployment Info) select Devices : Universal

Universal width when using freeform


Ola, estava a tentar construir o nome de uma TextBox atraves de uma string. TextBox+index

Question:     private void btnGravarNovosValores_Click_1(object sender, EventArgs e)
    {
        string descricao;
        string textBoxX;

        int i = 0;
        foreach (Object texto in lstTabelaProdutosPreco.Items)
        {
            descricao = texto.ToString();
            i++;
            textBoxX = ("textBox" + i.ToString());

            //MessageBox.Show(descricao + " " + textBox);

            TabelaAlterarProdutosCalibresValores tabelaAlterarProdutosCalibresValores = new TabelaAlterarProdutosCalibresValores();
            tabelaAlterarProdutosCalibresValores.idTabelaPrecos = Convert.ToInt32(lstNome.SelectedValue.ToString().Substring(0, 3));
            tabelaAlterarProdutosCalibresValores.idProduto = Convert.ToInt32(descricao.ToString().Substring(0, 4));
            tabelaAlterarProdutosCalibresValores.idCalibre = descricao.ToString().Substring(8, 5);
            tabelaAlterarProdutosCalibresValores.precoVenda = double.Parse(textBoxX.ToString().Trim());
            if (tabelaAlterarProdutosCalibresValores.UpDateDefault())
            {
                MessageBox.Show(lstNome.SelectedValue.ToString().Substring(0, 3) + descricao.ToString().Substring(0, 4) + descricao.ToString().Substring(8, 5) + textBoxX);
            }
        }
    }

Comment: Não entendi. Poderia discorrer um pouco mais no corpo da pergunta? Só o título e esse código não me disseram muita coisa
Comment: Consigo construir os nomes das TextBox através de um ciclo textbox +i = textbox1, mas nao consigo usa-la como nome da textbox
   tabelaAlterarProdutosCalibresValores.precoVenda = double.Parse(textBoxX.ToString().Trim());
Comment: "construir os nomes" das textbox ?!?!  tente ser mais claro jovem
Comment: string descricao;
            string textBoxX;

            int i = 0;
            foreach (Object texto in lstTabelaProdutosPreco.Items)
            {
                descricao = texto.ToString();
                i++;
                textBoxX = ("textBox" + i.ToString());
            }
Comment: Você quer acessar um textbox que está no seu form, informando o nome dele em uma string. Isso ?
Comment: Bem vindo ao StackOverflow, para começar faça um [tour] e depois veja [ask] e [answer]. Sempre informe [um exemplo Mínimo, Completo e Verificável](https://pt.meta.stackoverflow.com/questions/1186/como-criar-um-exemplo-m%C3%ADnimo-completo-e-verific%C3%A1vel)
Comment: atraves do ciclo foreach consigo a cada volta obter uma  descrição e construir um nome de textbox. quando vou utilizar o nome da textbox
Comment: você só está fazendo a pergunta errada jovem, O que você quer é acessar os TextBox na sua tela de forma dinâmica, dentro do loop. Ou seja, pela string `"textBox"+i.ToString()` voce quer ter acesso ao controle: `string texto =  textBox1.Text;`
Comment: se eu tentar usar o nome criado daigual a textbox (textboxX) em uma messagebox aparece o nome correto, se tentar utilizar o mesmo TextboxX para inserir o conteudo da textbox num banco, da erro "cadeia de carateres de entradacom formato incorreto"
Comment: é isso ,  como faço para que a string seja reconhecida como textbox
Comment: peco desculpa é a 1 vez que estou a utilizar este site e nao sei como fazer as perguntas
Comment: sem problemas, veja se minha resposta ajuda e acesse o tour indicado pelo Everson
Answer: Você quer acessar vários TextBox que existem no seu Form, de forma dinâmica, dentro do loop.
Para isso você vai utilizar o Método Find:
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find(v=vs.110).aspx
Exemplo:
for (int i =0; i< 10; i++)
{

        Control[] controls = this.Controls.Find("textBox" + i.ToString(), true);
        if (controls.Length > 0)
        {
            TextBox txtBox = controls[0] as TextBox;
            if (txtBox != null)
            {
                tabelaAlterarProdutosCalibresValores.precoVenda = txtBox.Text;
            }
        }
        else
        {
          //não achou o textbox
        }

 }

Comment: Resultou Obrigadao
Comment: Não se esqueça de marcar como resposta @user9426886


c++ User input validation in sorted array

Question: Hello i have a assinment that im making a weater program where we ask the user to enter info
first enter how many citys to use
then enter city name and degrees
then i will print out the list in order starting with the coldest city
and last i need to add a search funkar to search by degrees to find a location with that degrees
this one i havent started with
but my MAIN problem is that i need to validate that the user input is between -60 and 60 when enter the city and degrees... i just dont get it to work with anything... can someone please help out?`
cout<<"Enter Name of City and degrees \n\n";

for(i=0;i<n;i++){
    cout<<"---------\n";
    cin>>s_array[i].name;
    cin>>s_array[i].degrees;

this is the code where user put in city and degree EX Rio 50
i just dont know how to validate it to be between -60 and 60`
Comment: `if (degree < -60 || degrees > 60) { /* TODO: Error */ }`?
Comment: Concentrate on validating just one number. Then wrap that in a loop that terminates when the input is valid. Then add reading the city name before that loop. Then wrap the whole thing in a loop.
Comment: sorry i dont get it....
Answer: First of all, you should create a class. I understand from your code you must use class. If you don't have to it is easier than this. Then you should create an object.
Basic logic below here. You should create a class well.
 class Weather //create class

 Weather city // create object

 cout<<"Please enter a city name:"<<endl;

 cin>>city.name;

 cout<<"Please enter a city degree:"<<endl;

 cin>>city.degrees;

Comment: Fair enough, then I misunderstood.
Comment: Why do you say a class is necessary for this? Too much boilerplate.
Comment: @SimonC i did not say class necessary. He used class in his example so i think like it. If we dont use class it is easier.
Answer: What you're looking for, is simple data validation.
Assuming you have a struct City:
// used to hold the data
struct City {
     string name;
     double degrees;
};

and in your main(), you have initialised an array of these structs:
bool temperatureValid(const City);

int main() {
    const int32_t totalCities = 12;
    City cities[totalCities];
    for (int32_t i = 0; i < totalCities; i++) {
        // add data to structs
        cout << "Enter city name: ";
        cin >> cities[i].name; // you might want to validate this, too
        cout << "Enter temperature: ";
        cin >> cities[i].degrees;
        cout << cities[i].name << " has a temperature of " << cities[i].degrees << "°" << endl;

        if (temperatureValid(cities[i])) {
            // cool... or not
        } else {
            cerr << "Invalid temperature range!" << endl;
            --i; // make sure we can do this one again
            continue;
        }
    }
    return 0;
}

bool temperatureValid(const City city) {
    return city.degrees >= -60 && city.degrees <= 60;
}


Sphere with three Möbius strips glued and sphere with a handle and a Möbius strip glued

Question: I am reading the first chapter from Topology by Armstrong. There, after stating the classification theorem for closed surfaces, he has mentioned an example that a sphere with one handle and one Möbius strip glued is homeomorphic to a sphere with three Möbius strips glued.
I am not able to see this. I know that to prove the above is to say that a torus with a Möbius strip glued is homeomorphic to a Klein bottle with a Möbius strip glued. How do I prove this? Or how do I at least convince myself that this is the case, in case I don't yet have the tools to prove it.
Comment: Are you familiar with the Euler characteristic of a surface and how it changes when taking connected sums?
Comment: No I dont know much about it. Is there not a direct approach?
Comment: Polygonal models of surfaces should be enough to prove this. The torus is a square with opposite sides identified in natural way. The Moebius band is a square with a pair of opposite sides identified in an unnatural way. Connected sums can be performed by chopping off a vertex on each diagram (leaving a short edge in its place) and identifing these new edges. Then some cutting and pasting may be necessary to bring the two connected sums to the same polygonal form.
Answer: Each compact surface (except the sphere) has a standard fundamental polygon representation, and each surface belongs to one of the two categories (non-orientable) $mP^2$ or (orientable) $nT^2$. For example, a torus ($T^2$) has a standard representation $aba^{-1}b^{-1}$, see the following figure:

To construct the connected sum between two surfaces, we cut off a corner from each fundamental polygon, then glue the two polygons along the cut off edge. This is a process of concatenating (or inserting) the standard representation of one surface to another. For example, if you glue two torus handles you get a new representation like:
$$aba^{-1}b^{-1}cdc^{-1}d^{-1}$$
This is the standard representation of a $2T^2$, that is, a genus $2$ torus (a torus with two holes).
Back to your question, a Mobius band is a (real) projective space with a disc cut. It has a triangle representation:

Glue the third edge of this triangle with the torus handle, we get a new representation:
$$abcca^{-1}b^{-1}$$
See the following figure:

This representation has an edge pair $cc$ indicating that it belongs to the non-orientable category, and it has a single vertex class thus it has $6$ edges in its standard representation, implying that it is a $3P^2$. That is we've shown that the connected sum between $T^2$ and $P^2$ is
$$T^2\#P^2=3P^2$$
Answer: See the proof of Lemma 7.1 in Massey's "A Basic Course in Algebraic Topology" (1991), pp 23-25.
Comment: Could you summarize the basic idea of the proof here? It would be helpful for people without immediate access to the textbook.
Answer: Mobius strip allows access into the inside surface of the sphere. So slide one end of the g-handle into the strip and and it will then become attached to the sphere from the inside surface. That effectively turns the g-handle into a klien bottle and every such bottle is made up of two mobius strips.
So there, the three mobius strips you mentioned.


Highcharts conflict with extjs

Question: I am trying to render 3 highcharts inside the extjs tab using prototype adapter. I am rendering multiple bar charts in a single page all having click event on the bars. All charts that render below the first bar charts do not get the click event that i have registered for them. The first chart on the page has all the click event. But all the charts below are not click-able even though i have added click events for them. When I render the same page outside an extjs component all the charts and all the clicks work fine. I am guessing there is conflict with highcharts and extjs.
Was able to replicate the issue in jsfilddle http://jsfiddle.net/kNPeg/4/
The following is the javascript code where I am creating the extjs component in which the same highchart is rendered 3 times but the bottom to charts have bars that are not clickable.
<code>            var centerTabPanel = new Ext.TabPanel({
                       region:'center',
                       margins: '0 10 0 0',
                       id:'center-panel',
                       activeTab:0,
                       bodyStyle:'padding: 8 5 5 8;',
                       autoScroll: true,
               items:[  {
                                        contentEl: 'db_snapshots',
                                        title: "Charts",
                                        autoScroll: true,
                                        bodyStyle: 'background:#fffff0;padding: 8 5 5 8;'
                                    }
                        ]
                    });

                    var viewport = new Ext.Viewport({
                        layout:'border',
                                    loadMask : {msg:"testLoading..."},
                                    monitorResize : true,
                        items:[

                            centerTabPanel
                                    ]
                    });
                            viewport.doLayout();

            var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: "container",
                        defaultSeriesType: 'column',
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false

                    },
                        title: {
                            text: null
                        },
                        xAxis: {
                            categories: ['First','Second','Third']
                        },

                        series: [{
                            name:"Values",
                            data: [133, 156, 947]
                        }],
                        plotOptions: {
                            series: {
                                animation: false,
                                cursor: 'text',
                                point: {
                                    events: {
                                        click: function() {
                                            alert("hello");
                                        }
                                    }
                                },
                                marker: {
                                    lineWidth: 1
                                }
                            },
                            line: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                }
                            },
                            bar: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'String',
                                dataLabels: {
                                    enabled: false
                                }
                            }
                        }

                });

                 var chart2 = new Highcharts.Chart({
                    chart: {
                        renderTo: "container2",
                        defaultSeriesType: 'column',
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false

                    },
                        title: {
                            text: null
                        },
                        xAxis: {
                            categories: ['First','Second','Third']
                        },

                        series: [{
                            name:"Values",
                            data: [133, 156, 947]
                        }],
                        plotOptions: {
                            series: {
                                animation: false,
                                cursor: 'text',
                                point: {
                                    events: {
                                        click: function() {
                                            alert("hello");
                                        }
                                    }
                                },
                                marker: {
                                    lineWidth: 1
                                }
                            },
                            line: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                }
                            },
                            bar: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'String',
                                dataLabels: {
                                    enabled: false
                                }
                            }
                        }

                });

                var chart3 = new Highcharts.Chart({
                    chart: {
                        renderTo: "container3",
                        defaultSeriesType: 'column',
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false

                    },
                        title: {
                            text: null
                        },
                        xAxis: {
                            categories: ['First','Second','Third']
                        },

                        series: [{
                            name:"Values",
                            data: [133, 156, 947]
                        }],
                        plotOptions: {
                            series: {
                                animation: false,
                                cursor: 'text',
                                point: {
                                    events: {
                                        click: function() {
                                            alert("hello");
                                        }
                                    }
                                },
                                marker: {
                                    lineWidth: 1
                                }
                            },
                            line: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                }
                            },
                            bar: {
                                size:'100%',
                                allowPointSelect: true,
                                cursor: 'String',
                                dataLabels: {
                                    enabled: false
                                }
                            }
                        }

                });
</code>
Answer: Instead of setting point click, you can use workaround, and iterate on each series element (in each chart) and add action to SVG element by "on" trigger.
http://jsfiddle.net/kNPeg/5/
<code> for (var i = 0; i < chart3.series[0].data.length; i++) {
            chart3.series[0].data[i].graphic.on('click', function () {
                alert('aaa3');
            });
        }
</code>
Comment: Thanks for the fast reply.

Highcharts conflict with extjs


Java jdk - Class path, java home, PATH variables set but javac command does not work

Question: java -version :
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

javac :
'javac' is not recognized as an internal or external command,
operable program or batch file.

echo %path% : (Note: C:\Program Files\Java\jdk1.8.0_131\bin)
C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\MATLAB\R2012a\runtime\win64;C:\Program Files\MATLAB\R2012a\bin;C:\xampp\php;C:\ProgramData\ComposerSetup\bin; C:\Program Files\Java\jdk1.8.0_131\bin; C:\Program Files\Git\cmd;C:\Users\Aditi\AppData\Local\Programs\Python\Python35\Scripts\;C:\Users\Aditi\AppData\Local\Programs\Python\Python35\;C:\Users\Aditi\AppData\Roaming\Composer\vendor\bin; C:\Program Files\Java\jdk1.8.0_131\bin;

JAVA HOME is set to:
C:\Program Files\Java\jdk1.8.0_131\

Some forum suggested to set "classpath" as :
C:\Program Files\Java\jdk1.8.0_131\src.zip

Now, I have restarted my system after making each of these changes but still no luck. All the IDE's requiring Java seem to work fine but javac doesn't work in my command line.
Please help if you now a way around to get it working.
Thanks
Comment: Is there a javac.exe in C:\Program Files\Java\jdk1.8.0_131\bin?
Comment: There is a wrong space character in the parameter's value before the path "C:\Users\Aditi\AppData\Roaming\Composer\vendor\bin; C:\Program Files\Java\jdk1.8.0_131\bin". Remove it.
Comment: Yes, there is a javac.exe
Comment: remove the duplicate C:\Program Files\Java\jdk1.8.0_131\bin in your path and use the JAVA HOME: %JAVA_HOME%\bin;

btw if you place yourself in the directory C:\Program Files\Java\jdk1.8.0_131\bin and then run javac does it works?
Answer: Your %path% variable has two classpaths(C:\Program Files\Java\jdk1.8.0_131\bin). Remove both paths, Add env variable JAVA_HOME, set it to "C:\Program Files\Java\jdk1.8.0_131" then add "JAVA_HOME\bin" in path variable.
Restart your machine.
For troubleshooting use command "where javac" to see if your env variable set properly.
Yes and there should not be any space between to paths, only ";" is allowed to separate paths.
More details:
your "java -version" is working as expected because  SYM link for java.exe is there in the directory "C:\ProgramData\Oracle\Java\javapath;"(which is first path in your path variable)
C:\ProgramData\Oracle\Java\javapath>dir
 Volume in drive C has no label.
 Volume Serial Number is <.....>

 Directory of C:\ProgramData\Oracle\Java\javapath

09/21/2016  06:02 PM    <DIR>          .
09/21/2016  06:02 PM    <DIR>          ..
09/21/2016  06:02 PM    <SYMLINK>      java.exe [C:\Program Files\Java\jre1.8.0_91\bin\java.exe]
09/21/2016  06:02 PM    <SYMLINK>      javaw.exe [C:\Program Files\Java\jre1.8.0_91\bin\javaw.exe]
09/21/2016  06:02 PM    <SYMLINK>      javaws.exe [C:\Program Files\Java\jre1.8.0_91\bin\javaws.exe]
               3 File(s)              0 bytes
               2 Dir(s)  18,429,718,528 bytes free

C:\ProgramData\Oracle\Java\javapath>

Comment: Thank you so much. Turns out the space character was the problem.
Also, I have no idea why echo %path% gives out those many paths, with the jdk path twice. In the environmental variables tab, the path only has about 5 paths.


Loan Repayments and Yield Rates

Question: Jose loans Martin $12000$. Martin repays the loan by paying $5000$ at the end of two years and $10000$ at the end of $4$ years. The money received at time $t=2$ is immediately reinvested at an annual effective interest rate of $2.4$%. Find Martin's rate of interest and Jose's annual yield rate.
Answer: Well assuming the amount is compounded once every two years, then we can figure it out.  The first payment will go partly towards interest and partly towards the principle (usually the interest is paid first).  So let's assume a rate of $x$ compounded every two years.  The interest due would then be $A_0x$ so the final balance after the initial payment of $p_0$ would be:
$$
A_2 = A_0(1 + x) - p_0
$$
Note that we know $A_0$ and $p_0$ here (but not $A_2$).  Next we make another payment (two years later) which just so happens to be twice the initial payment meaning the new balance would be:
\begin{align}
A_4 =& A_2(1 + x) - 2p_0\\
=& (A_0(1 + x) - p_0)(1 + x) - 2p_0 \\
=& A_0(1 + x) - p_0 + A_0(1 + x)x - p_0x - 2p_0 \\
=& A_0(1 + x + x + x^2) - p_0(1 + x + 2) \\
=& A_0(1 + 2x + x^2) - p_0(3 + x) \\
=& A_0x^2 + x(2A_0 - p_0) + (A_0 - 3p_0)
\end{align}
Since the loan is payed off after 4 years, $A_4 = 0$ (there is no remaining balance).  So this is a quadratic in the interest rate $x$ which can be solved using the quadratic equation:
$$
x = \frac{p_0 - 2A_0 \pm \sqrt{(2A_0 - p_0)^2 - 4A_0(A_0 - 3p_0)}}{2A_0}
$$
We know $A_0 = 12000$ and $p_0 = 5000$:
$$
p_0 - 2A_0 = 5000 - 24000 = -19000 \\
A_0 - 3p_0 = 12000 - 15000 = -3000 \\
4A_0(A_0 - 3p_0) = -48000 * 3000 =  -144 * 1000^2 \\
(2A_0 - p_0)^2 = 361 * 1000^2 \\
(2A_0 - p_0)^2 - 4A_0(A_0 - 3p_0) = (361 + 144)*1000^2 = 505*1000^2 \\
\sqrt{(2A_0 - p_0)^2 - 4A_0(A_0 - 3p_0)} \approx 22472 \\
 \frac{p_0 - 2A_0 + \sqrt{(2A_0 - p_0)^2 - 4A_0(A_0 - 3p_0)}}{2A_0} \approx \frac{-1900 + 22472}{24000} \approx 0.1447
$$
So Martin's interest rate is approximately $14.47\%$ per two years, which would mean an annual interest rate of half of that: $\approx 7.23\%$.
We can check to make sure that's right:
$$
A_2 \approx 12000 \cdot 1.1447 - 5000 = $8736.4 \\
A_4 \approx 8736.4 \cdot 1.1447 - 10000 = $0.55708
$$
Notice that there is $55$ cents left out of a \$12,000 loan (because the interest rate of $14.47\%$ isn't exact).
Answer: All interest rates are annual.
The borrower's rate:

The residual debt after paying 5000 is $12000(1+b)^2-5000$
The residual debt after paying the remaining 10000 is zero:

$[12000(1+b)^2-5000](1+b)^2=10000$
this is a quadratic in $x=(1+b)^2$:
$12x^2-5x-10=0, x=\frac{5+\sqrt{5^2-4\cdot12\cdot(-10)}}{2\cdot12}=\frac{5}{24}(1+\sqrt{21})$
from here we deduce the borrower's rate: $b=\sqrt{\frac{5}{24}(1+\sqrt{21})}-1\approx 7\%$
The lender's return rate:
$\left(\frac{5000(1+2.4\%)^2+10000}{12000}\right)^{\frac{1}{4}}-1\approx 6\%$

Loan Repayments and Yield Rates


Integer solution of $x^3 - x + 9 = 5 y^2$

Question: Prove/disprove that $x^3 - x + 9 = 5 y^2 $ has integer solution. i.e) There doesn't exist $x,y$ in integers satisfying above equation.
I tried using congruence and get if solution exist then $x$ should be congruent to $2\pmod{5}$. But after that, I tried something but I haven't get any conclusion. Please give me a hint if the statement is true.
Comment: It does have a rational solution, $x=\frac {4}{5},y=\frac{33}{25}$.
Comment: Cloud JR, @S.Dolan's discovery is very important. It implies that modulo any integer not a multiple of five there are integer solutions (because $5$ and hence also $25$ have a modular inverse). This strongly suggests that we may need tools other than modular arithmetic to settle this.
Comment: Is your question actually $x^2-x+9=5y^2$?
Comment: No square of an integer can be $2 \pmod 5$. Is this what you mean?
Comment: @metamorphy thanks for pointing out !
Comment: @S.Dolan thanks for remarks But question is about integers
Comment: Which brings me to request for the source of the quesion. Is there a reason to believe that tools lesser than those developed to find integer points on elliptic curves are sufficient here?
Comment: @Jyrki Lahtonen.@S.Dolan I haven't know this before , my apologies.
Comment: @jyrki lahtonten , It was in exercise of notes sum of two square. But I have no idea what sum of square have anything to do with this. Btw, this is not my homework as the due date ends a month before. I haven't solve it. So now I am trying but i think It won't work , that's why I ask here
Comment: No it's x^3.  Not squared, I checked it .
Comment: Can you attach the notes "sum of two squares" if it is a PDF? Else, take a photo of the problem, and of the pages coresponding to the chapter.
Comment: https://drive.google.com/a/iisertvm.ac.in/file/d/13k5w7mboGYxpY4QgKxWmMq1hZ_MPPuPO/view?usp=drivesdk
Answer: The substitution $U=5x, V=25y$ turns this equation into that of an elliptic curve with the short Weierstrass form
$$
U^3-25U+1125=V^2.
$$
According to its LMFDB entry the integer points on this elliptic curve are $(U,V)=(4,\pm33)$
There are no solutions with $V$ a multiple of $25$, so the original equation has no integer solutions.
Comment: Bailing out with a table look-up. I am not knowledgeable enough to tell whether an elementary argument giving all the integer points of this curve exists.
Comment: Check out [this thread](https://math.stackexchange.com/q/32847/11619) for more information and sources.
Answer: More of a comment, but there are too many already. Having read all the comments, it seems to me a strong possibility that the equation whoever produced the pdf problem sheet intended to set was $$x^2-x+9=5y^2$$
Put another way, the OP insists his Q has $x^3$, but I strongly suspect the Q whoever set the problem wanted him to solve had $x^2$, so it might be worth giving a quick answer to that. @JyrkiLahtonen has already given an excellent answer to the Q as the OP has given it. I hope it has piqued his curiosity for delights to come ...
So completing the square: $$(x-1/2)^2+35/4=5y^2$$ Multiplying by 4 and rearranging: $$5(2y)^2-(2x-1)^2=35$$
Now $2x-1$ must be divisible by 5, so writing it as $5z$ and $2y$ as $w$ we get $$w^2-5z^2=7$$ which is a standard Pell equation. They are discussed endlessly on this site, and it is not hard to show that it has no solution in integers, and a fortiori no solution with $w$ even and $z$ odd).


Eigenvalues of $\sum_i A_i P_i$ with $(A_i)_{jk}=\delta_{ij}\delta_{ik}$ and $P_i$ orthogonal projections

Question: Assume $$C=\sum_{i=1}^nA_iP_i$$ where each $P_i$ is an $n\times n$ orthogonal projection matrix ($P_i=P_i^\top$ and $P_i=P^2_i$) and $A_i$ is an $n\times n$ matrix of zero elements except the $(i,i)$-th element equal to one.
Can I say something about the eigenvalues of $C$?
Answer: The matrix $A_iP_i$, is a matrix containing a lot of zeros, and its $i$-th row is equal to the $i$-th row of $P_i$. That is, the resulting matrix has rows all with Euclidean norm equal to $1$. This implies $\|C\|_2 \le \sqrt n$:
$$
\|Cx\|_2^2 =\sum_i (c_i^Tx)^2\le \sum_i \|c_i\|^2 \|x\|^2 = n \|x\|^2,
$$
where $c_i$ is the $i$-th row of $C$.
This bound is realized if all rows of $C$ are the same up to factors with absolute value $1$.
This shows that all eigenvalues of $C$ are in the circle $\{z\in \mathbb C:\ |z|\le \sqrt n\}$.
This bound is sharp as the matrix $C=(c_{ij})$ with $c_{ij}=\frac1{\sqrt n}$ shows.
Using Gershgorin theorem, one can prove inclusions for eigenvalues.
The radius of the Gershgorin circle $i$ can be estimated by
$$
\sum_{j\ne i} |c_{ij}| \le \sqrt{n-1} \left(\sum_{j\ne i} |c_{ij}|^2 \right)^{1/2} = \sqrt{(n-1)(1-|c_{ii}|^2)}.
$$
Then the eigenvalues of $C$ are inside the circles with center $c_{ii}$ and radius as above. If more is known about the entries of $C$, the bound can be improved.
Comment: Thank you for your response. I'm confused in the notations. In the first part of the answer: what did you mean by the matrix $A$. Furthermore, I did not  understand how the bound on the radius of the Gershgorin circle is established.
Comment: @user293017 I confused $A$ and $C$. Gershgorin bound: first inequality is $l^1$-norm against $l^2$-norm, second equality uses that $\sum_{j}|c_{ij}|^2=1$.
Comment: You are right! Sorry for the confusion, I thought $A_i$ had a row of ones.


Adjust Shiny to show correct graphic

Question: I have a function where it generates a scatter plot according to the selected date. As you can see I have three days 01/08, 08/08 and 13/08. That is, there are three different scatter plots. However, on shiny I can only show one, which is from the 01/08.
Could you help me tweak the code so that when it picks one of those three days on the calendar, it shows the correct scatterplot on shiny?
This resolved question may help: Link Calendar with Scatter Plot in Shiny
Executable code below:
library(shiny)
library(shinythemes)
library(dplyr)
library(ggplot2)
library(tidyr)
library(lubridate)

function.cl<-function(){
  df <- structure(
    list(date = c("2021-08-01","2021-08-01","2021-08-01","2021-08-01","2021-08-01",
                  "2021-08-08","2021-08-08","2021-08-08","2021-08-08","2021-08-08","2021-08-08",
                  "2021-08-13","2021-08-13","2021-08-13","2021-08-13","2021-08-13"),
         Week= c("Sunday","Sunday","Sunday","Sunday","Sunday","Sunday","Sunday","Sunday",
                 "Sunday","Sunday","Sunday","Friday","Friday","Friday","Friday","Friday"),
         D1 = c(0,1,0,0,5,0,1,0,0,9,4,3,4,5,6,7), DR01 = c(2,1,0,0,3,0,1,0,1,7,2,3,4,6,7,8),
         DR02 = c(2,0,0,0,4,2,1,0,1,4,2,3,4,5,6,7),  DR03 = c(2,0,0,2,6,2,0,0,1,5,2,2,4,5,7,5),
         DR04 = c(2,0,0,5,6,2,0,0,3,7,2,3,4,5,6,4),  DR05 = c(2,0,0,5,6,2,0,0,7,7,2,3,4,5,6,7),
         DR06 = c(2,0,0,5,7,2,0,0,7,7,1,3,5,6,7,8),  DR07 = c(2,0,0,6,9,2,0,0,7,8,1,3,5,6,4,3)),
    class = "data.frame", row.names = c(NA, -16L))

  scatter_date <- function(dt, dta = df) {
    dta %>%
      mutate(date = ymd(date)) %>%
      filter(date == ymd(dt)) %>%
      summarize(across(starts_with("DR"), sum)) %>%
      pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
      mutate(name = as.numeric(name)) %>%
      plot(xlab = "Days", ylab = "Types", xlim = c(0, 7))
  }
    Plot1<-scatter_date("2021-08-01")

    return(list(
      "Plot1" = Plot1,
      date = df$date
    ))
}

ui <- fluidPage(

  ui <- shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),

                          tabPanel("",
                                   sidebarLayout(
                                     sidebarPanel(

                                       uiOutput("date"),
                                       br(),
                                     ),

                                     mainPanel(
                                       tabsetPanel(
                                         tabPanel("",plotOutput("Graph",width = "95%", height = "600"))),
                                     ))
                          )))

server <- function(input, output,session) {
  data <- reactive(function.cl())

  output$date <- renderUI({
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date)), origin = "1970-01-01")

    dateInput(input = "date",
              label = "Select Date",
              min = min(data()$date),
              max = max(data()$date),
              value = max(data()$date),
              format = "dd-mm-yyyy",
              datesdisabled = disabled)
  })

  output$Graph <- renderPlot({
    function.cl()[["Plot1"]]

  })

}

shinyApp(ui = ui, server = server)

Answer: Try this
library(shiny)
library(shinythemes)
library(dplyr)
library(ggplot2)
library(tidyr)
library(lubridate)

function.cl<-function(dt){
  df <- structure(
    list(date = c("2021-08-01","2021-08-01","2021-08-01","2021-08-01","2021-08-01",
                  "2021-08-08","2021-08-08","2021-08-08","2021-08-08","2021-08-08","2021-08-08",
                  "2021-08-13","2021-08-13","2021-08-13","2021-08-13","2021-08-13"),
         Week= c("Sunday","Sunday","Sunday","Sunday","Sunday","Sunday","Sunday","Sunday",
                 "Sunday","Sunday","Sunday","Friday","Friday","Friday","Friday","Friday"),
         D1 = c(0,1,0,0,5,0,1,0,0,9,4,3,4,5,6,7), DR01 = c(2,1,0,0,3,0,1,0,1,7,2,3,4,6,7,8),
         DR02 = c(2,0,0,0,4,2,1,0,1,4,2,3,4,5,6,7),  DR03 = c(2,0,0,2,6,2,0,0,1,5,2,2,4,5,7,5),
         DR04 = c(2,0,0,5,6,2,0,0,3,7,2,3,4,5,6,4),  DR05 = c(2,0,0,5,6,2,0,0,7,7,2,3,4,5,6,7),
         DR06 = c(2,0,0,5,7,2,0,0,7,7,1,3,5,6,7,8),  DR07 = c(2,0,0,6,9,2,0,0,7,8,1,3,5,6,4,3)),
    class = "data.frame", row.names = c(NA, -16L))

  scatter_date <- function(dt, dta = df) {
    dta %>%
      mutate(date = ymd(date)) %>%
      filter(date == ymd(dt)) %>%
      summarize(across(starts_with("DR"), sum)) %>%
      pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
      mutate(name = as.numeric(name)) %>%
      plot(xlab = "Days", ylab = "Types", xlim = c(0, 7))
  }
  Plot1<-scatter_date(dt)

  return(list(
    "Plot1" = Plot1,
    date = df$date
  ))
}

ui <- fluidPage(

  ui <- shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),

                          tabPanel("",
                                   sidebarLayout(
                                     sidebarPanel(

                                       uiOutput("date"),
                                       br(),
                                     ),

                                     mainPanel(
                                       tabsetPanel(
                                         tabPanel("",plotOutput("Graph",width = "95%", height = "600"))),
                                     ))
                          )))

server <- function(input, output,session) {
  data <- reactive(function.cl("2021-08-01"))

  output$date <- renderUI({
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date)), origin = "1970-01-01")

    dateInput(input = "date",
              label = "Select Date",
              min = min(data()$date),
              max = max(data()$date),
              value = max(data()$date),
              format = "dd-mm-yyyy",
              datesdisabled = disabled)
  })

  output$Graph <- renderPlot({
    req(input$date)
    function.cl(input$date)[["Plot1"]]

  })

}

shinyApp(ui = ui, server = server)

Comment: Thank you YKS! A question: There my base is with the format
yyyy-mm-dd but if it happens to be in the dd-mm-yyyy format, what do you need to adjust? I tested it in the last format, but it gave an error.
Comment: You can try `data$date <- as.Date(data$date,format= "%d/%m/%y")`.  Please look into different date formats.
Comment: Thanks for reply! But where did you think to insert this code? on the function or on the server?

Adjust Shiny to show correct graphic


Mongodb $unwind array of arrays in an array

Question: MongoDB driver: 4.2.6,
Mongoose: ^5.9.6
I want to unwind keyword properties:
[
 {
    "_id": null,
    "totalNumberOfData": 4,
    "data": [
        {
            "numberOfData": 2,
            "sentiment": "Good",
            "keyword": [
                "A",
                "B",
                "C"
            ]
        }
    ]
  }
]

I tried this, but it didn't work.
{
    $unwind: {
      path: "$data.keyword",
      preserveNullAndEmptyArrays: true,
    },
  },

How to unwind keyword array?
Answer: In general input to $unwind stage should be an array, Since you're doing data.keyword unwind is expected a field named data as an object with nested field named keyword as an array like :{data : keyword : []} & it's not able to find it that way which results in an empty array as output of aggregation. As data is also an array, you need to unwind it first, So double unwind is needed in your case :
db.collection.aggregate([
  {
    $unwind: {
      path: "$data",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $unwind: {
      path: "$data.keyword",
      preserveNullAndEmptyArrays: true
    }
  }
])

Test : mongoplayground


Ruby doesn't raise correct exception

Question: I'm trying to raise 2 exceptions when one of my variables is bigger than 13 or less than 1
also I want to raise exception if the type of my card is not one of the defined one.
this is my code :
require "../lib/suit"
class Card
    attr_reader :suit,:number
 def initialize(suit,number)
     raise "CardNumberNotValid" if 1>number>13
     raise "SuitNotValid" if suit!=Suit::CLUB or suit!=Suit::HEART or suit!=Suit::DIAMOND or suit!=Suit::SPADE
     @suit=suit
     @number=number
 end
end

and this is my test:
require "rspec"
require "../lib/suit"
require "../lib/card"

describe Card do

  it "should check if card number is between 1 and 13" do
    expect{Card.new(Suit::CLUB,14)}.to raise_error("CardNumberNotValid")
  end
end

The result is below :

Failures:
1) Card should check if card number is between 1 and 13
       Failure/Error: expect{Card.new(Suit::CLUB,14)}.to raise_error("CardNumberNotValid")
         expected Exception with "CardNumberNotValid", got #' for false:FalseClass>
       # ./card_spec.rb:8
Finished in 0.00064 seconds 1 example, 1 failure
Failed examples:
rspec ./card_spec.rb:7 # Card should check if card number is between 1
  and 13

can you please help ?
Answer: 1>number>13

Does not work in Ruby. Use something like:
number.between?(1, 13)

Comment: Thanks , I didn't notice that :) I'm new to Ruby
Answer: If you raise an error in ruby without a type:
raise "My pink pig"

ruby is going to raise a RuntimeError with "My pink pig" as a message (assuming that you aren't already processing an error, in which case the new error will have the same type).
You should probably be expecting your error differently:
expect{Card.new(Suit::CLUB,14)}.to raise_error(RuntimeError, "CardNumberNotValid")

Comment: Thanks but it is not working same error got #' for false:FalseClass>

Ruby doesn't raise correct exception


Qual seria a forma correta de verificar se um valor existe na tabela em Lua?

Question: if not name in Namez do
    table.insert(Namez,name)
end

Qual seria a forma correta de verificar se um nome não se encontra na tabela?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Não tem nada pronto, você pode criar uma função que faça isto, assim:
local function contains(tabela, valor)
    for i = 1, #tabela do
        if tabela[i] == valor then
            return true
        end
    end
    return false
end

local names = {"joão", "maria", "josé"}
if not contains(names, "carlos") then
    table.insert(names, "carlos")
end
for i = 1, #names do
    print(names[i])
end

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Se você quiser evitar ter que fazer uma busca linear pelo valor, você pode usar os nomes como chave da tabela
if not Namez[name] then
    Namez[name] = true
end

Você pode iterar pelas chaves da tabela com a função pairs:
for name, _ in pairs(Namez) then
    -- ...
end

Vale notar que a função pairs não necessariamente percorre as coisas em ordem. Se a ordem dos nomes for importante, você pode manter uma lista com table.insert simultaneamente a este mapeamento (pode até reaproveitar a mesma tabela para os dois, se os nomes forem todos strings).


Array salvando dados no banco com um campo escrito array

Question: Eu tenho dos campos dois quais salvo no banco de dados (no caso seria como comentário do pedido no magento, mas isso não importa muito). Esses campos estão sendo salvos corretamente, porém com um problema, ele salva um dos campos escritos array. Os campos de ponto de referência e tipo de endereços são salvos corretamente.
Código HTML dos campos:

  <?php echo $this->__('Referência: ') ?>

      <input style="width: 100% !important;" class="input-text" id="comments_1" name="comments[]" title="<?php echo $this->__('Pontos de Referência') ?>" />

    Tipo de Endereço:

       <select id="comments_2" name="comments[]" title="<?php echo $this->__('Tipo de Endereço') ?>" class="onestep">
          <option value="">Selecione</option>
          <option value="residencial">Residencial</option>
          <option value="comercial">Comercial</option>
       </select>

Código no Model do módulo, que percorre o Array e salva os campos:
if (!empty($oscOrderData['comments'])) {

    $order = $observer->getEvent()->getOrder();
    /* @var $order Mage_Sales_Model_Order */

    // Force array type
    if(!is_array($oscOrderData['comments']))
        $oscOrderData['comments'] = array($oscOrderData['comments']);

    foreach($oscOrderData['comments'] as $comment) {
        $order->addStatusHistoryComment($comment);
    }
    $order->save();
}

Comment: Qual campo está salvando errado?
Comment: @ThiagoBarcala O que está acontecendo é que ele está salvando um campo a mais. Os dois campos são salvos corretamente, porém, ele salva um campo a mais escrito `array`.
Comment: Pode ser que tenha algum outro input no form com esse mesmo nome (comments[]) e tem valor "array". Verifique no navegador quais os valores enviados ao submeter o form. Se vc usa Chrome, aperte F12, clique na aba network, e submite o form. Vc vai poder ver o request e todos os valores enviados ao servidor.
Comment: Você pode procurar por comment[] na aba elements para ver se tem mais inputs do que deveria.
Comment: Qual é a estrutura do banco de dados e como está ficando esse registro errado?
Answer: O problema não estava em ter mais de um input com o name="comments[]", mas estava na duplicação do código no arquivo Observer.php do módulo, ou seja, existiam dois códigos iguais e por isso estava salvando um campo a mais escrito Array. Retirei um dos códigos e o problema foi solucionado.


Difference between two measures

Question: A numerical value was generated for each of 65 samples on machine A at time T, and then on machine B and time S. I tested for a difference between the two runs using R as follows:
<code>t.test(d$Run1, d$Run2, paired=T)
</code>
This showed a p-value of 0.26, which indicates that there is no difference between the runs, or that there is no difference between each pair of values? Is this the correct test to use?
Answer: This post (Which test should be used to compare two mean differences?) may be of interest to you (I guess my reply should've been in a comment rather than an answer, but I am new here and I do not have enough reputation points to add a comment)

Difference between two measures


Translate untranslated strings

Question: I downloaded and enabled translations for my Drupal core and modules using these Drush commands:
drush dl l10n_update && drush en -y $_
drush language-add lt && drush language-enable $_
drush l10n-update-refresh
drush l10n-update

I got almost everything translated, and in "Administration » Configuration » Regional and language" I see that I have almost 60% of translations to Lithuanian.
However, not everything is translated. For example, harmony forum module thread reply;

2 replies

Atsakyti

Reply as a new thread

      (0) Like

and user profile statistics

Thread count:

Post count:

How can I edit these strings to be translated?
Answer: Here is a custom function I use in update hooks, to translate some missing translations, just in case you want to do this programmatically:
function translateString($source_string, $translated_string, $langcode) {
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(array('source' => $source_string));
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // If exists, replace
  $translation = $storage->createTranslation(array(
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ))->save();
}

To implement it you can do the following (i.e. in a update hook):
function my_module_update_8000() {
  translateString(
    'The original String',
    'My translated String to german thats why the next parameter is "de"',
    'de'
  );
}

Answer: Identify what template it is using with Themer. Override it and use t() function to wrap those strings needed to be translated.
Answer: My solution:
I tried Devel Themer module as suggested, but I was not able to find function source to copy and change it for my needs. After unsuccessfull tries to add my translations via template.php and by creating custom tpl.php in templates folder of my theme, I decided to use this method:

! Before proceeding make sure that you have your non-english language downloaded and enabled as default in "Administration » Configuration »
  Regional and language » List"

1. Download and enable:

https://www.drupal.org/project/potx
https://www.drupal.org/project/i18n
Locale
Block translation
Entity translation
Field translation
Views translation
String translation

2. In
Administration » Configuration » Regional and language »
    Multilingual settings » Strings choose "English" as source language.
3. In
Administration » Configuration » Regional and language »
    Translate interface » Translate search for your string, which you want to
        translate and limit search to Views, Fields or Blocks.
4. Translate
all occurrences of your untranslated strings.
5. Go to
Administration » Configuration » Regional and language »
    Translate interface » Strings , choose all text groups and click "Refresh
        strings" to clean up translations, which can overlap.

That's it!

P.S. You can also use Administration » Configuration » Regional and
  language » Translate interface » Extract to choose any module or
  theme, extract untranslated strings to .po file and then Import that
  file back when translated. This potx module scans for strings wrapped
  with t() function.

Translate untranslated strings


Is there an easy way to get the image derivatives links?

Question: I'm working with complex image styles, and I'd like to be able to load all the different derivatives quickly to check they're being processed correctly.
But I don't see how to easily get the links. The best I can come up with is opening the node in JSONAPI and, with the patch from https://www.drupal.org/project/drupal/issues/2825812, getting the URLs for derivatives from that.
It there something easier?
Back in the Drupal 6 days, the Image module showed the links to all the sizes on the image node itself.
Answer: You can get that info with the following code:
$original_uri = 'public://images/image.jpg';

$styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();

$urls = array_map(function($style) use ($original_uri) {
  return $style->buildUri($original_uri);
}, $styles);

$urls should now contain a list of URLs based on the original, one for each image style in the system.
Answer: To get the image derivative URI for an image to which is applied a specific image style, you can use the following code.
// Load the ImageStyle instance in $image_style, for example with
// $image_style = ImageStyle::load($id).
// $image_uri is the path/URI for the image to which the style is applied.
if ($image_style->supportsUri($image_uri)) {
  $derivative_uri = $style->buildUri($image_uri);
}

Keep in mind that image derivatives are created only when the URL returned from $image_style->buildURL($image_uri) is requested (from a browser). Building the URI (or the URL) doesn't generate the derivative image; it returns the URI (URL) for an image that couldn't exist, yet.
To check an image derivative could be created, code similar to the one used from ImageStyleDownloadController::deliver() should be used.
if ($image_style->supportsUri($image_uri)) {
  $derivative_uri = $style->buildUri($image_uri);

  if (!file_exists($image_uri)) {
    $path_info = pathinfo($image_uri);
    $converted_image_uri = $path_info['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'];
    if (file_exists($converted_image_uri)) {
      $image_uri = $converted_image_uri;
    }
  }

  $success = file_exists($derivative_uri) || $image_style->createDerivative($image_uri, $derivative_uri);

  if ($success) {
    $image = Drupal::service('image.factory')->get($derivative_uri);
    $uri = $image->getSource();
  }
}

Comment: I don't know of any module that does that. A custom module that uses the code I suggest can show the URIs on a page.
Comment: Thanks! What I meant though is whether there's a way of getting those out in the UI. Content editors, for example, may want to verify the derivative images quickly.


Inserir chave estrangeira hibernate

Question: Possuo quatro entidades (selecao, partida, aposta e apostador) onde dentro da classe Aposta possuo os IDs de uma aposta e de um apostador. Quando vou tentar inserir uma aposta carregando dentro dele a partida e o apostador, me gera o seguinte erro:

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():

Classe Aposta
public class Aposta implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "idAposta")
private Integer idAposta;
@Size(max = 3)
@Column(name = "Palpite")
private String palpite;
@Size(max = 1)
@Column(name = "Status")
private String status;
@JoinColumn(name = "Apostador_idApostador", referencedColumnName = "idApostador")
@ManyToOne(optional = false, cascade = CascadeType.ALL)
private Apostador apostadoridApostador;
@JoinColumn(name = "Partida_idPartida", referencedColumnName = "idPartida")
@ManyToOne(optional = false, cascade = CascadeType.ALL)
private Partida partidaidPartida;

Acredito que seja algum mapeamento agora não sei qual. Pesquisei que precisava adicionar o parâmetro cascade dentro do @ManyToOne mas mesmo assim não rolou.
Answer: De acordo com esta resposta, você precisa colocar a assinatura para auto incrementar os IDs de sua Entity. Utilize @GeneratedValue(strategy=GenerationType.IDENTITY) nos campos que são @Id que já vai fazer isto automático.

Inserir chave estrangeira hibernate


Add HTTPS support for an application running its own web server, under a non standard HTTP port

Question: I have a server running Debian 10.
It runs Apache 2.4 for a a web services accessible under https://example.com, thanks to a LetsEncrypt certificate.
But it also runs an app (Subsonic) which serves a web UI on port 4040, under its own webserver, as I have no vhost for it and as it is still accessible when Apache is stopped.
So for now the app is accessible under HTTP on http://example.com:4040.
I know how to add SSL support for an Apache vhost, but how can I add HTTPS support for it this app, so that it is accessible on https://example.com:4040 or https://example.com:1234?
Also, should I use a different SSL certificate than the one I already have for this domain?
Answer: Add a reverse proxy in front of the app and configure HTTPS on this proxy.  Conveniently, you have Apache running which can happily reverse proxy for you.
As it currently stands, you can't use port 4040 as that's already taken by the app, so unless you can change the app's port or get it to bind to localhost (127.0.0.1 etc) only, then you'll have to run this app on a different port.  On that note, if you want to run this app over HTTPS there's no point leaving it still accessible by the insecure HTTP, so it would be better to configure this app to bind to localhost and have it accessible only through the reverse proxy.
You need the ProxyPass family of configuration options to create a reverse proxy.  Here's an incomplete example:
Listen <Public IP address of server>:4040

<VirtualHost *:4040>

  Protocols h2 h2c http/1.1
  ServerName example.com

  SSLEngine On

  # LetsEncrypt certificates (if not configured in another file)
  #  SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
  #  SSLCertificateKeyFile /etc/letsencrypt/live/eample.com/privkey.pem
  #  Include               /etc/letsencrypt/options-ssl-apache.conf

  ProxyPreserveHost On
  ProxyRequests Off
  ProxyPass / http://127.0.0.1:4040/
  ProxyPassReverse / http://127.0.0.1:4040/

</VirtualHost>

Certificates need to have the hostname that the client uses to connect embedded within their Subject Alternative Names extension, therefore as you don't seem to be proposing a different host (example.com in both cases) you won't need a new certificate.
Comment: Yes on both counts.  The app only listens locally and any external traffic hits the proxy on port 4040 before it forwards it to the app.  It can do this as the proxy is local too.
Comment: You can either add them to an existing config or create another.  Just check how any _other_ ones are enabled in your distro though.
Comment: Apologies - the `listen` directive is in the server config context, not virtual host.  Some distros have their `listen` directive in a separate file, such as `ports.conf`.
Comment: Thanks, reverse proxy with existing Apache is indeed what I need! One last thing, I'm still a bit confused about "binding to localhost". Does that mean the app wouldn't listen to external network anymore? Also, on your example, 4040 would be the external HTTPS port, right?
Comment: Got it. One last thing, do those virtualhost config lines have to be added to the existing virtual host config file for HTTPS, like example.com-le-ssl.conf?
Comment: I got an an Apache error regarding the "Listen" line: "Listen cannot occur within  section". Should I use this line outside of the section?


How to pass an argument to a hook without creating a custom module?

Question: I need to attach a theme-agnostic ("global") CSS file to the preprocess_hook() function so that any theme I use, would include that CSS.
I want to do that without creating a custom module because while I am a programmer, I am just not a PHP programmer and I find the documentation about creating custom modules overkill for this specific goal and I won't learn this entire subject just for a CSS file.
Answer: As a general rule, you can't use hooks without writing a custom module.
The Rules module provides a UI to access some hooks without writing code, but this is mostly limited to entity-related hooks (add, delete, update / CRUD operations).
Custom modules aren't that hard
Custom modules can be as little as ~10 lines of code; they are not hard to write.  However, the core documentation is quite thorough and difficult to skim; it may be more information than what you need.
In that case, I recommend beginner-friendly (but paid) tutorials like module development with Drupalize.me.
Comment: It's not about hard or not, it's about expertise; I am a programmer, just not a PHP programmer (maybe I should edit to clarify) and does not mean to learn the entire subject just for a CSS file.
Comment: You have made a wrong assumption that these are hard due to being "written for programmers"; I tell you as a programmer (I can refer you to my GitHub account to go through some Bash, JavaScript and even PHP codes I wrote if you don't believe me that I am a programmer) that my problem is at least one of these reasons: **1)** My native language is not English and not Germanic, **2)** I have a hard time reading such long English texts from a computer screen, **3)** I feel bad doing things I grasp as reserved for experts. In essence, I think you should edit the answer.
Comment: Here is a referral, just in case: https://github.com/bendqh1?tab=repositories
Comment: @Alkalix Ok, well the mechanism Drupal provides for using hooks is modules.  So the answer to your question **How to pass an argument to a hook without creating a module?** is no, you can't.  However, a custom module, as noted in my answer, can be as little as 10 lines of code and can be created in less than a minute with any text editor.  Creating a custom module does not require learning a bunch of Drupal APIs; basically, you create a `mymodule.info.yml` (not PHP! just YML), and then you add your custom hook code and you are done.
Comment: My main problem is with the saying `However, the core documentation is written for programmers so it may be difficult to understand the documentation.` which I find misleading and I think should be edited. Hardness with the documentation doesn't necessarily do with being a programmer or not, at least from my life experience.
Comment: @Alkalix That's a fair point; I updated my answer.


Bach BWV 817: how do you realize this ornament, bars 10, 18

Question: How do you realize this ornament with the big tailhook at the end?
The editorial contains a cheat sheet but not this particular
ornament.
Bach BWV 817 Sarabande (Henle): bars 10, 18
Comment: Related [question](https://music.stackexchange.com/q/108865/2600).
Answer: This ornament is to be played by filling up the interval, so an alternative notation would be
Answer: The way I've most often heard this performed is as a rolled chord in which some of the "in between" notes are included along the way. So, for example, the chord in measure 10 might be performed something like:

The rhythms are not intended to be accurate — just an illustration of the order in which the notes might be executed.
This interpretation is backed up by the fingering in measure 18, which suggests that the C# be played with the thumb, the E with finger 2, and then a run of 2-3-4 up to the G#.
Glenn Gould performs measure 18 in this way, although in measure 10 he puts the "run" at the beginning (i.e., bottom) of the chord.


How to use two instances of the same .ascx in the same page in ASP.NET MVC?

Question: I have two instances of an Address.ascx control in an ASP.NET MVC page.

Shipping Address

   <% Html.RenderPartial("Controls/AddressControl"); %>

Billing Address

   <% Html.RenderPartial("Controls/AddressControl"); %>

Of course, with the code exactly like this I'll end up with the same IDs for each field in the address. I can easily append a string to the ID of the fields so I'd have 'Street1_billing' and 'Street1_shipping', but I'm not clear how to map this to the model.
Whats the best solution to mapping a model to an array of items (in this case only 2).
I'm not aware of any ASP.NET 'out of the box' solution for this.
Note: This is slightly similar to this question and I could use this solution from Scott Hanselman, but its not exactly what I want. In my case I know I have two items, so its essentially a 2 item array but I'm wondering if there is a slightly more elegant solution.
PS. I'm sure this has been asked many times before, but I just cant seem to put in the right search terms. Please link this question if you're aware of dupes!
Answer: First, add an Address class to the model.
public class Address
{
    String StreetAddress1 { get; set }
    String StreetAddress2 { get; set }
    String City { get; set }
    String State { get; set }
    String Zip { get; set }
}

In Address.ascx, you need a line at the top that inherits the Address model, like this:
<%@ Page Language="C#"
    Inherits="System.Web.Mvc.ViewPage<MyProject.Models.Address>" %>

In the controller for the main view, push your two addresses into the ViewData.
Address myAddressObject1 = new Address
{
   AddressLine1 = "123 Anywhere Street",
   // ..etc.  Same with MyAddressObject2.  Or, just populate from database.
}

ViewData["Address1"] = myAddressObject1;
ViewData["Address2"] = myAddressObject2;
//
// do other stuff as needed
//
Return View();

In your main view, call your two Address subviews like this:
<%= Html.RenderPartial("Address", ViewData["Address1"]) %>
<%= Html.RenderPartial("Address", ViewData["Address2"]) %>

Answer: You can have a ViewModel
OrderCheckoutViewModel
{
    public Address ShippingAddress{get;set;}
    public Address BillingAddress{get;set;}
}

The values of formelements are mapped to the right Member of the ViewModel if they have the form
<input type="text" name="ShippingAddress.StreetAddress1"><input>

There is no easy and elegant way to come from StreetAddress1 to ShippingAddress.StreetAddress1.
My address model has the form:
public class Address
{
    String StreetAddress1 { get; set }
    String StreetAddress2 { get; set }
    String City { get; set }
    String State { get; set }
    String Zip { get; set }
    String InstanceName{ get; set }
}

I set the InstanceName to the Name of the property (ShippingAddress).
Then the form elements are defined in this form
<input type="text" name="<%=Model.InstanceName%>.StreetAddress1"><input>

The place of the ascx looks uncommon. Any reason why you dont put it in Shared and access it by
<% Html.RenderPartial("AddressControl",Model.ShippingAddress); %>

?
Comment: thanks. this looks the cleanest solution so far. i hadnt realized the modelbinder was this clever :-) and as far as the .ascx location is concerned i'm writing a shopping cart within an existing application nad i want to keep the shopping cart controls as separate as possible.
Comment: That guy is clever indeed. One thing I still have not seen is if you can map a value from the route with the same kind of syntax.


Atualizando apenas as propriedades enviadas - Entity Framework

Question: Estou tentando abstrair os métodos para salvar/atualizar os dados das minhas models. Fiz uma rotina genérica para abstrair essa operação mas estou com um probleminha. No cenário abaixo eu tenho a model Pessoa e no meu controller da web-api eu a recebo, só que ao invés de mandar todas as propriedades da classe eu mandei um JSON com apenas as propriedades que vão ser atualizadas. O problema é que o Entity tenta atualizar tudo inclusive as propriedades não enviadas.

Pessoa

class Pessoa {
   public int Id { get; set; }
   public String Nome { get; set; }
   public String Email { get; set; }
}

Supondo que eu tenha na tabela pessoa um registro com id "31" e eu queira enviar o json abaixo, o Entity iria dar um erro falando que e-mail não pode ser null mas eu só quero atualizar apenas o nome e queria isso de forma automática sem ter que ficar implementando classe a classe. Alguém já passou por isso? Obrigado.

Exemplo do JSON

{
    "id": 34,
    "nome": "Hiago"
}

Comment: Isso é em todo projeto?
Comment: Sim @VirgilioNovic na realidade estou criando uma arquitetura padrão para implementar nos meus projetos. Ai estou abstraindo essas coisas com métodos de beforeUpdate, afterUpdate essas coisas, para evitar repetição de código.
Comment: Acho que da forma que trabalha o EF não faz isso
Comment: Então Virgilio, eu consegui fazer.. Mas não gostei da solução, pois eu informo se a propriedade foi alterada ou não usando o dbEntityEntry.Property(property.Name).IsModified mas para saber se a propriedade foi alterada eu checo o null ou então o 0 no caso dos INT e isso não é confiável pois eu posso realmente querer enviar null no serviço ou então 0 em alguma propriedade.
Comment: Olha talvez utilizar reflexão mas não sei se é uma boa. Tem que ver se vale apena. Ou algum pacote que faça isso se acha algo posto
Answer: O que você tem que fazer nesses caso, na API você recebe o ID do objeto que deseja atualizar certo? Então você teria que fazer as seguintes etapas, vou criar um cenário aqui.
Esse é seu modelo (exemplo):
class Pessoa{
    public int Id { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}

Ai na API você receba (JSON) para atualizar apenas o nome:
{
     "Id" : 1,
     "Nome" : "Atualização"
}

você terá que fazer a seguinte ação, buscar no banco o objeto referente a esse ID:
var pessoa = contexto.Pessoa.First(x => x.Id == model.Id);

atualizar apenas o campo que você deseja nesse requisição (isso garante que caso a propriedade Nome do model que veio via JSON seja null, mantenha o valor anterior):
pessoa.Nome = model.Nome ?? pessoa.Nome;

é depois e só salvar no banco de dados:
contexto.SalveChanges();

Caso você coloque valores nulo no objeto que será salvo o EF-Core não consegue identificar que não deveria (tentar) gravar esse registro no banco, a validação se o campo e nulo ou não e uma "regra de negócio" e tem que ser validada antes do SaveChanges() o que o EF-Core faz e colocar NOT NULL impedido a gravação, caso isso seja configurado na criação do banco de dados.


VS 2008, Profiling Multiple Tests

Question: I have written a set of acceptance tests, and am trying to test the performance of a library with them.  Unfortunately, I can only seem to select a single test and "Create Performance Session" ...which doesn't give a true picture of performance of the app as a whole.
Is there a way to get a performance report of all the tests at once?
Answer: If you have Visual Studio Team Test or Team Suite, you should be able to create a Load Test, which looks like a single test, but can encapsulate as many unit tests as you want.
Since the Load Test is only a single test, you may be able to create a Performance Session for it. However, if you just need some performance statistics, the Load Test should be all you need.
Answer: Create your own test runner. Should not be too difficult depending on the testing frame work you are using. You can then profile the test runner.
Comment: Are you comparing the design of a language with writing a test runner? There is a tutorial over on codeproject (search for "advanced unit testing"). Also most unit testing frame works are open source...
Comment: I guess you are not really understanding the problem here. All the runner needs to do is find and run all the tests. There is no need for evaluation. Just calling a bunch of methods. That's it. Nothing unlikely about it.
Comment: There has to be a better solution than rolling my own test runner.  Somebody has to have done this already.
Comment: Really? Just develop your own testing framework runner. Why not reengineer the language too....

VS 2008, Profiling Multiple Tests


How to handle multiple validationsummary in mvc3

Question: I have partial view with its validation summary that must displayed with all views (I put it in the _Layout file) and in some views there is also validation summary.
So, when validate any view(doing server validation) both validation summary display errors?
How can I handle this case????
Comment: Is there a reason for you keeping the Validation Summary in the Views? if it is being picked up in the _Layout I dont see why the View's Validation Summary Control is needed?
Comment: the partial view is login part so I want it as separated control with its validation and the other views to have its own validation and also both (view and login) included in separated forms
Answer: One suggestion:
Use nested layouts:

_layout.cshtml:  as usual.  Use this for your login page.
_layoutWithValidationSummary.cshtml:  Uses _layout.cshtml as its layout, but adds a validationsummary.  Use this as the layout for your other pages.
Answer: I think you can only have one Validation summary, as you have seen more than one will cause duplications of errors.
I've tried looking to see if it is possible to assign certain validation errors to a specified Validation Summary, but I dont think this is possible.
You might need to look at an alternative solution. Not going as far as creating your own validation engine it might be possible passing something back in the ViewBag instead of using the validation summary for any of your Login errors?


How does resizing of images work with lighttpd?

Question: I switched the Webserver from Apache to Lighttpd. Since then, resizing images according to the defined sytles (/admin/config/media/image-styles) does not work anymore.
Anybody knows what may be missing?
Edit: Added excerpt from phpinfo():
gd
GD Support: enabled
GD Version: 2.0
FreeType Support: enabled
FreeType Linkage: with freetype
FreeType Version: 2.4.8
T1Lib Support: enabled
GIF Read Support: enabled
GIF Create Support: enabled
JPEG Support: enabled
libJPEG Version: unknown
PNG Support:    enabled
libPNG Version: 1.2.46
WBMP Support: enabled

imagick
imagick module: enabled
imagick module version: 3.1.0RC1
imagick classes: Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
ImageMagick copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
ImageMagick release date: 2012-08-17
ImageMagick number of supported formats: 206
ImageMagick supported formats: [.....Many!!]

Comment: Do you have a PHP image processing library installed? gd and imagemagick are supported as standard. You should be able to see at /admin/reports/status or in phpinfo
Comment: GD as well as imagemagick is installed, and shown as available in phpinfo()
Comment: "does not work" is most popular, and most useless statement in IT. What exactly happens when you try? What appears in server's error.log and Drupal's watchdog?
Comment: Last but not least, how do you generate image tags? Maybe it's simply lack of access token? What is HTTP response?
Comment: "Does not work" means that the other images styles are not available on the file system, but referenced in the article (tumbnail, medium and large). I do not use image tags. Drupal just tells me that the article has been added ord modified, There are no error.log outputs when the issue occurs.
Comment: is clean urls running?
Comment: In order for image styles to be generated, requests for the URLs in question have to be passed to Drupal when the file does not already exist. The default .htaccess file for Drupal includes a rule which does this. My suspicion would be your current Lighttpd configuration does not.
Comment: @AlirezaTabatabaeian Clean URLs is activated and working
Comment: @AlfredArmstrong You mean this one?

    `RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]`
Comment: Yes. Have you checked that a request for a file that is not present goes to Drupal?
Comment: Have you checked the the file and folder permissions are correct? The correct user needs write permission
Comment: @ColinShipton Permissions should be okay (same user and group as the one that runs all lighttpd processes)
Comment: @AlfredArmstrong At least the access log shows that the request for one of the modified pictures comes in, but is answered with a 404.
Comment: url.rewrtie-if-not-file seems not to work, I'm giving up after a goog days work now: `url.rewrite-if-not-file = (
                 "^/(.*)$" => "/index.php?q=$1"
     )`
Answer: Change your lighttpd rewrite rule to this :
url.rewrite-final = (
"^/system/test/(.*)$" => "/index.php?q=system/test/$1",
"^/([^.?]*)\?(.*)$" => "/index.php?q=$1&$2",
"^/([^.?]*)$" => "/index.php?q=$1",
"^/rss.xml" => "/index.php?q=rss.xml",
"^/(.+/files/styles/.+\.+.+)\?(.*)$" => "/index.php?q=$1&$2"
)

That must work. if not disable the clean ulrs to see if the problem is solved or not .
Comment: It worked out of the box this way and I have no side effects so far. I've been afraid I had to hassle with mod_magnet to solve the issue...
Comment: I'm glad I could help.


Code to output individual fields in a Theme view

Question: I know this question seems to have been half answered a few times but I'm finding it difficult to apply a working solution. I have created a new theme from scratch to use for a view I have created. I can get the view content to display in the Theme by using:

print render($page['content']);

However because of the complexity of my theme layout I need to display the fields in the view individually.
I understand that I need to create a file in the theme folder called something like:
views-view-field--viewname.tpl.php and add some php, then add some code to this but I just can't seem to find the correct code that is needed plus the correct syntax I add to the theme page.tpl.php to show the individual fields. Could anyone please help?
Thanks.
Answer: OK,
I sorted this out. I didn't quite understand that I need to make layout changes in the appropriately named views-view-fields--viewname.tpl.php. I was hoping to just add some php to the page.tpl.php theme file I have developed for my views.
It's quite a learning curve with Drupal!


Keep camera from rotating around relative z-axis

Question: I'm trying to create camera movement that mimics the behavior of the unity scene editor where you can perform a spherical rotation around the scene with 2d mouse movement. So far the camera is rotating correctly given x or y movement, but dragging diagonally causes the camera to rotate around its relative z-axis until it gets locked. I cannot force the camera to look at the origin relative to world up because then it cannot rotate upside-down
Here is the script that I've attached to the camera
using UnityEngine;

public class MainCamera : MonoBehaviour
{
    Vector2 startingPosition;
    Vector2 mousePosition;
    Vector3 orthogonalCameraVector;
    float degreesPerUnitWidth = 180f / Screen.width;
    float degreesPerUnitHeight = 180f / Screen.height;
    float cameraRadius = 10;

    void Start()
    {
        transform.position = new Vector3(0, 0, -cameraRadius);
        transform.LookAt(Vector3.zero);
        orthogonalCameraVector = -Vector3.left;
    }

    void LateUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            mousePosition = Input.mousePosition;
        }

        if (Input.GetMouseButton(0))
        {
            var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);

            startingPosition = mousePosition;
            var mouseDelta = startingPosition - input;

            var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
            var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
            var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
            var rotation = xzRotation * yRotation;
            orthogonalCameraVector = rotation * orthogonalCameraVector;
            transform.position = rotation * transform.position;
            transform.rotation = rotation * transform.rotation;
            mousePosition = Input.mousePosition;
        }
    }
}

Answer: I realized the orthogonalCamerVector only needed to be rotated about the y-axis because I wanted to keep it parallel with the xz-plane. I then applied this rotation to the orthogonalCamerVector before rotating the transform so it would always be rotating about a fixed plane so it looks something like this:
        var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
        var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
        orthogonalCameraVector = yRotation * orthogonalCameraVector;
        var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
        var rotation = xzRotation * yRotation;
        transform.position = rotation * transform.position;
        transform.rotation = rotation * transform.rotation;


Apache2 Virtual Host auto redirects to https

Question: I have ubuntu 16.04, I have setup virtual host in apache2 mysite.dev in file /etc/apache2/sites-available/mysite.conf
<VirtualHost *:80>
     ServerName      mysite.dev
     ServerAlias     *.mysite.dev
     DocumentRoot /var/www/mysite

     <Directory /var/www/mysite>

              Options FollowSymLinks

              AllowOverride All
     </Directory>

     ErrorLog /var/log/apache2/error.log

     # Possible values include: debug, info, notice, warn, error, crit,
     # alert, emerg.
     LogLevel warn

     CustomLog /var/log/apache2/access.log combined
</VirtualHost>

it was working fine and I was able to access my site in both firefox and chrome browsers in the link http://mysite.dev/ till yesterday but then I had ran following upgrade commands yesterday
sudo apt-get upgrade

and after restart it start redirecting my application to https i.e. https://mysite.dev/ and showing
ERR_CONNECTION_REFUSED

for obvious reasons
Please Note: I dont want the fix of ERR_CONNECTION_REFUSED instead I want my site to start working at http and stop redirecting it to https in browsers,
I have following versions

Ubuntu 16.04.4 LTS
Apache/2.4.29 (Ubuntu), Built 2017-10-22T13:35:47

Also note that I'm running PHP 7.0 Magento 2.2 and not intended to change the Virtual Host Domain from mysite.dev
Update: Following is the response to curl -v http://mysite.dev -o saved
* Rebuilt URL to: http://mysite.dev/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying 127.0.0.1...
* Connected to mysite.dev (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: mysite.dev
> User-Agent: curl/7.47.0
> Accept: */*
>
  0     0    0     0    0     0      0      0 --:--:--  0:00:30 --:--:--     0< HTTP/1.1 200 OK
< Date: Fri, 06 Apr 2018 09:03:36 GMT
< Server: Apache/2.4.29 (Ubuntu)
< Set-Cookie: store=english; expires=Sat, 06-Apr-2019 09:03:42 GMT; Max-Age=31536000; path=/; domain=mysite.dev; HttpOnly
< Set-Cookie: PHPSESSID=gbvs8fq6q9g67t9jd0bjl71ad4; expires=Fri, 06-Apr-2018 10:03:43 GMT; Max-Age=3600; path=/; domain=mysite.dev; HttpOnly
< Expires: Thu, 06 Apr 2017 09:03:44 GMT
< Cache-Control: max-age=0, must-revalidate, no-cache, no-store
< Pragma: no-cache
< X-Magento-Cache-Control: max-age=0, must-revalidate, no-cache, no-store
< X-Magento-Cache-Debug: MISS
< X-Magento-Tags: FPC
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Vary: Accept-Encoding
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
{ [15607 bytes data]
100 95593    0 95593    0     0   3065      0 --:--:--  0:00:31 --:--:-- 24219
* Connection #0 to host mysite.dev left intact

Comment: Well _somewhere_ is a redirect or path rewrite or whatever. Did you check snippets, `sites-enabled/*.conf`, `mods-enabled`, `apache2.conf`, `ports.conf`, etc.? Try using curl in verbose mode on your host and check the response.
Comment: @Lenniey please check the update
Comment: The redirect can also come from a .htaccess file in your document root, or from a script that is run by apache.
Comment: Nothing in your curl request shows a HTTPS connection. Maybe Magento itself redirects in some way?
Comment: there are other virtual hosts as well all of them are redirecting to https. @Lenniey
Comment: nothing in `.htaccess` @GeraldSchneider
Answer: This problem occur with latest versions of chrome. This (.dev) domain is not available since 2017. Check this link below https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/
Comment: ...dude. Nice catch!
Comment: Wow. It's been a while since I setup `.dev` so naturally my head was about to explode when it's suddenly redirecting to https. Good thing I stumbled upon this.


Ruby cancel object creation

Question: How to cancel object creation if get wrong params?
Example:
class MyClass
    def initialize(a, b, c)
        @a = @b = @c = nil
        @a = a if a.is_a? Integer
        @b = b if b.is_a? String
        @c = c if c.is_a? Integer or c.is_a? Float
        return nil if @a == nil or @b == nil or @c == nil # doesn't works
    end
end
cl = MyClass.new('str', 'some', 1.0) # need cl to be nil because 1st param isn't Integer

Comment: Maybe use the factory method pattern so that an external method checks for valid parameters and if failed it returns nil instead an initialized object.
Answer: It's simple, just don't use the constructor. :)
class MyClass
  def initialize(a, b, c)
    @a, @b, @c = a, b, c
  end

  def self.fabricate(a, b, c)
    aa = a if a.is_a? Integer
    bb = b if b.is_a? String
    cc = c if c.is_a? Integer || c.is_a? Float
    return nil unless aa && bb && cc
    new(aa, bb, cc)
  end
end

cl = MyClass.fabricate('str', 'some', 1.0) # => nil

This patten is called Factory Method, by the way.
Comment: `self.fabricate` can be improved to this: `def self.fabricate(a, b, c);
    return unless a.is_a?(Integer) and b.is_a?(String) and c.is_a?(Integer) || c.is_a?(Float);
    new(a, b, c)
end`
Answer: Unless you need some kind of silent failure mode for handling bad data, you may just simply want to raise errors and halt the program:
def initialize(a, b, c)
    @a = @b = @c = nil

    raise "First param to new is not an Integer" unless a.is_a? Integer
    @a = a

    raise "Second param to new is not a String" unless b.is_a? String
    @b = b

    raise "Third param to new is not an Integer or Float" unless c.is_a? Integer or c.is_a? Float
    @c = c
end

Whether you use this approach, or a factory method that passes over bad input depends on the kind of data you wish to work with.
Personally I would nearly always go with raising errors, unless I had a specific requirement to silently ignore bad data. But this is coding philosophy, and not necessarily the best answer for your problem.
Comment: + 1, but I'd make a case for always going with exceptions: if you really need to silently ignore bad input, wrapping the exception in a `rescue` clause is the way to go.

Ruby cancel object creation


Beginning to learn the transverse C-flute : with offset-G key or inline-G key?

Question: I have a nephew, eleven years old, who wants to start learning the flute next september.
I have seen that there are flute models with two central round keys either inline with the others or slightly offset towards the small fingers of the left hand if I understand well.
He does not have large hands for his age but it is difficult to tell how they will grow.
Is it a good idea to start with such an offset-G flute when young and then switch to an inline one in a few years when he will be larger?
Can he keep using an offset-G flute for all his life if he persists in playing the flute?
Comment: Just as a point of interest, I do not think there are many beginner flutes with inline-G keys.
Comment: @fluteflute and @Michael : thanks for your answers. I would like to accept both but the system is not designed this way so I will nominate the earliest one. I am happy I asked here (and that the beta of music.SE started sufficiently early so that I could have these advices).
Answer: Offset-G flutes are very common, certainly for beginners, but also for advanced and professional players. The position of the keys makes no difference to the sound produced.
Few would say that there is much difference between inline/offline other than ergonomics. Offset is more comfortable for most people, but if your nephew develops long fingers later in life he can always reconsider.
A far more important consideration is that he does't strain his wrists, and cause Repetitive Strain Injury or other serious injuries. Go for the most comfortable.
Comment: Agree. Even flutists with larger hands generally prefer the offset-G, and I don't know ANY flute teacher who would recommend a student buy an inline-G flute.
Comment: @Pyromonk I've updated the answer
Comment: What does RSI stand for?
Answer: For a beginner, especially with small hands, definitely an offset-G. When you are first learning, you don't need the added distraction of awkwardly reaching for the key. What the student will end up doing is playing the edge of the key, and that habit is very difficult to break.
I have heard it said that "professional" flutes are inline, but I have seen many of both. I have also heard that inline flutes have better tone, but the waveform won't change, so I doubt this. If there is a difference, it's minuscule.
Comment: @ogerard: That's right. Best to get it early - habits are first like cobwebs, later like cables.
Comment: Thanks. This agrees with the previous advice from fluteflute and makes sense in the context of my question. If I understand well, the main troubles with playing on the edge of the key is that it is at the same time unreliable and won't allow you to play with open keys later?
Answer: The inline g# flute fetish is mainly dying.  If you doubt that look at the number of used ones up for sale.  For most people offset is just more comfortable.  It has been proven over and over in blind tests that there is no difference in sound quality between two otherwise equal flutes.
Comment: When posting an answer based on statistics, it's a good idea to show your sources.


I am not sure whether my friend is saying the truth or if he's lying, how can I get the correct information out of him using logic?

Question: In a logic course, one of the problems went as follows:
You forgot whether the Logic class is at 11 or 12. Your friend certainly
knows which; but sometimes he tells the truth and at other times he
deliberately lies, and you know that he will do one of these but you do
not know which. What should you ask him?
Name the statement "logic class  is at 11": $p_1$ and "logic class is at 12": $p_2$.
The hint said that one should find a statement that is logically equivalent to $p_1$ or $p_2$. So I used this statement:
$( (p_1 \implies (p_1 \land (\neg p_1)) \Longleftrightarrow (\neg p_1) )$. So the question I should ask my hypothetical friend is "If the class is at 11, then the class is at 11 and 12 right?" But then whether he says yes or no it is not important, in either case the statement is equivalent to "the class is at 12" !
I am confused. Is this correct? I deliberately made a question from which I can only conclude $p_2$! It's like I am cheating.
If my answer isn't correct, what should I ask?
Comment: Your expression is just a tautology, always true.  There is  no way to construct a propositional logic statement out of just $p_1$ (and $p_2$ is just $\lnot p_1$) that determines the answer if your friend can change whether he lies or tells the truth between questions.  You could ask "p_1 xor you are a liar".
Answer: The central difficulty of this question seems to lie in our restriction to propositional calculus with two particular atomic propositions. Otherwise, if we are allowed to use a richer language in grammatical capabilities or introduce additional propositions, the question would be reduced almost to triviality. So, we need to find a principled interpretation of propositional calculus and a set of assumptions that we shall employ in coherence. It should be emphasised that we shall not interfere with propositional calculus; we shall articulate a setting in semantic and pragmatic terms the formalism of propositional calculus signifies.
We can analyse the "friend" in the question into two disparate characters, let us call them knight and knave in memory of Raymond Smullyan. The knight always takes an honest attitude and tells truths, points to the right road and the like, whereas the knave always takes a deceptive attitude and tells lies, points to the wrong road and the like. Hence, we talk to a person, but we do not know whether he is a knight or a knave.
An important assumption, which is usual in such problems, but should be remarked here, is that we know there are only two choices; the logic class is either at 11 or at 12. Thus, we can infer with certainty that if one choice is not the case, then the other one is. Our collocutor also knows that there are only two choices, furthermore, he knows which one is the case.
By a conditional proposition $p\rightarrow q$, we shall understand that given $p$, our collocutor's response will be about $q$. Thus, $p_{1}\rightarrow p_{2}$ will represent such a situation that we point to $11$ on our wirst watch and our collocutor points to $12$ in response. Alternatively, we may suppose, the conditional indicates that if we asked whether $p_{1}$, then our collocutor would say $p_{2}$. We might conjure up various natural situations on the logical baseline.
Subsequently, the truth values of the propositions $p_{1}$ and $p_{2}$ in the conditional will indicate the given situation in the antecedent and our interlocutor's attitude in the consequent. In order to facilitate explanation, we may additionally indicate the truth values $0$ and $1$ in square brackets.
Since the knight is honest, his attitude will be univocal and mutually opposite for $p_{1}$ and $p_{2}$. Hence, if the given situation is $p_{1}$ and $p_{1}$ is indeed the case ($[1]$), then the knight's attitude for $p_{2}$ will be negative ($[0]$) and vice versa. Since the knave is deceptive, his attitude will be equivocal on $p_{1}$ and $p_{2}$. Hence, if the given situation is $p_{1}$ and $p_{1}$ is indeed the case ($[1]$), then the knave's attitude for $p_{2}$ will be affirmative ($[1]$) and so for the case that the given situation $p_{1}$ is not the case ($[0]$).
By a resultant truth value $0$, we shall understand a negative reply (i.e., "no") and By a resultant truth value $1$, we shall understand a negative reply (i.e., "yes"). We may phrase the relevant question in any way that will sound or appear to us natural.
As we know from truth table, $p_{1}\rightarrow p_{2}$ presents us four resultant possibilities, one with truth value $0$ ("no") and three with truth value $1$ ("yes"). For example, if we asked our collocutor "if we said that logic class was at 11, then would you reply that logic class is at 12?" and he answered "no", we would realise that we had talked to a knight and logic class was indeed at 11. However, upon an affirmative answer, we could not conclude whether we had talked to a knight or knave.
Therefore, let us extend our question to $(p_{1}\rightarrow p_{2})\rightarrow p_{1}$.
We have to specify which truth value of the additional consequent, $p_{1}$, reflects whose attitude. We shall see that the following truth value will result, the green coloured values falling into the knight's lot and the red coloured values into the knave's lot:
$\begin{array}{c c|c c}
p_{1} & p_{2} & p_{1}\rightarrow p_{2} &(p_{1}\rightarrow p_{2})\rightarrow p_{1}\\
\hline
\color{red}{0} &\color{red}{0} &\color{red}{1} &\color{red}{0}\\
\color{green}{0} &\color{green}{1} &\color{green}{1} &\color{green}{0}\\
\hline
\color{green}{1} &\color{green}{0} &\color{green}{0} &\color{green}{1}\\
\color{red}{1} &\color{red}{1} &\color{red}{1} &\color{red}{1}\\
\end{array}$
A natural language question might be "Suppose you would reply that logic class is at 12 if we asked whether logic class was at 11, would you then say that $p_{1}$ now?". We shall consider the knave's replies; the knight's ones are simpler varieties of them along the same baseline.
If $p_{1}$ is indeed not the case ($[0]$), the knave would reply "no". On the condition that if logic class were said to be at 11, he would say that logic class was at 12 (or, if logic class were not at 11, he would say that logic class was not at 12), a "yes" reply would affirm that he would say now that logic class is at 11. Hence, the affirmation would mean that he would not say logic class is at 12, and imply that logic class is not at 11, thus he would unwillingly tell the truth. Therefore, he would alter his attitude to "no".
If $p_{1}$ is indeed the case ($[1]$), the knave would reply "yes". On the condition that if logic class were said to be at 11, he would say that logic class was at 12, a "no" reply would deny that he would say now that logic class is at 11. Hence, the denial would mean that he would not say logic class is at 11, and imply that he would say logic class is at 12, and by the given conditional, logic class is at 11. Thus, he would unwillingly tell the truth. Therefore, he would alter his attitude to "yes".