how to count in recurrsive function?

Question: Here is my code for printing the divisors and then number of divisors of a given number.
Now suppose I take 2 test cases: 5 and 8; this code gives count of 5 as 2 and 8 as 6 (i.e it adds the previous count).
Even if I declare it as int count = 0; it returns the same output.
The other problem arises when I declare int count = 0 inside function factors.
The code gives count as 0 for all cases.
#include<iostream>
using namespace std;
int count;
long long factors(long n, long f=1)
{

    if(n%f==0) {
        cout << f << endl;
        count++;
    }

    if(f==n) {
        return 0;
    }

    factors(n,f+1);

    return count;

}

int main()
{
    int n;
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n;
        cout << factors(n) << endl;
    }

    return 0;
}

Answer: Using globals is not usually a good idea. It is especially bad in recursive functions, which should preferably be re-entrant. Of course you can fix your function by resetting the count in the loop, like this:
while(t--)
{
    cin>>n;
    count = 0; // Reset count before the recursive call
    cout << factors(n) << endl;
}

You could also make factors "wrapper" that resets the count to free the callers from the need to reset count before calling factors, like this:
long long factors(long n) {
    count = 0;
    return factors(n, 1);
}
long long factors(long n,long f /* Remove the default */) {
    ... // the rest of your code
}

Answer: you can achieve this by passing count as reference -
#include<iostream>
using namespace std;

long long factors(long n, int& count, long f=1)
{
    if(n%f==0)
    {
        cout<<f<<endl;
        count = count + 1;
    }

    if(f==n)
      return 0;

    factors(n, count, f+1);
    return 0;
}

int main()
{
    int n,t;
    cin>>t;
    while(t--)
    {
            cin>>n;
            int count = 0;
            factors(n, count);
            cout << count << endl;
    }
    return 0;
}

-Gaurav
Answer: First, why are you declaring the count variable in the global space?
Second, you can not perform arithmetic operations to an undeclared variable (the int "count" in this case is never declared).
Third, why do you create an infinite loop by doing while(t--)?
You said the function gives you count as 0 for all input,
Can this be due to count never being declared?
Comment: I think in this form your post doesn't really qualify as answer. You're posing more questions than the OP! If this is not meant to be an answer, you'll have to earn some reputation to be eligible to post comments in which you may ask further questions.
Comment: Alex, just remember our format is one that involves Q&A. It seems your questions are more rhetorical, but for the sake of eliminating confusion, I'd strongly suggest editing to say what you're implying. For instance, why you're declaring in the global namespace could be edited to "You shouldn't declare count in the global namespace."  Good luck and hope this helps! :)

how to count in recurrsive function?


'User Account' menu link does not show to anonymous users

Question: When a user is logged in the User menu shows 'My Account' link and the 'Logout' link. However, when logged out the menu disappears.
How do I make a menu link to the user login page that only shows for anonymous users in the User Menu?

If Trey posted his comment as an answer, I would have checked it. I have disabled the block module since I use context. I created a second sitewide context that is triggered by the anonymous user role and placed the menu block with the link for login page in the user region. It works.
I still would like to see this accomplished in code. I tried to access the variables through preprocess functions but the menu links are already rendered by that time.
Answer: That is a feature. An anonymous user doesn't have an account nor can he log out, why should there be links to these pages?
You might want to update your question to better explain what you actually want instead of explaining how it works right now :)
EDIT: To have a link to the Login page, just create a menu entry that points to /user/login. Just like /user/logout, this link will only be shown if you can log in (which means that you are not already logged in).
Comment: This is the correct answer.
Answer: Check out the logintoboggan module; it provides a login block that works more as expected.
Or just go to your blocks, create a new block, and use the following code as block body:
Sign In

Use the following PHP code to determine the block visibility:
<?php global $user; return($user->uid == 0); ?>

Comment: logintoboggan does this but I don't want to add more code if the site really doesn't need it.
Comment: In order to change your login block from "my account | logout" to "sign in | register", which is what I assume you are looking for, you will have to add more code, either into your template.php file in your theme or via a modules like logintoboggan, I prefer the module in this scenario because it adds valuable functionality that becomes very useful as your site grows
Answer: The login links should appear when a user is not logged in. If you go to http://drupal.org, and you are not logged in, you will see the login link; once you are logged in, the login link is replaced by the logout link.
In fact, the following definitions are used for the "user/login" and "user/logout" menu callbacks:
  $items['user/login'] = array(
    'title' => 'Log in',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );

The first menu callback is not visible when the user logged in; the second menu callback is not visible when the user is not logged in.
Similar definitions are used in Drupal 6:
  $items['user/login'] = array(
    'title' => 'Log in',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'file' => 'user.pages.inc',
  );

In both the cases, only when the access callback returns TRUE the link is accessible to the user; when the access callback returns FALSE, the link is not visible to the user.
Comment: No it doesn't. Login toboggan does that. I just don't want to add that much code if I don't have to. @see http://drupal.org/node/937916
Comment: @Adam S No, that is how Drupal behaves. As far as I know, Drupal.org doesn't use Login Toboggan; I have never used that module in my site, and when I am logged in, the "log in" link is replaced by the user profile, and the "log out" link.
Answer: This is not that complicated if you're trying to do this in Drupal 7 using the Bartik theme.
Create a user menu item and call it Login. Give it the link, user/login. It will automatically show up for anonymous users, and disappear for logged in users.
If you have problems with this, you may need to rebuild your permissions (on admin/reports/status page)


If $\text{Var}(X) < \infty$, is $\text{Var}(XY) < \infty$ for $0 \le Y \le 1$?

Question: I have a variable $X$ that I know has finite variance (and therefore also finite mean). Is it always true that its variance remains finite after scaling by $0 \le Y \le 1$?
Note that $X$ and $Y$ are not necessarily independent.
Edit: I believe the "worst-case" $Y$ is $0$ whenever $X < c$ and $1$ whenever $X \ge c$, for some $c$ (and the mirrored case)?
Comment: An utterly trivial inequality sometimes is quite useful in such situations: $\mathbb{E}(X^2Y^2) \le \mathbb{E}(X^2)\sup(Y^2)$. (This is perhaps the simplest special case of [Hölder's inequality](https://en.wikipedia.org/wiki/H%C3%B6lder's_inequality) for $p=1,q=\infty$ applied to $X^2$ and $Y^2$.)
Comment: Is $Y$ a random variable?
Comment: Yes but it may depend on $X$.
Comment: Thanks whuber. I believe this leads to the correct solution (see the answer I made)!
Answer: I've unaccepted kjetil's answer since, as was pointed out in the comments, it assumes $X$ and $Y$ are independent.
The following answer should work when $X$ and $Y$ are dependent, by using whuber's suggestion:
\begin{align}
\text{Var}(XY) &= E((XY)^2) - E(XY)^2 \\
&\le E(X^2Y^2) \\
&\le E(X^2)\sup(Y^2) \\
&= E(X^2) \\
&= \text{Var}(X) + E(X)^2 \\
&< \infty
\end{align}
Note that the result also holds for any bounded $Y$ (since $\sup(Y^2)$ will be finite).
Comment: I don't believe kjetil assumed independence between $X$ and $Y$. The law of total variation holds in general, and not assuming independence. So I can find nothing in his statement that assumes independence. Also notice that your conclusion is exactly the same as my conclusion that is based off of kjetil's answer.
Comment: Independence must have been used somewhere (I guess when factoring out the expectation), otherwise the first equation from your answer (as shown in my comment) is stating that $\text{Var}(XY)$ is the same whether or not $X$ and $Y$ are independent, which is a contradiction. The fact that we came to the same conclusion is kind of a "coincidence", because we are both giving upper bounds. Mine comes from dropping the $E(XY)^2$ term and $Y^2 \le \sup(Y^2)$, and yours comes from $\text{Var}(Y), E(Y^2) \le \sup(Y^2)$.
Comment: I think I figured out where kjetil is using independence. By the law of total variance $Var(XY) = Var(E(XY|Y)) + E(Var(XY|Y))$. If we just look at the first term $Var(E(XY \mid Y)) = Var(Y^2E(X \mid Y))$ which is not the same as $Var(Y^2E(X))$. It is the same only when $X$ and $Y$ are independent.
Comment: Also note that we can conclude $|E(XY)| \le \sqrt{\text{Var}(X) + E(X)^2}$, since $\text{Var}(XY) \ge 0 \implies E(XY)^2 \le E((XY)^2)$.
Comment: I changed my answer to reflect the changes.
Comment: Yes that sounds right to me (I'd upvote but don't have the privilege). I think the same thing happens with the other term as well. Specifically, $E(Var(XY | Y)) = E(Y^2 Var(X|Y))$ which is not the same as $E(Y^2 Var(X))$. Thanks for helping clear that up. :)
Comment: Yep, that happens with the other term as well. I am glad this has cleared.
Answer: You need to use the formula
$$  \DeclareMathOperator{\Var}{\mathbb{V}} \DeclareMathOperator{\E}{\mathbb{E}}
   \Var (XY) = \E (\Var (XY | Y)) + \Var (\E (XY | Y))
