Two charts with regular peaks and troughs but only one is stationary?

Question: I'm reading Forecasting Principles and Practice section on stationarity. We are shown the following image and asked which are stationary:

Obvious seasonality rules out series (d), (h) and (i). Trends and changing levels rules out series (a), (c), (e), (f) and (i). Increasing variance also rules out (i). That leaves only (b) and (g) as stationary series.

I'm looking at the first two charts on the bottom row, g and h. Both have peaks and troughs.
Why is h considered stationary while g is not?
Answer: The very next paragraph says:

At first glance, the strong cycles in series (g) might appear to make it non-stationary. But these cycles are aperiodic — they are caused when the lynx population becomes too large for the available feed, so that they stop breeding and the population falls to low numbers, then the regeneration of their food sources allows the population to grow again, and so on. In the long-term, the timing of these cycles is not predictable. Hence the series is stationary.


Azure bug when scaling only ONE website (not all of them)

Question: I had one free website in Azure, lets call it "website1".
Then I created another free website (lets call it "website2"), using these settings:

As you can see, I choose: "Create new web hosting plan", so "website2" should be totally unlinked with "website1". They only information they share is the subscription (credit card)
Then, after "website 2" being created, I wanted to scale "website 2" from "Free" to "Shared".
But now they are at the same "web hosting plan", and before I told Azure that they should be different!

So.. my question is:
I want to scale one of them to "Shared" and the other to remain "Free". How can I achieve that?
Comment: Well... this worked: (1) Delete "website 2", (2) Scale up "website1" to "basic", (3) Create "website 2" as a new "web hosting plan", (4) Now one is free and the other "basic", (5) Scale down "website 1" to free, (6) Now one is free and the other shared. THANKS AZURE
Answer: Correct, in the current portal you can't change them independently.
You can change them via the API or use the preview portal.
Read about it at:
http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
Or just visit the preview portal at:
http://portal.azure.com and make the change there.


Transformation of MLE parameters standard deviations calculation

Question: I have run an MLE estimation using R to estimate parameters $\theta_1, \theta_2, \theta_3$, which are:
 0.0002022146  0.0222026625 -6.1910421067

the variance matrix is:
0.00000004574446 0.000001708064 0.0000008477115
0.00000170806367 0.000115362174 0.0000572542168
0.00000084771147 0.000057254217 0.0024674380942

Now, I need to simulate standard deviations for parameters $\kappa=\frac{\theta_1}{\theta_2}$. I have tried:
library(MASS)
df <- mvrnorm(n = 1000000, mu = fit@coef, Sigma = fit@vcov)
kappa<-df[,1]/df[,2]
sdkappa <- sd(kappa)

Is this the correct way? I doubt it, since the mean(kappa) is quite different from $\frac{\hat{\theta_1}}{\hat{\theta_2}}$. What is the proper way of doing this?
Answer: Briefly: your approach is reasonable.  It assumes that the sampling distribution of the MLE is approximately multivariate Normal, and it only makes sense (more generally the ratio of Normals only makes sense) if the mean of the denominator is far from zero ($\textrm{CV}_{\textrm{denom}}$ is large): see this blog post by Andrew Gelman. In your case $\textrm{CV}_2$ is $0.022/\sqrt{0.00011} \approx 2.09$, which is probably OK (I would really worry if CV were $<1$).

I don't know the formal name for this approach: in Ecological Models and Data (2008) ($\S$7.5.3) I call the confidence intervals derived in this way "population prediction intervals".
More approximately you can use the delta method (search here and elsewhere).
In general $f(\bar x, \bar y)$ is not the same as $\overline{f(x,y)}$: this is called Jensen's Inequality. (There is a delta-method-like approximation for estimating the magnitude of JI in particular cases.)
if the distribution of $\theta_1/\theta_2$ is markedly non-Normal, the standard deviation may not be as meaningful as you think (try computing the (0.025,0.975) quantiles of your sampled value and comparing it to the confidence intervals based on $\pm 1.96 \sigma$). (It would be useful to know why you want to calculate standard deviations of $\theta_1/\theta_2$, i.e. how do you plan to use this quantity going forward?)

Other ways of doing this that are less approximate include:

re-parameterizing the model to use $\theta_r= \theta_1/\theta_2$ as a primary parameter (then finding profile confidence intervals for $\theta_r$)
bootstrapping confidence intervals for $\theta_r$
Bayesian approaches (e.g. MCMC) to find the posterior marginal credible intervals of $\theta_r$ based on samples of $\{\theta_1, \theta_2\}$.


DEPRECATION WARNING in heroku during deploying rails app

Question:
Possible Duplicate:
Rails 2.3-style plugins and deprecation warnings running task in Heroku

<code>DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support
 for these plugins will be removed in Rails 4.0. Move them out and bundle them i
n your Gemfile, or fold them in to your app as lib/myplugin/* and config/initial
izers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonr
ails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required
)> at /app/Rakefile:7)
</code>
shows 3 times, sometimes shows 2 times what it means? is there any special meaning?
How to solve this problem for db:migrate
Answer: Heroku "injects" some plugins during slug compilation.
<code>-----> Rails plugin injection
       Injecting rails_log_stdout
       Injecting rails3_serve_static_assets
</code>
See Rails 2.3-style plugins and deprecation warnings running task in Heroku


Store an array of UIViews in NSUserDefaults

Question: I'm trying to add an array of uiviews to NSDefault but it doesn't seem to be keep the array. Does any one know why? I also tried to store each view in nsvalue before storing it in nsdefault which still didn't work.
<code>NSArray *arr = [[NSArray alloc] initWithObjects:[NSValue valueWithNonretainedObject:myView], nil]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arr forKey:@"myKey"];

NSArray *resultArray = [defaults objectForKey:@"myKey"];
</code>
and resultArray is nil!
Thanks
the reason why I'm trying to do this is because these are the header views of my uitableview. Since it takes time to create them I wanted to create them only once and store them for future access.
Comment: Why would you want to do this?  This is not what NSUserDefaults was designed for.  If you describe what you are trying to accomplish perhaps StackOverflow can give you a better method.
Comment: In that case how about converting these UIViews to UIImages and storing in document folder so that next time you can just add it in an imageView. I am not sure if you should be using NSUserDefaults for storing UIViews.
Answer: From the docs for NSUserDefaults:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

If you want to put a UIView (why?) in NSUserDefaults, you need to archive it first into an NSData object.
But you need to ask yourself why you want to put a view in NSUserDefaults. You should only be putting bits of data in NSUserDefaults. Views display data. It's easy to redisplay a view once you have the data back. Consider just putting some needed data in NSUserDefaults.
Comment: is it possible to store uiview in nsdata?
Comment: I wouldn't have told you that you need to archive the view into an NSData object if it wasn't possible. You need to use an NSKeyedArchiver to do it. But again, this is a really bad way of doing things. This is not the purpose of NSUserDefaults. If you really insist on archiving the view, at least store it in a file and not in NSUserDefaults. How long does it actually take to create these views? Do you think recreating them from an archive will be much faster?
Comment: Having tested this recently, NSKeyedArchiver does not guarantee the that the data generated for a view will be unarchived in the exact state that it was left.  I tried attempting this using some drawing code and some gif Imageviews and it did not unarchive properly
Answer: Are you sure you want to do that? It is definitely better to store an array of models to the data base or some file and recreate views from them when needed.
Comment: @Mona `NSUserDefaults` is just for small user settings, things like images, models or some other data have to be stored either in db or in files. In your case it is better to save images to files, and i recommend you to use [SDWebImage library](https://github.com/rs/SDWebImage), it does everything for you (memcache and disk cache) and it is very simple to use.
Comment: @Mona You should store the images to a file, not in NSUserDefaults.
Comment: I figured the reason why it takes so much time to load the my uiview headers was because of the image that they had to load from the server each time. so I only stored those images into nsdata and stored those on nsuserdefault. so now when i want to access them again it doesn't have to load the images from the server so it creates the header views almost instantly now.
Answer: A ha!  You are not the first person to face this issue.  I've not had this type of issue myself but, in the link below, is a blog with code that allows you to cache and re-use your views.  Then you would only need to re-create the views when you launch.  Example code:
Cache UIViews for re-use in tableview


padding not working on border-ed div

Question: I am trying to put a circle border around a div with a background image. I want the background image to be as big as can be with a 10px padding between it and the border. This image transitions (scaled down) to 50px when user scrolls and the border is removed so it needs to remain a background image that takes up as much space as possible
css
.brand, .brand:visited, .brand:hover {
 display: block;
 position: relative;
 height: 100px; width: 100px;
 margin-top: 25px;
 background: url('img/logo.png') no-repeat center center;
 background-size: 100% auto;
 padding: 10px;
 border: 1px solid #fff;
 border-radius: 50%;
}

Everything works except for the padding. Not sure how to fix it. ALSO, I don't want the background image clipped
Answer: The background of an element applies to any padding...unless the background-clip property is changed.

* {
  box-sizing: border-box;
}
.brand {
  margin: 25px auto;
  position: relative;
  height: 100px;
  width: 100px;
  background: url('http://lorempixel.com/image_output/city-q-c-200-200-7.jpg') no-repeat center center;
  background-size: 100% auto;
  padding: 10px;
  border: 1px solid red;
  border-radius: 50%;
  background-clip: content-box;
}
.brand:hover {
  padding: 5px;
}

Alternative: Use a wide border and a box-shadow for the outer "border".

* {
  box-sizing: border-box;
}
.brand {
  margin: 25px auto;
  position: relative;
  height: 100px;
  width: 100px;
  background: url('http://lorempixel.com/image_output/city-q-c-200-200-7.jpg') no-repeat center center;
  background-size: 100% auto;
  box-shadow: 0px 0px 0px 1px red;
  border: 10px solid white;
  border-radius: 50%;
}
.brand:hover {
  border-width: 5px;
}

Comment: I don't want the image clipped though
Comment: Good answer Paulie, from here on the user can CUSTOMIZE it to there need.
Comment: Added an alternative option.
Comment: looks good thank you, seems like easiest answer, but would a transparent border work since it may appear overtop an image so the thick border color would show
Comment: You could try it but I think you might get an odd result.
Comment: crap, thats why I was hoping for padding to work, It needs to look like a border/outline with space in between
Comment: You can still use the first option just play with the background size.
Answer: Here is a border added to the .brand class with an relative positioned .brand where the :after pseudo class is positioned absolute.
this is to create an cricle that goes outside the shape.

.brand,
.brand:visited,
.brand:hover {
  position: relative;
  height: 100px;
  width: 100px;
  margin-top: 25px;
  margin-left: 25px;
  background: url('http://lorempixel.com/200/200') no-repeat center center;
  background-size: 100% auto;
  border-radius: 50%;
}
.brand:before {
  display: inline-block;
  position: absolute;
  left: -15px;
  top: -15px;
  content: "";
  width: 120px;
  height: 120px;
  border: 5px solid #fff;
  border-radius: 50%;
}
body {
  background-color: #222;
}

Comment: Btw, you need to change `//border: 5px solid #fff;` to `/*border: 5px solid #fff;*/` as you can't use `//` with CSS.
Comment: Wel as that is technicaly true, any rules that are "wrong" are ingnored so adding // breaks the rule.
Answer: As far as I know, it's not possible to have an unclipped background: take account of padding:.
So... this is a little bit hacky, but you can:

