Full archive configuration export doesn't work

Question: When I go to /admin/config/development/configuration/full/export and want to export the full archive, the site loads for a while and then just goes completely blank and the URL bar shows /admin/config/development/configuration/full/export-download.
There is no error in the server log files and no entry in the Drupal reports.
In the sync directory sites\default\files\config_[...]\sync there is no file except for the .htaccess.
And when I try drush cex or drush cex sync this error occurs:
PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in C:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\lib\Drush\Command\DrushInputAdapter.php on line 27

I've tried everything with the settings.local.php enabled and disabled. But the export just doesn't work. What can I do?
Comment: probably outdated drush or too new php version....just guessing.
Answer: Firstly, What is the version of drush?
I advise that you use the console bundle(add it via composer:  "drupal/console": "~1.0")
and then execute this command
drupal config:export  --directory="modules/custom/import_export_config/config/install/"

Comment: I installed the console with composer `require drupal/console:~1.0 --prefer-dist --optimize-autoloader --sort-packages` but then when I run `drupal list` I get `Fatal error: Uncaught Error: Call to undefined method Drupal\Console\Core\Utils\DrupalFinder::getVendorDir() in vendor\drupal\console-core\src\Utils\DrupalFinder.php on line 41`


Como retornar 2 decimais em um valor monetário com jQuery?

Question: Como posso tratar esta string para que seja retornado apenas 2 decimais depois do ponto?
<code>$(".subtotal2").text(23.90);
    var sum = 0;
    $(".subtotal2").each(function() {

        var val = $.trim( $(this).text() );
        if (val) { val = parseFloat( val.replace( /^\$/, "" ) ); sum += !isNaN( val ) ? val : 0; }

});
$(".todo_total").text(sum*12);
</code>

Este código por enquanto me retorna isso:
Comment: [Não use `float` pra representar dinheiro em JavaScript](http://pt.stackoverflow.com/q/11018/215), se possível. Use valores inteiros, representando a menor unidade possível (centavos).
Comment: Relacionado: http://pt.stackoverflow.com/questions/11018/como-representar-dinheiro-em-javascript & também: http://pt.stackoverflow.com/questions/14728/realiza%C3%A7%C3%A3o-de-contas-de-ponto-flutuante-em-javascript-com-precis%C3%A3o-absoluta
Answer: Há ótimas respostas sobre o assunto no SO inglês.
Você pode até formatar a sua saída utilizando funções como:
<code>toFixed(2);
toPrecision(12);
sprintf("%.2f", number);
round(number, 12);
</code>
Porém, como o @mgibsonbr já comentou, o melhor a fazer é usar inteiros.
Se quiser consultar por quê isso ocorre, acesse THE FLOATING-POINT GUIDE
Answer: Faça assim amigo:
<code>$(".subtotal2").text((23.90).toFixed(2));
$(".todo_total").text((sum*12).toFixed(2));
</code>


Making an API request every X amount of seconds in reactJS

Question: On entering CurrencyPage, I am trying to get the list of currencyConversionRates from database and then subsequently set an interval to constantly get the new updated list of currencyConversionRates every 6 seconds.
Up till this point, everything works fine. However, I am unable to pass the value of the setInterval to the cleanup function. The value being returned is always in the format of a promise
Promise {<fulfilled>: 1}

How can I pass the setInterval value to the cleanup function so that the interval stops being executed upon navigating to other pages
Use Effect
useEffect(() => {
    const getCurrencyConversionRates=async()=>{
        console.log("Retrieving list of currency conversion rate");
        await retrieveCurrencyConversionRateFunction();

        //Gets new information every 6 seconds
        const intervalCall = setInterval(async() => {
            console.log("Getting new currency conversion rates!");
            const currTime = new Date().toLocaleTimeString();
            console.log("Time -> "+currTime);
            await retrieveCurrencyConversionRateFunction();
        }, 60*100);

        //Have to wait until currencyConversionRateFunction is loaded before the map function is called on it in the render view otherwise will have error
        setLoading(false);
        return intervalCall;
    }

    let intervalCall = getCurrencyConversionRates();
    //Clear interval
    return () => {
        console.log("CLEARING CURRENCY INTERVAL HERE");
        console.log(intervalCall);
        clearInterval(intervalCall);
      };

},[]);

Solution Based on Azzy's answer
Rather than to try and return the interval in getCurrencyConversionRates(), a simple alternative is to just initialize a variable to store the setInterval as it is created within the function.
Note to self -> It is not possible to pass a variable by reference through getCurrencyConversionRates() as a parameter as changes made to the variable wont be saved. However, in JS you can simply initialize the variable outside of the function and modify it's value from within the function.
https://www.javascripttutorial.net/javascript-pass-by-value/
useEffect(() => {

    const getCurrencyConversionRates=async()=>{
        // console.log("Retrieving list of currency conversion rate");
        await retrieveCurrencyConversionRateFunction();

        //Gets new information every 6 seconds
        intervalCall = setInterval(async() => {
            // console.log("Getting new currency conversion rates!");
            const currTime = new Date().toLocaleTimeString();
            console.log("Time -> "+currTime);
            await retrieveCurrencyConversionRateFunction();
        }, 60*100);

        //Have to wait until currencyConversionRateFunction is loaded before the map function is called on it in the render view otherwise will have error
        setLoading(false);
        // return intervalCall;
    }

    let intervalCall;
    getCurrencyConversionRates();

    //Clear interval
    return () => {
        console.log("CLEARING CURRENCY INTERVAL HERE");
        console.log(intervalCall);
        clearInterval(intervalCall);
      };

},[]);

Comment: You have to await for it. Every thing returned from an async function is a promise
Comment: @Konrad but i cant await getCurrencyConversionRates(); i cant make useEffect async
Comment: You could store the interval id in a ref so that you don't have to wait for the function to return it
Comment: @PhantomSpooks can you give an example? is it like storing it in a state?
Answer: This will help
useEffect(() => {

   let isValid = true;

   let intervalCall;

    const getCurrencyConversionRates = async () => {
        console.log("Retrieving list of currency conversion rate");
        await retrieveCurrencyConversionRateFunction();
        // after await if the component unmounts, and this scope
        // becomes stale, skip futher execution
        // so the interval wont be started, and wont break in dev mode where useEffect runs twice
        if (!isValid) { return; }

        //Gets new information every 6 seconds
         intervalCall = setInterval( async () => {
            console.log("Getting new currency conversion rates!");
            const currTime = new Date().toLocaleTimeString();
            console.log("Time -> "+currTime);
            await retrieveCurrencyConversionRateFunction();

            // might want to check valid scope inside
            // retrieveCurrencyConversionRateFunction
            // by passing it a flag to skip execution on a unmounted component scope

        }, 60*100);

        //Have to wait until currencyConversionRateFunction is loaded before the map function is called on it in the render view otherwise will have error
        setLoading(false);
    }

    getCurrencyConversionRates();
    //Clear interval
    return () => {
        console.log("CLEARING CURRENCY INTERVAL HERE");
        isValid = false

        // if interval was not stared, dont clear it
        if (intervalCall) {  clearInterval(intervalCall); }
        console.log(intervalCall);

      };

},[]);

more about useEffect life cycle, to get an idea why

A new effect is created after every render
The cleanup for previous effect occurs before executing of current useEffect

You can read about why isValid is set synchronizing with effects
If you are intererested in taking a deep dive, consider reading a blog post by Dan on useEffect, its old but explans the details to build a good mental model about useEffect and functional components.
Hope it helps, cheers
Comment: It works! but can you explain the logic behind it
Comment: After testing your solution , I realized you could simply set the value of variable intervalCall from the subfunction retrieveCurrencyConversionRateFunction() despite being on a different scope.

I tried passing the variable in by parameter and editing it by reference but it didnt work hence i thought it wouldnt be possible
Comment: I edited the answer with brief explanation and links to new docs, but I am trying to understand the new point, and if it could interval not being cleared
Comment: Yes you can optimize the solution, the answer is ment to be simple enough to explain what is going in
Comment: I have edited my question to include the solution that i have used which is a modification to your suggested answer. Thanks for your help!
Comment: Welcome, glad you where able solve the problem


Why does the boost lib have external linkage, not internal? (Best practice of linkage for header-only)

Question: Boost library defines functions as following style;
<code>namespace boost::io::detail {
    template<class Iter, class Facet>
    Iter wrap_scan_notdigit(...) {
        // snip
    }
}
</code>
To my understanding, the function has external linkage because

the namespace is on the global scope, not unnamed
function is not "static" declared

From my experience, the external linkage on the header often causes the ODR violation.
For example, two different translation units could include the different versions; this often happens when you use 3rd-party .so .a (static) libs.
The critical issue of the ODR violation is NDR: compiler/linker doesn't have to emit errors, but it could generate an execution-time bug in the rare case.
The internal linkage can avoid the problem.
So my question is (same as on the title):

Why is the boost's linkage external, not internal?
(To be generalized above) How should I set the linkage for my header-only library?
Comment: `inline` is the tool for this job, not `static`, and all function templates are `inline` by default.
Comment: You don't set any linkage in header-only library. Linkage is something that users of your library have to take care of. If there's any ODR violations because user wants to use different versions of boost library then they are screwed. It can only be resolved by separating the includes into different shared libraries. However, with C++20 modules it is possible to fix it in much simpler manner.
Comment: @ALX23z "different versions" - the same issue applies when users include the same version in a TU that has different flags/defines.
Comment: @MilesBudnek... `inline` functions still can participate in linking depending on compilers wishes. `static` / unnamed namespace functions declared in cpp aren't linked.
Comment: @ALX23z Yes, you're right. header.h itself doesn't have linkage, but included tokens by source.cpp has. I just omitted it.
Comment: @MilesBudnek TMU `inline` does *NOT* solve the situation in my question. `inline` does not change its linkage. ODR could be caused by functions which have the same name but different tokens even if inline. Am I wrong?
Answer:
the external linkage on the header often causes the ODR violation.

Only when the headers are poorly written (or possibly when they are poorly used, if definitions depend on preprocessor directives).
External linkage reduces code bloat, as you need only one copy of each function per program, rather than one copy per translation unit.

this often happens when you use 3rd-party .so libs.

Library object code should not export symbols from header-only libraries. The point of header-only is that it is available without linking to library object code.
Comment: Sorry for confusing you. It's my mistake (I'm not familiar with Linux). I wanted to write "3rd-party *.a* static libs". Static lib should contain the header-only lib's symbol. So the header-only lib who doesn't case its linkage has risk of  ODR violation as I said.


i want to clear 0 behind the decimals

Question: I have a problem because I want to show only a digit that isn't 0 such as
9 / 2 = 4.5 not 4.500000
8 / 3 = 2.666667
20 / 8 = 1.25 not 1.250000
Is there any code that will help me?
Answer: Try this:
<code>float f = 4.500000f;
NSString *s = [NSString stringWithFormat:@"%g", f];
</code>

i want to clear 0 behind the decimals


Convert dedicated server from Linux to FreeBSD