$$
where $\Var $ is the variance operator. Take it term for term, write $\mu=\E X, \sigma^2=\Var X$, $\E (XY | Y= y) = \E (yX) = y \E (X) =\mu y$ with variance (over $Y$) $\Var (\mu Y) $ which is finite since $Y$ is bounded.
Then the other term, $\Var (XY | Y=y) = \Var (yX) = y^2 \Var (X) = \sigma^2 y^2$ which again has a finite expectation since $Y$ is bounded. So the answer is yes.
Comment: @kjetilbhalvorsen $\mathbb{E}(XY \mid Y=y) = \mathbb{E}(yX)$ does not hold without some assumptions (such as independence).
Comment: Nice. To check my understanding this is using the [law of total variance](https://en.wikipedia.org/wiki/Law_of_total_variance)? Also this seems to prove something more general: that the variance $XY$ is finite as long as the variance of both $X$ and $Y$ are finite?
Comment: @Aaron Voelker:  There is no need for independence in the calculations.
Comment: @Juho $\mathbb{E}(1 X) = \mathbb{E}(X)=0.5$, too.  The relation $\mathbb{E}(XY\mid Y=y)=\mathbb{E}(X)y$ is an example of a very general theorem called "taking out what is known."  It does not require independence of $(X,Y)$.  See https://en.wikipedia.org/wiki/Conditional_expectation#Basic_properties.
Comment: @Juho Sorry, my comment was stupid.  Of course I needed to write the conditional expectation in $\mathbb{E}(XY\mid Y=y)=\mathbb{E}(X\mid Y=y) y$.  For some reason I just automatically understood these expectations as being conditional even when they weren't... .
Comment: Yes, it is total variance. And no, your last claim is untrue. I used  that $Y$ is bounded, which implies its variance exists.  I guess it would be easy to make an example where variance of $X$ and $Y$ both exist, but their product has infinite variance.
Comment: Hmm.. sorry but I'm confused. According to the formula in Greenparker's answer based on the above, this will still hold as long as $E(Y^2)$ and $Var(Y)$ are finite? And if $Var(Y)$ is finite, then so is $E(Y)^2$, and therefore $E(Y^2)$ as well. So how does my claim break down? Also thank you!
Comment: @Aaron Voelker: you are right.
Comment: Actually I'm confused again... I think the above answer only works when $X$ and $Y$ are *independent*... Please see my response to Greenparker below.
Comment: For a counterexample, let $X$ and $Y$ be Bernoulli with $P(X=Y=1)=0.5$. Then $\mathbb{E}(XY \mid Y = 1) = 1 \neq 0.5 = \mathbb{E}(1\,X)$
Comment: @whuber: indeed $\mathbb{E}(1\,X) = \mathbb{E}(X) = 0.5$ as I, too, said in my comment.  What do you think $\mathbb{E}(XY \mid Y= 1)$ is in the case where $X=Y$ almost surely?  If you refer to the  "Pulling out known factor" property in the Wikipedia link, wouldn't that lead to $\mathbb{E}(XY  \mid Y = y) =  y\mathbb{E}(X \mid Y = y)$, where the latter factor of the right hand side does not necessarily equal $\mathbb{E}(X)$.


Architecture clash? symbol(s) not found for architecture x86_64 on mac

Question: I'm trying to install a C library: ssht
I've set up the makefile and it's definitely finding the dependencies.  When I make it using gcc, however, I get some warnings:
In file included from ../ssht/src/c/ssht_core.c:23:0:
../ssht/src/c/ssht_core.c: At top level:
../ssht/src/c/ssht_sampling.h:39:20: warning: inline function 'ssht_sampling_ind2elm' declared but never defined
extern inline void ssht_sampling_ind2elm(int *el, int *m, int ind);

And then when I make the test for the code I get the error:
"_ssht_sampling_elm2ind", referenced from:
  _ssht_test_gen_flm_complex.constprop.1 in ssht_test.o
  _ssht_test_gen_flm_real in ssht_test.o
  _ssht_test_gen_lb_flm_real in ssht_test.o
  _ssht_test_gen_flm_complex in ssht_test.o
  _ssht_test_gen_lb_flm_complex in ssht_test.o
  _main in ssht_test.o
  _ssht_core_mwdirect_inverse in libssht.a(ssht_core.o)
  ...
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [../ssht/bin/c/ssht_test] Error 1

I've haven't been able to find any solutions that I could understand.  By the way my gcc version is:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-apple-darwin14.4.0/5.1.0/lto-wrapper
Target: x86_64-apple-darwin14.4.0
Configured with: ../gcc-5.1.0/configure --enable-languages=c++,fortran
Thread model: posix
gcc version 5.1.0 (GCC)

I've tried installing as a 32 bit installation with -m32 to see if that changed things, but I get the same error with i386 instead of x86_64.
I have installed it on a Linux machine that I also have access to with a makefile which is identical except for the location of one of the dependencies.
Please help!
Comment: @ead the function is just this: inline void ssht_sampling_elm2ind(int *ind, int el, int m) {

  *ind = el * el + el + m;

}
Comment: how does `ssht_sampling_ind2elm` looks?
Comment: Maybe you should build with GNU89 (I guess now it is building C99). See http://stackoverflow.com/questions/216510/extern-inline/216546#216546
Answer: It appears that the code is broken, and the warning that you present is indeed a good clue.  The standard specifies:

For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit.  If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline definition.  An inline definition does not provide an external definition for the function [...].

[C2011, 6.7.4/7]
The warning signals a violation of the cited restriction: the header file indicated in the warning contains the given function declaration, which  bears inline and extern specifiers.  Because of the inline specifier, C requires that every translation unit in which that declaration appears also provide a definition; since it appears in a header file, that applies to every source file that includes that header.  File ssht_core.c includes the header but does not provide a definition.
Examination of the source shows that the designated function is defined only in file ../ssht/src/c/ssht_sampling.c, but that that file does not include the corresponding header.  When a C source file has a corresponding header, it is customary and useful for it to include that header, for that helps catch discrepancies between declarations.  It is not obligatory to do so, however, so that omission is not wrong in itself.
In this case, however, the only declaration of ssht_sampling_ind2elm() in ssht_sampling.c is its definition, and that bears an inline specifier without extern.  The second part of the above-quoted section of the standard therefore applies: the translation unit corresponding to that file does not provide an external definition of the function.  That is, the definition it provides is only visible from within the same translation unit, not from others, such as the one associated with ssht_core.c.
The intention appears to be to provide a function definition in one file that can be inlined in other files, but that is not allowed, nor does it really make sense.  I'd file a bug report with the library's author.  One possible resolution would be to make ssht_sampling.c include its own header; that would not resolve the warning, but it ought to fix the linkage problem.  You could clear the warning by also removing the inline specifiers from the function declaration in the header.  Alternatively, you could remove the inline specifiers from the function in both the header and the main source, without changing which headers are included in which file.
Comment: Thank you very much for the detailed response, this fixes the warnings and error!  I will file a bug report with the author.
Comment: Removing `inline` is definitely the wrong fix, because it's a trivial function (the OP copied the definition in a comment).  Instead, move the definition into the header, where all users of the function can see the definition instead of just the prototype.


Independence of multivariate random variables

Question: Let $X=(X_1,X_2,...,X_n)$ be an independent multivariate random variable, i.e.
$$
F_X(x_1, x_2,...,x_n)=\prod_{i=1}^{n}F_{X_i}(x_i)
$$
This implies that if we take 2 components $X_i, X_j$, these are independent as well:
$$
F_{(X_i, X_j)}(x,y)=F_{X_i}(x) \cdot F_{X_j}(y)
$$
I need to prove that the reverse statement is not true, i.e this is false:
$$
F_{(X_i, X_j)}(x,y)=F_{X_i}(x) \cdot F_{X_j}(y) \implies F_X(x_1, x_2,...,x_n)=\prod_{i=1}^{n}F_{X_i}(x_i)
$$
A theoretical proof or a counter-example are both acceptable.
Thanks, András
Answer: The standard counter example is to take $X,Y,Z$ such that $Z=X\oplus Y$, where $\oplus$ denotes the ex-or operation. Each pair is independent, however any two completely determine the third.


Update value of one table with summed value of related table by using intermediate table

Question: I have three tables A, A_B and B.
Since mySQL doesn't support many to many relationships, tables A and B are related to each other by intermediate table A_B.
Table A:    Table A_B:  Table B:
aId aCount  aId bId     bId bCo
1   10      1   1       1   4
2   15      1   2       2   5
3   20      2   1       3   6
            3   2       4   7
            3   4

Now I want to add bCount of each bId to each related aCount.
Desired result:
Table A:    Remark:
aId aCount  (Current aCount + all related bCounts)
1   19      (10 + 4 + 5)
2   19      (15 + 4)
3   32      (20 + 5 + 7)

My mySQL knowledge is too basic.
I can create a SELECT query which gives me a result table like i want table A to look like after update, but I can't create the update statement. Everything I tried led to syntax errors or undesired results.
I also had one statement which might had work, but it took way to long to execute. Now I'm just confused about what to do.
Desired Result looks like:
SELECT `aId`, aCount + SUM(`bCount`) as `aCount` from `A`
INNER JOIN `A_B` ON `A_B`.`aId` =   `A`.`aId`
INNER JOIN `B`   ON   `B`.`bId` = `A_B`.`bId`
GROUP BY `aId`;

Is an update like I want even possible with a single query or do I need multiple (performance wise)?
Can anyone help me out with an approach or with creating statements?
Answer: Try below: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0b6a287d41eed001710e94612c4228ba
select x.id,x.val,sum(tableb.val)+x.val as vals from
(select * from tablea inner join tableab on tablea.id=tableab.id1) x inner join
tableb on x.id2=tableb.id
group by x.id,x.val,id1

Output:
id  val vals
1   10  19
2   15  19
3   20  32

To update tablea:
UPDATE tablea INNER JOIN
(SELECT x.id, x.val, SUM(tableb.val) + x.val as vals FROM
    (SELECT * FROM tablea INNER JOIN tableab ON tablea.id = tableab.id1) x INNER JOIN
    tableb ON x.id2 = tableb.id
    GROUP BY x.id, x.val, id1)Z ON tablea.id=Z.id
SET tablea.val = Z.vals;

Comment: Thank you so much. SQL can easily break my mind already. Do not even speak about optimal statements. ;)
Comment: Actually I'm looking for an UPDATE statement so table a will look the same as the result of your or mine query after this statement is executed.


How to Implement Modal AJAX Form Pagination

Question: With the new Drupal8 Modal API I've been able to get a pretty powerful form going.
The form essentially does a POST to an API and displays some search results, which the user can filter. I want to paginate these results.
I'm having a lot of trouble wrapping my head around how this could be done, whether it's with custom ajax requests to increment some kind of counter that is used in the buildForm() function that does the API call, or something else. I've attempted to use Drupal's built in pagination but that doesn't seem like a feasible option as it doesn't even take route parameters.
A full example of the form can be seen at https://github.com/acbramley/embridge/blob/master/src/Form/EmbridgeSearchForm.php
Pagination seems to be broken in core through modals as well, when using a modal window to display (for example) the admin/content screen, pagination doesn't work.
Comment: I think pager would have to have the proper css/ajax classes in order for it to work with modal.
Comment: @IvanJaros thanks, I might give it a go with a preprocessor to add those classes in.
Answer: To implement this I went down a similar route as the "Add another item" functionality on field api fields. For reference, this is done in WidgetBase.php.
Firstly, I copied over a couple of static functions to get and set values inside storage:
<code>/**
 * {@inheritdoc}
 */
public static function getModalState(FormStateInterface $form_state) {
  return NestedArray::getValue($form_state->getStorage(), ['search_results']);
}

/**
 * {@inheritdoc}
 */
