Compiler strangely trying to call another function (constructor) than intended

Question: Hiho,
I have implemented a singleton class in C++ which has got a problem with an initialization within its constructor where I try to initialize a member with a custom constructor but instead the compiler thinks I want to call the default constructor (without arguments) and (of course) can't find it as I don't need a default constructor for that class.
Here is the code:
class CionTokenTypes final {
private:
    CionTokenTypes();

    TokenType init_tt(TokenType token_type, bool skipped = false);

    std::vector<TokenType> m_all_token_types;
    std::vector<TokenType> m_skipped_token_types;

    static const CionTokenTypes c_instance;

public:
    CionTokenTypes(CionTokenTypes const&) = delete;
    CionTokenTypes(CionTokenTypes &&) = delete;

    static CionTokenTypes const& get_instance();

    std::vector<TokenType> const& get_all() const;
    std::vector<TokenType> const& get_skipped() const;

    TokenType const my_custom_token_type;
};

Here is the source file:
const CionTokenTypes CionTokenTypes::c_instance = {};

TokenType CionTokenTypes::init_tt(
    TokenType token_type,
    bool skipped
) {
    m_all_token_types.push_back(token_type);
    if (skipped) {
        m_skipped_token_types.push_back(token_type);
    }
    return std::move(token_type);
}

CionTokenTypes const& CionTokenTypes::get_instance() {
    return c_instance;
}

std::vector<TokenType> const& CionTokenTypes::get_all() const {
    return m_all_token_types;
}

std::vector<TokenType> const& CionTokenTypes::get_skipped() const {
    return m_skipped_token_types;
}

CionTokenTypes::CionTokenTypes():
    m_all_token_types{},
    m_skipped_token_types{},
    my_custom_token_type{init_tt({"bracket: closing bracket ]", "\\]"})}
{}

And you might also want to see the TokenType class:
class TokenType final {
public:
    enum class MatchType : uint8_t {
        non_greedy,
        greedy
    };

    TokenType(
        std::string const& name,
        std::string const& regex = "",
        TokenTypeStore store_type = TokenTypeStore::empty,
        MatchType match_type = MatchType::non_greedy);

    TokenType() = delete;
    TokenType(TokenType const& other) = default;
    TokenType(TokenType && other) = default;
    TokenType & operator=(TokenType const& other) = default;
    TokenType & operator=(TokenType && other) = default;
};

And its source file:
TokenType::TokenType(
    std::string const& name,
    std::string const& regex,
    TokenTypeStore store_type,
    TokenType::MatchType match_type
):
    m_data{
        std::make_shared<TokenType::Data>(
            name,
            regex,
            store_type,
            match_type
        )
    }
{}

I have cut out the not important parts as these files would have been just too huge for a complete paste at StackOverflow.
The compiler error:
/home/robbepop/coding/c++/projects/cion/src/token/cion_token_types.cpp: In constructor 'cion::CionTokenTypes::CionTokenTypes()':
/home/robbepop/coding/c++/projects/cion/src/token/cion_token_types.cpp:207:69: error: use of deleted function 'cion::TokenType::TokenType()'
   closing_brack  {init_tt({"bracket: closing bracket ]"    , "\\]"})}
                                                                     ^
In file included from /home/robbepop/coding/c++/projects/cion/include/token/cion_token_types.hpp:4:0,
                 from /home/robbepop/coding/c++/projects/cion/src/token/cion_token_types.cpp:1:
/home/robbepop/coding/c++/projects/cion/include/token/token_type.hpp:56:3: note: declared here
   TokenType() = delete;
   ^
/home/robbepop/coding/c++/projects/cion/src/token/cion_token_types.cpp:207:69: error: use of deleted function 'cion::TokenType::TokenType()'
   closing_brack  {init_tt({"bracket: closing bracket ]"    , "\\]"})}
                                                                     ^
In file included from /home/robbepop/coding/c++/projects/cion/include/token/cion_token_types.hpp:4:0,
                 from /home/robbepop/coding/c++/projects/cion/src/token/cion_token_types.cpp:1:
/home/robbepop/coding/c++/projects/cion/include/token/token_type.hpp:56:3: note: declared here
   TokenType() = delete;
   ^
src/CMakeFiles/cion_compiler.dir/build.make:1066: recipe for target 'src/CMakeFiles/cion_compiler.dir/token/cion_token_types.cpp.o' failed
make[2]: *** [src/CMakeFiles/cion_compiler.dir/token/cion_token_types.cpp.o] Error 1
CMakeFiles/Makefile2:75: recipe for target 'src/CMakeFiles/cion_compiler.dir/all' failed
make[1]: *** [src/CMakeFiles/cion_compiler.dir/all] Error 2
Makefile:76: recipe for target 'all' failed
make: *** [all] Error 2
make  62.10s user 5.93s system 98% cpu 1:08.80 total

I hope you can help me as I really don't know why the compiler thinks that I want to call the default constructor instead of my custom one ...
I finally found out what's the source of this strange compiler error:
It is in fact really strange. The source of the problem was that the header file declared about one hundred members of the CionTokenTypes class but they got initialized in the wrong order and some got even left out in the source file of the class which resulted in the error that the compiler can't find the default constructor for the last member.
So I guess this confusing was mainly caused by a poor error handling for this situation.
Comment: it is okay if it is huge put the whole thing, it will help in better understanding your problem.
Comment: Which compiler and which version? Also, the code in your posted errors does not seem to match the code you posted.
Comment: GCC 4.9.x was used. Is it also okay to provide a link to a gist at github for you guys?
Comment: Next time please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). The code you provided is neither complete enough to compile nor stripped of irrelevant pieces. Reducing the problem to its smallest size is both a great way to identify your own problem and to help others help you.
Comment: As I have only a vague understanding where the error actually does come from I can not provide you with a minimal or a verifiable example code. I'll create a github of my project and provide you with the link to it if this is allowed on StackoverFlow.
Comment: The easiest way to produce the MCVE is to just remove stuff until you get either no errors or a different error (which you can often fix by removing yet more stufF). Anyway, sure, throw up a link to github or ideone. Removing helper functions and other cruft is a great place to start.
Comment: yeah that's actually how I finally found the source of the bug - I edited my initial post for the solution. thanks!
Answer: Could be wrong, as I do not seem to have enough of your code to properly reproduce the error in ideone.
From the looks of things your are attempting to invoke the default constructor of TokenType at line 210 and because none is being automatically generated by the compiler, you get an error. It is not being generated because you have declared another constructor and the rules of C++ then skip generation of the default constructor.
Solutions include (one of):

You weren't supposed to be calling a default constructor, so investigate line 210 and stop that.
You actually did want a default constructor, add the line TokenType() = default; to your TokenType struct.
Comment: Side note: You also seem to have asked for default generation of the move assignment operator but *not* the move constructor. This strikes me as strange. You might also consider adding the line `TokenType(TokenType&&) = default;`
Comment: Thanks for your answer, however, you don't seem to fully understand or read my question as I have stated that I do not wish to call the default constructor on line 210.
Instead I call the line:

    my_custom_token_type{init_tt({"bracket: closing bracket ]", "\\]"})}

And the compiler somehow thinks I want to call the default constructor which is confusing me because I obviously have stated at least one parameter (the init_tt thingy).

I have changed the code above in order to make it more clear.


Put focus on input field after it will be conditionally rendered in Vue

Question: Target
On click to "edit" button, input field appears and automatically focused.
<button v-if="!editingMode" @click="editingMode = !editingMode">edit</button>
<input v-else type="text" value ref="input">

export default {
  name: "App",
  components: {
    HelloWorld
  },
  data: function() {
    return {
      editingMode: false
    };
  },
  methods: {
    onClickButton() {
      this.editingMode = true;
      this.$refs.input.focus();
    }
  }
};

 Fiddle
Problem
Because re-rendering in Vue synchronous, when we calling this.$refs.input.focus(), input field could be not rendered yet. I experienced two cases:

Input is not mounted yet. In this case, Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined" will occur.
No this error, but no focus too. It looks like there is the interval between input field mounted and ready to manipulations.
Comment: I had a look at your fiddle, there were a few other issues, see my answer, I added a working fiddle for you
Answer: Try calling it in this.$nextTick :
methods: {
  onClickButton() {
    this.editingMode = true;
    this.$nextTick(() => {
      this.$refs.input.focus();
    })
  }
}

https://codesandbox.io/s/sleepy-dew-5mcju
Comment: you use an arrow function there is no need for `self = this`


php quotation mark is not working

Question: I am facing some problem in PHP code. It is a basic question but I don't know the answer. The code is here:
echo '<a href="profile.php?act=show&id=<?=$_SESSION['id']?>&line=true" class="myac">My Data';

How to use the quotation mark in the id? Please help me.
Answer: That's wrong. Already you are using echo. So concatenate the value this way:
<?php
  echo 'My Data';
  //-------------------------------------^^^^^^^^^^

And please refrain from using short tags (<? ?>), use full tags: <?php ?>.
Comment: he is using the variable `$_SESSION['id']` not just `$id`.
Comment: @low_rents Thanks. Updated.
Answer: apart from the above mentioned way by @praveen  u can use it like below also if u don't want to put the anchor tag inside php
 <a href="profile.php?act=show&id=<?php echo $_SESSION['id']?>&line=true" class="myac">My Data

php quotation mark is not working


Is there a syntax checker for cron.d files?

Question: Is there a lint tool or a command line syntax checker for the files in /etc/cron.d? I work on a support team, and some members of the team have been known to mix up the syntax for crontab and /etc/cron.d (i.e. omitting the user), and since such entries will cause all of the entries in the file to fail, I would like to be able to test the entries in a given file in /etc/cron.d to make sure that the syntax is correct before cron jobs start failing.
I've read through the cron(8) man page and searched google and serverfault for cron.d lint and cron.d syntax checker with no success.
Answer: Maybe this can help you: chkcrontab In short:

chkcrontab is a script to check crontab files like those in
  /etc/cron.d and /etc/crontab. It tries to catch glaring errors and
  warn on suspect lines in a crontab file. Some valid lines will
  generate warnings. Certain silly yet valid crontab lines will generate
  errors as well.

Alternatively,  you can routinely check for cron logs (especially for the string "bad minute")
Comment: Yeah, I found `chkcrontab` shortly after I posted. (note to self -- google for 'cron syntax checker' not 'cron.d syntax checker'). It looks like a good tool.


Will the Newton's method be convergent to the root of the following function: $f(x)=\frac{-x}{x^2-1}$?

