Glancing at my hands while playing piano - how much is too much?

Question: Although I've noticed a huge improvement in my ability to sight read recently, I'm also noticing that I really have to look at my hands every bar or so to get the hand position correct.  As long as I'm going slowly this is ok, but I want to be able to sight read at speed.  I'm not sure if the reason I can't is because of my need to look at my hands, or just a general need for more experience at the keyboard.
So I have two questions:

How much is too much? Would, for example, a pro just sit down and never look at their hands, or is there some glancing involved?
Is it a good strategy to just open a simple piece that I'm familiar with and try to play by touch? Should I instead try to do this at all times, even though it may lead to very wrong notes at times?
Comment: Well, I expect the less  the better.  I sometimes practise in the dark to avoid the temptation.
Comment: Something that can help is to sing the melody along in your head, and your fingers might actually follow.
Comment: Unless the music stand is in a crazy position, you can probably see your hands in your peripheral vision anyway. If you *have* to look to "get your hand positions correct" in *every bar*, that seems too much. On the other hand, actively trying *not* to look may be just as distracting, mentally, as looking!
Answer: Learning to sight read is mostly about two things: keeping your eyes on the dots, and not stopping. It's about trusting your hands not to go off on their own adventure and it's about developing confidence. It's not really about sounding good; that comes later. It's a slippery slope once you start to look, because each time you look you're wasting valuable trust and confidence-building opportunities while feeding your filthy peeping habit.
You're probably going to execute some stinkingly dodgy fingerings, but so be it: press on, press on!
The best sight readers scour the chart for dangerous sections before they start to play. Yes it is a very good idea to go through simple pieces without looking at your hands. It's also a good idea to only go through a piece a couple of times and then 'chuck it away' and attack a new piece. You are not trying to learn the piece or memorise it. You are simply reading it: learning to process dots.
Comment: I'm glad to see your 'not stopping' advice. My feeling has been hitting a wrong note is forgivable, but stopping is a sin! Better to miss a note than stop the music altogether.
Answer: There are, and have been, some great blind pianists. I say this in an answer to point out that they don't look at the keys. No, they don't look at the dots either, but that's another matter! Generally the next note/s you're going to play after the one/s you're on will be less than an octave away. So, familiarise yourself with how much of a stretch a 6th is, or which finger will play a 3rd above the note your index finger is already on.
The more you sightread, the less you'll need to look at fingers and keys. A nice little practice idea is to play a note with a particular finger/thumb, then check which other notes are within easy reach, and make a mental note of how each gets played. Start with diatonics, for ease. And one hand at a time is not cheating with more tricky pieces, and slowly of course, but keeping in time, which is the other half of sightreading.
Answer: I'm still trying to improve in this area myself so while I can't offer advice as a 'master' I would like to share a few thoughts.
Clearly there are pros who can play brilliantly and don't need to look at their hands (but of course they do look, they just don't need to all the time.)
I wouldn't necessarily link keyboard mastery (in the sense of fingers getting to the right keys without look at your hands) with sight reading. They are not exactly the same thing.
Two things I have done which I think have helped me play better without looking at my hands are:

Play basic patterns like scales in contrary motion, rule of the octave, cadences, etc. with your eyes closed or averted from the keyboard. Speed isn't important here, getting the tactile feel of hand movements is the goal.
Repeat patterns through each octave of the keyboard. The point is to rapidly and accurately relocate your hands in the next octave. If playing within one octave is mostly a matter of finger independence, then to some degree the challenge is to reposition your hands. Silently exchanging fingers 1 and 5 is one technique for this octave repositioning. Another is playing full four-note chords in both hands moving up and down by octave. Of course the octave isn't the only interval at which the hands get repositioned, but as a practice method it seemed to make the keyboard feel 'smaller.' I felt like I could get anywhere on the keyboard with more ease and accuracy.


Is there a simple way to add user access on a page level?

Question: I'm still getting used to the way Drupal works, most of what I have read on adding User Level Security on a Drupal site seems to be either View based or by using a Module like Panels.  I am creating a site that is rather simple in structure, with some high level pages that differentiate out the content to different areas.  I am using Superfish to generate a drop down menu system at the high level, and underneath I have some content areas that will either contain only a few pages or one specific area that will have many.  I am also using shortened URLs to make site structure easier to manage, although in general it comes across as flat.  I may be wrong in thinking in terms of pages, and if I need to reconsider that for the site that's ok, I have only been using Drupal for the past 6 months but its a good fit as a CMS for the site I am working on.
The requirement is only for three types of Users - Admin, Group Leaders, and Members.  I'd like to give Group Leaders some access to pages for editing permissions, although mostly only at a second level or specific pages.  Members will have some editing rights but only on a few pages.  Group Leaders and Members will have access to content in one specific area, where I will have many pages, no one else should be able to get in.  Content pages on Member activities will be accessible by only those who have a login, those not logged in should ideally not see the links or not be able to access the pages.
With Drupal 7, and using the Bartik theme and some modules (Chaos Tools, Display Suite and Superfish for now) what is the best mechanism to be able to grant permissions to view and access content on only specific pages in the structure I have?  The site is still new, so if I have to make changes I'd like to do so now before it gets too complex.
Update:
Just to note in addition what happened.  I was looking for some sort of access that was simple to add in and allow me control on an individual node.  Content Access module gave me this in a way I can teach my Users to utilize.  Sorry if it seems a duplicate, I was looking for more of a description on what the modules did than I had seen before.
Answer: Well when you say page in drupal, it comes down to a lot of options. it might be a views page, a panels page, a page created directly with hook_menu().
So options:

If its a panels/views page, you already have permissions options there through UI in those cases.
Node and taxonomy term pages, have contrib modules that does this..Ankit's answer above lists out some.
If the page is a custom page defined bu hook_menu, you can employ '#access_callback' parameter to add a permissions function where you can return TRUE of FALSE based on check.

After restricting access to each page based on roles, these will be respected already when you add their links to the superfish menu.
Comment: Knowing the roles will be respected with Superfish is a bit off my mind, I was worried about that.  Thanks!
Comment: MichaelF, just to make sure you have got me right, roles will not be respected as such by Drupal menu System/ Superfish. You first need to set permissions (which you can do role specific), by employing any of the method above as i laid out, and once set, those permissions will be respected by menu system/superfish. Hope this clarifies a bit more.
Comment: Understood, one thing I have learned about Drupal is the configuration required for many things.
Answer: You can try the organic groups module, it provides all the functionalities that you are looking for:

Organic Groups (OG) enables users with permissions to create and manage their own groups.
Content of the "Group Content Type" has the unique ability to belong to multiple Groups at once. This reduces duplication and increases content accessibility.
Utilizing users to adopt content allows users to create their own libraries of content without having to create duplication.
Content is thus associated with the user and can be maintained by the user, and group maintainers can then manage content in ways that help their audience.

Few references for the organic groups:
Module docs: https://drupal.org/node/1114858 , https://drupal.org/node/1603460
http://vimeo.com/32398425
http://vimeo.com/32398425
https://drupal.org/node/2014929
https://drupal.org/node/2014793

However if you are looking for some simpler method than you can try the following modules:

Content access module: It allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
Node access module:It is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.
Comment: You can also check http://drupal.stackexchange.com/questions/87691/allow-all-og-members-to-view-edit-all-content/87693#87693
Comment: I saw the Content Access module but it looked to still be in Beta for Drupal 7, I like the OG module but that may be too sophisticated for my Users.  Some interesting options though.
Comment: Content Access module was the one I went with since it gave me the simplest mechanism and the easiest access control per page which is what I was looking for.  Thanks.
Comment: @MichaelF Great, Definitely content access module will provide you the required functionality.
Answer: It looks like choice is between organic groups use or not.
In order to get clear what exactly @MichaelF needs:
 - Do you have something on mind like subsites not exactly subsites though
 - Consider with this simple example. A "Sport" site where you need different groups as soccer, cricket and each sport will have related content we can say as events and also related users to it.So with a obvious reason we do not want a user from group cricket to see/edit/create events(will be content in terms of drupal) in soccer group, and also we need permission on granularity of groups let say we only want specific user roles in group cricket to create cricket events but not all users can.May be we need to have specific groups menus as well that means when a user belongs to soccer group logs in to the site user has different navigation menus and when user from group cricket logs in he/she has different.
 - If you have something on mind as as example mentioned above, with no doubt OG is what you are asking for.
Few modules after og module itself that can be helpful for building something mentioned in example are
https://drupal.org/node/206712
but yes if you have different thing in mind as per me using OG will turn out to be overkill in every aspect with no use and @neo has well said about the other side.
Comment: No subsites, these will be page groupings more by content areas, mostly the division will be by interest.  Such as Model Trains, Model Planes, Model Cars with pages that refer to methods of building, paint supplies and so on.  Site Login is all the same and they can look at each others content, but they will have specific interests.  I don't want anything too complex to configure but that's a hard reach with Drupal.
Comment: You don't need OG in that case, as a note do not get confuse with "subsite", I used this term to make it easy to see an usecase.


Passing uint array to Dll to be populated (Nvidia NVML library)

Question: I'm attempting to pass a uint array into the NVML function nvmlDeviceGetAccountingPids(Doc here) from C#, here's a minimum working sample of what I have so far:
<code>    {
        public const string NVMLDLL = "nvml.dll";
        public static class Constants
        {
            public const int NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE = 16;
            public const int NVML_DEVICE_NAME_BUFFER_SIZE = 64;
            public const int NVML_DEVICE_NAME_V2_BUFFER_SIZE = 96;
            public const int NVML_DEVICE_PART_NUMBER_BUFFER_SIZE = 80;
            public const int NVML_DEVICE_SERIAL_BUFFER_SIZE = 30;
            public const int NVML_DEVICE_UUID_BUFFER_SIZE = 80;
            public const int NVML_DEVICE_UUID_V2_BUFFER_SIZE = 96;
            public const int NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE = 32;
            public const int NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE = 80;
            public const int NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE = 80;
            public const int NVML_INIT_FLAG_NO_ATTACH = 2;
            public const int NVML_INIT_FLAG_NO_GPUS = 1;

        }
        public enum nvmlReturn_t
        {
            NVML_SUCCESS = 0,                           // The operation was successful.
            NVML_ERROR_UNINITIALIZED = 1,               // NVML was not first initialized with nvmlInit().
            NVML_ERROR_INVALID_ARGUMENT = 2,            // A supplied argument is invalid.
            NVML_ERROR_NOT_SUPPORTED = 3,               // The requested operation is not available on target device.
            NVML_ERROR_NO_PERMISSION = 4,               // The current user does not have permission for operation.
            NVML_ERROR_ALREADY_INITIALIZED = 5,         // Deprecated: Multiple initializations are now allowed through ref counting.
            NVML_ERROR_NOT_FOUND = 6,                   // A query to find an object was unsuccessful.
            NVML_ERROR_INSUFFICIENT_SIZE = 7,           // An input argument is not large enough.
            NVML_ERROR_INSUFFICIENT_POWER = 8,          // A device's external power cables are not properly attached.
            NVML_ERROR_DRIVER_NOT_LOADED = 9,           // NVIDIA driver is not loaded.
            NVML_ERROR_TIMEOUT = 10,                    // User provided timeout passed.
            NVML_ERROR_IRQ_ISSUE = 11,                  // NVIDIA Kernel detected an interrupt issue with a GPU.
            NVML_ERROR_LIBRARY_NOT_FOUND = 12,          // NVML Shared Library couldn't be found or loaded.
            NVML_ERROR_FUNCTION_NOT_FOUND = 13,         // Local version of NVML doesn't implement this function.
            NVML_ERROR_CORRUPTED_INFOROM = 14,          // infoROM is corrupted
            NVML_ERROR_GPU_IS_LOST = 15,                // The GPU has fallen off the bus or has otherwise become inaccessible.
            NVML_ERROR_RESET_REQUIRED = 16,             // The GPU requires a reset before it can be used again.
            NVML_ERROR_OPERATING_SYSTEM = 17,           // The GPU control device has been blocked by the operating system/cgroups.
            NVML_ERROR_LIB_RM_VERSION_MISMATCH = 18,    // RM detects a driver/library version mismatch.
            NVML_ERROR_IN_USE = 19,                     // An operation cannot be performed because the GPU is currently in use.
            NVML_ERROR_MEMORY = 20,                     // Insufficient memory.
            NVML_ERROR_NO_DATA = 21,                    // No data.
            NVML_ERROR_VGPU_ECC_NOT_SUPPORTED = 22,     // The requested vgpu operation is not available on target device, becasue ECC is enabled.
            NVML_ERROR_INSUFFICIENT_RESOURCES = 23,     // Ran out of critical resources, other than memory.
            NVML_ERROR_FREQ_NOT_SUPPORTED = 24,         // Ran out of critical resources, other than memory.
            NVML_ERROR_UNKNOWN = 999                    // An internal driver error occurred.
        }
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlInit_v2();
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlShutdown();
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlDeviceGetCount_v2(out uint deviceCount);
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlDeviceGetHandleByIndex_v2(int index, out IntPtr handle);
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlDeviceGetName(IntPtr device, [MarshalAs(UnmanagedType.LPStr)] StringBuilder deviceName, uint length);
        [DllImport(NVMLDLL)]
        private static extern nvmlReturn_t nvmlDeviceGetAccountingPids(IntPtr device, ref uint count, [In, Out] uint[] pids);

        static void Main(string[] args)
        {
            if (nvmlInit_v2() == nvmlReturn_t.NVML_SUCCESS)
            {
                nvmlDeviceGetCount_v2(out uint deviceCount);
                for (int i = 0; i < deviceCount; i++)
                {
                    StringBuilder name = new();
                    nvmlDeviceGetHandleByIndex_v2(i, out IntPtr _device);
                    nvmlDeviceGetName(_device, name, Constants.NVML_DEVICE_NAME_V2_BUFFER_SIZE);

                    // arbitrary number for now
                    uint count = 5;
                    uint[] pids = new uint[count];
                    nvmlDeviceGetAccountingPids(_device, ref count, pids);
                    foreach(uint ui in pids) Console.WriteLine(ui);

                }
                nvmlShutdown();
            }
        }
    }