Declare box-sizing: border-box;
Have a border: stand in for padding:; and then
Have a box-shadow: stand in for border:.

See example below:

/* Your original styles */
.brand, .brand:visited, .brand:hover {
 display: block;
 position: relative;
 height: 100px; width: 100px;
 margin-top: 25px;
 background: url('img/logo.png') no-repeat center center;
 background-size: 100% auto;
 padding: 10px;
 border: 1px solid #fff;
 border-radius: 50%;
}

/* A few extra styles just to make the background and border visible */
.brand, .brand:visited, .brand:hover {
 background-color: rgb(0,0,0);
 border: 1px solid rgb(255,0,0);
}

/* An alternative using border-box, and box-shadow */
.brand2, .brand2:visited, .brand2:hover {
 display: block;
 position: relative;
 height: 122px; width: 122px;
 margin-top: 25px;
 background: url('img/logo.png') no-repeat center center;
 background-size: 100% auto;
 background-color: rgb(0,0,0);
 border: 10px solid #fff;
 border-radius: 50%;
 box-sizing: border-box;
 box-shadow:1px 1px rgb(255,0,0), 1px -1px rgb(255,0,0), -1px -1px rgb(255,0,0), -1px 1px rgb(255,0,0);
}

/* Lining everything up */
div[class^='brand'] {
float: left;
margin-right:20px;
}

Comment: will that cut off the background image, I have it set so that it fills the div. So I get that it ignores the padding. I just need space between the edge of the background and the border
Comment: The circles in the example above have exactly the same radius. The first `content-box` circle is `50px` content-radius + `10px` padding + `1px` border (`61px`), the second `border-box` circle is `61px` radius (including `50px` content-radius, `10px` border & `1px` box-shadow). In  both cases, the content-radius is `50px`. So, if your background-image is `100px` x `100px`, nothing (except the corners) will be cut off, no.

padding not working on border-ed div


How create an ASP.NET C# that can generate its own field and and new panels?

Question: I am trying to create a web app that can create a survey form just like google forms.
<asp:Panel ID="container" runat="server"></asp:Panel>
<asp:Panel ID="question" runat="server" Height="391px">

    <asp:Label ID="Label1" runat="server" Text="Question:  " Font-Size="Large"></asp:Label>
    <asp:TextBox ID="txtQuestion" runat="server" Font-Size="Large"></asp:TextBox>
    <asp:DropDownList ID="lstQuestionType" runat="server">
        <asp:ListItem Enabled="False" Selected="True">Question Type</asp:ListItem>
        <asp:ListItem>Short Answer</asp:ListItem>
        <asp:ListItem>Paragraph</asp:ListItem>
        <asp:ListItem>Multiple Choice</asp:ListItem>
        <asp:ListItem>Check Box</asp:ListItem>
        <asp:ListItem>Linear Scale</asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="btnGenerate" runat="server" OnClick="btnGenerate_Click" Text="Generate Question" Width="137px" />
</asp:Panel>

<asp:Button ID="btnAddQuestion" runat="server" Text="Add Question" OnClick="btnAddQuestion_Click" />

and this is the C# code that generates the panel
protected void btnAddQuestion_Click(object sender, EventArgs e)
{
    Panel newQuestions = new Panel();
    newQuestions = question;
    container.Controls.Add(newQuestions);
}

but when I click the add question button, it does not add the panel
Answer: Although i can't tell from the code probably the problem is with the question parameter. Also use MVC with controllers it will be much more clean and also VS automatically generates the View for you based on your models and controllers which i guess it will save you time in the long run.


Are intermediate field extensions of a Galois extension Galois?

Question: Let $F \subset E$ be a Galois extension.  Let $F \subset G \subset E$.  What can we say about 'being Galois' for extensions $F \subset G$ and $G \subset E$?
I think for $G \subset E$ the answer is that it is Galois.  To show Galois I need to show normal and separable.  I have a theorem that says it will be normal so all thats left is to show it is separable.  $F \subset E$ being separable means the irreducible polynomial of any element $u \in E$ over has no multiple roots in any further extension of $E$, but I'm not sure how this means any polynomial over $G$ would also have no multiple roots.
For $F \subset G$ I'm not even sure what the answer is.  I thought no, but I see something later in my notes that makes me think it is.  I don't know how to show normal, but for separability I have: The extension of $E$ over $F$ being separable means the irreducible polynomial of any element $u \in E$ over has no multiple roots in any further extension of $E$.  If x is a root in $G$ then x will also be a root in an extension of $G$ so since there are no multiple roots in $E$ there are none in $G$ so it is separable.
Comment: $G\subset E$ is indeed always Galois. $F\subset G$ needn't be; that's actually equivalent to the Galois group $Gal(E/G)$ being normal in $Gal(E/F)$.
Answer: See the fundamental theorem of Galois theory. As has been pointed out in the comments by Wojowu, $E/G$ is always Galois, but $G/F$ is Galois iff $Gal(E/G)\triangleleft Gal(E/F)$ in which case $Gal(G/F)\cong Gal(E/F)/Gal(E/G)$
Comment: I haven't gotten to that yet, but I think I figured it out
Answer: Hint: Consider $\mathbb Q \subseteq \mathbb Q(\sqrt[3]{2}) \subseteq \mathbb Q(\sqrt[3]{2},\omega)$, where $\omega$ is a primitive cubic root of unity.


How to find integral $\underbrace{\int\sqrt{2+\sqrt{2+\sqrt{2+\cdots+\sqrt{2+x}}}}}_{n}dx,x>-2$

Question: Find the integral
$$\int\underbrace{\sqrt{2+\sqrt{2+\sqrt{2+\cdots+\sqrt{2+x}}}}}_{n}dx,x>-2$$
where $n$ define  the number of  the square
I know  this  if
$0 \le x\le 2$, then let $$x=2\cos{t},0\le t\le\dfrac{\pi}{2}$$
so
$$\sqrt{2+x}=\sqrt{2+2\cos{t}}=2\cos{\dfrac{t}{2}}$$
so
$$\sqrt{2+\sqrt{2+x}}=2\cos{\dfrac{t}{2^2}}$$
so
$$\int\sqrt{2+\sqrt{2+\sqrt{2+\cdots+\sqrt{2+x}}}}dx=\int2\cos{\dfrac{t}{2^n}}(-2\sin{t})dt$$
and for $x\ge 2$ case, I  let
$x=\cosh{t}$, but for  $-2\le x\le 0$ case, I can't do it.
Comment: How many iterations of $\sqrt{2+\ldots}$ are there? Is that your $n$ variable?
Comment: @user2357112,yes,that's mean
Comment: Can't you still take $x=2\cos t$ but with different values of $t$?  If you take $t$ from $\pi/2$ to $\pi$ then $\cos(t/2)$ is still positive so there is no problem with the square root.  Or am I missing something?
Comment: If you are concerned about domain issues, just let $t \in [0, \pi]$ (not only $[0, \frac{\pi}{2}]$) so that $-2 \le 2 \cos t \le 2$.
Comment: @SammyBlack yes indeed.  Do you agree that it is, essentially, just the same as what the OP has done?  I'm still not quite sure if I might have missed something.
Answer: You were too timid: For $-2\leq x\leq2$ use the substitution
$$x=2\cos t\qquad(-\pi\leq t\leq 0)\ .$$
Then everything goes through as before:
$$\sqrt{2+x}=\sqrt{2+2\cos t}=2\cos{t\over2},\quad \sqrt{2+\sqrt{2+x}}=\sqrt{2+\cos{t\over2}}=2\cos{t\over4}\ ,$$
etcetera.
Answer: For the finitely many nested radical case,
$$-4\int \cos\left(\frac{t}{2^n}\right)\sin t\,dt=-2\int \left(\sin(2^{-n}t+t)-\sin(2^{-n}t-t)\right)\,dt$$
$$=-2\left(-\frac{\cos(t(2^{-n}+1))}{2^{-n}+1}+\frac{\cos(t(2^{-n}-1))}{2^{-n}-1}\right)+C$$
Substitute $t=\arccos(x/2)$ to obtain the answer.
The substitution is valid for $-2\le x\le 2$.
I hope this addresses the issue.
Comment: This seems to be an extension of the OP's work for the $0 \le x \le 2$ case, but the OP is looking for an approach that works for $-2 \le x \le 0$. He's not trying to finish the $0 \le x \le 2$ case; he's probably already done that.
Comment: @user2357112: Yes, sorry, I didn't understand it properly. But for $-2\le x\le 0$, I think we can do the same thing, right?
Comment: I think we can, but this answer makes no attempt to point that out. The integral computations do little to answer the question; the important information is that the approach the OP was already using also works for this case.
Comment: @user2357112: Now its unclear to me what OP is actually asking. Should I add the integral computations for both the cases i.e for $-2\le x \le 2$ and for $x>2$?
Comment: I don't think the integral computations are particularly important at all, but you should probably mention something about this working for $x < 0$.
Answer: I think you have the wrong approach, take a look at this
$$f(x) = \sqrt{2+\sqrt{2+...+\sqrt{2+x}}}   $$
Square both sides
$$(f(x))^2 = 2+\sqrt{2+...+\sqrt{2+x}}   $$
$$(f(x))^2 = 2+f(x) $$
$$(f(x))^2 -f(x)-2= 0 $$
This has two solutions $f(x)=2$ and $f(x)=-1$
Note that $f(x)$ cannot be -1, since square root is always positive for real numbers, and it is given that $x > -2$
Hence you have $f(x)=2$, which is independent of $x$
The answer is therefore finally 2x
Comment: The question is asking about **finitely many** nested radicals.
Comment: if $x\to\infty$,then $f(x)\to  ?$
Comment: @user155188 You have the right functional equation but the wrong roots. The positive root is $2$.


Dynamic access to MySQL database in Java

Question: I am looking for some way how to access MySQL database more dynamically.
For example, I want to insert some text to my table.
I have some method called insert() which is called approximately every half of the second and does the insert stuff.
The code looks like this:
public void insert(String string) {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        java.sql.Connection conn = java.sql.DriverManager.getConnection(...);
        java.sql.Statement stat = conn.createStatement();
        stat.executeUpdate("INSERT INTO mytable (mytext) VALUES ('"+ string +"')");
        conn.close();
}