public static function setModalState(FormStateInterface $form_state, array $field_state) {
  NestedArray::setValue($form_state->getStorage(), ['search_results'], $field_state);
}
</code>
Then in buildForm() I added this to intialise the storage if it wasn't set yet.
<code>if (!static::getModalState($form_state)) {
  $field_state = array(
    'page' => 1,
  );
  static::setModalState($form_state, $field_state);
}
</code>
And then use the storage to get the page parameter for my search:
<code>$modal_state = static::getModalState($form_state);
$page = $modal_state['page'];
$search_response = $this->getSearchResults($page);
</code>
The crucial part of the implementation was separating the increment in the page variable from the ajax handler and putting it into the submit handler. So for the "Next" button:
<code>// Add "next page" pager.
$form['next'] = [
  '#type' => 'submit',
  '#value' => $this->t('Next'),
  '#submit' => ['::nextPageSubmit'],
  '#ajax' => array(
    'callback' => '::searchAjax',
    'wrapper' => self::AJAX_WRAPPER_ID,
    'effect' => 'fade',
  ),
];
</code>
And the submit handler
<code>/**
 * Submission handler for the "Next page" button.
 *
 * @param array $form
 *   The form.
 * @param FormStateInterface $form_state
 *   The form state.
 */
public function nextPageSubmit(array $form, FormStateInterface $form_state) {
  // Increment the page count.
  $modal_state = self::getModalState($form_state);
  $modal_state['page']++;
  self::setModalState($form_state, $modal_state);

  $form_state->setRebuild();
}
</code>
My ajax callback is then the same for searching, and paginating.
I also added a submit handler to the search button to reset the page back to 1.
The full source code for the form in this state can be found at https://github.com/acbramley/embridge/blob/2a561c9c388ccf715f93727cf136e50fc02163c9/src/Form/EmbridgeSearchForm.php
These code snippets are essentially the guts of what I needed to get the pagination working.


How to catch an ngrx action triggered from effect in UI component?

Question: I am new to the ngrx state management and I'm using @ngrx/store and effect of 6.0.1, suppose I would like to save a new member contact so I have following prepared:

member.effect.ts
@Effect()
memberContactCreate$ = this.actions$.pipe(
    ofType(MemberActions.MemberActionTypes.MemberContactCreate),
    switchMap((action: MemberActions.MemberContactCreate) => {
        return this.memberService.createMemberDetail(action.payload);
    }),
    map(
        (response) => {
            console.log('MemberContactCreate$ MemberContactCreate response: ', response);
            if (!response.didError) {
                return new MemberActions.MemberContactCreateSuccess(response.model as MemberDetailResponse);
            } else {
                return new MemberActions.MemberContactCreateFailure(response.errorMessage);
            }
        },
    ),
);

in my member contact component submit I will dispatch the create action
this.store.dispatch(new fromAction.MemberContactCreate(<MemberDetailRequest>this.memberDetailForm.value));

However, I would like to display a toastr or notification that if my member  successfully created from server, which is defined in my @Effect method, return the new action "MemberActions.MemberContactCreateSuccess", but how could I catch this action in my component as soon as it gets fired? I tried to do something like below and put it in my ngOnInit and thought it could be used like a subscription but it's not, in fact it fires everytime like page load or even I did not dispatch my memberContactCreate action...
this.store.select(fromSelector.getMemberCreateSuccess)
      .subscribe((stateSelector) => {
        console.log('getMemberCreateSuccess: ', stateSelector);
        setTimeout(() => {
          this.toastr('Hooray',
            'New contact has been created successfully!');
        }, 800);
        this.tableData = stateSelector;
      });

So how could my component interact with my triggered ngrx action just like subject/subscription? I've been reading a lot materials online but most of the example stops at "CreateSuccessful" action which just pushed an item into stored object list, there is no continued UI interaction after that...**So how should the component receive or catch the **MemberContactCreateSuccess/Failure action and let user know your action is success or not?
Answer: Personally I wouldn't handle the notifications within the component, but I would use @ngrx/effects to show/hide notifications. I briefly touch this in Start using ngrx/effects for this.
But if it's really necessary you can listen to your actions in your component just like you do in effects. You'll have to inject Actions in your component, use the  ofType
operator just like in the effects. The only difference is that you'll have to subscribe on the actions observable within the component (in ngrx/effects this is done for you).
Comment: thank you very much and I've read your article which is really helpful! I seemed have a little idea on my side but wasn't quite sure. For example, in your tutorial, effect CustomerActionTypes.Get you're returning a new action "GetCustomersSuccess" at the end, 1) should I perform the show modal/toastr inside the same effect? Maybe at the end in a new map or switchMap operation? 2) If so, should my effect become dispatch true or false? 3) Or maybe I should create a new effect on GetCustomersSuccess action and handle modal/toastr inside?
Comment: I am also very curious about your second suggestion which "listen to actions in component", do you have any sample code or tutorial on that? I would like to know where should I put my listener like in ngOnInit or somewhere else? Do I need to use ngOnDestroy to unsubscribe just like using subscription and subject?
Comment: I don't have any example code, but you can listen on these changes in `ngOnInit` and you should indeed unsubscribe.
it could something as `this.actions.pipe(ofType('FOO'), takeUntill(this.destroyed)).subscribe(() => this.showToastr);`. Let me know if you need some more details.


Why embedding linux on a docker image?

Question: I am new to docker, and from my understanding the biggest docker advantages are the facts that the containers are lighter and faster than VMs, that the docker-engine should be abstracting the Host OS, and that containers don't come with a guest OS as they depend directly on the docker-engine (which uses some components of Any Host OS).
Now, I have a requirement, to mount some docker containers on a linux machine (and windows server in the future). And these containers should have a Linux distro + some software installed.
Does it make sense in this case to have a linux distribution from within the docker? If so, what's the difference between a docker and a VM in this case? And if not, are there any reason that would make this a correct approach?
Answer: There is a spectrum of what isolation exists between apps. None, everything runs on one OS instance. OS provided, containers separate resources. Virtual machine, the hypervisor allows running multiple independent OS images.
A virtual  machine has to emulate hardware and go through system call overheads. With work towards hardware acceleration and OS driver support this overhead is less but not zero. The OS is a full install each time. But you get to install most any OS that runs on the platform.
OS containers are application processes. Highly isolated and sometimes bringing lots of libraries, but still processes. Lighter weight, but you have to choose the OS platform. Even if Docker can be on Window or Linux, there's lots of other OSes on x86 that are not available.
Big alien OS containers is not new. Solaris could run Linux branded zones years ago, in addition to Solaris zones.
Answer: This does muddy-the-waters doesn't it? I've seen full linux docker images from Oracle, Centos etc. and couldn't work out why you'd need them, as you say isn't the idea to get away from that sort of thing? In terms of differences, I'd prefer a full VM as you then get more data back about how it's running and more overall control. I say if you're doing lightweight containers do lightweight ones :)

Why embedding linux on a docker image?


Multi-site Subfolder Nginx Configuration

Question: I have Nginx server. Currently, I have two projects:

www.xyz.com -> /var/www/project/public; (This is working)
www.xyz.com/blog -> /var/www/blog; (Error: This webpage has a redirect loop)

How can I point both to the above folders. I tried the following code.
server {
 listen 80;
 server_name xyz.com;
 rewrite ^/(.*)/$ /$1 permanent;
 return 301 $scheme://www.xyz.com$request_uri;
}

server {
    listen   80 default_server;
    server_name www.xyz.com;
    rewrite ^/(.*)/$ /$1 permanent;
    root /var/www/project/public;
    index index.php index.html index.htm;

   location / {
            try_files $uri $uri/ /index.php?$query_string;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
    }

    location ~*  \.(pdf)$ {
            expires 30d;
    }

    location ~ \.(?:css|htc|js|js2|js3|js4)$ {
            gzip_vary on;
    }

    # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock

    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
   }

   location /blog {
        root /var/www/blog;
   }

   location ~ /blog/.+\.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME /var/www/blog$fastcgi_script_name;
    }
}

Comment: What works? What doesn't?
Comment: @gf_ www.xyz.com is working and
www.xyz.com/blog says "This webpage has a redirect loop".
Comment: Alright..so please put this into your question, so it makes sense and people are actually able to help you.
Answer: I think you should use a plus php section in location /blog:
location /blog {
  alias /var/www/blog;
  location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
  }
}

And you don't need location ~ /blog/.+\.php$.
Comment: I am getting 404 - Not found error. 2016/01/23 18:44:52 [error] 12447#0: *3 open() "/var/www/blog/blog" failed (2: No such file or directory), client: 188.8.131.52, server: www$
Comment: Removed /blog from /var/www/blog and now, it gives 502 Bad Gateway
Comment: Sorry, it's my fault - I don't check your `/blog` section. You should use `alias` instead of `root`. I think now will fine :)
Comment: Now it's saying, No input file specified.
Comment: 2016/01/23 21:13:17 [error] 20425#0: *214 FastCGI sent in stderr: "Unable to open primary script: /var/www/blogx.php (No such file or directory)" while reading response header from upstream,$
Comment: x.php? Can you update your question with full config?
Comment: I removed this line - fastcgi_pass 127.0.0.1:9000; and added fastcgi_pass unix:/var/run/php5-fpm.sock; and it worked. Please edit your answer and I'll accept your answer.
Comment: You wrote 127.0.0.1, I thought it's correct :)
But I'm glad on success :)


Decomposition for non symmetric matrix using left and right eigenvectors

Question: I have a few questions on decomposition of a matrix based on left and right eigenvectors.
Given a non-symmetric matrix,

Are its left and right eigenvectors always bi-orthonormal? Can the left and right eigenvectors be obtained from the singular value decomposition?
Can the matrix be decomposed in terms of its left and right eigenvectors?
Do either answers change if we assume that each eigenvalue has algebraic multiplicity equal to geometric multiplicity?

Either a direct answer to the question, or citations to references on this topics, both are welcome and appreciated!
Answer: For a square matrix $A$, $x$ is a right-eigenvector if $Ax = \lambda x$ for some scalar $\lambda$ and a left-eigenvector if $A^Tx = \lambda x$ for some scalar $\lambda$. $A^T$ denotes the transpose of $A$ (notably, not the Hermitian transpose in the case that $A$ or its eigenvectors are complex).
If $x$ is a right-eigenvector with $Ax = \lambda x$ and $y$ is a left-eigenvector with $A^Ty = \mu y$ with $\lambda \neq \mu$, then it necessarily holds that $x^Ty = 0$. I suspect that in your terminology, we might say that left and right eigenvectors are "biorthogonal, but not necessarily biorthonormal" (that said, this is the first time I remember seeing the term "biorthonormal").
A matrix can be completely decomposed in terms of left and right eigenvectors if and only if it is diagonalizable, which is to say that each eigenvalue has equal algebraic and geometric multiplicity. In this case, if $P$ is a matrix whose columns form a basis consisting of right-eigenvectors of $A$ (i.e. an $A$-eigenbasis), then the matrix $\Lambda := P^{-1}AP$ is diagonal with diagonal entries $\lambda_1,\dots,\lambda_n$ equal to the diagonal entries of $A$. Moreover, every matrix $P$ for which $P^{-1}AP$ is diagonal has columns consisting of an $A$-eigenbasis. If we let $Q = [P^{-1}]^T = [P^T]^{-1} = P^{-T}$, then we can "decompose" $A$ into the form
$$
A = PDP^{-1} = PDQ^T = \sum_{j=1}^n \lambda_j \, p_jq_j^T,
$$
where $p_1,\dots,p_n$ are the columns of $P$ and $q_1,\dots,q_n$ are the columns of $Q$. Notably, the columns of $Q$ are left-eigenvectors of $A$, as can be seen from the fact that
$$
D = D^T = [P^{-1}AP]^T = P^{T}A^TP^{-T} = Q^{-1}A^TQ,
$$
which means that the columns of $Q$ form an $A^T$-eigenbasis. The vectors $q_1,\dots,q_n$ (obtained in this particular fashion from $P$) form a "biorthonormal pair" with the vectors $p_1,\dots,p_n$ (i.e. $q_i^Tp_j$ is $0$ when $i \neq j$ and $1$ when $i = j$), as can be seen from the fact that $Q^TP = I$.
Comment: @ Ben Grossmann, thank you very much for taking the time to post such a detailed answer. I have one question, you made a statement `` A matrix can be completely decomposed in terms of left and right eigenvectors if and only if it is diagonalizable " -- could you provide a reference (or a proof) for the same?