</code>
and so far it's returning the correct # of processes that are utilizing the gpu, but the PID array keeps returning all 0's. I'm not particularly experienced with C# so if someone could show me the proper syntax for this(or lemme know if I have to resort to IntPtr's), the original function has this signature:
<code>nvmlReturn_t nvmlDeviceGetAccountingPids ( nvmlDevice_t device, unsigned int* count, unsigned int* pids )
    Parameters

    device
        The identifier of the target device
    count
        Reference in which to provide the pids array size, and to return the number of elements ready to be queried
    pids
        Reference in which to return list of process ids
</code>
If anyone knows that magic combo I'd sure appreciate it, thank you for your time =)
Answer: Sometimes I think I only type things to work them out ^_^
<code>        static void Main(string[] args)
        {
            if (nvmlInit_v2() == nvmlReturn_t.NVML_SUCCESS)
            {
                nvmlDeviceGetCount_v2(out uint deviceCount);
                for (int i = 0; i < deviceCount; i++)
                {
                    StringBuilder name = new();
                    nvmlDeviceGetHandleByIndex_v2(i, out IntPtr _device);
                    nvmlDeviceGetName(_device, name, Constants.NVML_DEVICE_NAME_V2_BUFFER_SIZE);

                    // arbitrary number for now
                    uint count = 0;
                    nvmlDeviceGetAccountingPids(_device, ref count, null);
                    uint[] pids = new uint[count];
                    if (nvmlDeviceGetAccountingPids(_device, ref count, pids) == nvmlReturn_t.NVML_SUCCESS)
                    {
                        foreach (uint ui in pids) Console.WriteLine(ui);
                    }

                }
                nvmlShutdown();
            }
</code>
so it turns out that when passing the count to the function it wants the same number as the size of the array in order to populate the pids list(which makes sense I suppose). This is retrieved by just setting count to "0" and passing a null array to the function and it will set count to the size of the array. Create a new uint array with that size, pass the array/count and BAM, it returns the pids as desired.
Thanks for reading SO!
If anyone has some constructive criticism in terms of syntax/practices please do comment so I can improve this code as I go. Have a wonderful day


queue:listen timeout stop processing queue processing

Question: i'm using laravel 5 queue for render some 3d files with blender.
some models, have problem with rendering and rendering time is really high like 1 min.
i want to have timeout for doing job (60 sec), when i add timeout to queue:listen , if some job executing time be higher that 60 second , my queue stops but i want just ignore that job and continue doing other jobs.
command i ran:
php artisan queue:listen --tries=3 --timeout=60

error :
Symfony\Component\Process\Exception\ProcessTimedOutException]
  The process "'/usr/local/php56/bin/php56' 'artisan' queue:work '' --queue='default' --delay=0 --memory=128 --sleep=3 --tries=3 --timeout=120 --env='production'" exceeded the timeout of 60
  seconds.

what should i do for solving this ?
Edit:
I googled supervisor,and i found that supervisor is used to continue queue when any problem happened such rebooting VPS or other problem happening outside of job works.
I do n't think supervisor must be used for my problem ...
Answer: You could use supervisor to restart the process again Laravel docs. You can't really catch a PHP timeout. Set the tries to 1, so it doesn't attempt the large process.
Comment: thanks for fast responding.
is there any solution to do that in shared hosting ?
Comment: You could try using the database queue driver and using a cron job. I've never done it, but it may be worth a shot. Other than that, get yourself a VPS. It's pretty much the same price as shared hosting (see DigitalOcean or similar)
Comment: As long as you have access to SSH you should be able to follow the docs and get supervisor up and running. Good luck!
Comment: i thing supervisor is not good solution , each time i want change any setting i should login as root ....


Proof-Reading My Answer For a Logic Question

Question: The question is "Replace the formula (p→(q→¬r))→(¬p→q) by an equivalent formula not involving ¬ or →".
(p→(q→¬r))→(¬p→q)
≡(p→(¬q∨¬r))→(p∨q)
≡(p→¬(q∧r))→(p∨q)
≡(¬p∨¬(q∧r))→(p∨q)
≡¬(p∧(q∧r))→(p∨q)
≡(p∧(q∧r))∨(p∨q)
A second part to the question then asked, based on the statement in the first part and assuming p,q and r are all equally likely, what is the probability that the above statement is true?
Answer: The reduction is correct. The probability of $(P \land (Q \land R)) \lor (P \lor Q)$ being true is 3/4, because there are 8 possible assignments of truth-values to the propositional variables; and only 6 of those satisfy the formula.


select descendants where attribute is x and if doesnt exist select where attribute is y

Question: I have this and i can select what i want when period is 2. But if period 2 do not exist i want to select where period is 3 instead. How?
<code> return document.Descendants("time")
                        .Where(node => (string)node.Attribute("period") == "2")
                        .Take(5)
                        .Select(status => WeatherFactory.Create(status, city, pos))
                        .ToList();