Question: I have a dedicated server with CentOS 4 on it. I want to put FreeBSD 7 on it, but I do not have console access nor physical access.
I was thinking of doing a generic install of FreeBSD on a local machine, making config tweaks such as setting up network cards etc, and then creating a disk image of the install. I would then write this image onto the server with netcat feeding dd. Only problem is, transferring 70G of data (the size of the disk) is not practical. I can't think of a good way to get around this while still being sure the system will boot FreeBSD properly when rebooted.
Of course, in order for this to work, I need to minimize reboots and try to do everything from the working Linux install. Has anyone pulled something like this off before? How did you do it?
Comment: I wouldn't even upgrade to Centos 5 in those conditions, switching over to an entirely different OS is a recipe for disaster. Forget it.
Answer: If I were you, I'd first set up a testbed server to replicate your remote system, then try to convert it in-house where screwing up won't kill your system.
I don't know what you have available as options in terms of how your remote system is hosted. Ideally you'd be able to boot or get it to boot something like RIP Linux, a memory-hosted OS so that you could manipulate the hard disk without running anything off it. I think that unless you have a way to control what boots when, you're asking for trouble manipulating the system disk while still running the system.
You could try using gparted to shrink your partitions down and then create a new partition in the blank space, then install FreeBSD into that slice and do a "dual boot" into the other system. That might be feasible.
No matter what, though, I'd still try doing it all in-house with a testbed to ensure you can get it working before playing with your working server.
Answer: As others have mentioned, if your time and sanity are worth anything you should pay your provider a one-time support fee to install FreeBSD.
If you're really bent on doing this yourself and you have a separate swap or otherwise unused partition you can do this by writing a bootstrap image to the extra partition and telling grub to boot to it. The Depenguinator is supposed to be able to do this for you. I haven't used it myself but I've used the same method to remotely switch Linux distribtutions.
(You might also want to look at a provider like SoftLayer, which has dedicated servers with remote console access at a pretty decent price.)
Answer: Make the image, compress it, transfer it to the Linux server you wish to convert and , then install that image onto a second partition of that server.  Then configure the boot loader to boot to the new partition.  I don't think writing over the active parition is likely to go smoothly.
This is pretty crazy, I like it :-)
Comment: P.S. As everyone is probably going to state, its likely not to work.  I don't really see how if you are paying for this dedicated hosting they won't provide you with 'remote hands'
Answer: You first need to check with your hosting provider if they allow that. If they do, ask them if they can install for you.
Anyway, your idea can sure work, but it is too risky to do remotely without console access to the box... You will likely end up locking yourself out of it.
Answer: I think, you need to use zeroer program or something like that to reduce size of HDD image
Answer: You want to do this all remotely with no interaction at the physical server? My good man!
The only way I could think of to do this would be to create a ramdisk with your OS on it, preconfigured to work on the network at your datacenter. Once you reboot (and the ramdisk is running the show on your server), you could then conceivably perform your plan, as long as you:

Have enough RAM on your server to run a small linux OS totally in memory
Can spare wasting a partition large enough to hold your dd image, or can hold it in your ramdisk
Figure out the many vagarities of your disk on the remote server that could botch a straight dd re-image of the partition (not to mention, creating the correct boot record entries)
Do this right, the first time.

Anyway, good luck in this project, but you might want to ask if it would be cheaper, considering the time involved, to just pay the datacenter the $20 or whatever to re-image your server with FreeBSD!
Answer: Easy option: if you have a hardware virtualisation capable processor, you could strip the CentOS install back to give yourself plenty of disc space, install kvm and create yourself a virtual FreeBSD system which is the only process running on the server.  The performance hit wouldn't be too bad, and you end up just using your CentOS system as a complicated bootloader for your FreeBSD system.
Alternatively, shrink your filesystem using resize2fs, shrink the partition with cfdisk to give yourself some free disk, and create a new partition at the end.  Then download you could still use kvm (or even qemu) and with the argument -hda=/dev/hda (i.e. tell kvm that it's allowed to write to your raw hard disc - careful now) and you can run the FreeBSD installer directly onto your new partition.
Finally you can try booting your new partition by fiddling grub from within CentOS, and use the "one-shot" option to hedge your bets.  Assuming you can power cycle the system, then if it fails to boot, you only have to power cycle to reboot back into your reliable CentOS install.
A bit hairy but we've done similar things with Linux->Linux systems before.


Drupal site returning 404 error for all pages besides the main page

Question: I have two completely independent Drupal installations on the same server. Both have https enabled in the settings file, and the Apache configuration was literally copied from one file to the other. However, one of them works under HTTPS and the other does not. The broken site will open the front page successfully, but, for example, https://www.example.com/user will return a 404. https://www.example.com/index.php?q=user works fine.
I opened the apache config of the WORKING site, and changed the DocumentRoot to the directory of the BROKEN site, and tried the site using the working URL, and I see the broken site...and it IS STILL broken.  This leads me to believe that it is not Apache, but something in the Drupal installation or configuration which is misbehaving.
Both installations have an .htaccess file in the base directory, and in sites/default/files, and the files are identical.
The apache error logs for both sites have the same errors:
server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
and
server certificate does NOT include an ID which matches the server name
Any advice on where to look next?
Comment: Sounds similar to this issue:  https://www.drupal.org/node/228462
Comment: mod_rewrite is installed, but the .htaccess file is not loading. However, both sites are using the same apache install, are in the same server location (/var/www/) and share the same 000-default.conf apache config.
Answer: I copied and pasted the <VirtualHost *:443>
section several times...and every time I changed the ServerName and ServerAlias...but didn't change the <Directory /var/www/example.com>
I hang my head in shame and embarrassment.


Loading html image description div at specified height before and after image loads

Question: Ok, so I have a page that loads an image onto a div, but it happens after one sec. The image has some description and story related to it that also loads but much faster. In fact the description loads at top of screen, and then "shifts" when the image completes loading. Obviously this is bad. I want such that even if the image hasn't loaded, the description loads exactly where it would be expected to be after the image has loaded.
The structure is:

Please help so I can go home for the weekend ;)
Answer: You can show the description when image is loaded - detect it in this way with jQuery:
$("#image").load(function (){
   alert("Image loaded!");
});

see this answer for deails
Comment: Yes, I was thinking in that route but it turned out to be much simpler to load the description in an absolute sense, where it should finally be. Thanks for the suggestion.
Answer: There are several ways to solve your problem. I suggest you read this article. There you will find a solution that exactly suits your needs. At least it will reduce image jumping noticeably
Comment: Thanks! The article also did something similar to what I figured out. Check my answer.
Answer: You have two possibilities (as far as I see):

Add/display the description as soon as the image is loaded (using JS to watch, when the image is loaded)
Pre-define the width + height (or aspect ratio) of the image and reserve that space, so the image loads into it and even the text is below it, it will be in the correct position from the beginning
Comment: Yes you are partly right - the description should also be loaded into absolute positioning for it work.
Answer: One way is to add style information onto the description tag:
style="position: absolute; top: 1000px;"

Here the 1000px is the height of the actual image. This will ensure that the description loads at 1000 pixels below the top margin, leaving space for the image to then load after 1 second, without shifting the description.
Comment: And I was able to go home as well ;)


Override log4j config available in a dependency to run unit/integration tests

Question: I have a multi module Maven project (following standard conventions) with the following structure:

module "core" contains the reusable code
modules "a", "b" & "c" all have "core" as their dependency apart from their own stuff. There are many modules like "a", "b" and "c" (more than 20).

There is a log4j.xml file in test/resources for modules "a", "b" and "c" but no log4j.xml in main/resources of these. The reason being that I want a different logging config for each module.
However, due to a recent change in requirements that requires the main application to send logs to email, I have added a log4j.xml with the SMTPAppender to main/resources of "core".
I had hoped that this would make the log4j.xml available in the classpath of all three modules and the email would work. Also, I had hoped that the test/resources/log4j.xml in the individual modules "a", "b" and "c" would override that of "core" and would behave as before.
This didn't happen though. The main/resources/log4j.xml from "core" is available in the classpath even during tests, causing the test to try sending emails which I do not want.
So, I would like a solution that will ensure that the main/resources/log4j.xml from "core" will not be used when the tests run in "a", "b" and "c".
I searched for other similar posts and found this: How to override log4j.properties during testing? which is similar but different. It talks about overriding log4j.xml in the "same" project but my case is different since this is about overriding a log4j.xml available in a dependency. Also, I do not want to rename test/resources/log4j.xml to something else and configure surefire plugin to use that, due to two reasons:

I have many modules like "a", "b" & "c" where I'd have to do that, which I don't want
That would make the code look magical at first glance for other developers until they figure out (or I communicate in the docs) that there's a hidden trick in the pom.xml.

Does this have a simpler solution? All help is appreciated.
Answer: If you switched to log4j2 or logback you would solve this problem easily. These two look for log4j2-test.xml / logback-test.xml in the first place. So test configuration overrides main configuration.
Comment: Thanks for a great idea. However, at this point of time difficult to accomplish within my deadline as a dependency upgrade would require many nods. I have this noted anyway.
Answer: In each applications "a","b","c" you can move "log4j.xml" from "main/resources" to deeper package, for example, for application "a": "main/resources/com/mycompany/a".
Path to required "log4j.xml" can be specified in concrete application in several ways:
1) With system properties, for ex.
export TOMCAT_OPTS="-Dlog4j.debug -Dlog4j.configuration=foo.xml"

2) With PropertyConfigurator during application start:
PropertyConfigurator.configure(AApplication.class.getClassLoader().getResource("com/mycompany/a/log4j.properties"));

3) In web application concrete "log4j.xml" can be specified in "web.xml".
Comment: Thanks for the response. However, please note that  "a","b","c" do not have log4j.xml in main/resources. They only have it in test/resources. The log4j.xml in main/resources is coming from a dependency. I am looking for a way that ideally, would not make me tweak the log4j.xml filename in every module ("a", "b", "c" etc.) or the module pom.xml in a way that would require detailed documentation of purpose of the tweak for the sake of future modules to follow suit.


how to import from csv file to EntityForm

