$3\mathbb Z$ as a direct summand of $\mathbb Z$

Question: Show that $\mathbb Z$ cannot have $\mathbb Z$ as a direct summand: Suppose $G$ and $3\mathbb Z$ are the two direct summands of $\mathbb Z$ and show that $G$ must be isomorphic to  $C_3$.
First of all, what exactly does the assumption say:  $\mathbb Z=3\mathbb Z \oplus G$  or  $\mathbb Z\simeq 3\mathbb Z \oplus G$?
Second, I have only an intuitive way of showing that $G\simeq C_3$. Namely, "mod out both sides by $\mathbb 3\mathbb Z\oplus\{0\}$". If I'm given that $\mathbb Z=3\mathbb Z \oplus G$, then the only problem I see is that formally speaking $\mathbb 3\mathbb Z\oplus\{0\}$ isn't a subgroup of $\mathbb Z$, so I need to say more words. What exactly the formal proof should look like? If I'm given $\mathbb Z\simeq 3\mathbb Z \oplus G$, then apart from the above think I should also justify that if two groups are isomorphic, then taking quotients by isomorphic (I guess) subgroups should yield the same result. Why is that true?
Comment: You have the right idea.  Everything you're doing is fine up to isomorphism, which is all that matters.
Comment: Here, you are thinking of $3\Bbb{Z}$ as a subgroup of $\Bbb{Z}$ (If you are only working up to isomorphism, then in fact you can say $\Bbb{Z} \cong 3\Bbb{Z}$ as groups). In this case, you are showing that $\Bbb{Z}$ cannot be written as the internal direct sum of $3\Bbb{Z}$ and $G$
Answer: What the assumptions says depends on whether you are talking about internal or external direct products. Since you are talking about $3\mathbb Z$ which already explicitly identified as a subgroup of $\mathbb Z$, it probably makes sense to talk about internal direct products here, in which case equality is appropriate.
These two notions are equivalent: Any time you write $G = H \oplus K$ as an internal direct product, this is equivalent to saying that $G \cong H \oplus K$ as an external direct product, via a particular isomorphism $\phi: G \to H\oplus K$ which satisfies $\phi(H) = H\oplus 0$ and $\phi(K) = 0\oplus K$.
If you consider external direct products instead, then just writing $\mathbb Z \cong 3\mathbb Z \oplus G$ doesn't fully describe the problem. It should be assumed there is not just any is isomorphism $\phi: \mathbb Z \to 3\mathbb Z \oplus G$, but one which additionally satisfies $\phi(3\mathbb Z) = 3\mathbb Z\oplus 0$.
As for "apart from the above ...", this is right, however you should be careful with what you mean by "isomorphic subgroups". If this just means "subgroups which are isomorphic to each other as groups" then the statement is false; for example $n\mathbb Z \cong \mathbb Z$ for all $n\neq 0$ in $\mathbb Z$, but $\mathbb Z / n\mathbb Z = C_n$ are not isomorphic for different values of $n$ (usually). Instead you need a choice of isomorphism between the subgroups which is compatible with the choice of isomorphism between the larger groups.
Here is a precise version:
"If $\phi: G \to H$ is an isomorphism of groups, and $G' \subseteq G, H' \subseteq H$ are (normal) subgroups such that $\phi(G') = H'$, then there is an induced isomorphism of groups $\phi': G/G' \to H/H'$ given in terms of coset by $\phi'(gG') = \phi(g)H'$."
As an aside: It would also be easy to show that $3\mathbb Z$ is not an internal direct summand of $\mathbb Z$ instead by showing that any subgroup $G$ of $\mathbb Z$ for which $G\cap 3\mathbb Z=0$ is trivial. (If $n \in G$, then $3n \in \mathbb Z\cap G = 0$ so $n=0$.)
Answer: If $\mathbb Z \cong G\oplus 3\mathbb Z$, then there is canonical epimorphism $p\colon \mathbb Z\to G$ whose kernel is $3\mathbb Z$. Define map $\varphi\colon G\to\mathbb Z/3\mathbb Z$ by $\varphi (p(n)) = n + 3\mathbb Z$.
We need to show that this map is well defined, so let $p(m) = p(n)$. This implies that $p(m-n) = 0$, or $m-n\in\ker p = 3\mathbb Z$. Thus, $\varphi(p(m)) = m + 3\mathbb Z = n + 3\mathbb Z= \varphi (p(n))$.
$\varphi$ is obviously surjective, so it remains to show that it is injective. Also, I didn't show that it is homomorphism. Can you finish it?
Comment: I guess here I have the same problem with "implicitness" of the isomorphism $\mathbb Z\simeq G\oplus 3\mathbb Z$. If we don't know how it's given, how can we conclude that $p$ has kernel $3\mathbb Z$? For injectivity of $\varphi$, actually I have no clue what can it follow from. If I knew the exact form of the isomorphism I could try to assume that $p(n)\in \ker \varphi$ and $p(n)\ne 0$ and arrive at a contradiction by considering its explicit preimage under $p$...
Comment: By what formula is that canonical epimorphism $p$ given?
Comment: @user437307, $(g,n+3\mathbb Z)\mapsto g$ precomposed by isomorphism $\mathbb Z\to G\oplus 3\mathbb Z$.


Are there any languages where people use a different word for goal?

Question: With the start of the World Cup today, I wanted to compile a list of how to say "goal" (event of scoring, not the target) in every language of the 2018 World Cup participating countries. As in many languages it's just a goal, I'm mainly interested in countries which use different word for goal or spell it differently.
Comment: You could find a bit from [Wiktionary](https://en.wiktionary.org/wiki/goal). Of course, getting some response from native speakers of those languages is more reliable. (Perhaps at least for some of the languages there are a few on this site.)
Comment: @gdrt Actually it is [hadaf] what we're looking for ([marma(n)] was the goal itself, so this doesn't apply here.. sorry for the bad translation there - I asked a Syrian friend), but like in Croatia they often use Gol instead of their native Version (Cilj in Croatia). Maybe we should agree on putting all translations into the answer if there is more than one.
Comment: I feel this is really much more an etymology question than a sports one. Unsurprisingly, if you take a bunch of [Indo-European languages](https://en.wikipedia.org/wiki/Indo-European_languages) (which is basically what we have in the World Cup), you get a lot of similarity. Step outside that to any other language family and you get very different words - for ones spoken in Europe, try Finnish or Basque. Go further outside to e.g. native African, American or Australasian languages and you get even more variation.
Comment: Indian languages have different words for the English word "goal", but in the context of football (and other similar sports which have a goal), it is called just "goal".
Comment: The word for `goal` in Arabic is `هدف [hdf]`, but Arabic commentators famously yell `goal`. An insight from native speaker would be helpful.
Comment: @dly Sure, I agree
Answer: The list:

Arabic (Saudi Arabia, Tunisia, Egypt): هدف [pronounced as "hadaf"], Gol
Catalan (Spain, France): Gol
Croatian (Croatia): Gol, Cilj
Danish (Denmark): Mål
Darija (Morocco): Bite
Dutch (Belgium): Doelpunt, Goal
English (Australia, England, Nigeria*): Goal
French (France, Belgium, Switzerland, Senegal*): But
German (Germany, Switzerland, Belgium): Tor
Icelandic (Iceland): Mark
Italian (Switzerland): Gol
Japanese (Japan):ゴール [gōru]
Korean (South Korea):골 [gol]
Persian (Iran): گل [pronounced as "gol"], توی دروازه [pronounced as "tooye darvaze"]
Polish (Poland): Gol, Bramka
Portuguese (Brazil): Gol
Portuguese (Portugal): Golo
Russian (Russia): Гол [Gol]
Serbian (Serbia): Гол [gol], Branka
Spanish (Argentina, Colombia, Costa Rica,  Mexico, Panama, Peru, Spain, Uruguay): Gol
Swedish (Sweden): Mål
Wolof (Senegal*):

*Could be interesting in countries that have several languages to find if there is another way of saying or writing goal


PHP Validate Value $_GET from url against lines of a txt file

Question: i have a problem i couldn't figure out since im self-taught and still exploring the php world
so i have a text file that looks like this:
951753159
456787541
123156488
748651651

and i got an url with a variable
http://example.com/mypage.php?variable=951753159

what i want is to check if the url variable matches one of the txt file lines in order to execute a code
i already tried this
 $search = $_GET["variable"];
 $file = "variables.txt";
 if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
 THE CODE THAT I WANT TO EXECUTE
 }

but for some reason it matches the whole content of the file
any help is highly appreciated
Thanks in advance :)
Comment: Possible duplicate of [How to read a file line by line in php](http://stackoverflow.com/questions/13246597/how-to-read-a-file-line-by-line-in-php)
Comment: Maybe this could help you (possible repost) : http://stackoverflow.com/questions/3686177/php-to-search-within-txt-file-and-echo-the-whole-line
Answer: Try with an array from file():
$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);

if(in_array($_GET["variable"], $lines)) {
    // YES FOUND
} else {
    // NOT FOUND
}

