Unitary representation of $SL(2,\mathbb R)$

Question: I am interested in understanding the proof the there is no unitary finite dimensional representation of $SL(2,\mathbb R)$ from Knapp's book. But the argument is hard to follow after some time. I have come up with the following argument. I want to know if it is correct.
Take the Cartan decomposition $\mathfrak{sl}(2,\mathbb R)$ as $\mathfrak f \oplus \mathfrak p$ where $\mathfrak f$ and $\mathfrak p$ consist off skew-Hermitian and Hermitian matrices. If $\Phi:SL(2,\mathbb R)\to GL(V)$ is finte dimensional unitary representation, then the diffenential $d\Phi$ is a Lie algebra homomorphism. Furthermore as $\mathfrak{su}(2)=\mathfrak f\oplus i\mathfrak p$, $d\Phi$ induces a representation of $\mathfrak{su}(2)$ as $\phi(X\oplus iY)=d\Phi(X)\oplus id\Phi(Y).$ As $SU(2)$ is simply connected and connected we can have a representation $\Psi:SU(2)\to GL(V)$ with $d\Psi=\phi$ and $\Psi$ is unitary. Therefore, $\Psi(g)^*=\Psi(g^{-1})=\Psi(g^*)$ for all $g\in SU(2).$ Therefore, we must have $\phi(X)^*=\phi(-X)=\phi(X^*)$ for all $X\in\mathfrak{su}(2).$ Hence for $X=X^*$ we have $\phi(X)=0.$ Therefore, $d\Phi(\mathfrak p)=0.$ Since $[\mathfrak f,\mathfrak p]=\mathfrak{sl}(2,\mathbb R)$ we must have $d\Phi=0.$ Hence $\Phi$ is trivial. But I am afraid that I have not used anywhere that $\Phi$ is unitary!! Where did my argument go wrong?
Comment: I don't understand why we must have $\phi(X)=0$ for **all** $X$.
Answer: The problem about your argument is being unitary for a representation just requires that some Hermitian inner product is preserved. Usually this is not a big deal, since there is only one such inner product on a finite dimensional vector space up to isomorphism. Hence, up to conjugation, you can always assume that a fixed inner product is preserved. This does not work any more if two groups are involved. You start with a unitary representation of $SL(2,\mathbb R)$ on $V$, so implicitly,you fix an inner product. Then you construct a representation of $SU(2)$ (which actually would not be necessary, you could stay at the level of Lie algebras right away). But when you say that that representation of $SU(2)$ is unitary, then this does certainly not mean that it preserves the given inner product. (This gets hidden even more, since you don't use an inner product explicitly but only the $*$ operation on matrices - which has the inner product in its definition.) Your line of argument probably can be made to work but I think this gets pretty complicated and might need classification of representations.
There is a simple argument based on conjugacy classes as follows: Suppose that $\Phi:SL(2,\mathbb R)\to U(N)$ is a (continuous) homomorphism. Then look at the matrices $A_t:=\begin{pmatrix} 1 & t \\ 0 & 1\end{pmatrix}$. For $t\neq 0$ they all have the same Jordan normal form (namely the matrix for $t=1$). On the other hand,   for $t\to 0$, they tend to the identity map. The first statement means that there is $B_t\in SL(2,\mathbb R)$ such that $A_t=B_tA_1B_t^{-1}$ and hence $\Phi(A_t)=\Phi(B_t)\Phi(A_1)\Phi(B_t)^{-1}$. Now consider the conjugacy class $C:=\{U\Phi(A_1)U^{-1}:U\in U(N)\}$\subset U(N). This is a continuous image of $U(N)$ and thus compact and hence a closed subset. By continuity of $\Phi$,  $\mathbb I=\Phi(A_0)$ is the limit for $t\to 0$ of $\Phi(A_t)$. We conclud that $\mathbb I\in C$, so $\mathbb I=U\Phi(A_1)U^{-1}$ for some $U\in U(N)$. This implies $\Phi(A_1)=\mathbb I$ and hence $\Phi(A_t)=\mathbb I$ for all $t$. Differentiating, you see that $\phi=\Phi'$ vanishes on $\begin{pmatrix} 0 & 1 \\ 0 & 0\end{pmatrix}$, which easily implies that $\phi=0$.


Why is my array not populating with successfully obtained information from my for-loop?

Question: I have a dateArray that collects an array of Integer arrays, for example: [[24,4,2016], [29,4,2016], [23, 4, 2016]]. I am essentially trying to pull hard coded data into this array. I am successfully obtaining it in the first print function but then the array is not populating. So my console outputs the following:
[24, 4, 2016]
nil
[29, 4, 2016]
nil
[20, 4, 2016]
nil
[14, 4, 2016]
nil. So there is an issue in filling the array - any clues?
<code>var dateArray: [[Int]]?

 override func viewDidAppear(animated: Bool) {

    dateArray?.removeAll(keepCapacity: true)

    for object in newentry.diaryArray {

        print(object["date"] as! [Int])
        dateArray?.append(object["date"] as! [Int])
         print(dateArray)
    }

}
</code>
Comment: I am not sure about Swift, but I think you should initialize your dateArray. Can you tell me if that works?
Answer: You need to initialize the dateArray, then you can add your data to your Array.


Como buscar um ficheiro a um servidor interno?

Question: Eu tenho um servidor a correr em casa, onde guardo alguns ficheiros. Eu queria ter na minha página, que está num servidor externo, uma forma de ir buscar esses ficheiro. Alguém sabe como posso fazer isso em PHP?
Comment: Veja se isto lhe ajuda: http://www.revistaphp.com.br/artigo.php?id=48
Comment: Que tipo de software roda neste seu servidor local?
Comment: @AndréRibeiro Ubuntu server
Answer: Neste caso específico iria talvez por utilizar soluções já existentes como por exemplo o OwnCloud.
Este dispõe de uma característica que dá pelo nome de External storage support e com ele podes referenciar ficheiros alojados em outros pontos como por exemplo:
<code>Local
Amazon S3
Dropbox
FTP
Google Drive
OpenStack Object Storage
SMB/CIFS
ownCloud/WebDAV
SFTP
iRODS
</code>
Para o OwnCloud externo chegar ao servidor de casa pode ser por FTP se não for solução instalar também o OwnCloud no servidor de casa. Se for possível, então ficará mais fácil. Analisa!
Dito isto, e com PHP como solicita a pergunta? O script ao ser executado no servidor externo poderá com o CURL obter uma lista por directório a cada click. Com a lista virá os links aos mesmos.
Para colocar alguma segurança, cria uma estrutura para uma API e com OAUTH autoriza os acessos. Um pouco de trabalho, mas não será difícil de fazer pois estamos a falar de um serviço online para uso pessoal onde a exigência não será certamente muita.


When is a divisible group a power of the multiplicative group of an algebraically closed field?

Question: It is known that for any algebraically closed field $\mathbb{F}$ its multiplicative group $\mathbb{F}^*$ is a divisible group, and consequently any power $\mathbb{F}^*\times\cdots\times \mathbb{F}^*.$
Now if we have an abelian divisible group $G,$ i would like to know under which conditions $G$ is a power of some algebraically closed field.
Thanks.
Comment: One necessary condition is that the $m$-torsion of $G$ has to be isomorphic to $C_m^k$, where $k$ is independent of $m$.
Answer: $\newcommand{\tors}{\operatorname{tors}}$
It is possible to completely describe the structure of the multiplicative group of an algebraically closed field $F$.  (It is funny that you mention this now, since over the last few weeks I've been writing up a proof of the corresponding structure theorem for the group of $F$-rational points on an(y) abelian variety over an algebraically closed field.)
For every divisible commutative group $G$, the torsion subgroup $G[\tors]$ is again divisible, hence an injective $\mathbb{Z}$-module (by Baer's Criterion), hence is it a direct summand of $G$.  That is, $G = G[\tors] \times V$ for some subgroup $V$.   $V$ is divisible and torsionfree, and it follows that it is a $\mathbb{Q}$-vector space.  Thus when $G = F^{\times}$ for an algebraically closed field $F$ I need to tell you the structure of $G[\tors]$ and the dimension of $V$.
The torsion subgroup of $F^{\times}$ is just the subgroup of roots of unity.  So if $F$ has characteristic $0$, this is the direct limit of cyclic groups of order $n$ for all $n$, namely $\mathbb{Q}/\mathbb{Z} = \bigoplus_{\ell} \mathbb{Q}_{\ell}/\mathbb{Z}_{\ell}$.  If $F$ has characteristic $p > 0$ then there are no nontrivial $p$-power roots of unity, so the answer is $\bigoplus_{\ell \neq p} \mathbb{Q}_{\ell}/\mathbb{Z}_{\ell}$.
On to the torsionfree part $V$.  If $F$ is algebraic over a finite field then it is simply the union of its finite subfields, so there is no torsionfree part: $V = 0$.  So now assume that $F$ is not algebraic over a finite field.  I claim that in this case
$\dim V = \# F$.  First note that in all cases we have $\dim V \leq \# F$.  Now:
Case 1: Suppose $F$ has characteristic $0$ and $\# F = \aleph_0$.   Then $F \supset \mathbb{Q}$ so $F^{\times} \supset \mathbb{Q}^{\times} \cong \{ \pm 1\} \times \bigoplus_{p} \mathbb{Z}$.  Here the sum extends over all prime numbers and comes from unique factorization in $\mathbb{Z}$.  This shows that $\dim V \geq \aleph_0$.
Case 2: Suppose $F$ has characteristic $p > 0$, is not algebraic over $\mathbb{F}_p$, and $\# F = \aleph_0$.  Then there is a transcendental element $t \in F$, so $F^{\times} \supset \mathbb{F}_p[t]^{\times} \cong \mathbb{Z}/(p-1)\mathbb{Z} \times \bigoplus_{P} \mathbb{Z}$.  Here the sum extends over all monic irreducible polynomials and comes from unique factorization in $\mathbb{F}_p[t]$.  This shows that $\dim V \geq \aleph_0$.
[In these two cases I am using the fact that the quantity $\dim V$ I'm trying to compute is also $\dim_{\mathbb{Q}} F^{\times} \otimes_{\mathbb{Z}} \mathbb{Q}$.  For any commutative group $G$, let $r(G) = \dim_{\mathbb{Q}} G \otimes_{\mathbb{Z}} \mathbb{Q}$.  Then if $G_1 \subset G_2$ are commutative groups, since $\mathbb{Q}$ is a flat $\mathbb{Z}$-module, $r(G_1) \leq r(G_2)$.]
Case 3: Suppose $\# F > \aleph_0$.  Then cardinality considerations show that $\# V = \# F^{\times}$, and a $\mathbb{Q}$-vector space of uncountable cardinality has dimension equal to its cardinality.  We're done.
Finally, you ask about finite powers, but you can see that the structure there follows immediately form the complete knowledge of the structure for just one factor.  E.g. in characteristic $0$ we get
$\bigoplus_{i=1}^n F^{\times} \cong (\mathbb{Q}/\mathbb{Z})^n \oplus V$,
where $\dim V = \# F$.
I remark in passing that the result for $A(F)$ for $A$ a $g$-dimensional abelian variety is almost the same: the only thing that changes is the structure of the torsion subgroup, which is now $(\mathbb{Q}/\mathbb{Z})^{2g}$ in characteristic $0$ and $(\prod_{\ell \neq p} \mathbb{Q}_{\ell}/\mathbb{Z}_{\ell})^{2g} \times (\mathbb{Q}_p/\mathbb{Z}_p)^a$ for some $0 \leq a \leq g$ in characteristic $p > 0$.  However, the proof is harder.  I found a proof using Hilbertian subfields and group theory before* learning that two other proofs of equivalent statements appear in the literature; the first is a 1973 paper of Michael Rosen which contains a very elegant proof.
[*This cannot be completely accurate, since this 2009 paper of mine not only cites Rosen's 1973 paper but includes other results from it, enough to convince me that I must have read the paper in 2008 and thus seen Rosen's result.  But then several years passed before I took up this subject again, and I forgot that Rosen's paper gives a proof and came up with a different proof of my own.]
Comment: Thanks a lot professor Clark.
Comment: You're quite welcome.
Comment: Very nice! This was thoroughly enjoyable to read!
Answer: Just want to mention that there is some new work done in the $k$ not being algebraically closed case. The paper is published in Journal of Algebra this year.
Answer: Greg Oman  in "divisible multiplicative groups of fields" obtained necessary and sufficient condition  for when a divisible group is isomorphic to  multiplicative group of a field. We can obtain two fields with isomorphic multiplicative groups such that one of them is absolutely algebraic field and another one is not.


Ensure argument is an output stream for the console

Question: I'm trying to make a stream manipulator for colour for use with output to the console. It works, changing the colour of text and the background:
std::cout << ConColor::Color::FgBlue << 123 << "abc"; //text is blue, sticky

The problem is with the signature:
std::ostream &FgBlue(std::ostream &);

This signature allows for derived classes, such as std::ostringstream as well, but there is no way to change the colour of a string stream. The function would change the colour of the console regardless if it was called with such an argument.
Therefore, I want to ensure the argument is something along the lines of std::cout, std::wcout, etc. I would prefer it be general in the case that more std::ostream objects are added in a future standard.
I tried many things involving std::is_same and std::is_base_of, when the former wouldn't work, just to eventually realize that it was pointless because any argument type inheriting from std::basic_ostream<> will be casted to the type I'm comparing against when passed to the function, giving false positives.
This eventually led me to my answer below (variadic template template arguments? Wow, that's a mouthful!) There are a couple problems, however:

The compiler must support variadic templates. I would prefer the solution work on MSVC.
The compiler gives cryptic errors in the case that a derived class with a different number of template arguments (such as std::ostringstream, which has 3 instead of 2) is used, as it doesn't get past the function signature.
It's possible to redirect stdout, say, to a file, so even if the argument is std::cout, the same thing as the stringstream case happens.

I encourage people to post any other solutions, hopefully better than mine, and really hopefully something that works with at least VS11.
Answer: This is what I came up with after a lot of trial:
template<template<typename...> class T, typename... U>
void foo(T &os) {
    static_assert(
        std::is_same<
            std::basic_ostream,
            typename std::remove_reference<decltype(os)>::type
        >::value,
        "Argument must be of type std::basic_ostream<T, U>."
    );
    //...
}

Source code containing each of the below tests can be found here.
Source code replacing the types with similar self-made ones that are more explicit and offer more freedom (e.g., instantiation), which might be more useful for testing, can be found here.

Passing in std::cout and std::wcout makes it compile fine.
Passing in an instance of std::ostringstream causes it to complain about the number of template arguments.
Passing in an instance of std::fstream, which has the same number of template parameters, causes the static assertion to fail.
Passing in a self-made 2-parameter template class causes the static assertion to fail.

Please feel free to improve upon this any way you can.
Comment: Yes, nevermind, I checked the links and saw you don't use it as manipulator. Anyway, the compilation succeeds with non-console `std::ostream`: [LWS](http://liveworkspace.org/code/5c18ba3b03adec80676083b891c58156)
Comment: @jrok, Huh, I thought you couldn't create `std::ostream` objects, but apparently you can indirectly, so I guess not all objects of `std::ostream` can be assumed to be tied with the console. For what I'd use it for, it's probably fine, but that's a welcome improvement.
Answer: Here's a trait for detecting std::basic_ostream instantiations:
template<typename T> struct is_basic_ostream {
  template<typename U, typename V>
  static char (&impl(std::basic_ostream *))[
    std::is_same<T, std::basic_ostream>::value ? 2 : 1];
  static char impl(...);
  static constexpr bool value = sizeof(impl((T *)0)) == 2;
};

Use as:
template<typename T>
void foo(T &) {
  static_assert(is_basic_ostream<T>::value,
    "Argument must be of type std::basic_ostream<T, U>.");
}

We use template argument deduction to infer the template parameters on the (non-proper) basic_ostream base class, if any.  As a more general solution, replacing U and V with a single variadic parameter would allow writing a generic is_instantiation_of trait on compilers that support variadic template parameters.

To detect whether stdout is piped to a file (which can only be detected at runtime, of course) use isatty; see how to use isatty() on cout, or can I assume that cout == file descriptor 1?
Comment: Good thinking. Thanks for the `isatty` tip as well, and a big thanks for removing the variadic templates. I've not once seen variadic template template arguments used (if they're called that), and probably for good reason. I'm sure there's a decently easy Windows way of checking if stdout is CONOUT$ or something like that that can be used in conjunction with #ifdef if it goes cross-platform.


Correct definition of number of parameters $K$ in Akaike Information Criterion

Question: What is the term $K$ in Akaike information criterion?
The AIC is defined as $2K-2log(L)$, where $L$ is the maximized value of the likelihood function for the estimated model.
On the internet, I found three competing candidates:

Number of parameters + error term (for simple linear one-predictor model, intercept, slope and error term: $K=3$)
Number of parameters (for the linear one-predictor model, intercept and slope: $K=2$)
Number of predictors (for the linear one-predictor model, the slope: $K=1$)

Which one is correct and why?
Answer: This is how the original 1974 paper by Hirotugu Akaike defines the AIC:

AIC = (-2)log(maximum likelihood) + 2(number of independently adjusted parameters within the model)

The error term is not a parameter which you're independently trying to adjust, but the intercept is (e.g. your slope might be zero and the data best fit by a horizontal line). The correct answer for your simple univariate regression is $K=2$ (intercept and slope).
Comment: "The error term is not a parameter which you're independently trying to adjust, but the intercept is (e.g. your data might best be fit by a horizontal line)." I think you mean "...fit by a line through the origin," since omitting the intercept term constrains the intercept to be zero, but yields a line with slope $\beta$.
Comment: The point I was trying to make was that the intercept *is* an independently adjusted parameter. That is, you could have a slope of zero, and an intercept of, say, one. This would draw a straight line through the data. Or you can start with a slope $\beta$ and then adjust the intercept until you get the best fit. The point is that the intercept should be counted.
Comment: I agree that the intercept is an independently-adjusted parameter. The sentence seems to indicate that the intercept parameter determines whether or not the line is horizontal, which is not the case.
Comment: Thanks for the quick answer. I was just wondering whether we must add a variance component to the estimated parameters (the first one above with error term perhaps implies that), bacause it has been counted in in some cases e.g.  http://www4.ncsu.edu/~shu3/Presentation/AIC.pdf
http://stats.stackexchange.com/questions/67786/aic-number-of-parameters
Comment: So in the multivariate case, would we increment K by 1 for each column/attribute added to the regression model, after the initial one? This is a great answer, but I want to make sure I understand it clearly; asking a separate question would probably qualify as a duplicate.


Admob in android. How to make it appear and disappear

Question: I am new to programming in android. I have followed instruction and create a admob banner. How can I make it appear at certain intervals, and make it disappear if I want to? For example the admob banner can goes up and down at the bottom of the screen whenever it wants to.
Thanks.
Edit:
I know that i can call adView.setVisibility( View.GONE ); to make the ads appear and disappear, but when i try to write it into a thread to make it appear and disappear with intervals, it just hangs there with a black screen.
Or is there anyway that admob can make their ad appear and disappear at intervals?
This is how i call the thread.
loadAdmob = new asyncAdmobProc();
loadAdmob.execute();
loadAdmob.doInBackground();//asyncAdmobProc();

The code:
//wakes up the admob
private class asyncAdmobProc extends AsyncTask<Integer , Void, Integer> {

    private boolean bconthread=true;
    protected Integer doInBackground(Integer... Params) {
        //wakes up and disable admob

        /*AdManager.setTestDevices( new String[] {
                AdManager.TEST_EMULATOR, // Android emulator
                "E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
                } );//*/

        adView = (AdView)findViewById(R.id.articleList_ads);
        adView.requestFreshAd();
        adView.setVisibility( View.GONE );

        //while(bconthread){
            adView.requestFreshAd();
            ShowAd();

            postDelayed();

            //HideAd();

            postDelayed();

        //}

        //call this to delete all bitmaps associated with the ad
        adView.cleanup();
        return 0;
    }
    private void HideAd()
    {
        // Hide the ad.
        adView.setVisibility( View.GONE );

        // Fade the ad in over 4/10 of a second.
        AlphaAnimation animation = new AlphaAnimation( 0.0f, 1.0f );
        animation.setDuration( 400 );
        animation.setFillAfter( true );
        animation.setInterpolator( new AccelerateInterpolator() );
        adView.startAnimation( animation );//*/

    }
    private void ShowAd()
    {
        // Unhide the ad.
        adView.setVisibility( View.VISIBLE );

        // Fade the ad in over 4/10 of a second.
        AlphaAnimation animation = new AlphaAnimation( 0.0f, 1.0f );
        animation.setDuration( 400 );
        animation.setFillAfter( true );
        animation.setInterpolator( new AccelerateInterpolator() );
        adView.startAnimation( animation );//*/
    }
}

Answer:
You don't have to call AsyncTask.doInBackground, this method will be called by AsyncTask itself.
AsyncTask.doInBackground is called in other thread instead of UI thread, you may not want to start an animation in it, that will cause some problems on UI.
There are lots of ways that you can make the view appear and disappear with intervals, using AsyncTask is not one of them, I think. Following is sample code which use Handler to archive this.

    public MyActivity extends Activity {

        private static final int SHOW = 1;
        private static final int HIDE = -1;

        private View adView;

        private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                adView.setVisibility(msg.what);
            }
        }

        private void startTriggerThread() {
            new Thread() {
                boolean show = false;
                public void run() {
                    while (true) {
                        if (show) {
                            handler.sendEmptyMessage(View.GONE);
                        } else {
                            handler.sendEmptyMessage(View.VISIBLE);
                        }
                        show = !show;
                        try {
                            Thread.sleep(INTERVALS);
                        }
                        catch (InterruptException e) {
                            // Ignore.
                        }
                    }
                }
            }.start();
        }

        // Other methods
    }


Can I force users to join a group when registering?

Question: I would like everyone to be a member of "our Community" by default.
I want everyone to be a member of a site-wide group so that we can have a site-wide wiki, events & all the other usual group stuff.
Do I miss the point? Is this already the case, or do I not really want what I think that I want?
Answer: I am not sure, but if Organic Groups has rules integration; you might be able to create a Rule which automatically adds the user to the desired group.
Answer: Well, you could code it, but it's kind of a cheesy solution.  Assuming you have a group called "My Group" you want everyone to join, you could write some code and embed it on a page that everyone hits.  As soon as they land on it, they get added to the group automatically.  PHP/Drupal code might look something like this (Drupal 7 example):
//get the user's id
global $user;
$uid=$user->uid;

//get the group's GroupID
$result=db_query("SELECT gid FROM og WHERE `label`=:groupName",array(':groupName'=>'My Group'));
$row=$result->fetchAssoc();
extract($row);

//check and see if the user is a member of the group already
$result=db_query("SELECT COUNT(id) AS og_count FROM og_membership WHERE etid=:uid AND gid=:gid",array(':uid'=>$uid,':gid'=>$gid));
$row=$result->fetchAssoc();
extract($row);
if($og_count==0 && $uid!=0)
  {
  $result=db_insert('og_membership')
  ->fields
    (
    array
      (
      'name'=>'og_membership_type_default',
      'etid'=>$uid,
      'entity_type'=>'user',
      'gid'=>$gid,
      'state'=>1,
      'created'=>time(),
      )
    )
  ->execute();
  }

This is not the preferred way to do it, but in a pinch you could add this code to a heavy traffic page and pretty much ensure your users get added.  The down side is that you are doing an extra database dip or two to ensure your users are added to a specific group.  Not very efficient, but it would likely do what you want.
As a caveat, this is based on what I know from playing around with Organic Groups.  This code is from the top of my head, so there may be a parsing error here or there - be sure to check it out first.  Also, this is direct dipping into og's table structure, which is frowned upon, as og could change their table structure in the future, during a code update...
Answer: I think you could use the Organic Groups - Multiple Mandatory Groups by Role module.

The goal of this module was to extend the capabilities of the original
  og_mandatory_group module to allow as many mandatory groups as the user wants for:

All users
Group administrators/owners
any role

As all of the changes constitute a module with drastically different capabilities, it didn't make sense to patch the original module with this code. Additionally, most of the old code was thrown out and a ton of new code put in place.
Answer: Use the Rules module. After a user registers, run PHP code that would add that newly registered member to a group. Then add a call to drupal_set_message(), notifying them that they are automatically member of a group.
Answer: In organic groups module you can set the "user: group audience field" to required and "show on registration page" in combination with the "show all groups" setting. That will force the user to select a group from the list when signing up.
I've only tested this in Drupal 7 but I'm pretty sure Commons uses organic groups as well.
Answer: I don't see any options such as Organic Groups offers.
The best that I could do is add some text to the registration guidelines and welcome email strongly recommending to join the group "Our Community".
I also made it a "featured group" so that it will appear on the front page.
Aha! If I (log in as admin and) edit the group, I see the option "Registration form
May users join this group during registration? If checked, a corresponding checkbox will be added to the registration form" ... but that still doesn't enforce membership :-(
Answer: what I found was this:
If you have one public group and all the rest are private groups, new members are added to the public group by default. May not help everyone but it solved the issue very easily for my use case.
I believe it is also necessary to edit the Group content type - Group Audience and/or - Group visibility fields and check the "required" box
Sean :)
Answer: You can do this programmatically.
Write a custom module that implements hook_user_insert.
In hook_user_insert, call og_group, which subscribes an entity to a group. So your .module file looks something like this:
/**
 * Implements hook_user_insert().
 */
function mymodule_user_insert($edit, $account, $category) {
  $values = array(
    'entity_type' => 'user',
    'entity' => $account->uid,
    'field_name' => 'field_group', // Must be the name of the field in user that references groups
  );

  og_group(group_type, group_id, $values); // replace group_type and group_id with the entity type of the group and its group id
}


Empty  items within Rules UI

Question:
Has anyone encountered behaviour similar to this and have any idea how to resolve it? I've checked the issues for Rules and can't find anything similar. I've run update.php and flushed caches, neither make a difference. Also tried completely uninstalling Rules and Rules UI and reinstalling from fresh.
Answer: This is odd, but it's probably not rules-centric.  It looks like the system itself is in a funky state.  Have you had any other problems with white screens?  Do your mysql logs show any errors (I have seen similar problems when the max_allowed_packet size was too small, for example, or when the mysql server ran out of disk space.)

Empty  items within Rules UI


Where do I find the @Guice Annotation

Question: I just learned about the @Guice Annotation. It might be a good exchange for the custom GuiceTestRunner I built.
Where can I find it? Its not in my classpath ...
Thanks
EDIT: Maybe I wasn't precise enough: I use ivy, and I have guice, guice-servlet, guice-assistedinject, guice-throwingproviders in my dependencies (and in my classpath). "Guice" is the class I use to createInjectors.
I dont see the @Guice(modules=....) Annotation mentioned in the referenced Question. So I wonder: where does the Annotation come from?
Answer: The complete class Name is org.testng.annotations.Guice, and it's available in testng 6.3
The maven dependency is =>
<code>    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <scope>test</scope>
        <version>6.3</version>
    </dependency>
</code>
Comment: Correct, it's a TestNG feature to make integration of TestNG and Guice easier. Upvoted.
Comment: Thank you very much. I was on the wrong trail, searching it in the guice-extensions directly. Certainly will give it a try.
Answer: If you're not using Maven or Ivy or one of the other automated dependency management tools (if you were, you wouldn't be asking this question) you should try the relevant project's download page.
Comment: Seriously, did you even try using Google?
Comment: Enlighten me! Google "@Guice Annotation" ... I am not looking for Guice, but @Guice

Where do I find the @Guice Annotation


Given $abc(a+b+c)=3$ prove $(a+b)(b+c)(c+a)>8$

Question: This is an exceptionally strange question. I have tried with all the methods I know. There is an equality which comes pretty close $(a+b)(b+c)(c+a)>8abc$. Please help me!!
Comment: What is the nature of $a,b,c?$
Answer: $a,b,c$ are positive numbers? If not, this inequality is not true, for example
$$a=b=-1,c=3.$$
So in the following we assume that $a,b,c>0$,and we can now use this inequality:
$$(a+b)(b+c)(a+c)\ge\dfrac{8}{9}(a+b+c)(ab+bc+ac)\ge\dfrac{8}{9}(a+b+c)\cdot 3\sqrt[3]{a^2b^2c^2}\ge\dfrac{8}{3}(a+b+c)abc=8$$
because:
$$3=(a+b+c)abc\ge 3(abc)^{\frac{4}{3}}\Longrightarrow abc\le 1$$
so:
$$\sqrt[3]{a^2b^2c^2}\ge abc$$


Why does my jqueryui modal form close when I execute this code?

Question: When I execute this code, my jqueryui modal form closes.  Why does it do this?

$(document).ready(function() {
  $('#mylink').click(function(){
   $('#textfield').val = '';
 });
});

mylink is defined like this:
My Link
Answer: Try $('#textfield).val('');
That's normally how you set the value.
Comment: You're href is not good too, try href="#". And try also to return false from your click function.
Comment: I tried this and the dialog still closes.  The link should only clear the text field for the user.
Answer: you need to return false in the click function to prevent the page from posting back


interpreting coefficients with binary dependent and independent variables

Question: Say the logistic regression is where I have $Y_{i}$ as dependent and $D_{i}$  as independent with coefficient beta.
Then how do I interpret beta when both my $Y_{i}$ and $D_{i}$ are binary? I say this because usually while interpreting, the authors of papers, multiply beta   by 100. So say beta is 0.045 , then is it correct to say that when D goes from 0 to 1 then Y increases by 0.045 units in layman language? What is the rationale for giving it a percent interpretation here? Because Y is going from say 0 to 0.045?
Comment: See also: [Interpretation of R's output for binomial regression](http://stats.stackexchange.com/q/86351/7290).
Answer: The beta coefficients reported in tables of logistic regression models are usually log odds, also known as the logit. The logit model can be written as
$$ \ln\left\{\frac{\text{Pr}(y=1|\text{x})}{\text{Pr}(y=0|\text{x})}\right\}=\ln\Omega(\text{x})=\beta_0+\beta_1x$$
for binary dependent and independent variable. The interpretation of coefficient ($\beta_1$) is similar to that of, let's say, simple linear regression, but the unit of the dependent variable is log odds (logit). So, we can simply interpret it as "for a unit change (let's say, if your independent variable is binary, from 0 to 1) in $x$, log odds of the outcome is expected to change by $\beta_1$ units" (if there would be other independent variables, we would add "holding other variables constant"). But as it has been noted in various sources, the interpretation of the logit might not be intuitive for the audience. In this case, the logit coefficients are transformed into odds. This has been accomplished by exponentiating both sides of the equation:
$$\Omega(\text{x})=e^{\beta_0}e^{\beta{_1}{x}}$$
As a result of this transformation, our model becomes multiplicative and the interpretation of the coefficient changes: "for a unit change in $x$, the odds of the outcome are expected to change by a factor of exp($\beta_1$)." To make the interpretation of the odds easier, it can be reported as a percentage change, using a simple formula: $ \% \Delta=(e^{\beta_1}-1)*100$. I think this is the source of confusion. After using this formula the interpretation becomes: "for a unit change in $x$, the odds of the outcome are expected to change by $[(e^{\beta_1}-1)*100]$%." That is why in some tables in addition to $\beta$'s, $\text{exp}(\beta)$'s are reported as well. So I guess, in those papers you are referring to, they multiply $\text{exp}(\beta)$ by 100 after subtracting 1, not the beta coefficient (log odds/logit).
I recommend Pampel's book (2000) as a short and simple introduction to logistic regression. It explains logits, odds, and predicted probabilities nicely.

Pampel, F. C. (2000). Logistic Regression: A Primer. Thousand Oaks London New Delhi: Sage Publications.


Is possible to convert multiple if  into an array?

Question: Code like this
def IsEven(n):
    if n%2==0:
        return "Is even"
    else:
        return "Is odd"

can be converted to a function like this
def isEven(n):
    return ["Is even","Is odd"][n%2==0]

The question is if code like this:
def intervalsToOutput(n):
    intervals=[(x1,x2), (x3,x4), (x5,x6), ... (xn,xn+1)]
    if x1<=n<=x2:
        return "in first interval"
    elif x3<=n<=x4:
        return "in second interval"
    elif x5<=n<=x6:
        return "in third interval"
    ...
    elif xn<=n<=xn+1:
        return "in last interval"

... can be replaced efficiently with a function like this:
(assuming the intervals (xi,xi+1) are not overlapping, and are sorted by xi)
def intervalsToOutput(n):
    intervals=[(x1,x2), (x3,x4), (x5,x6), ... (xn,xn+1)]
    answer=["in first interval","in second interval","in third interval",...,"in last interval"]
    return answer[index of (n in Interval)]

The best I made (looking for speed) is
def intervalsToOutput(n):
    intervals=[(x1,x2), (x3,x4), (x5,x6), ... (xn,xn+1)]
    answer=["in first interval","in second interval","in third interval",...,"in last interval"]
    import bisect as bisect
    return answer[bisect.bisect_left(intervals, (n, )) - 1]# -1 because it is a zero based list

What bisect_left does is to find the position of n in intervals (in O(log(n)) time) by comparing (n,) with (xn,xn+1)
But the purpose of bisect is to find the insertion place, so it fails for any n which is x_{i+1}<n<=x_{j}
... (x_i, x_{i+1}),   (x_j, x_{j+1}) ...
[x_i______x_i+1]   fails on this interval  x_j [________x_j+1]

EDIT:
This is a solution using intervaltree instead of bisect, but it has some overhead, because intervaltree returns a set, which may be empty
(I also accept faster/more elegant solutions based on this code)
#generate intervals and answers
import random
min=0
max=20
numIntervals=6

def Intervals(min,max,n):
    randInts = random.sample(range(min, max), n * 2)
    randInts.sort()
    return [(x1,x2) for x1,x2 in zip(randInts[::2], randInts[1::2])]

intervals=Intervals(min,max,numIntervals)
answer=[f"In {n}th interval" for n in range(len(intervals))]

#Implement solution

import intervaltree

tree = intervaltree.IntervalTree()
[tree.addi(i[0],i[1],a) for i,a in zip(intervals,answer)]

def intervalsToOutput(x):
    answer=tree.at(x)
    if len(answer)>0:
        return answer.pop().data
    return "value not found"

print(intervals)
[print(f"{x} is ",intervalsToOutput(x)) for x in random.sample(range(min,max),numIntervals)]

Comment: Please see my edit.
Answer: Well here's one way, but don't do this (for readability, and probably performance). You should really just chain if,elif,andelse statements (or use a for loop):
def really_esoteric(n):
    return ["first", "second", "n"][
        [n in range(0,10),
         n in range(11,16),
         n in range(16,30)].index(True)
        ]

REPL:
>>> really_esoteric(5)
'first'
>>> really_esoteric(13)
'second'
>>> really_esoteric(20)
'n'

Another way of going about this:
from bisect import bisect
def search_ranges(n, intervals):
    # Get the index on an insertion
    index = bisect(intervals, (n,))

    # Get the low and high values for the interval
    lower_low, lower_high = intervals[index - 1]
    upper_low, upper_high = intervals[index % len(intervals)]

    # Test if n is in the interval
    if n in range(lower_low, lower_high):
        return f"{n} in {intervals[index-1]}"
    elif n in range(upper_low, upper_high):
        return f"{n} in {intervals[index]}"
    else:
        return f"{n} not in an interval"

print(search_ranges(0, [(0, 10)]))
print(search_ranges(4, [(0, 10)]))
print(search_ranges(11, [(0, 10), (11,20)]))
print(search_ranges(12, [(0, 10), (15,20)]))
print(search_ranges(19, [(0, 10), (11,20)]))
print(search_ranges(11, [(0, 10), (11, 20), (21, 30)]))

Outputs:
0 in (0, 10)
4 in (0, 10)
11 in (11, 20)
12 not in an interval
19 in (11, 20)
11 in (11, 20)

Comment: it's O(n), which is the same as writing all the ifs
Comment: @Colim ah I see what you mean, one moment
Comment: @Colim There you are, O(log(n))
Comment: print(search_ranges(11, [(0, 10), (11, 20), (21, 30)])) returns "11 not in an interval"
Comment: @Colm trivial to fix just check the other side ill fix when im back at my desk
Answer: I would do this:
intervals=[(1,2),(6,8),(22,45),(101,110)]

tgt=27
idx=next(i for i,t in enumerate(intervals) if t[0]<=tgt<=t[1])

>>> idx
2

If you want to catch a not-found condition, either use try / except:
try:
   idx=next(i for i,t in enumerate(intervals) if t[0]<=tgt<=t[1])
except StopIteration:
    # not found

Or use the default form of next:
idx=next((i for i,t in enumerate(intervals) if t[0]<=tgt<=t[1]), None)

Fair point regarding this method being slow. Here is a monumentally faster way.
You can take the source of bisect and modify with custom logic to inspect each tuple in the list see if the condition of t[0] <= x <= t[1] and return None if that condition cannot be satisfied.
Given a list of tuples of this form:
[(0, 3), (5, 10), (13, 17)] ... [(69735, 69739), (69742, 69746), (69749, 69752)]

You can have a custom bisect search to find a tuple that satisfies the condition stated:
def bisect_search(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None or hi>len(a):
        hi = len(a)

    while lo < hi:
        mid = (lo + hi) // 2
        f_mid=-1 if xa[mid][-1] else 0
        if f_mid < 0:
            hi = mid
        elif f_mid > 0:
            lo = mid + 1
        else:
            return mid

    return None

Here is a benchmark for those two methods:
import random
import time

def gen_tuples(cnt, span=(1,5)):
    li=[]

    lo,hi=0,random.randint(*span)

    for _ in range(cnt):
        li.append((lo,hi))
        lo=li[-1][-1]+random.randint(*span)
        hi=lo+random.randint(span[0]+2,span[-1])

    rando=random.randint(cnt//2,cnt-1)
    to_find=li[rando][random.randint(0,len(li[rando])-1)]
    return (rando,to_find,li)

def next_(a, x):
    return next((i for i,t in enumerate(a) if t[0] <= x <=t [1]), None)

def bisect_search(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None or hi>len(a):
        hi = len(a)

    while lo < hi:
        mid = (lo + hi) // 2
        f_mid=-1 if xa[mid][-1] else 0
        if f_mid < 0:
            hi = mid
        elif f_mid > 0:
            lo = mid + 1
        else:
            return mid

    return None

def cmpthese(funcs, args=(), cnt=1000, rate=True, micro=True):
    """Generate a Perl style function benchmark"""
    def pprint_table(table):
        """Perl style table output"""
        def format_field(field, fmt='{:,.0f}'):
            if type(field) is str: return field
            if type(field) is tuple: return field[1].format(field[0])
            return fmt.format(field)

        def get_max_col_w(table, index):
            return max([len(format_field(row[index])) for row in table])

        col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
        for i,row in enumerate(table):
            # left col
            row_tab=[row[0].ljust(col_paddings[0])]
            # rest of the cols
            row_tab+=[format_field(row[j]).rjust(col_paddings[j]) for j in range(1,len(row))]
            print(' '.join(row_tab))

    results={}
    for i in range(cnt):
        for f in funcs:
            start=time.perf_counter_ns()
            f(*args)
            stop=time.perf_counter_ns()
            results.setdefault(f.__name__, []).append(stop-start)
    results={k:float(sum(v))/len(v) for k,v in results.items()}
    fastest=sorted(results,key=results.get, reverse=True)
    table=[['']]
    if rate: table[0].append('rate/sec')
    if micro: table[0].append('\u03bcsec/pass')
    table[0].extend(fastest)
    for e in fastest:
        tmp=[e]
        if rate:
            tmp.append('{:,}'.format(int(round(float(cnt)*1000000.0/results[e]))))

        if micro:
            tmp.append('{:,.1f}'.format(results[e]/float(cnt)))

        for x in fastest:
            if x==e: tmp.append('--')
            else: tmp.append('{:.1%}'.format((results[x]-results[e])/results[e]))
        table.append(tmp)

    pprint_table(table)

if __name__=='__main__':
    import sys
    print(sys.version)
    cases=(
        ('small, found', True, 100),
        ('small, not found', False, 100),
        ('large, found', True, 10000),
        ('large, not found', False, 10000)
    )
    for txt, f, cnt in cases:
        rando,to_find,li=gen_tuples(cnt)
        tgt=to_find if f else -1
        args=(li, tgt)
        f1,f2=bisect_search(*args), next_(*args)
        print(f'\n{txt}: {f1}, {f2}')
        cmpthese([next_,bisect_search], args)

Prints:
3.10.2 (main, Feb  2 2022, 06:19:27) [Clang 13.0.0 (clang-1300.0.29.3)]

small, found: 84, 84
              rate/sec μsec/pass  next_ bisect_search
next_          121,533       8.2     --        -82.0%
bisect_search  675,074       1.5 455.5%            --

small, not found: None, None
              rate/sec μsec/pass  next_ bisect_search
next_          155,885       6.4     --        -81.6%
bisect_search  847,744       1.2 443.8%            --

large, found: 8824, 8824
              rate/sec μsec/pass    next_ bisect_search
next_            1,232     811.9       --        -99.6%
bisect_search  299,677       3.3 24230.9%            --

large, not found: None, None
              rate/sec μsec/pass    next_ bisect_search
next_            1,524     656.0       --        -99.6%
bisect_search  340,112       2.9 22211.5%            --

Which shows that the bisect_search method is substantially faster.
Note: It is tempting to try and use the the key in Python 3.10 bisect to do the same thing. This is not possible since the upper end of the range of the target tuple is not known and the method of (x,) is only comparing to the bottom of the range of the target tuple.
Comment: Is faster than Intervaltree
Comment: Might make sense to use `-1` instead of `None`
Comment: But `-1` is still a valid index for the last element.
Answer: Are the intervals random? i.e. if the range is 0-10 and each there are 5 intervals (0-2)(2-4)(4-6)(6-8)(8-10)
Just do something like
def func(n):
    spacing = 2
    return n // 2

Comment: No. The intervals are sorted by the first element of the tuple, with varied length, and are non overlapping


Swiperjs. How can I pass custom props to SwiperSlide and get it onSlideChange function?

Question: I am in a different situation. I am using Swiper.js for my React app. I need to change app theme color on slide changes and it have to be dynamic. That's I need to pass some props to SwiperSlide and get this props on slide change. How can I handle that ?

    <Swiper
      id="pathway-slider"
      slidesPerView={1}
      onSlideChange={(swiper) => {
        console.log("Slide index changed to: ", swiper);
      }}
    >
      <SwiperSlide>
          Slide 1
      </SwiperSlide>

      <SwiperSlide>
          Slide 2
      </SwiperSlide>
    </Swiper>

When I console.log(swiper) it gives me huge object where I can access activeSlideIndex or etc. But how can I pass custom data to that ?
Comment: Hi did you find a solution to this. Im using typescript and I cant find any way to add additional prop to swipper core without having typescript errors
Comment: Hi, I am also using typescript. I don't know it's the right way or not but I only find solution by adding "accessKey" property.

 ...
Comment: A solution for people trying to use material ui and swipper is to wrapper the the swipper component in material styled and them pass your props through the sx={{}}  for some reason this doesn't throw a type script flag
Answer: A solution for people trying to use material UI and swiperis to wrapper the swiper component in amaterial styled componentand then pass your props through thesx={{}}for some reason this doesn't throw atypescript flag`
Import styled
import { styled } from "@mui/system";

Wrapper Swiper in styled
const StyledSwiper = styled(Swiper)(({ theme }: any) => ({
  padding: "20px 0 70px 0",
}));

Add Custom Swipper to your page or component

Comment: If it's so why don't you pass the conditional class name to SwiperSlide ?
...

  Later change your css according to that className.
Comment: So you want scale the Slider if the Slider show up on home page ?
Comment: this is just one of the use cases you can also pass it on the  component and it would be the same thing you will get typescript error.  To answer which not just use className property cause for this project we aren't using any classes directly at all we are using Mui styled and Material Styled for that whole thing an so we do want to have a class just for this small bit.
Answer: You can pass down the custom data on the SwiperSlide component as data-id and then access it from the onSlideChange event, using the dataset id. Heres an example:
The component:
 <Swiper
      onSlideChange={(e) => handleSwiperChange(e)}
     >

                          <SwiperSlide
                            data-id="your custom data"
                          >
                           1
                          </SwiperSlide>

                  </Swiper>

The handleSwiperChange function:
  const handleSwiperChange = (swiper) => {
    const activeSlide = swiper.slides[swiper.activeIndex];
    const id = activeSlide.dataset.id;
    console.log(id);
  };


Film Academy "Oscar"

Question: A committee of $3366$ film critics are voting for the Oscars. Every critic voted just an actor and just one actress. After the voting, it was found that for every positive integer $n \in \left\{1; 2; ... ; 100\right\}$, there is some actor or some actress who was voted exactly $n$ times. Prove that there are two critics who voted the same actor and the same actress.
My work so far:
All actors and actresses got together at least $5050$ votes from critics. Since $3366$ the critics, it is not less than $5050-3366 = 1684$ critics counted twice.
Comment: you have to consider how many actors and actresses there are and how many different pairs you can construct.  The rest is applying pigeonhole principle.
Answer: Source Serbian Mathematical Olympiad 2015

Assume the contrary. For each $i = 1,..., 100$ choose a candidate $A_i$ who was voted for exactly $i$ times.
The number of judges who gave both their votes for candidates in the set
$A = \{A_{34}, A_{35},..., A_{100}\}$
does not exceed the number of pairs actor-actress in $A$, and
the number of such pairs is at most $33 \cdot 34 = 1122$.
On the other hand, of the $2 \cdot 3366 = 6732$ votes, exactly
$34 + 35 +···+ 100 = 4489$
were given to the candidates in $A$.
Therefore at most $6732 − 4489 = 2243$ judges could have given a vote to a candidate not in $A$.
Thus, there were at most $1122 + 2243 = 3365$ judges, a contradiction.

Film Academy "Oscar"


Is an accidental considered off key?

Question: If you have a song with accidentals and you sing it, are you then singing off key? And if you are in the key of C major for example, and in the song a D is raised to a D# with an accidental and instead of the D# you sing a D. Does that mean that you are singing off key?
Comment: If you sing a D instead of the D# that is written then it means nothing more than that you are singing the wrong note.  The accidental, despite its name, is there on purpose.  Artistic licence brands this a [modal tune](https://en.wikipedia.org/wiki/Mode_(music)).
Comment: @J... _D#_ is not included in any of the modes of C Major. _D#_ is simply a chromatic tone - could be used as a passing tone from _D_ to _E_ - both of them diatonic to C major. D# is not _modal_.
Comment: @Stinkfoot I mean "modal" more generally (ie: moving beyond the diatonic).  The world is larger than seven greeks.
Comment: @J... IDK what modal has to do with it - modal is not the opposite of diatonic - on the contrary.  In this case, it's probably a chromatic passing tone - nothing to do with modes. Greeks or not, D# is not in any of the modes of C Major, no matter how you slice it or dice it.
Answer: 'Off key' often means 'out of tune', so if the singer is singing an accidental properly, they may well be 'in tune', but 'out of key'. The accidental D# isn't diatonic (meaning a note from the key) so it could be thought of as 'off key', but a more apposite term would be 'out of the key'.
Comment: In my experience, the phrase "off key" exclusive means "out of tune" or "off pitch". While it *could* grammatically be interpreted as referring to accidentals, I've never heard it used this way. Could be a question for the English SE if someone really wants to drill for examples / accuracy.
Comment: The words "succinct" and "concise" both mean "short", but "out of the key" is roughly twice as long as "off key" :-). Did you perhaps mean "precise" or "apt", or something like that?
Comment: @psmears - thanks for your input. Concise is still appropriate for what I wanted - it was not meant to mean 'this is shorter', merely 'this is short'. However, on reflection, it's edited. Approved now?! It's good to have things pointed out though...  Maybe I could have used 'pointed?
Comment: I like "apposite" :-)
Comment: I had to look up the definition of "apposite". It made me smile.
Comment: @skinnypeacock - I'm happy for you! It's just that it was the most *apposite* word to use...
Answer: Accidentals are used for all kinds of reasons. A D# in the key of C, alongside a B and an F#, would make a V/iii chord, for example, which is a perfectly legitimate chord in the key of C.
Or it could indicate a temporary modulation—a change of key—to E major or B major, or e minor for that matter. In that case, D# is "in key," despite what the key signature says.
Point is, accidentals aren't actually "outside the key" at all. They just indicate that something interesting is happening harmonically.
Answer: Does that mean that you are singing off key?

Your question is not quite comprehensible as stated:
As far as the singer goes, whether it's on key or off key is irrelevant. If the music says D# and you sing D , you are singing the wrong note: It's not the note the composer wanted you to sing, regardless of whether or not it's off key.
Are you simply asking about semantics? Terminology? Regardless, Off Key is not a technical term, so it's difficult to have such a discussion.
The first question to ask here boils down to your title, which I'd translate as Is D# diatonic to C Major? - meaning is it one of the notes of the C major scale. But the answer to that question simple: D# clearly is not diatonic to C Major - it's an accidental - a note outside the parameters of the key/key signature in question. You knew that before you asked the question - that's why you asked it.
So the real question is this:  Since D# is not part of the C major scale,  why is D# found in a piece of music that has the key signature of C Major? What functions might D# serve in the key of C Major?  Is it right or wrong, is it in key or off key aren't particularly relevant to anything - that's how the music is written, and so we need to deal with it.  What interests us as musicians or musical theoreticians is how would D# function in C Major - we need to understand the music we are dealing with.
To get a definitive answer to that question, we'd have to see the whole sheet, or ask the composer.
Offhand the simple explanation is that D# is serving as a chromatic passing tone between D and E. Such chromatic (non-diatonic) passing tones are extremely common - it's fair to say they're ubiquitous in virtually all genres - they add color, depth and smoothness to music.
@JohnMGant in his answer gave some other good reasons for why we might encounter D# in music with a key signature of C Major.
Answer: Every accidental indicates a modulation, or a feint towards one, otherwise, they'd be in the key signature. No one would consider a modulation "off key" or "out of the key" because it's intentional, and those refer to mistakes. In common practice tonality, almost always, if you see a sharp, it's the 7 of the key you're moving to; flats are the 4 of the key you're moving to, just as the last sharp in the key signature is the 7 of the key, the last flat is the 4 of the key.
Comment: This isn't true at all that _every_ accidental indicates a modulation. For example, in A minor you'll see a G# as the leading to to emphasize the tonic, but you'll never see it in the key signature.  Chromaitizm can also use accidentals and does not always mean you are modulating .
Comment: even in the common practice period this isn't true. It could be modulation, it could be a secondary chord (like a secondary dominant), or it could just be a chromatic embellishment like neoplatain and augmented 6th chords. And the example I gave is pure common practice period and doesn't fit what you are saying.

Is an accidental considered off key?


Atualizando do IONIC 1 para o 3: Como fazer login em JSON?

Question: Estou migrando de Ionic 1 para o 3, e quantas mudanças.
Criei minha API de login, com token:

Aqui coloco meu código de autorização para acesso a API.
E aqui o resultado em JSON:

ion-content padding id="page8" style="background-color:#050505;">

    <form>

        <ion-list>
            <ion-item>
                <ion-label floating>
                    Email
                </ion-label>
                <ion-input type="email" [(ngModel)]="usuario.email" name="email" placeholder=""></ion-input>
            </ion-item>
            <ion-item>
                <ion-label floating>
                    Senha
                </ion-label>
                <ion-input type="password" [(ngModel)]="usuario.senha" name="senha" placeholder=""></ion-input>
            </ion-item>
        </ion-list>

        <button (click)="submit()" ion-button color="stable" block>
      Entrar
    </button>
        <button ion-button color="positive" block icon-left (click)="loginWithFB()">
      <ion-icon name="facebook"></ion-icon>
      Entrar pelo Facebook
    </button>
        <button ion-button clear color="positive" block on-click="goToCriarConta()">
      Crie sua conta
    </button>

        <button ion-button clear color="positive" block>
      Esqueci a Senha
    </button>

    </form>

Até aqui, tudo bem...
Mas agora vem a atualização: Como posso passar esses parametros para a minha API e fazer o login? Estou fazendo desta forma, mas não funciona, está errada:
submit(){
    var link = 'http://localhost/rest/usuario/read_one.php';
    var data = '?email='+ JSON.stringify(this.usuario.email)  + '&senha='+ JSON.stringify(this.usuario.senha);

    this.http.get(link)
      .subscribe(data => {
       this.data.response = data._body;

       if(this.data.response != "[]"){
        var resposta = this.data.response;
        console.log(resposta);

        // tinha que pegar o ID do usuário.... :/
         sessionStorage.setItem("usuarioEmail", this.usuario.email);
         //sessionStorage.setItem("idUsusario", resposta[0].idusuarios);
         sessionStorage.setItem("flagLogado", "sim");

         this.navCtrl.setRoot(WellFitPage, {}, {animate: true, direction: "forward"});
        }else{
          let alert = this.alertCtrl.create({
            title: 'Usuário Não encontrado!',
            subTitle: 'Verifique se digitou seu e-mail e senha corretamente.',
            buttons: ['OK']
          });
          alert.present();
       }
    })
  }

Como posso fazer de forma correta? Não estou conseguindo. Preciso de ajuda. Já li tudo quanto é tutorial...
Answer: Ramos, sua API espera receber uma requisição POST e você está enviando um GET.
   this.http.get(link)

Para enviar o dado da maneira correta utilize
var data = JSON.stringify(this.usuario);
this.http.post(link , data)
.subscribe(response => { *Continue...* });

Comment: Por nada @Ramos !
Comment: Obrigado @Lucas Brogni, deu certo a sua referencia. :)


Closed operator bijective

Question:
Definition. Let $X$ and $Y$ normed space. A linear operator $T\colon X\to Y$ is said closed if the graph of operator $T$ is closed in the product topology. That is $T$ is closed if and only if for each sequence $\{x_n\}\subseteq X$ such that $\{x_n\}$ converges in $X$ and $\{Tx_n\}$ converges in $Y$, holds $$\lim_{n\to \infty}T (x_n)=T(\lim_{n\to \infty}x_n).$$

We suppose that $T$ is a bijective closed operator, how I can prove that $T^{-1}$ has closed graph and then it is closed?
Comment: "Close" as an adjective means nearby. The term you want is "closed".
Comment: Thanks! I just correct.
Answer: Let $y_n \to y$ and $T^{-1}y_n \to x$. We can write $y_n$ as $Tx_n$ for some $x_n$. Hence $Tx_n \to y$ and $x_n =T^{-1}y_n \to x$. Since $T$ is closed this implies $y=Tx$ or $x =T^{-1} y$ as required.

Closed operator bijective


Login fromAndroid : Api Key or Session Variables ,Which is better.?

Question: I want to create a user login from android phone (at Server side: PHP & Mysql).
So which is the following best option?
A) User Login return a Json Contains a API key, this key will used to Authenticate user.
OR
B) User Login sets a Session Variable(s).
Thanks
Answer: First one i.e. a)User Login return a Json Contains a API key, this key will used to Authenticate user. is a good way.
why not second one because when we talk about mobile application session variable is not a good way , it is for web applicaiton or websites.
Answer: I think First One is Better if User Login return a Json Contains a API key then You can Store it in Shared Preferences and use it in entire application and remove from Shared Preferences when You Logout.