But I really think this could cause many problems because it is opening and closing connections too often.
So isn't there any way to open some "MySQLStream" to the database and print the data to it without opening and closing the connection again and again?
Thanks for your replies.
Comment: You should be closing connection that is a good practice, the answer here is to use ConnectionPool.
Comment: Use "Connection pools", if you are worried about open/close connections frequently.
Answer: Create a Connection object at the beginning of the program, and use it for every query. Close it only at the end of the program.
Oftentimes one Connection is good, so you may declare it as static.
public static java.sql.Connection conn;
public static void buildConnection()
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = java.sql.DriverManager.getConnection(...);
}

public void insert(String string)
{
    java.sql.Statement stat = conn.createStatement();
    stat.executeUpdate("INSERT INTO mytable (mytext) VALUES ('"+ string +"')");
}

In the program, you may do the following:
buildConnection();
...
insert("....");
insert("....");
...
conn.close();

Comment: Yes thats also the option I was thinking about. And I am going to use it if I won't find other solution.


How to make language choice Required for Taxonomy term

Question: Is there any way to make the language choice required for taxonomy term.
I'm pretty sure there is a way to perform this.
Otherwise, how can I at least set a default language choice for my taxonomy.
By exemple, I would like to make English as default language. That's mean when the user will create a term the first time, the language choice will be english.
Thanks a lot
Comment: What modules are you using for the language choice?
Answer: Write a custom module and use the following code
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='taxonomy_form_term'){
     $form['#after_build'][] = 'MYMODULE_after_build';
  }
}

function MYMODULE_after_build($form, &$form_state) {
   if($form['language']['#value']=='und'){
     $form['language']['#default_value']='en';
     $form['language']['#value']='en';
   }
   return $form;

}
NOTE: In your custom_module.info file use this dependencies[] = i18n_taxonomy, so that your module can only be enabled if internationalization is enabled
Comment: Thanks a lot wolverine :) please see my other question if you can :)


How to implement a singleton in a static library

Question: I have a question regarding how does a singleton in a static library (.a/.lib) behave.
<code>class MySingleton {
public:
     static
     MySingleton&
     GetInstance() {
         static MySingleton singleton;
         return singleton;
     }
private:
     explicit
     MySingleton() {}

     virtual
     ~MySingleton() {}
};
</code>
How can you make sure that on OS level, there is ONLY ONE MySingleton if you use static library?
As you may know, static library has multiple copies in memory. Do those copies interfere with each other or totally irrelevant? Meaning if you have app1 and app2, does app1 has one MySingleton and app2 also has one MySingleton?
How can you meet the requirement that if once app1 starts up and consumes MySingleton, app2 has no chance to create another MySingleton even it holds another copy of static library.
Comment: You might be able to use a named semaphore (http://linux.die.net/man/3/sem_open) to achieve this behaviour. I don't know enough about named semaphores under Linux to help you any further, though.
Comment: This sounds like a bad idea. Why do you want to?
Comment: Let me try to elaborate on my comment: If you manage to marshal the state of your singleton instance for some IPC and then used a (named) semaphore to make other processes aware of existing instances you might be able to simulate what you've described without actually needing to share memory. Isn't sharing state sufficient?
Comment: Each running program (or process) will have its own data including any static singletons. They are unique to the program (or process). This is usually what you want. If you want to share a single object between programs (processes) then you may have to do some clever stuff with *shared memory*. For example your *singleton* could store its data in *shared memory* giving the illusion of one singleton (but hiding the *shared memory* access from the rest of the program), or you could instantiate your singleton in *shared memory*.
Comment: I think the design/architecture is questionable at least. First, Singletons are nowadays considered as an anti-pattern. They are the OO implementation of global variables, with all the drawbacks, and in C++ you get more trouble because of static initialization hell. Second, if you have something that both processes share, I would put it in a separate process which communicates with clients, e.g. via IPC, pipes, messages, shared memory etc. This process can be started automatically, and e.g. use a lock file. Or you start the process as a daemon and let the OS handle it.
Comment: Thanks! @Jens. I think I have to give up the singleton idea for static library design.
Comment: @minghua I am a fan of the service idea. Create a small daemon which is managed by the OS (if it is Linux, for Windows it could be a Service?), and communicate with it via some IPC means. Personally, I like message-passing and would look at zeroMQ, but there could other technologies which are more appropriate to your use-case.
Comment: @Jens, thanks for your info about zeroMQ, I'd have a look.
Answer: At a OS level, Processes do not share any memory, apart from shared libraries.
Process A will have its own instance  of your singleton and Process B will have a completely different instance of singleton and both the processes are isolated from each other.
If you want any logic that involves multiple processes, then think along the lines of a shared library/shared memory.
Comment: Even shared libraries don't share their address space (except for code).
Comment: agree with that..this is difficult/not possible to acheive even with shared libraries...
Comment: i am not sure about this but maybe can be acheived through some shared memory mapping between processes
Comment: Thanks for explanation! @basav


Prove that $ \sqrt{\frac{a}{b+3} } +\sqrt{\frac{b}{c+3} } +\sqrt{\frac{c}{a+3} } \leq \frac{3}{2} $

Question: For all $a, b, c>0$ and $a+b+c=3$ Prove that  $$ \sqrt{\frac{a}{b+3} } +\sqrt{\frac{b}{c+3} } +\sqrt{\frac{c}{a+3} } \leq \frac{3}{2} $$
I tried cauchy-schwarz inequality for the L. H. S like and I get
$ [\left( \sqrt{a} \right) ^{2}+\left( \sqrt{b} \right) ^{2}+\left( \sqrt{c} \right) ^{2}]\left[ \left( \frac{1}{\sqrt{b+3} } \right) ^{2}+\left( \frac{1}{\sqrt{c+3} } \right) ^{2}+\left( \frac{1}{\sqrt{a+3} } \right) ^{2}\right] \geq \left( \frac{\sqrt{a} }{\sqrt{b+3} } +\frac{\sqrt{b} }{\sqrt{c+3} } +\frac{\sqrt{c} }{\sqrt{a+3} } \right) ^{2}$
Then I get by AM-GM the maximum value of $abc=1$ and the inequality have the value 3... How I can prove inequality?.
Comment: @user236182 yes. I edited the question
Comment: The C-S approach won't work. The $LHS$ that you got is too large. Let $(a,b,c)=(2,0.5,0.5)$. Then $\sqrt{[\left( \sqrt{a} \right) ^{2}+\left( \sqrt{b} \right) ^{2}+\left( \sqrt{c} \right) ^{2}]\left[ \left( \frac{1}{\sqrt{b+3} } \right) ^{2}+\left( \frac{1}{\sqrt{c+3} } \right) ^{2}+\left( \frac{1}{\sqrt{a+3} } \right) ^{2}\right]} >\frac{3}{2}$
Comment: @user236182 so could you tell me a little hint?
Comment: @user260699 Could you share the source of this problem? Thanks.
Answer: First, we use Cauchy-Schwartz inequality:
$$
A^2=\left(\sqrt{\frac{a}{b+3} } +\sqrt{\frac{b}{c+3} } +\sqrt{\frac{c}{a+3} }\right)^2 =\\
\left(\sqrt{\frac{a}{(a+3)(b+3)}(a+3) } +\sqrt{\frac{b}{(b+3)(c+3)} (b+3)} +\sqrt{\frac{c}{(c+3)(a+3)}(c+3) }\right)^2 \leq \\
\left({\frac{a}{(a+3)(b+3)} } +{\frac{b}{(b+3)(c+3)} } +{\frac{c}{(c+3)(a+3)} }\right)\times (a+3+b+3+c+3) .
$$
Since $a+3+b+3+c+3=12$, it is enough to prove:
$$
\left({\frac{a}{(a+3)(b+3)} } +{\frac{b}{(b+3)(c+3)} } +{\frac{c}{(c+3)(a+3)} }\right)\leq \frac 3{16}. (\star)
$$
From this step on, I went the ugly way, since the manipulation was not so frightening. With a simple and nice proof of this step, the whole proof would become much easier.
Anyway, after the simple multiplications, we get to the following inequality:
$$
18-7(ab+ac+bc)+3abc\geq 0.
$$
This can be further simplified, using the fact such as $a^2+b^2+c^2=9-2(ab+ac+bc)$ and using the famous following identity:
$$
a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-ac-bc).
$$
We can further simplify the inequality to the following:
$$
a^3+b^3+c^3\geq a^2+b^2+c^2.
$$
This follows from the following steps:

Cauchy-Schwartz: $(a+b+c)(a^3+b^3+c^3)\geq (a^2+b^2+c^2)^2 \implies 3(a^3+b^3+c^3)\geq (a^2+b^2+c^2)^2$
Cauchy-Schwartz: $(1+1+1)(a^2+b^2+c^2)\geq (a+b+c)^2 \implies (a^2+b^2+c^2)\geq 3.$
Combine two previous steps:
$$
3(a^3+b^3+c^3)\geq (a^2+b^2+c^2)^2\geq  3(a^2+b^2+c^2).
$$
And therefore, this proves $(\star)$.


Renaming folders using VBA

Question: I am trying to rename folders based upon a template that a user will fill out. The user will specify the old name of the folder and what it will be updated to. There are bunch of sub folders that also get the name change.
I have confirmed that the folders exist and in the locations that they should be so I don't understand why this is failing. I have also tried using FileSystem objects and get the same problem.
Any help would be greatly appreciated.
Sub UpdateMain()

    'string capture variables
    Dim currentLocation As String
    Dim currentName As String
    Dim customerNumber As String
    Dim newName As String

    'path creation variables
    Dim rootPath As String
    Dim currentPath As String
    Dim newPath As String

    'counter variables
    Dim i As Integer

    With wsUpdate
        currentLocation = .Range("B1")
        currentName = .Range("B2")
        customerNumber = .Range("B3")
        newName = .Range("B5")
    End With

    'create path and folder for the root folder
    rootPath = currentLocation & "\" & currentName & " (" & customerNumber & ")"

    'edit all subfolders prior to root folder
    i = 0
    With wsUpdate.Range("A8")
        Do Until .Offset(i, 0) = ""
                If .Offset(i, 1) = "Customer" Then
                    currentPath = rootPath & "\" & currentName & " " & .Offset(i, 0)
                    newPath = rootPath & "\" & newName & " " & .Offset(i, 0)
                Else
                    currentPath = rootPath & "\" & currentName & " " & .Offset(i, 1) & "\" & currentName & " " & .Offset(i, 0)
                    newPath = rootPath & "\" & newName & " " & .Offset(i, 1) & "\" & newName & " " & .Offset(i, 0)
                End If
                Call FolderNameEdit(currentPath, newPath)
            i = i + 1
        Loop
    End With

    'edit root folder
    currentPath = currentLocation & "\" & currentName & " (" & customerNumber & ")"
    newPath = currentLocation & "\" & newName & " (" & customerNumber & ")"
    Call FolderNameEdit(currentPath, newPath)

End Sub

Sub FolderNameEdit(currentPath As String, newPath As String)
    Name currentPath As newPath
End Sub

I keep getting

Run-time error '53': File not found.

The error occurs on line:
Name currentPath as newPath

