Feature Importance/Impact for Individual Predictions

Question: At the model level, to assess predictor contribution/importance we can use:

Model Specific Techniques – e.g. purity (Gini Index) for a tree-based model, model coefficients where applicable etc.
Model Independent Techniques – e.g. Permutation Feature Importance, Partial Dependence etc.

What this does not convey is for a particular prediction (say a binary classification that provides a 92% probability of membership of class 1) what predictors were most "influential" in producing that prediction.
Having thought about this problem a little, it seems to me there are a few approaches that could be taken:

Model Specific Techniques – e.g. coefficients of applicable linear models, techniques such as described here for say XGBoost (https://medium.com/applied-data-science/new-r-package-the-xgboost-explainer-51dd7d1aa211)
Model Independent Techniques – e.g. some kind of "perturbation method" similar to Partial Dependence to understand how the prediction changes when we perturb the predictor and perhaps model that?, or techniques like LIME described in this paper (https://arxiv.org/pdf/1602.04938.pdf and https://github.com/marcotcr/lime), a modified Permutation Importance technique?

It seems to me the most valuable approach would be a model independent technique given the somewhat "black-box" nature of many algorithms, and providing an ability to interpret novel and new algorithms and techniques.
One naive method, described here (http://amunategui.github.io/actionable-instights/index.html) is to take each predictor, "neutralise" its impact by say imputing the "population" mean, and run the prediction again getting a difference between the original prediction and the neutralised version providing an importance measure. This seems a special case of a kind "perturbation" method hinted at above. A couple of flaws I see in this are that 1) it seems to imply that a prediction that has the "mean" (or equivalent) of each feature necessarily is a "middle" prediction perhaps, and 2) that features that are "means" (or equivalent) are necessarily non-impactful?
More generally any technique would have to account for:

How to handle different data types (numerical, categorical etc.)
How to handle missing data
How to handle conditional importance perhaps (i.e. that predictors may only be important in pairs etc.)
Computational efficiency (is it really practical to run a prediction $p$ times where $p$ is the number of predictors, or for a perturbation method $kp$ where $k$ is the number of predictions per predictor etc.)

With those loose and perhaps incorrect thoughts on the matter laid down, I wonder what approaches to the problem people are aware of, have considered, have used, would advise etc.?
Answer: The topic you are addressing is known as model explanation or model interpretation and quite an active topic in research. The general idea is to find out, which features contributed to the model, and which not.
You already mentioned some popular techniques, such as the Partial Dependence Plots (PDP) or LIME. In a PDP, the influence of a features' value to the model output is displayed by creating new instances from the data that have a modified feature value and predict them by the model. LIME creates a local approximation of the model by sampling instances around a requested instance and learning a simpler, more interpretable model.
In the naive method you described, the impact of a feature is neutralised by setting it to the population mean. You are absolutely right, that this is not an appropriate method, as the prediction of the mean value is not probably not the mean prediction. Also, it does not reflect the feature distribution and does not work for categorical attributes.
Robnik-Sikonja and Kononenko [1] addressed this problem. Their basic idea is the same: the prediction difference between the unchanged instance, and an instance with a neutralised feature. However, instead of taking the mean value to get rid of the features' impact, they create several instance copies, each with a different value. For categorical values, they iterate over all possible categories; for numerical values, they discretise the data into bins. The decomposed instances are weighted by the feature value frequency in the data. Missing data can be ignored by using classifiers that can handle it, or imputing it, e.g. by setting the values to the mean. Conditional importance has been addressed in a second publication by Strumbelj et al [2]. They extended the original approach by not only creating decomposed instances of a single feature, but observed how the prediction changes for each subset of the power set of feature values. This is of course computationally very expensive (as they mention themselves and tried to improve by smarter sampling in Strumbelj and Kononenko [3]).
By the way: for binary data, this problem becomes much easier, as you just have to compare the prediction between attribute is present and not present. Martens and Provost [4] discussed this for document classification.
Another approach for finding groups of meaningful features has been proposed by Andreas Henelius in [5] and [6]. The idea of his GoldenEye algorithm is to permute the data within-class and feature group. Imagine a data table where each row represents an instance and each column is a feature. In each column, all rows that share the same class are permuted. Features are grouped, i.e. permuted together. If the classification on the permuted data is very different (worse) than the original data, the current grouping did not reflect the true grouping. Check out the publications, its better described there. This approach becomes computationally expensive, too.
I'd also like to refer to the publications by Josua Krause [7], [8]. He developed interactive visual analytics workflows for the analysis of binary instance-based classification problems, including an enhanced PDP. They are well-written and an interesting read.

[1] Robnik-Šikonja, M. (2004, September). Improving random forests. In European conference on machine learning (pp. 359-370). Springer, Berlin, Heidelberg.
[2] Štrumbelj, E., Kononenko, I., & Šikonja, M. R. (2009). Explaining instance classifications with interactions of subsets of feature values. Data & Knowledge Engineering, 68(10), 886-904.
[3] Štrumbelj, E., & Kononenko, I. (2014). Explaining prediction models and individual predictions with feature contributions. Knowledge and information systems, 41(3), 647-665.
[4] Martens, D., & Provost, F. (2013). Explaining data-driven document classifications.
[5] Henelius, A., Puolamäki, K., Boström, H., Asker, L., & Papapetrou, P. (2014). A peek into the black box: exploring classifiers by randomization. Data mining and knowledge discovery, 28(5-6), 1503-1529.#
[6] Henelius, A., Puolamäki, K., Karlsson, I., Zhao, J., Asker, L., Boström, H., & Papapetrou, P. (2015, April). Goldeneye++: A closer look into the black box. In International Symposium on Statistical Learning and Data Sciences (pp. 96-105). Springer, Cham.
[7] Krause, J., Perer, A., & Ng, K. (2016, May). Interacting with predictions: Visual inspection of black-box machine learning models. In Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems (pp. 5686-5697). ACM.
[8] Krause, J., Dasgupta, A., Swartz, J., Aphinyanaphongs, Y., & Bertini, E. (2017). A Workflow for Visual Diagnostics of Binary Classifiers using Instance-Level Explanations. arXiv preprint arXiv:1705.01968.
Comment: +1 The 2014 Štrumbelj & Kononenko paper does not get remotely the recognition it deserves. Their game-theoretic approach is like "*WOW!*"
Comment: What a brilliant answer, and is in line with many of my thoughts on this topic. Thank you very much for your time and expertise. The references are particularly useful.
Answer: Two other methods worth mentioning here are:
1) Lundberg & Lee's SHAP algorithm, an extension of Štrumbelj & Kononenko's game theoretic approach that they claim unifies LIME and a number of other local importance measures; and
2) Wachter et al.'s counterfactual method, based on generative adversarial networks.
Both methods have advantages and disadvantages. SHAP is very fast and comes with a user-friendly Python implementation. Unfortunately, however, it always compares points against the data centroid, which may not be the relevant contrast in some cases. Also, like LIME and a number of other algorithms, it assumes (or enforces) local linearity, which can lead to unstable or uninformative results when our case of interest is near a distinctly nonlinear region of the decision boundary or regression surface.
Wachter et al.'s solution is more flexible in this regard, a refreshing deviation from what Lundberg & Lee call the "additive feature attribution" paradigm. I'm unaware of any open source implementation, however. The added overhead of GAN training can also be extremely onerous for some datasets.


How do I stop the border from breaking apart when zooming in?

Question: http://mistcave.com/temp/
Zoom into the page and scroll right. The 1px black border at the bottom of the header is cut off a bit short. How do I fix this issue?
Comment: Even Stack Overflow suffers this problem. Except it's with the `background-color` when resized smaller: http://i.imgur.com/9sA7d5C.png
Answer: put the border bottom property in your header div
also to note if you are using google chrome you can go to select elements and view the dimensions of each div which will help you trouble shoot in the future
Comment: Putting the border in the header div won't allow me to extend it to the rest of the page since I have the width on that div limited to 1200px.

I use FireFox, has a similar feature. Very useful!
Comment: Basically your wrapper is smaller than the divs it contains you need to set a width and height for it. The header is overflowing and the portion of the header div not being contained is not being underlined.

you can set your wrapper to a width of 1200 px and your header div to a width of 100%, it should keep it inside of the wrapper and give you the spacing you want
Answer: set the width of the #wrap in CSS to be 100%
OR simply do the following:
<code>body
{
    overflow-x: hidden;
}
.extendfull, .extendleft
{
    padding-left: 3000px;
    margin-left: -3000px;
}
.extendfull, .extendright
{
    padding-right: 3000px;
    margin-right: -3000px;
}
</code>
overflow-x: hidden prevents horizontal scrolling, and increasing the padding is pretty self explanatory.
Answer: That doesn't really matter. Because the Border-bottom effect follows the size of your browser. No web users would zoom in and out pages except you.
It will also be fine in every screensize, just don't zoom it in and out.
That thing is fine every site has that problem too but it's not a big deal.
Answer: Made a dirty hack. Tough it work flawlessly.
Demo Fiddle
<code>#wrap {
    width: 100%;
}

#header {
    border-bottom: 1px solid #000000;
    margin-bottom: -1px;
}
</code>
Comment: Thanks! I cleaned up your hack a bit. Here's the result.

http://mistcave.com/temp/


Laravel 4 Add Method to Class (IoC / Namespaces)

Question: I'm trying to figure out how to add a method to a class in a Laravel package, so that all controllers and models that call that class can access the new method.  How do I replace this class in the IoC?
This is the package in question, Angel CMS.  The package is my creation, so I can modify it if we need to add aliases or anything to accomplish this.
Let's say I want to add a method to this class:
vendor/angel/core/src/models/PageModule.php

Okay, so I copy the class file to here:
app/models/PageModule.php

And then I modify the copied file, adding a namespace and the desired custom_function method:
<?php namespace MyModels;

use Eloquent;

class PageModule extends Eloquent {
    protected $table = 'pages_modules';

    public static function custom_function()
    {
        return 'It works!';
    }
}

As you can see, I am using the MyModels namespace here.
Then, I run a composer dump-autoload.
Next, I open up my app/routes.php and register the binding and set up a test route:
App::bind('PageModule', function($app) {
    return new \MyModels\PageModule;
});

Route::get('test-binding', function() {
    return PageModule::custom_function();
});