Question: Will the Newton's method be convergent to the root of the following function, if the starting point $x_0>1$ will be chosen?
$$
f(x)=\frac{-x}{x^2-1}
$$
Answer: The Newton's method iteration function is
$$N(x)=x-f(x)/f'(x) = \frac{2 x^3}{x^2+1}.$$
Why don't you plug in $x=2$ and see what comes out?  You could then plug that result back in and try a few more iterates to see what's going on.  If you understand the follow the slope description of Newton's method, then the results make perfect sense.
Answer: I would say he shape of the graph of function $\frac{-x}{x^2-1}$ the Newton's method converges only for |x|<1, see http://www.wolframalpha.com/input/?i=%5Cfrac%7B-x%7D%7Bx%5E2-1%7D
Comment: Well, if you're going to use WolframAlpha, then you can just ask it to [perform Newton's method for you](http://goo.gl/sQmBEo)!  That link starts at $x_0=1/2$. Starting at $x_0=2$, WolframAlpha says [there are no valid results](http://goo.gl/xsH5ft).
Comment: @MarkMcClure Thank you for the helpful advice.


How to update a value in the TextView from a handler?

Question: I have a TextView in the xml and from the OnCreate method I call its SetContentView. I have also written a handler to get message from other classes. Upon receiving the messages, the handler has to update the TextView with the message. But the TextView is null inside the handler. What to do/?. Please help
Comment: i know you got the question answered already but i have a very similar problem and and trying to learn how to properly use 'Handler'. it would be very helpful to me if i could see the relevant parts of your code.
Answer: How are you getting a reference to the TextView?  Something like this?
final TextView myTextView = (TextView) findViewById(R.id.my_text_view);

Then depending on what you need, you can do one of many things, including:

Pass this to your handler class
Create a "listener" interface that has an onUpdate(String msg) method and store an instance of this in the handler, then implement
public void onUpdate(String msg) {
myTextView.setText(msg);

}

in your Activity class and call listener.onUpdate(msg) from your handler class.
I'd probably prefer doing something like #2 because it keeps the UI-specific code out of the handler which would make that class easier to test.


What is if (!caller) in perl?

Question: There are some perl files, which I have to convert them to python.
Reading perl concepts and understanding.
some_file.pl
use Cwd qw(realpath cwd);
realpath( $0 ) =~ /(.+)\/[^\/]+$/;
require "some_other.pl";
use warnings;
use strict;

sub sub_routine1 {
    my ($a) = @_;
    # Do something
}

sub sub_routine2 {
    my ($b, $c) = @_;
    # Do something
}

sub sub_routine3 {
    my ($c, $d, $e) = @_;
    # do something
}

if (!caller) {
    # Variable decalarations
    # Do something
}

In the above code, what does (!caller) mean ? How can I use that in python or any equivalent ?
In second line, I guess it's matching reg-ex pattern. But what does this exactly mean realpath( $0 ) =~ /(.+)\/[^\/]+$/;
Comment: Please don't ask unrelated questions in the same Question.
Comment: hmmm.... The second question was [asked very recently](https://stackoverflow.com/q/63772027/589924), and it was answered in detail too. So weird to get two people asking about the same badly-written code?!
Comment: The second line is nonsense unless captured $1 is used afterwards.
Comment: See also [Modulino: both script and module in Perl](https://perlmaven.com/modulino-both-script-and-module)
Answer: if (!caller) ... is the modulino pattern for Perl, used in dual-use source code files (a source code file that can either be incorporated into another script or run on its own). The equivalent pattern in Python is:
if __name__ == "__main__":
    ...

Comment: Thank you. So, when I run "perl some_file.pl", does it execute "if (!caller)" sub-routine ?
Answer: caller is a built-in Perl function that returns information about the caller of a subroutine. perldoc -f caller or see here for more information.
caller returns undef (which is treated as false) if there is no caller -- i.e., if it's called from the top level of your script rather than from inside a subroutine. if (!caller) can be used in a Perl module to let it behave in one way if it's invoked directly, and to behave differently if it's invoked from another script or module.
Comment: Thank yo, Keith. So, when i execute as "perl some_file.pl" , it directly invokes if "(!caller)" section, correct ?
Comment: How does this script behave when invoked from another script ? When this "some_perl.pl" imported (require) in another perl script (let's say, test.pl). So, when executed test.pl, will it invoke "(!caller)" ?
Answer: I'd highly recommend taking a chance to read through some of Perl's documentation as the regex operators are quite confusing/unintuitive at first.
Here are some things that might help:
https://perldoc.perl.org/perlrequick.html
https://perldoc.perl.org/perlretut.html
https://perldoc.perl.org/perlop.html
https://www.tutorialspoint.com/perl/perl_subroutines.htm
When we look at the line
realpath( $0 ) =~ /(.+)\/[^\/]+$/;

'$0' contains the name of the program being run, as given to the shell. If the program was run directly through the Perl interpreter, '$0' contains the file name. The backslash can perform one of two tasks: it either takes away the special meaning of the character following it (for instance, | matches a vertical bar, it's not an alternation), or it is the start of a backslash or escape sequence. The '.' is the concatenation operator, Perl's way of combining two or more things. So this statement is simply reading in the filepath.
Taking a look at:
https://perldoc.perl.org/functions/caller.html
Caller returns the context of the current pure perl subroutine call.
And so the following
if (!caller) {
    # Variable decalarations
    # Do something
}

is handling the case for whatever reason there are no subroutines running. Subroutines in Perl have to be called before they begin running. So this probably acts as a simple null check for when the file is called.
Comment: if '(!caller)' section is executed only when "some_file.pl" is run, is that correct ?
Comment: will "if (!caller)" section be executed, if "some_file.pl" invoked from another script ?
Comment: @Fresher It depends on the circumstances. I think that the other answers describing it as a dual-source code tool are exactly what it is used for. So if you wanted to call a specific subroutine in the file it wouldn't execute. If you called the entire file "some_file.pl" the "if (!caller)" would execute.
Comment: confusing. can you help me to understand better ?
Comment: Since you are trying to convert the file to Python, just focus on doing it piece by piece. [This](https://medium.com/python-features/understanding-if-name-main-in-python-a37a3d4ab0c3) might help you understand @mob's suggestion to use __ name __ = "__ main __". You might also start by writing a simple program in Perl, then implementing some subroutines and calling them to get the hang of things. Once you understand that, porting it to python will be quite easy. If this is a school assignment I'd suggest reaching out to your professor for help if you aren't able to make any progress.

What is if (!caller) in perl?


FA: Choosing Rotation matrix, based on "Simple Structure Criteria"

Question: One of the most important issues in using factor analysis is its interpretation. Factor analysis often uses factor rotation to enhance its interpretation. After a satisfactory rotation, the rotated factor loading matrix L' will have the same ability to represent the correlation matrix and it can be used as the factor loading matrix, instead of the unrotated matrix L.
The purpose of rotation is to make the rotated factor loading matrix have some desirable properties. One of the methods used is to rotate the factor loading matrix such that the rotated matrix will have a simple structure.
L. L. Thurstone introduced the Principle of Simple Structure, as a general guide for factor rotation:
Simple Structure Criteria:

Each row of the factor matrix should contain at least one zero
If there are m common factors, each column of the factor matrix should have at least m zeros
For every pair of columns in the factor matrix, there should be several variables for which entries approach zero in the one column but not in the other
For every pair of columns in the factor matrix, a large proportion of the variables should have entries approaching zero in both columns when there are four or more factors
For every pair of columns in the factor matrix, there should be only a small number of variables with nonzero entries in both columns

The ideal simple structure is such that:

each item has a high, or meaningful, loading on one factor only and
each factor have high, or meaningful, loadings for only some of the items.

The problem is that, trying several combinations of rotation methods along with the parameters that each one accepts (especially for oblique ones), the number of candidate matrices increases and it is very difficult to see which one better meets the above criteria.
When I first faced that problem I realized that I was unable to select the best match by merely 'looking' at them, and that I needed an algorithm to help me decide. Under the stress of project's deadlines, the most I could do was to write the following code in MATLAB, which accepts one rotation matrix at a time and returns (under some assumptions) whether each criterion is met or not.
A new version (If I would ever tried to upgrade it) would accept a 3d matrix (a set of 2d matrices) as an argument, and the algorithm should return the one that better fits the above criteria.
How would you extract an algorithm out of those criteria? I am just asking for your opinions (I also think that there's been criticism over the usefulness of the method by itself) and perhaps better approaches to the rotation matrix selection problem.
Also, I would like to know what software do you prefer to perform FA. If it's R, what package do you use? (I must admit that if I had to do FA, I would turn to SPSS again). If someone wants to provide some code, I would prefer R or MATLAB.
P.S. The above Simple Structure Criteria formulation can be found in the book "Making Sense of Factor Analysis" by PETT, M., LACKEY, N., SULLIVAN, J.
P.S.2 (from the same book): "A test of successful factor analysis is the extent to which it can reproduce the original corr matrix. If you also used oblique solutions, among all select the one that generated the greatest number of highest and lowest factor loadings."
This sounds like another constraint that the algorithm could use.
P.S.3 This question has also been asked here. However, I think it fits better on this site.
function [] = simple_structure_criteria (my_pattern_table)
%Simple Structure Criteria
%Making Sense of Factor Analysis, page 132

disp(' ');
disp('Simple Structure Criteria (Thurstone):');
disp('1. Each row of the factor matrix should contain at least one zero');
disp( '2. If there are m common factors, each column of the factor matrix should have at least m zeros');
disp( '3. For every pair of columns in the factor matrix, there should be several variables for which entries approach zero in the one column but not in the other');
disp( '4. For every pair of columns in the factor matrix, a large proportion of the variables should have entries approaching zero in both columns when there are four or more factors');
disp( '5. For every pair of columns in the factor matrix, there should be only a small number of variables with nonzero entries in both columns');
disp(' ');
disp( '(additional by Pedhazur and Schmelkin) The ideal simple structure is such that:');
disp( '6. Each item has a high, or meaningful, loading on one factor only and');
disp( '7. Each factor have high, or meaningful, loadings for only some of the items.');

disp('')
disp('Start checking...')

%test matrix
%ct=[76,78,16,7;19,29,10,13;2,6,7,8];
%test it by giving: simple_structure_criteria (ct)

ct=abs(my_pattern_table);

items=size(ct,1);
factors=size(ct,2);
my_zero = 0.1;
approach_zero = 0.2;
several = floor(items / 3);
small_number = ceil(items / 4);
large_proportion = 0.30;
meaningful = 0.4;
some_bottom = 2;
some_top = floor(items / 2);

% CRITERION 1
disp(' ');
disp('CRITERION 1');
for i = 1 : 1 : items
    count = 0;
    for j = 1 : 1 : factors
        if (ct(i,j) < my_zero)
            count = count + 1;
            break
        end
    end
    if (count == 0)
        disp(['Criterion 1 is NOT MET for item ' num2str(i)])
    end
end

% CRITERION 2
disp(' ');
disp('CRITERION 2');
for j = 1 : 1 : factors
    m=0;
    for i = 1 : 1 : items
        if (ct(i,j) < my_zero)
            m = m + 1;
        end
    end
    if (m < factors)
        disp(['Criterion 2 is NOT MET for factor ' num2str(j) '. m = ' num2str(m)]);
    end
end

% CRITERION 3
disp(' ');
disp('CRITERION 3');
for c1 = 1 : 1 : factors - 1
    for c2 = c1 + 1 : 1 : factors
        test_several = 0;
        for i = 1 : 1 : items
            if ( (ct(i,c1)>my_zero && ct(i,c2)<my_zero) || (ct(i,c1)<my_zero && ct(i,c2)>my_zero) ) % approach zero in one but not in the other
                test_several = test_several + 1;
            end
        end
        disp(['several = ' num2str(test_several) ' for factors ' num2str(c1) ' and ' num2str(c2)]);
        if (test_several < several)
            disp(['Criterion 3 is NOT MET for factors ' num2str(c1) ' and ' num2str(c2)]);
        end
    end
end

% CRITERION 4
disp(' ');
disp('CRITERION 4');
if (factors > 3)
    for c1 = 1 : 1 : factors - 1
        for c2 = c1 + 1 : 1 : factors
            test_several = 0;
            for i = 1 : 1 : items
                if (ct(i,c1)<approach_zero && ct(i,c2)<approach_zero) % approach zero in both
                    test_several = test_several + 1;
                end
            end
            disp(['large proportion = ' num2str((test_several / items)*100) '% for factors ' num2str(c1) ' and ' num2str(c2)]);
            if ((test_several / items) < large_proportion)
                pr = sprintf('%4.2g',  (test_several / items) * 100 );
                disp(['Criterion 4 is NOT MET for factors ' num2str(c1) ' and ' num2str(c2) '. Proportion is ' pr '%']);
            end
        end
    end
end

% CRITERION 5
disp(' ');
disp('CRITERION 5');
for c1 = 1 : 1 : factors - 1
    for c2 = c1 + 1 : 1 : factors
        test_number = 0;
        for i = 1 : 1 : items
            if (ct(i,c1)>approach_zero && ct(i,c2)>approach_zero) % approach zero in both
                test_number = test_number + 1;
            end
        end
        disp(['small number = ' num2str(test_number) ' for factors ' num2str(c1) ' and ' num2str(c2)]);
        if (test_number > small_number)
            disp(['Criterion 5 is NOT MET for factors ' num2str(c1) ' and ' num2str(c2)]);
        end
    end
end

% CRITERION 6
disp(' ');
disp('CRITERION 6');
for i = 1 : 1 : items
    count = 0;
    for j = 1 : 1 : factors
        if (ct(i,j) > meaningful)
            count = count + 1;
        end
    end
    if (count == 0 || count > 1)
        disp(['Criterion 6 is NOT MET for item ' num2str(i)])
    end
end

% CRITERION 7
disp(' ');
disp('CRITERION 7');
for j = 1 : 1 : factors
    m=0;
    for i = 1 : 1 : items
        if (ct(i,j) > meaningful)
            m = m + 1;
        end
    end
    disp(['some items = ' num2str(m) ' for factor ' num2str(j)]);
    if (m < some_bottom || m > some_top)
        disp(['Criterion 7 is NOT MET for factor ' num2str(j)]);
    end
end
disp('')
disp('Checking completed.')
return

Answer: The R psych package includes various routines to apply Factor Analysis (whether it be PCA-, ML- or FA-based), but see my short review on crantastic. Most of the usual rotation techniques are available, as well as algorithm relying on simple structure criteria; you might want to have a look at W. Revelle's paper on this topic, Very Simple Structure: An Alternative Procedure For Estimating The Optimal Number Of Interpretable Factors (MBR 1979 (14)) and the VSS() function.
Many authors are using orthogonal rotation (VARIMAX), considering loadings higher than, say 0.3 or 0.4 (which amounts to 9 or 16% of variance explained by the factor), as it provides simpler structures for interpretation and scoring purpose (e.g., in quality of life research); others (e.g. Cattell, 1978; Kline, 1979) would recommend oblique rotations since "in the real world, it is not unreasonable to think that factors, as important determiners of behavior, would be correlated" (I'm quoting Kline, Intelligence. The Psychometric View, 1991, p. 19).
To my knowledge, researchers generally start with FA (or PCA), using a scree-plot together with simulated data (parallel analysis) to help choosing the right number of factors. I often found that item cluster analysis and VSS nicely complement such an approach. When one is interested in second-order factors, or to carry on with SEM-based methods, then obviously you need to use oblique rotation and factor out the resulting correlation matrix.
Other packages/software:

lavaan, for latent variable analysis in R;
OpenMx based on Mx, a general purpose software including a matrix algebra interpreter and numerical optimizer for structural equation modeling.

References
 1. Cattell, R.B. (1978). The scientific use of factor analysis in behavioural and life sciences. New York, Plenum.
 2. Kline, P. (1979). Psychometrics and Psychology. London, Academic Press.
Answer: I find myself routinely using parallel analysis (O'Connor, 2000). This solves the problem of how many factors to extract nicely.
See: https://people.ok.ubc.ca/brioconn/nfactors/nfactors.html
O'Connor, B. P. (2000). SPSS and SAS programs for determining the number of components using parallel analysis and Velicer's MAP test. Behavior Research Methods, Instrumentation, and Computers, 32, 396-402.
Comment: (+1) I came across O'Connor's website some years ago and it has a lot of useful resources. Nice that you link it here.
Answer: I would have to second chl's suggestion of the psych package, its extremely useful and has implementations of the MAP and parallel analysis criteria for number of factors. In my own experience, i have found that if you create factor analysis solutions for all the numbers between those returned by MAP and parallel analysis, you normally can find a relatively optimum solution.
I would also second the use of OpenMx for confirmatory factor analysis, as it seems to give the best results of all of them, and is much, much better for badly behaved matrices (as mine tend to be). The syntax is also quite nice, once you get used to it. The only issue that i have with it is that the optimiser is not open source, and thus it is not available on CRAN. Apparently they are working on an open source implementation of the optimiser, so that may not be an issue for much longer.
Comment: (+1) Thanks for sharing your experience. I often observed that a good compromise is found just by looking at the scree plot while considering Kayser's rule as a lower limit and simulated data as an upper limit. What I like in `psych` is that it displays simulated scree plots from both PCA and FA.
Answer: Great Question. This is not really an answer, but just a few thoughts.
In most of the applications where I have used factor analysis, permitting correlated factors makes more theoretical sense. I tend to rely on the proxmax rotation method. I used to do this in SPSS and now I use the factanal function in R.


R leaflet - radio button overlay control

Question: I have 7 overlay raster layers on my Leaflet map added with addRasterImage. This results in 7 checkboxes when added to the legend using addLegend. I can check and uncheck layers, but what I would like is a radio button control. When a new layer is checked, the first layer get's unchecked. Has anybody suggestions on how to accomplish this in R?
    mymap.matteo <- leaflet(options = leafletOptions(minZoom = 3, maxZoom = 11)) %>%
  setView(lng = 50, lat = 42, zoom = 6) %>%

  addEasyButton(easyButton(
    icon='fa-globe', title='Pontocaspian extent',
    onClick=JS("function(btn, map){ map.setView([42,50],6); }"))) %>% # First lat then lon

  # Base groups
  addProviderTiles("Esri.WorldShadedRelief", group = "Shaded Relief") %>%
  addProviderTiles("Esri.WorldGrayCanvas", group = "Gray canvas") %>%

  # Overlay groups
  addRasterImage(Chl.variation, colors = palOranges(12), opacity = 1, group = "Chlorophyll variation") %>%
  addRasterImage(Dams, colors = palReds(12), opacity = 1, group = "Dams") %>%
  addRasterImage(Fishing, colors = palBlues(12), opacity = 1, group = "Fishing") %>%
  addRasterImage(Fuel.industry, colors = palBrowns(12), opacity = 1, group = "Fuel industry") %>%
  addRasterImage(Human.density, colors = palReds(12), opacity = 1, group = "Human density") %>%
  addRasterImage(Invasive.sp, colors = rev(viridis_pal(option = "D")(20)), opacity = 1, group = "Invasive species") %>%
  addRasterImage(Nutrient.load, colors = rev(viridis_pal(option = "A")(20)), opacity = 1, group = "Nutrient load") %>%
  addPolygons(data=PC.countries.shp, fill = FALSE, stroke = TRUE, color = "black", weight=1, opacity = 1, group = "Countries") %>%

  # Legend layers
  addLegend(pal = pal.chl.var, values = values(Chl.variation), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Chlorophyll variation", group = "Chlorophyll variation") %>%
  addLegend(pal = pal.dams, values = values(Dams), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Dams", group = "Dams") %>%
  addLegend(pal = pal.fishing, values = values(Fishing), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Fishing", group = "Fishing") %>%
  addLegend(pal = pal.fuel.industry, values = values(Fuel.industry), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Fuel industry", group = "Fuel industry") %>%
  addLegend(pal = pal.human.density, values = values(Human.density), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Human density", group = "Human density") %>%
  addLegend(pal = pal.invasive.species, values = values(Invasive.sp), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Invasive species", group = "Invasive species") %>%
  addLegend(pal = pal.nutrient.load, values = values(Nutrient.load), position = "bottomright", labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)), title = "Nutrient load", group = "Nutrient load") %>%

  # Layers control
  addLayersControl(
    position = c("topleft"),
    baseGroups = c("Gray canvas", "Shaded Relief"),
    overlayGroups = c("Chlorophyll variation", "Dams", "Fishing", "Fuel industry", "Human density", "Invasive species", "Nutrient load", "Countries"),
    options = layersControlOptions(collapsed = F, autoZIndex = F)
  ) %>%

  hideGroup(c("Chlorophyll variation", "Dams", "Fishing", "Fuel industry", "Human density", "Invasive species", "Nutrient load"))

mymap.matteo

saveWidget(mymap.matteo, file="matteo.html")

Comment: That's what `baseGroups` are for. Hence, I think the only solution is to only have one background map and add the raster groups to the `baseGroups` option in `addLayersControl`.
Answer: baseGroups() offer what you are looking for: layers in baseGroups() are selected with a radio button and are displayed one at the time. You have to place all your rasters in the baseGroups().
You should also move your basemaps to the overlayGroups() , otherwise they will not show up when you select a raster with a radio button. You may have to play around with addMapPane() to make sure the basemaps appear underneath the rasters.


Poincaré-Bendixson

Question: Let $M$ be an open subset of $\mathbb{R}^2$ and consider the ordinary differential equation $\dot{x}(t) = f(x(t))$, where $f \in \mathcal{C}^{1}(M, \mathbb{R}^{2})$ and denote by $\Phi(.,.)$ its flow. For $x \in M$, let $\omega (x) := \{y \in M \ : \ \exists t_{n} \to +\infty \ s.t. \Phi(t_{n},x) \to y \}$ and $\alpha(x):= \{y \in M \ : \ \exists t_{n} \to -\infty \ s.t. \Phi(t_{n},x) \to y \}$.
Suppose that $\omega(x)$ is compact. Then it is also connected (see for example the exercices in the according chapter in the book "Differential Equations ..." by Hirsch, Smale, Devaney). The Poincaré-Bendixson theorem states that if $\omega(x)$ contains only finitely many fixed points then $\omega(x)$ is either
a) a single fixed point b) the periodic orbit of some $y \in \omega(x)$ or c) it consists of regular and fixed points and for every regular point $y \in \omega(x)$ we have that $\omega(y)$ consists of a single fixed point, and the same is true for $\alpha(y)$ .
It can be also shown that for two distinct fixed points $z_{1}, z_{2} \in \omega(x)$ there is maximally one orbit $\gamma(y)\subset \omega(x)$ which joins them. So if one supposes additionally (to the compactness hypothesis) that in $\omega(x)$ there are only finitely many homoclinic orbits included, then it is easy to show that for each set of distinct fixed points $z_{1},z_{2} \in \omega(x)$  there is exactly one heteroclinc orbit connecting them (this is also called a "graphic").
But what can be said if there is a fixed point $z_{0} \in \omega(x)$ with infinitely many homoclinic orbits in $\omega(x)$? Is then still true that any pair of distinct fixed point $z_{1}, z_{2}$ in $\omega(x)$ can be joined by an heteroclinic orbit contained in $\omega(x)$?
This does not seem to be obvious, because (from what I know) it seems possible that the there is a sequence of regular points $y_{n} \subset \omega(x)$ such the orbits $\gamma(y_{n})$ are homoclinic ones which end in $z_{0}$ while the sequence $y_{n}$ converges to another fixed point $z_{1} \in \omega(x)$ in a way so that $\omega(x)$ is connected (think of the topologist's sine curve) without containing a heteroclinic orbit which joins the fixed points $z_{0}$ and $z_{1}$.
Comment: A nitpick while I am reading the rest of the text: I am pretty sure there can be two orbits inside $\omega(x)$ joining two disticnt fixed points. But there can only be one in each direction.
Comment: Also, I think it is false that there is a heteroclinic orbit connecting any two fixed points. There could be three fixed points $z_1$, $z_2$, $z_3$ with a homoclinic orbit at each of $z_1$, $z_3$, two heteroclinic orbits (one in each direction) between $z_1$ and $z_2$, and two more conncetint $z_2$ and $z_3$, but no direct orbit connecting $z_1$ and $z_3$.
Comment: Thank you for your comments, I think that you are right that both situations can occur.
Comment: But still, if you suppose that $\omega(x)$ contains only finitely many homoclinic orbits, all fixed points are connected by the heteroclinic orbits contained in $\omega(x)$ - even though they might not be "directly connected" (i.e. there is no heteroclinic orbit joining them - the situation as described in your secound orbit) but you can still travel along different heteroclinic orbits from one fixed point to another.
Comment: I don't quite understand how exactly you can have *infinitely* many homoclinic orbits in $\omega(x)$.
Comment: The theorem itself does not exclude that this happens. Theoretically it could happen that the homoclinc orbits of a fixed point $x_{0}$ (lined up like rose pedals) accumulate at another fixed point. Of course, this would be a very exotic behaviour, and there is a form of the Poincare-Bendixson theorem which tells you that if $f$ is analytic and satisfies additional assumptions, then this behaviour cannot occur - i.e. that there are only finitely many homoclinic orbits. And I heard that there are examples of functions which have a fixed point with infinitely many homoclinic orbits.
Comment: I think what is interesting about the question is that while the Poincare-Bendixson theorem is a theorem that tells you that the $\omega$-set is quite nice if it is compact and has finitely many fixed points included, it is not per-se clear how to deduce that $\omega$ looks like you expect it from reading the theorem  - that there are heteroclinic orbits connecting the finitely many fixed points with each other.
Comment: yes, indeed, it is actually non prohibited topologically to have infinite number of homoclinic trajectories, my previous comment was wrong.
Answer: The Poincaré–Bendixson theorem say that:
Given a differentiable real dynamical system defined on an open subset of the plane, then every non-empty compact ω-limit set of an orbit, which contains only finitely many fixed points, is either:
1) a fixed point,
2) a periodic orbit, or
3) a connected set composed of a finite number of fixed points together with homoclinic and heteroclinic orbits connecting these.
Aditionally, there is at most one orbit connecting different fixed points in the same direction.
However, there could be countable many homoclinic orbits connecting one fixed point.
This theorem does not apply to discrete dynamical systems, where chaotic behaviour can arise in two or even one dimensional systems. The main reasoon here is that the condition that the dynamical system be on the plane is necessary to the theorem. One of the caracteristics of chaos is the existence of infinite number of homoclinic trajectories. So your question must be reformulated to avoid this case. Also, chaotic behaviour can be seen only in n-D continuous dynamical systems with $n>2$. So, your claim "The theorem itself does not exclude that this happens" is wrong.

Poincaré-Bendixson


P5.JS - Action every few seconds

Question: I am quite new to p5 and would need some advice.
Is it possible to trigger an action only every few seconds?
For example: After two seconds i++;
If I use draw() or an own loop function it just goes way to fast.
Thanks a lot.
Max
Comment: Sure, it's possible. Every `draw()` invocation could test `Date.now()` against a cached `lastFired` date, and if it's greater than `x` seconds, save the new `lastFired` and do the thing you want to do every `x` seconds. Could you share your code so far as a [mcve], please?
Comment: Thank you. That's a big brain solution. :D
Answer: you can make use of setInterval(function, delay) as shown below:
let counter = 0;

function increment() {
  counter++;
}

function setup() {
  createCanvas(400, 400);
  setInterval(increment, 2000); // 2000 ms = every 2 seconds
  fill(0);
}

function draw() {
  background(220);
  text(counter, 100, 100);
}

I have set up an Example Sketch for you here.
You can read more about setInterval on MDN
Comment: Wow, that's handy. Didn't know sth. like this exists in P5. Why isn't it mentioned in their references?
Comment: `setInterval(increment, 2000); // 2000 ms = every 2 seconds` is somewhat misleading. The 2000 parameter to `setInterval` means "re-call at least 2 seconds after the last call". The delays will accrue and begin to drift over time. `Date` gives you a mechanism to correct the drift, and you'll probably want to poll `Date` inside `draw()` which is a tight `requestAnimationFrame` loop.
Comment: @Skaend It's not mentioned because it's not part of P5.js, but rather a feature of JS.
Comment: @ggorlen But why does it drift over time? I dont get that
Comment: That's how it was designed. If the contract is "fire this at least 2 seconds from now", the script might get bogged down doing other heavy tasks and it might not fire for 2.1 seconds. Now all subsequent calls are off, and maybe the next one after that won't fire for 2.3 seconds after the last one. leading to .4 seconds of drift that just keeps getting worse. There is no timer that internally corrects this. See [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript/29972322#29972322)

P5.JS - Action every few seconds


Convergence of $f_n=(1-x)^n$ on different intervals.

Question:
Let $f_n=(1-x)^n$. Show the convergence is uniform on $[a,2-a]$ where $a \in (0,1)$

I found the pointwise limit function $f$ to be $1$ is $x=0$ and $0$ on $x\leq 1$.
If $x>1$ the limit function is also $0$.
Now I showed that it's not uniformly convergent on $(0,1)$ because there isn't an $N$ which works for the whole interval, since I can take $\lim x\rightarrow 0$.
Now for the main part:
Clearly the local maximums are attained at $a$ and $2-a$ (in the second, could be negative).
Now I think I need to somehow pick $N$ depending on the $\max \{a,2-a\}$ such that $$|f_n(x)-0|<\epsilon$$
Can somebody help me out?
Answer: Hint: if $N$ works for both $a$ and $2-a$, then it works for every number in the range.
Comment: I need to solve $|(1-a)^n|<\epsilon$ and $|(a-1)^n|<\epsilon$ , but if I take logs, $n \log (1-a) < \log \epsilon $, somehow $n$ is less than, which I think is incorrect, surely any bigger $n$ should work too.
Comment: $log(1-a)$ is negative.
Comment: but then $\log (a-1)$ should'nt even exist (in reals at least).
Comment: In that case you could not take logs of both sides of the equations in the first place.
Comment: Will the answer be sufficient? $\max\{N_1,N_2\}$?
Comment: If I were grading this, I would prefer the whole proof written out, so if you are handing it in, I would recommend you write the proof out.  You might also want to write it out if you just want to practice writing proofs, or if you're not completely confident about it.


Base62 codificação

Question: Gostaria de saber onde posso obter alguma implementação em PHP, semelhante ao MIME Base64 do PHP mas que conte apenas com os caracteres de A-Z, a-z e 0-9.
O Base64 do PHP é bastante versátil, mas preciso de um algoritmo que não contemple os caracteres +, /, - e =. Sei que posso substituir os caracteres mencionados para efeitos de um URL, que até nem é o caso, mas pretendia mesmo um algoritmo de codificação directo.
A codificação de números para base62, é linear, mas pretendia a codificação de uma string PHP binária. Importante realizar o encode e o decode.
Alguém me pode indicar alguma implementação prática?
Comment: https://github.com/vinkla/base62
Comment: @gmsantos agradeço a referência mas já conhecia, mas como expliquei para mim a codificação Base62 de valores numéricos é básica e linear. O que pretendo é um codificador com o range (A-Z, a-z e 0-9) mas para strings. E isso não encontro e acho que tenho mesmo de desenvolver um e na unha mesmo. Mas agradeço o seu tempo.
Comment: @chambelix Viu a minha resposta?
Comment: @Victor vi e vou responder estou a analisar :)
Answer: Segue a implementação.

Implementado em duas linguagens diferentes: PHP e em Java.
Permite você especificar o alfabeto no construtor.
O tamanho do alfabeto é obtido a partir do próprio alfabeto.
Deve funcionar para qualquer tamanho de alfabeto >= 2 e < 256.
O funcionamento do encode consiste em interpretar a String de entrada como um número base-256 a ser convertido em BigInteger. Em seguida, o BigInteger é convertido para uma String em base-62 (ou qualquer outra, de acordo com o alfabeto dado).
O funcionamento do decode é apenas o inverso do encode. Recebe a String como se fosse um número em base-62 (ou qualquer outra), converte para BigInteger e então converte o BigInteger para uma String base-256.

PHP:
Eis o código:
<?php

include('Math/BigInteger.php');

class BaseN {

    private $base;
    private $radix;
    private $bi256, $one, $zero;

    function __construct($base) {
        $this->base = $base;
        $this->radix = new Math_BigInteger(strlen($base));
        $this->bi256 = new Math_BigInteger(256);
        $this->zero = new Math_BigInteger(0);
        $this->one = new Math_BigInteger(1);
    }

    public function encode($text) {
        $big = $this->one;
        for ($j = 0; $j < strlen($text); $j++) {
            $big = $big->multiply($this->bi256)->add(new Math_BigInteger(ord($text[$j])));
        }
        $result = "";
        while (!$this->zero->equals($big)) {
            $parts = $big->divide($this->radix);
            $small = intval($parts[1]->toString());
            $big = $parts[0];
            $result = $this->base[$small] . $result;
        }
        return $result;
    }

    public function decode($text) {
        $big = $this->zero;
        for ($j = 0; $j < strlen($text); $j++) {
            $i = strpos($this->base, $text[$j]);
            $big = $big->multiply($this->radix)->add(new Math_BigInteger($i));
        }
        $result = "";
        while (!$this->zero->equals($big)) {
            $parts = $big->divide($this->bi256);
            $small = $parts[1]->toBytes();
            $big = $parts[0];
            $result = $small . $result;
        }
        return substr($result, 1);
     }
}

?>

Modo de usar:
// Passa o alfabeto como parâmetro. Tem 62 caracteres aqui, então são 62 símbolos.
$k = new BaseN("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
$x = "The quick brown fox jumps over a lazy dog";
echo $x . "\n";
$c = $k->encode($x);
echo $c . "\n"; // Escreve "1u9WLfG65OMtVkQWPtWDcC6o8IjI5td5l9DzpilIK4Nyx81tKLRrStPj"
$d = $k->decode($c);
echo $d . "\n"; // Escreve "The quick brown fox jumps over a lazy dog"

Veja aqui no ideone (não se assuste com o tamanho do código, tive que colocar a classe BigInteger inteira lá).
Em Java
E, caso alguém se interesse, eu também implementei em Java. Eis o código:
import java.util.List;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author Victor
 */
public class BaseN {
    private static final BigInteger BI_256 = BigInteger.valueOf(256);

    private final String base;
    private final BigInteger radix;

    public BaseN(String base) {
        this.base = base;
        this.radix = BigInteger.valueOf(base.length());
    }

    public String encode(String text) {
        byte[] bytes = text.getBytes();
        BigInteger big = BigInteger.ONE;
        for (byte b : bytes) {
            big = big.multiply(BI_256).add(BigInteger.valueOf(b));
        }
        StringBuilder sb = new StringBuilder(bytes.length * 4 / 3 + 2);
        while (!BigInteger.ZERO.equals(big)) {
            BigInteger[] parts = big.divideAndRemainder(radix);
            int small = parts[1].intValue();
            big = parts[0];
            sb.append(base.charAt(small));
        }

        return sb.reverse().toString();
    }

    public String decode(String text) {
        BigInteger big = BigInteger.ZERO;
        for (char c : text.toCharArray()) {
            int i = base.indexOf(c);
            if (i == -1) throw new IllegalArgumentException();
            big = big.multiply(radix).add(BigInteger.valueOf(i));
        }

        List<Byte> byteList = new ArrayList<>(text.length());
        while (!BigInteger.ZERO.equals(big)) {
            BigInteger[] parts = big.divideAndRemainder(BI_256);
            int small = parts[1].intValue();
            big = parts[0];
            byteList.add((byte) small);
        }
        Collections.reverse(byteList);

        byte[] r = new byte[byteList.size() - 1];
        int i = 0;
        for (Byte b : byteList) {
            if (i > 0) r[i - 1] = b;
            i++;
        }
        return new String(r);
    }
}

Modo de usar:
public class Main {
    public static void main(String[] args) {
        // Passa o alfabeto como parâmetro. Tem 62 caracteres aqui, então são 62 símbolos.
        BaseN bn = new BaseN("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
        String x = "The quick brown fox jumps over a lazy dog";
        System.out.println(x);
        String a = bn.encode(x);
        System.out.println(a); // Escreve "1u9WLfG65OMtVkQWPtWDcC6o8IjI5td5l9DzpilIK4Nyx81tKLRrStPj"
        String b = bn.decode(a);
        System.out.println(b); // Escreve "The quick brown fox jumps over a lazy dog"
    }
}

Veja aqui no ideone.
Comment: dou os meus parabéns pois você acabou de me entregar um algoritmo que me vai poupar algumas horas... ainda por cima você utiliza o Math_BigInteger como eu. Só posso votar uma vez e já o fiz porque senão votava mais vezes na tua resposta. Deixe me dizer que a sua solução é completa e o código bem estruturado. Posso usar em meu código? Quanto à solução em JAVA é a cereja em cima do bolo.
Comment: já vi :) mais uma vez os meus parabéns... corrigidissimo!
Comment: @chambelix Claro que pode usar! :) Fico grato em ter ajudado, pois este daqui foi bem desafiador e interessante de fazer.
Comment: Ocorre um erro em determinados tamanhos de string no encode na linha $small=ord($parts[1]->toBytes()[0]). Mas já apanhei...mais uma vez obrigado.
Comment: @chambelix Me explique melhor o erro. Odeio bugs. Que string você usou?
Comment: @chambelix Acho que tenho uma solução para este bug, mas primeiro preciso de um caso de teste que o reproduza para confirmar se minha correção funciona. O problema é que não encontrei nenhum caso que reproduza o bug ainda, então se você puder me fornecer, corrijo com prazer. :)
Comment: tente a string "excelente solução" vai dar certo, mas se adicionar mais um espaço entre as palavras ou colocar mais um caracter... vai dar erro. estou aqui a acabar um código  só vou analisar o seu algoritmo depois e resolver o erro. se não se quiser incomodar depois dou resposta. erros são normais.
Comment: @chambelix: https://ideone.com/Mu6ZGh - `excelente  solução` o encode gerou `p0KO2123BeMgaOUElggUpPOWYFb` que gerou `excelente  solução` no decode, ou seja, funcionou. No entanto o `ç` e o `ã` me fazem querer olhar para problemas de encoding.
Comment: @chambelix `PHP Notice:  Uninitialized string offset: 0 in /home/miR2Be/prog.php on line 1990` - Ok, já dou um jeito nisso...
Comment: a mim "excelente solução1" me dá o erro "Notice: Uninitialized string offset: 0"... no entanto tentei uma abordagem direta ao problema e coloquei... if (isset($parts[1]->toBytes()[0])) {
                $small = ord($parts[1]->toBytes()[0]);
            } else {
                $small = 0;
            } ---> e resolve!
Comment: @chambelix Corrigido. :)
Answer: Você não pode ter algo representado em base64 com apenas este range de caracteres (A-Z, a-z e 0-9) pois este range conta com apenas 62 caracteres e base64 exige 64 representações distintas.
Então se você não quiser os caracteres + e / na sua representação em base64, precisará substituí-los por outra coisa fora deste range. Terá que escolher uma substituição para o = também pois ele pode aparecer numa representação em base64 a fim de completar o tamanho do último bloco.
O que tem sido usado na prática, quando da necessidade por exemplo de incluir uma representação base64 em uma URL, é substituir o conjunto {+ / =} por {- _ ,}, respectivamente.
Numa pesquisa rápida, me pareceu que PHP não possui nativamente uma função para isso, de modo que você terá que implementar a sua própria.
Mesmo que sua intenção não seja a utilização em URL, esta idéia deve lhe servir:
function base64url_encode($plainText) {

    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

function base64url_decode($plainText) {

    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

Update: Acabou de me ocorrer também que você pode converter seus bytes para Hexadecimal, o qual é representado apenas por 0-9 e A-F. A string resultante fica bem maior que na representação base64, mas talvez lhe sirva. Não conheço função PHP que faça isso mas a lógica de conversão de bytes para hexadecimal é bastante simples.
Comment: Não acho que seja isso que ele quer. Pelo que entendi, ele quer um algoritmo de codificação em base-62, e não representar um base-64 com 62 símbolos distintos. E mesmo assim, existe formas de você representar base-64 com 62 símbolos. Por exemplo, você usa 61 símbolos normalmente (`0`-`9`, `A`-`Z` e `a`-`y`), e então usa `za`, `zb` e `zc` para corresponderem aos três símbolos distintos restantes, aonde `z` não pode aparecer no final e nem seguido de algo que não seja `a`, `b` ou `c`.
Comment: @Victor Existem 1001 formas de representar qualquer valor de qualquer maneira, e você pode inventar mais uma - igual Neston. Basta fazer uma funçãozinha como esta que colei na minha resposta :-)
Comment: sim, exatamente. É que na sua resposta você diz *Você não pode ter algo representado em base64 com apenas este range de caracteres*, e eu acabei de mostrar uma forma de fazer isso. :)
Comment: @Victor, todos sabemos que entre o céu e a terra há mais coisas do que sonha a nossa filosofia; então escrevemos *"sim"*, *"não"*, *"sempre"*, *"nunca"* sem medo porque sabemos que em algum grau ou em algum momento ou de algum ponto de vista algo será diferente do que foi afirmado - e os sábios nos lêem sem levar ao extremo estas palavras porque sabem o mesmo e sabem que sabíamos ao escrever. Por isso não se preocupe, apenas escreva uma resposta com as suas idéias e ela terá o potencial de ajudar alguém. Se não ajudar, o mecanismo do SO (votos, moderação..) cuida para que também não atrapalhe.
Comment: @Caffé agradeço e muito o seu tempo mas como referi na minha pergunta mencionei que "Sei que posso substituir os caracteres mencionados para efeitos de um URL" e conheço muito bem o algoritmo Base64 a sua aplicabilidade. A sua resposta está um pouco fora da minha pergunta... Mas agradeço o tempo que perdeu.

Base62 codificação


How do I display fields from a Commerce Cheque transaction using Views?

Question: We have been processing payments in Drupal Commerce using the Commerce Cheque module. For accounting purposes, we would like a view showing all checks received with check numbers, etc..
How do I configure a view to display fields from Commerce Cheque, specifically check number?
Answer: You can create a view of of Payment Transactions and filter by Payment Method = check.
The check reference number is stored in the field called Remote ID. Just add that field to the view.


How to set up Google+ authorship in Drupal 7

Question: How do you set up Google+ authorship in Drupal 7?
So I can link my drupal website to our Google+ account so that our Google+ profile pic can appear in the search engines next to our site.
Answer: The easiest way is with the Metatag module:

The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about your website. In the context of
  search engine optimization, when people refer to meta tags they are
  usually referring to the meta description tag and the meta keywords
  tag that may help improve the rankings and display of your site in
  search engine results.

After you install/enable the module, you can edit the metatags at admin/config/search/metatags  The Google+ Author is under Advanced.


Creating melodic/harmonic music with Csound?

Question: I am diving into Csound in an effort to gain more control over the creation and manipulation of sound. It is comprehensive, to be sure, but its practitioners seem to be consumed with exploiting the unique capabilities of synthesized sound rather than creating music that has an emphasis on more traditional melody and/or harmony.
Is this a shortcoming of the language, making it exceedingly difficult to focus on these traditional aspects, or is it just that the composers who would choose to use a tool like this are more likely to prioritize other aspects of composition?
Comment: I find this interesting, but I'm afraid such questions are off-topic here.
Comment: @leftaroundabout How is it off-topic?
Comment: I find this interesting too, and though I know that such questions (requesting external resources as per https://music.stackexchange.com/help/on-topic) are off topic here, I wish this one wasn't - so +1 from me!
Comment: Ah, I see. I will reword to avoid the transgression :)
Answer:
Is this a shortcoming of the language, making it exceedingly difficult to focus on these traditional aspects, or is it just that the composers who would choose to use a tool like this are more likely to prioritize other aspects of composition?

It's certainly not a fundamental limitation of the language - CSound and its instrument libraries allow traditional note-based pieces with any kind of melody and harmony you like. In fact one reason I avoid CSound is that it's still a little too traditional for my liking - in particular, the similarity that i-statements have with the traditional idea of a 'note' with a certain duration.
However, the lower-level a tool you choose, the more work you typically have to do yourself to get things sounding nice - and it may be fair to say that "out-of-the-box", Csound instruments don't tend to sound as obviously pretty as the best patches on a typical VST or hardware synthesizer - and the workflow might not be as immediately fun as mucking around with those.
I would also agree that the priorities of a composer who has come to CSound might be atypical. But IIRC it's a fairly simple thing to set up a couple of instrument sounds and get some 'proper tunes' going. There are plenty of alternatives though when it comes to coding languages though - sonic Pi is one that I recently saw demonstrated impressively.
Comment: Yes, I have been toying around with Cabbage. I like the in-app help. There are Python bindings to Csound, and since I am a programmer, I think I could put that to great use. My original question unfortunately was off-topic, but does anyone have any links to compositions that were created with Csound that are focused on melody and/or harmony instead of sound design?
Comment: Interesting that you find Csound too traditional! I see what you're saying with the i-statements. That's also why I'm interested in it--it has been around for a very long time and will likely not be abandoned, so I can rely on its longevity.
Comment: @DavidVogel it's definitely here to stay, I would think. Have you tried any of the [frontends](http://csound.com/frontends.html)?


Why is Debussy's remark brilliant (on going out and smoking, at the start of Beethoven's developments)?

Question: From: Charles Rosen. Critical Entertainments. p. 117 Bottom - 118 Top.

  In the same way, attacks on Beethoven could be profound and even persuasive, and would continue to be so after his death even to the present. Most musicians (outside of Central Europe) will appreciate the brilliance of Debussy's remark at a concert during a Beethoven symphony: "Ah, the development section is beginning; I can go out and smoke a cigarette." The way Beethoven's reputation was "constructed" is perhaps revealed best in some comments made in 1812
  by a close friend of Goethe, the composer Karl Friedrich Zelter:5 "I, too, regard him with terror ... His works seem to me like children whose father is a woman or whose mother is a man ... I know musical people who once found themselves alarmed, even indignant, on hearing his works and are now gripped by an enthusiasm for them like partisans of Greek love."
A few years later Zelter was to
  become the teacher of Mendelssohn, who would take the latest and most difficult works of Beethoven as models for his own compositions, but in 1812 Beethoven was a monstrosity for Zelter.

Am I right to infer that Debussy judged these development sections boring and unworthy?
Even if yes, how's this judgement 'brilliant'? Isn't it churlish and cheeky?
Comment: Perhaps Debussy was making fun of those who didn't appreciate Beethoven's style.
Answer: In short, the German musical tradition (largely based upon Beethoven's towering presence) is one that prioritizes thematic development. Beethoven was known, for instances, for sometimes introducing and developing new themes in his codas!
This propensity for thematic development was not necessarily shared by the composers in the Italian and French traditions. This quote from Debussy would have been a quip against what he would have felt was an unnecessary fetishization of thematic development.
Some related quotes from Richard Taruskin's Music in the Nineteenth Century (The Oxford History of Western Music, Volume 3), pp. 21–22:

But the avoidance in [Rossini's] music, on the one hand, of rigorous motivic unfolding, and, on the other, of symbolic harmonic drama was something German musicians and their colonial adherents found infuriating, for these (along with the spirituality that was assumed to result from them) were the very terms on which they staked their claim to universality of appeal. . . . [W]hat was a lack in Rossini [of thematic development] was turned by later generations of "Latinate" composers into an avoidance, and touted. The best illustration is a quip supposedly made by Claude Debussy . . . while listening to a symphony by Johannes Brahms . . .

(No, that's not a typo; Taruskin claims this was at a Brahms concert, not Beethoven. But the rationale is still the same; Brahms's First Symphony, after all, was jokingly called Beethoven's Tenth.)
As for whether Debussy's remark was "brilliant" or "churlish and cheeky," that's ultimately a question of opinion and probably can't be definitively answered. My sense is that Rosen was probably using "brilliant" in the sense of "clever" or "funny."
Comment: I agree with this, but I also think that part of Debussy's joke is that Beethoven's developments were also *very* long by the standards of the day. Famously, Some of his developments are longer then the exposition and recapitulation combined.
Comment: @PatMuchmore Also very true!
Comment: I feel the remark is better applied to Brahms then Beethoven, but don't know what Debussy thought.


else statement ignored

Question: In my view, I am testing to see if certain records exist. If they do, I iterate over them and display each one. If these records do not exist, however, I want a message to be displayed. Here is the code from my view:
      <% if current_user.lineups %>
        <% for lineup in current_user.lineups do %>

<%= link_to "#{lineup.course.cl} #{lineup.course.cn}", index_path %>

        <% end %>
      <% else %>

<%= link_to "You have no courses", index_path %>

      <% end %>

Now, the iteration works just fine when the records exist. Whenever I create the proper records, this code works marvelously and creates a link for each record that is iterated over. However, If no records exists, nothing is displayed. The 'else' statement is completely ignored. I tried amending the 'if' stament but to no avail. I tried:
<% unless current_user.lineups.nil? %>

As well as:
<% if !( current_user.lineups.nil? ) %>

I am at my wits end here. Any and all input would be appreciated.
Comment: The reason `else` is "ignored" is that `lineups` is an empty array and empty arrays are *thruthy*. In other words, it never reaches the `else` because `if []` evaluates to `true`. Either of the answers below will solve your problem.
Answer: Empty array is not nil, try to use any? or empty?
<% if current_user.lineups.any? %>
  ...
<% else %>

<%= link_to "You have no courses", index_path %>

<% end %>

Answer: try this in your if statement
<% if current_user.lineups.blank? %>

<%= link_to "You have no courses", index_path %>

<% else %>
   <% for lineup in current_user.lineups do %>

<%= link_to "#{lineup.course.cl} #{lineup.course.cn}", index_path %>

   <% end %>
<% end %>

it will check lineups array is empty or nil both the cases.
Answer: you can try
if current_user.lineups.present? # true if any records exist i.e not nil and empty
  # do if records exist
else
  # do if no records exist
end

present? is just not(!) of blank?
you can use blank?  or present? as per your code placement you need.
if you use blank? go with @abhas answer

else statement ignored


Using ng-grid in partial page

Question: Is there any example of using ng-grid in partial pages. Whenever I try to use, an error pops up as TypeError: Cannot set property 'myData' of undefined.
My App.js
'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'ngGrid']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
    $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);

Controller.js
'use strict';

/* Controllers */

angular.module('myApp.controllers', ['ngGrid']).
  controller('MyCtrl1', [function ($scope) {

      $scope.myData = [{name: "Moroni", age: 50},
                 {name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27},
                 {name: "Nephi", age: 29},
                 { name: "Enos", age: 34 },];
      $scope.gridOptions = {
          data: 'myData',
          columnDefs: [{ field: 'name', displayName: 'Name' },
              { field: 'age', displayName: 'Age', cellTemplate: '
 30}">
{{row.getProperty(col.field)}}

' }],
          showGroupPanel: true
      };
  }])
  .controller('MyCtrl2', [function() {

  }]);
//MyCtrl1.$inject = ['$scope'];

Partial1.html

This is the partial for view 1.

{{ myData | json }}

Partial2.html

This is the partial for view 2.

  Showing of 'interpolate' filter:
  {{ 'Current version is v%VERSION%.' | interpolate }}

And index.html
<!doctype html>

  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="css/app.css"/>
  <link rel="stylesheet" href="css/bootstrap.css">
  <link rel="stylesheet" href="css/ng-grid.css">
  <link rel="stylesheet" href="css/Style.css">

view1

view2

Angular seed app: v

Can you please say, why 'myData' is unavailable in Partial1.html?
Thanks in advance.
Answer: It is probably too late, but for the code right here
    {name: "Enos", age: 34 },];
you don't need the coma.  It should read:
    {name: "Enos", age: 34 }];

Using ng-grid in partial page


Estimating Parameters using MLE

Question: I am new to R and I have been struggling on this for a while. I have a set of 611 data points, and I am trying to estimate its parameters (using MLE) to see if the data comes from a gamma distribution. I would then like to eventually plug the parameters found into a gamma model to then generate a density plot.
So far, I have
     library(MASS)
     fitdistr(fireloss, "gamma")
     #outputs
     shape           rate
     2.861599e+00   1.963065e-03
     (1.116362e-01) (7.202933e-05)

I am unsure how to interpret the output. How would these parameters be plugged into a gamma model to generate a density plot? Thanks for the help!
Comment: Possible duplicate of [How to draw fitted graph and actual graph of gamma distribution in one plot?](https://stats.stackexchange.com/questions/190465/how-to-draw-fitted-graph-and-actual-graph-of-gamma-distribution-in-one-plot)
Answer: The output gives you the shape and rate parameter of the gamma distribution; you can find on Wikipedia the formula for the shape-rate parametrization.
To plot the probability density function you can just plug the values you obtained in the dgamma function. (I have also generated some data for adding them in the plot as histogram).
shape <- 2.861599e+00  # these are your estimated parameters
rate <- 1.963065e-03

y <- rgamma(611, shape = shape, rate = rate) # some random data
x <- seq(0, 6000, length.out=300)

hist(y, breaks = 30, freq = F)
lines(x, dgamma(x, shape = shape, rate = rate), type = "l", col = "blue", lwd = 2)

Estimating Parameters using MLE


DB2 Select with group by and sum based on another column

Question: I have the following situation:
ACCT_TABLE

ID|TYPE|AMT
--+----+---
A |CR  |  5
A |DR  |  5
B |CR  |  2
B |CR  |  4
B |DR  |  2
B |DR  |  2
C |CR  |  1
C |CR  |  1

I am trying to build a query that produces the following results:
DESIRED RESULT

ID|BAL
--+---
A |  0
B |  2
C |  2

ACTUAL RESULT

ID|BAL
--+----
A | -10
B |  -8
C |   2

I'm not sure how to sum the values in amount based on the value in the TYPE column.
I have the following:
    select id, sum(
        case
        when
            type = 'CR'
            then AMT
            else -AMT
        end
    ) as BAL
    from acct_table
group by id;

Comment: so the only thing you missing is `GROUP BY ID` and you should be done
Comment: Sorry, I do have that. I just missed copying it here.
Comment: so what is the problem?
Comment: The problem is that it is summing, but not subtracting DR's. It just appends a `-` to those records.
Comment: replace `-AMT` with `(AMT*-1)`
Comment: Bal for B should be 2 instead 4 because you got +2,+4,-2,-2
Comment: Tried (AMT*-1)... same result.
Comment: What is data type of `AMT` column
Comment: AMT -> DECIMAL with length of 10
Comment: @VladimirOselsky I was once scolded here for using multiplication where subtraction would suffice: `0-AMT` produces the same result and should conceivably perform better.
Comment: @JTFRage were you able to figure out what issue caused this?
Comment: Yes I was, and it was correct. There was no problem. Just happened to have accounts that either had CR or DR. So the sum would either be a credit or a debit (+/-) so I wasn't seeing changes. I however did have one account lol that changed. LOL I just read my data wrong and wasn't checking manually.
Answer: I have tested your query in mysql, postgresql, sql-server,oracle and it produced desired results.
Your Query
SELECT id
       ,SUM(CASE WHEN type = 'CR' THEN AMT
                 ELSE -AMT
            END) AS BAL
    FROM acct_table
    GROUP BY id;

My Query
SELECT id
       ,SUM(CASE WHEN type = 'CR' THEN AMT
                 ELSE ( AMT * -1 )
            END) AS BAL
    FROM acct_table
    GROUP BY id;

oracle test - http://sqlfiddle.com/#!4/0b8cb/1
mysql test- http://sqlfiddle.com/#!2/0b8cbd
postgresql test - http://sqlfiddle.com/#!15/0b8cb/1
Please verify that data in your table matches what you have shown in the question.
Comment: Out of curiosity, why did you change `-AMT` to `AMT * -1`?
Comment: to make it more explicit.
Answer: I tested a query performing summing like that in DB2 (9.7 LUW), and it also worked.
There appears to be nothing wrong with your query; it must be something else.


How to cleanly put HTML elements on the same line using CSS

Question: My question is how to cleanly put two elements on the same line.
Here is my fiddle: https://jsfiddle.net/duqpn0wd/
CSS:
    .inline-block {
    display: inline-block;
    }

Wrapper:

In the fiddle you can see a text with a button underneath it but I need them to be left align and right align like so:
TEXT                                                                BUTTON
Right now using inline-block helps but I would need each element to be an inline and the line after that would also be inline so that would merge into my existing first line like so:
TEXT     BUTTON     TEXT    BUTTON
Any ideas on how to do this properly?
Comment: You put the text in ``, those are block level elements. Use `Alarm Horn: `
Comment: this is also a good point, thank you
Answer: Use float: left; for the p inside .inline-block:

.inline-block {
    display: inline-block;
    width: 100%;
 }
 .inline-block p{
   float: left;
 }
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />

 Alarm

Alarm Horn:

    <select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
      <option value="off">OFF</option>
      <option value="on">ON</option>
    </select>

Alarm Light:

    <select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
      <option value="off">OFF</option>
      <option value="on">ON</option>
    </select>

 Fault

    Start Fault Time:
    <button id="number-input-1" class="keyboard-input" data-inline="true">100</button>
    seconds

Comment: Nice and clean, I like the width since it makes it go to the next line. Thank you
Answer: Just add this code to your CSS
.inline-block > p {
  float: left;
}

Answer: Just modify your css with this

.inline-block {
 display: inline-block;
}
p{
  display:inline-block;
}
select{
  display:inline-block;
}
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />

 Alarm

Alarm Horn:

<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
  <option value="off">OFF</option>
  <option value="on">ON</option>
</select>

Alarm Light:

<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data- wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>

 Fault

Start Fault Time:
<button id="number-input-1" class="keyboard-input" data-   inline="true">100</button>
seconds

Comment: Changing `p` like that in general is probably a bad idea.
Comment: I just shown him how he can accomplish his goal, he can add `id` to `p` and use in css.
Answer: You can specify your CSS as :
.inline-block { /* select the class */
display: inline-block;
}

.inline-block *{ /* select all the child element  */
 display: inline-block;
}

Adding any element to your class will be aligned in a single line.


Partitions of the set of vertices of a directed graph

Question: Consider a directed graph and a partition $P$ of its set of vertices. We construct a new partition $P'$ of this set as follows: declare $v_1$ and $v_2$ to be in the same part of the partition $P'$ if for every $p\in P$, $v_1$ arrows into $x\in p$ for some $x$ iff $v_2$ arrows into $y\in p$ for some $y$. The problem is to prove or give a counterexample to the statement that the finer the original partition is, the finer the new partition will be. (By finer I mean either the same or strictly finer.)
I haven't been able come up with a counterexample, so I'm trying to prove this. Suppose this is false. Let $P_1$ and $P_2$ be two partitions. Denote by $P_i'$ the corresponding new partition. By assumption, $P_2'$ is not finer than $P_1'$. So there is $x\in P_2'$ such that for all $y\in P_1'$ it is not the case that $x\subset y$. I need to show that then there is $X\in P_2$ such that for all $Y\in P_1$ it is not the case that $X\subset Y$. But I don't quite understand how to use the definition of the new partition to deduce this. Any help?
Answer: I think that a direct proof is more simple than a proof to the contrary. Assume that $P_2$ is finer than $P_1$. Consider any $p'_2\in P_2'$. Let $v,u\in p'_2$ be any vertices and $p_1\in P_1$ be any element. If $v$ arrows to $x$ for some $x\in p_1$ then, since $P_2$ is finer than $P_1$, there exist $p_2\in P_2$ with $x\in p_2\subset p_1$. Since $v,u\in p'_2$, there exists $y\in p_2\subset p_1$ such that $u$ arrows to $y$. Similarly we can show that if $u$ arrows to $x$ for some $x\in p_1$ then there exists $y\in p_1$ such that $v$ arrows to $y$. Thus $v$ and $u$ are in the same part of the partition $P'_1$. So $P'_2$ is finer than $P'_1$.
Comment: What definition of "$P_2$ is finer than $P_1$" are you using? I thought it means that every element of $P_2$ is a subset of some element of $P_1$. But it looks you're using another definition. Is your definition equivalent to the above?
Comment: (Addition to the above: you must be using the definition in line 3 and in the last line, and I don't quite understand what's the definition that you are using and what exactly you are proving.) And could you clarify how this follows: "since $u,v\in p_2'$, there exists $y\in p_2\subset p_1$ such that $u$ arrows to $y$"? Also, you write "if $v$ arrows to $x$" or "if $u$ arrows to $x$", but what if not?
Comment: @user638943 1. Yes, I use the same definition as you. 2. Since $v$ arrows to $x$, $x\in p_2$, and $v,u\in p'_2$, by definition of $P'_2$, $u$ arrows to $y$ for som  $y\in p_2$. 3. In order to show that $v$ and $u$ are in the same part of the partition $P'_1$ we have to sheck that for every $p_1\in P_1$, $v$ arrows into $x\in p_1$ for some $x$ $\Leftrightarrow$ $u$ arrows into $y\in p_1$ for some $y$. When we consider $v$ arrows to $x$, we show $\Rightarrow$, when we consider $u$ arrows to $x$, we show $\Leftarrow$.


the derivative of $n^x, n\in\mathbb{R}$ using the definition of derivative

Question: I know that the derivative of $n^x$ is $n^x\times\ln n$ so i tried to show that with the definition of derivative:$$f'\left(x\right)=\dfrac{df}{dx}\left[n^x\right]\text{ for }n\in\mathbb{R}\\{=\lim_{h\rightarrow0}\dfrac{f\left(x+h\right)-f\left(x\right)}{h}}{=\lim_{h\rightarrow0}\frac{n^{x+h}-n^x}{h}}{=\lim_{h\rightarrow0}\frac{n^x\left(n^h-1\right)}{h}}{=n^x\lim_{h\rightarrow0}\frac{n^h-1}{h}}$$ now I can calculate the limit, lets:$$g\left(h\right)=\frac{n^h-1}{h}$$ $$g\left(0\right)=\frac{n^0-1}{0}=\frac{0}{0}$$$$\therefore g(0)=\frac{\dfrac{d}{dh}\left[n^h-1\right]}{\dfrac{d}{dh}\left[h\right]}=\frac{\dfrac{df\left(0\right)}{dh}\left[n^h\right]}{1}=\dfrac{df\left(0\right)}{dh}\left[n^h\right]$$
so in the end i get: $$\dfrac{df}{dx}\left[n^x\right]=n^x\dfrac{df\left(0\right)}{dx}\left[n^x\right]$$
so my question is how can i prove that $$\dfrac{df\left(0\right)}{dx}\left[n^x\right]=\ln n$$
edit:
i got 2 answers that show that using the fact that $\lim_{z \rightarrow 0}\dfrac{e^z-1}{z}=1$, so how can i prove that using the other definitions of e, i know it is definition but how can i show that this e is equal to the e of $\sum_{n=0}^\infty \frac{1}{n!}$?
Comment: If you are using the definition of derivative, it is illogical to use L'Hôpital's rule.
Comment: @Miguel i proved the case of L'Hôpital's rule for $\frac{0}{0}$ so i dont see why not
Comment: Because if you can compute the derivative to apply L'Hôpital's rule, you already know the derivative, which was your question to begin with?
Comment: @Miguel why? i proved that in case if $\frac{g(x)}{f(x)}=\frac{0}{0}$ than $\frac{g(x)}{f(x)}=\frac{g'(x)}{f'(x)}$, where did i found the derivative of $n^x$ there? i only use it
Answer: $n^h = \exp((h \log n))$;
$\dfrac{n^h-1}{h} = \dfrac{\exp(h(\log n))-1}{h};$
$z: = h\log n$.
Then:
$\lim_{h \rightarrow 0}\dfrac{\exp(h(\log n))-1}{h} =$
$\lim_{z \rightarrow 0}$ $\log n \dfrac{\exp(z) -1}{z} =$
$\log n ×1= \log n$.
Used: $\lim_{z \rightarrow 0} \dfrac{\exp(z)-1}{z} =1$.
Comment: but how can i show that $\lim_{z \rightarrow 0}\dfrac{e^z -1}{z}=1$?
Comment: Textbook:  Exponential series expansion, with remainder, then inequalities.Simpler, infinite series, exp(z) = 1 +z+z^2/2 +....., subtract 1, divide, take the limit, less stringent.Is ok?
Comment: yes, thank you very much
Comment: Anytime, welcome, hope it helps.The inequality is kind of standard, derivation can be found in textbooks, Peter
Answer: It depends on what you feel you can assume about the function ln(x) and the number e.
See the link below for an approach similar to yours:
http://tutorial.math.lamar.edu/Classes/CalcI/DiffExpLogFcns.aspx
Comment: But how did they proved that $\frac{e^h-1}{h}$ when h is a limit to 0 equal to 1?
Answer: If you don't have a definition of the logarithm handy (or suitable properties taken for granted), you cannot obtain the stated result because the logarithm will not appear by magic from the computation.
Assume that the formula $n^x=e^{x \log n}$ is not allowed. Then to define the powers, you can work via rationals
$$n^{p/q}=\sqrt[q]{n^p}$$ and extend to the reals by continuity.
Using this apporach, you obtain
$$\lim_{h\to0}\frac{n^h-1}h=\lim_{m\to\infty}m(\sqrt[m]n-1)$$
and you can take this as a definition of the logarithm.
$$\log n:=\lim_{m\to\infty}m(\sqrt[m]n-1).$$


what does "strict part writing(strenger satz)" means?

Question:
Suspensions, passing-notes and changing-notes greatly enhance the melodiousness of the voices; the simplest chord--succession can, by means of these three attributes of voice-leading, be exalted to a high pitch of artistic and technical perfection. Nowhere is this perfection so thoroughly attained as in so-called strict part-writing. He who can skillfully handle the scanty material, to which this mode of writing is restricted, may well consider himself a master of harmonization.

I excerpted some phrases from a book named "Guide to the Practical Study of Harmony" Written by Tchaikovsky.
What is strict part writing? Does it means the combination of the most fundamental elements? and Why did Tchaikovsky say "He who can skillfully handle the scanty material, to which this mode of writing is restricted, may well consider himself a master of harmonization." ?
Reference book:https://www.musikipedia.dk/dokumenter/ovelser/generalbas-bog.pdf
Comment: You may find more information by googling "strict counterpoint." Looking at the context of your excerpt, I'd say that this is what Tchaikovsky is referring to. Look up also Johann Fux and Gradus ad Parnassum.
Answer: I think that this refers to when you write for say 4 voices, and you obey all the rules required in traditional part writing (no consecutive 5ths or octaves, good spacing, no doubling of the 3rd, etc.) and yet you manage to come up with something interesting and musical.  This is easier said than done, and I guess that is what Tchaikovsky was referring to.  A great example of such a master is Palestrina.


PHP Library similar to GD

Question: Im looking for a PHP library similar to the PHP GD library though having simplified classes.
Any suggestions?
Comment: What is the complexity you like to avoid? GD is (mostly) straight forward
Answer: GD is only one library for image processing. PHP also has other library extensions:

ImageMagick a native php extension to create and modify images using the ImageMagick API.
Gmagick a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.
Cairo a native PHP extension to create and modify graphics using the Cairo Graphics Library.
Exif With the exif extension you are able to work with image meta data.

Here is comparison: http://kore-nordmann.de/blog/comparision_of_php_image_libraries.html
Comment: Wow thanks, if I get the chance I shall try these. Looks interesting.
Answer: Have you tried ImageMagick?
Comment: Thanks, this is helpful. Though it would be better if we have something much simpler.
Comment: ImageMagick can be fantastic, but I would hardly describe it as having simplified classes relative to GD like the OP describes. It is generally seen as a 'heavier' tool than GD. However, if you're doing something that ImageMagick supports directly and GD does not, your code will be more concise (and often achieve better results) with ImageMagick. If your goal is truly a simpler or lighter-weight package, look into libvips. It is minimal but has greatly increased performance and reduced memory demands.
Answer: You can use a wrapper library like wideimage, which simplifies the interface to GD.
Answer: There is another project that aims to simplify GD called PHP Image Magician that I'd recommend.

PHP Library similar to GD


Correctness proof for algorithm to generate k bitsets of n bits (nCk)

Question: The problem is to generate all bitvectors of length n that have k bits
set. For example, generate all bitvectors of length 5 that have 3 bits
set. There are $\binom 5 3$ possible combinations, and they are:
# 1 | 0 0 1 1 1
# 2 | 0 1 0 1 1
# 3 | 0 1 1 0 1
# 4 | 0 1 1 1 0
# 5 | 1 0 0 1 1
# 6 | 1 0 1 0 1
# 7 | 1 0 1 1 0
# 8 | 1 1 0 0 1
# 9 | 1 1 0 1 0
# 10| 1 1 1 0 0

The algorithm:
Begin from the state
#1           count of position
a b c d e    positions
1 1 1 0 0    bitset
< - - - -    velocity

Where the < represents that the 1 at position a is moving leftwards.
Our arena is circular, so the leftmost 1 can wrap around to the right.
This leads to the next state
#2
a b c d e
0 1 1 0 1
- - - - <

We continue moving left peacefully.
#3
a b c d e
0 1 1 1 0
- - - < -

whoops, we have now collided with a block of 1s. Not to worry, we simply
transfer our velocity by way of collision, from the 1 at d to the 1 at b.
I denote the transfer as follows:
#3
a b c d e
0 1 1 1 0  original state
- - - < -
- < < < -  transfer of velocity
- < - - -  final state after transfer of velocity

The 1 at b proceeds along its merry way with the given velocity
#4
a b c d e
1 0 1 1 0
< - - - -

Once again, it wraps around, and suffers a collision
#5
a b c d e
0 0 1 1 1
- - - - - < (collision, transfer)
- - < < < transfer of velocity
- - < - - final state after transfer of velocity

This continues:
0 1 0 1 1  #6
- < - - -
1 0 0 1 1  #7
< - - - - (collision, transfer velocity)
< - - < <
- - - < -
1 0 1 0 1 #8
- - < - -
1 1 0 0 1 #9
- < - - - (colision, transfer velocity
< < - - <
- - - - <
1 1 0 1 0 #10
- - - < -
1 1 1 0 0 #11: wrap around to initial state

I don't have a proof of correctness. I feel like intuition might be possible, but I am not sure. Could someone help me with a proof strategy? Is this a known algorithm?
Comment: What will your algorithm produce for $1010$ ?
Answer: This will not work.  At any point in time, by the very definition of how you "transfer verlocity", you always have a contiguous (in the circular sense) block of $1$'s of length $k-1$ (or $k$).
In this example, you are lucky to get $10101$ which looks like three separate $1$s but in fact, in the circular sense, has a block of two $1$s.
However, if you try e.g. $n=6, k=3$, this method will never be able to generate $101010$.
Comment: Ah, cool :) thanks for the counter example!


Policy to upgrade OS images in Google GCE

Question: https://cloud.google.com/solutions/image-management-best-practices isn't helpful.
Should I recreate infrastructure from new images or sudo apt dist-upgrade?
Answer: If your images are Linux based the answer is: you can use sudo apt dist-upgrade.
Check https://cloud.google.com/compute/docs/images#debian for description what Google's engineers are altered in Debian.
All alterations are done via packages google-compute-engine & python-google-compute-engine those are preinstalled and available via /etc/apt/sources.list.d/google-cloud.list:
deb http://packages.cloud.google.com/apt cloud-sdk-stretch main
deb http://packages.cloud.google.com/apt google-compute-engine-stretch-stable main
deb http://packages.cloud.google.com/apt google-cloud-packages-archive-keyring-stretch main

Before dist-upgrade you need to alter /etc/apt/sources.list and /etc/apt/sources.list.d/google-cloud.list and change occurrences of stretch to buster.
With kernel updates you need to reboot VM.


Get Property Decorator's attributes assigned to related property

Question: I've discovered that I need a way to utilize these two decorators and I'm struggling how.
Basically I'm trying to do 2 things:
1. have a property on 1 class contain metadata over a dataName from one type to a dataName to another type
2. have a method in the same class that looks at that information on the property to figure out how to translate it:
crappy example:
class Data {

  @dataMap({word:'cheese', ignore:true}) //filter out
  @dataMap({word:'item', ignore:false}) //filter in
  public mapper[]

  map(){
      // get dataMap info and filter against it

      return filtered mapper array;
  }
}

//setup

const m = new Data();
m.mapper = [];
m.mapper.push("this cheese is bad");
m.mapper.push("this item is good");
const j = m.map();

Now I know this isn't the best example, because array's filter can do the job, but this is becoming a large task and mapping to many parts of the system.
I found that I'm struggling on how to write a property decorator that combines storing the metadata of DataMap, and allowing the property to be set (w/o constructor injection of mapper).
Please help (and thanks),
Kelly
Answer: I think I discovered the answer...
Prior I was using Reflect.metadata(target, props). Instead I should have used Reflect.defineMetadata(metadataKey, props, target, propertyKey).
so to add on to the example above:

interface IOptions {
  word: string;
  ignore: boolean;
}

const mkey = Symbol('mySpecialProps');

//this is the property decorator
function dataMap(options: IOptions): PropertyDecoratorType {
  return function(target: any, propertyKey: string): any {
      Reflect.defineMetadata(mkey, options, target, propertyKey);
      return target[propertyKey];
  };
}

//this is how to extract that data
function getDataMap(target: any, propertyKey: string){
  return Reflect.getMetadata(mkey, target, propertyKey);
}

After that, you would reference in the map() method getDataMap(this, 'mapper')


Statistics usage for customer event

Question: We are preparing one event for our customers and I need to count numbers we need to prepare for this event (I think my question belongs to statistics and it isn't a homework).
Inputs:

We have 26 ASCII letters (ASCII codes 65-90) from which customers choose. When somebody choose a letter, he doesn't give it back.
We have 500 playing cards (= 500 customers can compete) with three empty boxes for letters.
In one draw customer gets one letter per one draw lot
The winner is somebody who has three particular letters, e.g. "A","L","Q".

Question: How many letters we need to prepare if we have prices for 100 winners?
Comment: do you mean 'prizes' where you say 'prices'?
Answer: I think you need 1500 letters, so that all 500 can play (i.e. get 3 letters)
The 100 prizes probably doesn't matter because, I think you'll be lucky to get even 1 winner.  Assuming 58 copies of each of the 26 letters (1508 total), the probability of the first drawer winning is 58x3/1508 x 58x2/1507 x 58/1506 or about 0.00034
Depending on whether they remove any of the 3 winner letters the odds go up and down a bit for subsequent players but I don't think they change wildly.  With the above p(win), the probability of no winners at all is (1-p)^500 or about 84%.  The probability of just one is p(1-p)^499*nchoosek(500,1) or about 14%.  The probability of two winners is about 1%.  For 3 winners, 0.07%, and for 4, 0.003%.  The probability of 100 winners is astronomically small.
Alternatively, if after the 500th person, you started again with the 1st, then you'd probably play for months on end, with one winner about every 7th round.  700 rounds of 500 people with 3 letters would be just over 1 million letters.

Statistics usage for customer event


What is the 1-step-ahead forecast from an ARCH(1) model?

Question: Can anybody shortly show and explain how to do an 1-step-forward ARCH(1) forecast?
Answer: An ARCH(1) model with a constant conditional mean is
\begin{aligned}
y_t &= \mu + u_t, \\
u_t &= \sigma_t \varepsilon_t, \\
\sigma_t^2 &= \omega + \alpha u_{t-1}^2, \\
\varepsilon_t &\sim i.i.d(0,1) \\
\end{aligned}
where $d$ is some distribution, e.g. Normal.
It gives you the conditional distribution of $y_t$ (the current value of $y$) conditioned on $y_{t-1}$ (the previous value of $y$):
$$
y_t \sim d(\mu,\omega + \alpha u_{t-1}^2).
$$
You can move one step ahead in time to get the conditional distribution of $y_{t+1}$ (the next period's value of $y$) based on $y_t$ (the current value of $y$):
$$
y_{t+1} \sim d(\mu,\omega + \alpha u_t^2).
$$
From this you can tell, for example, that an optimal point forecast of $y_{t+1}$ under square loss is $\hat y_{t+1} = \hat\mu$ where $\hat\mu$ is an estimate of $\mu$. Also, the forecast of the conditional variance $\sigma_{t+1}^2$ is $\hat\sigma_{t+1}^2 = \hat\omega + \hat\alpha\hat\sigma_t^2$ where again $\hat\omega$, $\hat\alpha$ and $\hat\sigma_t^2$ denote estimates of $\omega$, $\alpha$ and $\sigma_t^2$, respectively.

In R, you can use the "rugarch" package for forecasting with an ARCH(1) model.
You (1) specify the model, (2) fit it to the data, and (3) forecast as follows:
<code>library(rugarch)               # load the "rugarch" package
set.seed(1); x = rnorm(1000)   # generate an example time series
spec = ugarchspec(variance.model = list(garchOrder = c(0,1))) # specify the model
fit = ugarchfit(data = x, spec = spec)                        # fit the model
fcst = ugarchforecast(fitORspec = fit, n.ahead = 1)           # generate the forecast
print(fcst)                    # forecast object
print(fcst@forecast$seriesFor) # point forecast
print(fcst@forecast$sigmaFor)  # forecast of the conditional variance
</code>