Comment: If the error message is RTE 53 then check `currentPath` and `newPath` at run time. Do the variables really contain the values you expect?
Comment: Or start running your code by F8, and keep checking what your variables are storing.
Comment: See my comment is the answer below. I have the correct values being passed to the called sub but a null value is returned on the if statement. Any ideas?
Answer: Check folders before renaming:
Sub FolderNameEdit(currentPath As String, newPath As String)
    If Dir(currentPath, vbDirectory) = vbNullString Then
        ' error
    ElseIf Dir(newPath, vbDirectory) <> vbNullString Then
        ' error
    Else
        Name currentPath As newPath
    End If
End Sub

Comment: I updated the called sub to what you have above. `currentPath` has the correct value being passed but the logic branch goes to `If Dir(currentPath, vbDirectory) = vbNullString Then`  Why is it showing as null when `currentPath` has a value?
Comment: @jive14 `Dir(currentPath, vbDirectory)` returns nullstring when `currentPath` is not an existing directory. So the logic is: first we check if the original directory exists, then we check if the target directory does not exist, and if both are true then `Name`.
Comment: Thanks for explaining the logic. I'm confused because the directory exists (I'm looking at it while I step through the code) and the `currentPath` variable holds the exact string it needs to be, yet it can't find it? How do I solve this?
Comment: ,Scratch the comment about, I got it to make it through the logic to the `Name` keyword but it is still failing with the same error (Run-time error '53': File not found.) Any other ideas?
Comment: I figured it out. newPath was  the problem. It had a value I did not expect.

Renaming folders using VBA


Building mod_nss for Apache

Question: I need to compile mod_nss for Apache 2.4.27 on SLES 11 SP 4 since it's the only option to enable TLS 1.2 right now for me. I know using legacy OS is a pain, so it's a temporary solution just because SLES 11 doesn't support OpenSSL 1.X, so I can't use mod_ssl as usual.
What I have:

Apache 2.4.27 (installed from sources to /opt/apache2)
Apache source code located in /tmp/apache2_build/httpd-2.4.27
Mod_nss source code: https://releases.pagure.org/mod_nss/
OS: SLES 11 SP 4
Installed from packages prerequisites (mozilla-nss-devel-3.47.1-38.12.1, mozilla-nspr-devel-4.23-29.9.1)

What I was doing:
cd <mod_nss_sourcecode_dir>
autoreconf -ivf
./configure --with-apxs=/opt/apache2/bin/apxs
gmake all install

The last command returns the following output:
gmake  all-am
gmake[1]: Entering directory `/tmp/apache2_build/httpd-2.4.27/modules/mod_nss-mod_nss1018'
/bin/sh ./libtool --mode=compile gcc -DHAVE_CONFIG_H -I.  -I/opt/apache2/include -I/usr/include/nspr4   -I/usr/include/nss3 -I/usr/include/nspr4    -I/usr/include/apr-1  -I/usr/include/nspr4    -g -O2 -Werror=implicit-function-declaration -DLINUX -D_REENTRANT -D_GNU_SOURCE -DENABLE_CHACHA20 -DENABLE_SERVER_DHE -DNSS_SUPPORTS_TLS_1_3 -MT mod_nss.lo -MD -MP -MF .deps/mod_nss.Tpo -c -o mod_nss.lo mod_nss.c
libtool: compile:  gcc -DHAVE_CONFIG_H -I. -I/opt/apache2/include -I/usr/include/nspr4 -I/usr/include/nss3 -I/usr/include/nspr4 -I/usr/include/apr-1 -I/usr/include/nspr4 -g -O2 -Werror=implicit-function-declaration -DLINUX -D_REENTRANT -D_GNU_SOURCE -DENABLE_CHACHA20 -DENABLE_SERVER_DHE -DNSS_SUPPORTS_TLS_1_3 -MT mod_nss.lo -MD -MP -MF .deps/mod_nss.Tpo -c mod_nss.c  -fPIC -DPIC -o .libs/mod_nss.o
In file included from /opt/apache2/include/httpd.h:44,
                 from mod_nss.h:20,
                 from mod_nss.c:16:
/opt/apache2/include/ap_config.h:136:16: error: os.h: No such file or directory
In file included from mod_nss.c:16:
mod_nss.h:28:21: error: mod_ssl.h: No such file or directory
mod_nss.c:253: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token
mod_nss.c:254: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token
mod_nss.c: In function 'nss_proxy_enable':
mod_nss.c:310: error: 'othermod_proxy_enable' undeclared (first use in this function)
mod_nss.c:310: error: (Each undeclared identifier is reported only once
mod_nss.c:310: error: for each function it appears in.)
mod_nss.c:313: error: implicit declaration of function 'othermod_proxy_enable'
mod_nss.c: In function 'nss_engine_disable':
mod_nss.c:339: error: 'othermod_engine_disable' undeclared (first use in this function)
mod_nss.c:340: error: implicit declaration of function 'othermod_engine_disable'
mod_nss.c: In function 'nss_register_hooks':
mod_nss.c:588: error: 'othermod_proxy_enable' undeclared (first use in this function)
mod_nss.c:588: error: 'apr_OFN_ssl_proxy_enable_t' undeclared (first use in this function)
mod_nss.c:588: error: expected expression before ')' token
mod_nss.c:589: error: 'othermod_engine_disable' undeclared (first use in this function)
mod_nss.c:589: error: 'apr_OFN_ssl_engine_disable_t' undeclared (first use in this function)
mod_nss.c:589: error: expected expression before ')' token
mod_nss.c:595: error: 'apu__opt' undeclared (first use in this function)
gmake[1]: *** [mod_nss.lo] Error 1
gmake[1]: Leaving directory `/tmp/apache2_build/httpd-2.4.27/modules/mod_nss-mod_nss1018'
gmake: *** [all] Error 2

Previously I had errors related to absence of os.h and I fixed them by creating a symlink from apache source dir to apache installation in /opt:
/opt/apache2 screenshot
What can I do to fix this? I was trying to add path to "/tmp/apache2_build/" dir using --include= parameter
Comment: In my case "include" directory was absent in /opt/apache2. After running "make install" from Apache source, those directories were restored and the compilation process became easier.
Answer: mod_nss.h DOES include mod_ssl.h, so you need to put in an included path.
You can find it in the modules/ssl directory of the Apache source.

Building mod_nss for Apache


Understanding MappingView ABC

Question: What is the difference between a MappingView container and a Sized container? Any examples on how to implement a MappingView container?
I might be misunderstanding ABCs and the docs entirely, but a MappingView container is  any container that inherits from Sized, right? If so, then why doesn't my dummy example work?
import collections

class MySized:
    def __len__():
        pass

class MyMappingView(MySized):
    pass

print(issubclass(MySized, collections.Sized)) # True
print(issubclass(MyMappingView, collections.MappingView)) # False

Answer: Because you don't subclass from it (virtually or otherwise). MappingView is used as a base class for the keys/items/values views. Sized is used for any object for which getting its size (len) makes sense.
These ABCs are used to check if certain objects in Python follow the interface they define. Instead of creating a custom MappingView you can just register any new classes that conform to it.
Suffice to say, you wouldn't register a class to MappingView since it used solely as a base class to provide a default __len__, __repr__ and __init__ to Keys/Values/Items views. If you have defined a new mapping type that returns custom views, simply register these views to the appropriate Keys/Values/Items views.

Understanding MappingView ABC


html javacsript how to change background image of section while on hover?

Question: hey guys i am new to javascript and i am trying to figure out how to change the background image of my section while hovering the respective texts. currently i want to load 3 different backgrounds but i have issues trying to figure out. below is the code im using .do lmk if u have any suggestions. thanks in advance .
index.html

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>3d model</title>

Gold

Silver

Light Blue

Comment: Create a class:hover css that has the hover image url as background-image, and put the original image url in the original class
Comment: but wouldnt u only be able to set only 1 background-image?
Comment: and i mean to make it such that when i hover the text then will change background, not hover over the background
Answer: You can use the :hover property in CSS to add styles only whenever the mouse is over the specific HTML element; and to add an image you can use the CSS property background: url(URL_HERE);
For example, your gold ID can be set to display a background by creating a specific :hover property as such:
#gold:hover {
    background: url(" https://via.placeholder.com/600x200.png/FFFF00/");
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>3d model</title>

Gold

Silver

Light Blue

For every image, you would need to provide a separate class - if you don't want this behaviour, consider using JavaScript instead to dynamically adjust the background image.
Answer: First you need to get the element and then you need to set the backgroundImage  property to that element like
var goldElement = document.getElementById('gold');
goldElement.addEventListener('mouseover'), (event)=> { `goldElement.style. backgroundImage = "url('path_to_image')" ` }

And change the background to normal when mouse leave.
goldElement.addEventListener('mouseleave', (event)=> { `goldElement.style. backgroundImage = "url('')" ` });

Answer:

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>3d model</title>

Gold

Silver

Light Blue

If you want to stay on the color just hovered, then remove the leave function from the above code and from the Tags too.


JS/jQuery: Help modifying code to replace 4 images

Question: So I have this code (below) that will replace one image. I need this to be modified so it will replace four separate images, and is triggered after a button (image) is clicked.
Can someone help me do this, and also make it so it is triggered after clicking a button (image). Thanks x
This is my code:
<!DOCTYPE html>

        <meta charset="UTF-8">

If it helps here is my Design
Answer: It's hard to understand what you're trying to do here, but it does seem like a complicated way to swap out some images? Maybe something more like this would be easier :
$(document).ready(function() {
    var images = ['img/wallpaper/2.png',
                  'img/wallpaper/3.png',
                  'img/wallpaper/6.png',
                  'img/wallpaper/10.png'
                 ];

    $('#buttonID').on('click', function() {
        $('.image').attr('src', function(i, src) {
            return images[i];
        });
    });
});

example HTML:

    <input type="button" id="buttonID" value="Change images" />

Comment: Yes! Thanks! How would I make this keep going, like when I click "change image" for the second time - it changes to another new set of images? Also, is it possible to have a button that would take me'back', like back to the first set of images? x
Answer: <!DOCTYPE html>

        <meta charset="UTF-8">

        <input type="button" id="change" value="Change" />


Convert to Swift 3 - Notification Centre dispatch queue

Question: Struggling to convert this to Swift 3. Can you help?
dispatch_async(dispatch_get_main_queue()) { () -> Void in
    self.delegate.locationDidUpdateToLocation(self.currentLocation!)
    NSNotificationCenter.defaultCenter().postNotificationName(kLocationDidChangeNotification, object: self, userInfo: userInfo as [NSObject : AnyObject])
}

Many thanks!
Answer: I'm not sure what that delegate method is, but the rest of it would look like this:
DispatchQueue.main.async {

    NotificationCenter.default.post(name: notification_name, object: self, userInfo:userInfo )

}

I'm not sure about kLocationDidChangeNotification
Comment: It works! Must confess quite confused about all the changes on notification center, there are so many versions out there and none seems right!