Question: I have two drupal sites with exactly same entity forms, I would like to import entityform submissions from site A to entityform submissions site B.
I had a look into feed modules which works very well to import node but there is no option for to import data into entityform.
Comment: You can write a custom module, read from csv file and create new form submissions programmatically.
Comment: Have a look at the [Data export import](https://www.drupal.org/project/data_export_import) module
Answer: There doesn't seem to be any contributed module available for importing Entityform submissions from CSV.
You can simply try creating a small module which read CSV data and import Entityform submissions. To do this you can simply write a batch operation using Batch API and create Entityform Submissions using code snippet available here.
Another way could be to try Bundle Copy module that works with major entity in Drupal Core and also provide simple API for new/custom Entities. I've not tried Bundle Copy with Entities other than Node. You can try if this works with Entityform if not you can use its API and extend it.
Answer: use  Entity Reference Feeds and Feed Entity Processor
> Use case

How this module works is perhaps more easily conveyed through a simple
  example:
Lets say we are importing products, together with product-reviews as
  XML from a third pary API. This happens to be an ill-designed API, and
  the reviews are nested in the XML as children of the products they
  belong to, and cannot be fetched separately.
There are multiple solutions to this problem. One could for example
  create an API wrapper, preprocessing the file and separate products
  and reviews in two xml-feeds. This is a bit of work though, comes with
  additional issues like making sure reviews are imported before
  products etc.
Entity reference feeds provides a "quick and dirty" solution. After
  creating an entity reference to product reviews in the product bundle,
  fields and properties of product reviews will be available as mapping
  targets in the mapping settings of the product importer. Products and
  reviews will now both be imported in the same run, product reviews
  created "in place" as values of the entity reference field.

and if you'll try it by yourself  I suggest custom feed mapper instead your CSV parser.how use custom field mapper feeds


Preserving powerpoint/excel property data after converting to pptx/xlsx

Question: I have vba code to convert a ppt to pptx file, but how do I preserve the file properties (author/created date, modified date, etc)? Here is the vba code that converts the, in this case .ppt file, to a pptx file.
Sub BatchSave()
' Opens each PPT in the target folder and saves as PowerPoint 2007/2010 (.pptx) format

Dim sFolder As String
Dim sPresentationName As String
Dim oPresentation As Presentation
Dim bidpList As Collection

' Select the folder:

Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Select folder and click OK"
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "Cancelled By User", , "List Folder Contents"
Exit Sub
End If
sFolder = fDialog.SelectedItems.Item(1)
If Right(sFolder, 1) <> "\" Then sFolder = sFolder + "\"
End With

' Make sure the folder name has a trailing backslash
If Right$(sFolder, 1) <> "\" Then
sFolder = sFolder & "\"
End If

' Are there PPT files there?
If Len(Dir$(sFolder & "*.PPT")) = 0 Then
MsgBox "Bad folder name or no PPT files in folder."
Exit Sub
End If

' Open and save the presentations

sPresentationName = Dir$(sFolder & "*.PPT")
While sPresentationName <> ""
Set oPresentation = Presentations.Open(sFolder & sPresentationName, , ,
False)
Call oPresentation.SaveAs(sFolder & sPresentationName & "x")
oPresentation.Close
Wend

MsgBox "DONE"

End Sub

Answer: Declaring object variables for your two presentations will simplify the code a bit, and then you can do something along these lines:
Dim oPres As Presentation
Dim oCopyPres As Presentation
Dim x As Long

Set oPres = ActivePresentation
ActivePresentation.SaveCopyAs "c:\temp\test.pptx"
Set oCopyPres = Presentations.Open("c:\temp\test.pptx")

On Error Resume Next

For x = 1 To oPres.BuiltInDocumentProperties.Count
    oCopyPres.BuiltInDocumentProperties(x).Name = oPres.BuiltInDocumentProperties(x).Name
    oCopyPres.BuiltInDocumentProperties(x).Value = oPres.BuiltInDocumentProperties(x).Value
Next

You'll want to modify this to set WithWindow false and to use variables as file names, but you're already doing that in the code you have. It should be simple enough to fold in a modified version of the code above.
Comment: I get compiling errors when writing this line: ActivePresentation.SaveCopyAs ("c:\temp\test.pptx") because there is no expression here. Expects a '='
Comment: @Gofurther Remove the parentheses.  Darned if I know why it worked here when I tried it. Sure shouldn't have.  I'll edit the code in my answer as well.  Thanks for pointing this out.


Is there midi software that can show me if I'm hitting notes on the beat?

Question: I'm practicing phrases with a metronome and I can tell that my fingers are sometimes not hitting the individual notes at the proper time, even if the overall phrase starts and ends at the right time.
Is there midi software that can give feedback about each note I play telling me how early or late I play it? I'm envisioning loading a midi file and the software shows the score (or doesn't, that's just a nice-to-have) and then I can press 'record' and it will count me in with a preset tempo, and then record the difference between the midi score and what I actually play, showing it visually somehow.
Comment: You're already aware that your timing isn't spot on. Your ears should be the ones to rely on better than a printout, and even if you make the same errors each time, ears will tell you just as well as what you're looking for. Only my opinion, therefore not an answer!
Comment: I'm trying to rely on my ears but they're not very reliable, hence my desire to train my ears and my fingers with feedback from real-time data showing me just how off I am.
Comment: Your ears & fingers will not be trained by trying to compensate for any kind of 'block on a grid' visual feedback system that is already over & done with before it appears on screen. Music is done by 'feel' not by 'whack-a-mole' or scraping flies off a windscreen like some kind of Mavis Beacon typing tutor.
Answer: Yes - any sequencer program with an Edit window that displays note-on times.   Record yourself playing to its click, despair at your inaccuracy!   We've all done it.
If you want a more musical test, set up a drum track with a suitable groove and play to that.
Quirks of the system may cause your recorded notes to have a constant offset from the 'grid'.  But it should be easy to distinguish this from inaccurate playing.
Answer: Do you have a midi file of the exact arrangement you wanna play?  Then, yeah, most any midi sequencer.
But a better way is to just record yourself with your phone.  Not the whole dang song.  Cuz you're not playing the whole dang song, riiiiight?  Just the spots you have problems with.  How do you find those?  Recoooord yourself with your phone :)
Your ears will tell you if your rhythm is solid.  But, you're right - while you're going time and your brain WILL play tricks on your judgement.  Hence the phone.


Alternatives to ratios of counts if denominators can be zero

Question: I have been given a bunch of data and asked to calculate proportions between two variables. The variables are both counts (this is social science stuff).
The problem is that there are a number of zeroes dotted althrough my dataset which of course present a problem when calculating proportions.
Is there a way that I can transform the data to get rid of the zeros? I'm not going to analyze it, so I don't need it to satisfy any specific assumptions.
Comment: Proportions are just fractions, e.g. #who do/#who could, #males/#people. Zeros on top mean zero proportions. 0/0 means no calculation possible. Not clear why you are thinking of transformations here. No transformation can replace zeros with data. Perhaps you need to give an example in which you think zeros are problematic.
Comment: Hi Nick, thanks for your reply. I have been asked to track the change in proportions over time as a way of evaluating effectiveness in a specific service - the fractions in this case are #outcome we want to be increasing / #outcome we want to be decreasing. Anything / 0 is problematic for what I have been asked to do as with each non-possible calculation I am losing a bit of data. In addition, 0 / #outcome we want to be decreasing = 0, does not give us the information we are asking for, ie whether the proportion has changed from one time point to the next. Does this make sense?
Comment: Your clear example triggered a memory that I had written about this elsewhere. I'd call these ratios (but not fractions).
Comment: "Track[ing] the change in proportions over time ... [to] evaluate effectiveness" sounds like a solid analysis to me, apparently contradicting the assertion in the last paragraph of the question. Although you may wish to make few assumptions (there can be good reasons for this), that does not mean that computing proportions will be OK. Methods that account for both counts--not just their ratio--tend to work much better because they can account for the larger uncertainties when the denominators are small, information that is entirely lost when the proportion is computed.
Comment: @whuber, apologies, this was me not being exact with my language. What I meant was that I was not planning to perform any parametric tests. What do you mean by "methods that account for both counts"? The gender role example given by Nick Cox below, seems to account for small denominators or have I understood one of you wrong?
Comment: @whuber's comment underlines that uncertainty should be assessed too. There is no contradiction between his comments and mine that I can see. Differences based on small counts will be unstable too.
Answer: When reporting ordered or graded scales, working with simple descriptive summaries like
% improved $−$ % deteriorated
or
% ranking as good $−$ % ranking as bad
is sometimes helpful. In such summaries, omitting any neutral or middle category is common (but not essential). Clearly, such a measure gives the preponderance of two tails: if everybody improved, we get $100$, and, if everybody got worse, we get $−100$.
In political terms, an election could be imagined in which there are votes "for" and "against" from these two categories, and from that context, these measures may be described as plurality measures. (Is there a better general term, or any term that is standard in some field, for particular examples of such measures?) Whatever the terminology, such measures are discussed in Tukey (1977, pp.498–502), Zeisel (1985, pp.75–77), and Wilkinson (2005, pp.57–58).
Naturally, the percent formulation is not compulsory, and you could just as easily — in fact, a little more easily — work with proportions or fractions with results ranging from $1$ to $−1$. In either case, using a difference is natural whenever thinking is in terms of the percent or proportion scale being used. Also, a ratio such as
% ranking as good / % ranking as bad
may be less desirable with small denominators. Either the result may be unstable, or, if the denominators are ever 0, it may be indeterminate.
Let us illustrate both points with the idea of looking at gender roles across a set of activities, and
% who are female $−$ % who are male
as a way of summarizing data on who does what. If, in a village, 21 women and zero men do laundry, four men and 11 women fetch water, and 14 men and zero women take care of cows, then neither the male–female ratio nor the female–male ratio can be used throughout to summarize the balance of the sexes. Whenever zero is a denominator, the ratio is indeterminate. Even if no zeros are present, we should worry about sensitivity. However, the measure above is one which is always practical.
All that said, it should be evident that the raw frequencies remain important and should be reported, or at least easily accessible. "1/3 of the cats showed improvement, 1/3 deterioration, but the other cat ran away" has an equivalent here too.
The details should be simple in your favourite software, but for Stata details see Cox (2007) on which this is based.
Cox, N.J. 2007. How do I calculate measures such as percent improved minus percent deteriorated? http://www.stata.com/support/faqs/data-management/plurality-measures/
Tukey, J. W. 1977.
Exploratory Data Analysis. Reading, MA: Addison–Wesley.
Wilkinson, L. 2005.
The Grammar of Graphics. 2nd ed. New York: Springer.
Zeisel, H. 1985.
Say It with Figures. 6th ed. New York: Harper & Row.
Comment: Thank you! That makes a lot of sense. I don't use stata but can easily change the code to R. Will have a look at the referenced literature after work.


What's equal the below power nested radical?

Question: it is well known that
$$\frac{2}{\pi}=\sqrt{\frac12}{\sqrt{\frac12+\frac12\sqrt{\frac12}}{\sqrt{\frac12+\frac12\sqrt{\frac12+\frac12\sqrt{\frac12}}}{\sqrt{\frac12+\frac12\sqrt{\frac12\cdots}}}}}$$
My Idea is to know what about above product if it is a power as shown below :
$A=\sqrt{\frac12}^{\sqrt{\frac12+\frac12\sqrt{\frac12}}^{\sqrt{\frac12+\frac12\sqrt{\frac12+\frac12\sqrt{\frac12}}}^{\sqrt{\frac12+\frac12\sqrt{\frac12\cdots}}}}}$ ?
Comment: Why do you expect that something pretty will come out of this? Generally, exponents tend to produce not so pretty results.
Comment: Each term lie between (0,1) may this give a pretty result
Comment: $.725something$. https://www.desmos.com/calculator/u2qyo0gshs
Comment: By a derivable approximation we get $A\approx 2\frac{W\left(2^{-1.1}\ln\left(2\right)\right)}{\ln\left(2\right)}\simeq 0.725581$
Comment: This infinite product often goes under the moniker: Viete's formula and has a nice several nice interpretations here:https://en.wikipedia.org/wiki/Vi%C3%A8te%27s_formula#Derivation
Answer: First, let us try to find out what $\sqrt{\frac12+\frac12\sqrt{...}}$ can evaluate to.
By a recursive trick, we can set up an equation as below
$$x = \sqrt{\frac12+\frac12x}\to x^2-\frac12x-\frac12=0$$
So, $x=-0.5,1$. Now, we note that the radical could not converge to $-0.5$ as the number of recursive units grows, so if it even converges, it would approach $1$.
That's not terribly helpful, since $x^1=x$ for all $x$. But, what could be useful is seeing how fast it converges to $1$, to see how many terms we need to carefully look at in the exponentiation.
We note that if $f(a) =\sqrt{\frac12+\frac12a}$ and $b=\sqrt{\frac12}$ (Inspired by commenter @Mason), then $$f(f(f(f(f(b)))))\sim0.9996988$$
So, 4 levels of recursion should be very close to the final limit value of this exponentiation, which gives us an approximation of $0.725657309196$. I will add more to this answer if I find a more satisfying approach.
Comment: In explicit terms, $$A = \left(\cos\tfrac{\pi}{4}\right)^{\left(\cos\tfrac{\pi}{8}\right)^{\left(\cos\tfrac{\pi}{16}\right)^{\ldots}}}$$
Comment: http://isc.carma.newcastle.edu.au/advancedCalc. Doesn't know much about this number.
Comment: Mathematica is finding a different result than desmos. Weird


nonlinear fourth-order differential equation type

Question: Does anybody know how to reduce such nonlinear fourth-order differential equation to well-known type (like Ricatti, Painlevé, sine-Gordon etc)?
$\frac{{{d^4}\phi }}{{d{x^4}}} + q\frac{{{d^2}\phi }}{{d{x^2}}} - {\omega ^2}\sin\phi  = 0$
Comment: Please, be aware that "ricatti" in Italian means (more or less) "blackmail"; the mathematician was *Riccati*.
Comment: I doubt you can reduce order here. I would just solve numerically
Answer: $$\frac{{{d^4}\phi }}{{d{x^4}}} + q\frac{{{d^2}\phi }}{{d{x^2}}} - {\omega ^2}\sin\phi  = 0$$
Even in simplified case of $q=0$, the equation $\quad\frac{{{d^4}\phi }}{{d{x^4}}} - {\omega ^2}\sin\phi  = 0\quad$ as no closed form solution, as far as I know.
The solutions of the second order ODE : $\quad\frac{{{d^2}\phi }}{{d{x^2}}} - {\omega ^2}\sin\phi  = 0\quad$ involve the $am$ Jacobi elliptic function : $\quad \phi=-2\,am\bigg(\frac12(x+c_2)\sqrt{c_1-2\omega^2}\:\bigg|\:\frac{4\omega^2}{2\omega^2+c_1} \bigg)$
As far as I know, no special function was defined for solving similar ODE of higher order such as $\quad\frac{{{d^3}\phi }}{{d{x^3}}} - {\omega ^2}\sin\phi  = 0\quad$ and even more $\quad\frac{{{d^4}\phi }}{{d{x^4}}} - {\omega ^2}\sin\phi  = 0\quad$ and a-fortiori for your equation $\quad\frac{{{d^4}\phi }}{{d{x^4}}} + q\frac{{{d^2}\phi }}{{d{x^2}}} - {\omega ^2}\sin\phi  = 0$.
As usualy done, one can consider the approximate case of small $\phi\quad\to\quad \sin(\phi)\simeq \phi$ so that :
$$\frac{{{d^4}\phi }}{{d{x^4}}} + q\frac{{{d^2}\phi }}{{d{x^2}}} - {\omega ^2}\phi  \simeq 0$$
$$\phi(x)\simeq c_1e^{r_1x}+c_2e^{r_2x}+c_3e^{r_3x}+c_4e^{r_4x}\qquad r_{1,2,3,4}=\pm\sqrt{\frac12\left(-q\pm\sqrt{q^2+4\omega^2}\right)}$$
Of course, some of the $r$ are complex which implies sinusoidal terms is the solution.
Better approximate could be obtained with more or less limited series, but it should be arduous calculus. In practice, for accurate numerical result, it is simpler to directly solve the ODE thanks to numerical method.
Comment: A lot of thanks for your answer . I did all these approximations as well as got the solution of sine-Gordon equation in the form of Jacobi elliptic functions. I just try to know how does classify this type equation among well-known differential equations? Anyway thank you again.
Comment: I don't know if this fourth degree non-linear ODE has a particular name. In term of classification, it belongs to the ODEs of autonomous kind. The change of function $\frac{d\phi}{dx}=F(\phi)$ reduces to order three. But the reduction of order is not an advantage because the three order ODE is still non-linear and with more complicated terms.
Answer: Hint:
$\dfrac{d^4\phi}{dx^4}+q\dfrac{d^2\phi}{dx^2}-\omega^2\sin\phi=0$
$\dfrac{d\phi}{dx}\dfrac{d^4\phi}{dx^4}+q\dfrac{d\phi}{dx}\dfrac{d^2\phi}{dx^2}-\omega^2(\sin\phi)\dfrac{d\phi}{dx}=0$
$\int\dfrac{d\phi}{dx}\dfrac{d^4\phi}{dx^4}~dx+q\int\dfrac{d\phi}{dx}\dfrac{d^2\phi}{dx^2}~dx-\omega^2\int(\sin\phi)\dfrac{d\phi}{dx}~dx=0$
$\int\dfrac{d\phi}{dx}~d\left(\dfrac{d^3\phi}{dx^3}\right)+q\int\dfrac{d\phi}{dx}~d\left(\dfrac{d\phi}{dx}\right)-\omega^2\int\sin\phi~d\phi=0$
$\dfrac{d\phi}{dx}\dfrac{d^3\phi}{dx^3}-\int\dfrac{d^3\phi}{dx^3}~d\left(\dfrac{d\phi}{dx}\right)+q\int\dfrac{d\phi}{dx}~d\left(\dfrac{d\phi}{dx}\right)-\omega^2\int\sin\phi~d\phi=0$
$\dfrac{d\phi}{dx}\dfrac{d^3\phi}{dx^3}-\int\dfrac{d^2\phi}{dx^2}\dfrac{d^3\phi}{dx^3}~dx+q\int\dfrac{d\phi}{dx}~d\left(\dfrac{d\phi}{dx}\right)-\omega^2\int\sin\phi~d\phi=0$
$\dfrac{d\phi}{dx}\dfrac{d^3\phi}{dx^3}-\int\dfrac{d^2\phi}{dx^2}~d\left(\dfrac{d^2\phi}{dx^2}\right)+q\int\dfrac{d\phi}{dx}~d\left(\dfrac{d\phi}{dx}\right)-\omega^2\int\sin\phi~d\phi=0$
$\dfrac{d\phi}{dx}\dfrac{d^3\phi}{dx^3}-\dfrac{1}{2}\left(\dfrac{d^2\phi}{dx^2}\right)^2+\dfrac{q}{2}\left(\dfrac{d\phi}{dx}\right)^2+\omega^2\cos\phi=c$
$2\dfrac{d\phi}{dx}\dfrac{d^3\phi}{dx^3}-\left(\dfrac{d^2\phi}{dx^2}\right)^2+q\left(\dfrac{d\phi}{dx}\right)^2+\omega^2\cos\phi=C_1$


Prove $\int_0^{\pi/2} x\left({\sin nx\over \sin x}\right)^4\mathrm{d}x<{n^2\pi^2\over 8}$

Question:
Prove $$\int_0^{\pi/2} x\left({\sin nx\over \sin x}\right)^4\mathrm{d}x<{n^2\pi^2\over 8}.$$

My attempt:
\begin{align}
\int_0^{\pi/2} x\left({\sin nx\over \sin x}\right)^4\mathrm{d}x & =\sum_{k=1}^n \int_{{k-1\over 2n}\pi}^{{k\over 2n}\pi}x\left({\sin nx\over \sin x}\right)^4\mathrm{d}x\\
& \leq\sum_{k=1}^n \left({\pi\over 2}\right)^4 \int_{{k-1\over 2n}\pi}^{{k\over 2n}\pi}\left({\sin^4nx\over x^3}\right)\mathrm{d}x \quad (\text{use } \sin x\geq {2\over \pi}x ) \tag{1}\label{1}\\
&= \left({\pi\over 2}\right)^4 n^2\sum_{k=1}^n  \int_{{k-1\over 2}\pi}^{{k\over 2}\pi}\left({\sin^4x\over x^3}\right)\mathrm{d}x \quad (\text{use } x\to {x\over n}).\\
\end{align}
Is my direction right? If right, how can I prove the following $$\sum_{k=1}^n  \int_{{k-1\over 2}\pi}^{{k\over 2}\pi}\left({\sin^4x\over x^3}\right)\mathrm{d}x\leq\int_0^{+\infty}\left({\sin^4x\over x^3}\right)\mathrm{d}x \leq {2\over \pi^2}. $$
I use Mathematica to calculate the integral $\int_0^{+\infty}\left({\sin^4x\over x^3}\right)\mathrm{d}x\simeq 0.7>{2\over\pi^2}$, hence my process (\ref{1}) seems to be wrong.
Comment: I supposed $n$ positive integer. Is it right?
Comment: @Raffaele Yes it is.
Answer: The term $\left(\frac{\sin nx}{\sin x}\right)^4$ is associated with the Jackson kernel.
Your inequality is indeed just a minor variation on Lemma 0.5 in the linked notes, and it can be proved through the same technique: expand $|x|$ as a Fourier cosine series over $\left(-\frac{\pi}{2},\frac{\pi}{2}\right)$, do the same for $\left(\frac{\sin nx}{\sin x}\right)^4$, then apply orthogonality/Bessel's inequality.
Comment: Great answer! The question is the first exercise of a chapter about integral, I thought it would be easy for me. By reading the material you give, I should estimate the $\int_0^{\pi\over 2n}$ part by using $\sin x\geq {2\over\pi}x$ and the rest using $x\geq {k\pi\over 2n}$. The first part it self still larger than the right hand side. So I need to give a more concise estimate rather than $\sin x\geq {2\over\pi} x$. By the way, if I accept the answer, how can I ask more people to find if there is a more simpler answer?


Views API - how to replace PHP fields

Question: So a client that I inherited has multiple PHP fields in each of their views.
I'd like to replace them. They're using PHP Code module as well as Views Customfield.
Would I have to write a custom views handler? Or is there some sort of alter that would allow me to basically replace each of these fields/data sources with my own information, without exposing a PHP filter to a user (even an admin user).
Basically I am trying to increase site security.
Comment: Yes, a custom views handler is the way to go. There's a great example at https://gist.github.com/juampy72/5816530 on how to implement one.
Answer: In cases like this, I usually use:
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
For pre-processing the views render array.

Views API - how to replace PHP fields


Value of the 'height' of a triangle

Question: Given the length of $AB = x_1 = 10$ and $AC = x_2 = 14$, how do I find out the length of $AD = x_3$ and $BC$?
Is $AD = \frac{1}{2}(x_1+x_2)$
and
$BC = x_2-x_1$?
Comment: The existence of two pieces of triangle is not sufficient to find the rest of the ribs
Comment: Does segment $AD$ bisect the angle $BAC$? If so one could use that $BD/DC=x_1/x_2.$
Comment: What E.H.E is stating, that you didn't tell us all needed information to solve this problem. Have you forgotten something here?
Comment: @ctst: that is all the information I have.
Comment: @coffeemath: Yes, AD bisects angle BAC.
Comment: Is angle $ABC = \pi/4$?
Comment: " that is all the information I have."  If so, then D can be any point close B and AD is very close to 10, or D can be any point close to C and AD is very close to 14.  So there's no way to answer.  " Yes, AD bisects angle BAC."  That is an *essential* piece of information.   Now D can only be only point.  So that *wasn't* all the information you had.
Answer: There seems to be some information missing, but if we make some assumptions, we may be able to generalize to where the assumptions don't matter.
Now, it looks like $\triangle ABC$ is a right triangle with hypotenuse $x_2$. It also appears that angle $A$ is 45º.  If these two assumptions are correct, then we have an isosceles right triangle. The measurements of $x_1=10$ and $x_2=14$ provide validity that these assumptions are correct. (WHY? I leave this as an exercise for the OP.)
A third assumption we can make is that $x_3$ bisects side $BC$. If this is true, then $x_3$ bisects the angle $A$ (which we are assuming to be 45º). Using $SOH-CAH-TOA$ then, we have $\cos22.5 =\frac{x_1}{x_3}$, so $x_3\approx10.8$.
If we discard our assumptions and find more data regarding the triangle, then we have, in general, $x_3=x_1\div\cos(BAD)$.

Value of the 'height' of a triangle


Longitudinal correlation structure for messy data set?

Question: My data set tracks a bunch of animals throughout a period of a couple of months.
But, it's a messy data set. It's not like I have responses from week 1, week 2, week 3, week 4, and so on.
Instead, I have responses from random dates. Some animals have a response every day during these months.
Others, have a response here and there.
So, how do I model the correlation structure of such a data set? What I mean is, I can include random effects from each animal, but what about how that changes over time?
Answer: I would fit a multilevel model. You would have to put your data in long format, with each time being whenever the person responded.
$Response_{it} = \gamma_{00} + \beta_1Time + u_{0i} + e_{it}$
Where:
$\gamma_{00}$ is the average intercept across subjects
$\beta_1$ is the fixed effect of time
$u_{0i}$ is how much a subject deviates from the average intercept
$e_{it}$ is the residual term
The R code in lme4 would look something like:
response ~ 1 + time + (1|animal)
Observations would be nested within animal. Multilevel models allow some people to have 3 measurement occasions, others 10. Some can have times at 7, 10, 13, and 21 days, another animal could have times at 10, 30, and 50 days.


Can PCA be reversed to predict original variables based off a random point in PCA space?

Question: So, I recently read this answer: https://stats.stackexchange.com/questions/34724/reversing-pca-back-to-the-original-variables
I wanted to make sure that I'm understanding this correctly. So, normally I fit PCA to a dataset, like the digits dataset. Then, I plot the resulting projections (that were created for my original dataset) onto a 2D or xy plot. My understanding was: I can select a random point x,y in the plot (that does NOT exist in the projections data I plotted, or is not a plotted point), and then reverse this x,y point with PCA to "PREDICT" the original data (e.g. predict what digit that point represents).
Is my understanding of this correct? If so, doesn't this basically make PCA a prediction algorithm?
Also, does this understanding also apply to the following UMAP article: https://umap-learn.readthedocs.io/en/latest/inverse_transform.html ?
Answer: Your understanding is only half correct. PCA (Principal Component Analysis) is a dimensionality reduction technique that finds underlying patterns in data to reduce the number of features in a dataset. It does not make predictions; rather, it generates new dimensions from existing data for further analysis or visualization.
PCA can be reversed (or "back-transformed") to reconstruct the original data, but this does not imply predicting a new point in the PCA space. To do so, you would need to use a supervised learning algorithm, such as a regression model trained on the PCA-transformed data, predict a new point (in the PC space), and then use the inverse transform to project the predicted principal components to the original space.
I'm not as familiar with UMAP, but it appears to be similar in that it can be used to reduce the dimensionality of a dataset and then inverted to reconstruct the original data. This is not, once again, the same as making a prediction.
I hope this helps!
Answer: You're missing a step: fitting some kind of predictive model. Once you transform your PCA feature space into the original features (which need not be unique unless you use all of the PCs), you have to have some way of interpreting that.
For the MNIST digits to which you allude, that could be a convolutional neural network, through which you pass the $28\times 28$ picture you derive from your point in the PCA space. For other data, you might prefer another model.
Ditto for UMAP.
Comment: I guess UMAP would be a little different in that it offers a supervised version that would be prediction target aware: https://umap-learn.readthedocs.io/en/latest/supervised.html


Why autocompletion options in Spyder 3.1 are not fully working in the Editor?

Question: Running on Mac Sierra, the autocompletion in Spyder (from Anaconda distribution), seems quite erratic. When used from the Ipython console, works as expected. However, when used from the editor (which is my main way of writing), is erratic. The autocompletion works (i.e. when pressing TAB a little box appears showing options) for some modules, such as pandas or matplotlib. So writing 'pd.' and hitting TAB, gets the box with options as expected. However, this does not happen with many other objects: for example, after defining a dataframe named 'df', typing 'df.' TAB shows nothing. In the Ipython console, 'df.' TAB would show the available procedures for that dataframe, such as groupby, and also its columns, etc..
So the question is threefold. First, is there any particular configuration that should be enabled to get this to work? I don't think so, given some time spent googling, but just wanna make sure. Second, could someone state what is the official word on what works and what doesn't in terms of autocompletion (e.g. what particular modules do work from the editor, and which ones doesn't?). Finally, what are the technical aspects of the differences between the editor and the Ipython console in the performance of the autocompletion with Spyder? I read something about Jedi vs. PsychoPy modules, so got curious (however, please keep in mind that although I have scientific experience, I am relatively new to computation, so please keep it reasonably simple for an educated but not expert person).
UPDATE: As a side question, it would be great to know why is the autocompletion better in Rodeo (another IDE). It is more new, has way fewer overall options than Spyder, but the autocompletion works perfectly in the editor.
Answer: (Spyder developer here)
My answers:

is there any particular configuration that should be enabled to get this to work?

In Spyder 3.1 we added the numpydoc library to improve completions of some objects (like Matplotlib figures and NumPy arrays). If Dataframe completions are not working for you (they are for me), please open an issue in our issue tracker on Github to track and solve this problem.

could someone state what is the official word on what works and what doesn't in terms of autocompletion (e.g. what particular modules do work from the editor, and which ones doesn't?)

The most difficult part is getting completions of definitions when an object is generated by functions or methods developed in C/C++/Fortran and not in Python. I mean, things like
import numpy as np
a = np.array([])
a.<TAB>

As I said, this should be working now for arrays, figures and dataframes, but it doesn't work for all libraries (and most scientific Python libraries are created in C/C++/Fortran and wrapped in Python for speed).
The problem is that the completion libraries we use (Rope and Jedi) can't deal with this case very well because array (for example) can't be introspected in a static way (i.e. without running code involving it). So we have to resort to tricks like analyzing array's docstring to see its return type and introspect that instead.

what are the technical aspects of the differences between the editor and the Ipython console in the performance of the autocompletion with Spyder?

The most important difference is that in the IPython console you have to run your code before getting completions about it. For example, please run this in a fresh IPython console
In [1]: import pandas as pd
   ...: df = pd.Da<Tab>

and you will see that it won't return you any completions for Da (when it obviously should return Dataframe).
But, after evaluation, it is quite simple to get completions. You can simply run
dir(pd)

to get them (that's what IPython essentially does internally).
On the other hand, Spyder's Editor doesn't have a console to run code into, so it has to get completions by running static analysis tools in your code (like Jedi and Rope). As I said, they introspect your code without running it. While they work very well for pure Python code, they have the problems I described above for compiled libraries.
And trying to evaluate the code you have in the Editor to get completions is usually not a good idea because:

It is not necessarily valid Python code all the time. For example, suppose you left an unclosed parenthesis somewhere, but you want to get completions at some other point. That should work without problems, right?
It could involve a very costly computation (e.g. loading a huge CSV in a Dataframe), so evaluating it every time to get completions (and that's a must because your code is different every time you ask for completions) could consume all your RAM in a blink.

it would be great to know why is the autocompletion better in Rodeo (another IDE)

Last time I checked (a couple of years ago), Rodeo evaluated your code to get completions. However, we'll take a look at what they are doing now to see if we can improve our completion machinery.
Comment: Boy, this is the longest answer I've written in Stackoverflow!! I'll use it as a reference for this subject because it comes up a lot among our (frustrated) users :)
Comment: Indeed a great and comprehensive answer. Thanks a lot Carlos. One more thing: could you confirm if this is something high in the priority list for Spyder? Regarding Rodeo, last weekend I checked both IDEs thoroughly, and I have to say that their autocompletion works extremely well and efficiently. Would you mind updating back here once (if) you check what they are doing? Would be great to know if is possible to improve on Spyder or if it is definitely a core, unfixable issue. Gracias y saludos!
Comment: I also noted a cool feature in Rodeo: as in the example above, assume "my_data" has one column named "foo". As expected, "my_data.f" would show the options (along with a cool box including documentation for the object). But impressively, "my_data['f" or even 'my_data[' will show suggestion for 'my_data['foo']'. I guess there has to be some core differences between Rodeo and Spyder. Any clues or hunches on what allows that behavior?
Comment: Sorry, we haven't had enough man power to take a look at this.
Comment: I'll come back to you if we can improve things by studying Rodeo's code. We also have other ideas to improve the situation. I can assure this is an important problem for us, and we have gone to great lengths to improve what Jedi and Rope provide by default. The thing is this is a very tricky problem and Spyder has a lot of other things that need attention (with debugging being perhaps the most important one), so it'll take us some time to get to a point where completion works flawlessly.
Comment: Carlos, just to be sure on the bug report: you mentioned that autocompletion should work normally for pandas. Creating some variables (say, a standard DataFrame named 'my_data' ), in the editor typing 'my_' completes normally to 'my_data' as expected, but then 'my_data.' does nothing. However, directly in the Ipython console, the latter does show all suggestions (such as .data.. Is this buggy behavior to file the report?
Comment: About the bug: `my_data.` should return suggestions in the Editor. If that's not happening for you, that's a bug. About Rodeo: those features of completion of Dataframes are provided by IPython, so I'm almost sure they are evaluating the code you have in the Editor in an IPython kernel and getting completions from it. As I said in my answer, that's very risky. But we'll have to investigate further.
Comment: Hi @CarlosCordoba, have you looked into this ? I'm using Windows 11/Python 3.10.9/Spyder 5.4, and my_data. does not return suggestions in the Editor. Nor does my_data.add( show any calltip. Both those things work in the IPython console, though. Relating to ewadaniela's answer, I do have white spaces in the path to the python interpreter. Is this a problem ?
Thanks for your great work. :)
Answer: Autocompletion  works correctly if there are NO white spaces in the project working directory path.
Answer: Autocomplete was not working for me at all.
So, I tried Tools -> Reset Sypder to factory defaults and it worked.
Comment: Worked for me as well!


Given 2 Sheets of Acrylic, determine the maximum dimensions of a rectangular prism.

Question: I have been trying to figure this out all morning and I am having no success. I know I have to use calculus, but I am not sure exactly how to set this up.
I am trying to determine the maximum length of an aquarium that I want to build, but I don't want to use more than two (2) sheets of acrylic with dimensions of 96" x 48". Also, I want to keep the sides of the aquarium square at 24" x 24".
I tried using the total area of the sheets at substituting in the formula Area= 96"*48"*2 = 2ab + 2bc + 2ac. Given that b=c=24, then we have 9,216 = 2a(24) + 2(24)(24) + 2a(24);
9,216 = 96a + 1152; a = 84. This would mean that I would need to have 4 panels of 84" x 24" (for the top, bottom, front, and back) for a total surface area on 8,064. And 2 panels of 24" x 24" (for the left and right sides). It all looked great, until I realized that I can't cut the required panes from two sheets of 96" x 48".
I don't know if it matters for the calculation, but the acrylic is 1/2" thick. The front and back panels will lie on top of the bottom panel (as opposed to being glued next to it) and the top panel will rest on top of the front and back panels. This would require the right and left side of the cube to actually be 23 1/2" x 23 1/2".
Any help would be appreciated!
Thanks a lot!
P.S.: My next step is drawing the panels to scale and try to diagram it since my math skills are proving to be insufficient!
Answer: The longest you can make out of the sheets would be 24" by 72".
You will also be left with a sheet of 24" by 48" though.
<code>+ - - - + - - - - - - - - - - - +
|       |                       |
|   A   |           S           |
|       |                       |
+ - - - + - - - - - - - - - - - +
|       |                       |
|   A   |           S           |
|       |                       |
+ - - - + - - - - - - - - - - - +

+ - - - + - - - - - - - - - - - +
|       |                       |
|       |           S           |
|       |                       |
|   L   | - - - - - - - - - - - +
|       |                       |
|       |           S           |
|       |                       |
+ - - - + - - - - - - - - - - - +
</code>
A = squares of 24" x 24"
S = sides of 24" x 72"
L = leftovers
Comment: Thanks so much! I can't believe I wasted so much time trying to figure this out with a calculus equation! ... I feel kind of silly now! Thanks again for the super clear explanation!
Comment: @PetarMihaylov I'm glad to have helped! ^^


Android 3.1: Refactoring Button Code and Permissions to MVP Architecture

Question: I have a simple one button app. The app show a button to make a phone call. I am having trouble clearly refactoring the code into an MVP architecture. There is a similar SO question (What's the best way to check for permissions at runtime using MVP architecture?). However, in this question, the answers are not clear enough to apply it to my problem.
The permissions request is not being recognized in the view from the presenter. The problem I'm having is in the view at startActivity(intent);. Android Studio underlines the intent in red and tells me the "Call requires permission which may be rejected by the user. The code should explicitly check for permissions".
Why is this refactoring wrong and how can I correct it to adhere to MVP architecture?
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void BtnSetEmergency_onclick(View view) {
    String number = "1112223333";
    final int REQUEST_PHONE_CALL = 1;
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:" + number));

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

        Toast.makeText(MainActivity.this, "One Button App", LENGTH_SHORT).show();

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
        }
        else{
            startActivity(intent);
        }

        return;
    }
    startActivity(intent);
  }
}