Answer: From the documentation on `file_get_contents', the entire contents of the file are read as a string.  So that is why it is matching against the entire file.
The command that you want to use is file, this reads the file into an array of each line.
Answer: I would
Use file to read the file into an array.
Then array_flip the array so that it's values are now the keys
Which allows me to isset($array[$key])
Answer: You can do this.
<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
    if (trim($search) == trim($value)) {
        print "DO something! " . $value;
    }
}?>

Regards.
Nelson.


How can i validate from jquery form submit ?

Question: i couldn't enable validation message on view ,because i use jquery to submit form.
Could any one have some idea to use validation with jquery submit form ?
View
@using (Html.BeginForm("Index", "Sample", FormMethod.Post, new{ id="frmStep1"}))
 {

     Question 1:*

          @Html.ValidationMessageFor(model => model.answer_01)

             @Html.RadioButtonFor(m=>m.answer_01,"2355")Male

             @Html.RadioButtonFor(m=>m.answer_01,"2355")Male

  <button class="btn btn-primary" type="button" id="btnStep1">

      Save
  </button>
}

Script
$("#btnStep1").click(function () {

        $.ajax({
            url: "../Profile/Question",
            type: "POST",
            dataType: "json",
            data: $("form#frmStep1").serialize(),
            success: function(data) {
                alert('Ok');

            },
            fail: function(data) {
                console.log('failed to submit.');
            }
        });
    });

Controller
[HttpPost]
public ActionResult Index(SampleViewModel model)
{
    return Json("success",JsonRequestBehavior.AllowGet);
}

i don't have any idea to enable validator on ViewModel to active when user couldn't input some text, pls give some idea to solve these solution.
Comment: Model validations work after javascriptvalidations. If you want your model validations to work then you have to take input type as submit OR you have to validate your each field in Javascript before submit
Answer: You can Specify your action name and controller name in Form and take input type as 'submit', as given below:
 @using (Html.BeginForm("YourActionName", "YourControllerName", FormMethod.Post, new{ id="frmStep1"}))

   {

        Question 1:*

          @Html.ValidationMessageFor(model => model.answer_01)

          @Html.RadioButtonFor(m=>m.answer_01,"2355")Male

          @Html.RadioButtonFor(m=>m.answer_01,"2355")Male

 <input class="btn btn-primary" type="submit" value="Save" id="btnStep1" />

}


I get a read access violation **vf** was nullptr (LibVorbis)

Question: I'm getting a read access violation somewhere I say there is something pointing to null I am currently using XAudio2.9 and Libvorbis 1.3.7. I edited this to be more informative this is all of it I hope you guys can find the issue with this I'm new to messing with sound in C++ and been trying to learn how to use this for months now I have some trouble understanding things like this.
#include <xaudio2redist/xaudio2.h>
#include <fileapi.h>
#include <vorbis/codec.h>
#include <vorbis/vorbisfile.h>

#define STREAMING_BUFFER_SIZE 4096
#define MAX_BUFFER_COUNT 4

class SoundDevice
{
public:
bool audio_init();
bool audio_load(const char* filename);
bool play();
bool audio_clean();
private:
IXAudio2* Audio = nullptr;
IXAudio2MasteringVoice* Masteringvoice = nullptr;
IXAudio2SourceVoice* Sourcevoice = nullptr;
WAVEFORMATEX formatex;
XAUDIO2_BUFFER buffer = { 0 };
XAUDIO2_VOICE_STATE state;
HRESULT hr;

// LibVorbis
HANDLE vorbishandle;
OggVorbis_File* vorbisfile;
vorbis_info* vorbisinfo;

char buffers[MAX_BUFFER_COUNT][STREAMING_BUFFER_SIZE];
int sec = 0; // section
DWORD pos = 0; // position
int ret = 0; // return
DWORD currentDiskReadBuffer = 0;
};

bool SoundDevice::audio_init()
{
hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);

if (FAILED(hr))
{
    MessageBoxA(0, "Failed to CoInitialize", "Error:", hr);
    return false;
}

if (FAILED(hr = XAudio2Create(&Audio, 0, XAUDIO2_DEFAULT_PROCESSOR)))
{
    MessageBoxA(0, "Failed to create XAudio2", "Error:", hr);
    return false;
}

if (FAILED(hr = Audio->CreateMasteringVoice(&Masteringvoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, 0, 0)))
{
    MessageBoxA(0, "Failed to create Mastering Voice", "Error:", hr);
    return false;
}

vorbisinfo = ov_info(vorbisfile, -1);

ZeroMemory(&formatex, sizeof(WAVEFORMATEX));
formatex.wFormatTag = 1;
formatex.nChannels = 2;
formatex.nSamplesPerSec = 44100;
formatex.nAvgBytesPerSec = formatex.nChannels * formatex.nSamplesPerSec * 2;
formatex.nBlockAlign = formatex.nChannels * 2;
formatex.wBitsPerSample = 16;
formatex.cbSize = sizeof(formatex);

ZeroMemory(&buffers[currentDiskReadBuffer], sizeof(DWORD));

buffer.pAudioData = reinterpret_cast<BYTE*>(&buffers[currentDiskReadBuffer]);
buffer.AudioBytes = STREAMING_BUFFER_SIZE;
buffer.Flags = XAUDIO2_END_OF_STREAM;

if (FAILED(hr = Audio->CreateSourceVoice(&Sourcevoice, &formatex, 0, 2.0f, 0, 0, 0)))
{
    MessageBoxA(0, "Failed to create Source Voice", "Error:", hr);
    return hr;
}

return 0;
}

bool SoundDevice::audio_load(const char* filename)
{
vorbishandle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, FILE_SHARE_READ, FILE_ATTRIBUTE_NORMAL, vorbishandle);

if (ov_open_callbacks(vorbishandle, vorbisfile, nullptr, 0, OV_CALLBACKS_DEFAULT))
{
    CloseHandle(vorbishandle);
    return false;
}

while (ret && pos < STREAMING_BUFFER_SIZE)
{
    ret = ov_read(vorbisfile, buffers[currentDiskReadBuffer] + pos, STREAMING_BUFFER_SIZE - pos, 0, 2, 1, &sec);
    pos += ret;
}

return hr;
}

bool SoundDevice::play()
{
hr = Sourcevoice->SubmitSourceBuffer(&buffer, 0);
hr = Sourcevoice->Start();
return hr;
}

bool SoundDevice::audio_clean()
{
Sourcevoice->Stop(0);
Sourcevoice->FlushSourceBuffers();
Sourcevoice->DestroyVoice();
return hr;
}

Comment: Just because this is where the program crashes or reports an error doesn't mean this is where the problem is. C++ does not work this way. The problem can be anywhere in your code, but after the bug occurs the program keeps running for a little bit before it finally crashes here. This is why stackoverflow.com's [help] requires you to show a [mre] that everyone else can cut/paste ***exactly as shown***, then compile, run, and reproduce your problem. See [ask] for more information. Until you do that, it is unlikely that anyone will be able to figure out your problem.
Comment: Any suggestions?
Comment: The first suggestion would be to use your text editor to reformat the shown code so that it's logically indented. Unindented code, like that, is difficult to read or understand. The best way to improve your chances of getting help on Stackoverflow is to make it as easy as possible for everyone else to understand the shown code.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I've just been having trouble loading in audio with xaudio2 can someone explain how to do it I tried so many times.
Answer: I can't seem to find the problem for a few reasons, mainly because I can't see your error message. But also, a tip I can give you is to indent your code properly, for example you could indent everything inside of the class by a tab or a few spaces, it doesn't really matter which as long as it is consistent. Speaking from experience, I found it easier to read my code when I started to indent the code inside definitions like public or private and protected. Just a simple piece of advice to help debugging in general. (Keep in mind, this is my first answer ever so please be nice but don't be afraid to give tips.)


How can I fully reallocate a 2D array in C?

Question: Being concise, I want to read a file and store the content in a 2D array, where the first dimension refers to the line and the second dimension to the character in the respective line. I do not know the number of lines and columns on each line beforehand.
The code I tried is as follows.
P.S.: I know the variables's names are not that good XD
FILE *filepointer = fopen(commandlineargument.filtersfile, "r");
int numboflines = 0;
int numbofchars = 0;
char **array = malloc(numboflines + 1);
array[0] = malloc(numbofchars + 1);
char currentchar;
while(fscanf(filepointer, "%c", &currentchar) != EOF)
{
    if(currentchar != '\n')
    {
        array[numboflines][numbofchars] = currentchar;
        numbofchars++;
        array[numboflines] = realloc(array[numboflines], numbofchars + 1);
    }
    else
    {
        array[numboflines][numbofchars] = '\0';
        numbofchars = 0;
        numboflines++;
        array = realloc(array,  numboflines + 1);
    }
}
array[numboflines] = '\0';
numboflines--;

With the code above, I can just get the value of array[0][0] and only before it gets reallocated two lines down (then array[0][0] points to null). I get Segmentation Fault later.
P.S.: I know the code above will only work properly if the last line ends with a \n
An example of the desired output:
File Content:
>Abcde
fghijk
>Lmno
pq

2D Array values:
array[0][0] = ">"
array[2][1] = "L"

And so on.
Comment: Just to be clear, you aren't talking about a 2D array, which would have type `char [A][B]` or, as a pointer, `char (*)[B]`. Rather, you're talking about a jagged array, i.e. an array of *pointers* to arrays.  It's often used for the same thing, but is not the same.
Answer: Your code is fine, but it has one omission and one mistake:
The mistake: memory space for each element of array is not a character, but a pointer to a character, so this line:
char **array = malloc(numboflines + 1);

should be rewritten as this:
char **array = malloc((numboflines + 1)*(sizeof *array));

The omission: after you end a line and realloc array, you must malloc the newly array element:
numboflines++;
array = realloc(array,  numboflines + 1);

Becomes:
numboflines++;
array = realloc(array,  (numboflines + 1)*(sizeof *array));
array[numboflines] = malloc(numbofchars + 1);

Comment: Oh. You are totally right. I' m not on the computer right now, but will test as soon as possible and accept your reply here.


Why is $scope not getting passed to controller?

Question: For some reason $scope.username is not being passed to my controller. On click registerUser() $scope.username is undefined. I do have a scope and the function is running just no $scope.username.
For example:
HTML:
 <input bs-form-control
     type="text"
     ng-model="username"
     label="Username"
     />

<button class="btn btn-primary" ng-click="registerUser()">Register</button>

controller:
    .controller("loginController", ['$scope',
        function ($scope) {
            $scope.registerUser = function(){
                console.log($scope.username) // <=== undefined!
            }

  }])

My controller is passed using state:
.state('register', {
            url: "/register",
            templateUrl: "/static/html/profile/register.html",
            controller: "loginController"
        })

Comment: Can you create a plunker with your code? Are you sure `bs-form-control` doesn't create a new isolated scope?
Comment: add the code where u included ng-controller in html...
Comment: the code is fine. Are you sure you've added ng-app ? http://plnkr.co/edit/Elwzp9aWyPPyxKR25MME?p=preview
Comment: @Srinath you don't need ng-controller if you specify controller in your router.
Answer: I think bs-form-control creates a new isolated scope. What you should do is either use objects on your scope (Does my ng-model really need to have a dot to avoid child $scope problems?)
or use the new "constroller as" syntax introducted in AngularJS 1.2. It works with ui-router too!
See this plunker: http://plnkr.co/edit/hkmMGbTtURSHDH84miiK?p=preview
Routing:
.state('register', {
    url: "/register",
    templateUrl: "/static/html/profile/register.html",
    controller: "loginController as loginCtrl"
})

Template:
<input bs-form-control type="text" ng-model="loginCtrl.username" label="Username" />
<button class="btn btn-primary" ng-click="loginCtrl.registerUser()">Register</button>

Controller:
Use this instead of $scope:
.controller("loginController", [
    function () {
        this.registerUser = function(){
            console.log(this.username);
        }
    }
])

Comment: Yes when I strip things out it works. bs-panel seems to messy things up, removed it. I will also looked at the DOT issues too


Who decides this type of things in LIVE cricket matches?

Question: One day I am watching ODI LIVE cricket in TV, they suddenly showed old bowling clip about some player and sometimes they will show net practice clips also in middle of LIVE ODI match. Who will decide to play this interrupting clips: commentators or ICC staff?
Commentators also talks about this type of clips immediately when they showed up on screen.
Answer: Neither - the broadcaster does.
The commentators watch the broadcast themselves so that they are accurately describing what the audience will see, and can explain why something has happened when the camera or microphones didn't pick up all of it.


Perform Math operations on previous and current row value in Snowflake

Question: I have a requirement wherein I need to perform few mathematical calculations on the previous and current value of a column in Snowflake.
For eg:
My Snowflake table has data like below

Here CHANGE_IN_FRUIT_COUNT and CHANGE_IN_VEG_COUNT fields are calculated as below
((current_val/previous_val)*100)-100
I would like to implement the same logic in my table as well.
Answer: SELECT
    date,
    fruits_sold,
    vegetable_sold,
    lag(vegetable_sold) over (order by date) as prev_vegetable_sold,
    lag(fruits_sold) over (order by date) as prev_fruits_sold,
    ((vegetable_sold/prev_vegetable_sold)*100)-100 as change_in_veg_count,
    ((fruits_sold/prev_fruits_sold)*100)-100 as change_in_fruit_count

FROM VALUES
    ('2022-01-01'::date, 18, 11)
    ,('2022-01-02'::date, 20, 16)
    ,('2022-01-03'::date, 25, 40)
    ,('2022-01-04'::date, 12, 14)
    ,('2022-01-05'::date, 18, 6)
    d(date, fruits_sold, vegetable_sold);

gives:

DATE
FRUITS_SOLD
VEGETABLE_SOLD
PREV_VEGETABLE_SOLD
PREV_FRUITS_SOLD
CHANGE_IN_VEG_COUNT
CHANGE_IN_FRUIT_COUNT

2022-01-01
18
11

2022-01-02
20
16
11
18
45.4545
11.1111

2022-01-03
25
40
16
20
150
25

2022-01-04
12
14
40
25
-65
-52

2022-01-05
18
6
14
12
-57.1429
50

which shows how the LAG is used to get prior value. And if you really don't need to reuse the value for other things, you can bundle it into a single line as Lukasz has shown:
SELECT
    date,
    ((vegetable_sold/lag(vegetable_sold) over (order by date))*100)-100 change_in_veg_count,
    ((fruits_sold/lag(fruits_sold) over (order by date))*100)-100 change_in_fruit_count
FROM VALUES
    ('2022-01-01'::date, 18, 11)
    ,('2022-01-02'::date, 20, 16)
    ,('2022-01-03'::date, 25, 40)
    ,('2022-01-04'::date, 12, 14)
    ,('2022-01-05'::date, 18, 6)
    d(date, fruits_sold, vegetable_sold);

DATE
CHANGE_IN_VEG_COUNT
CHANGE_IN_FRUIT_COUNT

2022-01-01

2022-01-02
45.4545
11.1111

2022-01-03
150
25

2022-01-04
-65
-52

2022-01-05
-57.1429
50
Answer: Using LAG:
SELECT DATE,
   (FRUITS_SOLD / LAG(FRUITS_SOLD)
                      OVER(ORDER BY DATE))*100-100 AS CHANGE_IN_FRUIT_COUNT.
   (VEGETABLE_SOLD / LAG(VEGETABLE_SOLD )
                      OVER(ORDER BY DATE))*100-100 AS CHANGE_IN_VEG_COUNT
FROM tab
ORDER BY DATE;

db<>fiddle demo


Gradient descent or not for simple linear regression

Question: There are a number of websites describing gradient descent to find the parameters for simple linear regression (here is one of them). Google also describes it in their new (to the public) ML course.
However on Wikipedia, the following formulae to calculate the parameters are supplied:
$$
{\displaystyle {\begin{aligned}{\hat {\alpha }}&={\bar {y}}-{\hat {\beta }}\,{\bar {x}},\\{\hat {\beta }}&={\frac {\sum _{i=1}^{n}(x_{i}-{\bar {x}})(y_{i}-{\bar {y}})}{\sum _{i=1}^{n}(x_{i}-{\bar {x}})^{2}}}\end{aligned}}}
$$
Also, the scikit-learn LinearRegression function, does not have an n_iter_ (number of iterations) attribute as it does for many other learning functions, which I suppose suggests gradient descent isn't being used?
Questions:

Are the websites describing gradient descent for simple linear regression only doing so to teach the concept of it on the most basic ML model? Is the formula on Wikipedia what most stats software would use to calculate the parameters (at least scikit-learn does not seem to be using gradient descent)?
What is typically used for multiple linear regression?
For what types of statistical learning models is gradient descent typically used to find the parameters over other methods? I.e. is there some rule of thumb?
Answer:
Linear regression is commonly used as a way to introduce the concept of gradient descent.
QR factorization is the most common strategy. SVD and Cholesky factorization are other options. See Do we need gradient descent to find the coefficients of a linear regression model

In particular, note that the equations that you have written can evince poor numerical conditioning and/or be expensive to compute. QR factorization is less susceptible to conditioning issues (but not immune) and is not too expensive.

Neural networks are the most prominent example of applied use of gradient descent, but it is far from the only example. Another example of a problem that requires iterative updates is logistic regression, which does not allow for direct solutions, so typically Newton-Raphson is used. (But GD or its variants might also be used.)
Comment: @anu Solving logistic regression in a non-iterative way requires minimizing a non-linear system of equations; in general, this is hard! This situation is analogous to the Abel-Ruffini theorem (no algebraic solution to roots of a 5th degree polynomial): we simply don't have direct computation methods to solve the system exactly. IIRC, this is discussed in *Elements of Statistical Learning*'s chapter about logistic regression. There's probably a thread somewhere on stats.SE about it as well, but I'm having trouble finding a good one.
Comment: @OliverAngelil The "normal equations" are indeed the jargon term for the linear system of equations that are the first order conditions for the ordinary least squares optimization problem.
Comment: 6 decimal places is more than enough for me!
Comment: In the link you supplied, does #3: the "Normal equations", refer to the equations in my question here? If not, what is the technical term for these equations?
Comment: So are the "normal equations" used in statistical software when there's only 1 predictor variable? For n = 100, I get identical (to 6 decimal places) b0 and b1 coefficients when I use the normal equations vs the LinearRegression function in scikit-learn. Although I'm confused: #3 in the link states that the "normal equations" are a "TERRIBLE" idea??
Comment: Numerically stable algorithms in double precision floating point should match the exact answer to 15 decimals. Matching to merely six implies a loss of 9 decimal digits of precision!
Comment: @OliverAngelil be careful, though. In general, you might have even fewer. Without careful implementation, you could get a garbage result and never know it.
Comment: I asked a follow-up question: https://stats.stackexchange.com/questions/343069/why-not-use-the-normal-equations-to-find-simple-least-squares-coefficients
Comment: @Sycorax, Can you suggest a reason why we can't use Normal equations method(or other direct solution methods) for logistic regression ( why you highlighted that it requires iterative updates! in my understanding the only difference between linear & logistic regression. is there objective functions!). Any explanation or pointing to the right resource would be helpful!


Looking for functions

Question: I am looking for functions that

have a minimum at 0 [edit: I meant f'(0)=0]
and are asymptotically linear

I came up with $\tanh(x) x$, which is fine, but more suggestions would be welcome.
(It's needed for data-fitting.)
Thx in advance, Jo
Comment: [Logistic functions](https://en.wikipedia.org/wiki/Logistic_function) are great for modeling.  They are asymptotically constant, though of course you can multiply by $x$ if you like.  If you set the lower bound at $0$...does that do what you want?
Comment: what about : $f(x) = \lvert  ax \rvert$ $\quad a \in \mathbb R$
Comment: Try $f(x):=\sqrt{x^2+\epsilon^2}-\epsilon$ for $0<\epsilon\ll1$.
Answer:
$$\quad\quad\quad\quad\quad f(x)=C|x|+g(x)$$

where $\text{argmin}(g(x))=0$ and $g(x)=o(x)$ for $x\rightarrow \infty$. For example $g(x)=0,\frac{1}{1+x^2},e^{-|x|}...$
Comment: Thx, and sorry for the initially wrong formulated question ... experimentalists ...
Answer: You should declare the domain in question, for example: $f: \mathbb R_{+} \to \mathbb R$ given by $f(x)=x$ works.
Otherwise, consider $g: \mathbb R \to \mathbb R$ given by  $g(x)=\frac{x^2}{x+1}$.
I thought of this by noticing that for positive $x$, $\frac{x^2-1}{x+1} \leq g(x) \leq \frac{x^2+1}{x+1}$.
Either way, to really see it, take $h(x)=x$ and, so
$\lim_{x \to \infty}\frac{g(x)}{h(x)}=\lim_{x \to \infty}\frac{x}{x+1}=1.$
Comment: Thx. The question-comments by @lulu and
Comment: @ChristianBlatter also work.

Looking for functions


Update Windows 2000 server standard to Windows 2000 server professional with AD

Question: I have a Windows 2000 Server Standard Edition server (that's right, standard) on a home network  with three systems doing basic file/print sharing (and a few other services).  Until recently the systems were running XP Home, but I now have them updated to either XP Pro or Vista Ultimate.  I also have a Server 2000 Advanced product key + license that I acquired at the same time as the Standard license.
Now that every machine on the network will support being joined to a domain I would like to update the server to Advanced with Active Directory.  Can I do this in place, or do I need to re-install from scratch?  What do I need to know to get Active Directory set up?
Comment: ... windows 2000?
Comment: Yes, 2000.  My 2000 licenses are legal, but I'm not in a position to pay for 2003 (or a computer that will run it).  It's this or switch to a linux-based server.
Answer: Windows 2000 Professional is the desktop edition, not server.  Are you talking about Windows 2000 Advanced Server?  You can run dcpromo on the server to install AD and make it a domain controller.
Comment: Ok.  Alas, no.  There is no upgrade path from Win2000 Standard to Win2000 Advanced server.  Here are the options: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q232039.
Comment: D'oh!  Yes, that should read 'Advanced'.  Can I do that to the current standard install?
Answer: There is no advantage to running Windows 2000 Server Advanced unless you have a lot of cpus / cores or a lot of ram. Windows 2000 Server Standard will run Active Directory. My guess is your current install utilizes all your hardware fine.
Run dcpromo to install Active Directory.
I would also say that Active Directory is probably overkill on a 4 computer network.
Answer: I agree, AD is overkill for a home network, especially if you need to linger on Windows 2000 to do it.  If you don't want to shell out, why not try out a Gnu/Linux distro?  One with lots of users (eg Ubuntu or Fedora) is likely to have more documentation or help available out there for setting up any given use case.


Google map Zooming

Question: I'm trying to zoom google map on particular pin from lat long.it working fine but i want to change pin image when zoom in on pin in swift.i have doing like this but there have putting 2 image on same lat long.
func zoom(lat: Double, long : Double){
        CATransaction.begin()
        CATransaction.setValue(1, forKey: kCATransactionAnimationDuration)

        // It will animate your camera to the specified lat and long
        let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 15)
        self.mapView!.animate(to: camera)
        let position = CLLocationCoordinate2D(latitude: lat,longitude: long)
        let marker = GMSMarker()
        marker.map = self.mapView
        marker.icon = UIImage.init(named: "pin-1")

         CATransaction.commit()
    }

Answer: You can put a function that detects changes in your zoom level then put a condition that will change the value of your marker icon.
Here is how my code looks like:
import UIKit
import GoogleMaps

class ViewController: UIViewController, GMSMapViewDelegate {
 let marker = GMSMarker()

    override func viewDidLoad() {

    }

   override func loadView() {
    // Create a GMSCameraPosition that tells the map to display the
        // coordinate -33.86,151.20 at zoom level 6.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        self.view = mapView

    mapView.delegate = self

        // Creates a marker in the coordinate of the map.

        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView
       marker.icon = UIImage(named: "pin_orange")
    }

//This detect the changes in the cameraposition
    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
          let zoom = mapView.camera.zoom
          print("map zoom is ",String(zoom))

        //put a condition here to change the icon of your marker
        if zoom > 6 {
            marker.icon = UIImage(named: "icon1")
        }else{
            marker.icon = UIImage(named: "icon2")
        }
    }
}

Hope this helps!

Google map Zooming


Reduce array of objects on key and sum value into array

Question: I have the following object:
data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'foo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'bar', type: 'buzz', val: 7 },
];

And used lodash map:
result = _.map(data, function item, idx){
  return {
    key: item[key],
    values: item.value,
  }
}

Which results in:
[
  { key: foo, val: 9 },
  { key: foo, val: 3 },
  { key: bar, val: 4 },
  { key: bar, val: 7 },
]

but now I'm trying to return:
[
  { key: 'foo', val: 12 },
  { key: 'bar', val: 11 },
]

I tried using reduce which seems to only output to a single object, which I could then convert back into an array, but I feel like there must be an elegant way to use lodash to go from my source data straight to my desired result without all of the intermediate steps.
I thought this was addressing my exact problem, but it seems like quite a bit of work just to have to convert the object into the desired array of objects outlined above.
Cheers.
Answer: A twist to the accepted answer that uses groupBy instead of reduce to do the initial grouping:
var result = _.chain(data)
    .groupBy('name')
    .map((group, key) => ({ key, val : _.sumBy(group, 'val') }))
    .value();

Comment: If es6 is allowed it's a whole different ball game :) For example `memo[obj.name = obj.val] += obj.val;`, removing the undefined check, and `return {key, val}`
Answer: Interestingly not straight forward, because of wanting to accumulate the value by key, but then wanting the key as a value of the property key. So somewhat like an inverse map reduce:
var result =
    _.chain(data)
        .reduce(function(memo, obj) {
            if(typeof memo[obj.name] === 'undefined') {
                memo[obj.name] = 0;
            }
            memo[obj.name] += obj.val;
            return memo;
        }, {})
        .map(function (val, key) {
            return {key: key, val: val};
        })
        .value();

For the sake of brevity in es6:
_.chain(data)
    .reduce((memo, obj) => {
        memo[obj.name = obj.val] += obj.val;
        return memo;
    }, {})
    .map((val, key) => ({key, val}))
    .value();

Comment: Brilliant. Thank you. The wonky end result is to feed into d3 which seems to expect quirky data structures at times.
Answer: You can get all the unique names using map() and uniq(), and then map() each name to get their respective sums using sumBy().
var result = _(data)
  .map('name')
  .uniq()
  .map(key => ({
    key,
    val: _(data).filter({ name: key }).sumBy('val')
  }))
  .value();

var data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'foo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'bar', type: 'buzz', val: 7 }
];

var result = _(data)
  .map('name')
  .uniq()
  .map(key => ({
    key,
    val: _(data).filter({ name: key }).sumBy('val')
  }))
  .value();

console.log(result);

Here is a non es6 version:
var result = _(data)
  .map('name')
  .uniq()
  .map(function(key) {
    return {
      key: key,
      val: _(data).filter({ name: key }).sumBy('val')
    };
  })
  .value();

Comment: Wow, very elegant!
Comment: Actually, I just realized your totals are incorrect. They're including all of the items.
Comment: You're totally right, I updated the answer. I guess grouping it would have been the optimal solution and then use sumBy().
Answer: Here's a simple non-lodash version.

const data = [{
    name: 'foo',
    type: 'fizz',
    val: 9
  },
  {
    name: 'foo',
    type: 'buzz',
    val: 3
  },
  {
    name: 'bar',
    type: 'fizz',
    val: 4
  },
  {
    name: 'bar',
    type: 'buzz',
    val: 7
  },
]

const result = data.reduce((acc, curr) => {
  const index = acc.findIndex(item => item.name === curr.name)
  index > -1 ? acc[index].val += curr.val : acc.push({
    name: curr.name,
    val: curr.val
  })
  return acc
}, [])

console.log(result)


Get the database content posted on a selected option into a form with single fields

Question: I have a form with a select. The options are coming from a database and displayed into the select.
The columns on the database are:
id, date, title, body.

On the select I display only date and title. In the same page I have a form with:
 date -> input text
 title -> input text
 body -> text area

I want that when an option from the select is clicked by the user the fields below will be update with the content kept from the selected option which contain the database data.
Now I have no idea how to get the data on the fields below.
My idea was to get the index of the option of the drop down. Is this possible?
EDIT COMPLETE CODE:

        geste n

            <input type="radio" name="n" id="new" value="nuova" onchange="shown(this.id);" <?php if($_POST['n'] == "nuova"){echo "CHECKED";} ?> />Nuova n
            <input type="radio" name="n" id="mod" value="modifica" onchange="shown(this.id);" <?php if($_POST['n'] == "modifica"){echo "CHECKED";} ?> />Modifica n
                <select id="sceltannascosta" style="display:none">
                    <?php
                        include("/login/flock/sql.php");
                        $conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
                        $a = "SELECT * FROM n ORDER BY id DESC";
                        $b = mysqli_query($conn, $a);
                            print '<option></option>';
                        while ($c = $b->fetch_object()) {
                            print '<option>'.$c->id.$c->data.$c->title.$c->body.'</option>';
                        }
                        $b->close();
                        $conn->close;
                    ?>
                </select>

                <select id="sceltan" style="display:none" onChange="showEntry(this,this.value);setndamod(this);">
                    <?php
                        include("/login/flock/sql.php");
                        $conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
                        $a = "SELECT * FROM n ORDER BY id DESC";
                        $b = mysqli_query($conn, $a);
                            print '<option></option>';
                        while ($c = $b->fetch_object()) {
                            print '<option>'.$c->data.' - '.$c->title.'</option>';
                        }
                        $b->close();
                        $conn->close;
                    ?>
                </select>
            <input type="submit" id="botenascostogeste" class="button">
        </form>

        c nuova n

        Data

        <form name="nuovan" method="post" action="cht.php?c=yes">
            <input name="datan" type="text" maxlength="10" size="8" value="<?php echo date(d.".".m.".".Y) ?>"> gg.mm.aaaa

        Titolo

                <input name="titolon" type="text" maxlength="50" size="50" value="<? echo htmlspecialchars("titolo n - lunghezza massima 50 caratteri") ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">

          6 caratteri rimanenti per il titolo

                <textarea name="teston"><?php if(isset($_POST['teston'])){echo $_POST['teston'];}else{echo 'Testo n con stile personalizzato';} ?></textarea>

        <input type="submit" name="c" class="button" onClick="document.getElementById('botenascostogeste').click();">
    </form>

    <?php
        $c = $_GET['c'];
        $titolon = $_POST['titolon'];
        $teston = $_POST['teston'];
        $datascritta = $_POST['datan'];

        if($c == 'yes'){
            if($_POST['titolon'] == NULL || $_POST['teston'] == NULL || $_POST['datan'] == NULL){
                echo '';
            } else {

                function verificadata($datascritta) {
                    list($dd,$mm,$yyyy)=explode(".",$datascritta);
                    if (is_numeric($dd) && is_numeric($mm) && is_numeric($yyyy))
                    {
                        return checkdate($mm,$dd,$yyyy);
                    }
                    return false;
                }

                if(verificadata($datascritta)){
                    $connessione = mysql_connect ($host, $user, $pw) or     //connect to the database
                        die('');
                    mysql_select_db ($db); //select the database
                    mysql_query("INSERT INTO n(data, title, body) VALUES ('$datascritta', '$titolon', '$teston')");
                    mysql_close($connessione);
                    echo (' Ok'); // It worked.
                } else { die('');
                }
            }
        }
    ?>

        Modifica n

        Data

        <form name="modifican" method="post" action="cht.php?modifica=yes">
            <input name="idmodifican" type="text" style="display:none" value="INSERIRE ID DI MODIFICA DEL DATABASE QUI">
            <input name="datanmodificata" type="text" maxlength="10" size="8" value="POST DATE FROM THE n TO MODIFY SELECTED"> gg.mm.aaaa

        Titolo

                <input name="modificatitolo" type="text" maxlength="50" size="50" value="POST TITLE FROM THE n TO MODIFY SELECTED" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">

          50 caratteri rimanenti per il titolo

                <textarea name="modificatesto">POST BODY FROM THE n TO MODIFY SELECTED</textarea>

        <input type="submit" name="modifica" class="button">
    </form>

    PHP I HAVE TO DO TO UPDATE THE n ON THE DATABASE (I'm able to do this part).

Comment: Neat idea! [What have you tried](http://whathaveyoutried.com/)?
Comment: Do you have a question about how this is accomplished? Because right it sounds more like you're asking someone to build this system for you, which is NOT what this site is about.
Comment: Use jQuery/Js (ajax) to populate the `select` options when the parent `select` index changes.
Comment: I added some text I tried without success...
Comment: can you provide more code detail so that i can try :)
Answer: for this you need to make ajax call.
 then use jquery to get the field set up depending upon the value selected in the select field you can set the value of the other fields  try this modify it according to your need

    <form>
        <select id="sel_opt">
        <?php
          $i = 1;
          foreach($valueformdb as $value)
          {
              echo "<option class=\"option\" id=\"opt_$i\">";
              echo $value;
              echo '</option>';
              $i++;
          }

        ?>
        </select>
       <input type="text" id="txt_date" value="" />
       <input type="text" id="txt_title" value="" />
       <textarea id="ta_body"></textarea>
    </form>

this is not the exact code you need to modify a bit, cause i don't know the exact thing you are trying to achieve


Column style alignment with floating

Question: HTML:

I want to have three columns that are made off elements 1 to 3, 4 to 6 and 7 to 9. As you could see in the fiddle, I've managed to make the first two columns. However the third column unexpectedly falls down ?
Does anybody know why the crimson boxes are not starting at the top right corner of the container even though they are floated right ?
http://jsfiddle.net/AleKS/e8G2C/
EDIT: I SHOULD CLARIFY, the HTML can't be changed!
EDIT2: Also a JS solution is ok, but it shouldn't be too long.
Comment: +1 for use of cornflowerblue
Comment: try playing around with css-column, eg: http://jsfiddle.net/8FLWZ/
Answer:
Does anybody know why the crimson boxes are not starting at the top
  right corner of the container even though they are floated right ?

Yeah - when you float elements, they don't automatically move UP.  They float left or right, but at the same vertical level that they would have been if they were not floated.  If you remove the floats from those divs, you can see that their natural position is below the other elements, so that's where they stay even after they are floated right.
You'll need to change the HTML structure (add some column divs) if you really want to do what you are trying to do.
Comment: yes I've concluded this also, but may be if someone could explain why exactly this happens, may be I could trick it somehow :)
Also a JS solution is also ok, however it shouldn't be too long ?
Answer: I believe the best solution here for you is to wrap each set of boxes in a another element. This should work better across browsers and cuts down the number of floated elements on the page. The less elements out of flow, the better.
Your elements should be positioned properly by adding column like so:

Here's a demo : http://jsfiddle.net/e8G2C/1/
Answer: I have an alternative which doesn't use floats. You could use box-sizing (supported in all good browsers and IE8+ - see CanIUse - box sizing) and make them all 33% width with display: inline-block. Ensure that you use the -webkit- and -moz- prefixes too, and make sure these are before the box-sizing property.
Note that you would have to ensure there is no white-space between the "cells" (else browsers will put a space between them) - you can do this in 2 ways I know of, either by putting the opening tag on the same line as the previous closing tag or putting an html comment at the end of each closing tag with the closing comment before the start tag:

    ...

    ...

OR...

    ...

    ...

This should achieve the layout you're looking for without those nasty floats.
Edit: One advantage of having all cells in one div (rather than having column or row wrappers) is that you can use @media queries to display different numbers of columns based on viewport size. This would be good if you have a set of articles or icons which bear no relation to one another.
Comment: unfortunately the HTML can't change. The only tool at my disposal is CSS and may be JS if its not too long :)
Comment: Well since jQuery is ok, you should be able to just create another div after the wrapper and the append all of the `box` divs to that. Something like (untested) `$(".container").hide().after(""); $(".container:visible").append($(".box"));`. This should equally get rid of any white space from new lines etc.
Answer: Given that this is almost like cheating, but if the deadline is approaching etc, etc.
Using javascript + jquery, it's rather trivial to insert three column divs around 1/3s of boxes.
This allows you to float the .col's instead of the boxes and all is kind of well.
var boxes = $(".container > .box");

var firstCol = boxes.length / 3;
var secondCol = 2 * firstCol;
var thirdCol = boxes.length;

(boxes.slice(0, firstCol)).wrapAll('

');
(boxes.slice(firstCol, secondCol)).wrapAll('

');
(boxes.slice(secondCol, thirdCol)).wrapAll('

');

I'll repeat for clarity that yea, this is a bit hackish, but the CSS solutions is also rather hackish for this sort of issue. Make sure that it dosen't look like horseshit on the off chance of js failing/disabled.
http://jsfiddle.net/Prjjb/

Column style alignment with floating


How to create Multi-pages in PDF file created with JSPDF from a html page

Question: I have a html page containing many text in tables. I'm using jspdf version 1.5 and higher and html2canvas libraries for creating a pdf when clicking on a button "generate the pdf".
The pdf is correctly generated.
Here is my code:
<!DOCTYPE html>

            <meta charset="utf-8">
            <title>Template 01</title>
            <link id="BootstrapCSS" rel="stylesheet" type="text/css" href="bootstrap.min.css">

<button type="button" class="btn btn-primary btn-lg" onclick="download()">Generate PDF</button>

                                ...

                                ...

                            ...

And the jsfiddle code: http://jsfiddle.net/amadese57/17npbu4y
My problem is the tables are sometimes broken at the bottom of the page (and at the top of the next page).
I would like to create automatically a break when the tables cannot be entirely on the page.
I don't know how to do that and if I can do that in the function pdf.html() that I used.
Could you help me please with that ?
Thanks in advance for your help
Answer: you have added the width of the PDF file, try to add the height of the PDF file. And add some more information to the meta data
Comment: can you provide the snippet?


Prevent view to urlencode contextual filters

Question: I have 2 views.
View 1 is a small exposed form which collects some data and has some contextual filters.
View 1 is linked to View 2, so when the form is submitted the form redirects to View 2 and inserts the collected data as contextual filters in the url.
The fields in the url are in the form of module[module_field] but they are printed as module%5Bmodule_field%5D in the addressbar in the browser when View 1 redirects to View 2.
But opening manually the same page with the decoded version module[module_field] works.
How can I prevent View 1 to urlencode the parameters for the contextual filters?
Answer: You need to use theme_links() function in template.php file of your theme. The original theme_links() function has this:
if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You should replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}


Using Partial Correlations and Correlations to calculate each other's values

Question: EDIT:
I have a correlation matrix with some known values and some unknown values, and i have a partial correlation matrix with the exact opposite known and unknown values.  For example, my correlation matrix is:
\begin{bmatrix}1&.1&.5&.5\\.1&1&.4&.4\\.5&.4&1&?\\.5&.4&?&1\end{bmatrix}
and my partial correlation matrix is:
\begin{bmatrix}1&?&?&?\\?&1&?&?\\?&?&1&0\\?&?&0&1\end{bmatrix}
How can I solve for the question mark values in the correlation matrix above?  In general, the method will need to work for larger matrices with question marks in the lower right quadrant of the correlation matrix.
thank you!
Original unedited question below, which while off topic, gives some motivational background for why I want to solve the above problem.

Everywhere I look, I can find calculators that measure partial correlations for 3 variables; a good example is this one: https://datatab.net/tutorial/partial-correlation .  However, I can't seem to find any such calculator in R.  Plus I need something that can handle more variables.
Currently the best approach I can find in R is to simulate a dataset with the known partial correlation coefficients and then I measure the covariance of the final data to get my answer for the needed correlation.
#generate x1 and x2 by drawing each from a standard normal distribution so they have the correlation specified by r, 0.1 in the case below.
x1x2 <- rnorm_multi(n=1000000, vars=2,mu=0,sd=1,r=0.1)

#generate y1 and y2, such that each of them has correlations with x1 and x2 as specified by
r, which in this case means cor(x1, y1)=0.5 and cor(x2, y1)=0.4
y1<-rnorm_pre(x1x2, r = c(0.5, 0.4))
y2<-rnorm_pre(x1x2, r = c(0.5, 0.4))

#finally, measure the covariance of y1 and y2 to get the correlation I'm interested in.
cov(y1,y2)
[1] 0.372786

This works, I've used my correlation matrix for x1, x2, and y to determine the correlation between two different ys correlated with the same x value
\begin{bmatrix}1&.1&.5\\.1&1&.4\\.5&.4&1\end{bmatrix}
Is there an R package to do these calculations?  If not, are there any other approaches you can recommend?
-thank you
Answer: Quick search on CRAN shows ppcor package. It mentions derivation of a general matrix formula of the semi-partial correlation for fast computation. Also upon reading the documentation, corpcor is mentioned as well to compute partial correlation from a given correlation matrix.Further reading. Below are examples directly from ppcor and corpcor package
# load corpcor library
library("corpcor")

# covariance matrix
m.cov = rbind(
  c(3,1,1,0),
  c(1,3,0,1),
  c(1,0,2,0),
  c(0,1,0,2)
)
#       [,1] [,2] [,3] [,4]
# [1,]    3    1    1    0
# [2,]    1    3    0    1
# [3,]    1    0    2    0
# [4,]    0    1    0    2

# corresponding correlation matrix
m.cor.1 = cov2cor(m.cov)

#       [,1]      [,2]      [,3]      [,4]
# [1,] 1.0000000 0.3333333 0.4082483 0.0000000
# [2,] 0.3333333 1.0000000 0.0000000 0.4082483
# [3,] 0.4082483 0.0000000 1.0000000 0.0000000
# [4,] 0.0000000 0.4082483 0.0000000 1.0000000

# compute partial correlations (from covariance matrix)
m.pcor.1 = cor2pcor(m.cov)
#         [,1]       [,2]        [,3]        [,4]
# [1,]  1.0000000  0.4000000  0.43852901 -0.17541160
# [2,]  0.4000000  1.0000000 -0.17541160  0.43852901
# [3,]  0.4385290 -0.1754116  1.00000000  0.07692308
# [4,] -0.1754116  0.4385290  0.07692308  1.00000000

# compute partial correlations (from correlation matrix)
 cor2pcor(m.cor.1)
#         [,1]       [,2]        [,3]        [,4]
# [1,]  1.0000000  0.4000000  0.43852901 -0.17541160
# [2,]  0.4000000  1.0000000 -0.17541160  0.43852901
# [3,]  0.4385290 -0.1754116  1.00000000  0.07692308
# [4,] -0.1754116  0.4385290  0.07692308  1.00000000

###############################################################

library(ppcor)
# data
y.data <- data.frame(
  hl=c(7,15,19,15,21,22,57,15,20,18),
  disp=c(0.000,0.964,0.000,0.000,0.921,0.000,0.000,1.006,0.000,1.011),
  deg=c(9,2,3,4,1,3,1,3,6,1),
  BC=c(1.78e-02,1.05e-06,1.37e-05,7.18e-03,0.00e+00,0.00e+00,0.00e+00
       ,4.48e-03,2.10e-06,0.00e+00)
)
# partial correlation
pcor(y.data)

# $estimate
# hl       disp        deg        BC
# hl    1.0000000 -0.6720863 -0.6161163 0.1148459
# disp -0.6720863  1.0000000 -0.7215522 0.2855420
# deg  -0.6161163 -0.7215522  1.0000000 0.6940953
# BC    0.1148459  0.2855420  0.6940953 1.0000000
#
# $p.value
# hl       disp        deg         BC
# hl   0.00000000 0.06789202 0.10383620 0.78654997
# disp 0.06789202 0.00000000 0.04332869 0.49299871
# deg  0.10383620 0.04332869 0.00000000 0.05615021
# BC   0.78654997 0.49299871 0.05615021 0.00000000
#
# $statistic
# hl       disp       deg        BC
# hl    0.0000000 -2.2232666 -1.916030 0.2831875
# disp -2.2232666  0.0000000 -2.552768 0.7298173
# deg  -1.9160295 -2.5527682  0.000000 2.3617433
# BC    0.2831875  0.7298173  2.361743 0.0000000
#
# $n
# [1] 10
#
# $gp
# [1] 2
#
# $method
# [1] "pearson"

# partial correlation between "hl" and "disp" given "deg" and "BC"
pcor.test(y.data$hl,y.data$disp,y.data[,c("deg","BC")])

# estimate    p.value statistic  n gp  Method
# 1 -0.6720863 0.06789202 -2.223267 10  2 pearson

# semi-partial (part) correlation
spcor(y.data)
#
# $estimate
# hl       disp        deg         BC
# hl    1.0000000 -0.5791734 -0.4991364 0.07377194
# disp -0.5505041  1.0000000 -0.6320921 0.18071040
# deg  -0.3180603 -0.4237587  1.0000000 0.39204867
# BC    0.0669124  0.1724434  0.5580398 1.00000000
#
# $p.value
# hl      disp       deg        BC
# hl   0.0000000 0.1324601 0.2079431 0.8621787
# disp 0.1573861 0.0000000 0.0926718 0.6684724
# deg  0.4426360 0.2954469 0.0000000 0.3367589
# BC   0.8749132 0.6830213 0.1506047 0.0000000
#
# $statistic
# hl       disp       deg        BC
# hl    0.0000000 -1.7402746 -1.410960 0.1811974
# disp -1.6152392  0.0000000 -1.998086 0.4500579
# deg  -0.8217590 -1.1459717  0.000000 1.0438882
# BC    0.1642694  0.4288224  1.647252 0.0000000
#
# $n
# [1] 10
#
# $gp
# [1] 2
#
# $method
# [1] "pearson"

Comment: thank you! i never knew about the corpcor package, and it has amazing features.  The problem for me, is it doesn't seem to be able to do calculations to solve for the missing matrix values.  It expects either a full correlation matrix to convert to partial correlations, or it expects a full partial correlation matrix to create the correlation matrix.  BUT, I have a mix of unknown values in each matrix. My correlation matrix is:
1, .1, .5,   .5,
 .1,  1, .4,   .4,
.5, .4,  1,   ??,
 .5, .4, ??,  1
and my pcor matrix is the opposite:
 1 ?? ?? ??
??  1 ?? ??
?? ??  1  0
?? ??  0  1


Degrees of freedom of a linear function of four independent random variables

Question: This is basically a modified version of a previously unanswered question I posed here, as I'm starting to have second thoughts about my methodology.
In summary, I have four random variables:
Xideal, Xnonideal, Yideal, Ynonideal,
which I have sampled a different number of times (> 30).
I am able to get the difference between Xideal and Xnonideal (denoted X) as well as the difference between Yideal and Ynonideal (denoted Y), which I can display as mean difference and standard error:
     N_ideal  N_nonideal  Mean Difference  Standard Error
X    64       62          23.5             1.56
Y    71       67          27.1             1.67

I'm now looking to get the p-value to assess the difference between X and Y. The t-statistic if I'm not mistaken is simply
$$
t_s = (27.1 - 23.5)/\sqrt{1.56^2 + 1.67^2};
$$
I guess the question is now, how do I calculate the degrees of freedom (df)?
Edit:
I calculated the standard error with the following formula
$$
ste_{X} = \sqrt{ \sigma^2_{X_{ideal}}/N_{X_{ideal}}+\sigma^2_{X_{nonideal}}/N_{X_{nonideal}}}
$$
Edit 2: Ok, to sum this up, I have four independent random variables, I need the df of
$$
Z = (X_{i}-X_{n}) - (Y_{i}-Y_{n})
$$
Looking at the Welch–Satterthwaite equation, would my answer be:
(if $$Nt_x = N_x - 1$$)
$$
v_Z = \frac{(Var(X_{i})+Var(X_{n}) + Var(Y_{i})+ Var(Y_{n}))^2}{(Var(X_{i}))^2/Nt_{Xi}+(Var(X_{n}))^2/Nt_{Xn}+(Var(Y_{i}))^2/Nt_{Yi}+(Var(Y_{n}))^2/Nt_{Yn}} = 236
$$
or
$$
v_Z = \frac{(Var(X_{i})-Var(X_{n}) - Var(Y_{i} )+ Var(Y_{n}))^2}{(Var(X_{i}))^2/Nt_{Xi}+(Var(X_{n}))^2/Nt_{Xn}+(Var(Y_{i}))^2/Nt_{Yi}+(Var(Y_{n}))^2/Nt_{Yn}} = 16
$$
Comment: @whuber Rasman's approach is to treat the prepost (ideal versus nonideal) differences as fixed and to determine if there is mediation by group (X versus Y). This approach is simply a two sample T-test between the pair-differences treating the differences between ideal and non-ideal as observed values.
Comment: Exactly how did you compute the standard errors?
Comment: the perennial question... see edit
Comment: The edit is unclear: each SE refers to *two* sets of data, so what exactly are $s_a^2$, $N_a$, $s_b^2$, and $N_b$?  (Underlying these prompts is a concern about pooled *versus* unpooled estimates.) BTW, there are enough data here that determining a precise value for degrees of freedom will make only a tiny difference.
Comment: @whuber The standard error is of difference between ideal and non-ideal
Comment: Yes, but *how is it calculated*?  See the [Wikipedia article on pooled variance](http://en.wikipedia.org/wiki/Pooled_variance) to see what the issue is.
Comment: @whuber I'm still not sure what you're referring to. X_ideal is a variable with it's own mean and std (sigma - calculated with an unbiased estimator). I have computed the random variable X = X_ideal - X_nonideal, whose properties are mean(X) = mean(X_ideal) - mean(X_nonideal), var(X) = var(X_ideal) + var(X_nonideal) and se(X) = sqrt(se(X_ideal)^2 + se(X_nonideal)^2). I have not pooled anything as of yet to resemble Wikipedia's article. Also note that the premise of pooled variance is that the true variance is assumed to remain the same which is not true between any of my RV
Comment: You have *four* variables but you provide only two standard errors. If you will not explain how you compute those SEs from your data, it will not be possible to know how to answer your question.
Comment: @AdamO I still don't see that: if what you say is true, then the *counts* for ideal vs non-ideal should match, but they don't.
Comment: @whuber I suspect you are over-thinking this. I have four independent random processes, each has its own mean, std, var and standard error (the traditional formula is s^2/N). These four random process were measured a a different number of time in an independent fashion: Xi has 64 measurements, Xn has 62 measurements (see table). I'm looking for the p-value of the random process Z = (Xi - Xn) - (Yi - Yn). I know what the t-stat is, I just need the df
Comment: Thank you--now I understand what you have done (almost, because you still haven't stated what formula you use for the SDs, but that doesn't really matter). You are asking a difficult question, because your statistic doesn't exactly have a t distribution. This appears to be a variant of the Behrens-Fisher problem and could be addressed with a Welch-Satterthwaite approximation: see http://en.wikipedia.org/wiki/Welch%27s_t_test. After you look at that, it would be understandable if you decided that determining the DF to the second decimal place (or more) might not be worth the effort :-).
Comment: @whuber I assumed he was restricting to a complete case analysis for paired observations. Thanks for bringing that to light.
Comment: @AdamO well I kindda am, and I am not trying to be a purist, but that is simply the crudest way of umming up the problem
Comment: @whuber ... which was why I didn't understand your obsession with the pooled calculations (note that I also said std was calculted using an unbiased estimator). I saw that page, as well as Welch-Satterthwaite, and all I want is a rounded value of the DF (but I do need a formula)...
Comment: Pooling changes the DF by one (and therefore could change the DF of the difference by two): that was why I was concerned.
Answer: There are a number of ways to approach this. Because of the balanced design, you were able to take differences between various values of $X = X_i - X_n$ and $Y = Y_i - Y_n$. (subscript $n$ meaning nonideal, not sample size).
You are treating $X$ and $Y$ as independent samples and testing the hypothesis $\mu_X = \mu_Y$ with an ordinary T-test for unequal standard errors. Using this methodology consistently, you can calculate standard errors using the Satterthwaite DFs.
However, had you had an unbalanced design, I would have advocated the regression modeling approach and a test of interaction. Using the full model:
$E[outcome | group, ideal] = \beta_0 + \beta_1 group + \beta_2 ideal + \beta_3 group*ideal$
versus the reduced model:
$E[outcome | group, ideal] = \beta_0 + \beta_1 group + \beta_2 ideal$
The benefit of doing this aside from allowing for unbalanced design is that you get explicit estimates of marginal effects, such as the group differences and the ideal versus nonideal differences.
Comment: Thank you for your response, and I saw that page, I'm just not sure I am interpreting it properly. I'm guessing the numerator is (Var(X) - Var (Y))^2 and the denominator's vi is (Ni - 1) for each of the four random variables?
Comment: Also, how do you define "balanced"?
Comment: The design would be unbalanced if some subjects did not measure their ideal or non-ideal performance. Their differences would be excluded from the final analysis with your approach, but the regression modeling approach could apply their information to estimation of group / ideal effects.
Comment: The trick to your problem is realizing that you've no longer got 4 variables, but instead have 2 variables: the differences in X and Y groups. The Ns would be the number of *differences* (e.g. w/ 50 subjects and 100 test results, you have 50 differences and hence N_i = 50 for that group)
Comment: Ok, I lost you on that last bit. In my case what is N_x and N_y ?


display achor tag in angular Js expressions

Question: I am not able to display the anchor tag inside the AngularJS expression. The problem is that when I am trying to display an anchor tag as an icon which is being fetched from the API, it's only displaying the raw path as
a href='../UserControls/DownloadRLCSFile.ashx?Path=\\dotnetdev\csv\RLCSDocuments\Registrations\ABACF\E.S.I.C. Registration\Sample.xlsx' target='_blank' download>

Please find the below code:

Regulatory Updates

            <asp:HyperLink ID="HyperLink1" NavigateUrl="~/RLCS_Connect/RegulatoryUpdateDetails.aspx?Subject={{bs.Subject}}" runat="server">{{bs.Subject}}</asp:HyperLink>
            {{bs.Document_Path}}	 //here i am facing the problem

Answer: Sounds like you might need ng-href:
https://docs.angularjs.org/api/ng/directive/ngHref
The wrong way to write it:
link1

The correct way to write it:
link1


$ \lambda \int_M |\text{grad} \; u|^2 dV_g\leq n \int_M |\nabla^2 u|^2 dV_g. $

Question: I am doing problem 5-15 in John Lee's "Introduction to Riemannian Manifolds" and I am somewhat confused as to what the hint is suggesting. The set-up is that $(M,g)$ is a compact Riemannian manifold (without boundary) and $u\in C^\infty (M)$ is an eigenfunction of $M$ (meaning $-\Delta u=\lambda u$) for some constant $\lambda$. We are asked to show that
$$
\lambda \int_M |\text{grad} \; u|^2 dV_g\leq n \int_M |\nabla^2 u|^2 dV_g.
$$
The hint is to consider the 2-tensor $\nabla^2 u-\frac{1}{n} (\Delta u)g$ and use one of Green's identities. But I am confused how one is supposed to apply Green's identities with this 2-tensor. Green's identities applies to functions and not tensors. Are we supposed to define $v=(\nabla^2 u-\frac{1}{n} (\Delta u)g )(\text{grad} \; u,\text{grad} \; u)$ and apply Green's to $v$?
Comment: Taking $u=v$ in the Green's identity gives: $$\int_M u\Delta udV_g=-\int_M |\mathrm{grad}\  u|^2dV_g$$ and in other hand: $$\int_M u\Delta udV_g=-\lambda\int_M u^2 dV_g.$$
Comment: So it is enough to show $$\lambda^2\int_M u^2 dV_g\leq n \int_M |\nabla^2 u|^2dV_g.$$ I don't know how to proceed.
Answer: The missing point is that $n\lvert\nabla^2u\rvert^2\geq(\Delta u)^2$.  There are two ways to see that.  One is to apply Cauchy--Schwarz to $\langle g,\nabla^2u\rangle$.  The other is to set $E=\nabla^2u-\frac{1}{n}(\Delta u)g$ and observe that
$$ 0 \leq \lvert E\rvert^2 = \lvert\nabla^2u\rvert^2 - \frac{1}{n}(\Delta u)^2 . $$
This is, of course, just the usual proof of Cauchy--Schwarz.
Now integrate the inequality $n\lvert\nabla^2u\rvert^2\geq(\Delta u)^2$, use the hypothesis $-\Delta u=\lambda u$, and use the divergence theorem to relate $\int u^2$ and $\int\lvert\nabla u\rvert^2$.
Comment: Thank you very much! I was hoping you could clear up one more confusion for me. I've seen many people interchange $\nabla u$ and grad $u$ despite these being very different (one is a form and one is a vector field). Is this just because we have an equality $|$grad $u|^2=|\nabla u|^2$?
Comment: You have to be careful, because some authors use $\nabla u$ to mean the gradient of $u$, while others use that symbol to refer to $du$.  Anyway, if a Riemannian metric $g$ is fixed, they are dual to one another by the formula $g(\mathrm{grad}\,u,X)=du(X)$.


How to notate free time in MuseScore

Question: Inspired by this question: Why does Musescore interpret Westergaard's A-flat as G? Seeking Clarification on Pitch Spelling

Let's say I would like to notate some sequence of notes in MuseScore, without any meter, barlines, possibly without any rhythm. I found a suggestion to adjust the measure's "actual duration" in the measure properties. So e.g. in order to place 10 consecutive whole notes, I could set the measure duration to 40/4. But it seems quite inconvenient, because if I don't fill all 10 notes, MuseScore will add rests, and if I exceed 10 notes, I will need to adjust the "actual duration" again. I wonder if there is an easier way to do it?
Answer: One approach is to split the sequence into smaller measures and hide time signatures and barlines for the passage, In MuseScore select the element and deselect 'visible' in the properties tab, then optionally deselect View > Show > Show Invisible. The advantage of doing this rather than putting everything into one huge measure is that the passage can be automatically broken over systems if needed. If you do this you'll need to make sure any accidentals are shown correctly.
The example can be engraved as ten 4/4 measures with hidden barlines.
Comment: "The advantage of [splitting the sequence into smaller measures with hidden time signatures] rather than putting everything into one huge measure is that the passage can be broken over systems if needed": Surely any software that supports unmeasured music also supports system breaks independently of measure boundaries, doesn't it?
Comment: @phoog This question is about MuseScore which doesn't yet offer unmeasured music. Finale now does offer unmeasured music and split measures, but even the Finale manual suggests my method as an alternative.
Comment: I see the advantage of this method, but there is also disadvantage in form of extra spacing that MuseScore (and probably Finale as well) adds to each invisible measure. But I guess one can adjust it somewhere.
Comment: @user1079505 In Finale at least it's adjustable.
Comment: @user1079505 Format > Style > Measure > set "Note to barline" and "Barline to note" to 0.
Answer: Free time is not directly supported as of v. 4.2.0; however, according to this bug report, the feature is planned for eventually.
The "large-enough time signature route" is one of the two commonly prescribed ways to accomplish free time. The other is the use Tools > Measures > Join selected measures.

How to notate free time in MuseScore


Incrementally Computing $\Sigma_t v_t$ Without Storing $x_i$, $v_i$, or $\Sigma_t$

Question: Motivation: I have a discussion with friends many days ago, at that time I think this problem is very easy so we directly skip, later I realize I cannot solve it XD. The problem is:
Given a sequence of vectors $x_1, x_2, \ldots, x_t$ and $v_1, v_2, \ldots, v_t$ in $\mathbb{R}^p$ in an online fashion, I'm interested in computing the product of the sum of outer products $\Sigma_t$ with $v_t$, where
$$
\Sigma_t=\sum_{i=1}^t x_i x_i^T
$$
Specifically, the term of interest is $\Sigma_t v_t$.
However, there are constraints for memory (only O(p)):

I cannot store all individual vectors $x_i$ or $v_i$ for $i<t$. Finite them is ok.
I cannot store the matrix $\Sigma_t$.
The vector $v_i$ can change from one time step to the next.

Given these constraints, is there a way to compute $\Sigma_t v_t$ incrementally as each new $x_t$ and $v_t$ arrives?
I'm looking for an efficient approach that uses minimal storage and captures the effect of the changing $v_t$ without explicitly storing past data or the matrix sum. Any suggestions, insights, or relevant literature would be greatly appreciated!
When $v_t$ is unchanged over time, we definitely have a solution by introduce some ancillary variables. But I fail for the varying $v_t$ case.
Comment: What *can* you store??
Comment: $\Sigma_t$ seems to be a $t\times t$ matrix. So for $\Sigma_tv_t$ to make sense, $v_t$ should be a vector of length $t$, no? Specifically, the sequence $(v_t)$ needs to consist of vectors of increasing length: $v_1\in\mathbb{R}^1$, $v_2\in\mathbb{R}^2$ and so forth.
Comment: ... in which case the question of course is whether $v_t$ is just $v_{t-1}$, to which we concatenate a new $t$-th component, or some completely new vector. In the latter case, you will likely at least need to store $v_{t-1}$ for an online algorithm (though probably not $v_1, \dots, v_{t-2}$).
Comment: both $x_t,v_t$ are p dimensional vector, $\Sigma_t $ is positive semidefinite matrix with dimension p by p. If we can store $v_t$ and $v_{t-1}$, it is ok because store 2p, 3p, 4p are just constant times p, they are all $O(p)$, but even we store finite them, it seems still not work if I do not store all of them.
Comment: I modify the constraint 1, but this is still quite ideal, maybe impossible...
Answer: You ask how to perform a sequential update of the vector sequence
$$\sigma_n = \sum_{t=1}^n \Sigma_t v_t = \sum_{t=1}^n \sum_{i=1}^t x_i x_i^\prime \, v_t.$$
To update $\sigma_n$ to $\sigma_{n+1}$ you will add their difference,
$$\sigma_{n+1} - \sigma_n = \sum_{i=1}^{n+1} x_i x_i^\prime v_{n+1} = \left(\sum_{i=1}^n x_ix_i^\prime\right)v_{n+1} + x_{n+1}\left(x_{n+1}^\prime v_{n+1}\right).\tag{*}$$
Consequently, if you maintain a data structure that includes
$$A_n = \sum_{i=1}^n x_i x_i^\prime$$
which (because it is symmetric) requires storing only $p(p+1)/2$ coefficients, then the total storage for all variables in the update is $p(p+1)/2$ (for $A_n$) plus $p$ (for $\sigma_n$) plus $2p$ (for $x_{n+1}$ and $v_{n+1}$ plus $1$ (for accumulating $x_{n+1}^\prime v_{n+1}$), summing to $p^2/2 + 7p/2 + 1 = O(p^2).$
This is the best you can possibly do, because clearly the update depends on $A_n$ and if you don't store full information about it, then for sufficiently large $p$ you can construct an alternative matrix $B_n$ that yields the same value of your data structure but a different value of $B_n v_{n+1}$ for some nonzero possible value of $v_{n+1}.$

To show this is not mere speculation or opinion, I will offer a definite statement and a proof.
Proposition. Let the available storage asymptotically be less than $O(p^2)$ and suppose you can store piecewise differentiable functions of the data (which is all you can do in standard models of computing).  Then there exists a $p$ for which you cannot sequentially update $\sigma_n$ forever.
Proof. The assumptions imply the set of possible values you can store are at most a countable union of differentiable manifolds (possibly with boundaries and corners).  Let the largest dimension of any component of this union be $d(p).$  We have supposed that for any number $\lambda \gt 0,$ there exists a sufficiently large $p$ for which $d(p) \lt \lambda p^2.$
Formula $(*)$ shows that $\sigma_n$ can be updated with $O(p)$ storage plus the amount of storage required to compute $A_n v_{n+1}$ for arbitrary vectors $v_{n+1}$.  In other words, any possible updating algorithm will be capable of computing every possible $A_n v_{n+1}$ with at most $O(p)$ extra storage.  The map $v\to A_n V$ defines a symmetric endomorphism of $\mathbb R^p.$  The set of such transformations is a differentiable submanifold of $\mathbb R^{p^2}$ of dimension $p(p+1)/2.$   Applying the first observation to the case $\lambda = 1/2$ shows we cannot store every possible element in this set, implying it is not possible to update $\sigma_n$ with certainty for all $n$ with this value of $p,$ qed.
Comment: Thanks whuber, I agree this one should be the best we can possibly do.


Erro ao popular Array com VueJS + Firebase

Question: Sou Dev RoR e estou em meus estudos iniciais com VueJS. Para tanto, iniciei a criação de uma TodoList com Firebase para a persistência de dados e um problema me ocorreu.
Criei um função para retornar os dados do FireBase.
https://github.com/luizpicolo/ToDo.list/blob/8e2ba8cba714a9541ef0c91cf38d4ae69ae915c7/js/database.js#L22
Logo, quando há uma alteração ou inclusão de algum dado no banco, o Firebase me retorna todos os dados que são apresentados por meio dessa instância do Vue.
https://github.com/luizpicolo/ToDo.list/blob/8e2ba8cba714a9541ef0c91cf38d4ae69ae915c7/js/main.js#L1
Porém, ao fazer a primeira  chamada da função listTasks(), na linha 4 no link acima, ela me retorna os dados corretamente. Mas, quando há a alteração, o vetor não é montado novamente, mas sim concatenado com os valores novos, ou seja, tenho dados duplicados.
Como faria para que, sempre quando houve dados novos ou alteração, o Vue não concatene o vetor?
Acredito que seja algo do Vue por meio de todos os testes que fiz até o momento. Mas isso é apenas um achimos inicialmente.
Comment: @AndersonCarlosWoss Entendi como sendo Developer Ruby On Rails
Comment: Não edite uma questão para mostrar que foi resolvida. Ao invés disso, coloque a resolução como resposta e aceite-a.
Comment: O que é Dev RoR?
Comment: Conforme suas orientações, o tópico foi corrigido. Obrigado pela dica  @RosárioPereiraFernandes
Answer: O erro era na função quer retornava os dados. Ao invés do método on eu utilizei o método once. Funcionou da forma que queria. [https://firebase.google.com/docs/database/web/read-and-write?hl=pt-br][3]
function listTasks(){
    var tasks = [];
    var listTasks = database.ref('tasks');
    listTasks.once('value', function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
         tasks.push(childSnapshot.val());
      });
    });

    console.log(tasks);
    return tasks;
}

Answer: Viva,
Parece-me que o problema está no facto do array tasks não estar a ser limpo antes de obteres os dados da base de dados.
Experimenta assim:
function listTasks(){
  var listTasks = database.ref('tasks');
  listTasks.on('value', function(snapshot) {
    var tasks = [];
    snapshot.forEach(function(childSnapshot) {
       tasks.push(childSnapshot.val());
    });
});

Comment: Infelizmente esse não é o problema. Já havia testado essa função desta forma e nada funcionou.
Answer: methods: {
  addTodoInList: function(){
    this.tasks = []
    writeTask(11, "teste 7", "12/12/2012", 'Lorem Ipsum 3');
  }
}

function listTasks(){
  var tasks = []; // REMOVA ESSA LINHA
  var listTasks = database.ref('tasks');
  listTasks.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
       tasks.push(childSnapshot.val());
    });
  });

  console.log(tasks);
  return tasks;
}

Comment: Respostas só com código dão muito pouco valor à comunidade. Vale lembrar que o objetivo no StackOverflowPT é não só mostrar qual o problema que existe, assim como o que fazer para ultrapassa-lo, e até quais outros possíveis obstáculos. Em suma queremos evitar os que o autores das perguntas se limitem a copiar código sem saberem o que estão a fazer.
Comment: Está certo, é que falei com o autor do tópico em outro canal, por isso só postei o código, vou corrigir isso.


When trying to generate Java Tests in VS Code I get "Cannot find a valid classpath entry to generate tests."

Question: I try to use JUnit tests in a Java project in VS Code.
My setup
1) JDK 17
2) Via the Extension Pack for Java I have a its extensions installed including the following:

Language Support for Java by Red Hat
Debugger for Java
Java Test Runner

3) I went to the Testing pane and downloaded (via the wizard) the testing JARs hamcrest-core-1.3.jar and junit-4.13.2.jar into the lib directory.
4) I made sure in Classpath Configuration the two JARs are listed under Referenced Libraries.
5) The project contains a main unqualified App.java with a main method and a qualified package like org.mydomain.calculations. The method(s) which I want to test are in the qualified package!
What I did then
In a class of the qualified package I right-click and choose from the context menu Source Actions..., then Generate Tests.... From the appearing project chooser I select the current project -- and then I get the error ballon "Cannot find a valid classpath entry to generate tests".
This confuses me, because I did add the JUnit JAR to the classpath.
What else can I do to make generating tests in the qualified package work?
Answer: Please install all extensions in the Extension Pack for Java and use Clean the java language server workspace in the command palette to clean up the Java workspace.

Follow the steps below to implement a minimal test example in vscode.

Open the command palette(Ctrl+Shift+P) and create a java project

Add an AppTest.java file

Select Enable Java Tests in the Testing panel

select JUit

It will automatically download third-party packages. The tests can then be run.
Comment: This works, thanks. - But how can I make my real project using the testing framework? The real project is now not even anymore recognized as a Java project! (Probably because of the "Java: Clean Workspace" action...)
Comment: I have updated the question to explain that the problem might lie in the setup with a qualified package.
Comment: Would you mind sharing some of your code, or provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)? It's a good idea to attach your folder structure if you can.
Comment: Sorry for the delay. Today I'll put a reprex together.
Comment: I created a small example - and it just works (for the test generation). This means for me, that your answer is correct. :-)
Comment: For all people coming here later: The intermediate problems I had were related to the fact that I'm on Linux and I used symlinks in the path to the project folder. (See GitHub issue [JUnit tests not found on symlinked project folder](https://github.com/microsoft/vscode-java-test/issues/630)) As soon as I switched to the canonical path to open the folder in VS Code it all worked as expected.


Get request returns 500. The routing in my MVC project seems to be correct, but I am unable to investigate further

Question: I'm having a react app that performs a get request to my MVC app, and it works fine for most controllers/actions, but I have made a new one, and it only returns 500.
For testing I've just made some simple data to make sure it can connect. So an request Url like: "api/internal/v1/new/getsomestuff"
Like with the other controllers, it inherits from a base API controller which is like this:
<code>[Produces("application/json")]
[Route("api/internal/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[ProducesResponseType(typeof(ProblemDetails), 400)]
[ProducesResponseType(typeof(ProblemDetails), 401)]
[ProducesResponseType(typeof(ProblemDetails), 403)]
[ProducesResponseType(typeof(ProblemDetails), 404)]
[ProducesResponseType(typeof(ProblemDetails), 409)]
[ProducesResponseType(typeof(ProblemDetails), 500)]
[Authorize(AuthPolicies.InternalApi.InternalApiPolicy)]
[BffApi]
public class InternalApiController: ControllerBase
{
   // some stuff
}
</code>
Any I have my new controller:
<code>[ApiVersion("1")]
public class NewController : InternalApiController
{

    public NewController()
    {
      // some stuff
    }

    [HttpGet("getsomestuff")]
    [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
    public async Task<IActionResult> getsomestuff()
    {
        return Ok("success");
    }

}
</code>
As I explained, this returns 500, and a breakpoint on the action is never hit. If I add this action to an existing controller and update the URI, it works. So I suspected that it was a problem with the routing. So I checked the startup.cs in the project, which contains this code:
<code>  endpoints.MapControllers();
</code>
When I inspect it I see that my NewController has it's action registered, and the routing path is correct.
What should I do next? Have I missed something obvious? If not, how can I find out more?
Answer: The routing was fine. There was a problem with the interface of the controller.


Problemas no JSONObject no Android

Question: Olá, pessoal ! Estou com uma dúvida relacionada ao JSON, é a primeira vez que estou mexendo com JSON no Android e estou com várias dúvidas, mas eu vi um tutorial no YouTube e consegui montar essa função
<code>private void jsonParse(String url) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("nome");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject nome = jsonArray.getJSONObject(i);
                    String name = nome.getString("nome");

                    razao.append(name);
                    razao.setText(name);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "CNPJ Inválido ! ", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError erro) {
            erro.printStackTrace();
        }
    });

    mQueue.add(request);
}
</code>
Eu sei que em .getJSONArray(nome do JSON), mas o WebService que me retorna as informações não tem nome para percorrer um Array, preciso do "nome:" e ele está sozinho. Poderiam me ajudar ?
Retorno do Android Studio:
W/System.err: org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of type java.lang.String cannot be converted to JSONArray
JSON
{
"atividade_principal": [
{
"text": "Portais, provedores de conteúdo e outros serviços de informação na internet",
"code": "63.19-4-00"
}
],
"data_situacao": "01/09/2004",
"complemento": "ANDAR 17A20 TSUL 2 17A20",
"tipo": "MATRIZ",
"nome": "GOOGLE BRASIL INTERNET LTDA.",
"uf": "SP",
"telefone": "(11) 2395-8400",
"email": "email@example.com",
Link: https://www.receitaws.com.br/v1/cnpj/06990590000123
Comment: Se precisar de mais informações no código, podem pedir, por favor ! Realmente preciso de ajuda e não consigo me entender nessa parte
Answer: Aparentemente, você está tentando pegar a chave "nome", que não é um array/lista, e transformar em um objeto JSONArray. Isso é um problema porque a função não vai conseguir converter uma string em um objeto JSONArray. Acredito que você poderia usar simplesmente getString("nome"). A chave "qsa" sim é um array e você poderia utilizar getJSONArray("qsa") para iterar e obter a chave nome de cada objeto desse array.
Espero ter entendido direito seu problema, porque confesso que não sou experiente em Java. rsrs
Comment: Obrigado ! Não sabia dessa parte ! Mas ele continua dando erro de conversão de String.

public void onResponse(JSONObject response) {
                try {
                    JSONObject jsonObject = response.getJSONObject("nome");
                    jsonObject.toString();

                    razao.append(jsonObject.toString());
                    razao.setText(jsonObject.toString());

W/System.err: org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of type java.lang.String cannot be converted to JSONObject

Problemas no JSONObject no Android


Conteúdo do footer responsivo

Question: Gostaria de ajuda no meu código para tornar as colunas "conteudo" do footer responsivo.
Segue o código abaixo:

*{
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    margin:0;
    padding: 0;
}

*.*:before, *:after{
    box-sizing: border-box;
    font-family: sans-serif;
    font-size: 14px;
    line-height: 1.5;
}

body,html{
    width:100%;
    height:100%;
}

footer{
    bottom: 0px;
    width: 100%;
    color: #000000;
    height: 200px;
    margin-bottom: 20px;
    background-color:#000;
    color:#fff;
    clear: both;
    padding: 40px;
    position:absolute;
    z-index: 10;
}

footer:after{
    content: '\00a9  Infogyba Soluções em Ti  ';
    position: absolute;
    width: 100%;
    color: #8c8c96;
    line-height: 40px;
    font-size:1em;
    font-weight:600;
    font-family:'Arial',sans-serif;
    text-align: left;
    bottom:0;
    display: block;
}

.endereco,.telefone{
    float:left;
    width: 33.33%;
    border-right: 1px;
    margin-right:15px;
    border-right-style: outset;
}

.redes sociais{
    float:left;
    width: 33.33%;
}

@media only screen and (max-width: 480px) {
    .endereco, .telefone, .redes-sociais  {
        float: none;
        width: 100%;
    }
}

footer h1,h2{
    font-size:1em;
    font-weight:600;
    font-family: 'Arial',sans-serif;
    text-align:center;
    display:inline-block;
}

footer .redes-sociais  a:hover{
    display: inline-block;
    position: relative;
    -webkit-animation-name: rotacao; /* Chrome, Safari, Opera (nome da animação)*/
    -webkit-animation-duration: 2s; /* Chrome, Safari, Opera (Duração da animação)*/
    animation-name: rotacao; /* nome da animação */
    animation-duration: 2s; /* Duração da animação */
}

@keyframes rotacao {
    from {transform: rotate(1deg);}
    to {transform: rotate(360deg);}
}
@media screen and(max-width:768){
    footer{
        padding-bottom: 3em;
    }
}

Nosso endereço:

Rua blalal, 132 - Irajá

Rio de Janeiro Cidade - RJ.

Cep: 21300-630

Consulte-nos:

Telefone: (21)9999-9999

Horário de Atendimento

de Seg a Sexta: 08:00 as 17:00

Fale conosco nas Redes Sociais

Email:

firstname.lastname@example.com

Comment: Eu acho que o problema é as scções estarem com posição absoluta, apague isso e coloque `float:left;` a ver se resulta
Comment: não deu certo exclui o position absolute e coloquei o float:left.
Comment: O mais facil é postar o código relevante em vez de imagens, para ser mais facil quem o quer ajudar testar
Comment: Tem um erro muito grave no seu HTML, está a fechar a `` já depois do `` deve fecha-la emediatamente antes do ``
Answer: Tem muita coisa que não precisa e é muito mais simples do que fez, isto é só um exemplo, apenas pegando no seu HTML, pode testar aumentando e diminuindo a janela do browser (navegador) aqui, determinei que o footer muda de display quando janela <= 480px:

.endereco, .telefone, .redes-sociais  {
  float:left;
  width: 33.33%;
}

@media only screen and (max-width: 480px) {
  .endereco, .telefone, .redes-sociais  {
     float: none;
     width: 100%;
   }
}

Nosso endereço:

Rua blalal, 132 - Irajá

Rio de Janeiro Cidade - RJ.

Cep: 21300-630

Consulte-nos:

Telefone: (21)9999-9999

Horário de Atendimento

de Seg a Sexta: 08:00 as 17:00

Fale conosco nas Redes Sociais

Email:

firstname.lastname@example.com

Note que o comprimento das secções (33.33%) é apenas 100% / 3 secções
Comment: Cara muito  obrigado , ficou muito bom, vlw mesmo.
Comment: De nada @ClaytonCampos. Boa sorte

Conteúdo do footer responsivo


Retrieving cookie and array values in JSTL tags

Question: While retrieving cookies I need to use:
<c:forEach items="${cookie}" var="currentCookie">
    ${currentCookie.value.name}

</c:forEach>

But, while using custom arrays, why we need to skip the .value function?
<c:forEach items="${myList}" var="myList">
    ${myList.name}

</c:forEach>

Cookie contains a .getValue function() which returns the content of the cookie in string format, so how does using currentCookie.value.name work?
Answer: The ${cookie} points to a Map<String, Cookie> with the cookie name as map key and the Cookie object as map value. Every iteration over a Map in <c:forEach> gives you a Map.Entry back which in turn has getKey() and getValue() methods. Your confusion is that the Cookie object has in turn also a getValue() method.
<c:forEach items="${cookie}" var="currentCookie">
    Cookie name as map entry key: ${currentCookie.key}

    Cookie object as map entry value: ${currentCookie.value}

    Name property of Cookie object: ${currentCookie.value.name}

    Value property of Cookie object: ${currentCookie.value.value}

</c:forEach>

It's a Map<String, Cookie> because it allows you easy direct access to cookie value when you already know the name beforehand. The below example assumes it to be cookieName:
${cookie.cookieName.value}

Your list example is by the way invalid. The var should not refer the same name as the list itself.
Comment: I suppose you meant ${cookie} instead of ${cookies}, as running it with ${cookies} outputs empty rows
Comment: Right, I just copypasted your original code, I fixed the answer :)
Comment: thanks for your help, also when we directly use cookie.cookieName.value, does it internally resolve to cookie.get(cookieName) to get the matching pair? Isn't this unusual on how EL tags function
Comment: Yes. See also http://stackoverflow.com/questions/5395308/read-data-from-hashmap-using-jstl-tag-in-jsp-without-using-for-each-or-for-loop and http://stackoverflow.com/tags/el/info The job is by the way done  by container's builtin `MapELResolver` http://docs.oracle.com/javaee/6/api/javax/el/MapELResolver.html


TinyMCE buttons by content type

Question: I installed tinyMCE with IMCE in my Drupal 7 site. I'm finding a way to show different buttons in tinyMCE editor by each content type. For example, the image button is displayed for the Article content type, but it will not be displayed for my custom content type.
Is there a way to set this up with the existing module?
Answer: You need 2 text-formats.  Allow "Image" in tinyMCE profile of one text-format and not allow it for the other.
To set fixed text-format to each text-area field, you can use Better Formats module.  Download from http://drupal.org/project/better_formats and install it.
In "Managed Field" page of your text-area field, check "Filtered text (user selects text format)" and "Limit text format".  You will see all your defined text-formats with leading check-boxes.
Click the check-box of a text-format and save.  In your "Add Content" page, you will see your text-area is assigned with respective tinyMCE editor.
Comment: You really helped me. Thanks! When I installed Better Formats, I could chose "Allowed formats" in the field configuration page of the respective content type. But one thing is that the module is still beta release.

TinyMCE buttons by content type


Proof of a practical method of a natural number's equation

Question: Example Question :
$3m + 4n = 70$,  $m,n$ are natural numbers. How many values can $m$ have?
I learned a method to solve this kind of problem, but I've never thought about that before.
for
n=1  => m=22
n=4  => m=18
.
.
n=16 => m=2
So n increase 3 by 3 and m decrease 4 by 4
How do we proof this works everytime?
Answer: Once you have an initial solution, say $(m_0, n_0)$ such that
$3m_0 + 4n_0 = 70$
then you can add (or subtract) any multiple of $3$ to $n_0$ as long as you subtract (or add) the same multiple of $4$ from $m_0$. This is because
$3(m_0-4k) + 4(n_0+3k) = 3m_0-12k + 4n_0+12k = 3m_0 + 4n_0=70$
Answer: You have the equation $3m + 4n = 70$ and you have an "initial" solution
$(m_0, n_0) = (22, 1)$. How do we characterize all of the other solutions.
Subtract $3m_0 + 4n_0 = 70$ from $3m + 4n = 70$
\begin{array}{c}
    3m   &+ &4n &= &70 \\
    3m_0 &+ &4n_0 &= &70 \\
\hline
   3(m-m_0) &+ &4(n-n_0) &= &0
\end{array}
So $3(m-m_0) = -4(n-n_0)$.
Since $3$ divides $3(m-m_0)$, then $3$ divides
$-4(n-n_0)$.
Since $3$ and $4$ are relatively prime to each other, it follows that
$3$ divides $n - n_0$
So, for some integer, $t$, $n-n_0 = 3t$.
Hence $n = n_0 + 3t$.
Substituting $n = n_0 + 3t$ into $3(m-m_0) = -4(n-n_0)$, we get
\begin{align}
   3(m-m_0) &= -4(n-n_0) \\
   3(m-m_0) &= -4(n_0 + 3t -n_0) \\
   3(m-m_0) &= -12t \\
   m - m_0 &= 4t \\
   m &= m_0 - 4t
\end{align}
So, in general, $(m, n) = (m_0 - 4t, n_0 + 3t)$.
To check that this works every time, you can substitute
 $(m, n) = (m_0 - 4t, n_0 + 3t)$ into $3m + 4n = 70$.
\begin{align}
   3m + 4n &= 70 \\
   3(m_0 - 4t) + 4(n_0 + 3t) &= 70 \\
   3m_0 - 12t + 4n_0 + 12t &= 70 \\
   3m_0 + 4n_0 &= 70 \\
   70 &= 70
\end{align}