But, when visiting the test route, I always receive the same error that the method is undefined.
What am I doing wrong here?  Thank you in advance for any help.
To Clarify:
I am attempting to replace the class application-wide so that all other classes (controllers/models/etc.) that call PageModule will have access to the custom_function method.  Thanks.
Comment: I don't think there's an easy way to do it. I checked their `CoreServiceProvider.php` and they didn't do any bindings. They also call create `PageModule` object directly in their controllers using `new PageModule`.
Comment: @Unnawut, the package is mine - I can add anything necessary to make this work.  Do you think I should bind aliases to accomplish easily replaceable classes or how do I go about it?
Comment: This might sound irritating, and I'm sure you would have done it already if it suits your scenario, but what stops you from modifying the PageModule class directly?
Comment: @Unnaawut - This is a composer package, which means that it is overwritten every time it is updated (in the vendor/ folder).  We need to find some way of extending classes differently across dozens of different websites that will need different methods on each of them, so that they aren't overwritten.  This is what the IoC was built for, I just don't understand how to use it.  :(
Comment: Ok, that's pretty much the answer I expected, I'll try write an answer to that.
Answer: To be honest, I'm pretty new to all this IoC, dependency inversion/injection concept too. But I think I've gone through the same struggle before. What I would do, as much as my knowledge allows, is...
Add a constructor to src/controllers/admin/AdminPageController.php:
protected $pageModule;

public function __construct(PageModule $pageModule)
{
    $this->pageModule = $pageModule;
}

Then where you did $module = new PageModule in the same file. You replace it with:
$module = $this->pageModule;

The two modifications above makes use of Laravel's IoC to allow injecting a different PageModule object into your controller, instead of strictly creating PageModule in your code.
Now at this point Laravel should know that when it constructs the AdminPageController, it should create a PageModule and inject into the controller for you.
Since your controller now expects a PageModule class, you can no longer do class PageModule extends Eloquent in your app anymore, because even though the name is the same, PHP does not think that it is! You'll need to extend it:
So let's rename your app/models/PageModule.php to app/models/CustomPageModule.php, and in the file change the class to:
class CustomPageModule extends \PageModule {

Up to this point, you also have a CustomPageModule class that is a child of your package's PageModule. All you need to do now is to let Laravel knows that if any controllers ask for PageModule, it should serve the controller with your MyModels\CustomPageModule instead.
So at the top of your app's routes.php file:
App::bind('PageModule', 'MyModels\CustomPageModule');

Your AdminPageController should now be using your CustomPageModule and can use whatever public methods that are in there!

I'm expecting to be editing this answer heavily since this will be quite a long discussion. My first try at answering above isn't the best code you can write, but I hope it takes the least amount of edit to the original code, and then we can work up from there.
Or fast track by reading up articles like http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories
Comment: @Leng Glad it helps! I think this deserves another question by it's own. Even though content about IoC and dependency inversion/injection is all around. I didn't find any specifically on developing easily-extendible packages like building a CMS package.
Comment: @Leng actually, speaking of easily-extendible packages, This [Laravel-Administrator](https://github.com/FrozenNode/Laravel-Administrator) pop into my mind. Since it's supposed to fit as backend admin for all sorts of Laravel applications, I think you might gain some good ideas from looking at their source code.
Comment: By the way this answer was written along with me modifying my project code and it's working. So I hope it would work everywhere.
Comment: Hey thanks so much again @Unnawut.  You got me going in the right direction... I have to replace all occurences of direct `PageModule::` calls within the entire framework to use `$pageModuleModel = App::make('PageModule'); $pageModule::`, similarly to how the constructor dependency injections work.  It's a huge overhaul (I'm going to do it for *all* controllers and models, not just `PageModule`) - but it will be well worth it!  Thanks!
Comment: Awesome!  Thanks again - that `Laravel-Administrator` package is going to be a huge help to figuring out how to use bindings and namespaces correctly!
Answer: You probably have a alias for the PageModule facade, you should override this alias using your class \MyModels\PageModule in your app/config/app.php file.
Be careful, it seems like you are overwriting the PageModule class instead of extending it. You should probably extend the parent class instead of Eloquent.
Comment: Thanks for your help.  Unfortunately, there are no facades in the package, and I am indeed trying to *replace* the class so that all other classes that call PageModule load my new class with the custom function.
Comment: Perhaps using aliases on all my classes that I want to be extendable would actually be a good solution?  The complete error message is `Call to undefined method Illuminate\Database\Query\Builder::custom_function()`
Comment: Angel CMS is my package, so I can set up aliases if you think it'd be a cleaner solution!
Comment: Seems like you don't really extends Eloquent... Try to remove the `use` statement and extends Eloquent using `extends \Eloquent` (wild guess)


Evaluating $\int_{0}^{\frac{\pi}{4}}\frac{x\sin(x)}{\cos^{3}(x)}\,dx$

Question: $$\int_{0}^{\frac{\pi}{4}}\frac{x\sin(x)}{\cos^{3}(x)}\,dx$$
I started like this:
$$\int_{0}^{\frac{\pi}{4}}\dfrac{x\sin(x)}{\cos^{3}(x)}\,dx=\int_{0}^{\frac{\pi}{4}}\dfrac{1}{\cos^{2}(x)}\cdot \dfrac{\sin(x)}{\cos(x)}\cdot (x)\,dx=\int_{0}^{\frac{\pi}{4}}(x\cdot \tan(x))\cdot (\tan'(x)) \,dx$$
How to continue ?
Answer: We could try integration by parts, giving $$I:=\int_0^{\pi/4}x\tan x\sec^2 xdx=[x\tan^2 x]_0^{\pi/4}-\int_0^{\pi/4}(\tan x+x\sec^2 x)\tan xdx\\=\frac{\pi}{4}-I-\int_0^{\pi/4}\tan^2 xdx.$$Hence$$I=\frac{\pi}{8}-\frac12[\tan x-x]_0^{\pi/4}=\frac{\pi}{8}-\frac{1-\pi/4}{2}=\frac{\pi-2}{4}.$$
Comment: Bear in mind the OP had already noticed the $\tan^\prime x$ factor, suggesting they'd thought to do parts, which is often easier said than done. In any case my IBP differs from the one you suggested (but matches what the OP seemed to have in mind), which would have taken $v=\frac12\tan^2 x+C$. If you can show in a fleshing out of your answer that it would also work, I'll try to upvote you when I get up tomorrow. Goodnight.
Comment: What's the difference with my hint, except you completely solve the problem?
Answer: $$\frac{x\sin x}{\cos^3x}=x\tan x\sec^2x$$
then use the integration by part
Comment: Are there other way without involving sec ?I didn't learn at school about sec
Comment: @DanVaja Did you learn $\tan^\prime x=\cos^{-2}x$? If so, you could work just with powers of $\sin x,\,\cos x,\,\tan x$. (In case you're wondering, $\sec x=1/\cos x$.)
Answer: Hint:
Integration by parts, setting
$$u=x,\quad\mathrm d v=\tan x\,\mathrm d(\tan x).$$
You'll have to remember that the other form of the derivative of $\tan x$ is $\;1+\tan^2x$:
\begin{align}
\int_{0}^{\pi/4}\frac{x\sin x}{\cos^{3}x }\,\mathrm dx &=\tfrac12x\tan^2x\biggm\vert_0^{\pi/4}-\frac12\int_{0}^{\pi/4}\tan^2 x\,\mathrm dx \\[-1ex]
\\&=\frac\pi8-\frac12\int_{0}^{\pi/4}(1+\tan^2 x)\,\mathrm dx+\frac12\int_{0}^{\pi/4}\mathrm d x = \frac\pi4 -\frac12\int_{0}^{\pi/4}(1+\tan^2 x)\,\mathrm dx
\end{align}
Answer: You're definitely headed in the right direction, with realizing that $\sec^2(x)$ is the derivative of $\tan(x)$. Your next step is going to be to use integration by parts with $u = x$ and $dv = \tan(x)\sec^2(x)\,dx$, so we get $du = 1$ and $v = \frac{1}{2}\tan^2(x)$.
Answer: Nothing new compared to other answers, just the mechanics I find useful. Notice that $$\tan'(x) \,dx = \,d \tan(x)$$ and $$\tan(x) \tan'(x) \,dx = \tan(x)\,d\tan(x) = \frac{1}{2} \,d \tan^2{x}$$ That is your integral is in fact
$$\frac{1}{2}\int_{0}^{\frac{\pi}{4}}x\,d \tan^2{x}$$
Now continue integrating by parts.
Answer: An alternative solution.
Observe that:
\begin{align}\dfrac{\partial}{\partial x}\left(\frac{1}{2\cos^2 x}\right)=\frac{\sin x}{\cos^3 x}\end{align}
Therefore,
\begin{align}\int_{0}^{\frac{\pi}{4}}\frac{x\sin(x)}{\cos^{3}(x)}\,dx&=\left[\frac{x}{2\cos^2 x}\right]_{0}^{\frac{\pi}{4}}-\frac{1}{2}\int_{0}^{\frac{\pi}{4}} \frac{1}{\cos^2 x}\,dx\\
&=\frac{\pi}{4}-\frac{1}{2}\Big[\tan x\Big]_{0}^{\frac{\pi}{4}}\\
&=\boxed{\frac{\pi-2}{4}}
\end{align}
Answer: Just for the fun of rewriting it:
\begin{align}
\int_0^{\pi/4}x\frac{\sin x}{\cos^3 x}dx&=\int_0^{\pi/4}\int_0^x\frac{\sin x}{\cos^3 x}dtdx\\
&=\int_0^{\pi/4}\int_t^{\pi/4}\frac{\sin x}{\cos^3x}dxdt\\
&=\int_0^{\pi/4}\left(1-\frac12\sec^2 t\right)dt
\end{align}


Using Pandas how to multiply the values incrementally and take the summation of those values

Question: (Not duplicate question)
My dataset df looks like this:
time                    Open
2017-01-01 00:00:00     5.2475
2017-01-01 01:00:00     5.2180
2017-01-01 02:00:00     5.2128
...., ....
2017-12-31 23:00:00     5.7388

This is an hourly dataset.
I want to multiply the values in +1 incremental order for 10 values and then take the summation of those values.
For example:

The 1st value is multiplied by 1
The 2nd value is multiplied by 2
The 10th value is multiplied by 10 and then on the 11th value we repeat with 1 and so on.
After that take the summation, value1 + ... + value10

What did I do?
I came close to only multiply each value with the same number like this:
df['Open_Multiply'] = df['Open'] * 1     # Number to multiply

but I am not able to iterate and calculate incrementally. I can do this in Python but not yet with Pandas.

Once the multiplication is done, I want to store the **summation**
of the 10 value in new df called df2 so that we have time and
Open_Mult_Sum in the df2 dataframe
(SOLVED) summation calculation: Take the sum of every N rows in a pandas series
Comment: same question again ?
Comment: https://stackoverflow.com/questions/57099709/how-to-multiply-each-value-in-dataframe-series-in-incremental-order-using-pandas
Comment: @WeNYoBen That answer does not work, I already tried that.
Comment: Possible duplicate of [How to multiply each value in DataFrame series in incremental order using Pandas](https://stackoverflow.com/questions/57099709/how-to-multiply-each-value-in-dataframe-series-in-incremental-order-using-pandas)
Comment: @floss if the answer doesn't work it's better explain so in comments rather than post again the same question.
Comment: @rpanai ok thank you, I will do that. The answer by rafaelc in this question is excellent. I only need to find the summation now.
Comment: @everyone: fyi (solved) summation calculation: https://stackoverflow.com/questions/47239332/take-the-sum-of-every-n-rows-in-a-pandas-series
Answer: Use np.tile and np.arange and then just multiply
df['Open'] * np.tile(np.arange(1,11), len(df))[:len(df)]

Comment: (SOLVED) Summation Calculation: https://stackoverflow.com/questions/47239332/take-the-sum-of-every-n-rows-in-a-pandas-series


textfield label is not coming inside formpanel inside panel

Question: I have designed one extjs page but my problem is
i have to give a textfield inside inner panel which is form panel but textfield label is not coming can you please solve...this is my code...but problem is i have to give employeeid inside one inner panel based on some condition i have to hide the inner panel but when i am creating panel i am not getting textfield label....can anyone please solve
Ext.onReady(function(){

 var tab2 = new Ext.FormPanel(
    {
        labelAlign: 'left',
        title: 'Main Panel',
        buttonAlign: 'left',
        bodyStyle:'padding:5px',
        width:700,
        height:500,
        method: 'POST',
        url : '../../WebPages/ServerTask.aspx',
        id: 'formTest',
        //anchor:'60%',
        collapsible: true,
            items: [{layout:'column', border:false,
            items:[{columnWidth:.6,layout: 'form', border:false,labelWidth:120,
            items: [{
                       xtype:'textfield',
                       fieldLabel:'employeeid',
                       id:'employeeNo',
                       width:110
                    }]
              }]
              }]
         });

Answer: Ok, here is the problem. You are configuring the items config three times. There are more errors in your code but that is the one that breaks it.
Try this example and add/remove config you don't need.
Ext.create('Ext.form.Panel', {
    title: 'Main Panel',
    buttonAlign: 'left',
    bodyStyle:'padding:5px',
    width: 700,
    height: 500,
    url : '../../WebPages/ServerTask.aspx',
    id: 'formTest',

    items: [{
        xtype:'textfield',
        fieldLabel:'employeeid',
        id:'employeeNo',
        width:110
    }],

    renderTo: Ext.getBody()
});

Other errors:

Create your objects with the Ext.create function.
The layout config specifies the position of the child object so add the layout config to the parent.
Don't add child config to parent. see labelAlign
Begin an array with [{ and close it with }]
Don't work with id's (only if you have to)


Apache reverse proxy 302 redirect browsers directly takes to the redirected URL

Question: I have setup a reverse proxy through glassfish server via apache mod_proxy.
my concern is when there is a 302 redirect happens then after that every time i access that url which invoked 302 redirect all the browsers directly takes me to that redirected url.
Please see my apache config.
<VirtualHost *:80>
    ServerName proxy
    ProxyRequests Off
    ProxyPreserveHost On
    AllowEncodedSlashes NoDecode

    ProxyPass / http://server:port/ nocanon
    ProxyPassReverse / http://server:port/
    ProxyPassReverse / http://proxy/

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

Answer: I had a global option setup as ExpiresDefault "access 1 month", this was causing the issue.
I put ExpiresDefault "now" in my virtual host setting to resolve my problem.


my compiler says that this thing __attribute__ is wrong, a syntax error

Question: The following is inside GNU m4 sources in a file called lib/verror.h :
<code>/* Declaration for va_list error-reporting function
   Copyright (C) 2006-2007, 2009-2011 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifndef _VERROR_H
#define _VERROR_H 1

#include "error.h"
#include <stdarg.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Print a message with `vfprintf (stderr, FORMAT, ARGS)';
   if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
   If STATUS is nonzero, terminate the program with `exit (STATUS)'.
   Use the globals error_print_progname and error_message_count similarly
   to error().  */

extern void verror (int __status, int __errnum, const char *__format,
                    va_list __args)
     __attribute__ ((__format__ (__printf__, 3, 0)));

/* Print a message with `vfprintf (stderr, FORMAT, ARGS)';
   if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
   If STATUS is nonzero, terminate the program with `exit (STATUS)'.
   If FNAME is not NULL, prepend the message with `FNAME:LINENO:'.
   Use the globals error_print_progname, error_message_count, and
   error_one_per_line similarly to error_at_line().  */

extern void verror_at_line (int __status, int __errnum, const char *__fname,
                            unsigned int __lineno, const char *__format,
                            va_list __args)
     __attribute__ ((__format__ (__printf__, 5, 0)));

#ifdef __cplusplus
}
#endif

#endif /* verror.h */
</code>
My compiler blows up all over that strange thing called "attribute" and I looked
in the K&R C for it but can not find it.
Looks to be a strictly GNUism GCC thing and not C at all.
So the question is how to remove this junk to make the code able to be compiled
by an old C compiler on an old Sun server? The very same compiler can build GNU
make just fine as well as libiconv and gNU gettext but the latest GNU m4 looks
to be non-portable.
The error that I see is :
<code>/opt/SUNWspro/bin/cc  -I.   -D_REENTRANT -I/usr/local/include  -dy -xmemalign=8s -errfmt=error -erroff=%none -errshort=full -errwarn=%none -fns=no -ftrap=%none -xarch=v9 -xcode=pic32 -g -i -mc -Qy -v -Wl,-R/usr/local/lib -Xa -xstrconst -xtemp=/var/tmp -xunroll=1 -D_POSIX_PTHREAD_SEMANTICS -D_LARGEFILE64_SOURCE -D_TS_ERRNO -c verror.c
"verror.h", line 35: error: syntax error before or at: __attribute__
"verror.h", line 35: warning: old-style declaration or incorrect type for: __attribute__
"verror.h", line 35: warning: syntax error:  empty declaration
"verror.h", line 47: error: syntax error before or at: __attribute__
"verror.h", line 47: warning: old-style declaration or incorrect type for: __attribute__
"verror.h", line 47: error: identifier redefined: __attribute__
        current : function() returning int
        previous: function() returning int : "verror.h", line 35
"verror.h", line 47: warning: syntax error:  empty declaration
"verror.c", line 44: error: identifier redefined: verror
        current : function(int, int, pointer to const char, pointer to void) returning void
        previous: function(int, int, pointer to const char, pointer to void) returning void : "verror.h", line 33
"verror.c", line 57: error: identifier redefined: verror_at_line
        current : function(int, int, pointer to const char, unsigned int, pointer to const char, pointer to void) returning void
        previous: function(int, int, pointer to const char, unsigned int, pointer to const char, pointer to void) returning void : "verror.h", line 44
cc: acomp failed for verror.c
gmake[3]: *** [verror.o] Error 2
gmake[3]: Leaving directory `/usr/local/build/m4-1.4.16_SunOS5.8_sparcv9.001/lib'
gmake[2]: *** [all] Error 2
gmake[2]: Leaving directory `/usr/local/build/m4-1.4.16_SunOS5.8_sparcv9.001/lib'
gmake[1]: *** [all-recursive] Error 1
gmake[1]: Leaving directory `/usr/local/build/m4-1.4.16_SunOS5.8_sparcv9.001'
gmake: *** [all] Error 2
</code>
pretty nasty looking stuff that.
Comment: Put this in some header file and include it: `#define __attribute__(x) /* as nothing */`. The `__attribute__` syntax is designed to make this possible (double-parens). Alternatively, download GCC for Solaris and use that, since GNU contributors generally feel free to use GCC extensions.
Answer: <code>__attribute__</code> is a GCC extension, which has also been borrowed by clang and maybe other compilers as well. If your compiler doesn't support attributes using this syntax, you can get rid of the errors by defining this macro before any attributes are used:
<code>#define __attribute__(x)
</code>
Keep in mind though that removing attributes may affect the program's behaviour.
Comment: @paullanken: In this particular case, disabling the attribute won't do anything at all in terms of program behaviour, but it should allow it to compile. That particular attribute looks like it tells the compiler that it expects a "printf"-style format string (which in turn allows for better diagnostics when invalid format specifiers are given etc). Log a bug though... the source code now "assumes" GCC (or clang) is the compiler, which isn't great for portability as you say.
Comment: So essentially a non-portable piece of code thrown in by the GNU/Linux world to render GNU m4 non-portable. Lovely. OKay, I will give this a try but first I will look at an older release of GNU m4 to see if it has the same issue.  If not then I will use an older GNU m4 until I can bootstrap GCC.  Actually, m4-1.4.14 compiles just fine.  Looks like a recent addition in GNU m4 breaks it for portability.  I should file a bug, which will get ignored.
Comment: configure line looks good : `./configure --enable-dependency-tracking --enable-threads=posix --with-libsigsegv-prefix=/usr/local` so that isn't the issue.  I have reverted down to m4 (GNU M4) 1.4.14 which compiles and tests fine.  I want to see if I can find where the GCCism feature was inserted and file a bug report with some valid info in it.
Comment: @paullanken: Note that USUALLY, the configure script will create precisely this macro for you when you configure the package to build with a non-gcc compiler.  The fact that it didn't suggests you didn't run configure properly.  Check the INSTALL instructions for your m4 package that you're trying to build...


What is the difference between method and model?

Question: I know that OLS is an estimation method. I suppose that OLS models are simply a bunch of variables in one group for which an OLS method is used. Is that correct?
Also, is it wrong to say that negative binomial is a method? I guess so, it's a distribution, right? But then what is the estimation method? E.g. what estimation method am I using when I use glm.nb function in r?
Answer: A model is a mathematical description of a problem. In statistics this description is made in terms of probability distributions, random variables, and their functions, but there are also mathematical models outside of statistics that aren't concerned about random variables. For example, in case of linear regression, we describe the relation between dependent and independent variable in terms of a linear function of independent variables. If we use negative binomial distribution as a model, we assume that the observed variable can be approximated using this distribution, so that the properties of the distribution could be used to describe the data.
What you call a method sounds as an algorithm used for estimating the parameters. OLS is an algorithm that uses linear algebra to minimize the squared error to find the linear function used by linear regression. Another example may be using a black-box optimizer to find a maximum of a likelihood function, to fit the negative binomial distribution to the data.


Need Help Combining 2 VBA codes

Question: I need to combine these two VBA Codes the first is finding and replacing multi items in one document and the second find and replaces a word throughout an entire folder. As you can imagine I need to find and replace multiple words in each document in the folder with 1 button.
CODE 1:
Sub FindAndReplaceMultiItems()
  Dim strFindText As String
  Dim strReplaceText As String
  Dim nSplitItem As Long

  Application.ScreenUpdating = False

  ' Enter items to be replaces and new ones.
  strFindText = InputBox("Enter items to be found here,seperated by comma: ", "Items to be found")
  strReplaceText = InputBox("Enter new items here, seperated by comma: ", "New items")
  nSplitItem = UBound(Split(strFindText, ","))

  ' Find each item and replace it with new one respectively.
  For nSplitItem = 0 To nSplitItem
    With Selection
      .HomeKey Unit:=wdStory
      With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = Split(strFindText, ",")(nSplitItem)
        .Replacement.Text = Split(strReplaceText, ",")(nSplitItem)
        .Format = False
        .MatchWholeWord = False
      End With
    Selection.Find.Execute Replace:=wdReplaceAll
  End With
Next nSplitItem

  Application.ScreenUpdating = True

End Sub

CODE 2:
Sub FindAndReplaceInFolder()
  Dim objDoc As Document
  Dim strFile As String
  Dim strFolder As String
  Dim strFindText As String
  Dim strReplaceText As String

  '  Pop up input boxes for user to enter folder path, the finding and replacing texts.
  strFolder = InputBox("C:\Users\freil\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\TempState\Downloads\Agreements Folder:")
  strFile = Dir(strFolder & "\" & "*.docx", vbNormal)
  strFindText = InputBox("Find:")
  strReplaceText = InputBox("Replace:")

  '  Open each file in the folder to search and replace texts. Save and close the file after the action.
  While strFile <> ""
    Set objDoc = Documents.Open(FileName:=strFolder & "\" & strFile)
    With objDoc
      With Selection
        .HomeKey Unit:=wdStory
        With Selection.Find
          .Text = strFindText
          .Replacement.Text = strReplaceText
          .Forward = True
          .Wrap = wdFindContinue
          .Format = False
          .MatchCase = False
          .MatchWholeWord = False
          .MatchWildcards = False
          .MatchSoundsLike = False
          .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
      End With
      objDoc.Save
      objDoc.Close
      strFile = Dir()
    End With
  Wend
End Sub

Answer: Try something along the lines of:
Sub BulkFindReplace()
Application.ScreenUpdating = False
Dim Doc As Document, strFolder As String, strFile As String, i As Long
Const FList As String = "One,Two,Three"
Const RList As String = "Four,Five,Six"
StrFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.doc", vbNormal)
'Loop through all documents in the chosen folder
While strFile <> ""
  Set Doc = Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
  With Doc
    With .Range.Find
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      'Process each word from the Find/Replace Lists
      For i = 0 To UBound(Split(FList, ","))
        .Text = Split(FList, ",")(i)
        .Replacement.Text = Split(RList, ",")(i)
        .Execute Replace:=wdReplaceAll
      Next
    End With
    .Close SaveChanges:=True
  End With
  strFile = Dir()
Wend
Set Doc = Nothing
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
    Dim oFolder As Object
    GetFolder = ""
    Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
    If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
    Set oFolder = Nothing
End Function

Answer: Welcome to SO. You just need to encompass While strFile <> "" loop (and related  variables etc) from Code 2 around Code 1 For loop. However there are other issues with code. May try
Sub FindAndReplaceMultiItems()
  Dim strFindText As String
  Dim strReplaceText As String
  Dim nSplitItem As Long, i As Long
  Dim strFolder As String, StrFile As String
  Dim objDoc As Document
  'Application.ScreenUpdating = False

    With Application.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
        If .Show = -1 Then
        strFolder = .SelectedItems(1)
        End If
    End With

    If Len(strFolder) = 0 Then
    MsgBox " No folder Selected"
    Exit Sub
    End If

  strFindText = InputBox("Enter items to be found here,seperated by comma: ", "Items to be found", "asdf,qwert,zxc")
    If Len(strFindText) = 0 Then
    MsgBox " No Find Text Entered"
    Exit Sub
    End If

  strReplaceText = InputBox("Enter new items here, seperated by comma: ", "New items", "0000000000,1111111111,222222222222")

    If Len(strReplaceText) = 0 Then
    MsgBox " No Replace Text Entered"
    Exit Sub
    End If

  nSplitItem = UBound(Split(strFindText, ","))
      If nSplitItem <> UBound(Split(strReplaceText, ",")) Then
      MsgBox " Unequal Numbers of Find & Replacement Text"
      Exit Sub
      End If

  StrFile = Dir(strFolder & "\" & "*.docx", vbNormal)
    'Open each file in the folder to search and replace texts. Save and close the file after the action.
    While StrFile <> ""
    Set objDoc = Documents.Open(FileName:=strFolder & "\" & StrFile)
    objDoc.Select

      ' Find each item and replace it with new one respectively.
        For i = 0 To nSplitItem
            With Selection
            .HomeKey Unit:=wdStory
                With .Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .Text = Split(strFindText, ",")(i)
                .Replacement.Text = Split(strReplaceText, ",")(i)
                .Format = False
                .MatchWholeWord = False
                .Execute Replace:=wdReplaceAll
                End With
            End With
        Next i
     'objDoc.Save
     objDoc.Close True
     StrFile = Dir()
    Wend
'Application.ScreenUpdating = True
End Sub

Comment: Thank You very much appreciated

Need Help Combining 2 VBA codes


Inserir dados em uma array multidimensional

Question: Tenho uma array multidimensional

    [0] => Array
        (
            [per] => Array
                (

                    [per_dep] => Array
                        (
                            [0] => 1115921
                            [1] => 1705572
                            [2] => 1126464
                            [3] => 1131324
                        )

                )

        )

E eu gostaria de alterar o valor do per_dep. Porém, essa alteração deverá ser dinâmica. Ou seja, eu tenho uma outra array com os keys.

Array
(
    [0] => 0
    [1] => per
    [2] => per_dep
)

e tenho o valor a ser inserido
9999999
Como eu poderia realizar esse processo sabendo que será dinâmico o processo?
Eu sei que não posso fazer $array.$keys = $valor pois não funciona. O que eu poderia fazer?
Comment: Se possível, disponibilize o código que já tem pronto, isso ajuda na depuração.
Answer: Algo próximo a isso:
<code>    $arrayOriginal[$arrayKeys[0]][$arraykeys[1][$arraykeys[2]][$arraykeys[4]] = 9999999;
</code>
Sugestão de automatização:
<code>  $arrayOriginal = [
  'a' => 0,
  'b' =>   [ 'f' => 5 ,
             'g' => [ 'h' => 4 ] ,
             'i' => [ 'o' => 5 ]
            ],
  'c' => 2,
  'e' => 5
  ];

  $arrayKeys = ['b','g','h'];

  $arrayTemp  = &$arrayOriginal;

  $i = 0;

  for ($i = 0;  $i<count($arrayKeys)-1;$i++) {
       $arrayTemp = &$arrayTemp[$arrayKeys[$i]];
  }

  $arrayTemp[$arrayKeys[count($arrayKeys)-1]] = 999999;

  print_r($arrayOriginal);
</code>
Saída:
<code> Array ( [a] => 0 [b] => Array ( [f] => 5 [g] => Array ( [h] => 999999 ) [i] => Array ( [o] => 5 ) ) [c] => 2 [e] => 5 )
</code>
Comment: certo, como automatizar isso? tipo com um foreach varrendo as keys?
Comment: Editei a resposta, ta ai um exemplo funcional, usando o código que eu sugeri :D
Comment: Muito bom!! Deu certo! Eu estou tentando aumentar a pontuação e não consigo...
Comment: ué, vota na minha resposta.
Comment: `@user5978`: se votares na pergunta o Claudio ganha pontos e pode votar na tua resposta também :) @Claudio: se esta resposta resolveu o teu problema podes marcar como aceite.
Comment: votei, só não consegui aumentar um ponto utilizando a seta para cima..
Answer: Para fazer isso num array multidimensional, sendo as chaves dinâmicas, é importante saber qual a chave que você quer atualizar, coloquei um exemplo de array que pega toda a estrutura da matriz e atualiza o valor onde encontrar a chave que você procura, usando uma função recursiva, do PHP 5 ou superior, saiba mais aqui:
<code>$seuArray = array(
  'a' => 0,
  'b' =>   array( 'b1' => 5 ,
                  'b2' => array( 'b2_0' => 4 ) ,
                  'b3' => array( 'b3_0' => 5 )
            ),
  'c' => 2,
  'd' => 5
  );

$saida = replaceValue($seuArray, 'b2_0', array('nova_chave'=>'novo_valor'));

function replaceValue($array, $key, $newValue)
{

    $params = array(
      'newvalue' => $newValue,
      'key'      => $key
    );

    array_walk_recursive($array, function(&$v, $k) use ($params) {

        if ($k == $params['key']) {
            $v = $params['newvalue'];
        }
    });
    return $array;
}
</code>
Veja o exemplo funcionando no IDEONE
Comment: é aí que tá o problema... do modo como você escreveu é algo fixo.. a minha array é dinâmica.. as keys são dinâmicas.. dessa forma como você colocou é algo fixo.. entende?
Comment: Entendo, mais ou menos... você precisa identificar as keys para poder trabalhar com um array, senão, não tem lógica usar o array. O valor é variável, a chave não tem que ser, está mal feito isso. Neste caso vc deveria reescrever as chaves, para um modelo comum.
Comment: Para fazer isso, existe uma função chamada [`array_map()`](http://php.net/array_map).
Comment: Outra coisa que vc pode fazer é resetar as keys dinâmicas desse array, usando `array_values($seuarray);`
Comment: então, como está na pergunta... eu terei uma array que são as keys... o que eu precisaria é algo que una a $array com as $keys para inserir um valor...
Answer: A questão é muito parecida com essa: Pre programar parametros a retirar de um objecto
A diferença é que na outra pergunta o problema é obter o acesso e o que mais complicou é que era um objeto e não um array.
No PHP, existe a função array_reduce() para esse propósito, mas para o seu caso, o que complica é que precisa setar e não somente ler.
Então usando uma lógica muito semelhante ao que postei na outra pergunta, fiz uma versão simples para o seu caso:
<code>function SetArrayReduce($array, $key, $val)
{
    $r = array();
    $l = function($r) use (&$l, &$key, $val) {
        foreach ($key as $k => $v) {
            if (!isset($key[$k])) {
                break;
            }
            unset($key[$k]);
            if (count($key) < 1) {
                return array($v=>$val);
            }
            $r[$v] = $l($r);
        }
        return $r;
    };

    if (is_string($key)) {
        $key = explode(':', $key);
    }

    $r = $l($r);
    unset($key, $val);
    return array_merge_recursive($array, $r);
}

/*
O array com os dados originais.
*/
$array = array(
    0 => array(
        'per' => array(
            'per_dep' => array(
                0 => 1115921,
                1 => 1705572,
                2 => 1126464,
                3 => 1131324
            )
        )
    )
);

/*
A chave/índice que pretende modificar.
Exemplo, para modificar somente $array[0]['per']['per_dep']

A função SetArrayReduce() aceita uma string como parâmetro.
Apenas precisa definir um delimitador. Por padrão o delimitador é :
$key = '0:per:per_dep';
*/
$key = Array
(
    0 => 0,
    1 => 'per',
    2 => 'per_dep'
);

/*
O array $key pode ser escrito de outras formas:
$key = array(0, 'per', 'per_dep');
$key = array('string1' => 0, 'string2' => 'per', 'string3' => 'per_dep');
O importante é que os valores devem estar na ordem correta pois serão agrupados em cascata.
*/

/*
Remova o comentário da linha abaixo e experimente o resultado usando $key como string.
*/
//$key = '0:per:per_dep';

/*
O valor que deseja atribuir a chave/índice.
*/
$val = 9999999;

/*
Invoca a função e mostra o resultado.
*/
$rs = SetArrayReduce($array, $key, $val);
print_r($rs);
</code>


How can I access row field values in the parent views template?

Question: In views-view-fields--myview.html.twig I can print a views fully formatted/rewritten field with a variable like: {{ fields.field_my_view_field.content }}.
I am wondering if there is some way to print fields in the same fashion in the parent view template: views-view--myview.html.twig. This would require having access to these variables with the sub items (row) of the {{ rows }} variable.
Is this possible? And if so, what is the correct syntax to access?
Comment: Have you tried to dump `{{ rows }}`? Is it an array that you can simply loop through?
Answer: You say that outputting the variables the template is supposed to be outputting is very powerful. Interesting, I would say this is the (only) correct way to use this template. In special cases it might be necessary to access field raw values, for example to add CSS classes to divs you put into the template, wrapping HTML markup around the content variables. The real purpose of this template.
======================================
If you want to control the rendering from the main View level then use a custom style plugin. Then you don't need to use the mentioned Views field templates. You can build a structure entirely from scratch rendering the fields as you want.
See Views style plugins.
Comment: (I removed the noise from the question.)


$f$ holomorphic from unit disc to itself. $f\left(\frac{1}{2}\right) = f\left(-\frac{1}{2}\right) = 0$. Show that $|f(0)| \le 1/3$.

Question: I'm studying for a qual exam. I cannot solve the following problem:

Let $f$ be holomorphic from the unit disc to itself. $f\left(\frac{1}{2}\right) = f\left(-\frac{1}{2}\right) = 0$. Show that $|f(0)| \le \frac{1}{3}$.

With an application of Schwarz lemma, I showed that $|f(0)| \le \frac{1}{2}$. I can't prove the tighter bound. Any ideas?
Comment: [This question](http://math.stackexchange.com/questions/282016/a-qualifying-exam-problem-involving-schwarz-lemma) might help.
Answer: Consider the function
$$g(z) = f(z) \frac{1 - r^2 z^2}{r^2 - z^2}$$
where $r = \frac{1}{2}$, which is holomorphic on $\mathbb{D}$ since $f$ has roots at $\pm r$. When $|z| = 1$, $|f(z)| \leq 1$ and
$$|g(z)| \leq \left|\frac{1 - r^2 z^2}{r^2 - z^2} \right|$$
We have
$$16 |1 - r^2 z^2|^2 = |4 - z^2|^2 = (4 - z^2) (4 - \overline{z}^2) = 16 - 4z^2 - 4\overline{z}^2 + 1$$
and
$$16|r^2 - z^2|^2 = |1 - 4z^2|^2 = (1 - 4z^2)(1 - 4\overline{z}^2 = 1 - 4z^2 - 4\overline{z}^2 + 16$$
We conclude that $|1 - r^2 z^2| = |r^2 - z^2|$, so $|g(z)| \leq 1$ whenever $|z| = 1$.
So by the Maximum Modulus Principle, $|g(0)| \leq 1$; in particular,
$$|f(0)| \frac{1}{1/4} \leq 1 \implies |f(0)| \leq \frac{1}{4}$$
which is a stronger result.
The approach was suggested by an answer here, as indicated in Clayton's comment.


Even harmonic sums?

Question: How do we calculate this?
$ \displaystyle \sum_{n=1}^{\infty} (-1)^{n-1} \frac{H_{2n}}{2n} $
I am stuck that the integrals isn't converging for harmonic (even) numbers . somebody please help .
Comment: This question has different answers here:http://math.stackexchange.com/questions/1000140/evaluating-sum-n-1-infty-1n-1-frach-2nn
Comment: Independently of what the solution is, note that the Harmonic numbers grow like $\log(n)$ and thus, as the sum is alternating, the series will converge, by the Leibniz test.
Comment: Oh thanks @OlivierOloa :)
Comment: Yup I am also pretty convinced about the convergence , WA also supports but when I find the generating function of even harmonics and then integrate we fond a non-converging integral.
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\color{#f00}{\sum_{n = 1}^{\infty}\pars{-1}^{n - 1}\,\,{H_{2n} \over 2n}} & =
{H_{2} \over 2} - {H_{4} \over 4} + {H_{6} \over 6} - {H_{8} \over 8} + \cdots =
\sum_{n = 0}^{\infty}{H_{4n + 2} \over 4n + 2} -
\sum_{n = 0}^{\infty}{H_{4n + 4} \over 4n + 4}
\\[5mm] & =
\sum_{n = 0}^{\infty}{H_{n + 2} \over n + 2}
\,{1 + \pars{-1}^{n} + i^{n} + \pars{-\ic}^{n} \over 4} -
\sum_{n = 0}^{\infty}{H_{n + 4} \over n + 4}
\,{1 + \pars{-1}^{n} + i^{n} + \pars{-\ic}^{n} \over 4} =
\\[5mm] & =
\sum_{n = 2}^{\infty}{H_{n} \over n}
\,{1 + \pars{-1}^{n} - i^{n} - \pars{-\ic}^{n} \over 4} -
\sum_{n = 4}^{\infty}{H_{n} \over n}
\,{1 + \pars{-1}^{n} + i^{n} + \pars{-\ic}^{n} \over 4}
\\[5mm] & =
-\,\half\sum_{n = 1}^{\infty}{H_{n} \over n}
\bracks{i^{n} + \pars{-\ic}^{n}} =
-\Re\sum_{n = 1}^{\infty}H_{n}\,\ic^{n}\int_{0}^{1}x^{n - 1}\,\dd x
\\[5mm] & =
-\Re\int_{0}^{1}\sum_{n = 1}^{\infty}H_{n}\,\pars{\ic x}^{n}\,{\dd x \over x} =
\Re\int_{0}^{1}{\ln\pars{1 - \ic x} \over x\pars{1 - \ic x}}\,\dd x
\\[5mm] & =
\color{#f00}{{5 \over 96}\,\pi^{2} - {1 \over 8}\,\ln^{2}\pars{2}} \approx
0.4540
\end{align}

Even harmonic sums?


Mathematics of MC Escher

Question: I'm working with an undergraduate math major McNair Scholar, whose had our 10 week 'Group Theory for High School Teachers' class and will start our year long Abstract Algebra sequence in the fall.
I'm looking for an independent study reading project for him that might also reinforce what he's learned and prepare him to learn more.  Can anyone suggest an undergrad level book or expository paper about the classification of wallpaper groups?
Answer: "The Symmetries of Things" by Conway et al has some really interesting material at different levels including wallpaper groups, and also some examples (and great illustrations) which could be used in a high school or maths club.
Comment: @Barry Cipra - thanks for the edit
Comment: You're welcome.  I had the link in hand because I was going to post it in an answer myself.  You saved me the trouble.
Comment: Thanks, this looks very promising!

Mathematics of MC Escher


Am I using the BLAS/LAPACK libraries when using MTJ?

Question: I'm not sure this is the right place to ask my question, so if not, I apologize.
I'm writing a Java program that does a lot of sparse matrix multiplications. After some research, I've found that the Matrix Toolkits Java provides some of the best performance, but only when using the netlib-java wrapper for BLAS/LAPACK fortran libraries.
Now I've tried following the instructions on these github pages, and I have installed both BLAS and LAPACK from the Arch Linux repositories:
$ pacman -Ss lapack
extra/lapack 3.5.0-1 [installed]
    Linear Algebra PACKage
$ pacman -Ss blas
extra/blas 3.5.0-1 [installed]
    Basic Linear Algebra Subprograms

When checking /usr/lib/, it does contain
-rwxr-xr-x 1 root root 1866088 Jan 27 21:46 liblapacke.so
lrwxrwxrwx 1 root root      13 Jan 27 21:46 liblapacke.so.3 -> liblapacke.so
lrwxrwxrwx 1 root root      13 Jan 27 21:46 liblapacke.so.3.5.0 -> liblapacke.so
-rwxr-xr-x 1 root root 5878120 Jan 27 21:46 liblapack.so
lrwxrwxrwx 1 root root      12 Jan 27 21:46 liblapack.so.3 -> liblapack.so
lrwxrwxrwx 1 root root      12 Jan 27 21:46 liblapack.so.3.5.0 -> liblapack.so

and
-rwxr-xr-x 1 root root 358448 Jan 27 21:46 libblas.so
lrwxrwxrwx 1 root root     10 Jan 27 21:46 libblas.so.3 -> libblas.so
lrwxrwxrwx 1 root root     10 Jan 27 21:46 libblas.so.3.5.0 -> libblas.so

Now, my program multiplies a sparse matrix of about 450,000x450,000 elements with a vector. This takes about a second. I'm running on an Intel Core 2 Duo @ 2.53GHz.
My question after all this is, am I really using the Fortran backend, or still the Java implementation of these functions? I realize my calculations are large, but I still feel they could be faster... Is there any way to check which libraries are used while running?
Thanks in advance!
Regards,
Linus
EDIT:
I've just tried something, which to me suggests that I am in fact NOT using the libraries. I've renamed both liblapack and libblas, assuming this would make it impossible for Java to find them. My program still ran after renaming the libraries, and more importantly, took just as long... I guess what I'm looking for now is how to make sure that the libraries are loaded and being used!
Comment: What files do you rename?
Comment: /usr/lib/liblapack.so and /usr/lib/libblas.so
Answer: You are using the shared libraries, which should be written in Fortran.
Keep in mind that for a large matrix, it is not unreasonable that the multiplication takes time.
Comment: Thanks for your answer, but I'd like to know how you know this, and whether you could explain my little experiment in my new edit!
Comment: If you look at the netlib-java documentation, it states that it uses the Fortran libraries.
Comment: Alright, in that case my question is whether I'm using the "self-contained native builds" or the "delegating builds that use machine optimised system libraries".
Answer: There is an easy way to check which version of the BLAS library you are using in your code:
System.out.println(BLAS.getInstance().getClass().getName());

If you are running the Native library, you should see something like:
com.github.fommil.netlib.NativeSystemBLAS

If, on the contrary, you are still linked to JBLAS, then you should see instead a reference to F2jBLAS or JBLAS
With that said, you still need to make sure that your sysmtem BLAS library is linked to the correct implementation (custom-compiled OpenBLAS, Intel MLK, etc.) if you want the very best performance.


How do I monitor how busy a Python event loop is?

Question: I have an asynchronous application that is serving requests via aiohttp and doing other async tasks (interacting with a database, handling messages, making requests itself as an HTTP client). I'd like to monitor how busy the event loop is, perhaps how much time it's spending executing code versus waiting for a select to complete.
Is there a way to measure this with standard library event loops or other third-party loops (uvloop)?
Specifically, I'd like an ongoing percentage measure of saturation, not just a binary "is it busy" that this question seems to address.
Answer: Digging source code shows following:

Event loop is basically executing _run_once in while True loop
_run_once does all stuff including waiting for a select to complete
timeout to wait for select isn't stored anywhere outside _run_once

Nothing stops us to reimplementing _run_once, so we can time what we need.
Instead of copying the whole _run_once implementation, we can time right before select, which is when _run_once started (because before select nothing time consuming happens) and time right after select is when _process_events started.
From words to action:
import asyncio

class MeasuredEventLoop(asyncio.SelectorEventLoop):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._total_time = 0
        self._select_time = 0

        self._before_select = None

    # TOTAL TIME:
    def run_forever(self):
        started = self.time()
        try:
            super().run_forever()
        finally:
            finished = self.time()
            self._total_time = finished - started

    # SELECT TIME:
    def _run_once(self):
        self._before_select = self.time()
        super()._run_once()

    def _process_events(self, *args, **kwargs):
        after_select = self.time()
        self._select_time += after_select - self._before_select
        super()._process_events(*args, **kwargs)

    # REPORT:
    def close(self, *args, **kwargs):
        super().close(*args, **kwargs)

        select = self._select_time
        cpu = self._total_time - self._select_time
        total = self._total_time

        print(f'Waited for select: {select:.{3}f}')
        print(f'Did other stuff: {cpu:.{3}f}')
        print(f'Total time: {total:.{3}f}')

Let's test it:
import time

async def main():
    await asyncio.sleep(1)  # simulate I/O, will be handled by selectors
    time.sleep(0.01)        # CPU job, executed here, outside event loop
    await asyncio.sleep(1)
    time.sleep(0.01)

loop = MeasuredEventLoop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.close()

Result:
Waited for select: 2.000
Did other stuff: 0.032
Total time: 2.032

Let's test it against code with real I/O:
import aiohttp

async def io_operation(delay):
    async with aiohttp.ClientSession() as session:
        async with session.get(f'http://httpbin.org/delay/{delay}') as resp:
            await resp.text()

async def main():
    await asyncio.gather(*[
        io_operation(delay=1),
        io_operation(delay=2),
        io_operation(delay=3),
    ])

Result:
Waited for select: 3.250
Did other stuff: 0.016
Total time: 3.266

Answer: One way of measuring how much time the CPU was busy (applicable for all sorts of IO-bound situations, not just async) is to periodically check time.process_time().
For example, here's how I would implement something which occasionally prints the percentage of time that the loop was "busy" because the process was running code on the CPU:
import asyncio
import time

async def monitor():
    while True:
        before = time.process_time()
        await asyncio.sleep(10)
        after = time.process_time()
        print('{:.2%}'.format((after - before) / 10))

async def busy_wait():
    while True:
        await asyncio.sleep(.001)

loop = asyncio.get_event_loop()
loop.create_task(monitor())
loop.create_task(busy_wait())
loop.run_forever()

The monitor coroutine measures the amount of process time elapsed every 10 seconds, and prints it as a percentage of the full 10 seconds.
The busy_wait coroutine generates artificial load on the CPU by repeatedly sleeping for short periods. By increasing the length of the sleep you can make the process time ratio decrease arbitrarily, and by decreasing the length of the sleep to 0 you can make the process time approach 100% of the wall-clock time.
One caveat: this will only tell you how busy the python event loop is in terms of time spent "running python code" (in the CPU-bound sense). If someone is blocking the event loop with calls to time.sleep() (rather than asyncio.sleep()), my method will show the loop as being free but it is really "busy" in the sense that it is blocked by a system-level sleep. Most correctly written async code shouldn't call time.sleep() or do blocking IO, but if it does, it will not be reflected correctly by this type of monitoring.
Comment: This assumes that the event loop is spent doing very CPU-intensive tasks. At one extreme if you drop a `time.sleep(x)` into a call somewhere, it will show the event loop is very free. I'm not that familiar with how kernels will split up tasks, but if a process grabs some memory that's not cached, it'll take a while to get and other jobs may be run in the meanwhile? Dunno how that would appear as process time...


Nodes with Views

Question: I am trying to construct a page template where I display node information in the content area, and some views in a sidebar that display data from another node type.  I am using the Entity Reference module.  I am displaying apartment units, and these unit content types have a many-to-one relationship to its community complex.  So, when the user views the unit profile, its community data will pop up on the side.
Anyone know the best way to go about doing this?
Answer: Have a node_reference field in the content type Apartment Unit.
Use node id from content as the contextual filter.
Use the node_reference field as a relationship in the view that you create. When you go to the fields section now(after adding the relationship), now you can add the fields from the referenced community complex.
Comment: Should I install the References module and not the Entity Reference module?  I removed the reference I had from the community content type and added it to the apartment unit type.  So, when we add a new unit, we'll just select the community it belongs to.  However, the contextual filter doesn't seem to work.  I set the filter to the field (that resides in the Community content type).
Comment: My bad, I have updated the description.
Comment: Actually, I spoke too soon.  All apartment units are showing up for any community.
Comment: On a apartment page, you wanted to display the data regarding community right?
Comment: Actually, both ways.  On an Apartment, I want to display community information.  In a community, I want to display properties of that community.  I'm making it confusing....
Comment: OK, I got it to work for the Community page with a view of Apartments for that community.  Now I'm trying to do it the other way, for when I bring up an apartment, I should see the community it belongs to.
Answer: I figured it out.  In the view, in Relationships, choose Entity Reference: Referencing Entity.  Click 'Require this relationship'. Next, add a Contextual filter for Content:Nid.  Under Relationship, select the ID you set up in Relationships.
For 'When the filter is NOT available', select 'Provide default' with 'Content ID from URL'.  Below that, for when filter IS available, select Validator.
That worked for me.

Nodes with Views


Optimize CSS file size too big

Question: I'm trying to check my website speed by Google PageSpeed Tools.
Google PageSpeed Tool result:

<code>http://cellsoftware.co.uk/wp-content/cache/autoptimize/css/autoptimize_741fb0cdb70079b195ed32dd2fe38206.css
</code>
The css file is too much big. I downloaded for check the size and it's size 1.11MB . After then I'm trying to reduce css by Critical Path CSS Generator  it's capacity MAX: 800000 characters but my css file have 1169501 characters. So it's can't reduce.
So what process I can use for optimization ?
Answer: A bit late, but my approach would be to see why your CSS file is so large. 1.11MiB for styling is too much. For comparison, a good size CSS should be under 150KiB, perhaps 200KiB maximum. In the case that your CSS is over that, you may have some optimizations you can do. A few points of optimization:

Unused CSS. Does your stylesheet contain CSS rules that aren't even used? There are tools out there that can scan/crawl your entire site and provide you with references to unused style lines.
Any data URI's like base64 encoded images in your CSS? Perhaps consider pulling these out. However, if this is your case, you can probably optimize the images through some sort of image file size crunching tool then re-encode them for your CSS.
Style duplication. If a group of classes have a large portion of style overlap, they should share a style definition and then be altered separately further down the CSS for specific style requirements.
Overuse of complex selectors. Generally having an ID or class name is preferred and one should avoid complex cascading DOM selectors. This not only hurts the browser parsing of the CSS but bloats the CSS file itself.

If you're using a template (looks like you're using Wordpress), then I'd almost suggest throwing out your current template, getting a nice lean one that is close to what you want and further styling that one with the above rules in mind. I believe that may be your quickest route to a speedy site.

Optimize CSS file size too big


FInite automata to regular expression clarification

Question: Can you check on this: https://dl.dropbox.com/u/25439537/finite%20automata.png
This is a checked homework, so don't worry. I just want to clarify whether my answer is correct or not, because it is marked by my teacher as incorrect.
My answer is ((a+b)(a+b))*a
The first (a+b) signifies the upper arrows. The second (a+b) signifies the lower arrows. The last 'a' tells us that it should always end in 'a'.
I just want to record evidences from a lot of experts so that I can give it to my teacher.
Answer: I believe your answer is correct.
Let's consider the whole process as two parts: (1) start with start, and go back to start; and (2) go from start to end and accept. Obviously, the (1) part is a loop.
For (1), starting with start, either accept b or a. For b, it's b(a+b) to go back. For a, it's a(a+b) to go back. So (1) is b(a+b) + a(a+b) which is (a+b)(a+b).
For (2), it's a'.
So, the final result is (loop in (1))* (2) i.e. ( (a+b)(a+b) )* a.
Follow the description above, you can also come up with a proof of the equivalence between the two. Proof part (a) every sequence accepted by the automata is in the set ((a+b)(a+b))*a; part (b) every sequence in the set ((a+b)(a+b))*a is accepted by the automata.
Answer: Your answer is wrong, because it doesn't provide for strings starting with b.
The path (start) -> b -> a+b -> a -> (end) is accepted by your finite automaton, but not by your regex. The simplest counterexample to your answer being correct is the regex's rejection of the string "baba".
By the way, if the teacher gave you that regex without the "end" state having two concentric circles (to indicate being an accept state) it was probably a trick question. Having no accept state means your automaton rejects everything. The best way to describe that would be to just write down {} (the empty set).
Comment: In our discussion, (a+b) is equivalent to 'a' OR 'b', okay? so I can actually start at b in my regex since I can choose 'b' in my first (a+b) expression.
Comment: 'baba' CANNOT be accepted in both finite automata and regular expression. try it out. it would just end at the start position.
Comment: Regular expressions containing a+ typically indicate aa*. That's one instance of a, followed by a*, representing zero to infinite consecutive instances of a (see: http://en.wikipedia.org/wiki/Kleene_star). a OR b is usually represented as a|b in a written regex, but in a drawn FA, it tends to be two edges with common source and destination nodes, one labeled a, and the other labeled b.. The notation in your class is unlike anything I've seen in relation to finite automata (though I've seen + used as inclusive OR in boolean algebra).


Android Child Activity Canvas Size Width Limited

Question: I have written an app with a main activity GUI consisting of multiple buttons and text views within a relative layout specified by an XML layout file. It occupies approximately half the landscape width and two thirds the height.
I wish to call a child activity with a full screen canvas that, when activated, would cover up the then paused main activity GUI.
I have made a separate app that uses an onDraw(Canvas) class called DrawView that provides,  when run as a stand alone app, the full screen canvas that I want. It is constructed from an activity with the code that is shown below.
The problem I have is that when I merge this code into my main package and start the canvas activity from the main activity the window width for the canvas is reduced from 1280 to 696 pixels according to the getWidth() method. It appears my parent main activity limits the child activity window size. I don't know what is causing this width reduction nor how to control it. I have tried many options to no avail. How do I prevent this width reduction from happening? Is it controlled by an Android scheme? Can this be overridden?
Thanks in advance for any help!
<code>    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set full screen view
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);

        drawView = new DrawView(this);
        setContentView(drawView);
        drawView.requestFocus();
        drawView.setBackgroundColor(0xFFFFFFFF);
    }
</code>
Comment: A picture is worth a thousand words.
Answer: I am answering my own question here just in case there is someone else who is new to I imagine common high level graphics terminology runs into this same problem.
All I needed to do was remove the manifest file "themes" line for this activity which was:
android:theme="@android:style/Theme.Holo.Dialog"
The Dialog theme limits the size of the Activity window to a typical user input dialog screen size.


Trying to display a binary representation

Question: I am working a serial stepper motor controller and programming it in C. The problem I have run into is that the controller returns values in binary representations and I am not sure how to display. Obviously converting it to int is not an option as I need the exact binary representation that the controller sends.
The output is of the form:
MSB -> LSB (Most Significant Bit to Least Significant Bit).
At the moment I am trying something like:
char buff[] = "@01 STAT\r";
char readbuff[10];
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
n = write (fd,buff, len);
......

n = read(fd, readbuff, 3);
printf("STAT returns %c\n", readbuff);
......

This returns nonsensical data ie weird shapes and symbols. I have set output to raw and am using 0 parity. I have skipped the initialization parameters but can add them if it helps.
If anyone is curious I am using an Ocean Control KTA-190 Serial Stepper Motor.
Answer: You're printing out the values as %c, i.e. ASCII characters, hence the "weird shapes and symbols".
If you change %c to %d or %x then you will get the decimal or hexadecimal representation of the value. You can then interpret that as binary as you wish (for example 0x0A would be 00001010).
You also need to make sure you get each character out of readbuff. You might want to loop through and print out %x for each array index, as in:
for (i = 0; i < 10; i++)
{
    printf("readbuff[%d]: 0x%x\n", i, readbuff[i]);
}

(Note, it is better to avoid magic numbers, so it would be nicer to do something like #define READBUFF_LEN 10
and then use READBUFF_LEN in place of 10 in the definition of readbuff and the loop termination condition.
If you really want the binary value printed out, i.e. it is not sufficient to print out hex or decimal, then you will need to do this conversion yourself using bit shifting.
There's an example of how to do this in the answers here: Is there a printf converter to print in binary format?


How to find the critical points of a polynomial?

Question: I need help finding the critical points of the function $x^5+x^4-2x^2$, I don't understand, can someone help show me how to find the critical points please
Comment: Do you know how to differentiate this function?
Answer: Hint: Try differentiating $f(x) = x^5 + x^4 - 2x^2$.
Then try to find the values of $x$ at which $f^\prime(x) = 0.$  One such value for $x$ will be clear. Then try to find the second root, by approximating, if necessary.
See for example, the plot of your function close to the origin:
.

In general, for finding critical points $c$ of a function $f$ (not necessarily a polynomial), the following may help:
Critical point checklist:
Given a function $f(x)$ defined on an interval $J$ and a point $c$ in $J$ in its domain, then...
<code>either f(x) is continuous at x = c or it is not. If f(x) is not continuous at x = c, then c is a critical point. If f(x) IS continuous at x = c, then

    either c is an endpoint of J or it is not. If c is an endpoint of J, then c is a critical point. If c is NOT an endpoint of J, then

        either f '(c) is defined or it is not. If f '(c) is not defined, then c is a critical point. If f '(c) IS defined, then

            either f '(c) = 0 or f '(c) 0. If f '(c) = 0, then c is a critical point. If f '(c) 0, then f '(c) is not a critical point.
</code>
Answer: You take the derivative-what do you get?  Then set it to zero.  You should have a fourth degree derivative.  One root is obvious.  There is a second real one that you can only approximate unless you want to solve a messy cubic.


Not able to change colour of the fragment toolbar

Question: I am making an activity with two fragments and I want to change the color of each fragment when I go to it.
I've tried
getActionBar()

and
setColorDrawable()

but it is returning null.
Here is my activity and fragment.
      public class MenuPage extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private TabLayout tabLayout;
private ViewPager viewPager;

public List<Food> orderedList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu_page);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

   private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Veg(), "VEG");
    adapter.addFragment(new NonVeg(), "NON-VEG");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

and here is my fragment
  public class Veg extends Fragment{

public Veg() {
}

public static Veg newInstance(String param1, String param2) {
    Veg fragment = new Veg();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

}
Please help, I am stuck...
Comment: Where is color change code in fragment ?
Answer: As you are using AppCompactActivity, you need to use getSupportActionBar() instead of getActionBar().
Answer: Use this line of code in your MenuPage activity to set custom color in your fragment toolbar
getSupportActionBar().setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#00695C")));

Comment: But I want to change color as I change the fragment.@Sudip Podder
Comment: are you looking for something like [this](https://gfycat.com/CautiousBewitchedJabiru)? Then you may follow [this link](http://stackoverflow.com/a/26813188/5829624).


Strange volume fluctuations

Question: When I plug my electric guitar into a multi-effects pedal and from the pedal into my amp, it works perfectly. But, when I use the same guitar, pedal, and cords that were just functioning correctly, but connect to a PA instead of an amp, the volume fluctuates - almost like a tremolo, but not at any particular tempo.
To be clear, these strange fluctuations happen regardless of the effect I choose, but none of the other instruments/vocals through the PA are affected. I can't figure out what this could be, especially considering that the exact same setup works fine through an amp. Thoughts?
Comment: What kind of PA? Normally guitar signals won't work well plugged right into a PA or mixer unless it has a high impedance input. Or you can use a DI box. A guitar amp and a PA input are very different.
Comment: Though, a digital multi-effect pedal should normally work fine into a mixer's low-impedance line input.
Comment: @ToddWilcox - Mixer is a Mackie 2404 VLZ4 to powered Mackie Thumps. I might try a DI like I use for my keyboardist, but that still leaves me confused. I know a PA and amp are very different, but another guitarist uses her multi effects pedal without any problem, and my acoustic pedal works well, too. No high impedance input needed for those.... Thoughts? Thanks in advance.
Comment: @leftaroundabout That's what I thought, too. I don't know why other pedals are working but mine's not. Especially when it was fine through an amp. Same guitar, pedal, cords, etc.
Answer: Is there a compressor on the mixer? I wonder if you are hearing the pumping of a compressor. If your signal is overly compressed, you may hear some strange volume changes. I suppose it could sound like a wonky tremolo.
Comment: Again, apologies for not getting back sooner, and thanks for trying to help. Notifications were coming to my inbox, and then randomly started going to spam.

Turns out the pedal "went bad" suddenly and with no indication until it was connected to the PA. Go figure.
Answer: I had the same situation when plugged into a Fender Passport. As it happened, the system had a feature called priority, controlled by a single knob, which would permit the first channel to override the other channels when sound was picked up by the first channel, resulting in automatic decrease in volume in the secondary channels. Supposedly designed to enable use of the system in situations where announcements are made during a performance, the whole idea caused us nothing but headaches for us during our performance just because that single knob was improperly set, I don't know about your set-up but it might be worth checking into.
Comment: Thanks for the help! For some reason the email with this notification went to spam so...excuse the delay. It turns out the volume fluctuations were caused by the pedal itself. It was so strange...

The pedal worked through the amp, then in the ten feet between the amp and the PA, it went bad. I tested all the cables and used another guitar to confirm. Plugged back into the amp and the problems from the PA were there. No idea what I did in that short trip across the room.

Strange volume fluctuations


Where to add license of windward in .net core

Question: I am new to windward & I want to use .net core with windward restful engine.Where I can add windward license in .net core.I am getting windward license excpetion in .net core
Answer: Unfortunately, Windward products don't yet support .NET Core, but you can use our RESTful engine which has to be hosted on a Windows Server running IIS and it will answer POSTs and GETs from your .NET Core application.
If you have more questions, please contact Windward Support at firstname.lastname@example.com.


Grassmann manifold (example Abraham, Marsden, Ratiu book)

Question: I am reading, the book Manifolds, Tensor analysis of Abraham, Marsden and Ratiu. In particular, there are several points that I do not understand about a Grassmann manifold. The example starts like this,
I can not see why the applications $\pi_{G}(F,H)$ is in $L(F,H))$ and why is invertible. (Maybe, it's because I do not understand what the projections are doing).
Later in the demonstration, they define for $\alpha\in L(F,G)$ the graph of $\alpha$ by $$\Gamma_{F,G}(\alpha)=\{f+\alpha(f);f\in F\}$$ which is a closed subspace of $E=F\oplus G$, but I can not see this either, I thought to occupy the theorem of the closed graph.
Could you please help me, thank you!
Answer: Let $x\in F$, suppose that $\pi_G(F,H)(x)=0$, you can write $x=x_G+x_H$ where $x_G\in G$ and $x_H\in H$, you deduce that $\pi_G(F,H)(x)=\pi_H(x)=x_H=0$, this implies that $x\in G$, since $G\cap F=0$, you deduce that $x=0$.
Let $y\in H$ write $y=x_F+x_G, x_F\in F, x_G\in G, \pi_G(F,H)(y)=\pi_H(x_F+x_G)=\pi_H(x_F)=y$ implies that $\pi_G(F,H)$ is surjective. You deduce that $\pi_G(F,H)$ is bijective. The open mapping theorem implies that $\pi_G(F,H)$ is invertible.
For the second question, consider: $L:F\oplus G\rightarrow G$ defined by $L(f+g)=g-\alpha(f))$, show that $L$ is continuous and consider $L^{-1}(0)$.


For a Steiner system, how many blocks intersect exactly one position of a specific block?

Question: Consider Steiner system $S(2,k,v)$ with $2 = t < k < v$, a family of $k$-subsets of finite set $S$ with $|S|=v$ such that each $t$-subset of $S$ is contained in exactly one block.
A paper I'm reading states without proof that, for some specific block $B$, "the number of blocks meeting $B$ in exactly one specified point" (containing exactly one specified element of $B$) is $\frac{v-k}{k-1}$, and therefore the number meeting $B$ in a single point is $\frac{k(v-k)}{k-1}$.
It also says the number of blocks not meeting $B$ at all is $\chi=\frac{v(v-1)}{k(k-1)}-\frac{k(v-k)}{k-1}-1$.
Where did these expressions come from?
Answer: Since $t=2$, any block $B'\neq B$ is either disjoint from $B$, or meets $B$ in exactly one point $x\in B\cap B'$.
Now how many blocks $B'$ are there that meet $B$ in exactly one specified point $x$? Every such block $B'$ must also have at least one point $z \in S\setminus B$.
You can count all such points $z$ (there are $|S\setminus B| = v - k$) of them, but since different values of $z$ might yield the same block $B'$, you will have to divide that number by the size of $B'\cap (S\setminus B) = B'\setminus B$ (which is $k-1$ by the initial remark).
In summary, the number of blocks $B'$ meeting $B$ in $x$ is $\frac{v-k}{k-1}$, and since $B$ contains $k$ such points $x$, multiplying that fraction by $k$ gives you the number of blocks $B'$ meeting $B$ in some single point.
Your last equation is simply a way to re-phrase the initial remark: The number of blocks disjoint from $B$ is the total number of blocks ($\frac{v(v-1)}{k(k-1)}$) minus the number of blocks intersecting $B$ in one point (the number just calculated) minus 1 (for the block $B$ itself).


Give the interval for which $\frac{\ln(t)}{1+t^{x}}$ is differentiable

Question: We are given the function: $$f(x) = \frac{\ln(t)}{1+t^{x}}$$ and are asked to show for which interval $I \subset \Bbb{R}$, where I can be unbounded, $f(x)$ is derivable.
I'm not sure how to start working this out, so any help would be appreciated.
Thank you in advance.
Comment: You have $\frac{1}{1+t^{x}}$ in the title and $\frac{\ln(t)}{1+t^{x}}$ in the body. Which one do you want to know is driveable?
Comment: Do you know the chain rule and the derivative of $t^x$?
Comment: Sorry for the confusion, I edited the title a bit to make it more clear. And yes we know the chain rule, but not the derivative of $t^{x}$ if we don't prove it.
Answer: I assume you mean differentiable.
Since it's a function of $x$, the factor $\ln(t)$ can be viewed as a constant, just use the linearity of the derivative in the end. Since nothing is mentioned I assumed that $f: \mathbb{R} \to \mathbb{R}$ and then $t>0$,
$$
\lim_{h \to 0}\frac{\frac{1}{1+t^{x+h}} - \frac{1}{1+t^x}}{h} = \lim_{h \to 0} \frac{1+t^x - (1 + t^{x+h})}{h(1+t^x)(1+t^{x+h})} = \\ \lim_{h \to 0} \frac{t^x(1-t^{h})}{h(1+t^x)(1+t^{x+h})} =  \frac{t^x}{1+t^x} \cdot \lim_{h \to 0}\frac{1-t^h}{h(1+t^{x+h})} =\\ / \text{ h'opitals rule }/ = \frac{t^x}{1+t^x} \cdot \lim_{h \to 0}\frac{-t^h \ln(t)}{t^{h+x} + 1 + h\ln(t)t^{h+x}} \\ = \frac{-t^x \ln(t)}{(1+t^x)^2}
$$
Thus $f'(x) = \frac{-t^x \ln(t)^2}{(1+t^x)^2}$
Comment: Why downvotes? If I have made mistakes, please let me know.
Comment: I did not downvote, but I assume  they are because you didn't really answer the question. The OP asked the interval where $f(x)$ is derivable, not the derivative of the function. Also, the calculation of the derivative might be a bit overkill, since you don't really have to use the definition (but it is very nice and interesting calculation thou).
Comment: The title of the question says "Show that blabla is deriveable". And to answer the WHERE we need to know where the limit exists. So my train of thought was that if I showed that it's Differentiable, the op can reason when the limits exists. But I understand your point, thanks! @mitchbus
Comment: Sorry, I edited the title to make the question more clear.
Comment: For which points in $\mathbb{R}$ is the above calculation valid? @Pyrus


Economizing finger movement in exercise vs following the book

Question: In Al Di Meola and Bob Aslanian's books "Al Di Meola - A Guide to Chords, Scales & Arpeggios" there's an exercise to strum a chord four times and move from one form to another, fluidly. Below is the excerpt I'm questioning:

Similarly this exercise is to be played the same way:

This makes sense, as it keeps fingers 2-4-3 in the same shape (i.e. economizing finger movement).
I'm trying to determine if there is a reason why I would be told to setup the Gmaj7 with fingers stacked on the fretboard as (high to low) 2-4-3-1 then move them to the Gmaj9, instead of stacking the Gmaj7 as 2-3-4-1? Wouldn't this would economize finger movement and allow me to play smoother/faster, as directed? Or is there a reason why I would want to learn it this way?
Answer: I myself have practiced these exercises too. The way I do it is:

I master each chord shape by following the indicated fingerings
Play the chord changes freely, with no specific time
Practice them with metronome, 1 chord by bar and even 2 bar sometimes
I accelerate and the faster I get the more staccato I play each chord per beat

As I see it, "fluid" here has nothing to do with playing legato but rather  with changing between chords confidently and accurately.
This happens to be an excellent set of warm-up/finger independence exercises.
Answer: It is a bit unclear to me what your precise question is so I will give it my best shot. I understand you're concerned about the fingering of the Gmaj7.
Fingering it as 2-4-3-1 (using your notation) is the most comfortable way to play  a maj7 chord with the root on the 6th string (in this case, Gmaj7). Playing it as 2-3-4-1 would be uncomfortable for your fingers (at least it is for mine!).
Most jazz tetrad chords have only one comfortable fingering. In general, only open chords can have more than 1 valid fingering. Which means that you're stuck in fingering your chord in the "right" way, regardless of the precending and following chords.
I cannot say why the book tells you to practice it this way. I guess that the purpose is not to teach you how to minimize finger movement, but rather to get you to practice chord changes that require you to move your fingers quickly.
The second sequence plays a G chord followed by a clear chromatic sequence maj7 - 7 - maj 6, so I guess the aim of the second sequence is to teach you how to create a chromatic voicing from the maj7 to the maj6.
Comment: You can challenge established technique and develop your own, but you might have higher chances of injury in the long run.
Comment: Fingering 2-4-3-1 isn't necessarily the most comfortable way, I assume it's the way you're most comfortable with. Think of G# augmented, played {4,3,2,1,x,x}. The 4th finger on the 4th fret E, the 3rd on the 3rd fret A, etc. Now place your fingers for an open EM such that your 4th finger is on the A string, 2nd fret. Same pattern, the two fingers are just sharing the same fret "space". My question then is the same, is there any merit to learning the EM shape in the non-traditional manner of fingers stacked 4-3-2, or is there merit in only being able to fluidly move into the 3-4-2 positioning?
Comment: Or in other words why not play an EM [like this](https://imgur.com/XckOkOE) instead of [this](https://imgur.com/rgqCpk6)? Apply the same logic to the Gmaj7 example in the question.
Comment: I think that the fingering you suggest is not anatomically the most comfortable. Technique has evolved over the decades not to just allow us to play things "the way it feels more natural", but rather, to minimize injuries to your hands/fingers, especially for professional musicians who play hours a day. I would argue that given that the pinky finger is shorter than the ring finger, it would cause fewer injuries to play it in the second position you linked, instead of the first. In the G# example, the pinky and the ring finger are on different frets.
Answer: Quite simply because what you describe as "stacking the Gmaj7 as 2-3-4-1" is not a viable fingering for that chord at all.
Others have described that position as not "comfortable", but I'd go further and say it's not viable at all.
You might be able to play it if you slow down and painstakingly place the fingers that way, but it'll be extremely hard, if not impossible, to play it cleanly in real life playing, especially if you go even a bit higher on the fretboard.
And if you don't believe this, just try playing this fingering at fret 5 or higher... ;-)
Answer: More than one factor contributes to "economy".  You are on the right track to think that one should endeavor to try and (1)  find common forms that move without rearranging the fingers, and/or (2) find common notes between neighboring chords so that something stays put.
This is usually very possible when cycling through changes in the circle of 4ths/5ths since there are common tones in the chords.  However, as it has been pointed out, you need to be able to easily play the chords and if the fingers are too contorted this is not possible.


Accessing ActiveX control through web server

Question: I have developed the ActiveX control & register with Common CLSID number .
using the CLSID number accessing the active X control on the internet explorer (as web page).using following object tag used in .html file

OBJECT id="GlobasysActiveX" width="1000" height="480" runat="server" classid="CLSID:E86A9038-368D-4e8f-B389-FDEF38935B2F"

i want to access this web page through web server .I have place this web page into the vitual directory & access using localhost\my.html it's working.
but when i have accessed from LAN computer it will not access the activeX control from my computer .
how to embed or download the activeX control form my computer into the LAN computer through web server
thanks in advance
Answer: Just like Flash or QuickTime, you will have to install and register your plugin on each client before it will work.
You can nest several object tags, if the outer one is not executed, the inner object will execute. In the inner object you can put a notice where to download your plugin installer.


how to select records based on count of column field

Question: I have a scenario that a query who will work like select records based on status = 1 with highly number of records found in database.
suppose i want to select artists who have max number of status = 1 with their names fetch from other table.
another problem is my query is repetiting records.
my query:
SELECT order.status,
       order.artist_id,
       web_user.uFname,
       web_user.uLname,
          web_user.uID
FROM `order`
INNER JOIN `web_user`
ON web_user.uID = order.artist_id
HAVING order.status = '1'

my record set i am getting:
status artistid uFname   uLaname  uID
1      14       Pitbull  Armando  14
1      14       Pitbull  Armando  14
1      13       Enrique  Iglesias 13
1      15       Robyn    Rihanna  15
1      15       Robyn    Rihanna  15
1      15       Robyn    Rihanna  15

i simple want:
downloadtimes artistid uFname   uLaname      uID
2             14       Pitbull  Armando      14
1             13       Enrique  Iglesias     13
3             15       Robyn    Rihanna      15

please enhanced my query.
Answer: You can use COUNT()
SELECT
COUNT(*) AS downloadtimes ,
order.artist_id,
web_user.uFname,
web_user.uLname,
web_user.uID
FROM `order`
INNER JOIN `web_user` ON web_user.uID = order.artist_id
WHERE order.status = '1'
GROUP BY order.artist_id

Comment: thank you but its was keep saying 5minutes wait so i was unable to accept it and keep waiting. :)
Comment: @user3040719 `COUNT(*) AS downloadtimes` is same as `COUNT(*)  downloadtimes` you just need to get the count of each group that is per artist
Comment: yes yes you are right Sir. thank you for the help and meaningful query.
Answer: you should use the count
like:
COUNT(*) AS downloadtimes

you should just add the like you full code:
SELECT
COUNT(*) AS downloadtimes ,
order.artist_id,
web_user.uFname,
web_user.uLname,
web_user.uID
FROM `order`
INNER JOIN `web_user` ON web_user.uID = order.artist_id
WHERE order.status = '1'
GROUP BY order.artist_id

and refer this following link:
SQL COUNT