My Attempt at refactoring to an MVP architecture
View
public class MainActivity extends AppCompatActivity {

mainActivityPresenter mainActivityPresenterObject = new mainActivityPresenter();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void BtnSetEmergency_onclick(View view) {
    boolean phonePermissions = false;
    String number = "1112223333";
    final int REQUEST_PHONE_CALL = 1;
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:" + number));

    phonePermissions = mainActivityPresenterObject.checkPhonePermissions(view);

    if(phonePermissions == true){
        startActivity(intent);
    }else if (phonePermissions == false){

    }
  }
}

Presenter
public class mainActivityPresenter {

public boolean checkPhonePermissions(View view){
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

        Toast.makeText(MainActivity.this "One Button App", LENGTH_SHORT).show();

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
            return false;
        }
        else
        {
            return true;
        }
    }
    return false;
   }
}

===========================================================>
EDIT: Applying Final Answer Based on Nilesh Rathod Answer
===========================================================>
View
public class MainActivity extends AppCompatActivity {

    mainActivityPresenter mainActivityPresenterObject = new mainActivityPresenter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void BtnSetEmergency_onclick(View view) {
        boolean phonePermissions = false;
        int number = 1112223333;
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + Integer.toString(number)));

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)
            == PackageManager.PERMISSION_GRANTED) {
            startActivity(intent);
        }else {
            mainActivityPresenterObject.checkPhonePermissions(view, MainActivity.this);
        }
    }
 }