SQL Transaction Logs bloating with Replication

Question: I am trying to setup a replication database that has a lot of read/writes, although the overall database size is about 35gb.
A transactional replication server has been configured, however over a week, the logs bloated to 22GB and slowed the server to a grind.
I managed to stop the replication and the logs from growing and now is stable with the logs at 0.1% of 22gb used (I have not shrunk the overall log size as I did not see the need for this as yet).

Full backups done nightly with Windows Backup
Recovery model is SIMPLE
Runs on RAID10 with 8x SAS 10K drives
32GB RAM, Win2008 x64 SP1
Restricted SQL to utilise only 24GB, thus server holding 75% memory utilisation
Avg Disk Activity is about 100KB/s and queue length being 0.05 without any replication according to Resource Monitor
Backup Server is running same OS, 4GB RAM, RAID1 SATA 7.2k 500GB

Question is - what did I do wrong to cause the Transaction logs to continually grow?
If more info is needed, please advise what tool I should use and I can post them accordingly.
Thanks for the help in advance.
Comment: I am sorry to hear about this ordeal. I'll star this question, if nobody answers i'll put it under a bounty.
Comment: Thanks for the push - although I figured out a work-around which s settings up a Maintenance Plan to just dump the Logs every 15 minutes. However now I have the issue of the Clients crashing every time they do a report when mirroring or replication is enabled!
Answer: You can try to read the transaction logs and investigate operations that cause the growth. For more information check out the Open LDF file and view LDF file content online article
Disclaimer: I work as a Product Support Engineer at ApexSQL
Answer: When this happens, what do you see for the 'log_reuse_wait_desc' in sys.databases ( SELECT * FROM sys.databases )
It sounds like the replication engine may be holding on to the transaction logs because the data hasn't been fully replicated yet  - do you have any subscribers that are offline?


Two string is anagrams ignoring white spaces, capital letters or punctuations

Question: I understand how to check 2 Strings for anagrams. Before that how would I clean up the input strings from white spaces, capital letters and punctuations.
Comment: http://stackoverflow.com/questions/21946042/remove-all-spaces-and-punctuation-anything-not-a-letter-from-a-string
Comment: @KrishnaKumar SO isn't the appropriate site for code reviews; the [Code Review StackExchange](http://codereview.stackexchange.com/) is.
Comment: Instead of removing spaces, capital letters or punctuation, put a condition in the checkAnagram code for these characters and skip those. This way one iteration can be saved(:P). Can you post your Anagram code, so that we can have a look at that and suggest changes?
Comment: I am not asking for code review, to suggest an answer I am just giving one suggestion, we can point out easily the change based on the code.
Answer: Try this:
s = s.replaceAll("[^\\p{Alnum}]", "").toLowerCase();


What are the (practical) differences between Tukey's HSD and the Dunn-Sidak correction procedures?