If $E\subset \mathbb{R}$ is not bounded, then $E$ got no limit points in $\mathbb{R}$. Why?

Question: I have seen a lot of proofs that when a set is not bounded, called $E \subset \mathbb{R}$, then it got no limit points in $\mathbb{R}$. But I am still not convinced.
I was thinking about this set:
$$N = \left\{\frac{1}{n} : n \in \mathbb{N} \right\} \bigcup \left\{n : n \in \mathbb{N} \right\}.$$
Then $N$ is not bounded but $0$ is a limit point of $N$, right? Can someone explain me what am I doing wrong?
Comment: The statement is clearly false. In fact it's very easy to devise unbounded sets that contain $\textit{all}$ it's limit points.
Comment: To emphasize, if $E$ is unbounded then there is no guarantee of a limit point of $E$. $E$ may or may not have a limit point.
Answer: You are doing nothing wrong. The statement "when a set is not bounded […] then it got no limit points in $\mathbb R$" is false.
Comment: (+1) Take for example $E = \mathbb R$. It's unbounded and every point is a limit point.
Comment: Oh, thank you, now I see that what I was trying to prove was different than what I needed.
Comment: @Rodrigo I'm glad I could help.


Matlab color-coded plot of matrix

Question: Say I have a matrix like
A= [0 -50 2;
    0 -18 7;
    0  13 3;
    1 -50 3;
    1 -18 5;
    1  13 1;]

In reality, this matrix is larger but the first column is counting upwards while the second one is repetitive. Now I want to plot this colour-coded to get a result like e.g. this one, i.e. A(:,1) and A(:,2) are the x and y axes, respectively.
How would you do that? I've tried pcolor, imagesc and others but no luck so far. Sorry if this is a duplicate - I have searched stackoverflow and other websites but did not find anything that I could use.
Comment: That means you need to set up array axes as `x=unique(A(:,1))` and`x=unique(A(:,2))`, and then fill a matrix with the values from the 3rd column at appropriate places. This matrix you can plot using the two functions you tried.
Comment: No, that doesn't solve it. Are the first two columns always in the same order? That is, the y column visits each of the sample points in sequence for the first x coordinate, then again the same points for the second x coordinate, etc.? That makes it easier, you can just `reshape` the third column to the right sizes. If there are missing values, or if the order is not always preserved, then things get much more complicated.
Comment: `imagesc` and `pcolor` are the way to do it. Please show your code, or rather a minimal example that reproduces the problem, so that you can get help
Comment: When you say `A(:,2)` is the y axis, do you mean y axis is sampled at -50, -18 and -13 in your example?
Comment: @CrisLuengo yes, exactly.
Comment: I guess you mean `y=unique(A(:,2))`?
I just tried that:
    ```x=unique(A(:,1));
    y=unique(A(:,2));
    figure
    imagesc(x,y,A(:,3))```

But unfortunately this doesn't solve it.
Comment: "That is, the y column visits each of the sample points in sequence for the first x coordinate, then again the same points for the second x coordinate, etc.?" - yes, that is correct and there are no missing values.
Answer: The following code works even if the grid defined by the x and y columns has missing or repeated entries. In the first case the result will contain no colour for the missing values (just the axis background), and in the second case the values will be overwritten.
The code generates a matrix from the data where the missing entries are marked with NaN, and then displays it using pcolor, which ignores NaN entries. Because of how this function works, a column and a row need to be added to the matrix before displaying.
A = [0 -50 2;
     0 -18 7;
     0  13 3;
     1 -50 3;
     1 -50 5;
     1  13 1] % example. Entry (1,-50) is repeated, and entry (1,-18) is missing
[ux, ~, ind_x] = unique(A(:,1)); % unique values of x and indices to them
[uy, ~, ind_y] = unique(A(:,2)); % same for y
B = NaN(numel(uy), numel(ux)); % row is y, column is x
B(ind_y + size(B,1)*(ind_x-1)) = A(:,3); % linear indexing to fill the values into B
pcolor([B NaN(size(B,1),1); NaN(1,size(B,2)+1)]) % pcolor discards last row and column
axis xy
xticks((1:numel(ux))+0.5), xticklabels(ux)
yticks((1:numel(uy))+0.5), yticklabels(uy)
colorbar

Comment: Glad that it worked! Ask me anything you need and I'll try to explain, so it's not "magic" anymore :-)
Comment: I am having a really hard time understanding what magic you're doing there, mate, but it works perfectly - thank you so much!

Matlab color-coded plot of matrix


Add Vue.js event on window

Question: Vue.js allow apply event on element:

   <button @click="play()">Play</button>

But how to apply event on window object? it is not in DOM.
for example:

Drag me

in this example, how to listen mousemove event on window ?
Answer: You should just do it manually during the creation and destruction of the component
...
created: function() {
  window.addEventListener('mousemove',this.move);
},
destroyed: function() {
  window.removeEventListener('mousemove', this.move);
}
...

Comment: Thanks Jeff. The answer was helpful. Do I need destroyed if I have to add the listener in the main parent component on App level?
Comment: Destroying registered listener isn't required on the main component of your project unless it might be embedded in more complex setup with your vue application being just one part of the view. Thus, unregistering everything is best practice in all situations to make your code future proof.
Answer: Jeff's answer is perfect and should be the accepted answer. Helped me out a lot!
Although, I have something to add that caused me some headache. When defining the move method it's important to use the function() constructor and not use ES6 arrow function => if you want access to this on the child component. this doesn't get passed through to arrow functions from where it's called but rather referrers to its surroundings where it is defined. This is called lexical scope.
Here is my implementation with the called method (here called keyDown instead of move) included:
export default {
  name: 'app',
  components: {
    SudokuBoard
  },
  methods: {
    keyDown: function () {
      const activeElement = document.getElementsByClassName('active')[0]
      if (activeElement && !isNaN(event.key) && event.key > 0) {
        activeElement.innerHTML = event.key
      }
    }

  },

  created: function () {
    window.addEventListener('keydown', this.keyDown)
  },

  destroyed: function () {
    window.removeEventListener('keydown', this.keyDown)
  }
}

To be extra clear, The method below doesn't have access to this and can't for example reach the data or props object on your child component.
methods: {
    keyDown: () => {
      //no 'this' passed. Can't access child's context
      }

Comment: Your example isn't even using `this` in the `keyDown()` function. I doubt `this` is pointing to the component there anyways. If you actually need access to the component it is safest to bind the handler or use arrow function on registration. But in that case you have to save that bound/arrow function as a property of your component for use on removeEventListener() to prevent memory leak, too.
Answer: You can also use the vue-global-events library.
<GlobalEvents @mousemove="move"/>

It also supports event modifiers like @keydown.up.ctrl.prevent="handler".
Answer: This is for someone landed here searching solution for nuxt.js:
I was creating sticky header for one of my projects & faced issue to make window.addEventListener work.
First of all, not sure why but window.addEventListener doesn't work with created or beforeCreate hooks, hence I am using mounted.
<template lang="pug">
  header(:class="{ 'fixed-header': scrolled }")
    nav menu here
</template>

Comment: mounted / unmounted should be always preferred over created / destroyed to support SSR. I guess, this applied in your case, too.
Answer: I found that using window.addEventListener no longer worked as I expected with Vue 3. It appears that the function is wrapped by Vue now. Here's a workaround:
...
created()
{
  document.addEventListener.call(window, "mousemove", event =>
  {
    ...
  });
}
...

The important part is document.addEventListener.call(window, what we're doing is to take the unwrapped addEventListener from document and then call it on the window Object.
Comment: This does not seem to work in the Vue 3 CDN version

Add Vue.js event on window


Flipping a fair coin 3 times. T/F

Question: We flip a fair coin (independently) three times. Define the following two events:
A = "the number of tails is odd"
B = "the number of heads is even"
True or false: The events A and B are independent. (Recall that 0 is even.)
The answer is False, but I don't logically understand why, because if we know that if B occurs then we know that A also occurs. Does that means they are independent?
Answer: If the number of tails is odd, then since we are flipping the coin 3 times, the number of heads must be even.
Therefore, A is the same event as B and so they are very much not independent.
More generally, A and B are independent if and only if $P(A\cap B) = P(A)P(B)$.
In this scenario, since $A\cap B = A$, they are independent if and only if $P(A)= P(A)P(A)$ which is only the case when $P(A) = 0$ or $1$. However, with the fair coin neither of these is possible and so the two events are dependent.

Flipping a fair coin 3 times. T/F


ORACLE Database | remove tablespace with missing datafile

Question: I mistakenly remove the datafiles before I drop the tablespace. But the tablespace occupy a large size space. I need to remove it, any method?
It occur:
DROP TABLESPACE abc;

*
ERROR at line 1:
ORA-01116: error in opening database file 8
ORA-01110: data file 8: '/data/oradata/oracle/abc.dbf'
ORA-27041: unable to open file
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3

Answer: If your datafile is held inside a PDB.
You will have to follow the next commands :
SHUTDOWN ABORT
STARTUP
ALTER PLUGGABLE DATABASE $MyPDB OPEN;

On this last command it should fail with an ORA-01110 error.
And if you try ALTER DATABASE DATAFILE $datafileNumber OFFLINE DROP;
You will encounter an ORA-01516.
This is because you are trying to DROP a datafile on the CDB instead of the PDB.
To do this properly, you have to modify the session to target PDB :
ALTER SESSION SET CONTAINER=$MyPDB;

Now you can drop the datafile and open the database :
ALTER DATABASE DATAFILE $datafileNumber OFFLINE DROP;
ALTER PLUGGABLE DATABASE $MyPDB OPEN;

References
https://blogs.oracle.com/robertgfreeman/pdb-recovery-your-pdb-wont-open-because-a-datafile-is-missing
Comment: Thank you. "ALTER SESSION SET CONTAINER=" was what I was missing
Answer: You can follow the steps given here in this Oracle forum:

Follow the below steps : -
1) Shutdown abort
2) sqlplus sys/xxx as sysdba
3) Alter database mount
4) alter database datafile '' offline drop;
5) Alter database open
Comment: Is there any impact of other tablespace or database?
Answer: try to recover the datafile , identefy the name of the tablespace
select tablespace_name from dba_data_files where file_id =  8;