Presenter
public class mainActivityPresenter {
    final int REQUEST_PHONE_CALL = 1;

    public void checkPhonePermissions(View view, MainActivity mainActivity){
        ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
    }

}

Comment: It does not appear obvious how this SO answer applies. The first section of code I provided works and checks for user permissions. Yet, when I refactor and follow Android Studio's guidance, it attempts to place the permissions check in the view right above the startActivity(intent) statement.
Answer:
"Call requires permission which may be rejected by the user. The code should explicitly check for permissions"

Its behaving as intended.
You need to check whether user granted permission for call or not before making call using startActivity(intent);
FYI
You can handle the result of permission dialog  using ActivityCompat.OnRequestPermissionsResultCall

This interface is the contract for receiving the results for permission requests

Try this
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
       startActivity(intent);
}else {
     // ask here for call permission
}


The inverse of Lagrange's Theorem is true for finite supersolvable group.

Question: We have already known that the inverse of Lagrange's Theorem is a right fact about for example abelian or nilpotent finite groups. How can I show that:

If $G$ be finite and supersolvable$^*$ and $n\mid|G|$, then $G$ has a subgroup of order $n$?

$^*$ A group is supersolvable if there exists normal subgroups $N_i$ with $$1=N_0\subseteq N_1\subseteq ...\subseteq N_r=G$$ where each factor $\frac{N_i}{N_{i-1}}$ is cyclic for $1\leq i\leq r$.
Thanks for any hint to start.
Comment: I like this question +
Answer: See this article for a solution.
The basic idea is this. Suppose $G$ is supersolvable of order $$|G| = p_1^{a_1} \ldots p_{t-1}^{a_{t-1}} p_t^{a_t},$$ where $p_1 < p_2 < \ldots < p_t$ are primes. We can prove the claim by induction on $t$, the case $t = 1$ being true by Sylow's theorem. Because $G$ is solvable, its $p_t$-Sylow subgroup has a complement $H$. We can then use the inductive assumption on $H$ since subgroups of supersolvable groups are supersolvable. The claim follows by combining this with the fact that as a supersolvable group, $G$ has a normal subgroup of order $p_t^k$ for all $0 \leq k \leq a_t$.
Comment: You may also see the [note](http://www.academia.edu/2605307/On_CLT_Groups).


Optimization of a quadratic function with qudratic constraints

Question: I'm a Graduate student of Electrical Engineering. I have some basic knowledge on Convex Optimization. For my research, I cam across the following optimization program. With $\mu > 0$, find
$\arg \max \{ \mathbf{a}^T\mathbf{x} - \frac{1}{2}\mu ||\mathbf{x}||_2^2 \} \\ \text{s.t. } ||\mathbf{x}||_2^2 \leq 1$
In a paper, I got a similar problem and the unique maximizer to the above problem is given as,
$\mathbf{x}^*(\mathbf{a}) =
\begin{cases}
\frac{\mathbf{a}}{\mu}, & 0\leq ||\mathbf{a}||_2 \leq \mu \\
\frac{\mathbf{a}}{||\mathbf{a}||_2}, & ||\mathbf{a}||_2 > \mu
\end{cases}
$
Can anyone help me to understand how to get this maximizer? I think I'm missing something very obvious but that completely makes sense as I am not an expert in (convex) optimization.
However, I'd like to add one observation that if I put the maximizer's value to the cost function, I get a function very similar to the Huber function. Denoting the cost function as $f(\mathbf{x})$, the $f(\mathbf{x^*})$ which is a function of $\mathbf{a}$ and $\mu$ can be found to be,
$f(\mathbf{x^*}) = f(\mathbf{a},\mu) =
\begin{cases}
\frac{||\mathbf{a}||_2^2}{2\mu}, & 0\leq ||\mathbf{a}||_2 \leq \mu \\
||\mathbf{a}||_2 - \frac{\mu}{2}, & ||\mathbf{a}||_2 > \mu
\end{cases}
$
Would be highly thankful if you can help me solve this optimization problem or any direction to any reference would also be highly appreciated.
Comment: You can just complete the square in the objective function. You'll see you have to project a particular vector onto the $2$-norm unit ball.
Answer: You want to equivalently minimize the convex quadratic
$Q(\mathbf{x}) = \frac{1}{2}\mu ||\mathbf{x}||_2^2 -  \mathbf{a}^T\mathbf{x}$.
 $Q(\mathbf{x})$ is convex and differentiable, which implies that there exists a unique (global) minimizer, and that is the point where the gradient becomes zero.
The gradient of your quadratic is
\begin{align}
 \nabla_{\mathbf{x}}Q(\mathbf{x})
 &= \frac{1}{2}\mu \left( \mathbf{I}\mathbf{x} + \mathbf{I}^{T} \mathbf{x}\right) - \mathbf{a}\\
 &=
  \mu \mathbf{x}- \mathbf{a}.
\end{align}
Setting the gradient equal to $\mathbf{0}$, we get the global minimizer
$$
 \mathbf{x}_{\star} = \frac{1}{\mu}\mathbf{a}.
$$
If $\|\mathbf{a}\|_{2} \le \mu$, then $ \mathbf{x}_{\star}$ is feasible and it is the optimal solution of the constrained maximization. Of course, this might not be the case. For the constrained problem we exploit the following Lemma:
$Q(\mathbf{x})$ is a convex, differentiable function. The constraint set $C$ (here $C$ is the unit $l_{2}$-ball) is convex, nonempty and closed.
A point $\widehat{\mathbf{x}} \in C$ is an optimal solution of the constrained maximization if and only if
$$
 \nabla_{\mathbf{x}}Q(\widehat{\mathbf{x}})^{T}(\mathbf{z}-\widehat{\mathbf{x}}) \ge 0,
\quad \forall \mathbf{z} \in C.
$$
Now, lets see how from that we get the desired solution.
If the global optimal is also a feasible point, then it is the solution of the constrained problem; the above criterion is trivially satisfied since the gradient is zero at $\widehat{\mathbf{x}} = \mathbf{x}_{\star} \in C$.
If that is not the case ($\mathbf{x}_{\star} \notin C$), then we look for $\widehat{\mathbf{x}}$ such that
$$
 \nabla_{\mathbf{x}}Q(\widehat{\mathbf{x}})^{T}(\mathbf{z}-\widehat{\mathbf{x}})
=
\left( \mu \widehat{\mathbf{x}} - \mathbf{a}\right)^{T} (\mathbf{z}-\widehat{\mathbf{x}})
\ge 0,
\quad \forall \mathbf{z} \in C.
$$
Lets treat $\widehat{\mathbf{x}}$ as a fixed (unknown) point for now,
and minimize the left-hand side with respect to $\mathbf{z} \in C$; if the inequality holds for the $\mathbf{z} \in C$ that minimizes the left-hand side, it will hold for all $\mathbf{z} \in C$.
By the Cauchy-Schwarz inequality, we have
\begin{align}
  \left( \mu \widehat{\mathbf{x}} - \mathbf{a}\right)^{T} (\mathbf{z}-\widehat{\mathbf{x}})
&=
\left( \mu \widehat{\mathbf{x}} - \mathbf{a}\right)^{T} \mathbf{z}
-\left( \mu \widehat{\mathbf{x}} - \mathbf{a}\right)^{T}\widehat{\mathbf{x}}\\
&\ge
-\|\mu \widehat{\mathbf{x}} - \mathbf{a}\|
-\left( \mu \widehat{\mathbf{x}} - \mathbf{a}\right)^{T}\widehat{\mathbf{x}}
\end{align}
The inequality can be achieved with equality for $\mathbf{z} = -(\mu \widehat{\mathbf{x}} - \mathbf{a})/\|\mu \widehat{\mathbf{x}}-\mathbf{a}\| \in C$,
and hence that is the minimizing $\mathbf{z} \in C$.
Now, it suffices to determine $\widehat{\mathbf{x}} \in C$ for which the above is nonnegative. But again by the Cauchy-Schwarz inequality, we have
\begin{align}
-\|\mu \widehat{\mathbf{x}}-\mathbf{a} \|
-\left(\mu \widehat{\mathbf{x}}-\mathbf{a}  \right)^{T}\widehat{\mathbf{x}}
\le 0
\end{align}
for all $\widehat{\mathbf{x}}$ in the unit-ball.
Our only hope is to find $\widehat{\mathbf{x}}$ for which the above is equal to zero, i.e to find $\widehat{\mathbf{x}}$ such that
$$
\widehat{\mathbf{x}} = -\frac{\mu \widehat{\mathbf{x}}-\mathbf{a}}{\| \mu \widehat{\mathbf{x}}-\mathbf{a}\|}.
$$
But note that this means that $\widehat{\mathbf{x}}$ must be colinear with $\mu \widehat{\mathbf{x}}-\mathbf{a}$ and in turn with $\mathbf{a}$,
 i.e. if $\exists \lambda \in \mathbb{R}$ such that $\widehat{\mathbf{x}} = \lambda \mathbf{a} \in C$. Then,
$$
\lambda\mathbf{a}
= -\frac{\mu \lambda\mathbf{a}-\mathbf{a}}{\| \mu \lambda\mathbf{a}-\mathbf{a}\|}
= -\frac{(\mu \lambda-1)\mathbf{a}}{|\mu \lambda-1| \cdot \|\mathbf{a}\|}.
$$
By assumption, we are in the regime where $0 \le \mu < \|\mathbf{a}\|_{2}$.
Also note that $\lambda \le 1/\|\mathbf{a}\|_{2}$ because we want $\|\widehat{\mathbf{x}}\| \le 1$. (By the form of $Q(\mathbf{x})$ we can also deduce that $\lambda$ should be positive.).
Hence, $\mu \lambda-1 < 0$, and in turn $-(\mu \lambda-1) = |\mu \lambda-1|$.
Finally,
$$
\lambda\mathbf{a}
= \frac{|\mu \lambda-1| \cdot \mathbf{a}}{|\mu \lambda-1| \cdot \|\mathbf{a}\|}
=\frac{\mathbf{a}}{\|\mathbf{a}\|}
.
$$
Comment: Thanks for the answer. Yes, the quantity $\mu > 0$. I forgot to tell that at first. Now I have edited the question to include it. $\frac{\mathbf{a}}{\mu}$ is easily understood. Can please elaborate on the other case $||\mathbf{a}||_2> \mu$? Thanks again.
Comment: I edited the answer. Hope it helps now.
Comment: Thanks again. The reasonings are easy to follow and interesting. Everything is clear except that I'm stumped at the very last. Can you please elaborate a little more on how you get $\lambda = \frac{1}{||\mathbf{a}||}$? I was trying by putting $\hat{\mathbf{x}} = \lambda \mathbf{a}$ on both sides of the very last equation, but that is going no where. Would be grateful if you can kindly elaborate that a little more.
Comment: @ADas I edited the answer a little more.
Comment: Perfect. Everything is crystal clear. Thanks a ton for your time.
Answer: I don't think this requires anything too fancy. Note that $a^Tx \leq \|a\|\|x\|$ with equality if and only if $x = \alpha a$ for some $\alpha > 0$. Then, under this assumption, this cost function is
$$\alpha \|a\|^2 - \frac12 \mu \alpha^2 \|a\|^2 = \|a\|^2 (\alpha - \frac12 \mu \alpha^2)$$
You want to maximize this quantity, subject to the constraint that
$$
\alpha \|a\| = \|x\| \leq 1
$$
i.e. $\alpha \in \left[0,\dfrac{1}{\|a\|}\right]$. Consider the two cases $\|a\| \leq \mu$ and $\|a\| > \mu$ and find the $\alpha$ that maximizes the cost (you can just use calculus here, and don't forget to test the endpoints of the interval).
Comment: Hi BaronVT, thanks for responding. Your solution approach helped me a lot. I have given a response to your solution as another answer. I wanted to add that as comment, but was too long. Thanks again and please have a look on that response.
Answer: @BaronVT, At first, I was not convinced why we have to assume that $\mathbf{x}$ is a multiple of $\mathbf{a}$. I could think of the following reasonings. Please let me know if I'm correct.
\begin{equation}
\mathbf{a}^T\mathbf{x} \leq ||\mathbf{a}||||\mathbf{x}|| \\
\Rightarrow \mathbf{a} ^T\mathbf{x} - \frac{1}{2}\mu ||\mathbf{x}||_2^2 \leq ||\mathbf{a}||||\mathbf{x}|| - \frac{1}{2}\mu ||\mathbf{x}||_2^2
\end{equation}
So the cost function is upper bounded by $||\mathbf{a}||||\mathbf{x}|| - \frac{1}{2}\mu ||\mathbf{x}||_2^2$. The minimum value of this upper bound is $-\infty$ unless $\mathbf{x} = \alpha \mathbf{a}$. In this case the minimum of the upper bound is more informative than $-\infty$. The least upper bound is the maximum value of the cost function and this oocurs when $\mathbf{x} = \alpha \mathbf{a}$
Now, under this condition, the problem translates to what you wrote, i.e., the cost function becomes, $\alpha \|a\|^2 - \frac12 \mu \alpha^2 \|a\|^2 = \|a\|^2 (\alpha - \frac12 \mu \alpha^2)$ which is to be minimized under the constraint said by you.
Now applying Calculus and equating the gradient to $0$, we get $\alpha = \frac{1}{\mu}$. $\alpha = \frac{1}{\mu}$ means $\mathbf{x} = \frac{\mathbf{a}}{\mu}$ and to satisfy the constraint $||\mathbf{x}||_2 \leq 1$ (or equivalently, $\alpha \leq \frac{1}{||\mathbf{a}||}$), we have to make sure that $||\mathbf{a}|| \leq \mu$. So, for the case, $||\mathbf{a}|| \leq \mu$ the maximizer is $\mathbf{x} = \frac{\mathbf{a}}{\mu}$.
Now, let us consider the case $||\mathbf{a}|| > \mu$.
\begin{equation}
\mu < ||\mathbf{a}|| \\
\Rightarrow \frac{1}{2}\mu \alpha^2 < \frac{1}{2}||\mathbf{a}|| \alpha^2 \\
\Rightarrow ||a\|^2 (\alpha - \frac12 \mu \alpha^2) > ||a\|^2 (\alpha - \frac12 ||\mathbf{a}|| \alpha^2)
\end{equation}
So the cost function is lower bounded by $||a\|^2 (\alpha - \frac12 ||\mathbf{a}|| \alpha^2)$. Instead of finding the maximizer of the cost function directly, we find the maximizer to its lower bound. (Though I'm giving such explanations, I'm not fully convinced. Is there any better argument?) The maximum of this lower bound occurs at $\alpha = \frac{1}{||\mathbf{a}||}$ (Obtained by equating the gradient to $0$). So for the case $||\mathbf{a}|| > \mu$ the maximizer is $\mathbf{x} = \frac{\mathbf{a}}{||\mathbf{a}||}$.
So for the two cases combined, the maximizer is given by,
$\mathbf{x}^*(\mathbf{a}) =
\begin{cases}
\frac{\mathbf{a}}{\mu}, & 0\leq ||\mathbf{a}||_2 \leq \mu \\
\frac{\mathbf{a}}{||\mathbf{a}||_2}, & ||\mathbf{a}||_2 > \mu
\end{cases}
$
Comment: @BaronVT - Your claim also sounds good. Thanks.
Comment: For the second part (once you have decided that $x = \alpha a$), I think you can just treat this as a you would a function in calculus: it is a smooth function of the single variable $\alpha$, and so you can find it's maximum on the interval $[0,1/\|a\|]$ by checking the critical points and the endpoints (i.e. the possible maxima are where $f'(\alpha) = 0$, $\alpha = 0$ or $\alpha = 1/\|a\|.$
Comment: For the first part, your reasoning looks valid. Another way to observe my claim is that you can note the cost function is equal to $\mu(-\|x-\frac1\mu a\|^2 +\frac{1}{\mu^2} \|a\|^2)$ (complete the square, as I think another commenter suggested) and so this is maximized when $\|x-\frac1\mu a\|^2$ is minimized. By the triangle inequality, $\|x - \frac1\mu a\| \geq |\|x\| - \|\frac1\mu a\||$, with equality if $x = \alpha a$ for some posivite $\alpha$ (and in particular, if $x = \frac1\mu a$ satisfies the constraint, then $\|x - \frac1\mu a\| = 0$).
Answer: You can just complete the square in the objective function.
This optimization problem is equivalent to finding a minimizer of $\|x\|_2^2 - \frac{2}{\mu} a^T x$ subject to $\|x\|_2 \leq 1$, which is in turn equivalent to finding
a minimizer of $\|x\|_2^2 - \frac{2}{\mu} a^T x + \frac{\|a\|_2^2}{\mu^2}$ (subject to the given constraint).
(Adding a constant term to the objective function does not change the minimizer.)
But notice that
\begin{equation}
\|x\|_2^2 - \frac{2}{\mu} a^T x + \frac{\|a\|_2^2}{\mu^2} = \left \|x - \frac{a}{\mu} \right \|_2^2.
\end{equation}
So, our optimization problem is equivalent to
\begin{align}
\text{minimize} & \quad \|x - \frac{a}{\mu} \|_2^2 \\
\text{subject to} & \quad \|x\|_2 \leq 1.
\end{align}
The solution to this is just the projection of $\frac{a}{\mu}$ onto the $2$-norm unit ball.


What transformations of the sphere keep triple product fixed?

Question: Given three unity vectors from the origin to the surface of a sphere centred on the origin we can get a quantity $(A\times B).C$
If we rotate the sphere by rigid rotations this quantity remains the same.
Are there any groups of diffeomorphisms which keep this quantitiy the same?
It's not so obvious that there aren't but seems likeley that there aren't.
Comment: For a given set of three vectors, there are an infinite number of diffeomorphisms.  For any set of three vectors, the transformation would need to be isometric on the sphere.  You could come up with a diffeomorphism that's isometric in the sphere but not elsewhere.
Comment: @NicNic I meant diffemorphisms on the surface of the sphere only.
Answer: Let $V(u,v,w)=|(u\times v)\cdot w|$. We show that if $f$ is any self map on the sphere satisfying
$$V(f(u),f(v),f(w))=V(u,v,w),$$
then $f$ is an isometry of the sphere. Let $i,j,k$ be the standard basis vectors of $\mathbb{R}^3$. For unit vectors $u,v,w$, the quantity  is maximum possible (value=1) if and only if the three vectors are mutually perpendicular. Without loss of generality, we can assume $f(k)=k$ (otherwise, compose with an isometry). It follows that $i,j$ are mapped to two perpendicular vectors on the $xy$-plane. By composing with a rotation around the $z$-axis followed by a reflection if necessary, we can assume $f(i)=i$ and $f(j)=j$.
Now let $u=(a,b,c)$ be an arbitrary vector and let $f(u)=(a',b',c')$. We have
$$(u \times i)\cdot j=(f(u) \times i) \cdot j,$$
which implies that $c=c'$. Similarly one can show $a=a'$ and $b=b'$. This completes the proof.


UITableView not showing left-side multiple selection circles on edit

Question: I am trying to get the standard multiple selection behavior for UITableView as in the system Mail.app and Messages.app when edit is pressed in the inboxes. I am setting allowsMultipleSelectionDuringEditing to YES, and am calling [self.tableView setEditing:YES animated:YES] when my edit button is pressed. However, everything remains still and the open circles do not emerge from the left side of the cell as I want them to. I am not setting any of the UITableViewCells' accessoryType or calling setEditing on any of them as it is.
Is there anything I am missing, or something further that I have to do? To be clear, I am looking for the left-side multiple selection functionality, not the floating checkmarks that might appear on the right side of the cell. Thanks
Edit: I just realized that I should specify that I am not using a table view within a UITableViewController, but rather one that is placed within a UIViewController. Am I not able to get this functionality without using a UITableViewController?
Comment: I have up voted urs hope to get it back in my answer too and u can accept it too
Answer: Solved!
It turns out that I was not properly returning YES for the data source method canEditRowAtIndexPath. So it looks like multiple selection is different (right side checkmarks vs left side circle selection checkmarks) depending on whether the table view knows it can edit.
Answer: Try using this
- (void)viewDidLoad
{
self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [tableView setEditing:editing animated:YES];
    if (editing) {
        addButton.enabled = NO;
    } else {
        addButton.enabled = YES;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    SimpleEditableListAppDelegate *controller = (SimpleEditableListAppDelegate *)[[UIApplication sharedApplication] delegate];
    if (indexPath.row == [controller countOfList]-1) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // If row is deleted, remove it from the list.
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        SimpleEditableListAppDelegate *controller = (SimpleEditableListAppDelegate *)[[UIApplication sharedApplication] delegate];
        [controller removeObjectFromListAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

Comment: Thanks for your response. Although it wasn't exactly the answer, your code with some of the data source methods helped me stumble upon the solution. Cheers!
Comment: you are welcome any way can you post your code. I want to study the code you are implementing


Upgrading 32-bit XFS filesystem to 64-bit

Question: What would be the procedure for upgrading XFS filesystems from 32-bit to 64-bit?  What damage or issues would arise from accessing XFS fs that was formatted on a 32-bit OS with a 64-bit OS?
To recap, I had some issues with NFS to a fileserver that was recently upgraded.  Part of the upgrade was to move to a 64-bit OS.  The problems with apps hanging on file access over NFS also occurred on the local machine.  At this point I noticed the partition was XFS.  Somewhere I recall that XFS is not portable between 32-bit and 64-bit systems.  Is this correct?
A run of xfs_check showed nothing wrong and xfs_repair ran successfully.
Update:
Found the following on the Ubuntu wiki:
"The journal is currently not 32-bit / 64-bit portable. Before mounting a xfs prevously used on 32-bit linux in 64-bit linux (or different arch) the journal has to be emptied using xfs_repair." -- https://wiki.ubuntu.com/XFS
There is no date on this page.
Leaves me wondering why the system behaves strangely, though.
Comment: Makes a bit more sense now, with a particular implementation having a bug. Thank you for the update!
Answer: I'm assuming you're referring to XFS running on Linux... You shouldn't have any conversion issues going from a 32-bit system to a 64-bit system on XFS. The filesystem won't need to be modified.
Comment: +1, The only difference are a few upper limits of things, going from 32 to 64 would simply increase the limits.


boost serialization and doubles

Question: I am trying to serialize a class to a string using the boost serialization library and included in my class are several double member variables.
Below is the code I'm using to serialize:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>

std::stringstream ss;
boost::archive::text_oarchive oa(ss);
oa << mPoint;

Here is the serialiation method within my Point class:
friend class boost::serialization::access;

template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
    if (version > 0)
    {
        ar & mLatitude;
        ar & mLongitude;
    }
}

When I serialize to a string, boost doesn't appear to handle the double to string conversion as I would expect (there appear to be rounding issues).  Researching a bit it looks like others have reported the same behavior.  I also understand the precision related issues associated with converting a double to a string and vice versa and how this could cause the issue.
What is strange and I don't understand though is this doesn't appear to happen when I'm using a stringstream itself and redirecting the double to the stream nor when I use boost's lexical_cast function to convert from a stringstream.str() back to a double.  Before discovering boost had its own serialization/deserialization classes, I had actually written my own using stringstream and lexical_cast calls and it worked w/o issue.  I'm really hoping I don't have to abandon the serialization library and go back to what I had before.  Hopefully there is just some setting/trait/etc. I'm missing.
Comment: obvious and stupid suggestion would be to serialize it as a binary data, not as a string? Maybe that is the solution? Again if it was that easy you would probably do it already... :) I wouldnt be offering my advice if it wasnt a long time without answer and my curiosity to find out the solution.  :)
Comment: boost's lexical_cast has complex logic to set the precision of the stream appropriately - see http://www.boost.org/doc/libs/1_46_1/boost/detail/lcast_precision.hpp
Comment: Can you give an example of values that do and don't round-trip correctly?
Answer: You could try forcing your stream to use scientific format for floating point before serialising to it:
ss << std::scientific;

It looks like the boost library sets the precision correctly, but doesn't appear to set the format. Alternatively, you can I think derive and override the logic for saving and/or loading floating point numbers without throwing away the rest of the library - start here.
It also looks like there is work in progress on supporting infinities etc.
Comment: I had also modified the class to represent my data elements as float as opposed to double which looked to do the same and at least solved my issue with regards to serialization.
Answer: This doesn't directly answer the Boost.Serialization question, but is a possible workaround.
From the above question, it's not clear to me that you need a string representation or not. If you are looking for a cross-platform representation (binary or otherwise), consider using protobuf, which does have support for encoding doubles.
http://code.google.com/apis/protocolbuffers/docs/proto.html#scalar

boost serialization and doubles


Best way to use getString()

Question: I'm having some problems on where and how to place and call the getString().
I tried at the beginning of my activity where I usually define it but always get an error. Should it be only after onCreate()?
Some of my strings I use it very often so I don't want to use getString() every time I use them.
Is this the correct way?
private String helloWorld = getString(R.string.hello_world);

Thank you very much! :)
Comment: http://developer.android.com/training/basics/supporting-devices/languages.html
Answer: at the top of your file do:
private String helloWorld;

And then, in onCreate(),
do:
helloWorld = getString(R.String.hello_world).

The problem is that getString needs a reference to the activity context, which has not been associated with your class until onCreate is called.

Best way to use getString()


How do I fix this syntax problem? I am confused

Question: I don't know what I am doing wrong here
p = ["5","3","4","5"]
for i in range(len(p),-1,-1):
    print(p[i])

Error:
Traceback (most recent call last):
  File "C:\Users\jeffbezoz\Desktop\vbvbvbvbvbvbvvmvm.py", line 3, in <module>
    print(p[i])
IndexError: list index out of range

Comment: `range(len(p) - 1,-1,-1):`
Answer: That's an IndexError, not a SyntaxError, it's because you're starting the loop at len(p), when it should be len(p) - 1:
for i in range(len(p) - 1, -1, -1):

A better way to loop through a list backwards is using reversed:
for x in reversed(p):
    print(x)

Output:
5
4
3
5


I'm a beginner. Can I play most of popular music - The Beatles is an example - on a 61 key keyboard?

Question: I've just purchased a 61-key keyboard, the Yamaha PSR-E253. I know it's not the best to start with, as it lacks touch sensitivity, especially so for those serious in their learning. I will purchase a high-end digital piano in due time. I've picked this one up to learn how to play.
What I'd like know is whether I can play most popular music songs on a 61-key keyboard. Specifically, the Beatles, the Rolling Stones and 60s work. Certainly other music too, but I'd like to start with the music I like before progressing to the classical music I enjoy.
Thank you.
Answer: The only music you can't play on a 61-note keyboard is piano music that specifically uses notes outside that range.   Pop songs aren't piano pieces.  The songbook arrangements you can buy, laid out for piano, aren't sacrosanct.  If you run out of notes, modify them!
To play a Beatles song authentically, you need 3 guitars, a drum kit, vocalists...  To give an impression of it on keyboard is quite another thing.
Comment: Interesting! It's good to know that I can play them and work with them, if necessary. That'll be more motivation.
Comment: This reminds me of all the pieces I've played on a glockenspiel with two mallets. Melody octave voicings obviously got modified.
Answer: Yes you certainly can play pop songs on your 61 note keyboard, but "playing" has more than one definition.
If you want to sing along with say a Beatles song having only a few chords in it, "Misery", "Love me Do", for example, songs which are structurally simpler than some nursury rhymes, you need only to  play simple chords to accompany yourself, good fun too. You may want to accompany the melody line (the words that is) played with your right hand, with chords played with the left. You can do this on your 61 key keyboard. As the playing becomes more complex, it follows that your learning will eventually urge you to get a keyboard with more notes on it.
But just Beatles and Stones? Of course you can.
Have fun
Comment: Thanks a lot! I'd like to play the melody line as well. I've just received my keyboard and I can't wait to start!


How to Get both Notification and data when app is background in android

Question: How to Get both Notification and data when app is background in android.
When app is foreground than get both Notification and data.
But when app in background than get only data.
I want Get both Notification and data when app is background.
Comment: What have you done?
Answer: As i searched it's not possible.
you can pass Notification parameters to data and get them in
<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage){
 createNotification(remoteMessage.getData());
}
private void createNotification(Map<String, String> data) {
....
 NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_icon)
            .setContentTitle(data.get("title"))
            .setContentText(data.get("body"))
}
</code>