Is it possible to install Kubernetes manually in my existing GCP VM instance?

Question: I am a newbie in Kubernetes. I have hosted my microservice application on the GCP VM instance. I want to use Kubernetes for deploying, managing, and scaling my applications. GCP provides GKE for that, but if I don't want to use that and installing Kubernetes manually in my existing VM instance.
Is it possible and how to install Kubernetes manually in my existing GCP VM instance?
Comment: You follow the directions for installing Kubernetes. It is extremely complex, which is why Google has a simple Kubernetes product.
Comment: @BhargavPatel `GKE` nodes are in fact `GCE` nodes and they are under the same pricing scheme. You can see it in the [GCP Pricing calculator](https://cloud.google.com/products/calculator). Please review this [Kubernetes Engine Pricing](https://cloud.google.com/kubernetes-engine/pricing) (additional fees). As for installing Kubernetes cluster on a `GCE` VM you can look on: [minikube](https://kubernetes.io/docs/tasks/tools/), [kubeadm](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/), [kubespray](https://github.com/kubernetes-sigs/kubespray).
Comment: @MichaelHampton thanks for the reply, Yeah it is extremely complex, but if somehow I installed it then google charges for computing resources? My main concern here is how to reduce my cost that's why I think if I install manually then it became beneficial for me or simply use google provided Kubernetes product.
Comment: It is god damn simple with Rancher. Prove me wrong.
Answer: As pointed by @Michael Hampton this topic could be extremly complex and there is no one straight and correct solution.
This answer is to give/set more a baseline and reference than the actual solution.

Dividing this question on parts:

Is it possible Kubernetes manually in my existing GCP VM instance?

In short, it's possible. There are a lot of options to choose from. Each solution will have it's advantages and disadvantages. It will also depend on the operating system your VM is deployed with.
Some of the options are the following:

Minikube
Kind
Kubeadm
Kubespray
Kops
Rancher <- as pointed by user @uav
Kelsey Hightower: Kubernetes the hard way

How to install Kubernetes manually in my existing GCP VM instance?

Each of the solutions linked above have a link to it's respective homepage. You can find there installation steps/tips. Each solution is different and I encourage you to check if selected option suits your needs.

A side note!
If you were to create a Kubernetes cluster on GCP with for example kubeadm please check if you have IPIPprotocol allowed in your network.

This question will inherently go into the differences between provider-managed and self-managed Kubernetes solutions.
The general idea behind it is that in a provider-managed solution (like GKE, AKS, EKS) some aspects of provisioning, management, updates, logging and monitoring, etc. are taken care of by your cloud provider. With a cluster provisioned on a GCE VM (not using GKE) you will have a self-managed solution.
You will need to take care of updates, provisioning and also you will need to tailor (which could be a good thing) your installation to your specific needs (and requirements).
There are articles talking about differences between provider-managed and self-managed solutions. They can give a general idea about the aspects that I mentioned:

Medium.com: SWLH: On premise Kubernetes clusters
Magalix.com: Blog: Provider-managed vs self-managed Kubernetes

To estimate the difference in costs of running:

GCE VM with a Kubernetes installed on top of it
GKE single zone cluster with a single node

You can use:

Cloud.google.com: Products: Calculator

I also encourage you to check the documentation about GKE pricing:

Cloud.google.com: Kubernetes Engine: Pricing

A note!
Additional fees may apply to other resources used in a project like static ip addresses, persistent disks used as PVC's etc.

Additional reference:

Kubernetes.io
Cloud.google.com: Kubernetes Engine: Docs: Quickstart


How to search and get count of special characters for every unique item in pandas

Question: By using pandas dataframe, I am trying to get count of special chars in column using but not getting desired output.
My .tsv file is:input file
NAME        ID
S. gambu    NNNTYR
S. gambu    RTD:78689
S. gambu    GTT:67878
S. gambu    RTD?78689
G. homos    SFDG\SS234R
G. homos    SFHG#SR234R
G. homos    JHFG:EE345T
G. homos    TYU=TT678R
T. mosus    RTU,YY67ET
T. mosus    TTR%YY67ET
G. ytrty    NaN

I am trying to get count for every special characters (:\,#%=?) form 'ID' w.r.t 'NAME' (for every name)(name =4 and special characters = 7) , I am not getting an desired output for every name and special characters present in ID's which are "(:\,#%=?)"
i need count for every special characters for every name.
i tried, but not getting following desired output.
Desired output is:
NAME         :        \          #       ?         %           =          ,

S. gambu  RTD:78689    0         0    RTD?78689    0          0          0
           GTT:67878
           count(2)                    count(1)

G. homos     0   SFDG\SS234R  SFHG#SR234R    0       0       TYU=TT678R     0
                  count(1)     count(1)                       count(1)

T. mosus     0       0          0         0    TTR%YY67ET      0    RTU,YY67ET
                                             count(1)                 count(1)

G. ytrty     NaN    NaN         NaN     NaN      NaN           NaN      NaN

Total         2      1           1       1          1            1            1

desired output
~ ~ ~ python
code i tried:
pattern1 = [':','#',',','%',]
count= 0
count1 = 0
with open('name.txt') as f:
lines = f.read().splitlines()

for pat in pattern1:
    pattern1 = re.compile(pat)
     for line in lines:
        for i in range(len(df3)):
                if ((df3.loc[i,'NAME'] == line)):
                    if (pattern1.search(df3.loc[i,'ID'])):
                        count = count+1
                    out =str(df3.loc[i,'NAME'])+"\t"+str(df3.loc[i,'ID'])+"\n"
                    print(out)

~ ~ ~
for desired output i have attached snap since out it contained more fields.
Comment: Welcome to SO! Please, if you waste the two minutes of your time to transcribe the results screenshots to markdown text, you improve the odds of having somebody who wastes the five minutes of their time to provide a competent and useful answer.
Comment: Do you have a [mcve]? What have you already done to try to solve this?
Comment: @AMC I have edited my question and also  paste my code which i tried
Comment: i have attached snap since it contained more fields. sorry for inconvenience
Comment: @Twonky thanks! i have edited my qestion
Answer: IIUC this should do the trick (df being your input data frame)
import re
special_chars=r"(:/,#%=@)"

#to take care of nan-s
df=df.fillna("")

for el in special_chars:
    temp_df=df["ID"].str.count(re.escape(el))
    df[el]=np.where(temp_df.gt(0), df["ID"] + " (" + temp_df.astype(int).astype(str) + ")", None)

df2=df.groupby("NAME")[list(special_chars)].agg(lambda x: list(x[~x.isna()]))

I'm not completely sure what's your desired output format for values - so I put it into a list...
Answer: IIUC,
we can use .str.count
Note that i've added 3 special chars into T.  mosus.
data = d="""NAME        ID
S. gambu    NNNTYR
S. gambu    RTD:78689
S. gambu    RTD:78689
S. gambu    RTD:78689
G. homos    SFDG/SS234R
G. homos    SFHG#SR234R
G. homos    JHFG:EE345T
G. homos    TYU=TT678R
T. mosus    RTU@:/YY67ET
G. ytrty    NaN"""

df = pd.read_csv(StringIO(data),sep='\s+')
pat = '[(:/,#%\=@)]'
df['count'] = df['ID'].str.count(pat)

print(df)
     NAME            ID  count
S.  gambu        NNNTYR    0.0
S.  gambu     RTD:78689    1.0
S.  gambu     RTD:78689    1.0
S.  gambu     RTD:78689    1.0
G.  homos   SFDG/SS234R    1.0
G.  homos   SFHG#SR234R    1.0
G.  homos   JHFG:EE345T    1.0
G.  homos    TYU=TT678R    1.0
T.  mosus  RTU@:/YY67ET    3.0
G.  ytrty           NaN    NaN

Comment: I have edited my question and also paste my code which i tried, i have attached snap since it contained more fields..i need count for every unique name for every special characters please see desired out snap...


Likelihood ratio tests

Question: Is likelihood ratio test ($F$-test) of significance of difference of two linear models the same as chi-square test of difference of $-2\log L$?
SAS PROC GLM produces $F$-statistics and PROC MIXED $-2\log L$.
Answer: I think that you might be confusing an extra-sum-of-squares F-test with a likelihood ratio test. Although, both are used to compare two models.
A likelihood ratio statistic, denoted by $\Lambda$, is given by
$$\Lambda = \frac{L\text{(reduced model})}{L(\text{full model})}$$
Taking $-2\log\Lambda$ produces a statistic that has $\chi^2_{d.f(\text{reduced model})-d.f(\text{full model})}$ distribution. That is to say that taking $-2\log$ of the $\Lambda$ gives you a $\chi^2$ distribution.
I have not used SAS so I cannot comment on the output, but I hope that I have been able to answer your question.
Note: that $\Lambda$ is equivalent to your L

Janne: For linear regression you could use either the likelihood ratio test or the extra-sum-squares F-test and you should end up with the same p-value. Despite, this they are not the same thing.
As has been mentioned above the likelihood ratio test produces a statistic that has $\chi^2_{d.f(\text{reduced model})-d.f(\text{full model})}$ distribution. Where as an extra-sum-of-squares F-test, given by
$$F = \frac{(SSR_{\text{reduced model}}-SSR_{\text{full model}})/d.f_{\text{reduced model}} - d.f_{\text{full model}}}{\hat{\sigma}^2_\text{full model}}$$
producing a statistic that has $F_{d.f(\text{reduced model})-d.f(\text{full model}),d.f(\text{full model})}$ distribution.
Where SSR is the sum of squared residuals and $\hat{\sigma}^2$ is our standard estimate.
Comment: I think the difference in d.o.f. for the $\chi^2$ should read the other way around (full - reduced).
Comment: The reduced model has less parameters, thus lower df. It turns out that $df_\text{reduced}-df_\text{full}<0$.
Comment: Thank You. So Chi2-test for comparing two models is not the same as F-test for the same purpose. The p-value I mean...
Comment: @chl it is only full - reduced if you take the -2 into the equation.

Likelihood ratio tests


Raphael JS Text Along path

Question: I am looking for an example or some confirmation on a concept. Looking to use Raphael JS on an app and want to be able to warp text similar to how graphic design applications such as Illustrator do.
Comment: This was from 2010:  http://stackoverflow.com/questions/2612764/attach-text-on-path-in-raphael
Comment: Thanks CM Kanode. I found this earlier in my hunt. It does not show the concept of orienting the text to the path. I am being extremely lazy here, would you think orienting to the path would just be a simple bit of math or does your linked example kind of prove that orientation would be a problem in Raphael?
Comment: Check out this [fork](https://github.com/petecocoon/raphael) - author claims that he added textPath support. Only to SVG though.
Comment: I didn't look at it in depth.  Just a quick look at the concept which seemed sound.  Offhand, I'd lean towards thinking that it'd need a lot of tweaking by hand.  Hopefully, the fork mentioned by Andrei above provides the solution that you are looking for.
Comment: I've done something much like this using Raphael only, using `print` and `path.getPointAtLength`.  I seem to remember there was a bug in the `alpha` attribute that had to be corrected for when the path passes through PI/2, but it was quite functional.  Just to clarify: individual characters are not skewed; the skew is accomplished simply by translation and rotation of complete characters.
Answer: Here's an adaptation of Chris Wilson's code, refactored as a drop-in function, with added features:

IE8 / VML mode support and Gecko/Firefox support (by defining the rotation origin - without this, IE8 and Firefox go nuts throwing the text all around the page)
A small adjustment to make text less ugly in Gecko browsers (e.g. Firefox) - without this, these increase the letter spacing arbitrarily
Support for manually defined font sizes and letter spacing, as well as dynamic 'fill the path' sizes and spacing
Support for manual kerning (fine-tuning letter spacing character by character). Text on a path often creates really ugly letter spaces; this allows you to define manual tweaks to fix these, by:

Numeric position in the string, or,
Character, or,
Character pairs (applying to instances of a character based on the preceding character, e.g. the below example tightens 'ae' pairs and widens 'rn' pairs)

JSBIN DEMO
function textOnPath( message, path, fontSize, letterSpacing, kerning, geckoKerning) {
    // only message and path are required, other args are optional
    // if fontSize or letterSpacing are undefined, they are calculated to fill the path
    // 10% of fontSize is usually good for manual letterspacing

    // Gecko, i.e. Firefox etc, inflates and alters the letter spacing
    var gecko = /rv:([^\)]+)\) Gecko\/\d{8}/.test(navigator.userAgent||'') ? true : false;

    var letters = [], places = [], messageLength = 0;
    for (var c=0; c < message.length; c++) {
        var letter = paper.text(0, 0, message[c]).attr({"text-anchor" : "middle"});
        letters.push(letter);

        if (kerning) {
            if(gecko && geckoKerning) {
                kerning = geckoKerning;
            }
            var character = letter.attr('text'), kern = 0;
            var predecessor = letters[c-1] ? letters[c-1].attr('text') : '';

            if (kerning[c]) {
                kern = kerning[c];
            } else if (kerning[character]) {
                if( typeof kerning[character] === 'object' ) {
                    kern = kerning[character][predecessor] || kerning[character]['default'] || 0;
                } else {
                    kern = kerning[character];
                }
            }
            if(kerning['default'] ) {
                kern = kern + (kerning['default'][predecessor] || 0);
            }
            messageLength += kern;
        }

        places.push(messageLength);
        //spaces get a width of 0, so set min at 4px
        messageLength += Math.max(4.5, letter.getBBox().width);
    }

    if( letterSpacing ){
        if (gecko) {
            letterSpacing = letterSpacing * 0.83;
        }
    } else {
        letterSpacing = letterSpacing || path.getTotalLength() / messageLength;
    }
    fontSize = fontSize || 10 * letterSpacing;

    for (c = 0; c < letters.length; c++) {
        letters[c].attr("font-size", fontSize + "px");
        p = path.getPointAtLength(places[c] * letterSpacing);
        var rotate = 'R' + (p.alpha < 180 ? p.alpha + 180 : p.alpha > 360 ? p.alpha - 360 : p.alpha )+','+p.x+','+p.y;
    letters[c].attr({ x: p.x, y: p.y, transform: rotate });
    }
}

Comment: Your solution helped me a lot. Thank you for that! But I have a problem with adjusting the text to appear exactly in the center of the path. I asked for help here: [link](http://stackoverflow.com/questions/20047029/raphael-js-centered-text-on-path). Maybe you could have a look?
Comment: Text alignment for text on paths would be a useful feature. I had a quick look at it, and got this far - http://jsbin.com/UJIYAco/18/edit - it's a starting point, works on GC/FF/IE8+, but as you'll see the characters are always skewed a little too far to the right, sometimes bunching up at the end. The approach seems sound, but it needs something to counteract the rightward shift - for some reason it's either underestimating the length of the text or overestimating the length of the path.
Comment: Thank you for that! It seems to be working good enough for me!

But now I have a different problem. I need the text printed on path to change it's attibutes (color in particular) on hover. Is it at all possible with your function given it's not the Raphael Paper element?
Comment: @zorza if you've got it working can you share what you did e.g. as an answer to your question?
Comment: This function has one bug and one place for improvement. 1) It does not center the text on path. Sometimes it might be intended, but not having an option to makes aligning texts a pain. 2) Letter rotation is broken, because a) it relies on Raphael's broken angle calculation (it is not consistent) b) it does not take path direction into account.
Comment: https://gist.github.com/friendzis/9362577
Here is my modified version to take my comments into account
Answer: This isn't too difficult using path.getPointAtLength, as Kevin Nielsen suggests:
path = paper.path("M50,100c40,-50 270,50 300,0").attr("stroke", "#CCC");
message = "I want to do this in RaphaelJS";