Question: I have a data set with three groups, one of which is a control and the other two groups have been administered either a moderate or a high dose of a drug. The data are not normally or log-normally distributed, hence I am using the Kurskal-Wallis test to find if there is a difference among the three. Next, I would like to perform a post-hoc (the dosages were not planned ahead and the reason behind this is kind of complicated; however, I'm not sure if this warrants the use of the term "post-hoc" or not) analysis of the two dosages to the control (essentially, a non-parametric analog of Dunnett's test [1]).
I understand that I can run a multiple comparison test (such as MATLAB's "multcomp") to answer my next questions. However, I'm not sure which correction procedure is most suitable to use on my data. The two procedures that I suspect are the most relevant are Tukey's HSD and Dunn-Sidak.
My understanding is that there are no good multiple comparison tests that do not assume normality, though the ones that do are generally robust to the assumption of normality ([2] Ch. 4).
On the other hand, since I only need 2 of the 3 possible comparisons, I thought I could use Dunn's procedure and again according to [2] this could have a higher power than HSD if fewer comparisons that there are possible are desired.
How would one choose between Tukey's HSD and Dunn-Sidak in general? More specifically, how about in my design?
Finally, in [3], there is a section (§ 11.5.a) that introduces what's called "Dunn's test" therein (and the reference cited is [4]). Is this the same as the Dunn-Sidak correction procedure? If not, should I use that instead? If so, will this not run into the problems mentioned in Post-hoc tests after Kruskal-Wallis: Dunn's test or Bonferroni corrected Mann-Whitney tests? ?
Thank you.
[1] C. W. Dunnett (1955). A Multiple Comparison Procedure for Comparing Several Treatments with a Control, J Amer Statist Assoc, 50: 1096-1121.
[2] L. E. Toothaker, "Multiple Comparison Procedures", 1993.
[3] J. H. Zar, "Biostatistical Analysis", 2010.
[4] O. J. Dunn (1964). Multiple comparisons using rank sums, Technometrics 6: 241-252.
Comment: Since you are using Kruskal-Wallis test, you want to use a multiple comparison procedure on ranks. The procedure in the Dunn 1964 article is usually used. I know it has implementations in R. Those also sometimes make an adjustment to p-values for the multiple comparisons. I don't know if there are additional adjustments made to this procedure after the original paper.
Comment: And this is the same answer given in the Cross Validated question you cite.
Comment: That answer does not concern the difference between the HSD and Dunn procedures. It only talks about doing the Dunn test after KW. I'm specifically interested in the HSD-Dunn comparison here.
Answer: Tukey HSD, Dunn-Sidak correction, and Dunn test are all different things, and aren't really alternatives to one another.
Tukey HSD is a method to compare among means of multiple groups, as would be common as a post-hoc test after a one-way anova.  It is limited by requirements for normality and homoscedasticity. Modern statistical software has techniques with fewer restrictions, e.g. this, and this.
Dunn-Sidak, usually just called Šidák, is a method of correcting either the alpha value or the p-value of a series of hypotheses to control the familywise error rate.  It can be used for any collection of (independent) hypotheses.  That is, not just to compare multiple means. It's not clear in the question what the "Dunn's procedure" would be in regard to post-hoc testing.  Perhaps pairwise t-tests with alpha or p corrected by Sidak.
Dunn test is a post-hoc procedure appropriate to follow a Kruskal-Wallis test.  In this sense, it is analogous in use to Tukey HSD, though very different.


Why is this nginx rewrite apparently duplicating pre-existing configuration?

Question: I am new to nginx, I have read some of the documentation at wiki.nginx.org, as long as I know the try_files sentence will do exactly as it says, it will search a file in the order given, as I see this sentence is used extensively along with the $uri variable (which has the requested uri), however, nginx is not accessing the directories without the trailing slash even using the try_files sentence as this:
try_files $uri $uri/ =404;

if I am understanding well, if I look for this: 127.0.0.1/directory, it will not find anything at the begining but it should find the directory at second (unless the index file is not being checked), but that is not happening, looking for a solution for this I have found this quetion add-slash-to-the-end-of-every-url-need-rewrite-rule-for-nginx, one of the answers suggested to apply this rewrite sentence in order to make the directories be accessed without a trailing slash (something that it worked):
rewrite ^([^.]*[^/])$ $1/ permanent;

my question is: is not the try_files sentence doing that already? (it has sense to me but it does not work as I think, I checked the access.log file in order to find a logic answer but I could not figure out this).
Comment: hopefully none of the meaning was lost by simplifying the question title.
Answer: "is the try_files sentence not doing that already?"
No. There is a gotcha with try_files:

In the event that no file is found, an internal redirect to the last
  parameter is invoked. Do note that only the last parameter causes an
  internal redirect, former ones just sets the internal URI pointer.

Nginx doesn't attempt to use the last parameter and check to see if it exists as a file or directory, instead it rewrites the request to match the last parameter, and then reprocesses the server block.
Without seeing the rest of your config file it is not easy to see the exact effect of this, but it has caused me issues in the past. You may be able to make a simple work around by doing:
try_files $uri $uri/ /404_static.html =404;

and also include another location block.
location = /404_static.html {
    root   /documents/projects/intahwebz/intahwebz/data/html/;
    internal;
}

If you're passing nginx to a proxy, this does require a small work around to pass the correct URI to the backend e.g.:
location  / {
    set $originalURI  $uri;
    try_files $uri /routing.php /50x_static.html;
    fastcgi_param  QUERY_STRING  q=$originalURI&$query_string;

    fastcgi_pass   unix:/opt/local/var/run/php54/php-fpm-www.sock;
    include       /documents/projects/intahwebz/intahwebz/conf/fastcgi.conf;
}

Answer: The $uri/ in try_files does not exactly add a / to the end of the URL and try it. Instead, when the parameter ends with a  / the request is passed on to an index module, depending on whether you have specified the index, autoindex or random_index directives in your server or location blocks.
Thus, if you had specified:
index index.php;

then
try_files $uri $uri/ =404;

will look for index.php in that corresponding directory, when given a URL ending in /. If you used autoindex instead, then nginx would generate a directory listing for that directory.
Comment: I think I will choose your answer as the correct one because it seems to be logic, however, I insist the trailing slashes are used only to separate directories in a file path so this "/dir" and this "/dir/" should be the same, I will investigate more about this later anyway, I just have one final question, is that a good practice, isn't that a duplicate configuration?


Problema para vincular duas structs em C

Question: O programa é sobre um banco, preciso de duas structs (uma de cliente e uma de contas), o titular da conta tem que ser vinculado com algum cliente. Porém na função Add_Conta, não estou conseguindo fazer esse vinculo, preciso de uma maneira que aponte para o local onde o cliente esta cadastrado, ou de alguma sugestão de como eu poderia fazer.
Mais adiante vou precisar imprimir os clientes de uma agencia, então eu precisaria de filtrar dados das duas structs.

//Declara��o structs - Cliente e Conta
typedef struct
{
  char nome[100];
  int RG;
  char endereco[200];
  int telefone;
  float renda;
  int tipo_cliente; //1-private, 2-alta renda, 3-varejo
  union
  {
      int cpf;
      int cnpj;
  } cpf_cnpj;
  int num_cl;
} Cliente;
Cliente cliente[MAX_CLIENTES];
char nome[100];
char endereco[200];

int posicao;

typedef struct
{
  int Numero_Conta; //deve ser unico e gerado pelo programa
  int Agencia;
  float Saldo_Conta;
  int Tipo_Conta;          // 1- Conta corrente 2-Conta poupanca 3- conta-salario
  struct Cliente *Titular; // titulares (deve estar vinculado aos clientes cadastrados)

} Dados_Contas;
Dados_Contas contas[MAX_CLIENTES];

void Add_Conta(int j, int num)
{
  int id;
  printf("Preencha os dados a seguir: \n \n");
  printf("Agencia: \n");
  scanf("%d%*c", &contas[j].Agencia);
  contas[j].Numero_Conta = num;
  printf("O sistema definiu o seguinte numero para a conta: %d \n", num);
  printf("Saldo da conta: \n");
  scanf("%f%*c", &contas[j].Saldo_Conta);
  printf("Tipo da conta: \n 1- CONTA-CORRENTE \n 2- CONTA POUPANCA \n 3- CONTA-SALARIO \n");
  scanf("%d%*c", &contas[j].Tipo_Conta);
  printf("Qual o numero (identificador) do cliente titular? ");
  scanf("%d", &id);
  // contas[id]->Titular=&cliente[id];1
}

  ```

Comment: Poste um programa completo, algo compilável. Ajude os outros a ajudar você...
No seu programa Cliente é uma estrutura. Um nome. E assim cliente é Clientes[MAX_CLIENTES]; Então ao declarar Titular como um ponteiro para um Cliente não é uma struct. Use apenas Cliente* Titular
Comment: Na proxima vez eu posto o codigo completo, obrigada pela ajuda!
Answer: Você provavelmente está sofrendo na hora de de-referenciar um endereço.
Veja esse trecho do código:
contas[j]->Titular = &cliente[id];

Com o operador -> você de-referencia um endereço, isso diz que o código deve checar o endereço que está gravado no ponteiro, e continuar o acesso a partir desse endereço.
O valor de contas[id] não é um endereço, ele é do tipo Dados_Contas, não do tipo Dados_Contas*, o que significa que você não deveria estar de-referenciando ele. Deveria ser:
contas[j].Titular = &cliente[id];

Agora o atributo Titular é um ponteiro do tipo struct Cliente*, ele grava um endereço, e aí sim faria sentido de-referenciar esse endereço para acessar uma das propriedades dessa estrutura, como seria o caso:
printf("Nome do cliente: %s \n", contas[id].Titular->nome);

Comment: Era isso mesmo! muito obrigada!


Can I construct a $C^2$ function on $\mathbb{R}$ from a $C^2$ function on $\mathbb{R}^{> 0}$?

Question: Given $f:\mathbb{R}^{> 0} \rightarrow \mathbb{R}$ such that:
a) $f$ is $C^2$ in its domain.
b) $f$, $f'$, and $f''$ have finite limits as $x \rightarrow 0^+$
I want to extend $f$ to nonpositive values of $x$ (really just to a neighborhood of the origin) so that it remains $C^2$. Does the following construction work?
Let $\lim_{x\rightarrow 0^+} f = a$, $\lim_{x\rightarrow 0^+} f' = b$, $\lim_{x\rightarrow 0^+} f'' = c$, and define $g(x)$ to be equal to $f(x)$ if $x>0$ and to $a+bx+cx^2/2$ if $x \leq 0$.
In particular, how can I prove (if it is true) that $g$ as defined is continuously differentiable twice at $x=0$?
My motivation (you can ignore this part, but comments on it are welcome)
It seems to me that given a series $\sum_{n=1}^\infty a_n$ that happens to have the property that $a_n$ (currently a function of the positive integers) can be extended to a $C^2$ function $f(x)$ of $\mathbb{R}^{>0}$ at least for sufficiently high $x$, the convergence of the series should be able to be established by the behavior of $f$ and its first two derivatives "at infinity." More precisely, defining $f^*(x)=f(1/x)$, I think that if $f^*$ and its first derivative $\rightarrow 0$ as $x \rightarrow 0$, and its second derivative has a finite limit, then the series converges, and I am trying to prove this.
My idea for a proof is to show that $f^*$ is bounded by something of the form $kx^2$ for sufficiently small positive $x$. In this case, $\sum_{n=1}^\infty a_n = \sum_{n=1}^\infty f^*(1/n)$ would for sufficiently high $n$ be bounded term-by-term by $\sum k/n^2$ which converges. To prove this bound I would like access to Taylor's theorem at the origin, but I don't have this unless $f^*$ is actually twice-differentiable at the origin.  This is why I want to create the extension I asked about above. If you have another or simpler route to my desired result (or a counterexample!) I'd be interested too.
Answer: It may be worth considering the answer given here to a related question.
Comment: It seems to me this fully answers the question. By your argument $g$ is differentiable with continuous derivative at the origin; then apply the result to $g'$ and we get what I want. Yes?
Comment: Yes, that's the idea.


Reverter animação no segundo click

Question: Estou a tentar reverter uma simples animação quando carrego novamente num botão. O primeiro click anima um div retirando a sua margem esquerda, mas quando carrego novamente queria voltar a colocar a margem no seu valor normal que são os 250px. Para o efeito decidi usar o toggle do jQuery. A animação da margem corre normalmente mas o problema é que o div também desaparece e reaparece cada vez que pressiono o botão, o que suponho seja o comportamento normal do toggle. O meu código é o seguinte:
$("#sidebar-toggle").click(function(){

$("#content").toggle(function(){

    $(this).animate({marginLeft:0},200);
},function(){

    $(this).animate({marginLeft:'250px'},200);
});

})
Answer: Essa funcionalidade do .toogle em alternar duas funções já foi removida à partir da versão 1.9. O método é usado para esconder/mostrar elementos de forma animada.
Sugiro você não usar .animate para isso: use .toggleClass() e faça a animação via classe no CSS usando transition:

$("#sidebar-toggle").click(function(){
   $("#content").toggleClass("margem");
})
#content{
   width: 50px;
   height: 50px;
   background: red;
   margin-left: 250px;
   transition: margin-left 200ms;
}

#content.margem{
   margin-left: 0;
}

<button id="sidebar-toggle">Clique</button>
Comment: Perfeito :) muito obrigado!

Reverter animação no segundo click


Retrieving data from wrong database

Question: I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{

private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
    super.onCreate(savedInstanceState, persistentState);

    final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);

    saveDetails = (Button) findViewById(R.id.saveDetailsButton);
    saveDetails.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String erm=surnameArray.getText().toString().trim();
            if(erm.length() != 0){
                CUSTOMERS.add(erm);
                surnameArray.setText("");
            }
            Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
            Bundle arrayItemsBundle = new Bundle();

        }
    });

}

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

    ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
    ContactName.addTextChangedListener(this);
    ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
    ContactSurname.addTextChangedListener(this);
    ContactEmail = (EditText) findViewById(R.id.customerEmail);
    ContactEmail.addTextChangedListener(this);
    ContactPhone = (EditText) findViewById(R.id.customerNumber);
    ContactPhone.addTextChangedListener(this);
    ContactAddInfo = (EditText) findViewById(R.id.addInfo1);

    setupSaveDataButton();

}

public void addContact(View view) {

    String name = ContactName.getText().toString();
    String surname = ContactSurname.getText().toString();
    String email = ContactEmail.getText().toString();
    String phone = ContactPhone.getText().toString();
    String add_info = ContactAddInfo.getText().toString();

    userDbHelper = new UserDbHelper(context);
    sqLiteDatabase = userDbHelper.getWritableDatabase();
    userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
    Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
    userDbHelper.close();
}

RecapPage:
public class RecapPage extends AppCompatActivity{

ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;

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

    goButtonAction = (Button) findViewById(R.id.goButton);
    listView = (ListView) findViewById(R.id.list_view);
    listView.setClickable(true);
    listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
    listView.setAdapter(listDataAdapter);
    userDbHelper = new UserDbHelper(getApplicationContext());
    sqLiteDatabase = userDbHelper.getReadableDatabase();
    cursor = userDbHelper.getInformation(sqLiteDatabase);
    if(cursor.moveToFirst()) {
        do {

            String first_name, surname, email, phone, add_info;
            first_name = cursor.getString(0);
            surname = cursor.getString(1);
            email = cursor.getString(2);
            phone = cursor.getString(3);
            add_info = cursor.getString(4);
            DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
            listDataAdapter.add(dataProvider);

        } while (cursor.moveToNext());
    }

    Intent arrayItems = getIntent();
    Bundle arrayItemsBundle = arrayItems.getExtras();

}

GarmentEntry:
public class GarmentEntry extends AppCompatActivity {

Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
        cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.garment_entry);

    final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);

    saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
    saveOrderDetails.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String erm=shirtArray.getText().toString().trim();
            if (erm.length() != 0){
                ORDERINFO.add(erm);
                shirtArray.setText("");
            }
            Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
            Bundle arrayItemsOrderBundle = new Bundle();
        }
    });

    OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
    OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
    OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
    OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
    OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
    OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
    OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
    OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);

}

public void addOrder(View view){

    String no_of_shirts = OrderNoOfShirts.getText().toString();
    String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
    String front_text = OrderFrontText.getText().toString();
    String print_position = OrderPrintPosition.getSelectedItem().toString();
    String colour_of_text = OrderColourOfText.getSelectedItem().toString();
    String back_print = OrderBackPrint.getSelectedItem().toString();
    String back_colour = OrderBackColour.getSelectedItem().toString();
    String shirt_1 = OrderShirt1.getText().toString();

    userDbHelperOrder = new OrderDbHelper(contextOrder);
    sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
    userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
            back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
    Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
    userDbHelperOrder.close();

}

RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {

ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;

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

    listViewOrder = (ListView)findViewById(R.id.list_view_order);
    listViewOrder.setClickable(true);
    listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
    listViewOrder.setAdapter(listDataAdapterOrder);
    userDbHelperOrder = new UserDbHelper(getApplicationContext());
    sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
    cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
    if (cursorOrder.moveToFirst()){
        do {

            String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
            no_of_shirts = cursorOrder.getString(0);
            colour_of_shirts = cursorOrder.getString(1);
            front_text = cursorOrder.getString(2);
            print_position = cursorOrder.getString(3);
            text_colour = cursorOrder.getString(4);
            /*back_print = cursorOrder.getString(5);
            back_colour = cursorOrder.getString(6);
            shirt1 = cursorOrder.getString(7);*/
            DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
                    text_colour,null,null,null);
            listDataAdapterOrder.add(dataProviderOrder);

        }while (cursorOrder.moveToNext());
    }

    Intent arrayItems = getIntent();
    Bundle arrayItemsBundle = arrayItems.getExtras();
}

I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
        do {

            String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
            no_of_shirts = cursorOrder.getString(0);
            colour_of_shirts = cursorOrder.getString(1);
            front_text = cursorOrder.getString(2);
            print_position = cursorOrder.getString(3);
            text_colour = cursorOrder.getString(4);
            /*back_print = cursorOrder.getString(5);
            back_colour = cursorOrder.getString(6);
            shirt1 = cursorOrder.getString(7);*/
            DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
                    text_colour,null,null,null);
            listDataAdapterOrder.add(dataProviderOrder);

Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);

has something to do with the matter.
Answer: I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());

was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder

in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());

with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());

Retrieving data from wrong database


$f\in L^1 [0,1]$, condition for integrability of $g =\int_x^1t^{-1} f(t)dt$

Question: In my continuing studies towards an upcoming exam, I have run across a number of problems similar to the following, and would appreciate 1) some guidance on how to approach such problems in general and 2) how to solve this one in particular.
Let $f \in L^1[0,1]$ and define $g(x) = \int_{[x,1]} \frac{f(t)}{t} dt$. Show that $g \in L^1[0,1]$ and $\int_{[0,1]} g = \int_{[0,1]} f$.
I suspect the use of Tonelli's theorem is required, so I wrote
\begin{align*}
\int_{[0,1]} |g| &= \int_{[0,1]} \left| \int_{[x,1]} \frac{f(t)}{t} dt \right| dx \\
&= \int_{[0,1]} \left| \int_{[0,1]} \chi_{[x,1]} \frac{f(t)}{t} dt \right| dx \\
&= \int_{[0,1]} \left| \frac{f(t)}{t} \int_{[0,1]} \chi_{[x,1]} dx \right| dt
\end{align*}
However, I'm not sure if this is even a productive direction. Thanks for any assistance.
Answer: Since it should hold for all $f \in L^1([0,\,1])$, it would in particular hold for positive $f$, so you must be able to move the absolute value into the inner integral. That yields
$$\begin{align}
\int_{[0,1]} \lvert g(x)\rvert\,dx &= \int_{[0,1]}\left\lvert \int_{[x,1]} \frac{f(t)}{t}\,dt\right\rvert\, dx\\
&\leqslant \int_0^1 \int_x^1 \frac{\lvert f(t)\rvert}{t}\,dt\,dx\\
&= \int_0^1\int_0^t \frac{\lvert f(t)\rvert}{t}\,dx\,dt\\
&= \int_0^1 \left(\int_0^t dx\right)\frac{\lvert f(t)\rvert}{t}\,dt\\
&= \int_0^1 \lvert f(t)\rvert\, dt.
\end{align}$$
Changing the order of integration is no problem because the integrand is measurable and non-negative.
The same computation without the absolute value yields (we now know that Fubini's theorem can be applied)
$$\int_0^1 g(x)\,dx = \int_0^1 f(t)\,dt.$$
Comment: @BettyMock For $f(t) = 1$, we get $g(x) = \int_x^1 \frac{dt}{t} = \log 1 - \log x = \log (1/x)$. While $1/x$ indeed is not integrable, $\log (1/x)$ is integrable. For $f \in L^1([0,1])$, the function $t \mapsto \frac{f(t)}{t}$ is in general not in $L^1([0,1])$, but it(s restriction) is in $L^1([x,1])$ for every $0 < x < 1$. That makes $g(x) = \int_x^1 \frac{f(t)}{t}\,dt$ well-defined on $(0,1]$. And that function $g$ is again in $L^1([0,1])$.
Comment: I'm sorry, but can you be more explicit about how you changed the limits of integration? Also, the first part demonstrates that $g$ is integrable, so the latter computation is justified by Fubini, correct?
Comment: Edited to make it more explicit, hope that clarifies it. Yes, after the first part, we know Fubini is applicable.
Comment: @daniel -- I don't quite understand your explanation for being able to switch the integrals.  We know that f is L1 integrable, but we specifically don't know that f(t)/t is - it's part of what we are trying to prove.  I thought we could not switch order of integration unless both integrals converge.
Comment: @BettyMock $\frac{f(t)}{t}$ is in general not integrable. But the function $$h(x,t) = H(t-x)\cdot \frac{\lvert f(t)\rvert}{t},$$ where $H$ is the Heaviside function, is non-negative and measurable. By Tonelli's theorem, both iterated integrals and the two-dimensional integral are equal. Since one of them is finite, all of them are, and $h$ is integrable. From that we deduce that $H(t-x)\frac{f(t)}{t}$ is integrable too, hence 1) we can apply Fubini, and 2) $g$ is integrable.
Comment: @DanielFischer commented below my non-proof that I'm thinking the result isn't even true. Since f(x) = 1 is integrable, that would make f(x) = 1/x integrable.  Cannot see why it would be.  Maybe I'm confused about something, but would you be good enough to comment further?  Thanks.
Comment: Yes, thank you.  I looked at it again, after seeing your note above, and I had really not read it right. I appreciate that you rewrote things in a way that was clearer to me. the result does make perfect sense once I put back the integral sign I lost. I've deleted my bad answer.


How to use proftpd in SliTaz

Question: I would like to use FTP over TLS on SliTaz. I've installed proftpd with the following command:
tazpkg get-install proftpd
I'm used to start and stop programs on SliTaz with /etc/init.d/program start or stop but I can't figure out how to start proftpd because there is no /etc/init.d/proftpd.
The proftpd config is still default and I tried to connect with FileZilla but I get Could not connect to sever after authenticating the user.
The SliTaz (5.0) is a virtualmachine on a Windows 10 host. I tried with FileZilla on the host to the SliTaz host-only ip.
How can I configure proftpd on SliTaz?
EDIT
I figured out I can start proftpd with just typing proftpd in the command line. I do have a /etc/proftpd.conf file but when I change something in the file not changes. I cannot use proftpd restart so I assume proftpd reloads with just proftpd?
I tried using TLS with the following lines in /etc/proftpd.conf:
<IfModule mod_tls.c>
TLSEngine                  on
TLSLog                     /var/log/proftpd/tls.log
TLSProtocol TLSv1.2
TLSCipherSuite AES128+EECDH:AES128+EDH
TLSOptions                 NoCertRequest AllowClientRenegotiations
TLSRSACertificateFile      /etc/proftpd/ssl/proftpd.pem
TLSRSACertificateKeyFile   /etc/proftpd/ssl/proftpd.pem
TLSVerifyClient            off
TLSRequired                on
RequireValidShell          no
</IfModule>

I created the proftpd.pem with openssl req -new -x509 -days 365 -nodes -out /etc/proftpd/ssl/proftpd.pem -keyout /etc/proftpd/ssl/proftpd.pem

A normal FileZilla works perfect but a Require explicit FTP over TLS returns 500 AUTH not understood.
EDIT 2
The mod_tls.c is not compiled by default. With proftpd -l I was able to see all the modules:
Compiled-in modules:
  mod_core.c
  mod_xfer.c
  mod_rlimit.c
  mod_auth_unix.c
  mod_auth_file.c
  mod_auth.c
  mod_ls.c
  mod_log.c
  mod_site.c
  mod_delay.c
  mod_facts.c
  mod_ident.c
  mod_cap.c

Mod_tls.c is not in the list and that is probably why it is not working. How do I add mod_tls.c to the proftpd list?
Answer: Someone created a Proftpd TLS SliTaz package for FTPS. Install the package with:
tazpkg get-install proftpd-tls
You will be able to start and stop proftpd with:
/etc/init.d/program start / stop
The proftpd package will standard work without TLS. You must create certificates and configure them in the proftpd config file.
Create the certificates:
openssl req -new -x509 -days 365 -nodes -out /etc/proftpd/ssl/proftpd.cert.pem -keyout /etc/proftpd/ssl/proftpd.key.pem

Configure proftpd with TLS:

Open /etc/proftpd.conf and add: Include /etc/proftpd/tls.conf
Create /etc/proftpd/tls.conf and add:

<IfModule mod_tls.c>
  TLSEngine           on
  TLSLog              /var/log/proftpd/tls.log
  TLSProtocol         TLSv1.2
  TLSCipherSuite      AES128+EECDH:AES128+EDH
  TLSOptions          AllowClientRenegotiations
  TLSRSACertificateFile     /etc/proftpd/ssl/proftpd.cert.pem
  TLSRSACertificateKeyFile  /etc/proftpd/ssl/proftpd.key.pem
  TLSVerifyClient     off
  TLSRequired         off
  RequireValidShell   no
</IfModule>

Restart Proftpd: /etc/init.d/program restart

Proftpd works now with FTPS.
Special thanks to Mojo for creating the proftpd-tls package.

How to use proftpd in SliTaz


Preimages of prime ideals when only one of the rings is commutative

Question: Given a ring homomorphism between noncommutative rings, the preimage of a prime ideal is not necessarily prime. On the other hand, the preimage of a prime ideal is always prime if both rings are commutative, which is why the usual prime spectrum $\operatorname{Spec}$ is functorial on commutative rings.
I am just curious what happens if only one of the rings involved is commutative. Suppose we have a pair of rings $R$ and $K$, where $K$ is commutative, and $R$ is not.
If we have a ring homomorphism $f: R \to K$, is the preimage of every prime ideal in $K$ prime?
Likewise, if we have a ring homomorphism $g: K \to R$, Is the preimage of every prime ideal in $R$ prime?
Answer: An ideal $P\subset R$ is prime iff $R/P$ is a prime ring.  So modding out the prime ideal and its preimage, you can assume your homomorphism is injective and the question is whether a subring of a prime ring is prime, when you know one of the rings is commutative.
In the case of $f:R\to K$, a commutative prime ring is just an integral domain, and a subring of an integral domain is an integral domain.  So the answer is yes, the preimage of a prime ideal is prime.  Another way to think about this case is that the inverse image of a completely prime ideal is always completely prime, where $P$ is completely prime if $ab\in P$ implies $a\in P$ or $b\in P$ (the proof is easy).  Since prime ideals in commutative rings are completely prime, the inverse image of a prime ideal in a commutative ring is always prime (in fact, completely prime).
In the case of $g:K\to R$, the answer is no in general.  For instance, if $A$ is an integral domain, then $R=M_2(A)$ is a prime ring, but the subring $A\times A$ of diagonal matrices is commutative and not prime.


How do I POST data from an asp.net MVC controller to a non-MVC asp.net page?

Question: One department in our company is using classic asp.net while ours department is using MVC.
We need to pass 5 variables to his page (by form submit). Can someone please show a simple example of posting form data from an MVC controller to an asp.net page expecting the form variable?
Answer: If I am reading this correctly, you should be able to do this without any cross domain / application concern. You want to do this in the controller, so you can use the HttpWebRequest class to post the data. It's conceptually the same as posting from a web browser as far as the target application is concerned.
Here's a quick and dirty snippet:
// name / value pairs. field names should match form elements
string data = field2Name + "=" + field1Value + "&" + field2Name+ "=" + field2Value

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(<url to other applications form action>);

// set post headers
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";

// write the data to the request stream
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);

// iirc this actually triggers the post
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Comment: remember to flush your writer or use
   using(var writer = new StreamWriter(request.GetRequestStream())
   {
       writer.Write(data);
   }
Comment: This looks like the solution I'm looking for. Thanks, I'll give it a try!
Answer: If you are crossing domains, or applications, I think you might be out of luck.  Can you direct to the other site and use the querystring?
Or write to a table and direct to the other site.
Really not sure you'll be able to post to the other site as I think it goes against the security model.
Comment: I can't use query string because of security exposure, and it's too easy for users to modify. It is crossing domains.
Comment: For crossing domain, convert your object to JSON and Serialize Javascript, then assign it to ViewBag if the controller returns the View or TempData if it redirects to another View. Then this is what I did: use AngularJS to post to a WebAPI with CORS enabled. WebAPI can specify URLs that are permitted to post to its controller. The @Html.Raw(TempData["yourdata"]) can be assigned to a Javascript object where Angular can post it to the WebAPI. Refer to this answer:  http://stackoverflow.com/a/32769992/1171842 . For Classic ASP, the code that accepts data need to be ported to WebAPI.
Answer: I might be missing the subtle problem, but can't you just set the action on the MVC form to the url of the classic asp page that will receive it?
The fields will be available in the form headers which you can read on the ASP side.
The only issue will be if the ASP site has cross site request forgery detection (but if they're inhouse apps, you can add an exception to the forgery detection code on the ASP side).


jQuery tabs sort

Question: I'm using jQuery tabs, and trying to save the positions of the Tabs (and of course the content in the tabs). Could you please suggest me a way to do the same?
Regards
Answer: the order is defined by the element position in html, not the tabs plugin, not jquery, not javascript.
Answer: You can set which tab is active by using the selected property
<code>$('.selector').tabs({ selected: 3 });
</code>
You'll also need a way of storing which tab is active. For that we have the select event, you can listen for the select event, and then on the callback either send an Ajax call back to the server with the information (which tab is active), or create a cookie where you store the same information.
Then when the page loads you just need to either get that information from the server or the cookie, and use the select property to set the active tab.
Comment: We can save the active tabs by using selected property, but how can we decide/save the order of the tabs?
Comment: Either in a cookie or on the server. Use the select event (which gets triggered every time the selected tab changes) to call a callback function that creates/updates the cookie, or sends the data back to the server with Ajax.

jQuery tabs sort


User migration not setting custom field values correctly

Question: I have a User migration in Drupal 8 which is coming from custom SQL tables.
The user entity in Drupal 8 has a bunch of custom fields on it (First Name, Last Name, About, etc).
When I run the migration I can go into the field data tables in Drupal 8 and see that all of the values are there in the table where they should be, meaning they migrated into the new database correctly.
If I go to the users' edit pages (/user/#/edit), the fields are completely empty.  If I then click save and wait for the page to reload, all of the migrated values magically appear in the form.
I tried running a post-migration script to manually save the users, but it still does not make the fields show up and I have to manually save the empty form for the values to show.
Here is the post-migration script I tried:
$ignored_users = [0, 1];
$uids = db_select('users', 'u')
  ->condition('uid', $ignored_users, 'NOT IN')
  ->fields('u', ['uid'])
  ->execute()
  ->fetchCol();

$users = user_load_multiple($uids);

foreach ($users as $user) {
  $user->save();
}

This is my config for the migration:
id: my_users
label: User Migration
migration_group: users
source:
  plugin: migrate_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  changed: changed
  access: access
  login: login
  langcode: language
  preferred_langcode: language
  preferred_admin_langcode: language
  init: init
  roles: roles
  user_picture:
    plugin: migration
    migration: my_files
    source: field_image_fid
  'field_about/value': body_value
  'field_about/summary': body_summary
  'field_about/format':
    plugin: default_value
    default_value: full_html
  field_first_name: field_first_name_value
  field_last_name: field_last_name_value
migration_dependencies:
  required:
    - my_files
dependencies:
  enforced:
    module:
      - my_migrate

Here is my user migration plugin:
class Users extends Nodes {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('users', 'u')
      ->fields('u', array_keys($this->baseFields()))
      ->condition('uid', 0, '>');
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = $this->baseFields();
    $fields['field_about/format'] = $this->t('Format of body');
    $fields['field_about/value'] = $this->t('Full text of body');
    $fields['field_about/summary'] = $this->t('Summary of body');
    $fields['field_first_name'] = $this->t('First Name textfield');
    $fields['field_last_name'] = $this->t('Last Name textfield');

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'u',
      ],
    ];
  }

  /**
   * Returns the user base fields to be migrated.
   *
   * @return array
   *   Associative array having field name as key and description as value.
   */
  protected function baseFields() {
    return [
      'uid' => $this->t('User ID'),
      'name' => $this->t('Username'),
      'pass' => $this->t('Password'),
      'mail' => $this->t('Email address'),
      'created' => $this->t('Registered timestamp'),
      'access' => $this->t('Last access timestamp'),
      'login' => $this->t('Last login timestamp'),
      'status' => $this->t('Status'),
      'language' => $this->t('Language'),
      'picture' => $this->t('Picture'),
      'init' => $this->t('Init'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');
    $profile_nid = $this->getProfileData($uid);

    $row->setSourceProperty(
      'body_value',
      $this->getFieldValue($profile_nid, 'field_data_body', 'body_value')
    );
    $row->setSourceProperty(
      'body_summary',
      $this->getFieldValue($profile_nid, 'field_data_body', 'body_summary')
    );

    $row->setSourceProperty(
      'field_first_name_value',
      $this->getFieldValue($profile_nid, 'field_data_field_first_name', 'field_first_name_value')
    );

    $row->setSourceProperty(
      'field_last_name_value',
      $this->getFieldValue($profile_nid, 'field_data_field_last_name', 'field_last_name_value')
    );

    return parent::prepareRow($row);
  }

  /**
   * Gets the profile data node in Drupal 7 associated with a User account.
   *
   * @param int $uid
   *   Drupal user Id.
   *
   * @return int
   *   Team Member node Id.
   */
  private function getProfileData($uid) {
    return $this->select('field_data_field_drupal_user', 'fdp')
      ->fields('fdp', ['entity_id'])
      ->condition('field_drupal_user_target_id', $uid)
      ->execute()
      ->fetchField();
  }

}

Answer: The problem was the 'langocde' map in the config.  The Drupal 7 langcode did not match the Drupal 8 langcode format.
When I set a default value for langcode in the migration config the fields showed as normal.
  langcode:
    plugin: default_value
    default_value: en


Is it better to reference jQuery file include through jQuery CDN?

Question: Is it better to reference jQuery file inclusion through jQuery CDN for better performance?
Like

Or
Is it better to reference stored jQuery file in our project?
Like

As jQuery CDN link handles caching, Does it improve performance more than jQuery file included from our project?
Comment: Is better using CDN, but always have a fallback to local see: http://stackoverflow.com/questions/1014203/best-way-to-use-googles-hosted-jquery-but-fall-back-to-my-hosted-library-on-go
Comment: The only drawback is if google servers get unreachable .. As @IrvinDomininakaEdward said, consider using a  fall-back too
Answer: Do like this with a fallback

CDN first, if not (or blocked) ? so bring it from your server
Why should I use Google's CDN for jQuery? (For me, my point is about Cache Hit)
Comment: No server with 100% uptime. @Dhaval
Comment: @Dhaval, Google's servers can be blocked in Iran or China.
Comment: but when do u think the file will not be downloaded from CDN?? as far as i think CDNs are much more reliable then personal server.
Answer: First variant. Because google has best world-wide servers.

Decreased Latency
Increased parallelism
Better caching

The best way to initiate jQuery engine:

Here is a good article about this:
http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/
Comment: Get `/jsapi/` then.. get `jQuery` ?
Comment: @l2aelba yes. jsapi - Google's universal loader. Take a look [link](https://developers.google.com/loader/)
Answer: With CDN :

If the user have already downloaded the file on an other website, the file is already in cache
If the user haven't the file, the file will always be located on the server nearest to your visitor
In addition, you will reduce the load on your server, which allows it to render the site faster


How do I add recaptcha to a custom form programatically?

Question: I'm using the following contrib module: https://www.drupal.org/project/google_recaptcha
How do I add a recaptcha to my form programatically, since the form I'm using isn't listed under forms on the config page of the module?
The following doesn't seem to work:
$form['recaptcha'] = array(
  '#type' => 'recaptcha'
);

Comment: Not sure but you could try once . $form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);
Answer: The module doesn't implement hook_element_info, so it doesn't define a new element type. The code you're using looks like it's borrowed from the traditional captcha module, which does things a bit better and provides the element type.
Looking at the code, this is all you need in your form alter hook:
g_add_captcha($form, $form_id);

Answer: For Drupal 8, use the following (after installing the reCaptcha module):
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);


Ionic: can't build Android app

Question: I'm trying to build an Android app using inonic build android but I have the following error:
running cordova build android
Running command: "c:\Program Files\nodejs\node.exe" c:\xampp\htdocs\discipulado\
discipulado\hooks\after_prepare\010_add_platform_class.js c:/xampp/htdocs/discip
ulado/discipulado
add to body class: platform-android
Running command: c:\xampp\htdocs\discipulado\discipulado\platforms\android\cordo
va\build.bat
[Error: Please install Android target: "android-21".

Hint: Open the SDK manager by running: C:\Users\Thiago\AppData\Local\Android\sdk
\tools\android.BAT
You will require:
1. "SDK Platform" for android-21
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)]
ERROR building one of the platforms: Error: c:\xampp\htdocs\discipulado\discipul
ado\platforms\android\cordova\build.bat: Command failed with exit code 2
You may not have the required environment or OS to build this project
Error: c:\xampp\htdocs\discipulado\discipulado\platforms\android\cordova\build.b
at: Command failed with exit code 2
    at ChildProcess.whenDone (c:\Users\Thiago\AppData\Roaming\npm\node_modules\c
ordova\node_modules\cordova-lib\src\cordova\superspawn.js:131:23)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1015:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

I already installed Apache Ant, but the error remains. I removed the Android platform with ionic platform remove android and added with ionic platform add android with no success.
Any idea?
UPDATE
I already installed Android Studio and Android SDK Tools.
Answer: As the error suggests, your system needs to install "android-21", which is Android 5.0 Lollipop
Comment: The thing you missed is, in the environmental variable PATH, add these two items 1. path-to-android-sdk-***/tools 2. path-to-android-sdk-***/platform-tools. Update me if it works.
Comment: I've checked the Android SDK Manager and the following items are installed **Android 5.0.1**: SDK Platform, Google APIs, Sources for Android SDK.
Comment: Not sure what happened. I've just rewrite the `ant/bin` folder in the `Path` and it worked.

Ionic: can't build Android app


Norm in $L^2$ goes to zero for function away from zero

Question: Let $f\in L^2(\mathbb{R})$ and $M>0$. Define $f_M(x)=f(x)$ for $|x|\leq M$ and $f_M(x)=0$ for $|x|>M$. Show that $\|f_M-f\|_2\rightarrow 0$ as $M\rightarrow \infty$.
Well, we have $$\|f_M-f\|_2^2=\int_{|x|>M}|f|^2dx$$
Since $f\in L^2(\mathbb{R})$, we know that $$\int_{x\in\mathbb{R}}|f|^2dx<\infty$$ But why does this imply that $$\int_{|x|>M}|f|^2dx\rightarrow 0 \text{ as } M\rightarrow\infty?$$
Comment: Dominated convergence theorem is one possible way to see it.
Answer: Because
$$\int_\mathbb{R} |f|^2 = \sum_{n=1}^\infty A_n\ ,$$
where $A_n = \int_{\{n< |x|\leq  n+1\}} |f|^2$. Then $\int_{|x|>M} |f|^2 = \sum_{n=M}^\infty A_n \to 0$.