</code>
Comment: Why do you need to do this in one query?
Answer: Can't you just change the Where to:
<code>.Where(node => (string)node.Attribute("period") == "2" || (string)node.Attribute("period") == "3")
</code>
?
Comment: But actually. Now it selects both.. :(
Answer: If you first select all descendants where period == 2, check if it contains any results, and if it doesn't select all descendants where period == 3:
<code>var timeDescendants = document.Descendants("time")
   .Where(node => (string)node.Attribute("period") == "2");
if(!timeDescendants.Any()) {
   timeDescendants = document.Descendants("time")
      .Where(node => (string)node.Attribute("period") == "3");
}
return timeDescendants.Take(5)
.Select(status => WeatherFactory.Create(status, city, pos))
.ToList();
</code>


How would I use entity wrapper to insert new values into an entity property list? bundle?

Question: I would like to save a list of values into a entity property.
<code>foreach ($results as $result)
{
   $wrapper->title->set(value);
}
</code>
Can an entity property hold an array of values or would I use an entity reference defined as a field for each of my values?
Thanks
Answer: A field can only hold multiple values if it's been explicitly set to hold more than one value (this is an option when creating the field - see "How many values the field will store" at http://drupal.org/documentation/modules/field-ui ). In that case, the correct syntax using the entity metadata wrapper is to use array operator [] as follow:
<code>$tids = array(....);
$wrapper = entity_metadata_wrapper('node', node_load(1));
foreach ($tids as $tid) {
  $wrapper->field_taxonomy[] = $tid;
}
</code>
Please note that in your original example you use the field 'title' - however that is a special drupal field, and it cannot be made to be multi-valued.
Comment: Also, if you're setting a term_reference field. The format needs to be $wrapper->field_term_ref['und'][] = array('tid' => TID);
Comment: @donutdan4114 - that is how you access a entity object, NOT an entity metadata wrapper. The whole point of entity metadata wrappers is that you don't deal with things such as language directly. See https://drupal.org/node/1021556
Comment: Thanks for the info! So are you able to use the entity_metadata_wrapper on an entity that has not been saved yet?


Variance of ARMA (1,1) Model

Question: I'm trying to find the variance of an ARMA(1,1) model of the following form:
$$y_t=a_0+a_1y_{t-1}+\epsilon_t+b_1\epsilon_{t-1}$$
where $\epsilon_t$ is a white noise process. I have found it more convenient to write this model in terms of $\epsilon_t$'s:
Writing using lag operators:
$$(1-a_1L)y_t=a_0+(1+b_1L)\epsilon_t$$
Re-arranging:
$$y_t=\frac{1}{1-a_1L}(a_0+(1+b_1L)\epsilon_t)$$
$$=\sum^\infty_{j=0}a_1^jL^j(a_0+(1+b_1L)\epsilon_t) $$
$$=\sum^\infty_{j=0}a_1^ja_0+\sum^\infty_{j=0}a_1^jL^j(\epsilon_t+b_1\epsilon_{t-1})$$
$$=\frac{a_0}{1-a_1}+\sum^\infty_{j=0}a_1^j(\epsilon_{t-j}+b_1\epsilon_{t-1-j})$$
Taking Variance,
$$Var(y_t)=Var(\frac{a_0}{1-a_1}+\sum^\infty_{j=0}a_1^j(\epsilon_{t-j}+b_1\epsilon_{t-1-j}))$$
$$\sum^\infty_{j=0}a_1^jVar(\epsilon_{t-j})+b_1\sum^\infty_{j=0}a_1^jVar(\epsilon_{t-j-1})+2Cov(\sum^\infty_{j=0}a_1^j\epsilon_{t-j},  b_1\sum^\infty_{j=0}a_1^j\epsilon_{t-1-j})$$
$$=\sum^j_{j=0}a_1^j\sigma^2+b_1\sum^\infty_{j=0}a_1^j\sigma^2+\sum^\infty_{j=0}a_1^j.2Cov(\epsilon_{t-j},  b_1\epsilon_{t-1-j})$$
$$\frac{\sigma^2}{1-a_1}+\frac{b_1\sigma^2}{1-a_1}=\frac{\sigma^2(1+b_1)}{1-a_1}$$
This answer seems intuitive however it differs from ARMA (1,1) Variance Calculation
@Neeraaj
$$Var(y_t)=\frac{(1+2a_1 b_1 + b_1^2)\sigma^2}{1-a_1^2}$$
Comment: (A) $y_{t-1}$ is not independent of $\epsilon_{t-1}$ and I suspect that leads to the $2a_1 b_1$ term
Comment: (B) $Var(kX) = k^2 Var(X)$ and I suspect that leads to the $b_1^2$ and $a_1^2$ terms being squares
Answer: Two errors in your solution:

As @Henry pointed out in the comment, you forgot to square the coefficients when you took them out of the variance. Your second line after "Taking Variance" should be

$$
\sum^\infty_{j=0}a_1^{2j}Var(\epsilon_{t-j})+b_1^2\sum^\infty_{j=0}a_1^{2j}Var(\epsilon_{t-j-1}) + \ldots
$$

In the same expression, the covariance contains some non-zero terms. We have:
$$
\mathrm{Cov}\left(\sum^\infty_{j=0}a_1^j\epsilon_{t-j},  b_1\sum^\infty_{j=0}a_1^j\epsilon_{t-1-j}\right) = \sum^\infty_{j=1} \mathrm{Cov}\left(a_1^j\epsilon_{t-j}, b_1a_1^{j-1}\epsilon_{t-j}\right)=
\sum^\infty_{j=1} b_1 a_1^{2j-1}\sigma^2
$$
This gives you the missing $a_1b_1$ term.
Comment: Thank you for your answer, mathemtically this makes sense to me, only thing is, how come the covariance between $\epsilon_{t-j}$ and $\epsilon_{t-j-1}$ isn't zero? Since $\epsilon_t$ is white noise, then would you not expect there to be no covariance? Thank you
Comment: The second term in the left sum ($a_1\epsilon_{t-1}$) and the first term in the right sum ($b_1\epsilon_{t-1}$) are correlated. Similarly for the subsequent terms.

Variance of ARMA (1,1) Model


Emails not being sent from Acquia dev desktop2, win7

Question: I have a Acquia DevDesktop2 set up on my development machine (win7). I'm testing a webform submission and I'm running into an issue where I get messages that the emails are sent, but nothing reaches the inboxes. I have  I'm trying to email them to regular Gmail accounts. The vanilla install on my live site sends the emails without a problem, but I don't want to code on the live codebase.
I've seen that a lot of people have this issue, but there's no good documentation that I've stumbled across on how to set up the xmail server, or how to configure it after the fact. The acquia docs all say it comes cooked in, but I'm not sure why this doesn't work for me. Any references to how to trouble shoot this would be appreciated.
So any advice would be appreciated
Answer: Had the same problem and switched from XMail to Papercut recently:

Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn't enforce any restrictions on addresses, it just takes the message and allows you see it.

So, turn off the XMail service and start Papercut. When a mail is sent in Drupal, Papercut acts as the (local) SMTP server and allows you to see the message.
Comment: can you clarify where/how to do this?
Comment: sc stop "XMaill"
Comment: Of course there are different ways to stop a service on Windows, however, [this tutorial](http://www.eightforums.com/tutorials/12411-services-start-stop-disable-windows-8-a.html) seems to be an easy method. It should be quite similar for Windows 7.
Answer: Many (most?) ISPs will block email sent via port 25.  See Comcast's info on the subject: http://customer.xfinity.com/help-and-support/internet/email-port-25-no-longer-supported/
Comment: Ok...so how can I configure the xmail server that comes with dev desktop to use a diff port? Or what's a work around?
Comment: I am using the SMTP Authentication Support module. When you click configure for that module you will see the port specification that you can change. Start at the modules page or configuration.


Finding out the generative log-likelihood $\log(p(x|t))$

Question: The question ask to build classifiers to label images of handwritten digits. Each image is $8$ by $8$ pixels and is represented as a vector
of dimension $64$ by listing all the pixel values in raster scan order. The images are grayscale and the pixel values are between $0$ and $1$. The labels $t$ are $0$, $1$, $2$, ..., $9$ corresponding to
which character was written in the image. There are $700$ training cases and $400$ test cases for each digit.
Using maximum likelihood, fit a set of 10 class-conditional Gaussians with a separate, full covariance matrix for each class. Remember that the conditional multivariate Gaussian probability density is given by,
$$p(x |t = k) = (2\pi)^{-D/2}|\Sigma_k|^{-1/2}\text{exp}\bigg\{-\frac{1}{2}(\text{x}-\pmb{\mu}_k)^{\text{T}}\Sigma_k^{-1}(\text{x}-\pmb{\mu}_k)\bigg\}$$
where $\pmb{\mu}_k \in \mathbb{R}^{1\times D}$, $\Sigma_k \in \mathbb{R}^{D\times D}$ and positive-definite. Assume that $p(t=k)=\frac{1}{10}$.
Given that $D=64$ and $N=7000$, and $\text{x}\in\mathbb{R}^{N\times D}$ which $\text{x}$ is a $7000 \times 64$ matrix.
$\textbf{(1)}$ First compute parameter $\mu_{kj}$ and $\Sigma_K$ for each $k\in{0,..,9}$ and $j\in\{1,...,64\}$. Note: To ensure numerical stability you may have to add a small multiple of the identity to each covariance matrix. For this question should add 0.01I to each covariance matrix.
After use numpy in python I find out the $\mu_{kj}$ which is a $1 \times 64$ vector, and $\Sigma_K$ is a $64 \times 64$ matrix, for each $k\in{0,..,9}$ and $j\in\{1,...,64\}$.
$\textbf{(2)}$ Compute $\log(p(x|t))$.
Notice that
$$\log(p(x|t)) = -\frac{D}{2}\log(2\pi) - \frac{1}{2}\log(|\Sigma_k^{-1}|) -\frac{1}{2}(\text{x}-\pmb{\mu}_k)^{\text{T}}\Sigma_k^{-1}(\text{x}-\pmb{\mu}_k)$$
But the problem is that
$(\text{x}-\pmb{\mu}_k)^{\text{T}}$ is a $64 \times 7000$ matrix in python
and $\Sigma_k^{-1}$ is a $64 \times 64$ matrix in python
and $(\text{x}-\pmb{\mu}_k)$ is a $7000 \times 64$ matrix in python
So, that is impossible to compute
$$(\text{x}-\pmb{\mu}_k)^{\text{T}}\Sigma_k^{-1}(\text{x}-\pmb{\mu}_k)$$
So, I am stuck on computing $\log(p(x|t))$
So, my question is that are there any other ways to compute $\log(p(x|t))$ ?
Answer: There are closed-form solutions to the MLEs in this case since the membership probabilities are given (sample mean and sample variance-covariance matrix) for observations within each class.
However, your set-up is flawed.  Let $\boldsymbol{x}_{ik} \in \mathbb{R}^{64}$ denote the $i$th vectorized 8x8 image for the $k$th label.  The last term of the full log-likelihood should be $\sum_{k=0}^9 \sum_{i=1}^{700} \left(\boldsymbol{x}_{ik} - \boldsymbol{\mu}_k\right)^{\prime} \Sigma_k^{-1} \left(\boldsymbol{x}_{ik} - \boldsymbol{\mu}_k\right)$.
You can group all the terms together as well.  For instance, let
\begin{eqnarray*}
\boldsymbol{X}_k = \begin{pmatrix}
\boldsymbol{x}_{1,k}^{\prime} \\
\ldots \\
\boldsymbol{x}_{700,k}^{\prime}
\end{pmatrix}.
\end{eqnarray*}
Then we may write the last term of the full log-likelihood as $\sum_{k=0}^9  \left(\mbox{vec} \left(\boldsymbol{X}_k^{\prime}\right) - \boldsymbol{1}_{700} \otimes \boldsymbol{\mu}_k\right)^{\prime} \Sigma_k^{-1} \left(\mbox{vec} \left(\boldsymbol{X}_k^{\prime}\right) - \boldsymbol{1}_{700} \otimes \boldsymbol{\mu}_k\right)$, where $\boldsymbol{1}_{700}$ is a vector of seven hundred 1s.
Finally, the second term is also incorrect in your full log-likelihood.  It should be $-350\sum_{k=0}^9 \ln \left|\Sigma_k\right| $


EAP-MS-CHAPv2 verification failed Arch Linux (strongswan)

Question: I cannot get Strongswan, networkmanager-strongswan (client)
work on your Arch-PC. My vpn-strongswan server (hereinafter deb (server)) has been configured for a long time, any devices (such as android, windows), except for my arch linux (hereinafter arch (client)) are successfully connected to it.
When I try to connect to my vpn deb (server), I get an error that the user data is invalid. I am using the same certificate for the connection as on other devices. I've tried different unique users, but I always get a message with incorrect user information. What am I doing wrong?
I have installed Strongswan and networkmanager-strongswan on my arch (client)
sudo pacman -S networkmanager-strongswan strongswan

My other device can connect to the server from the same network as my arch (client), so the error about nat has nothing to do with it.
ipsec.secrets file on my deb (server) of correct format:
: RSA "server-key.pem"
test : EAP "password"

On deb (server), the time is different from Arch(client) time (on Android and Windows the time is the same as on Arch(client)), this is due to the fact that deb (server) is in a different time zone. But this does not prevent other devices from connecting to it without problems.
log on arch(client)
-- Journal begins at Tue 2021-10-05 23:12:10 MSK, ends at Wed 2021-10-06 21:10:15 MSK. --
Oct 06 21:10:13 Arch-PC charon-nm[16823]: 01[IKE] server requested EAP_MSCHAPV2 authentication (id 0x8B)
Oct 06 21:10:13 Arch-PC charon-nm[16823]: 01[ENC] generating IKE_AUTH request 3 [ EAP/RES/MSCHAPV2 ]
Oct 06 21:10:13 Arch-PC charon-nm[16823]: 01[NET] sending packet: from 172.16.1.20[53461] to my_white_ip_vpn[4500] (140 bytes)
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[NET] received packet: from my_white_ip_vpn[4500] to 172.16.1.20[53461] (124 bytes)
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[ENC] parsed IKE_AUTH response 3 [ EAP/REQ/MSCHAPV2 ]
Oct 06 21:10:15 Arch-PC audit[16823]: SYSCALL arch=c000003e syscall=44 success=yes exit=40 a0=8 a1=7f69867fb5a0 a2=28 a3=0 items=0 ppid=1 pid=16823 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 comm="charon-nm" exe="/usr/lib/strongswan/charon-nm" key=(null)
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[IKE] EAP-MS-CHAPv2 failed with error ERROR_AUTHENTICATION_FAILURE: '(null)'
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[IKE] EAP_MSCHAPV2 method failed
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[ENC] generating INFORMATIONAL request 4 [ N(AUTH_FAILED) ]
Oct 06 21:10:15 Arch-PC charon-nm[16823]: 07[NET] sending packet: from 172.16.1.20[53461] to my_white_ip_vpn[4500] (76 bytes)

log on deb(server)
Oct 06 18:10:14 vpn-srv charon[1611]: 16[NET] received packet: from my_white_ip_home[34671] to 172.26.6.255[500] (464 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 16[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Oct 06 18:10:14 vpn-srv charon[1611]: 16[IKE] my_white_ip_home is initiating an IKE_SA
Oct 06 18:10:14 vpn-srv charon[1611]: 16[IKE] my_white_ip_home is initiating an IKE_SA
Oct 06 18:10:14 vpn-srv charon[1611]: 16[IKE] local host is behind NAT, sending keep alives
Oct 06 18:10:14 vpn-srv charon[1611]: 16[IKE] remote host is behind NAT
Oct 06 18:10:14 vpn-srv charon[1611]: 16[ENC] generating IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(CHDLESS_SUP) N(MULT_AUTH) ]
Oct 06 18:10:14 vpn-srv charon[1611]: 16[NET] sending packet: from 172.26.6.255[500] to my_white_ip_home[34671] (472 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 05[NET] received packet: from my_white_ip_home[53461] to 172.26.6.255[4500] (348 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 05[ENC] parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ CPRQ(ADDR ADDR6 DNS NBNS DNS6) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
Oct 06 18:10:14 vpn-srv charon[1611]: 05[IKE] received cert request for "CN=VPN Root CA"
Oct 06 18:10:14 vpn-srv charon[1611]: 05[IKE] initiating EAP_IDENTITY method (id 0x00)
Oct 06 18:10:14 vpn-srv charon[1611]: 05[IKE] peer supports MOBIKE
Oct 06 18:10:14 vpn-srv charon[1611]: 05[IKE] authentication of 'my_deb_vpn_server_domain' (myself) with RSA_EMSA_PKCS1_SHA2_384 successful
Oct 06 18:10:14 vpn-srv charon[1611]: 05[IKE] sending end entity cert "CN=my_deb_vpn_server_domain"
Oct 06 18:10:14 vpn-srv charon[1611]: 05[ENC] generating IKE_AUTH response 1 [ IDr CERT AUTH EAP/REQ/ID ]
Oct 06 18:10:14 vpn-srv charon[1611]: 05[ENC] splitting IKE message (1980 bytes) into 2 fragments
Oct 06 18:10:14 vpn-srv charon[1611]: 05[ENC] generating IKE_AUTH response 1 [ EF(1/2) ]
Oct 06 18:10:14 vpn-srv charon[1611]: 05[ENC] generating IKE_AUTH response 1 [ EF(2/2) ]
Oct 06 18:10:14 vpn-srv charon[1611]: 05[NET] sending packet: from 172.26.6.255[4500] to my_white_ip_home[53461] (1248 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 05[NET] sending packet: from 172.26.6.255[4500] to my_white_ip_home[53461] (800 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 06[NET] received packet: from my_white_ip_home[53461] to 172.26.6.255[4500] (76 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 06[ENC] parsed IKE_AUTH request 2 [ EAP/RES/ID ]
Oct 06 18:10:14 vpn-srv charon[1611]: 06[IKE] received EAP identity 'test'
Oct 06 18:10:14 vpn-srv charon[1611]: 06[IKE] initiating EAP_MSCHAPV2 method (id 0x8B)
Oct 06 18:10:14 vpn-srv charon[1611]: 06[ENC] generating IKE_AUTH response 2 [ EAP/REQ/MSCHAPV2 ]
Oct 06 18:10:14 vpn-srv charon[1611]: 06[NET] sending packet: from 172.26.6.255[4500] to my_white_ip_home[53461] (108 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 07[NET] received packet: from my_white_ip_home[53461] to 172.26.6.255[4500] (140 bytes)
Oct 06 18:10:14 vpn-srv charon[1611]: 07[ENC] parsed IKE_AUTH request 3 [ EAP/RES/MSCHAPV2 ]
Oct 06 18:10:14 vpn-srv charon[1611]: 07[IKE] EAP-MS-CHAPv2 verification failed, retry (1)
Oct 06 18:10:16 vpn-srv charon[1611]: 07[ENC] generating IKE_AUTH response 3 [ EAP/REQ/MSCHAPV2 ]
Oct 06 18:10:16 vpn-srv charon[1611]: 07[NET] sending packet: from 172.26.6.255[4500] to my_white_ip_home[53461] (124 bytes)
Oct 06 18:10:16 vpn-srv charon[1611]: 08[NET] received packet: from my_white_ip_home[53461] to 172.26.6.255[4500] (76 bytes)
Oct 06 18:10:16 vpn-srv charon[1611]: 08[ENC] parsed INFORMATIONAL request 4 [ N(AUTH_FAILED) ]
Oct 06 18:10:16 vpn-srv charon[1611]: 08[ENC] generating INFORMATIONAL response 4 [ N(AUTH_FAILED) ]
Oct 06 18:10:16 vpn-srv charon[1611]: 08[NET] sending packet: from 172.26.6.255[4500] to my_white_ip_home[53461] (76 bytes)

What should i do so that i can connect to my vpn? Help me please
Comment: What strongSwan versions are you using on client/server? Do the passwords contain any non-ASCII characters?
Answer: To connect from the console, this guide on configuring the client stronswan helped me: https://protonvpn.com/support/linux-ikev2-protonvpn/
In IDE when you first connect your new VPN connection, the NetworkManager-Strongswan asks for a password from the VPN, not from the Sudo. Because of this, when connecting from ide, an authorization error occurred.
Comment: What does "the NetworkManager-Strongswan asks for a password from the VPN, not from the Sudo" mean exactly? And why it it a problem? Did you try storing the password in the connection editor?


Retornar todos os dados em um mysql_fetch_assoc

Question: Tenho uma consulta que retorna os dados abaixo:
nome -------- vencimento
Joao -------- 09/08/2012
Maria ------- 04/12/2015

Ou seja, dois registros.
Porém, ao colocá-la no código PHP apenas o registro superior é retornado, mesmo utilizando += e uma estrutura while no mysql_fetch_assoc.
Código PHP
 $result = array();

    $sql_select = mysql_query(
        "SELECT nome, vencimento
        FROM alunos"
    )or die(mysql_error());

    while($l = mysql_fetch_assoc($sql_select)){
        $result += $l;
    }

return json_encode($result);

Retorno $result atual:
{"nome":"Joao","vencimento":"09/08/2012"}

Retorno $result esperado:
   {"nome":"Joao","vencimento":"09/08/2012"}
   {"nome":"Maria","vencimento":"04/12/2015"}

Answer: += não funciona para adicionar um item em um array, faça a atribuição com colchetes.
Mude:
while($l = mysql_fetch_assoc($sql_select)){
    $result += $l;
}

Para:
while($l = mysql_fetch_assoc($sql_select)){
    $result[]= $l;
}

Comment: Funcionou @rray, mas sabe me dizer porque isso acontece?


How can I place object outside of panel in same place?

Question:
If I move ☘운동일기 label to location which option panel located,

☘운동일기 label move inside of option panel! But I want to ☘운동일기 label's parents would be not panel but window.
Comment: It appears that in both of your screenshots that the label's parents are the window. What are you asking?
Comment: Take a look at [this post](https://stackoverflow.com/a/38703523/3110834) for example.
Comment: Move it somewhere that is clearly outside of the panel and then change the position in the code-behind.
Answer: If you are doing that on design mode, when you move the control, you must put the mouse cursor outside the panel when dragging the label.If you move the label with the cursor pointing to the half that stay inside the panel, Visual Studio interpret label is inside the panel.
Comment: And I edited Designer.cs InitializeComponent function directly. Anyway... thank you!
Comment: You're welcome. I hope it will help you.


Probability of event appearing at least 2 times

Question: The average percentage of defective product is 10%. There were released 100 units of this product. What is a probability that there will be at least 2 defective products among them?
I tried to solve this with Bernoulli formula. So, lets say $m$ is a number of defective products. I need to find $P(m \geq 2)$. We can rewrite it like this: $P(m \geq 2) = 1 - P(m < 2) = 1 - P(m=0) - P(m=1)$. So, $P(m=0)= {100\choose 0} (0,9)^{100}$, $P(m=1)= {100\choose 1} (0,1)^{1} (0,9)^{99}$.
So, $P(m \geq 3) = 1 - {100\choose 0} (0,9)^{100} - {100\choose 1} (0,1)^{1} (0,9)^{99} = 1 - 0,00003 - 10 \cdot 0,00003 = 0,99967$
It seems like too high probability. Did i do everything right?
Comment: In expectation, you should have $10$ defective products. With high probability, you'll have around that number, and above $2$.
Answer: You did everything right (except that you mistyped $10$ instead in $100$ for the evaluation of ${100\choose 1}$, but the final result is ok).
It's not an unexpected result. If the failure rate is $10\%$, then in $100$ samples we have on average $10$ failures . So, we can guess, it's very probable that we have at least $2$ failures.
More in detail, it's a Binomial distribution, the standard deviation is $\sqrt{n p (1-p)}=3$, and it resembles a Gaussian, hence we can expect that more than $99.7\%$ of the ocurrences happen in the range $[7,13]$
Comment: i don't see that mistyped
Comment: You wrote $ 1 - 0,00003 - 10 \cdot 0,00003 $ What about that $10$ ?
Answer: Your computation is correct, I get the same result. Also, it does not seem too high to me, since it is extremely unlikely that there is only one or even zero defective products among 100 at such a high deficiency rate.


$(\alpha +\beta - \gamma - \delta)(\alpha -\beta + \gamma - \delta)(\alpha -\beta - \gamma + \delta)$ in terms of elementary symmetric polynomials?

Question: Is it possible to express $(\alpha +\beta - \gamma - \delta)(\alpha -\beta + \gamma - \delta)(\alpha -\beta - \gamma + \delta)$ in terms of elementary symmetric polynomials ? What I tried was rewriting each factor as a sum of two terms, e.g. $(\alpha +\beta - \gamma - \delta) = (\alpha - \gamma) + (\beta - \delta)$, but that didn't lead anywhere.
Comment: sorry to ask such a question, but what is an elementary symmetric polynomial? in this case the polynomial is a function of what?
Comment: In this case the elementary symmetric polynomials would be $s_1 = \alpha + \beta + \gamma + \delta$, $s_2=\alpha\beta + \alpha\gamma + \alpha\delta + \beta\gamma + \beta\delta + \gamma\delta$, $s_3= \alpha\beta\gamma + \alpha\beta\delta + \alpha\gamma\delta + \beta\gamma\delta$ and $s_4= \alpha\beta\gamma\delta$.
Answer: Well, it is symmetric, so this must be possible. Indeed, your polynomial is $s_1^3-4s_1s_2+8s_3$.
Upd. How did I find this? Well, it is of degree 3, so it must be some combination of $s_1^3,\;s_1s_2$, and $s_3$. Now look at the term $\alpha^3$ (also $\beta^3$, etc.) - it must have come from $s_1^3$, so we subtract that. Then look at the terms $\alpha^2\beta$ and the like. These are from $s_1s_2$, and they go with a coefficient -4, so we subtract $-4s_1s_2$, and instantly recognize the rest.
Comment: Did you use any general sort of method to find this ?
Comment: Wait a sec, I'll add some explanation.
Comment: For a general approach, check: http://math.stackexchange.com/questions/14051/symmetric-polynomials-and-the-newton-identities/14061#14061
Comment: How did you realize that the $ s_1s_2$  elements have coefficient -4 ?
Comment: Wolfram Mathematica, Expand[...].


How to remove default div of views block?

Question: My html code:

    →

<img class="img-responsive" src="<?php print base_path(). path_to_theme();?>/assets/images/img.jpg" alt="">

In views-view-fields--name--name.tpl I'm using this code:

    →

<?php print $fields['field_fieldName']->content;?>

The generated output is the following.

    →

## I have to remove this div

I have to remove the default
 before the  tag.
Comment: use Java Script to remove this div instead of create new view template file.
Comment: possible duplicate of [Create template file for views block](http://drupal.stackexchange.com/questions/11468/create-template-file-for-views-block)
Comment: For anyone reading - do not use Javascript to do this. Override the default view template to remove the wrapping div.
Answer: Click on field and edit settings
Override style settings for field
Customize field HTML
Customize field and label HTML
Comment: @ gfarishyan Thank you. Actually there is not printing an image. I am using content;?> Am I wrong??
Comment: what is the output of print_r($fields['field_fieldName']) or even use dsm/dpm dpr if you enabled devel module ?


Selection of a row in pandas

Question: I need to select a row where age is NaN in Pandas
df[df['age']==np.nan]
This does not return anything. But my dataset has a row where age is NaN
Comment: Use `df['df['age'].isna()]`
Comment: `df[pd.isnull(df['age'])]`
Answer: df = pd.DataFrame({'age': [15,np.nan, 30, 40]})
print(df)

    age
0  15.0
1   NaN
2  30.0
3  40.0

df['age'].isna() will give True for the rows that are nan:
0    False
1     True
2    False
3    False

Then you can find the rows and their values (which is nan) by using df[df['age'].isna()]:
   age
1  NaN

Selection of a row in pandas


Mapping of an ellipse to an ellipse with different eccentricity that maps focal points to focal points

Question: The title describes what I'm looking for:
Is there a (canonical) way of mapping an ellipse (interior and boundary) to an ellipse with different eccentricity that maps focal points to focal points?
(Obviously, an affine linear map won't do it and I think it can't be a conformal mapping either.)
Put in other words: Is there among all (let's say differentiable) maps that map a given ellipse (interior and boundary) to a given other ellipse and preserving the focal point one canonical (e.g. based on geometric reasons or extremal principles, e.g. mean square of deplacement of the points is minimal or the like).
P.S. Note that you won't be able to map first to a circle then to the other ellipse,  because mapping to the circle won't be injective (both focal points map to the center.
Answer: Hint:
From two foci, we can define two families of confocal conics, ellipses and hyperbolas. Furthermore, they are orthogonal.

Every point in the plane can be referred to by $(u,v)$ coordinates associated to this network of curves. Then any transformation of the form $(u,v)\to(\phi(u),v)$ achieves the desired effect. Obviously, the $v$-curves map to themselves.
See https://en.wikipedia.org/wiki/Confocal_conic_sections.


Multiple column in JavaScript

Question: I am new to JavaScript. I wrote forEach and the head table repeats every time I add something in database. I need col to stay and when I add something new to database its add in rows.
Here is a screenshot to illustrate what I mean:

Code:
import {http} from "./http.js";

document.addEventListener("DOMContentLoaded", getProducts);

function getProducts() {
    http

        .get('http://localhost:3000/products')
        .then((data) =>{
            let output = "";

            data.forEach((product) => {

                output += `

                    #
                    Clasa
                    Numar Elevi
                    Profesor
                    Media Notelor

                    ${product.id}
                     ${product.numar}
                    ${product.profesor}
                     ${product.elevi}
                     ${product.media}

`;

            })
            document.getElementById('table').innerHTML = output;
        });
}

Comment: Would you add a screenshot to explain the issue visually?
Comment: Ah, I think I can see the problem - you are adding a full new table for each row. Could you find the tbody and in the loop just append new rows (tr) to it?
Comment: Looks like this would be helpful (perhaps even a duplicate): https://stackoverflow.com/questions/10309650/add-elements-to-the-dom-given-plain-text-html-using-only-pure-javascript-no-jqu
Comment: @halfer i added a screenshot
Answer:

// As the Ajax call is not the issue here, simulate some sample data
const data = [
  { id:1, numar: "a IV-a A", profesor: 23, elevi: "Matel Marian", media: "8.32"},
  { id:2, numar: "a VI-a C", profesor: 26, elevi: "Cornel Ababei", media: "7.96"},
  { id:3, numar: "ss", profesor: "sss", elevi: "sss", media: "sss"},
];

// The
,
, and
 tags are needed just once
let output = `

                   #
                   Clasa
                   Numar Elevi
                   Profesor
                   Media Notelor

`;

// Then for each item, append a
...
 element
data.forEach((product) => {
                output += `

                    ${product.id}
                     ${product.numar}
                    ${product.profesor}
                     ${product.elevi}
                     ${product.media}

`;
            });

// Finally, close off with

output += "

";

document.getElementById("table").innerHTML = output;

// Say later you have another Ajax call and got another item.
const add = () => {
  // simulated data:
  const newItem = I = { id:4, numar: "b IX-c D", profesor: 88, elevi: "Richard Feyman", media: "9.99"};
  let row = document.createElement("tr");
  row.innerHTML = `<td>${I.id}</td><td>${I.numar}</td><td>${I.profesor}</td><td>${I.elevi}</td><td>${I.media}</td>`;
  const tbody = document.getElementById("tbody");
  tbody.appendChild(row);
}
.table, .table td, .table th {
  border: solid 1px black
  }

 <button onclick="add()">Add another row</button>

Comment: Can you add some commentary to this to explain what you fixed, and what the problem was? I admit the question author didn't seem to have made much of an effort, but perhaps for the benefit of future readers, some explanatory material might be useful.
Comment: @Snaksss Does this address your question?

Multiple column in JavaScript


How to set HTML value for taxonomy description field using entity_metadata_wrapper

Question: I've set my taxonomy description field to taking a filtered text value. Using the UI, I can edit a taxonomy term, write some HTML, save, and when I view it I see the HTML rendered by my browser.
However when doing this:
$wrapper = entity_metadata_wrapper('taxonomy_term', 123);
$wrapper->description->set('
My html
');
$wrapper->save();

And viewing the term's page, the description comes out with the html converted to entities, i.e. I see
My html
 instead of a paragraph with My html as its content.
I notice that
$wrapper->description->value(); //
<p&gtp;My html<p>

Whereas if I load a term that I have edited with the UI, saving HTML to the description field,
$wrapper->description->value(); //
Some html

I've looked at $wrapper->description and $wrapper->value()->description and there's no difference between a term with/without the correct/desired behaviour.
Also, I note that with normal fields, when you set a formatted text field you pass/get an array [ 'format' => 'filtered', 'value' => '
the html
' ] whereas here I only ever get a string.
Is this something peculiar to taxonomy terms (and is there a workaround or extra code I need)? Have I misunderstood something?
Thanks.
Answer: I just encountered a similar situation myself and it looks like you're choices are either taxonomy_term_save() or to update the table directly via  db_update(). The format property belongs to the term itself, rather than the Description property of the term. If you execute $term->getPropertyInfo() you'll see that the format property is not returned. Keep in mind that the Description is a property of the taxonomy entity, rather than a field, but doesn't seem to be accessible via EMW.
taxonomy_term_save()
taxonomy_term_save((object)array(
  'tid' => $tid,
  'description' => $t($descriptions[$info['step']]),
  'format' => 'full_html',
  'vid' => $vocab->vid,
));

Comment: Thanks for this work around. Strange how the wrapper can't deal with this.


Robust regression vs bootstrapping of confidence intervals

Question: In multiple regression, when the independent variable is not normally distributed and the dependent variable is not normally distributed, is bootstrapping of the confidence intervals or robust regression first choice?
Is there any advantage of bootstrapping of confidence intervals if the independent variable is normally distributed but not the dependent variable?
Is there any publication explaining the difference between the methods?
Comment: In regression, we don't care about the distribution of the independent or dependent variables, we only care about the distribution of the error term - and even that only somewhat.
Answer: Welcome to our site! But your question is very broad and unclear, see below.
In regression, we do not care about the marginal distributions of neither the dependent nor predictor variables. We care about the conditional distribution of the dependent variable (given the regressors), that is, of the error term.  In regression models we condition on $x$, that is, we take the predictor variables $x$ as given, deterministic. Regression models do not care about their distribution, at least not very much.
Apart from that, you would be better off asking your real question. What kind of data do you have? What is the goal? Maybe present some plots, and some of your preliminary analysis. First then can we see if you need bootstrapping, or robust regression, or something entirely else!


Count all users having specific amount sum

Question: I have database table similar to the one below.
id     user_id     amount
1      5546        1000
2      5546        52
3      53          10000
4      45          120
5      5546        10

Each user's payment is recorded there, which means each user can have multiple records.
Now I need to get number of users having more than 10$ sum of amounts.
Here is some basic code I wrote but it gives me many results instead of one counted number but I dont understand why.
I mean, its probably because I am grouping by but I need to count it by user id so no idea how to make it properly.
SELECT count(*), sum(amount) as amount FROM `revenues`

GROUP BY user_id

HAVING amount > 10

This question might seem stupid but please tell me what I am doing wrong
Answer: Use a subquery:
SELECT COUNT(*)
FROM (SELECT sum(amount) as amount
      FROM `revenues`
      GROUP BY user_id
      HAVING sum(amount) > 10
     ) r;

Notice that I repeated the expression.  You have aliased the sum() with the same name as the column.  I can never remember if having in MySQL refers to the column or the alias.  So, the query repeats the expression just to avoid potential problems.
Comment: MySQL allows the use of aliases in `group by` and `having` clauses, see http://www.mysqltutorial.org/tryit/query/mysql-alias/#3
Comment: @TheWildHealer . . . It is not whether or not they are allowed.  It is about the scoping rules.  Which comes first, the alias definition or a table definition?


É possível aplicar um atributo em CSS apenas para uma página que contém uma substring?

Question: Olá, sou iniciante em CSS e estou criando um tema negro para o site do Globo usando Stylish, enfim, gostaria de saber se é possível aplicar um atributo/regra que seja só respeitada dentro um site que tenha tal domínio ou se for detectado uma substring na URL do site. Neste caso, por exemplo, eu gostaria apenas de transformar essas fontes negras em #BFBFBF para este site que contêm "fina-estampa" na URL.

Não entendo nada de PHP ou Javascript, então, é possível fazer isso usando apenas CSS? Já chequei os ID's da página e não há nada específico para ela, então fiquei perdido.
Obrigado!
Comment: Existe uma regra semelhante aos media queries, que ainda esta em fase de proposta e é considerado experimental, o [@document](https://developer.mozilla.org/en-US/docs/Web/CSS/@document), no entanto só funciona no FF61+ (requer o prefixo -moz), isso pq como disse, ainda esta em fase proposta, se for usar em Chrome/Chromium esqueça... PS: PHP não tem nada haver com Stylish, PHP é uma linguagem que rodado lado do servidor apenas.
Comment: @AlecsanderCamilo eu já citei na resposta, como usar o regex, veja lá.
Comment: Meu eu acho que a sua lógica que está errada, não seria mais interessante coloca um classe no Body e mudar tudo que está dentro dele do que mandar um usuário para outra página na qual dependendo da URL vai usar um .CSS diferente...? Na verdade eu nunca vi um Dark Mode que leva o usuário para outra página ou que muda a URL...
Comment: É que a página do Globo.com tem várias sub-páginas, como Esportes, Novelas, Sociedade, etc, a maioria das classes é parecida, mas algumas coisas mudam devido ao leiaute. Usando o Stylish com o domínio Globo.com eu consigo englobar todos eles. O meu único problema é com especificamente a página desta novela que fica negro dentro do parêntesis, e caso eu mude, TODAS as páginas vão ficar com links (a) com a mesma cor, o que eu não gostaria, já que geralmente a cor dos links da globo são indicadores pra qual tipo de conteúdo você está indo...
Answer: Existe uma regra semelhante aos @media (usado para diversas situações incluindo media-query), que ainda esta em fase de proposta e é considerado experimental, o @document, no entanto para páginas web normais (não estou falando do Stylish) só funciona no Firefox 61+ (requer o prefixo -moz), isso porque como disse, ainda esta em fase de proposta, se for usar em Chrome/Chromium esqueça.
No entanto ao ler a documentação do Stylish:

https://github.com/stylish-userstyles/stylish/wiki/Applying-styles-to-specific-sites

Eles afirmam:

The @-moz-document format is the supported format when posting on userstyles.org. The site software handles converting to other formats for browsers that do not support it.

Ou seja, dentro do Stylish é funcional para suportar outros navegadores além do Firefox.
Exemplo pra aplicar CSS pra uma URL exata:
@-moz-document url("http://pt.stackoverflow.com/questions/453131/É-possível-aplicar-um-atributo-em-css-apenas-para-uma-página-que-contém-uma-subs") {
    body {
        background-color: black !important;
    }
}

Exemplo pra aplicar CSS para um domínio especifico, ignorando se é HTTPS ou HTTP ou a página que estiver:
@-moz-document domain("pt.stackoverflow.com") {

Exemplo pra aplicar CSS para uma URL que comece com exatamente:
@-moz-document url-prefix("https://pt.stackoverflow.com/questions/") {

e no seu caso a solução será com regex, algo como mais ou menos assim:
@-moz-document regexp('://.*\\.globo\\.com/.*fina-estampa.*') {

Eu não vou ficar ensinando regex, porque não é algo que se aprende do dia pra noite (apesar de alguns Youtubers e artigos e cursos afirmarem que você pode aprender coisas assim em poucas aulas)
Se tiver uma duvida mais especifica sobre regex então aprenda um pouco e depois formule uma pergunta só sobre regex.
Note que se a URL for esta https://gshow.globo.com/novelas/fina-estampa/, o url-prefix já resolveria:
@-moz-document url-prefix("https://gshow.globo.com/novelas/fina-estampa/") {
    ... SEU CSS AQUI ...
}

Comment: @AlecsanderCamilo foi o que eu disse na resposta, o Stylish converte (faz "funcionar").
Comment: @AlecsanderCamilo editei a resposta com uma sugestão alternativa para outros problemas nada relacionados ao Stylish e se a resposta resolveu o seu problema marque-a como correta, fico agradecido.
Comment: Removi a alternativa, eu me confundi, esqueci do nivel do head ~ body, não teria como funcionar.
Comment: Obrigado pela resposta! O último código deu certo, embora eu use o Chrome, o Stylish tem uma forma de converter. A questão é que eu teria que fazer outra section com o url-prefix e assim que colei o que você postou ele detectou o @moz e me sugeriu isso. Deu certo! Muito obrigado!
Comment: Interessante esse esquema de usar a url como "seletor". Espero que ganhe mais suporte!


Class Field Towers

Question: Let k a number field whose $p$-class group $C_k$ of type $(p,p)$ i.e $C_k \cong \mathbb{Z}/p\mathbb{Z}\times \mathbb{Z}/p\mathbb{Z}$. Let $k^{(1)}$ be the Hilbert class field of $k$ and $k^{(2)}$ the Hilbert class field of $k^{(1)}$, for a positive integer $n$, we define $k^{(n)}$ is the Hilbert class field of $k^{(n-1)}$...
We define the class fields tower of k as: $k \subset k^{(1)} \subset k^{(2)}\subset k^{(3)} \subset.....\subset k^{(n)}\subset.....$
I need to prove that the class field tower of $k$  terminate in the second step i.e $k^{(2)} = k^{(3)}= k^{(4)}=....$
Comment: What have you tried?
Comment: I try to use $G = Gal(k^{(2)}/k)$ and determine its commutator group $G/G'$, such that $G/G' $ is of type $(p,p)$
Answer: This is only known to be true for $p = 2$. For odd $p$, Wingberg (On the maximal unramified p-extension of an algebraic number field, J. Reine Angew.
Math. 440 (1993), 129–156) claims to have proved that there exist infinite $p$-class field towers for certain fields with class group of type $(p, p)$. I seem to remember that there were problems with some of his claims but at least it shows that the problem is not exactly of the homework type.
For examples in which the towers have length $3$ see
https://arxiv.org/abs/1601.00179 .

Class Field Towers


A not semisimple representation of $S_3$ over $k^3$ with $k$ a field of characteristic 3.

Question: Let $k$ be a field of characteristic 3. Then we can naturally define the representation $\rho : S_3 \to GL(k^3)$ such that $\rho(\sigma)(x_1,x_2,x_3) = (x_{\sigma_1},x_{\sigma_2}, x_{\sigma_3})$. Clearly, $W = \text{Span}_k \lbrace (1,1,1) \rbrace$ is a subrepresentation beacuse is a $\rho(\sigma)$ invariant sub-space for all $\sigma \in S_3$. Show that $W$ is contained in all nonzero subrepresentation of $(k^3,\rho)$.
Let $0 \neq U \subset k^3$ a subrepresentation of $(k^3,\sigma)$.
Suppouse $\dim(U) = 1$, then $U = \text{Span}_k\lbrace(u_1,u_2,u_3)\rbrace$. Let $\sigma = (i \hspace{2mm} j)$ and $l \neq i,j$. Then, $u_i = \lambda u_j$,  $u_j = \lambda u_i$,  $u_l = \lambda u_l$. The last equation sates that $\lambda = 1$ and $u_i = u_j$. Since $\sigma$ is an arbitrary transposition, then we conclude that $u_1 = u_2 = u_3$ and $U = W$.
I'm having problems when $\dim(U) = 2$, because now all vector in $U$ under $\rho(\sigma)$ is a linear combination of two vectors and not only one, I don't even know how to start. However, I have the hunch that there is not a subrepresentation of dimension 2. I appreciate any hint :)
Comment: In all characteristics there is the zero-sum subrepresentation
$$V=\{(x_1,x_2,x_3)\in k^3\mid x_1+x_2+x_3=0\}.$$
I leave it to you to figure out how the relation of $V$ and $W=\langle(1,1,1)\rangle$ is exceptional exactly in characteristic three.
Comment: Mind you, are you sure about the definition of $\rho$? We can think of the vectors as functions from the index set $\{1,2,3\}$ to the field $k$. The group $S_3$ acts on the index set from the left. so unless you use the inverse, it will act on the functions from the right. In other words, I think it should read
$$\sigma\cdot(x_1,x_2,x_3)=(x_{\sigma^{-1}(1)},x_{\sigma^{-1}(2)},x_{\sigma^{-1}(3)}).$$
Comment: (cont'd) For example, if $(x_1,x_2,x_3)=(4,5,6)$, then the 2-cycle $(12)$ interchanges the first two coordinates, the 2-cycle $(13)$ the first and the last. Therefore
$$(13)\cdot((12)\cdot(4,5,6))=(13)\cdot(5,4,6)=(6,4,5).$$
As $(13)(12)=(123)$, this should be equal to $(123)\cdot(4,5,6)$.
Answer: Since $U$ is 2-dimensional, it has a basis $\{u,v\}$. Naïvely all we can say about them is their coordinates $u=(u_1,u_2,u_3)$ and $v=(v_1,v_2,v_3)$ and $v\neq0, u\neq \lambda v$. But a little bit of linear algebra saves a lot of tedium.
Since the transposition $\tau=(2\,3)$ satisfies $\tau^2=e$, we know that $\rho(\tau)$ acting on $U$ has minimal polynomial dividing $X^2-1$. This splits completely into distinct factors $(X+1)(X-1)$ over $k$ and therefore is diagonalizable, that is, it admits an eigenbasis. Hence we can take $u$ and $v$ to be eigenvectors of $\rho(\tau)$, with eigenvalues for $u$ and $v$ being $\pm 1$.
Then $u_2=\pm u_3$ and $v_2=\pm v_3$. Note that neither of these can be zero, or else $(*,0,0)\in U$ and therefore by applying $\sigma=(1\, 2\, 3)$, all of $k^3$ is in $U$, but $U$ is supposed to be 2-dimensional.
Case I. If $u_1=v_1=0$ then we may scale so that $u_2=v_2=1$. But since $u\neq v$ we must have that $u_3=-1$ and $v_3=1$. In particular $v=(1,1,1)$, so $W\subseteq U$.
Case II. If $u_1\neq 0$ and $v_1\neq 0$ then we may scale so that $u_1=v_1=1$. Now we consider $\rho(\sigma)u=au+bv$, or in expanded form,
\begin{align*}
u_2 &=a+b \\
\pm u_2 &=au_2+bv_2 \\
1 &=\pm(au_2+bv_2)
\end{align*}
The signs in the last two equations are the same, and thus $u_2=1$. Similarly $v_2=1$. So as before, $(1,1,1)\in U$.
Case III. Otherwise, without loss of generality: $u_1=1$, and $v_1=0$ and $v_2=1$. The above equations still hold, so that $u_2=1$. Note that $u_3=-1$ is impossible: if $v_3=-1$ also, then $u-v=e_1$, but if instead $v_3=1$, then
$$u-\rho(\sigma^{-1})v=(1,1,-1)-(1,1,0) = -e_3.$$
Either statement contradicts that $U$ is 2-dimensional. Therefore, $u_3$ and so $u=(1,1,1)\in U$, as desired.
[ Note that Jyrki's example falls in the final subcase: $u=(1,1,1)$ and $v=(0,1,-1)$ is permitted, and $u+v=(1,2,0)=(1,-1,0)$. ]


Prove $S_4$ has no normal subgroup of order 8, or of order 3?

Question: Prove that $S_4$ does not have a normal subgroup of order 8, nor a normal subgroup of order 3. (Dummit/Foote 3.2.14)
Proof: Suppose $A$ and $B$ are normal subgroups of $S_4$ with orders 8 and 3, respectively.
(i) Since $A \trianglelefteq S_4$ then for any subgroup $X\leq S_4$ we have $AX \leq S_4$. Let $X= \{1,x\}$ such that $|x|=2$ and $x\notin A$. Since $|A|=8$, and $S_4$ contains more than 8 elements of order 2, then $x$ exists. By definition we therefore have $A\cap X = \{1\}$ and hence their product $AX$ has order
$$|AX|=\frac{|A||X|}{|A\cap X|}=\frac{8\cdot 2}{1}=16,$$
however by LaGrange's Theorem, if $AX\leq S_4$ then $|AX|$ divides $|S_4|$, but 16 does not divide 24, so $A$ cannot be a normal subgroup.
(ii) Similar to part (i), since $B \trianglelefteq S_4$ then for any subgroup $Y\leq S_4$ we will have $BY\leq S_4$. Let $Y= \{1, y, y^2\}$ such that $|y|=|y^2|=3$ and $y, y^2 \notin B$. Once again, this is possible since $S_4$ contains more than 3 elements of order 3. Then we will have,
$$|BY|=\frac{|B||Y|}{|B\cap Y|}=\frac{3\cdot 3}{1}=9,$$
but since 9 does not divide 24 therefore $BY$ is not a subgroup of $S_4$, so $B$ is not a normal subgroup.
Is this correct?
Comment: Look fine, and nice, to me.
Comment: $A$ contains at most 7 elements of order 2 and $B$ contains only 2 elements of order 3. So the existences of $X$ and $Y$ are marginally easier than you make them out to be. Not that it matters much for the correctness.
Answer: There is still another less involved method for showing that $S_4$ does not have any normal subgroups of order $3$ or $8$. The trick is that you observe that a normal subgroup must be the (disjoint) union of some of the conjugacy classes and that one of them is the class of the unity $1$ (since $1 \in$ normal subgroup).
The conjugacy classes are easy to figure out, since they correspond to cycle types; their sizes are $1, 3, 6, 6$, and $8$ (respectively the size of the conjugacy classes $[(1)], [(12)(34)], [(12)], [(1234)], [(123)]$).
Now you immediately see that there is no way of building a normal subgroup of order $3$ or $8$ out of these classes: for $3$, you are left with $2$ elements, impossible, for $8$ you are left with $7$, also impossible.
This is quite a cool way to check if something is a normal subgroup or not. With this method you can easily prove that $A_5$ is a simple group (that is without any non-trivial normal subgroups). I leave that to you.
Answer: Here's another low calculation approach that relies on properties of quotient groups instead of on conjugacy classes.
I show that $S_4$ can't have a normal subgroup with order $8$ by contradiction.  Suppose $H \unlhd S_4$ is a normal subgroup with order $8$.  Then $S_4 / H$ is a quotient group with order $3$.  Since all groups with order $3$ are cyclic, $S_4 / H$ is cyclic and it's two non-identity cosets $C_1$ and $C_2$ are generators of $S_4 / H$ and have order $3$.  So, for example, $(C_1)^3 = H$, since $H$ is the identity.  Observe that $S_4$ has only $8$ elements with order $3$.  Since the two non-identity cosets require $16$ elements between them, at least one of them, say $C_1 \in S_4 / H$, must contain elements that have order $2$ or $4$ (since the elements of $S_4$ have orders $1$, $2$, $3$, and $4$ and the order $1$ element is in $H$--the identity coset,and we run out of elements with order $3$).  If $\sigma \in C_1$ has order $2$, then $(C_1)^3 = \sigma^3 H = \sigma H \ne H$ which is a contradiction. If $\sigma \in C_1$ has order $4$, then $(C_1)^3 = \sigma^3 H \ne H$ which also is a contradiction.  Therefore, $H$ is not normal and $S_4$ cannot have any normal subgroups with order $8$.
I also show that that $S_4$ can't have a normal subgroup with order $3$ by contradiction.  Suppose $H \unlhd S_4$ is a normal subgroup with order $3$.  Then $S_4 / H$ is a quotient group with order $8$ (i.e. with $8$ cosets).  Since $H$ only uses two of the order $3$ elements in $S_4$, at least one of the non-identity cosets in $S_4 / H$, say $C_1$, contains an element with order $3$.  Let $\sigma \in C_1$ with $|\sigma| = 3$.  Then $(C_1)^3 = \sigma^3 H = H$.  But that means that $<C_1>$ is a subgroup of $S_4 / H$ with order $3$.  That's a contradiction since the order of subgroups of $S_4 / H$ must divide $8$.  Therefore, $H$ is not a normal subgroup and $S_4$ cannot have any normal subgroups with order $3$.


How do I programmatically set up multiple default flags?

Question: How do I programmatically set up multiple default flags?
The documentation shows how to create a single flag using mymodule_flag_default_flags(). If I need two or three default flags for my custom module, how could I achieve it?
Answer: Figured it out. To have multiple default flags you simple do this:
function mymodule_flag_default_flags() {

$flags = array();

$flags['FLAG_NUMBER_1'] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

$flags['FLAG_NUMBER_2'] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

return $flags;

}

where ['FLAG_NUMBER'] is the machine name for the flag.


Determinacy of Negation of Class of Formula

Question: First, this question is strictly in the context of Reverse Mathematics where various set comprehension and various axiom of choice may not be available.
Question: Over $\text{RCA}_0$, if one has $\Sigma_1^0$-DET in Baire Space, does one have $\Pi_1^0$-DET in Baire Space? (Games in Baire Space are the only kind considered in Simpson's book).
For example, it is clear that $\Sigma_1^0$-DET in Cantor space implies $\Pi_1^0$-DET in Cantor Space. Given a $\Pi_1^0$ formula $\varphi(f)$. Consider the new $\Sigma_1^0$ game $\neg\varphi(0*f)$ and $\neg\varphi(1*f)$.
Case 1: If there exists an $i$ ($i = 0$ or $i = 1$) such that Player II has a winning strategy $T'$ in $\neg\varphi(i*f)$, then Player I has a winning strategy $S$ for $\varphi(f)$ where $S$ plays $i$ on the first move and then follows $T'$.
Case 2 : If player I has a winning strategy $S'$ for $\neg\varphi(0*f)$ and a winning strategy $S''$ for $\neg\varphi(1*f)$, then player II has a winning $T$ for $\varphi(f)$ which is described as follows, if Player I plays $0$, then player II follows $S'$ and if Player I plays $1$, then Player II follows $S''$.
Note that the above does not require the axiom of choice because in the second case, I constructed $T$ by merely combining two strategies $S'$ and $S''$.
This argument would not hold for games in Baire Space since the analog for case II would be that for all $i \in \mathbb{N}$, player I has a winning strategy $S_i'$ for $\neg\varphi(i*f)$. However, now I can not combine all these strategy together to get a winning strategy for $\varphi(f)$.
It seems that I may have heard that this fact is true even for games in Baire Space. If this claim known to be true and how is it proved. Thanks for any help you can provide.
Answer: Given a formula $\phi(f)$, where $f$ ranges over Baire space, let $\psi(f)$ be defined as $\lnot \phi(f')$, where $f'(n) = f(n+1)$. So, basically, in game $\psi$ the first move is ignored, after which player II gets the first move to try to make $\phi(f')$ hold (really the second move of the game), while player I gets the second move (really the third) and the first player tries to make $\phi(f')$ not hold. The complexities of $\phi$ and $\psi$ will be complementary in the arithmetical or analytical hierarchy, and the roles of the two players are also reversed.
Suppose that player I has a winning strategy $s$ in game $\psi$, which means that $\psi(s(g))$ holds for any $g \in \mathbb{N}^\mathbb{N}$. Then player II can win $\phi$ by just using this strategy and pretending that the two players have swapped roles. In particular, when player I has played a finite sequence $\sigma$, player II will simply compute the number $s(\sigma) \in \mathbb{N}$ and play this number. This gives a strategy $s^*$ for player II in game $\phi$.
Say player I plays an infinite sequence of moves $g$ in game $\phi$. Then $\psi(s(g))$ will hold, by definition of $s$, so $\phi(s(g)')$ will not hold. But $s^*(g) = s(g)'$ so $\phi(s^*(g))$ will not hold, i.e., player II will win game $\phi$ using strategy $s^*$ against $g$.
Similarly, if player II has a winning strategy $s$ in game $\psi$, which gives a way to make $\phi(f')$ hold, then player I can win game $\phi$, by using the winning strategy for $\psi$ and pretending that the two players have swapped roles.
Now the strategy $s^*$ for player I is defined from $s$ by arbitrarily letting $s^*(\sigma) = s(0 * \sigma)$; the choice of $0$ won't matter because $s$ is a winning strategy for II in game $\psi$.
Say player II plays an infinite sequence $g$ against $\phi$. Then $\phi(s(0 * g)')$ will hold because $s$ is winning for player II in game $\psi$. Again $s^*(g) = s(0 * g)'$, although the calculation is different because $s^*$ is now a strategy for player I. Since $\phi(s^*(g))$ holds, player I will win game $\phi$ when II plays $g$.
This shows that determinacy respects complementary classes all the way up the arithmetical and analytical hierarchies. Comparing this to the argument in the question, the trick is to just discard the first move rather than trying to do anything with it.
Comment: Thanks. Ignoring the first move is very clever.
Comment: I can't take credit for it, this is just a standard proof.


nginx is redirecting all requests to root

Question: I am new to nginx configurations. NGINX is redirecting all my requests to the home page and i do have an admin area placed in the /app folder in the root. My configuration is below. What am I doing wrong?
<code>server
{
   listen 443 default_server ssl;
   listen [::]:443 ssl http2;
   server_name xxxxxxx.io www.xxxxxxx.io;
   ssl_certificate /etc/letsencrypt/live/xxxxxxx.io/fullchain.pem; # managed by Certbot
   ssl_certificate_key /etc/letsencrypt/live/xxxxxxx.io/privkey.pem; # managed by Certbot
   location /
   {
      root /home/ubuntu/xxxxxxx-ui/_work/xxxxxxxWebV1/xxxxxxxWebV1/build/web/;
      index index.html index.php;
      # try_files $uri /index.html index.php;
   }

    error_log /var/log/nginx/xxxxxxx.log;
    access_log /var/log/nginx/xxxxxxx.log;
}

server
{

    listen  80;
    server_name xxxxxxx.io www.xxxxxxx.io;
    return 301 https://xxxxxxx.io$request_uri;
    charset utf-8;
    root  /home/ubuntu/xxxxxxx-ui/_work/xxxxxxxWebV1/xxxxxxxWebV1/build/web/;
    index  index.html index.htm index.php;
    # Always serve index.html for any request
    location /
    {
        root /home/ubuntu/xxxxxxx-ui/_work/xxxxxxxWebV1/xxxxxxxWebV1/build/web/;
        # try_files $uri = index.html index.php;
    }
    return 301 https://xxxxxxx.io$request_uri; # managed by Certbot
    error_log  /var/log/nginx/vue-app-error.log;
    access_log /var/log/nginx/vue-app-access.log;
}
</code>
Answer: I figured it out. I moved the root directive outside of the location block and it now works very well.


If $k$ is the smallest positive integer such that $a^k=1$ and $a^n=1$, where $a$ is an element of group $G$, $n\in\mathbb{Z^+}$, then $k$ divides $n$

Question: I am hoping for verification of this proof. My concern is if the contradiction really refutes that k does not divide n.
PROOF
Let $a\in G$ where $G$ is a group.  Let $k$ be the smallest positive integer such that $a^k=1$.  Let $n\in\mathbb{Z^+}$, such that $a^n=1$.
This implies that $k\le n$.  If $k=n$ and $p=1$, then $n=kp$.  Thus $k$ divides $n$.
Now consider $k<n$.
If $k=1$, then $a^k=a^1=1$.  Choose $m=n$.  Then $n=m=1m=km$ and $k$ divides $n$.
Now assume $k>1$ and assume $\forall q\in\mathbb{Z}$, $n\ne kq$.
Since  $1<k<n$ we can exclude the cases on $q\le 0$ and we consider only $q>0$.
Choose a $q$ such that $kq<n$ and $k(q+1)>n$.  This $q$ exists in view of the division algorithm, $n=kq+r$, where $r\in\mathbb{Z}$ and $0\le r < \vert k\vert = k$.  This implies that $kq=n-r<n$ and $n< kq+k = k(q+1)$.
Subtracting $kq$ from both sides of the latter inequality gives $0<n-kq<k$.
Thus, we have $a^n=1=1^q=(a^k)^q=a^{kq}$.  This implies that $a^{n-qk}=1$.  Since $n-kq<k$, this implies that k is not the smallest positive integer such that $a^k=1$, a contradiction.
Hence, there exists a $q\in\mathbb{Z}$ such that $n=kq$.  Therefore $k$ divides $n$.
Comment: Can't you just write $n=kq + r$ where $0\leq r<k$ and then $a^n = (a^k)^q*a^r = a^r = 1$ and since $r < k$, $r=0$?
Comment: The proofs in the linked dupes (by Euclidean descent) also work here. You are on the way to rediscover them (in less concise form).
Comment: If you know about subgroups of $\mathbb Z$, then the set $\{ n \in \mathbb Z : a^n =1\}$ is a nontrivial subgroup of $\mathbb Z$ and so is generated by its smallest positive element.
Comment: @Snowball yes. But I should have had $0<r<k$. Thank you.
Comment: @Ihf not that far along yet. Just started with group theory. Thank you, though.
Comment: @Bill Dubuque thank you. That is excellent. I actually wanted to prove this statement for a problem that asked whether or not it $k$ divides $n$, but did not ask for the proof. Basically, in chapter 1.1 of the abstract algebra book I just started. I am just happy I was on the right track, which it seems was so, despite an unoptimized proof. Your link, however, is very informative.
Comment: Glad it helped. I expanded [this answer.](https://math.stackexchange.com/a/719321/242)
Comment: @Bill Dubuque so cool. I am just learning real mathematics myself (I am a chemist and pharmacist). Such examples are why I find it so amazing. Thanks again.
Answer: You can simplify the proof.  If $k \nmid n$, then by the division algorithm $\exists q, r \in \Bbb Z^+~(n=kq+r)$, where $0 \lt r \lt k$.  But then $1=a^n= a^{kq} a^r=({a^k})^q a^r=1^qa^r=a^r $, contradicting the minimality of $k$.
Comment: Thank you. And, in turn, showing that contradiction provides for divisibility, as non-divisibility was implied in the $r>0$.


Writing / Reading Value to an Array in C

Question: I must be going insane. This is incredibly simple so I am apparently overlooking something:
Here is my code:

int salesarray[20];
scanf("%d",&sales_input);
printf("sales_input is %d",sales_input);
salesarray[i] = sales_input;
printf("salesValue is %d",i,salesarray[i]);

Here is what I will see:
sales_input is 2salesValue is 1
Can anyone explain why my array is not being updated properly? salesValue should be changing to the value 2. Or I am reading it wrong here...
Comment: The %d in your second printf prints the value of i, not salesarray[i].
Comment: I'm sorry everyone -- I confused myself here since its so late. Everyone is right -- I should be just using printf("text",salesarray[i]);

My fault for copying my own code from a previous project and then failing to carefully inspect it.
Answer: Fix this:
printf("salesValue is %d",i,salesarray[i]);

shouldn't it be?
printf("salesValue is %d", salesarray[i]);

Comment: What is wrong with it? I'm sorry -- its 3:36 AM, I must not be seeing something here.
Comment: @BSchlinker, you want to output i or salesarray[i] ?
Answer: printf("salesValue is %d",i,salesarray[i]);

is missing a %d (you are not printing the salesarray value at all):
printf("salesValue is %d %d",i,salesarray[i]);

Try compiling with -Wall -Werror to make warnings into errors. -Werror would have showing you the problem from the beginning
Answer: Do you want to print i or salesarray[i]?
You only have a single %d in the printf "format string" ...
printf("salesValue is %d",i,salesarray[i]);
/*                        ^ ^^^^^^^^^^^^^ */


$x$ is a member of $X$ if it is a member of $Y$--what is proof that $X=Y$?

Question: $x$ is a member of $X$ if it is a member of $Y$. From this fact can we get to the statement $X=Y$?
Comment: That's just the definition of Y being a subset of X. You need X to also be a subset of Y for set equality.
Comment: To see this for yourself, try some examples and use a Venn diagram.
Answer: You can't make this conclusion unless the converse is true as well that if y is a member of Y then it is also a member of X


Interpretation of power and detectable difference

Question: I know power is the likelihood of correctly rejecting the null hypothesis, but I just want to check that my interpretation of it with the detectable difference is correct.
Consider a 2 sample test with the null hypothesis that there is no difference between group means.
My understanding is that, by putting a minimum detectable difference of say 5%, with power 80%, into the sample size calculation, then in conjunction with the computed sample size this means that:

if the true difference is 5% then my test will have a likelihood of 80% of rejecting the null hypothesis.  My test will also have a slightly higher likelihood of rejecting the null hypothesis if the true difference is 6%, etc.

Is this correct?
Comment: Short answer: yes. Longer answer to follow.
Comment: Are you the same person as [this user](http://stats.stackexchange.com/users/39704/hatti) (cf. [this question](http://stats.stackexchange.com/questions/85804/choosing-between-z-test-and-t-test)), @Hatti? If so, please register & merge your accounts (see [here](http://stats.stackexchange.com/help/merging-accounts)). This has advantages for you: eg, you will be notified if something happens on 1 of your questions, & your previous good questions have earned you privileges such as the ability to vote. It also helps CV function smoothly & properly.
Answer: Your understanding looks correct, but when talking to statisticians it's best not to use the word 'likelihood' when you mean 'probability'; in statistics likelihood is a technical term with a very specific meaning (one that isn't the same thing as probability).
When computing sample size, it's common to specify what power is desired for a specific effect size (for some situations, a few additional details or assumptions may be required as well).
If you specify a minimum desired power at a given a sample size, then the effect size that gives that power is often called the "minimum detectable difference".
If the true effect size is larger, the power will be larger (just as you said), if it's smaller, the power will be smaller.
If you draw the relationship between power and effect size, you get a thing called a power curve.
Here's a power curve for a two-sample t-test, n=35 in each group, with the effect size measured in number of $\sigma$'s of difference between means:

The 80% power line is marked in, and corresponds to an effect size of about $0.68\sigma$. In this case both sides of the power curve are shown, but for symmetric cases it's common to omit the left side (or equivalently to put the effect size as $|\mu_1-\mu_2|/\sigma$, thus only getting the curve on right side in the above diagram).
The "power" at effect size 0 is really the probability of rejection when the null is true (i.e. not actually power at that point) - which is of course the significance level, $\alpha$; in the above plot that's 0.05. Normally the rejection rate at that point is drawn in, even though it's not strictly power.
Here are a few other examples of power curves (used in answers to other questions):
(1) A power comparison of paired t-test (curve) and Signed Rank test (points) for 4 pairs of normal observations (it's actually two-sided, but the left half isn't shown as it's a mirror image of the right half):

(2) Power for a binomial (one tailed test):

(3) These can even be drawn for goodness of fit tests if you restrict consideration to a particular set of alternatives (in this case, the null is normality, and the subset of alternatives considered in this power comparison are gamma distributions):
Comment: Note that this is a post made more than four and a half years ago. Further, each of the plots contained in it are from posts made earlier still (some may well be 7 or 8 years old), so source code would not be made available here unless I wrote it again. You may be able to locate some of the earlier posts if a particular analysis interests you and some of those *might* have code. However, I expect it would be much more instructive to write one for yourself. Did you anticipate some difficulty in doing so? If it's not a pure coding-question it may be that you can post an on-topic question here.
Comment: Thanks so much for your reply, just want to make sure I'm using the correct terminology though, sorry.  I think it's because it's called 'minimal' detectable difference.  With a 2-sample test, you get an estimate of the difference with a confidence interval.  So smaller differences than the MDD can be detected (down to the half-width of the confidence interval) but with smaller power? Thanks again!
Comment: Yes, that's my understanding of the situation.
Comment: Will be also the source code for this analysis provided? Thanks.


Are the boost socket read and write functions thread safe?

Question: I use the boost.asio to implement the network communication. In Main thread, I create the TCP socket and connect the remote machine. Then start a working thread to read data from the socket. In the Main thread, the same socket is used to send data. That means the same socket is used in two threads without mutex. The code is pasted below. Is there any issue regarding the read and write functions of the socket?
<code>boost::asio::io_service         m_io_service;
boost::asio::ip::tcp::socket    m_socket(m_io_service);
boost::thread*                  m_pReceiveThread;

void Receive();

void Connect()
{
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 13);
    m_socket.connect(endpoint);

    m_pReceiveThread = new boost::thread(Receive);
}

void Send()
{
    std::wstring strData(L"Message");
    boost::system::error_code error;
    const std::size_t byteSize = boost::asio::write(m_socket, boost::asio::buffer(strData), error);
}

void Receive()
{
    for (;;)
    {
        boost::array<wchar_t, 128> buf = {0};
        boost::system::error_code error;

        const std::size_t byteSize = m_socket.read_some(boost::asio::buffer(buf), error);

        // Dispatch the received data through event notification.
    }
}

int main()
{

    Connect();

    while(true)
    {
        boost::this_thread::sleep( boost::posix_time::seconds(1));
        Send();

    }

    return 0;
}
</code>
Comment: Sending and receiving uses different buffers, so on the low level it might be okay. However, errors are shared on the low level, so that will of course propagate up to your use of Boost in different threads.
Answer: No, this doesn't appear to be thread safe, per the bottom of http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/ip__tcp/socket.html, and previous answers at boost::asio::socket thread safety


Can structs be compared with hashes or dictionaries

Question: I have been trying to understand the use of structs in C to have a better understanding on programming concepts in general and structs are some how confusing to me; it's easy to learn the syntax but hard to determine why and when to use them, I got to the point to believe that structs are just one more tool in the C programming language since it looks like you could accomplish anything you want without really having to use structs. Again, this is what I think so far since I don't fully understand them.
Besides creating a unique data-type with structs what would be the difference between structs and hashes/dictionaries?
What would be the main benefit of choosing structs?
Does it make sense to think about structs as hashes or dictionaries?
Again, I'm just trying to have a better understanding about concept of structs in C.
Thanks
Comment: Please choose one language to ask about, either C or C++. They are different languages, and structs are different in them. In C, they are simply data. In C++, they may have active components (methods) and more complicated semantics. If you need to ask about both languages, then use separate questions. When you have decided, please remove the other tag and edit the question to specify the language.
Comment: Thinking that some feature doesn't have use is common among new learners. I've heard some friend of my saying that OOP is useless or design pattern is useless and even pointers and callbacks are useless. If you think that way, is because you haven't yet overcame any programming questions large scaled enough. Just keep in mind, every feature in any popular programming language has it's meaning because the creators of them are not idiots, on the contrary, they're genius.
Comment: @Eric Postpischil: There's no reason to compulsively say "C is not C++" just because you've seen both tags at a time. The idea of structures and classes is similar in C and C++. This is a good question from someone who thinks about how OOP is done in other languages. While the fields of structures (read it as: classes) are known at compile-time, the keys of hashmaps aren't, which makes it similar to classes in languages like Python. Actually, I like this question. It's the question of someone who already knows a language and compares the new language with the ones she's already familiar with.
Comment: @EricPostpischil: Yes, they are different, no question about that. But the basic idea is the same (as opposed to the way how classes are implemented in languages like Python). The differences between C and C++ structs are actually syntactic sugar. This isn't a question about programming style, idioms or anything similar; it's a question about how C/C++ structs are similar to hashmaps. The differences between C and C++ don't matter here at all!
Comment: @EricPostpischil: People who are thinking about this question may be interested in the answers given here, no matter whether they want to write C or C++ code.
Comment: Could any of the downvoters be so good to give an explanation? I can't see any problem with that question...
Comment: "'Questions asking for code must demonstrate […]'" — this question is asking for code? Honi soit qui mal y pense…
Comment: @TwilightSun: I was totally with you until you said that *every* feature has a meaning. Some features are widely acknowledged to have been mistakes, or are explicitly stated to be present only because of backward-compatibility.
Comment: @ruakh Well, I had to admit that you may be right. But the author of the language definitely wanted to solve some problem by adding a feature, it just might not turn out to be as perfect as the author thought in the first place.
Comment: @mafso: I did not object to having both tags "just because" both were present, and it is a straw man to suggest it. As my comment states, structs are different in C and C++. The answers should be different for each language, and they should not be conflated because that dilutes the search results for people seeking answers for one language specifically.
Answer:
Does it make sense to think about structs as hashes or dictionaries?

No, they are neither. Introducing hashes/dictionaries only muddies the water; in fact, neither C nor C++ provide hashes/dictionaries (though the C++ standard library provides some containers that make use of hashing, and maps could be called "dictionaries").
In C++, structs are classes, so the question you should be asking is "what is the benefit of a class?"
The answer to this question can be found very easily on the internet and in your C++ book (which I suggest you read now!) but, in brief, classes:

group data into one object
group operations
allow encapsulation for safety

At the very simplest level, ask yourself whether you would want to pass around 10 integers to lots of functions, repetitively, or group them into a single object and send that one.
In C, the grouping of data is pretty much all you get from structs, but that's still very useful.
Answer: There is a conceptual similarity between structs/classes in C/C++ and hash tables/dictionaries. In both cases, values are associated with "keys" and can be accessed using the "key" value. However, the two things are different in one very important respect:

Structs/classes map data and functions (whether through pointers or as methods) to identifiers provided by the programmer in the source code while hash tables/dictionaries map data to key values provided by the user of the compiled code, either directly or indirectly.

The consequence of this distinction is that the compiler replaces the identifiers provided by the programmer with memory addresses and offsets at compile-time -- slightly more complicated in the case of dynamically allocated objects. Users of the compiled code cannot add or remove members of structs/classes. In the case of hash tables/dictionaries, the users of the compiled code can typically add and remove members -- though not always, depending on what the programmer has provided -- and various hashing or indexing methods are evaluated at run-time to update or access members of the hash table/dictionary.
Still, while there is a conceptual similarity, programmers are trying to develop very different solutions when using either mechanism in C or C++ and will almost never encounter a situation which calls for choosing between a struct/class or hash table/dictionary. The need and use cases for each are sufficiently different to ensure that kind of a choice will never trouble a programmer in practice.
Answer: Consider a program that maintains a list of students at a school.  The students will have names, addresses, dates of birth, classes they're enrolled in etc..  You could put each of these things in separate containers (probably hash tables or balanced binary trees, sorted arrays if they don't change much) keyed on their student id, but then you'd have to find them all separately and access lots of pages of memory to get all the information for a single student.  Using structures, you can effectively say "store all this information together", then put the struct of such fields into a single place in an array or hash table.
In C++ they're more powerful as you can use Object Oriented/Orientated Programming to force people to use a particular set of functions to interact with the data, which helps you keep it - and even related data outside the struct - in a consistent, valid state.  (OOP has other functionality too, but that's the most relevant and fundamental here).
Comment: Thank you all for the good explanations, it starting to make sense, I thought I had read enough to have a good understanding but aparently NOT, I will look into it deeply. Thanks a lot.