//since not every letter is the same width, get the placement for each letter
//along the length of the string
//however, Raphael appears to group the width of letters into intervals of 4px,
//so this won't be perfect
for (; c < message.length; c += 1) {
        letter = paper.text(0, 0, message[c]).attr({"text-anchor" : "start"});
    letters.push(letter);
    places.push(message_length);
    //spaces get a width of 0, so set min at 4px
    message_length += Math.max(4, letter.getBBox().width);
}

ratio = path.getTotalLength() / message_length;
fontsize = 10 * ratio;

for (c = 0; c < letters.length; c += 1) {
    letters[c].attr("font-size", fontsize + "px");
    p = path.getPointAtLength(places[c] * ratio);
    //there does appear to be a bug in p.alpha around 180. Here's the fix
    letters[c].attr({ x: p.x, y: p.y, transform: 'r' + (p.alpha < 180 ? p.alpha + 180 : p.alpha)});
}

jsFiddle
Comment: Nice approach, +1, but in my testing this only worked in Webkit (Chrome, Safari etc) and IE9+. In **Firefox** and **IE8**, the text is thrown around and doesn't follow the path. I've posted an adapted version below (with rotation origin) that works in IE8+, Firefox and Webkit and has a few extra tweaks and features.

Raphael JS Text Along path