change the status of the tablespace to offline , so you can run the RMAN(recovery manager)
alter tablespace test offline immediate;

after that you have to run the RMAN to recovery the file.. for more info how to do that check this read this more about RMAN Burleson


Confidence intervals in probabilities for mixed effects logistic regression

Question: A while back I was helped to get correct confidence intervals for predicted probabilities in a logistic regression model: Correct interpretation of confidence interval for logistic regression?
Now, I want to do the same but for a mixed effects logistic regression. I use the glmer function in the lme4 package to build the mixed effects logistic regression. I can then use the predict function to get at probabilities; predict(glmer_model, newdata = new, type = "response").
But, in the non-mixed effects case, I was directed to predict(log_model, newdata = new, type = "link", se.fit = TRUE) to get the standard errors, the 95% intervals for the logits and transform back to probabilities. Problem is, predict.merMod does not take type = "link" and se.fit = TRUE as arguments.
I'm guessing this is not a problem of R syntax, but rather a deeper problem of standard errors for these models, but I would be grateful for any feedback between a fix to pointing out material for me to digest.
Comment: I'm using a model with a single fixed effect and a random intercept. I realize that the predicted probabilities and CI along the fixed effect will depend on the random intercept - in the graph, I'm intending to pick the mean intercept for presentation.
Answer: There are two issues you should be aware of here.

The only easy way (that I'm aware of) to compute the variances for individual predictions in a mixed model is to "condition on the estimates of the random effect variances", in other words to pretend that the variance of the intercept (in your case) is estimated without error. The authors of lme4 were too fussy to make this assumption, and there is no particularly easy way to way to do the calculation otherwise, so they simply declined to add an se.fit option.
If you are willing to make this assumption, then the calculation is not too hard: there's a section in the GLMM FAQ devoted to it. There are also several different packages (ggeffects, sjPlot, emmeans) that implement these computations. (Note that these recipes will generally give you confidence intervals on predictions at the population level, not for individual groups; there are some further technical difficulties with combining the uncertainties in individual group offsets and the uncertainty in the fixed-effect parameters, see here.)
If you really want confidence intervals on individual predictions without worrying about all this stuff, you can try a Bayesian MCMC approach (e.g. using the MCMCglmm or rstanarm or brms packages), which will give you samples incorporating uncertainty at all levels which you can then use to compute confidence intervals.

When computing population-level predictions on the probability scale you may want to worry about the bias caused by the nonlinear (back-)transformation of an estimate that also has among-group variability, e.g. see the last section of this emmeans vignette.


Gibbs sampling on the use of gamma distribution

Question: I am trying to reproduce a Gibbs sampling but some points are unclear to me. Let's assume a linear model of the following form $$y=x\beta + \epsilon$$
The prior distribution for the beta sensitivities is normal, while the prior distribution for the error term epsilon is gamma.
Can you provide me the intuition of this the prior gamma distribution (and not normal)?
Comment: Are you sure it's not $y \sim \mathcal{N}(x\beta, \tau)$ where for $\tau$ gamma prior is used..?
Comment: @Tim you are right, sorry i am completely new on this field and my background is limited. can you provide me further reference or explanation
Comment: I assume you would not use a gamma distribution here, because this would constrain $\epsilon$ to be $>0$, while $x\beta$ could be negative.
Answer: What you are describing is a simple regression model
$$ Y = X\beta + \varepsilon $$
that can be alternatively described as
$$
\begin{align}
\mu &= X\beta \\
Y &\sim \mathcal{N}(\mu, \tau)
\end{align}
$$
saying it differently, you estimate conditional mean of $Y$
$$ E(Y|X) = \mu $$
and assume normally distributed errors
$$ \varepsilon \sim \mathcal{N}(0, \tau) $$
what leads to $Y = \mu + \varepsilon$.
As about priors, normal distribution is a perfectly fine prior for $\beta$, but for precision parameter you need prior with positive support, since precision (as alternative to variance) need to be positive (there is nor such a thing as negative variance). Gamma fits this requirements and, moreover, is a conjugate prior for precision parameter of normal distribution, what makes computation easier since closed-form solution is directly available (see here for example using variance rather then precision).
This has nothing to do with Gibbs sampling, but it is about formulation of the model.
Comment: @samvoit4 yes, gamma is a conjugate prior for precision, inverse gamma is a prior for variance.
Comment: thanks for these references and for your expalanation, very helpful
Comment: Am I correct in thinking that the values that are sampled using the full conditional gamma distribution will be values of the precision? Will the empirical mean of these samples then estimate precision of the error term $\epsilon$ rather than the variance?


Javascript code appears in search results

Question: I use JavaScript in the body of a node with some PHP code. After I run cron.php and search on the site, I can see Drupal indexes the JavaScript code contained in a node.
How do I avoid Drupal indexes the JavaScript code?
Alternatively, how do I avoid Drupal indexes those nodes?
Answer: Since the javascript code is actually part of the node content it would take a bit of work to get it to be ignored.
An easier solution would be to use implement hook_db_rewrite_sql() and excludes from appearing in search results. Here is a great tutorial: Hiding content from Drupal's search system.
That said, there is a module out there that does this, Search Config. However it is marked as obsolete and not being maintained anymore, therefore you might want to think twice before using it.
For the record it does indeed work as designed, and works well! (I use it on my website with no problems).


Quadratic function with positive integral coefficients problem

Question: Here is the problem statement:

Let $f(x)$ is a quadaratic expression with positive integral coefficients such that for every $\alpha, \beta\; \epsilon\; \Re$, $\beta>\alpha$, $\int_\alpha^\beta f(x) dx>0$. Let $g(t)=f''(t)f(t)$ and $g(0)=12$, then
  (a)$16$ such quadaratics are possible (b) $f(x)=0$ has either no real root or distinct roots
  (c) minimum value of $f(1)$ is $6$ (d) maximum value of $f(1)$ is $11$

From the condition $\int_\alpha^\beta f(x) dx>0$, it is clear that $f(x)$ must always be positive or zero meaning that $f(x)=0$ will have either identical roots or no roots at all. So, option (b) can be eliminated.
Now let $f(x)=ax^2 + bx+c$. So $f''(x)=2a$ (obviously $>0$).
Therefore, $g(t)=2a(ax^2+bx+c) \implies 2ac=12 \implies ac=6$
Also the minimum value for $b$ is $0$ amd the maximum can be found out in this way :
Since $f(x)=0$ has either no or equal roots, then
$$  b^2-4ac\le 0
\implies b^2\le 4ac \implies b^2\le 24\implies b^2\le 16\implies b\le4$$
Therefore max value of b is 4. Now this means that there should be $5 \times 4=20$ quadratics possible ($5$ for $b$ and $4$ for the combination of $a$ and $c$). But the option (a) is given to be true. How then is it possible? Please provide a hint.
Moreover, please also provide a hint for finding the maximum and minimum values of $f(1)$.
Answer: Positive integer coefficients means $b\neq0$ so there are only $\textbf{4}$ possibilities for $b$.
For $f(1)$ I would work through an enumeration of the possible values of $a$, $b$ and $c$ and find which set gives the smallest value.


What must be correct dist_threads in heavy loaded SphinxSearch

Question: We have heavy load sphinx instance. Index is realtime, but we bulk insert data only once a week or so.
It runs on dedicated 12 core / 24 thread server.
Server have only sphinx installed.
Here is snipped of conf file:
index data_all
{
        type                    = distributed

        local                   = data_0
        local                   = data_1
        local                   = data_2
        local                   = data_3
}

searchd
{
        listen                  = 9305:mysql41
        listen                  = 9405
        log                     = /usr/local/sphinx/var/log/searchd.log
        query_log               = /usr/local/sphinx/var/log/query.log
        read_timeout            = 5
        max_children            = 2000
        pid_file                = /usr/local/sphinx/var/log/searchd.pid
        seamless_rotate         = 1
        preopen_indexes         = 1
        unlink_old              = 1
        workers                 = threads
        dist_threads            = 4
        binlog_path             =
}

Each local index is about 17 GB.
Most of the time server load average is less 2-3, but sometimes, the load average of the machine spike to 50 or so.
Currently we have very good response time, even during those spikes.
I am wondering about dist_threads. Do I need to keep it 4 (as number of local indexes) or I need to choose 24 (number of CPU threads). Or should I choose 1, because we have lots of queries in parallel anyway.
Answer: Short answer - setting must be equal to number of local indexes.
long ansewer - it depends :
In case of CPU bound workload, setting dist_threads to 1x the number of cores is advised (creating more threads than cores will not improve query time). In case of mixed CPU/disk bound workload it might sometimes make sense to use more (so that all cores could be utilizes even when there are threads that wait for I/O completion).


ftp process is not working properly

Question: I have a ssis package that does the following

copies a file from an ftp to a folder. overwrite if it exists
copy data to sql db
delete file from ftp

i have send email task if the ftp fails.
Scheduled this ssis in jobs.
I created a 2MB test file and ran the job. Works perfect!
now tried with a 500 MB file in the ftp. Works pefect when i run it from the IDE.
When i execute the job

ftp file is NOT copied
data is copied from existing file

no errors returned. package executed successfully. What's going wrong here?
Answer: Could be a silent timeout or such.
Have you considered zipping/unzipping to reduce the actual FTP duration and size?
Answer: the issue was
it was a directory permission issue. Sql server doesnot throw any error message when the ftp task does not copy.

ftp process is not working properly


Reference thesis for outliers in Likert scale data

Question: I have a data set that was collected in form of a Likert scale through questioners. Now I am trying to eliminate or identify outliers in my data. By far, from all that I have been able to search, outliers do not apply to my type of data since it is a Likert scale: the only possible values are between 1 and 5, and thus no possible value can be an outlier.
What I am looking for is any thesis stating that outliers do not apply since data is on a 5 point scale. So that i can cite that thesis in my thesis ?
Comment: What constitutes an "outlier" is up to you.  If I had a dataset of a hundred replies on a five point scale, and one is a 5 but the others are all 1s and 2s, I would likely characterize the 5 as an outlier.  More subtly--this happened to me once on a teaching evaluation--what if one respondent systematically misinterpreted the scale, writing "1" instead of "5," "2" instead of "4," and so on.  It's possible such responses wouldn't look out of place on any individual question, but collectively would be obviously very different. Thus, I strongly doubt there is any such thesis to cite.
Comment: Strictly a Likert scale is the sum of responses on several Likert items.  Using a scale from 1 to 5 for individual items is common, but if I understand correctly it is not part of any definition.
Answer: I agree with whuber. Instead of looking for outliers on restricted scales such as Likert, it is more convenient to identify suspicious responses. Three of the categories you should check carefully include:

Straight lining (respondents mark all answers with the same score).

Diagonal lining (scores follow a diagonal pattern, from the smallest score to the largest, or vice versa).

Alternating extreme pole responses (scores are assigned following a zig zag pattern like an ECG).

After identifying such cases, it is important to reason whether to include them in the subsequent analysis or to eliminate them. The nature of the measurement itself and the underlying theory help in this decision.
Answer: If you want a specific citation about the impact (or lack of impact) of outliers on Likert scales, could you provide more context regarding what the impact would be on and your sample size? For example, here is a paper on the impact of outliers in Likert scales on alpha. But, the answer will change depending on what kind of analyses you are running. Some analyses are more robust or sensitive to outliers.
As Pavel noted above, it is useful to try and determine the cause of outliers. However, in my experience, you often can have a reasonable guess, but not know the cause. The cause of the outlier and the impact on specific analyses will affect what you do with it. For instance, see here and here.
In my experience, if you don't have strong evidence to support removal (e.g., a lot of deviant responding), I have found it beneficial and reviewer-friendly to run analyses with and without the outlier(s) and report whether the results changed at all. It's more work re-running analyses, but ultimately it is transparent and saves you from trying to argue for either their inclusion or removal (often on grounds that make assumptions).


Decile Analysis for model comparison

Question: I am working on a simple classification problem (bank marketing response data) and trying various evaluation methods for multiple models to compare and understand the output.
And I was trying to do a decile analyses to compare logistic and random forest models and had one thing I wasn't completely sure.
From the logistic regression model output, we get the class probability of a customer to respond to a marketing communication.
Model output from random forest also provides some probabilities and those are basically mean of predicted outcome (probability of trees predicting 'response' for each customer).
And my question would be;
How would interpret those probabilities? (Could it be used as a measure of how confidently the model predicts? etc.)
Are those two probabilities comparable in the first place?
Comment: What is decile analysis?  The terminology implies that you are molesting the original continuous variable in some way, which would be a statistical no-no.  And note that the estimated probabilities are not measures of confidence in predictions.
Answer: Model comparison is essential to the development of a useful predictor. There a various aspects that come into play. What you are trying to predict, is customer response just like sales predictor.
Logistic regression and random forests both estimate posterior probabilities by Bayes rule
$
\hat{P}(R \mid M)
$
with $R$ being the response and $M$ the marketing communication action. See other question for an explanation of Bayes rule.
When comparing the predicted outcomes the first approach is generally to threshold your posterior probabilities
$\hat{P}(R \mid M) > \hat{P}(\neg R \mid M) \Rightarrow R=Response$
whereas
$\hat{P}(R \mid M) \leq \hat{P}(\neg R \mid M) \Rightarrow \neg R=No Response$.
You first compare the number of correct predictions on your training set from logistic regression with that of random forests. What are the fractions of correct predictions? The fraction of correct predictions is called the accuracy and it is binomially distributed. You can compare the performance of the two accuracies using a $\chi 2$ test for two independent samples.
The probabilities $\hat{P}(R \mid M)$ are estimates and they have an underlying distribution too. The computation of $\sigma^2 [\hat{P}(R \mid M)]$ is complex but they are known for some types of predictive classifiers (specifically for linear and quadratic discriminant analysis).
A final thing is that you are performing model comparison. A general strategy is to use n-fold cross validation for that. You don't want your models to overgeneralize so eventually the accuracy needs to be computed on an independent test set as well.

Decile Analysis for model comparison


How to add display button on check on checkbox

Question: I am displaying a list of week using CheckboxGroup, now i want if user check any checkbox, let say if user check the monday checkbox then it should display button in front of it. the design should look like this

CheckboxGroup code is here
Container(
                  // padding: EdgeInsets.only(right: 70),
                    child: Row(
                  children: [
                    Expanded(
                        child: SizedBox(
                            height: MediaQuery.of(context).size.height * 0.45,
                            child: ListTile(
                              title: CheckboxGroup(
                                  onChange: (bool isChecked, String label,
                                          int index) =>
                                      setState(() {
                                        day = isChecked;

                                      }),
                                  labelStyle:
                                      GoogleFonts.montserrat(fontSize: 15),
                                  labels: <String>[
                                    "Monday",
                                    "Tuesday",
                                    "Wednesday",
                                    "Thursday",
                                    "Friday",
                                    "Saturday",
                                    "Sunday",
                                  ],
                                  onSelected: (List<String> checked) =>
                                      ),
                            ))),
                    SizedBox(
                      width: 10,
                    ),
                    picktimebutton(),
                  ],
                ))

I am trying to do it like this but it shows this result

here is the code of  picktimebutton()
picktimebutton() {
    if (day == true) {
      return customButton(context, "Pick Time", (){},
      MediaQuery.of(context).size.width*0.3, 40.0);
    } else {
      return Padding(
          padding: const EdgeInsets.only(left: 70),
          child:
              Row(crossAxisAlignment: CrossAxisAlignment.center, children: []));
    }
  }

please help if anyone know how to do this
Answer: You can use the smart_select package from https://pub.dev
See below link
https://pub.dev/packages/smart_select
Comment: can u please explain more on it? i'm getting from it what i want


Load Testing RestFul Api , one time authorization

Question: I need to test wheather API is working or not and also to put load on each of them .
In post man I can do this but how to get it on jmeter.
I have an POST request from where i get access_tokken , then copy this token and put it in other API Header to get response from API .
Here is request json to get access :
Response 201 (application/json)Body  {
      "token_type":  "Bearer",
      "expires_in" : 3600,
      "access_token" : "generated_access_token"
  }

When run I am getting :
{"token_type":"Bearer","expires_in":3599,"access_token":"accesstoken value here"}

Need to get this access_token and pass it to other POST body to get reponse .
Answer: add JSON Extractor as a Post Processor for the request (child)
Variable Names access_token

JSON Path expression `$.access_token`

Match No. 1

Then use ${access_token} for its value ( or vars.get("access_token") in JSR223)
For Header of next request add the HTTP Header Manager under the second request as below:
Comment: Where to add ${access_token}.
Comment: when you need it, inside Body Data of next HTTP Request for example
Comment: I need to pass it as header manager , I added ${access_token} , but in request body it showing as it is .Request Headers:
Connection: keep-alive
Accept: application/json
Authorization: {access_token}
Content-Type: application/json
Content-Length: 64
Comment: For Header of next request add the `HTTP Header Manager` under the second request . see updated answer
Comment: Done but still the same .
Comment: Name:Authorization Value:${access_token}
Comment: This is what request is going after adding Header manager has you said :      POST http://myurl/api/app/sendotp

POST data:
{
      "mobile_no": 9867908264,
      "is_registered": 1
  }

[no cookies]

Request Headers:
Connection: keep-alive
Accept: application/json
Authorization: {accesstoken}
Content-Type: application/json
Content-Length: 64
Host: losapi.flexiloans.in
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_144)
Comment: do you seen that you have a typo? you use `accesstoken` instead of `access_token`
Comment: Done , Actually I forget to mentioned $ , but do i need to set header manager for each request or is there way to set one header manager for all other request.
Comment: In this specific request you want to take the value **after** first request so header manager must be after first request . so you can put it between the requests also
Answer: Firstly you extract access token to variable