Using Case When Then to Filter Dates

Question: I need to create a view for my accounts team to show aged debtors via Excel.
I've got the due dates for all of the outstanding invoices and i want to achieve a 30,60,90 and 120 day breakdown.
My current script is this...
CASE WHEN ST_TRANSMONTH = MONTH(GETDATE())
     then '30 Days'
     else if ST_TRANSMONTH = MONTH(GETDATE()) + 30 = '60 DAYS' and so on.

I can't ge this to work though, help would be appreciated!
Comment: Please post your database schema, some sample data and desired output.
Comment: CASE doesn't have ELSE IF in it, it just has multiple WHEN (and possible one ELSE)
Comment: You do not seem to look at 30 days, only if it is the current month?
Answer: Your math has a subtle flaw in it, in that you're using MONTH to check the length of days from transaction date, but as we know, not all months have 30 days, therefore you're going to introduce some areas for discrepancy, which could potentially involve legal issues if you send late notices to people when they're not technically late.
Furthermore, someone could be more than 30 days passed due, but you're not catching it because it's a different month, for example, they bought something on the 25th of last month and it's the 31st of the month now, they're > 30 days passed due, but you're not reporting it.
Instead of month, use the DATEDIFF command, that is part of TSQL.  It allows you get to get the difference between two dates for a specified unit:
CASE
    WHEN ST_TRANSMONTH > DATEADD(DD, -30, GETDATE()) THEN '30 Days'
    WHEN ST_TRANSMONTH > DATEADD(DD, -60, GETDATE()) THEN '60 Days'
    -- add more cases as needed
END

Give that a try instead.
Good luck.
Comment: +1 : Though the pattern `ST_TRANSMONTH > DATEADD(DD, -30, GETDATE()) THEN '30 Days'` will use slightly less CPU by only applying the date functions to a scalar constant, rather than every row in the table.
Comment: @matbailie - I updated my answer to use your suggestions.  Thanks again!
Answer: Should be like this:
CASE WHEN ST_TRANSMONTH = MONTH(GETDATE()) THEN '30 Days'
     WHEN ST_TRANSMONTH = MONTH(GETDATE()) + 1 = '60 DAYS'
     WHEN ST_TRANSMONTH = MONTH(GETDATE()) + 2 = '90 DAYS'
END as ColumnName

Comment: I have concerns about using month for the reasons that I explain above.  Not all months are 30 days long, and using a month to fuzzy match the days could lead to problems, including potential legal issues if they proceed with collection against a person who isn't actually late, but appears to be on the report.
Answer: You only seem to store the month, not the year? Then you can hardly check how many days/months there are between two dates. You should better store a complete date (or at least month + year).
If you store a complete date and you really want to check for 30 day intervals then you can
select convert(varchar, datediff(day, st_date, getdate())/30*30) + ' days' from mytable

If you store a complete date and you only want to check for month intervals then you can
select convert(varchar, datediff(month, st_date, getdate())/30) + ' days' from mytable