Then you use this variable in proper header in other request/requests


Perl CGI using span to style data

Question: I'm a CGI/HTML/CSS newbie but not too bad with perl.  I'm writing a little CGI script and need to know how to change the style for certain elements of data on a line of text. I have adopted the Object Oriented approach to using CGI.
I'm iterating through an array of data and want to change the style of the variables on each line to something different from that standard style. My output for each line will look something like:
server=$hostName  appHost=$appHost  port=$port   cache=$maxCache

At the moment, I'm just doing:
print $cgi->br("server=$hostName  appHost=$appHost  port=$port   cache=$maxCache");

I'd ideally like each of the variables to be say, bold red (or preferably, a style that I've created in my CCS style sheet). I'm thinking that perhaps I need to use the span element but i've tried and failed miserably
Many thanks & regards
John
Answer: In your perl script, write:
print $cgi-br "server=$hostName  appHost=$appHost  port=$port   cache=$maxCache

";

(notice that the

 needs to be inside the string, not outside).
Then in your CSS file, put:
.myclass {
    color: red;
    font-weight: bold;
}

You link them together by having your perl script print the following in the  section of the HTML:
print $cgi-br "<link rel='stylesheet' href='URL of your CSS file'/>";

Comment: Wow!  That was quick!  I will try this out after a cup of tea and let you know how I get on. Many thanks for taking time out to answer this Barmar.  Regards

Perl CGI using span to style data


A beginner's attempt on image filtering

Question: My question might sound stupid but please understand i don't study in a university/college where a professor could give me decent help. I am self learning and its hardly been 3-4 months of coding for me. Hence i request patience from SO Users.
I am trying to code a simple filter function where i define a kernel, a 3x3 2D Array. I create another matrix load, where i would like to store the pixel values of my Image array. I face 2 Major problems. For the 1st problem i am completely confused and bewildered. I read this brilliant answer about How do I gaussian blur an image without using any in-built gaussian functions?, it mentions:

For pixel 11 you would need to load pixels 0, 1, 2, 10, 11, 12, 20,
  21, 22.
you would then multiply pixel 0 by the upper left portion of the 3x3
  blur filter. Pixel 1 by the top middle, pixel 2, pixel 3 by top right,
  pixel 10 by middle left and so on.

I would like to know for an IplImage with 3 channels how do i store the corresponding pixels [as mentioned in the link above] in my load matrix because what i am confused about is there are 3 values [R G B], so i am supposed to multiply what with what??
Also how to ensure that the Pixels do not go out of bounds? Since once we are near the edges of the image the pixel value might go out of bounds.
void filter(const IplImage *img)
{
    unsigned char kernel[][3]  = { 1,  2,  1,
                                   2,  1,  2,
                                   1,  2,  1 , };
    unsigned char load[][3] = { 0 };
    int rows=img->height,cols=img->width,row,col;
    uchar* temp_ptr=0 ;

    for( row = 0; row < rows; ++row)
    {

            for ( col = 0; col < cols; ++col)
            {
                CvPoint pt = {row,col};
                temp_ptr  = &((uchar*)(img->imageData + (img->widthStep*row)))[col*3];

            }
    }

}

Comment: If you look at this (interesting) and active question: http://stackoverflow.com/questions/7860575/optimized-float-blur-variations I think you will find that it has many similarities.
Comment: also look up convolution matrix's and take a quick look around processing's website, they have tutorials (for processing obviously), but they're very well written and will transfer easily into C++
Answer: To your RGB question: You apply the kernel separately to each channel. That is, you basically treat the three channels as three independent monochrome pictures and blur each one.
Ensuring that your pixels don't go out of bounds in principle is simple: When you access the pixel, you first test whether the pixel would be out of bounds, and if so, don't access it. However the interesting question is what to do instead. One possibility would be to just not apply the filter to the border points where the kernel would exceed the image, but that would mean to leave an unblurred border (unless you can afford to lose a one pixel border, in that case this would probably be the best solution). Another solution would be to assume a certain color for outside pixels (e.g. white). The third option, which I think is the best here, is to just not use those points but work with the reduced kernel only containing the in-bounds pixels of the mask. Note that you need to adapt normalization factors as well in this case.
And BTW, are you sure your kernel describes a blur? I would have expected the middle value to be the largest for a blur.
Comment: Another option for out-of-bounds pixels is to substitute the closest in-bounds pixel value.
Answer: 1) Filtering an image by a linear system is equivalent to what we call a convolution. It is really easy to realize, it is a term by term multiplication of your image with the symmetric kernel (central symmetry). If your kernel is symmetric, as it is the case for a gaussian kernel then it is a simple term by term multiplication.
You move your kernel over the image and as you say there can be out of bounds exceptions...
Two options, or you don't filter the borders (it's mostly the case) or you interpolate the result (it may be too difficult if you are starting in image processing so, let's do something simple).
The algorithm will look like, notice that the col and rows start at 1 and end at width-1 and height-1 to avoid out of bounds problems... If you have a larger kernel, you would do the same with width-kernelSize/2 kernelSize is an odd number 3x3,... 7x7... etc.
kernel[9] = {1/13, 2/13, 1/13, 2/13, 1/13, 2/13, 1/13, 2/13, 1/13};

for(row=1;rowheight-1;row++)
{
     for(col=1;rowwidth-1;col++)
     {
           img->data[row*img->width+3*col+0] = ... ; //B Channel
           img->data[row*img->width+3*col+1] = ... ; //G Channel
           img->data[row*img->width+3*col+2] = ... ; //R Channel
      }
}

Instead of the ... or you use a loop to compute the convolution and then replace the ... by the result of the loop (which is the most flexible solution if sometimes you want a larger kernel (ex 9x9), or you write by hand :
double convB = kernel[0]*img->data[(row-1)*img->width+3*(col-1)+0]
+ kernel[1]*img->data[(row-1)*img->width+3*(col)+0]
+ kernel[2]*img->data[(row-1)*img->width+3*(col+1)+0]
+ kernel[3]*img->data[(row)*img->width+3*(col-1)+0]
+ kernel[4]*img->data[(row)*img->width+3*(col)+0]
+ kernel[5]*img->data[(row)*img->width+3*(col+1)+0]
+ kernel[6]*img->data[(row+1)*img->width+3*(col-1)+0]
+ kernel[7]*img->data[(row+1)*img->width+3*(col)+0]
+ kernel[8]*img->data[(row+1)*img->width+3*(col+1)+0];

2) For G and R channels you use the same with +1 and +2 instead of +0 in the brackets [] to address the correct memory location;
3) You should use a Kernel which is normalized, that's why I used value x 1/13 (which is the sum of all the values), if you want a normalized result on your image (with normalized intensities).

A beginner's attempt on image filtering


How to create a function to test normality of each variable

Question: I am trying to build a function that iteratively returns i) JarqueBera test stat, ii) JarqueBera pvalue, iii) the slope, intercept and determination coeff of the probplot, and iv) the probplot itself. All is intended to be returned for a single variable at a time.
def normality(c):
    JB_test_stat = ss.jarque_bera(c)[0]
    JB_pval = ss.jarque_bera(c)[1]
    probplot_slope = ss.probplot(c, plot = plt)[1][0]
    probplot_interc = ss.probplot(c, plot = plt)[1][1]
    probplot_r = ss.probplot(c, plot = plt)[1][2]
    return(print("Skewness:",c.skew(),"\nExcess kurtosis:",c.kurt(),"\nJarque-Bera stat:",JB_test_stat," pvalue:", JB_pval,"\nSlope:",probplot_slope,"Intercept:",probplot_interc, "r:",probplot_r,"\n"))

Unfortunately, when I call the function on my dataframe[numeric_cols], being numeric_cols a list,
for c in numeric_cols:
    normality(df[c])

I get all the numeric results in the return statement correctly, but at the bottom a single probplot with all variables plotted in a messy way, whereas what I expect is to get the numerical results for each variable along with its corresponding probplot.
Skewness: 0.1004187952160102
Excess kurtosis: -0.543819517693596
Jarque-Bera stat: 7.593972235734294  pvalue: 0.022438296430201454
Slope: 4.3135147782152465 Intercept: 25.5 r: 0.9947611456706487
Skewness: -0.1560130144763728
Excess kurtosis: -1.2824901951466612
Jarque-Bera stat: 38.56183464454786  pvalue: 4.23061985443951e-09
Slope: 11.492550446207257 Intercept: 19.535714285714285 r: 0.9668502992894236
Skewness: 0.2347601433103727
Excess kurtosis: -1.242639192300385
Jarque-Bera stat: 39.0662449724179  pvalue: 3.287552452491127e-09
Slope: 11.545683807955731 Intercept: 15.714285714285714 r: 0.9647448407831439
Skewness: 0.24353437856100904
Excess kurtosis: -1.1969521906230485
Jarque-Bera stat: 36.98912338336009  pvalue: 9.287822622106034e-09
Slope: 1013.985374629207 Intercept: 1411.4436090225563 r: 0.9682492605786011
Skewness: 2.837876986150242
Excess kurtosis: 9.516628330654008
Jarque-Bera stat: 2675.4455000782764  pvalue: 0.0
Slope: 2.6057664781688454 Intercept: 1.8533834586466167 r: 0.7776054895177505
Skewness: 2.406153102778617
Excess kurtosis: 7.002529753885085
Jarque-Bera stat: 1573.6596724989513  pvalue: 0.0
Slope: 1.714847443415902 Intercept: 1.287593984962406 r: 0.8152919114915671
Skewness: 0.9337529310147361
Excess kurtosis: 0.45862734243889847
Jarque-Bera stat: 81.22389376608798  pvalue: 0.0
Slope: 605.3354149443196 Intercept: 717.75 r: 0.9550404156079808
Skewness: -3.030640857636996
Excess kurtosis: 15.686541621050898
Jarque-Bera stat: 6154.761075129672  pvalue: 0.0
Slope: 11.37955609488042 Intercept: 77.82387218045113 r: 0.8711740556551902
Skewness: 6.398317104228115
Excess kurtosis: 49.10097819497357
Jarque-Bera stat: 56029.69126113364  pvalue: 0.0
Slope: 0.41431397013222515 Intercept: 0.1917293233082707 r: 0.48503363895959983
Skewness: 6.204252341215679
Excess kurtosis: 47.28662289867727
Jarque-Bera stat: 52010.755388690835  pvalue: 0.0
Slope: 0.4947086253584861 Intercept: 0.23496240601503762 r: 0.5050004904368586
Skewness: 2.06633193738682
Excess kurtosis: 5.770784034742405
Jarque-Bera stat: 1098.0175308306793  pvalue: 0.0
Slope: 0.12821997057404685 Intercept: 0.11328947368421052 r: 0.8619773533976459
Skewness: 2.9189857433086495
Excess kurtosis: 16.837230233306762
Jarque-Bera stat: 6909.724155123523  pvalue: 0.0
Slope: 0.07805612907589729 Intercept: 0.07265037593984962 r: 0.8632361803763113
Skewness: 1.2633082232077495
Excess kurtosis: 1.5265390704578943
Jarque-Bera stat: 190.6495836394772  pvalue: 0.0
Slope: 2.09821120102269 Intercept: 2.1146616541353382 r: 0.9211028014650718
Skewness: 3.091346622737553
Excess kurtosis: 8.530683362863476
Jarque-Bera stat: 2421.371001114453  pvalue: 0.0
Slope: 0.16657862407594715 Intercept: 0.09022556390977444 r: 0.5658043763386988

How could fix it?
Thank you all in advance
Comment: Why would you return a `print` statement?? Also, please add your expected output and an example of the current output.
Comment: What about now man? I still don't know pretty much how to use the posting interface
Comment: You mean you want a separate figure for each? Or something else? The question is still not very clear.
Comment: Exactly, one probplot figure for each variable.
Answer: Just add a plt.figure() in your function, so that every call to the function opens a new figure.
On a completely different note, using return(print('stuff')) is superfluous. If you really want to print the results then just use print with no return.
It would be more pythonic and generally better practice to return the values you're currently printing, and then print them externally:
def normality(c):
    JB_test_stat = ss.jarque_bera(c)[0]
    JB_pval = ss.jarque_bera(c)[1]
    probplot_slope = ss.probplot(c, plot = plt)[1][0]
    probplot_interc = ss.probplot(c, plot = plt)[1][1]
    probplot_r = ss.probplot(c, plot = plt)[1][2]
    return c.skew(), c.kurt(), JB_test_stat, JB_pval, probplot_slope, probplot_interc, probplot_r

for c in numeric_cols:
    c.skew(), c.kurt(), JB_test_stat, JB_pval, probplot_slope, probplot_interc, probplot_r = normality(df[c])
    print("Skewness:",c.skew(),
          "\nExcess kurtosis:",c.kurt(),
          "\nJarque-Bera stat:",JB_test_stat,
          " pvalue:", B_pval,
          "\nSlope:",probplot_slope,
          "Intercept:",probplot_interc,
          "r:",probplot_r,"\n")


A better way to define $\bigcap S$?