Using Case When Then to Filter Dates


Solve $y''-3y'-4y=3\mathit{e}^{2t}$ using variation of parameters formula.

Question:
Solve $y''-3y'-4y=3\mathit{e}^{2t}$ using variation of parameters formula.

I just want to know whether I am on the right track with my solution.
I started by solving the differential equation $y''-3y'-4y=0$ by finding its companion matrix and the eigenvalues of that matrix. I got the solution set $\left \{ \varphi_{1},\varphi_{2} \right \}=\left \{ \mathit{e}^{-t},\mathit{e}^{4t} \right \}$.
The variation of parameters theorem is the following:

So I am guessing that $\phi_{h}(t)=c_{1}\mathit{e}^{-t}+c_{2}\mathit{e}^{4t}$ for some constants $c_{1},c_{2}$. I then calculated the sum of integrals:
$W(\phi_{1},\phi_{2})(t)=5\mathit{e}^{3t}$
$W_{1}(\phi_{1},\phi_{2})(t)=-\mathit{e}^{4t}$
$W_{2}(\phi_{1},\phi_{2})(t)=\mathit{e}^{-t}$
Then $\phi(t)=c_{1}\mathit{e}^{-t}+c_{2}\mathit{e}^{4t}-\frac{3}{5}\int_{\tau}^{t}\mathit{e}^{2s}ds+\frac{3}{5}\int_{\tau}^{t}\mathit{e}^{2s}ds=\phi_{h}(t)$.
I am not sure if this is how to find the solution or not. Is my $\phi_{h}$ correct, and is it really true that the solution is just $\phi_{h}$?
Any help and guidance appreciated!
Comment: The answer is correct if it solves your equation. In any case, your solution appears to have two terms that cancel.
Comment: Thank you so much for reading through my solution and letting me know. I thought the answer was too simple to be true. Thanks!!
Comment: @LordSharktheUnknown I actually have a quick question regarding the same problem. If I decide to instead convert the problem into a system of $2$ first order equations, is the unique solution then $\mathit{e}^{At}\xi$, where $\mathit{e}^{At}$ is a fundamental matrix and $\xi$ is the initial condition?
Answer: Solutions of the homogeneous part:  $$y''-3y'-4y=0$$ are $y_1=e^{-t}, y_2=e^{4t}$
The soloution of the in-homogeneous ODE:
$$Y''-3Y-4Y= 3 e^{2t} =f(t)$$ by Vvariation of parameters $(C_1,C_2)$ is given by
$$Y(t)=C_(t) e^{-t}+ C_2(t) e^{4t},$$wjere
$$C_1=\int\frac{-y_2(t) f(t)}{W(t)} dt+D_1, C_2= \int \frac{y_1(t) f(t)}{W(t(} dt +D_2$$ $$W(t)=[y_1y'_2-y_1'y_2]=3e^{3t}.~~~(1)$$
$$C_1=-\int \frac{e^{4t}~ 3 e^{2t}}{5e^{3t}} dt + D_1=-\frac{1}{5}e^{3t}+D_1$$
$$C_2=\int \frac{e^{-t}~3e^{2t}}{5e^{3t}}+ dt+D_2 =-\frac{3}{10} e^{-2t}+D_2$$
Finally we have from Eq. (1)
$$Y(t)=[-\frac{1}{5}e^{3t}+D_1]e^{-t}+[-\frac{3}{10}e^{-2t}+D_2]e^{4t}$$
$$\implies Y(t) =D_1 e^{-t}+D_2e^{4t}]-\frac{1}{2}e^{2t}.$$


C# Replacing escaped escapes

Question: Ive parsed a text file into a List<string> object and the test file contains \n and \t, however once I output the strings to console they appear as "\n" and "\t" rather than a new line and a tab.
At the moment i'm using myList[i].Replace(@"\n", "\n").Replace(@"\t", "\t") but this seems a little cumbersome, especially if more escape sequences need to be added in the future.
Is their any way to un-escape the escaped sequences? Something like string.UnEscape would be just to perfect.
Comment: Am I right that test file keep `\n` and `\t` as text?
Comment: @sll yes, plain text document written in notepad
Comment: Are you sure that the escape sequences in your text file will always match *exactly* the escape sequences used by C#? If not, you are better of writing your own `Unescape` method.
Comment: @Heinzi Yup, i'm writing the test files.
Comment: Ok how are you parsed a file?
Comment: @sll Using `StreamReader.ReadLine()` and from there the strings get split up a bit before being stored in a `List`
Answer: You could write your own helper..
 public static class Helper
    {
        public static string Unescape(this string val)
        {
            return val.Replace(@"\n", "\n").Replace(@"\t", "\t");
        }
    }

Answer: I'm not sure if this will do exactly what you're after but there is an Unescape method in the RegEx namespace.
string result = Regex.Unescape(myList[i]);

Comment: Watch out for this issue...

If the Unescape method encounters other escape sequences that it cannot convert, such as \w or \s, it throws an ArgumentException.
Comment: Exactly what i was looking for, I did come across it but thought it was only for use with regex's, guess I should have read the documentation better

C# Replacing escaped escapes


Chamar modal por javascript

Question: Esses são os arquivos referentes ao boot e o js. Os inseri na página Layout

Meu modal

Esse procedimento pode levar alguns minutos. Por favor aguarde!

Meu javascript
function abreModal() {
 $("#myModal").modal({
      show: true
    });
 }
setTimeout(abreModal, 1000);

Meu botão para chamar a função Javascript
@Html.ActionLink("Criar nova tabela de Markup", "Create", null, new { @class = "btn btn-azul wd-270", @onclick = "startLoading();abreModal();", @id = "novaTabela" })

tá dando esse erro:

Uncaught TypeError: $(...).modal is not a function
      at abreModal (Markup:439)

O que está errado?
Comment: Quando for criar uma pergunta, tente detalha-la com informações importantes, sugiro que leia  [como criar uma boa pergunta aqui na comunidade](https://pt.stackoverflow.com/help/how-to-ask). Então você está utilizando o modal do bootstrap correto? Qual versão realmente você está utilizando a do bootstrap? A função deste botão, você somente quer que ela exiba o modal é isto?
Comment: [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas). Me parece ser um bom tópico para que seja lido para evitar pergunats como essa.
Comment: Tente colocar `data-load-url` no seu botão com o `@Html.ActionLink` nela.
Comment: @Miyukii, e como eu uso no javascript isso, ou não precisa
Comment: Seria no HTML mesmo, mas só agora que eu vi que você quer tirar o botão HTML, então meio que ele seria necessário pra usar @pnet
Comment: @pnet Você inseriu o [arquivo JS](https://getbootstrap.com.br/docs/4.1/getting-started/introduction/#js) referente ao Bootstrap?
Answer: É tudo uma questão de ler a documentação.

function abreModal() {
  $("#myModal").modal({
    show: true
  });
}

setTimeout(abreModal, 1000);

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Modal body text goes here.

        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Comment: Lendo o código que você copiou e colou.
Comment: @pnet Então seu exemplo não é um bom exemplo. Faça um [mcve].
Comment: @pnet Mas não tem como reproduzir o problema. Pela resposta eu mostrei que só chamando a função `modal` e passando o objeto o modal abre corretamente. Se isso não funciona para você é porque outra coisa está interferindo.
Comment: @pnet Não, esses são atributos que o Bootstrap considera para fazer o botão abrir o modal sem que você precise escrever o JS. Para testar, é só fazer como eu fiz na resposta: elimine todos os ruídos. Crie um modal simples (eu copiei da própria documentação) e faça a função igual eu fiz. Se não funcionar, edita a pergunta **somente** com esse código. Se funcionar, o problema está em outro lugar e não temos ajudar.
Comment: @AndersonCarlosWoss, consegui com esse exemplo. Era a ordem dos scripts na página layout. Mas tem um problema que não consigo resolver. Quando a página entra, já mostra o Modal e deveria apenas no click do botão. Como resolvo isso?
Answer: Resolvi dessa forma
<input type="hidden" id="md" data-toggle="modal" data-target="#myModal" />

Função javascript
function MostraModal() {
        $("#md").click();
    }

E o botão
@Html.ActionLink("Criar nova tabela de Markup", "Create", null, new { @class = "btn btn-azul wd-270", @onclick = "startLoading();MostraModal();", @id = "novaTabela" })

Sei lá, acho que pode ter outra solução sem a necessidade do hidden e ainda fico no aguardo dessa solução, que ao meu entender, seria mais elegante.
Comment: Considerando seu [comentário](https://pt.stackoverflow.com/questions/382685/chamar-modal-por-javascript#comment756990_382691), apenas ocultar o botão não parece-me uma solução plausível.
Comment: @AndersonCarlosWoss, concordo com você, por isso não dei por encerrada a questão e ainda procuro uma outra solução, sem a necessidade de um hidden. Você está cheio de razão

Chamar modal por javascript


Is Archimedes's method for computing volumes equivalent to Cavalieri's?

Question: Encyclopaedia Britannica is unequivocal: "It turned out that Archimedes had used a method later known as Cavalieri's principle, which involves slicing solids (whose volumes are to be compared) with a family of parallel planes." I suppose it's true that both are based on slicing, but Cavalieri's calculation for sphere and cylinder only needs a simple comparison of cross sections, whereas Archimedes's requires a diagram with a tangle of lines, and a lever with unequal arms to balance the pieces. Also in Cavalieri's case the sphere is inscribed into the cylinder, while in Archimedes's it has only half the cylinder's radius, and Cavalieri's cone is inverted compared to Archimedes's.
Can somebody explain the exact relationship between Archimedes's and Cavalieri's use of slicing? Is there a general way to rephrase any Archimedian calculation into a Cavalierian one and/or vice versa? Is one of them more general than the other?
Answer: Archimedes used the optical properties of the parabola to prove that the area of the parabolic segment is $\frac{2}{3}$ of the circumscribed rectangle. In modern terms, the optical property is equivalent to $\frac{d}{dx}x^2 = 2x$, while the area depends on $\int x^2 = \frac{1}{3}x^3$, and the Archimedean argument for the parabolic segment can be viewed as the first attempt to provide an antiderivative for a polynomial.
With such a preliminary result, he proved that the volume of the sphere is $\frac{4\pi}{3}R^3$ by "slicing" it. Since the area of a section is proportional to the square radius of that section, to find the volume of a sphere is essentially the same problem as finding the area of a parabolic segment, since they both depend on $\int x^2$ - and not by chance, the coefficient $\frac{1}{3}$ appears in both of them.
So, in a quite vague (but not so much) sense, we can say that the Archimedean method was a precursor of the Cavalieri's method. And that Archimedes was a true genius.
Comment: I am not referring to the method of exhaustion computation in On Sphere and Cylinder, but to the method in the letter to Eratosthenes,  that according to Archimedes motivated the result. The letter itself is often called The Method, and is contained in the famous palimpsest that Heiberg found in 1906. It does not use quadrature of the parabola, but compares cone, sphere and cylinder slices directly. However, the manner of comparison seems to be different from Cavalieri's in some ways, even though their approaches are often identified.
Answer: The method used by Archimedes in that letter includes Cavalieri's method (and I don't know whether Cavalieri's method is really Cavalieri's), but Archimedes's method also involves centers of gravity. I think Archimedes may have been the first ever to conceive of centers of gravity. Archimedes used his method to show that the center of gravity of the interior of a hemisphere (not a sphere; a hemisphere) is $5/8$ of the way from the north pole (if we were to take it to be the northern hemisphere) to the center of the sphere.


How do I send a file attachment via email in php (what's wrong with my code)

Question: I am fairly new to php, and am unfamiliar with email headers. This is a function based on some code I came across / updated to use a file object. The result is a 'File Sent Successfully gets echoed, but the email never comes. I can only assume this has something to do with the email headers that this thing is generating. Hopefully somebody see's what's wrong here:
function mail_attachment ($from , $to, $subject, $message, $attachment){
    $fileatt = $attachment["tmp_name"];
    $fileatt_type = "application/octet-stream";
    $fileatt_name = $attachment["name"];
    $email_from = $from;
    $subject = "New Attachment Message";
    $email_subject = $subject;
    $email_to = $to;
    $headers = "From: ".$email_from;
    $file = fopen($fileatt,'rb');
    $data = fread($file,filesize($fileatt));
    fclose($file);
    $semi_rand = md5(time());
    $mime_boundary = "Multipart_Boundary_x{$semi_rand}x";
    $headers .= "\nMIME-Version: 1.0\n" .
                "Content-Type: multipart/mixed;\n" .
                "boundary=\"{$mime_boundary}\"";
    $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" .
                "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
    $data = chunk_split(base64_encode($data));
    $email_message .= "--{$mime_boundary}\n" .
                "Content-Type: {$fileatt_type};\n" .
                "name=\"{$fileatt_name}\"\n" .
                "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"
                . "--{$mime_boundary}--\n";
    $ok = mail($email_to, $email_subject, $email_message, $headers);
    if($ok) { echo "File Sent Successfully.";}
    else { die("Sorry but the email could not be sent. Please go back and try again!"); }
}

Comment: Stealing code then asking SO to fix it for you?
Comment: You should use [PHP Mailer](http://phpmailer.worxware.com/)
Comment: @Sean Why?  `mail` works just fine
Comment: it's heavily modified, i'm not dumb, i just don't really know what's wrong with the headers.
Comment: It's your decision to use cumbersome code like that. So please debug it yourself. Everybody else ought to use [PHPMailer or SwiftMailer](http://stackoverflow.com/questions/303783/phpmailer-vs-swiftmailer).
Comment: @Madbreaks because it simplifies mail attachments.
Comment: You said you are "unfamiliar with email headers". Did you consider familiarizing yourself with them?
Comment: I'm also not that familiar with php as I usually program in c#. I just didn't know if I was doing something blatantly incorrect, or if it was the headers. I wasn't trying to leach off you guys or anything.
Comment: using php's mail() for complicated stuff (and even uncomplicated simple "hello world") emails just leads to premature baldness and jackets that close up in the rear. it should never be used in a production system.
Answer: Use phpMailer()
<?php
require_once('phpmailer.php');

$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSendmail(); // telling the class to use SendMail transport

try {
    $mail->AddReplyTo('firstname.lastname@example.com', 'First Last');
    $mail->AddAddress('firstname.lastname@example.com', 'John Doe');

    $mail->SetFrom('firstname.lastname@example.com', 'First Last');
    $mail->Subject  =  "Subject Line";
    $mail->AltBody    = "Alternate Text"; // optional, comment out and test

    $mail->WordWrap     =   50; // set word wrap
    $mail->Body = "This is the body of the email";
    $mail->IsHTML(true); // send as HTML

    // Single or Multiple File Attachments
    $mail->AddAttachment('../path-to-file.pdf', 'File-Name.pdf');
    $mail->Send(); // Try to send email
    //echo "Message Sent OK

\n";
    } catch (phpmailerException $e) {
        echo $e->errorMessage(); //Pretty error messages from PHPMailer
    } catch (Exception $e) {
        echo $e->getMessage(); //Boring error messages from anything else!
}
// end try

?>