Question: In books on set theory $\bigcap S$ is defined for $S \neq \emptyset$ by taking some arbitrary member $x \in S$ and separating those elements from $x$ that belong to every memebr of $S$. It leads to a problem of what to do if $S = \emptyset$. This case is handled separately by defining $\bigcap S = \emptyset$.
Why don't they just define $\bigcap S := \{x \in \bigcup S |$ $x$ belongs to every member of $S\}$. Then if $S$ is empty, $\bigcup S$ will be empty and there is nothing to separate from it. If $S$ is not empty, then the result is the same as if we used the previous definition.
The only drawback of the new definition is that we need the axiom of union to get $\bigcup S$. But it is a standard axiom.
Comment: The problem is that the simple characterization $x\in \bigcap S\iff \forall s\in S\colon x\in s$ does not hold any more; it is replaced by the less handy $\iff (\exists s\in S\colon x\in s)\land (\forall s\in S\colon x\in s)$. Btw, I usually see $\bigcap \emptyset $ left undefined instead of specifically defined to be empty. - The latter has ugly consequences such as $S\subseteq S'\not\rightarrow \bigcap S'\subseteq \bigcap S$.
Comment: Somewhat related:
http://math.stackexchange.com/questions/6613/unary-intersection-of-the-empty-set, http://math.stackexchange.com/questions/370188/empty-intersection-and-empty-union,
http://math.stackexchange.com/questions/151924/unnecessary-property-in-definition-of-topological-space and other posts shown there among linked questions.
Comment: Usually the sets being considered live in some universe $X$. It's natural to have "empty intersection" = "everything (considered)". So $\bigcap ∅ = X$. If there is no other universe, then $\bigcap ∅$ is universal class which is not a set.
Comment: Another problem with $\bigcap \emptyset = \emptyset$ is we would no longer have $\bigcap (A \cup B) = \bigcap A \cap \bigcap B$.
Answer: I don't think it's ever correct to define $\bigcap \emptyset=\emptyset$.  One always expects that taking an intersection of more things should get you a smaller result.  (The set of big red ugly expensive things is a subset of the set of big things.)  That is, $$\def\S{\mathscr S}\text{if $\S\subset \mathscr T$ then $\bigcap \mathscr T\subset \bigcap \S$}.$$  But having $\bigcap\emptyset = \emptyset$ would spoil that.  So that answers one of your questions, which is why we don't do that.   I find it hard to believe that any serious text for set theory would do as you say and make $\bigcap \emptyset = \emptyset$.
In set theories with a universal set $V$, one takes $\bigcap \emptyset= V$ for that reason; then we have $\emptyset\subset \S$ for all $\S$ and also $\bigcap \S \subset \bigcap \emptyset = V$, as we would hope.  In set theories without a universal set, most notably ZF, one leaves $\bigcap \emptyset$ undefined.
In ZF there is no axiom of intersection that corresponds to the axiom of union; one uses the specification axioms to define intersections.  Recall that this means that for any predicate $\Phi(x)$ and any set $X$ we can construct $\{x\in X\mid \Phi(x)\}$, the subset of $X$ for which $\Phi$ holds.  Let's see how this goes in this case.  We want to take the set of all $s$ that are in every $S$ that is an element of $\S$.  But to use the specification axiom schema, we can't take this condition by itself; we have to attach it to some set $X$ and use it to select the desired subset of $X$.
So in ZF the best we can do is $$\{x\in X\mid \forall S\in \S . x\in S\}$$  for some set $X$, which we might agree to abbreviate as  $$\def\S{\mathscr S}\bigcap_{(X)}\S.$$   This is the subset of $X$ whose elements are in every element of $\S$, or we might call it the intersection of $S$ "taken relative to $X$".  If there were a universal set $V$ then we could take the intersection relative to $V$ and be done (and note that then $\bigcap_{(V)}\emptyset = V$) but ZF has no universal set.
But it should be clear (or you can take it as an exercise) that no matter what $X$ is, if $S\in \S$, we have $$\bigcap_{(X)}\S \subset \bigcap_{(S)} \S.$$  From this it immediately follows that for any $S, S'\in \S$, then $$\bigcap_{(S)}\S = \bigcap_{(S')}\S$$ so it doesn't matter which element of $\S$ we take the intersection relative to.
This shows that when $\S$ is nonempty, there is a unique maximal relative intersection of the elements of $S$, which we can abbreviate as simply $\bigcap \S$.  And since $$\bigcap_{(X)}\S = X\cap \bigcap \S$$ the relative intersections weren't getting us anything interesting, and we lose nothing to forget about them.  In particular it doesn't matter if we take $X = \bigcup \S$ as you suggest, because the intersection is the same regardless.  So we may as well take the simpler definition.
On the other hand, when $\S=\emptyset$, we have $\bigcap_{(X)} \S = X$, which is rather useless, so we lose nothing to forget about it.
Comment: Carl Mummert and Arturo Magidin agree in http://math.stackexchange.com/questions/6613/unary-intersection-of-the-empty-set%E2%80%8C%E2%80%8B that some authors do make $\bigcap\emptyset=\emptyset $, to my amazement.
Comment: Another potential problem with defining $\bigcap \emptyset=\emptyset$ would be no longer having $\bigcap (A \cup B) = \bigcap A \cap \bigcap B$.

A better way to define $\bigcap S$?


How to print a field in node.tpl.php without labels or markup?

Question: In Drupal 7, you can render a field in a tpl.php file like this:
But that prints it out with it's label and HTML. Is there a way to get just the raw value of the field.
I know you can do the following:

Override the field markup in the field.tpl.php file (or field--FIELDNAME.tpl.php)
Turn off labels in the admin interface
Use a module like Fences to control mark up in the admin interface.

However, all of those involve extra steps. I was wondering if there is a way to do it directly in the node.tpl.php file. That way, all the changes are contained in a single place. (Plus if you change themes to one that requires the labels, you have to go back in the admin interface and turn them back on).
Answer: If you just want the value of a given field, it will be in the $node object in your node.tpl.php file (or node--type.tpl.php).
Normally it's under something like:
$node->field_name['und'][0]['value']

Comment: It's widely used, but not good practice.  The best way is to use the field api:

    $node = node_load($nid);
    $field = field_get_items('node', $node, 'field_name');
    $output = field_view_value('node', $node, 'field_name', $field[$delta]);

(Source: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way )

Or use the entity api module and use their wrappers.
Comment: Is 'und' good practise to use? I think I read somewhere that is bad, but I can't find the source.
Comment: @big_smile, I've seen it used quite a bit, it's a language indicator, there was a discussion of it at http://drupal.stackexchange.com/questions/25839/best-practice-for-drupal-7-language-key-for-und-in-hook-form-alter
Comment: The `LANGUAGE_NONE` constant is preferred; the value isn't likely to be changed from 'und', but magic vars should be avoided wherever possible. You should also check that the field value has been sanitised before output
Comment: Or you could use `$node->field_name[$node->language][0]['value']`
Answer: You're on the right track!
Rather than a node template file though, the individual markup of a field is controlled by its field.tpl.php file. You can control the display of a field in a very granular way by making a custom one - copy your theme's default implementation of it, name the copy field--field-name.tpl.php, and remove all the excess markup.
Comment: The way I always do it is this: tpl files for presentation/markup, functions in the template for logic (or for cases where you need to pass in a variable that wouldn't be available in the template file).
Comment: I think this is the right answer in this case as its theme specific and doesn't involve too many function calls in the template file which always looks hacky to me.
Answer: You might want to try
<?php print render($content['field_your_field']); ?>

in node.tpl.php
combined with context and entity view modes modules
or simply modify the display settings of the field in the content type configuration
Answer: If you are in the node template you can load the field, then get the content from the loaded field. Check out the field_get_items documentation for more info.  In short it returns the values you want in the current language.
$field_name = 'your_field_here';
$field= field_get_items('node', $node, $field_name);
print $field[0]['value']

should do it.  It will return an element for each item if it is a multi value field.  They can be accessed via $field[$key]['value']
Answer: wolffer-east's answer satisfies the original question goals of:

Printing a field
Doing it in a single file (so everything is in one
place).

However, the code is quite complex for a node.tpl.php file which are only supposed to contain simple PHP statements.
So in the end, I reworked it as follows. In my template PHP file, I put the following:
function print_field($field_name) {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);
print $field[0]['value'];
}

This is the same as wolffer-east, except it loads the node.
In my node file, I can then use the following:
<?php print_field('field_body_text') ?>

This renders out the field without any labels and HTML, but still clean.

A more advance version is this:
In template.php
    function print_field($field_name, $format = 'safevalue') {
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);

if ($format = 'url') {
    print file_create_url($field[0]['uri']);
} else {

print $field[0][$format];
}
}

In node.tpl.php
You can swap 'filename' with any of the following:

value: Prints field without any extra HTML for paragraphs and line
breaks
safe_value: Prints field HTML for paragraphs and line breaks
filename: Prints field's filename uri: Prints field's path in
public:// format[*]
url: Prints field's path in traditional URL format[*]
alt: Prints field's alt value[*]
title: Prints field's title value[*]
width: Prints field's width value[*]
height: Prints field's height value[*]

[*] only applies to fields that have files/images
The only downside is that it displays the following error message:

Notice: Undefined index: safevalue in print_field() (line 16 of template.php)

I am not sure how to fix this error message, but I guess it is a separate question.


Core PowerShell commands missing when remoting into Exchange 2016 configuration

Question: I'm running into an issue where simple commands (Get-Module, for example) are not present when remoting into an Exchange 2016 server.
The command I'm running is:
Invoke-Command -ConfigurationName Microsoft.Exchange -ConnectionUri http://SERVERNAME/powershell -Authentication Kerberos -Credential $cred -ScriptBlock { Get-Module }

The result is:
The term 'Get-Module' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (Get-Module:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : SERVERNAME

Other core commands, like Get-Command, work as expected - including Exchange commands (Get-Mailbox, etc).
The only change I've made is changing PSLanguageMode within IIS for the Powershell site to be 'FullLanguage'. Reversing this change (and restarting applicable pools and sites) does not affect the result.
I don't regularly deal with Exchange or PowerShell, so any advice is appreciated.
Answer: Exchange servers were designed to be constrained endpoints.  The session configuration Microsoft.Exchange is a bare bones configuration schema with limited exposed methods.  As Exchange servers are exposed to the outside world the designers are obsessed with security.  The command you're trying to use is trivial in your existing context as you specified the environment you wanted with your instantiation.
It is strongly recommended that you work within the existing session configuration (for remote) or run code locally for access to all methods.  However, if your risk tolerance affords it you can create a custom session configuration schema using information you find here.
Comment: I'm using the Exchange profile due to the larger script using Exchange commands. With missing core commands some operations as part of the script become difficult. `Get-Module` is just one of the known failing commands.

I'll test the solution given above. It looks like it's not the greatest for security, however it looks like it would solve the issue at hand. I'll mark this as the accepted answer provided it works. Thanks :D
Comment: Still encountering the same issue. Things like Where-Object and the like are also missing from the command set.
Comment: You missed the point.  Perhaps this will help clarify:  https://blogs.msdn.microsoft.com/dvespa/2011/07/20/where-or-where-has-my-where-object-gone/
Comment: It looks like my edit didn't make it through. I later revised my previous comment to say that I'll have to update my scripts to work around the limitations. Much like the article you've linked.