Configuring static content for a webapp with Jetty 9

Question: Could someone please tell me how to configure static content for a webapp with Jetty 9. I've been trying to do this for a while and I'm not having any luck. All requests for static content (e.g. css/* or img/*) just go straight to my servlet handler for the /.
root
    |-war
        |-css
        |-img
        |-js
        |-WEB-INF
                |-web.xml

My web.xml looks like:
<webapp>
    ...
    ...
    <servlet-mapping>
        <servlet-name>App</servlet-name>
        <url-pattern>/app</url-pattern>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</webapp>

I just don't understand what to do with this example from the jetty docs:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
  <Set name="contextPath">/scratch</Set>
  <Set name="handler">
    <New class="org.eclipse.jetty.server.handler.ResourceHandler">
      <Set name="resourceBase">/home/jesse/scratch</Set>
      <Set name="directoriesListed">true</Set>
    </New>
  </Set>
</Configure>

I've tried playing around with it and putting the file in different places but I can't get it to work. My servlets are handled fine, but my pages have no styles, images or js because they can't find the content.
Comment: As said in the Jetty documentation you should create that XML file under "${jetty.home}/webapps" @ http://www.eclipse.org/jetty/documentation/current/static-content-deployment.html

But this raises many concerns, because if you need to declare this in a project context (to override default values) or use it on top of platforms like Jenkins...
Answer: I ultimately just slapped this in my web.xml:
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

The default just seems to hand back whatever is there with an appropriate mime type based on the filename extension, so that's fine.
Comment: I've never used Maven before, but just having a quick look at some Maven docs, would `${basedir}/src/main/webapp/static/...` be it?
Comment: And where do you place the files on the project?
Comment: On my Maven projects I do not have a `war`folder. Could it be `src/main/static`a "sibling" of `src/main/webapp`?
Answer: I am using Jetty through Maven Plugins, and I have found this:
http://jamesphilipps.wordpress.com/2012/06/13/serving-static-content-with-the-maven-jetty-plugin/
<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-maven-plugin</artifactId>
  <version>7.1.0.RC0</version>
  <configuration>
    <contextHandlers>
      <contextHandler implementation="org.eclipse.jetty.webapp.WebAppContext">
        <contextPath>/static</contextPath>
        <resourceBase>src/main/webapp/static</resourceBase>
      </contextHandler>
    </contextHandlers>
  </configuration>
</plugin>


How to Reset Active Directory Secure Channel If Broken

Question: Occasionally, a computer account can lose its secure channel to a domain controller.
How can secure channel be reset without rebooting the computer?
The computer in question is a clustered SQL Server running Server 2008 R2 in a 2008 R2 Functional Level Active Directory domain and forest.
Answer: nltest.exe can be used to check the channel and attempt to reset it.
nltest.exe /sc_verify:<fully.qualified.domain.name.here>

If that does not do it, you can restart the netlogon service (I mainly use PowerShell, so I'll give an example of that).
Get-Service netlogon | restart-service
nltest.exe /sc_verify:<fully.qualified.domain.name.here>

I ran the nltest command after restarting the service to validate that the secure channel was back in operation.
If you've made some network changes (IP Addresses, changing hardware, virtualizing, etc..) you might want to flush your dns cache and clear your arp table before running the above commands.
ipconfig /flushdns
arp -d *
Get-Service netlogon | restart-service
nltest.exe /sc_verify:<fully.qualified.domain.name.here>

Answer: I've had some instances where a machine will decide to use an off-site domain controller (elsewhere on our WAN) as it's logon server and map offsite network drives instead of local ones; that can be resolved by resetting the secure channel directly:
nltest /sc_reset:<domain>\<domain controller>

Answer: UPDATED for new versions of powershell
Open PowerShell AsAdministrator
Test-ComputerSecureChannel  -Verbose

If False then run:
Test-ComputerSecureChannel -Repair -Server PDCEmulatorName -Verbose

If repaired you will see message, if it fails then try adding a credential
Test-ComputerSecureChannel -Repair -Server PDCEmulatorName -Credential Domain\UserName -Verbose

Comment: This worked for me. I bet the other answers would work too, but they didn't show how to specify the credentials
Comment: Repair failed for me.  I had to disjoin it from the domain (assign to the WORKGROUP workgroup), reboot, reset computer account in AD (VERY important! - will eventually happen again if you miss this step), log in with local Admin, rejoin to domain with domain admin account, reboot.


How to limit direct access to URLs of nodes that are shown in a video gallery created with Views?

Question: I have made a video gallery using Views. But I only want that the page accessible to public and prevent access to each of the videos individually.
The videos had to be created as a type of content, so all of them have accessible ULRs like /content/video-1, etc.
Answer: Try content access module and prevent access to video content individually( or also you can set access to it for you desire roles )

This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Also you can use Node View Permissions module, but I suggest use Content access module.
(if you want work with drupal for future is better getting involve with this useful modules)
Comment: Almost what I needed. Finally I did control the access via low-level, because wanted to redirect to home page in some cases, 404 in others, etc., so I had better control, but I think this module could work in most of the cases. Maybe with a better adjust in my case, but had no time to investigate.
Answer: Install Node View Permissions module.

Node view permissions module enables permissions "View own content"
  and "View any content" for each content type on permissions page as it
  was on Drupal 6.

Now goto permission page and remove View any content permission from video content type for Anonymous user.
In case you want only few of the videos from Video gallery to be accessible to the anonymous user, then install Deny Access module.
Answer: Just update your content type.

Add a numeric field like display_order etc.
Set value of this field only for those videos you want to show.
Go to your view settings and set;
Use pager:Display a specified number of items | x items
where x is the no.of videos you want to show
Then apply sorting by display-order

Hope it will work.
Answer: I think the Rabbit Hole module does exactly what you're looking for. Here's an excerpt from the module's description page answering your need. Good luck.

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.
Answer: Go for rabbit hole module, it does exactly the same. All the content is accessible via views/code but when you try to access the detail page "content/***" it is either access denied or you can set a redirect.
Comment: I will give it a ride, thanks. For the moment, I have solved it at low level, but it is best to know already done custom modules.
Answer: 1) Create a Boolean value field in your content type.
2) If value is selected as true a unique class should be added to that video field,
if value is selected as false the class should not be added to that video field.
3) Write some CSS to hide the videos where the class is not present.
Answer: Using the Rules module you can implement a rule that looks similar to this:
{ "rules_disallow_accesss_to_selected_urls" : {
    "LABEL" : "Disallow access to selected URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "content\/video-1",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, access to URLs like [site:current-page:url] is not allowed ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Anybody trying to access relative path content/video-1 will be redirected to a page with path no_access, and a related error message will be shown (adapt this path to fit your own conventions, and review the message to be shown).
The above rule only restricts access to relative path content/video-1 (as in your question). If you want to expand the rule to similar URLs, change  content\/video-1 to something like content\/video-\\d+$, or any variation that fits the naming convention of your paths.
The above rule does not (yet) take into account to only apply the Rules Action for users with selected roles only. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add ... eg: skip the rules action for users with a role like editor, administrator, etc. Which you can do by adding a Rules Condition like "user does NOT have role administrator (and/or editor)". That way those kinds of special users can still view such nodes anyway (without such extra condition they also cannot view such nodes anymore ...).
To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if Rules UI is enabled). Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown).
Additional refinement
In one of the other answers you added a comment that includes this:

... I wanted to redirect to home page in some cases, 404 in others, etc., so I had better control ...

If that's what you also want to do, then you can further refine the above Rules Action by adding the Conditional Rules module also. With that, for each of your "some cases" you can then specify the appropriate URL to redirect to. Refer to my answer to "How to set the values of some fields depending on the value of a list box?" for an illustration of how to use this module within a Rules Action.


Using logistic regression to estimate whether probability of an outcome is greater than chance (and by how much)?

Question: I have an outcome variable that is subjects' correct or incorrect responses to a single question asked at two time points (before and after the experiment). I want to know if subjects were better than chance at answering these questions and by how much (i.e., obtain an effect size). I already know from a separate analysis that performance didn't vary depending on when the question was asked, so I think the most appropriate approach is to treat the responses as successes/failures and use the following code to run a model comparison, one estimating the intercept and one leaving it out and comparing the models using the likelihood ratio test to determine if the intercept-only model is more likely:
df$successes<-df$question1+df$question2
df$failures<-2-df$successes
modela<-glm(formula = cbind(df$successes, df$failures) ~ 1, family = binomial)
modelc<-glm(formula = cbind(d$successes, d$failures) ~ 0, family = binomial)
anova(modela, modelc)

I will interpret the exponent of intercept estimate (exp(2.6692) = 14.42) as the odds ratio relative to chance (e.g., Subjects' probability of responding correctly was 14 times higher than would be expected by chance.
Is this correct?
EDIT: I didn't realize this approach wasn't addressing the repeated measurement issue. To do so I propose the following code instead:
modela<-glmer(df$outcome ~ 1 + (1|df$ID), family=binomial)
modelc<-glmer(df$outcome ~ 0 + (1|df$ID), family=binomial)

Note, the data are melted in this case so that the responses (0 vs. 1) to the two questions are in the same column and ID is the variable that identifies multiple responses from the same individual.
Is this okay? The results seem interpretable. Or is there a simpler way to do this that gives me an effect size?
Answer: No, this isn't correct because the model treats all the trials as independent, when in reality they were grouped into pairs by subject. (And besides, in the case of independent trials, a binomial test is a much simpler approach to this problem.)
One way to account for this grouping is to augment your logistic-regression models with a batch of random effects, with one random effect per subject.
Comment: "For some reason I thought this approach addressed the issue of linked observations" — Yeah, it's an easy mistake to make because of R's interface which lets you specify trial counts. In reality, under the hood, logistic regression always has dichotomous outcomes, whose probabilities differ only with the covariates. "Can you let me know if this is correct and if this is the most straightforward way to do this and to obtain an effect size (odds ratio)?" — Yeah, I think it's correct, and I can't think of a simpler way that properly accounts for the grouping by subject.
Comment: Thanks. For some reason I thought this approach addressed the issue of linked observations but I guess I was wrong. I did as you suggested and ran a GLMM instead. Can you let me know if this is correct and if this is the most straightforward way to do this and to obtain an effect size (odds ratio)? I don't want to run an overly sophisticated model if it's not necessary, but I'm more familiar with regression these days so I don't always think of more basic approaches.


Measure theoretic proof on composition of invariant functions and integrability

Question: I'm looking for a proof that if f is $\mu$-integrable ($\mu(|f|) < \infty$, where $\mu(f)$=sup{$\mu(g):g \leq f,\ g  \text{ simple}$}), and $\tau$ is measure preserving ($\tau^{-1}(A)$ measurable for every measurable A), then $f \circ \tau$ is integrable and $\int f d\mu = \int f \circ \tau \, d\mu$. I have tried proving it myself (I need a proof but I don't need to have proved it myself) but I'm not sure where to start. Could anyone either direct me to a proof (online if possible though if it's a book that's not a disaster) or help me with such a proof? I can't seem to get going on it, so the more help you can give the better!
Thanks very much, Giles.
Comment: Can you prove it for simple functions?
Comment: There are two typos. 1. the first instance of $\mu(g)$ should be $\mu(f)$. 2. In the integrals you can not have $E$ in both cases.
Comment: My apologies - careless of me. Why can you not have E in both cases, sorry? If f has domain E (f: $E \to \mathbb{R}$, say) and $\tau$ is a map: $E \to E$, should the integrals not both be over E? Perhaps I am being slow.
Comment: @Qiaochu, yes, I believe I can prove the first and second statement for simple functions (I originally wrote '$f \circ \tau$ is measurable' when I meant 'integrable', sorry for any confusion), but it is unclear to me why it follows necessarily that if for all simple functions f, $f \circ \tau$ is integrable, then for -all- functions f, $f \circ \tau$ is integrable. Is it perhaps because of the dominated convergence theorem, taking better and better simple approximations to f?
Answer: There are two issues in the formulation of your question:

The definition
\[
\mu(f) = \sup\{\mu(g)\,:\,\text{$g \leq f$ simple}\}
\]
only works for $f \geq 0$. For general $f$ you have to write $f = f_+ - f_{-}$ with $f_+ \geq 0$ and $f_{-} \geq 0$ and use that by definition $\mu(f) = \mu(f_{+}) - \mu(f_{-})$.
You forgot the condition $\mu(A) = \mu(\tau^{-1}A)$ in the definition of measure-preserving.

As Qiaochu pointed out, the case of simple functions implies the general case. I'll treat the case $f \geq 0$ only.
Note that for the characteristic function $g = [A]$ of a measurable set $A$ we have $g \circ \tau = [\tau^{-1} A]$ and $\mu(g) = \mu(g \circ \tau)$ by hypothesis. By linearity of the integral $\mu(g) = \mu(g \circ \tau)$ for simple $g$. Now if $f \geq 0$ we may choose a sequence $g_{n}$ of simple functions such that $g_{n} \to f$ pointwise (a.e.) and monotone. By using the monotone convergence theorem twice and using the fact that $\tau$ is measure-preserving in the second equality we have
\[
\mu(f) = \lim_{n \to \infty} \mu(g_{n}) = \lim_{n \to \infty} \mu(g_{n} \circ \tau) = \mu(f \circ \tau)
\]
as desired.
Comment: That's perfect, thankyou - yes, I'm very sorry, I appear to have written the question out a bit carelessly, it will be better next time. Thankyou so much for the help.
Comment: @Giles H.: No problem ;-) Be sure to keep this argument in mind, it's of fundamental importance. A large number of basic results in measure theory are proved this way.


Jquery having trouble positioning images

Question: Follow on from:
Javascript wait for image to load before calling Ajax
function initResources() {

    var newImage;
    for (i = 0; i < resourceData.length; i++) {

        // Create the image
        newImage = $('');

        newImage.load(function() {

            alert(i);

            // Position
            $('#imgA' + i).position().top(Math.round(resourceData[i][5] * currentScale));
            $('#imgA' + i).position().left(Math.round(resourceData[i][4] * currentScale));

        });
        newImage[0].src = uploadFolder + '/' + imgData[resourceData[i][1]][1];
        $('#thePage').append(newImage);
    }
}

I have an array of images.  When the page is loaded initially from the server, this function loops through all the images and places them on the page.
This function is also called when the scale of the page changes.  The scaling function clears the HTML and redraws everything with the scale multiplier.
The problem with this function, is that it always alerts resourceData.length, which is the end of the loop.  I need to somehow pass data to the load function, so that when the image does finally load, it is referencing the correct ID/i.
Answer: You have a single i variable which is shared among all of your callbacks.
Since the callbacks execute asynchronously, they will all execute after the loop finishes, when i is length.
You need to put the loop body into a separate function that takes i as a parameter.
This way, each load callback will use a separate i variable (the function parameter), which will never change.
Answer: You can use a $.each() loop to create the closure (into which that index is it's own variable, not shared) you need...and the .position() call needs a bit of change as well, you should use .css() here which takes an object, like this:
function initResources() {
    var newImage;
    $.each(resourceData, function(i, data) {
       newImage = $('');
       newImage.load(function() {
            $(this).css({ top: Math.round(data[5] * currentScale),
                         left: Math.round(data[4] * currentScale) });
       });
       newImage[0].src = uploadFolder + '/' + imgData[data[1]][1];
       $('#thePage').append(newImage);
    });
}

You can shorten this up more, but it'll be no more efficient.  Keep in mine that inside the .load() event handler you can refer to the element the handler is for with this, no need to select it again.
Comment: If you added a parameter to the `$.each()` callback you could get the value of `resourceData[i]` without having to dig through the array every time.
Comment: @gnarf - good point - it won't matter for small arrays but does look much cleaner....I also didn't notice that markdown totally screwed some array values there - thought *something* looked off, fixed now.


R - Get averages from column combinations

Question: I am having a hard time finding answers/examples on SO of what I'm trying to do, which is the following:
Example data frame where I've got values (1) as well as NAs in cells:
Obvs | Cond1 | Cond2 | Cond3 | Cond4 | Value
---------------------------------------------
1    | 1     | NA    | 1     | NA    | 3
2    | NA    | 1     | 1     | NA    | 2
3    | 1     | NA    | 1     | NA    | 9
4    | 1     | NA    | NA    | 1     | 9
5    | NA    | 1     | NA    | NA    | 7
6    | NA    | NA    | NA    | 1     | 7
7    | NA    | NA    | 1     | NA    | 10
8    | NA    | 1     | NA    | NA    | 9
9    | NA    | NA    | NA    | 1     | 4
10   | 1     | NA    | NA    | NA    | 4
11   | NA    | NA    | 1     | 1     | 3
12   | NA    | 1     | 1     | NA    | 5

My goal is to get the average of rows that satisfy each column combination with a value (i.e., value of 1) in them. For example, observations in Obvs 1 and 3 both have values in Cond1 and Cond3 while the other Cond cols are NA , so I would want to create a separate column that would hold that average of those two Obvs' Values. So output would be something like below where it shows the average Value of all Cond combinations available in the dataset. Is there any way for R to find all of those combinations elegantly (without me manually specifying them) and spit out the average Value if it satisfies a specific combination?  This would be for a large dataset with many more columns in it to consider.
Cond1 | Cond2 | Cond3 | Cond4 | Avg_Value
1     | NA    | 1     | NA    | 6
NA    | 1     | 1     | NA    | 3.5
1     | NA    | NA    | 1     | 9
NA    | 1     | NA    | NA    | 8
NA    | NA    | NA    | 1     | 5.5
NA    | NA    | 1     | NA    | 10
1     | NA    | NA    | NA    | 4
NA    | NA    | 1     | 1     | 3

Thanks a lot!
Answer: You can use group_by and summarise from package dplyr:
df %>%
  group_by(Cond1,Cond2,Cond3,Cond4)%>%
  summarise(Avg_Value=mean(Value))

    Cond1   Cond2   Cond3   Cond4 Avg_Value
    <chr>   <chr>   <chr>   <chr>     <dbl>
1  1       NA      1       NA           6.0
2  1       NA      NA      1            9.0
3  1       NA      NA      NA           4.0
4  NA      1       1       NA           3.5
5  NA      1       NA      NA           8.0
6  NA      NA      1       1            3.0
7  NA      NA      1       NA          10.0
8  NA      NA      NA      1            5.5

Comment: Thanks @HubertL!  That is what tripped me up--the group_by() part. I will gladly take the downvote that a couple people have given me--I realized I was quite close to solving this on my own!
Comment: To avoid downvotes, it's better to provide the data in a machine readable format (instead of /  in addition to human readable format). It's important to add your (not working) code too


li jQuery Animation

Question: Please, someone can help me? I can't resize #top from li menu item. this is html code:

ESTUDIO

PORTFOLIO

SERVICIOS

PRESUPUESTO

CONTACTO

AND THIS jQUERY
$("#nav li[id='nav4']").live('click', function(e) {
$("#top").animate({height:114});
});

Comment: Works fine for me. http://jsfiddle.net/z4KrL/
Comment: What do you mean by "resize" #top?
Answer: I would suggest .on() instead of .live(), "As of jQuery 1.7, the .live() method is deprecated"

http://jsfiddle.net/z4KrL/9/
and don't use so menu ID's use Classes, e.g
UPDATE:

copy code from above to the bottom of the page
Add link to the Jquery library
remove link to external topheight.js
Comment: Why should we not use IDs? They're pretty useful...
Comment: That article does not argue against using ids.
Comment: pasted wrong link, sorry, http://css-tricks.com/the-difference-between-id-and-class/
Comment: That article does not argue against using ids either.
Comment: I can just imagine css styling with html like that
Comment: thanks, bt #top don't make nothing. not working. another solution?
Comment: it's works, see here http://jsfiddle.net/z4KrL/17/, click on the "PRESUPUESTO"
Comment: you can see it here please. Don´t work. You can see it something wrong?

http://www.vektorlab.com/nuevo/prueba.html
Comment: I don't see link to Jquery library in your page?
Comment: ?¿ sorry, i don't understand. your code from jsfiddle.net/z4KrL/17 don't work on local. why? sorry for my ignorance.
Comment: yes, sorry, one moment...
Comment: now you can see it. many thanks for helping

http://www.vektorlab.com/nuevo/prueba.html
Comment: Ok, now work it!! but why i can't put the code in external .js?

li jQuery Animation


Array of pointers to struct in C

Question: I have a struct in my c code of about 300Bytes (5xint + 256chars), and I wish to have a good mechanism of array for handling all my 'objects' of this struct.
I want to have a global array of pointers, so that at first all indices in the array points to NULL, but then i initialize each index when I need it (malloc) and delete it when im done with it (free).
typedef struct myfiles mf;
mf* myArr[1000];

Is that what Im looking for? Pointers mixed with arrays often confuse me.
If so, just to clerify, does
mf myArr[1000];

already allocates 1000 structs on the stack, where my first suggestion only allocates 1000pointers?
Answer: You are correct.  Former allocates 1000 pointers, none of which are initialized, latter initializes 1000 objects of ~300 bytes each.
To initalize to null:  foo_t* foo[1000] = {NULL};
But this is still silly.  Why not just mf* myArr = NULL?  Now you have one pointer to uninitialized memory instead of 1000 pointers to initialized memory and one pointer to keep track of.  Would you rather do
myArraySingle = malloc(sizeof(mf)*1000); or
for(int i = 0; i < 1000; i++) {
    myArray[i] = malloc(1000);
}

And access by myArraySingle[300] or *(myArray[300])`?  Anyway my point is syntax aside don't create this unnecessary indirection.  A single pointer can point to a contiguous chunk of memory that holds a sequence of objects, much like an array, which is why pointers support array-style syntax and why array indices start at 0.
Comment: Thanks. Is it ok to depend on the fact that all pointers in my first suggestion are NULL, or it points to arbitrary location in the memory?
Comment: It would be better to do a memset on the array to ensure all pointers, point to NULL.
Comment: @e-r-a-n see edit, you can do this in one line since I think C99.
Comment: Why silly? I want to have clean start with my array, as I want to relay on the fact a spot in it is either null or storing a location for a struct
Answer: typedef struct myfiles mf;
mf* myArr[1000];

This is what you are looking for. This will allocate array of 1000 pointers to the structure mf.
Answer: You seem to understand correctly.
More accurately, I believe mf* myArr[1000] = { 0 }; would better meet your requirements, because you want a guarantee that all of the elements will be initialised to null pointers. Without an initialisation, that guarantee doesn't exist.
There is no "global" in C. You're referring to objects with static storage duration, declared at file scope.
Answer: typedef struct myfiles mf;
mf* myArr[1000];

yes, it will initialize 1000 pointers, you have to allocate memory to each one using malloc/calloc before use.

Array of pointers to struct in C


Show that the equation $\sin x = 1 − x^2$ has at least one solution.

Question: I'm a university student taking a real analysis course and I've been asked the question above. I've worked ahead on the term problem sheet so I'm in territory my lecture notes haven't covered, so all I can do is make some entry level observations. If anyone knows the formal and rigorous way to answer this question please let me know!
Naturally the first thing I do is abuse Wolfram-Alpha. There appear to be two solutions that are the roots of $x^2 + \sin x -1 $ occurring near at $x \approx -1.40962 $ and $x \approx 0.636733$
This idea of roots occurring "near" something sounds new to me and is maybe the link I could be missing.
Any tips would be much appreciated!
Comment: Have you learnt about the intermediate value theorem? Apply it to the function $f(x) = \sin x - 1 + x^2$ (note that  $x$ is a solution to your equation if and only if $f(x) = 0$).
Comment: $F(x):=1-x^2-\sin x$, continuos function. $F(0)=1>0$; $F(-2)<0$; IVT, there is a $c \in (-2,0)$ with $F(c)=0$.
Comment: IMHO, the "near" notation is only to specify which exactly root is meant if it can't be expressed in terms of elementary functions or maybe if explicit expression is quite long
Answer: $\sin(0)=0$ while $1-0=1$ .. that is, $\sin(x)<1-x^2$ at $x=0$
Then $sin(\pi)=0$, but $1-\pi^2 <0$ That is, $sin(x)>1-x^2$ at $x=\pi$
Since $sin(x)$ and $1-x^2$ are continuous, then by the Intermediate Value Theorem, they must cross somewhere between $(0,\pi)$
Answer: Draw the graphs, i.e draw y=sin(x) and y=1-x^2. If you are not expected to find the values of x for the above equation, you are good to go.
y=1-x^2 is a simple parabola and, being a uni student you must be familiar with y=sin(x).
hope that helped :")


Filtrar palavra em um texto com php

Question: Gostaria de extrair algumas palavras em um texto com php. Mas não são palavras fixas.. Quero palavras que sempre irão mudar mas elas estarão ao lado de palavras chave padrão EX:
ID : 123123
Nome : Elvis
Endereço : Totis bla
Eu quero filtrar os valores de "ID" "Nome" "Endereço".
Não há um separador padrão ID:123, Nome: Elvis, Endereço! Ele separa por espaço, por traço, e ai vai... Porque o texto vem de um texto extraído de um arquivo PDF e salvo em uma variável ID: 123, Nome: Elvis - Endereço: toest.
Comment: Pergunta: Daonde vem estes dados? Algum Json?
Comment: @MarceloAymone isso realmente importa?? Essas informações no final onde eu vou fazer o filtro vai estar em uma variável.
Comment: Importa, porque se elas vierem de um formato json, ou algo assim, talvez seja mais simples de transformar em um array.
Comment: então, ele vem de um texto cara. Eu faço a leitura de um arquivo pdf padrão, e nesse arquivo pdf tem essas informações especificas que eu necessito retirar...
Comment: Entendi, então há a necessidade de trabalhar com a string mesmo
Comment: O valor de cada item pode ter espaço? Por exemplo, "Nome" pode vir com "Elvis da Silva"?
Comment: Ele me volta isso, onde eu salvo numa variável. Então eu queria pegar essas informações, tipo Advogado.. Código publicação..publicação....
Advogado

ADVOGADO (OAB: 0000 SC)

Código da Publicação

309437294

Disponibilização do Jornal

02/04/2014

Publicação do Jornal

03/04/2014
Comment: Pelo visto sim, to apanhando ai.. rsr
Comment: @MarceloAymone desculpa, é sim.. Vai ser string :D
Comment: Pelo menos tem uma ordem tipo: começa do ID, depois é o Nome e depois é o Endereço? e são separados por `:` ?
Comment: Isso, sempre serão os índices padrões com o mesmo nome, e são separados por espaço, porque vem de uma tabela.. Ai são separados por espaço
Comment: @DouglasBernardino, estava olhando aqui novamente, e pensando em outra solução para lhe ajudar, mas para isto precisaria de um exemplo mais completo, com os índices reais, teria como?
Answer: Tenta assim:
$string = "ID : 123123 Nome : Elvis Costelo da silva Endereço : Totis bla florianópolis";

$id = preg_split('#(?<!\\\)ID :|Nome :|Endereço :#', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$id = array_map('trim', $id); //Adicionado para eliminar os espaços

var_dump($id);

Imprime:
array (size=3)
   0 => string '123123' (length=6)
   1 => string 'Elvis Costelo da silva' (length=22)
   2 => string 'Totis bla florianópolis' (length=24)

Update - Solução sem regex: (Com Novas informações do usuário).
$string = "Advogado ADVOGADO (OAB: 0000 SC) Código da Publicação 309437294 Disponibilização do Jornal 02/04/2014 Publicação do Jornal 03/04/2014";

$indice = array("Advogado", "Código da Publicação", "Disponibilização do Jornal", "Publicação do Jornal");

for ($i = 0; $i < sizeof($indice); $i++) {
    $a = strpos($string, $indice[$i]);
    $a_size = strlen($indice[$i]);
    if (isset($indice[$i + 1])) {
        $b = strpos($string, $indice[$i + 1]);
    } else {
        $b = strlen($string);
    }
    $valores[] = substr($string, $a + $a_size, $b - $a - $a_size);
}
$resultado = array_combine($indice, $valores);
$resultado = array_map('trim', $resultado);
var_dump($resultado);

Resultado:
array (size=4)
    'Advogado' => string 'ADVOGADO (OAB: 0000 SC)' (length=23)
    'Código da Publicação' => string '309437294' (length=9)
    'Disponibilização do Jornal' => string '02/04/2014' (length=10)
    'Publicação do Jornal' => string '03/04/2014' (length=10)

Comment: Ótima solução. Pra ficar ainda melhor bastaria apenas um `array_map( 'trim', $id );`sobre **$id** pra limpar os espaços ao redor. Maiores informações sobre a ER em si, deixo como referência a quem interessar o [metacaractere modernoso](http://aurelio.net/regex/guia/modernosos.html#3_5) [(?<!ER)](http://aurelio.net/regex/guia/modernosos-nao-atras.html#3_5_6)
Comment: Se adicionar sobrenomes, complemente de endereço, funcionou aqui.
Comment: Pois é, terei que da uma verificada em expressão regular, porque essas informações eram para exemplo. Agora tenho que fazer expressão para minha necessidade.. Já ja eu testo e falo o resultado
Comment: Uhu, dá uma olhada nestas funções que utilizei, todas tem exemplos no manual do php;
Comment: Verdade, vou complementar
Comment: Não conhecia essa expressão e nem tinha o costume de usar o preg_split. Muito boa a solução.
Comment: @MarceloAymone Muito bom! E muito obrigado pela atenção!
Comment: @MarceloAymone: Esse meu comentário não lhe interessa para este tópico, mas peço que quando possível dê uma olhada [nesse tópico](http://meta.pt.stackoverflow.com/questions/1903/revers%C3%A3o-de-exclus%C3%A3o) do META que pode ser de seu interesse. Aos que acharem que isso pode ser um SPAM, essa atitude foi sugerida no próprio META por outros de maior calibre que eu.
Answer: Não sei bem como você pega esses valores pois não está claro a questão, mas vamos dizer que seja da seguinte forma (com o separador ",").
$dados = "ID : 123123, Nome : Elvis, Endereço : Totis";

Então basta fazer o seguinte para obter as keys.
$dados = "ID : 123123, Nome : Elvis, Endereço : Totis";

$dadosArray = explode(',', $dados);

$dadosCorretos = array();
foreach ($dadosArray as $da) {
    $temp = explode(':', $da);
    $dadosCorretos[$temp[0]] = $temp[1];
}

$dadosKeys = array_keys($dadosCorretos);

O retorno será:
dadosCorretos:
array(3) {
  ["ID "]=>
  string(7) " 123123"
  [" Nome "]=>
  string(6) " Elvis"
  [" Endereço "]=>
  string(6) " Totis"
}

dadosKeys:
array(3) {
  [0]=>
  string(3) "ID "
  [1]=>
  string(6) " Nome "
  [2]=>
  string(11) " Endereço "
}

Comment: Nesse caso então tem que ser uma regex mais bem trabalhada, vou testar aqui.
Comment: No comentário da questão está como pego esses valores... E não tem um separador padrão. Tipo, ID: 123431 - Endereço : Tide Numero: 123144, Nome: Doug
Answer: Nesse caso você pode utilizar expressões regulares (função: ereg_match ou preg_match).
Pra pegar o valor de ID, por exemplo, você pode utilizar:
$ereg_pattern = '/ID : (\d*)/';
$string = "ID : 123123 Nome : Elvis Endereço : Totis bla";
preg_match($ereg_pattern, $string, $matches);

Você terá o código ID no array $matches:
array (size=2)
  0 => string 'ID : 123123' (length=11)
  1 => string '123123' (length=6)

Para os outros casos bastaria apenas alterar o $ereg_pattern.
Comment: cara, não entendi muito bem sua função, teria como dar uma exlpicada??
Comment: E os valores de Nome? Endereço?
Comment: Expressões regulares é um tema extenso. Em resumo: É um método de pesquisa de texto baseado em "metacaracteres". No caso, os "metacaracteres" da pesquisa está entre as / / em $ereg_pattern.
Lendo a expressão, diz-se q tem de começar com 'ID : (\d*)' significa qualquer quantidade de dígitos (o \d representa dígitos).

Então, ao rodar a função da expressão regular, ele vai procurar por esse padrão: ID : (DIGITOS), e vai jogar dentro de um array o que ele encontrou.

Eu recomendo que leia o guia do Aurélio: http://aurelio.net/regex/guia e até compre o livro, pois vale a pena. Espero ter ajudado.
Comment: Beleza, entendi. Mas como eu vou fazer uma leitura num texto onde no meio do texto ele vai obter essas informações ?
Comment: Se o padrão sempre for o mesmo como você citou, a própria expressão regular vai fazer o trabalho pra você. No meu exemplo, a variável $string vai conter o seu texto.

Mas parece que o Marcelo, que entende bem de expressão regular já deu um exemplo mais completo. ;)

Filtrar palavra em um texto com php


Why are choices expressed the way they are?

Question: When I see a problem such as "Given a rod of length $n$ inches, how many ways can you cut it? Components after the cut should have integer inch lengths.", I immediately know that the answer is $2^{n-1}$ since we have an independent option of cutting or not cutting at distance $i$ inches from the left end.
However, I have forgotten why is it so? I know I have 2 options, and I know that we have $n-1$ points where the rod can be cut (or not). But, why is $n-1$ the exponent of $2$?
Answer: You can't cut at $0$ or $n$ as there is no rod on the other side.  So there are points you can cut from $1$ to $n-1$.  Try counting from $1$ to $3$, how many numbers do you count?
Answer: Since you recognize that there are $n-1$ potential cut points on an $n$-inch stick, I'm assuming that the question is why you combine the $2$ alternatives at each potential cut point with the $n-1$ potential cut points by exponentiation rather than in some other way.
It's the multiplication principle at work. Let's look at a rather different problem first. Suppose that you have a group of $4$ girls and $3$ boys, and you want to select a mixed couple. You can combine any of the $4$ girls with each of the $3$ boys. The possible combinations correspond to the $12$ numbered cells in this table:
$$\begin{array}{c|c|}
&B_1&B_2&B_3\\ \hline
G_1&1&2&3\\ \hline
G_2&4&5&6\\ \hline
G_3&7&8&9\\ \hline
G_4&10&11&12
\end{array}$$
More generally, if you have to make a sequence of two choices, and the first can be made in $m$ ways and the second in $n$ ways, you have $mn$ ways to make the pair of choices, corresponding to the $mn$ cells in a similar $m\times n$ table whose rows correspond to the alternatives for the first choice, and whose columns correspond to the alternatives for the second choice.
If you have to make a sequence of three choices, the corresponding table will be $3$-dimensional, but the principle is the same. If there are $k$ alternatives for the third choice, you'll have an $m\times n\times k$ table whose $mnk$ cells correspond to the different ways of combining the choices.
In the stick problem you have a sequence of $n-1$ choices, each of which has $2$ alternatives: at the $k$-inch point, for $k=1,\dots,n-1$, you can either cut or not cut. Thus, a table showing all of the possible combinations would be $(n-1)$-dimensional, with $2$ rows/columns/whatevers in each direction and would have
$$\underbrace{2\cdot2\cdot2\ldots\cdot2}_{n-1}=2^{n-1}$$
cells.
Alternatively, you can simply observe that every time you add an inch to the length of the stick, you add another possible cut point. If you had $a_n$ different ways of cutting an $n$-inch stick, you can still cut the first $n$ inches of an $(n+1)$-inch stick in $a_n$ different ways, and for each of those you can either cut or not cut at $n$ inches. This gives you twice as many possibilities, two for each of the old ones, so $a_{n+1}=2a_n$: the number doubles each time you add an inch to the stick and create a new potential cut point. Now $a_2=2$, since there's only one possible cut point (at $1$ inch), and you can either cut there or not. Thus, $a_3=2a_2=2^2$, $a_4=2a_3=2\cdot2^2=2^3$, and so on, so that in general $a_n=2^{n-1}$.


how can I study orchestration methods for electric guitar?

Question: In this post, I was given some tips on arranging electric guitars.  However, I would like to do further reading on the subject (spreads, range, register, coupling, doubling, unisons, etc), and I can't find anything outside of the realm of jazz/big band and classical music.  I am wondering:  is there another stringed instrument (orchestral) that is similar enough to an electric guitar that I can use it as a proxy for an electric guitar?  For example, if I study orchestration for "strings", would I learn a thing or two that can be applied to the electric guitar?
FYI, i'm working with a pop/rock setup--electric bass, two electric guitars, a vocal, and drum kit.
Thanks!
Comment: When you say "orchestration", what other instruments do you want to have the electric guitar playing along with? Generally orchestration is a study of using different instruments together.
Comment: How you arrange music for guitar, bass and drums depends very much on music style; perhaps it's one of important style defining elements. In this view, your question is quite broad.
Answer: Orchestrating the instruments in a rock band is pretty straightforward. Generally the guitars play above the bass. The challenges are not invading the bass territory and not drowning out the singer.
In terms of how to study it, the best answer is by analyzing the existing literature. Bands like Led Zeppelin (in recordings), Metallica, and AC/DC have very effective multi-guitar arrangements. Alice In Chains, Pearl Jam and Soundgarden also come to mind - "Fell On Black Days" by Soundgarden stands out in my mind in terms of its guitar arrangement.
Also the Eagles and some songs by The Beatles. Pop music in the 1980s and from today are less likely to have multiple guitar parts, so I wouldn't look too closely there. Country music is another place with more lush guitar arrangements. Also Eric Clapton - I think "Layla" has five or more guitar parts.
Comment: "The challenges are not invading the bass territory"  If you studied the music I listen to, it might seem that the challenge is "we keep running out of notes on the low end of the guitar".  And no matter how poorly you arrange your guitars, the bass will still have an entire octave below the guitars, unless you use some unusual alternate tunings.


How to make border bottom inside block?

Question: How to make border-bottom inside block after hover event?
I tried this using text-shadow, but seems it is not solution
Comment: You need to show us code that you are trying otherwise we won't be able to help you..
Comment: Can you explain it a bit.. with a codepen sample or provide the code you have tried..
Comment: Possible duplicate of [Placing border inside of div and not on its edge](http://stackoverflow.com/questions/9601357/placing-border-inside-of-div-and-not-on-its-edge)
Answer: An inset box shadow seems to be what you require

div {
  height: 75px;
  background: #c0ffee;
}

div:hover {
  box-shadow: inset 0 -5px 0 red;
}

OR
Use a pseudo-element

div {
  height: 75px;
  background: #c0ffee;
  position: relative;
}

div:hover::after {
  content: '';
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 5px;
  background: red;
}

How to make border bottom inside block?


(Weak) homotopy type of mapping cones of inclusions

Question: For cofibrations $A \subset X$ the projection $CA \cup X \rightarrow X/A$ is a homotopy equivalence. But what happens for general pairs of spaces ?
Is the projection at least still a weak equivalence or can the (weak) homotopy types actually differ ? I was not able to come up with any counterexample, but maybe someone here knows the answer.
Answer: Here is a kind of well known example.
Let $Y=A \vee B$ be the one-point union (wedge) of two Hawaian earings (look that up in wiki!), with base points the "bad point". Let $X=Y \cup CB$. Then $X/A$ is contractible. However $X \cup CA$ is a standard example of a space with an infinite fundamental group, with non homotopically trivial paths going alternately round the bases of the cones in ever decreasing lengths.
You can do this type of example another way round. Let $Z$ be the union of two (unreduced!)  cones on Haiwaian earrings together with a line segment $L$ joining the bad points at the bases of the cones. Then $Z$ is contractible, as is $Z \cup CL$, but $Z/L\cong X \cup CA$ as above is not contractible.
There is a paper by Morgan and Morrison in Proc London Math Soc (3) (1986) 562-576 which has more detail on such (difficult) determinations of the fundamental group.


Repair chain example problem in find the limiting distribution of a Markov Chain

Question: I am working through Durrett's book Essentials of Stochastic Processes, which is quite good. He had a problem in the first chapter on Markov processes, and I had trouble understanding how he obtained a particular matrix to solve the problem.
The problem is a repair chain problem. Here is the text of the problem from the book:
BEGIN QUOTE FROM BOOK
A machine has three critical parts that are subject to failure, but can function as long as two of these parts are working. When two are broken, they are replaced and the machine is back to working order the next day. Declaring the state space to be the parts that are broken $\{0, 1, 2, 3, 12, 13, 23\}$, we arrived at the following transition matrix:
$$
\begin{matrix}
   & 0    & 1    & 2    &3    &12   &13   &23 \\
0  & 0.93 & 0.01 & 0.02 &0.04 &0    &0    &0 \\
1  & 0    &0.94  & 0    & 0   &0.02 &0.04 & 0 \\
2  & 0    & 0    & 0.95 & 0   &0.01 &0    &0.04 \\
3  & 0    & 0    & 0    &0.97 &0    &0.01 &0.02 \\
12 & 1    & 0    & 0    &0    &0    &0    &0\\
13 & 1    & 0    & 0    &0    &0    &0    &0\\
23 & 1    & 0    & 0    &0    &0    &0    &0\\
\end
{matrix}
$$
and we asked: If we are going to operate the machine for 1,800 days (about 5 years) then how many parts of types 1,2, and 3 will we use?
To find the stationary distribution we look at the last row of
$$
\begin{bmatrix}
 & -0.07 & 0.01 & 0.02 &0.04 &0    &0    & 1 \\
 & 0    & -0.06  & 0    & 0   &0.02 &0.04 & 1 \\
 & 0    & 0    & - 0.05 & 0   &0.01 &0    & 1 \\
 & 0    & 0    & 0    & -0.03 &0    &0.01 & 1 \\
 & 1    & 0    & 0    &0    & -1    &0    & 1\\
 & 1    & 0    & 0    &0    &0    & -1    & 1\\
 & 1    & 0    & 0    &0    &0    &0    & 1\\
\end{bmatrix}^{-1}
$$
END QUOTE FROM BOOK
So I was trying to understand where Durrett obtains this this second matrix which he inverts? I checked and this is not the transition matrix raised to the 1800 power. Also, it seems like this second matrix is formed by taking $p(i, i) - 1$ except for the last column which becomes all 1s. It did not make sense that these negative values represented transition probabilities.
As a hint he does suggest that the solution to this problem illustrated a theorem:
$$
\text{Suppose a markov process is irreducible, stationary, and } \sum_x|f(x)|\pi(x) < \infty \ \text{then} \\
\frac{1}{n}\sum_{m=1}^n f(X_m) \rightarrow \sum_x f(x)\pi(x)
$$
Answer: Let $A$ be the transition matrix and let $e_n$ be the all-one vector of dimension $n$. Since each row of the transition matrix sums to one, one properties that a transition matrix has to satisfy is $Ae_n = e_n$ that is $(A-I)e_n = 0$.
Let's express $A-I = [B , b]$ where $b$ is the last column.
That is we have $$Be_{n-1} +b = 0\tag{1}$$
For a stationary distribution $\pi \neq 0$, it satisfies$$\pi^TA = \pi^T$$
that is
$$\pi^T(A-I) = 0$$
or $$\pi^T[B, b]=0$$
From $(1)$, we can see that $\pi^TB=0$ would imply $\pi^Tb=0$.
As a probability distribution, $\pi$ also has to satisfy
$$\pi^Te = 1$$
We can write the requirement compactly as $$\pi^T [B ,e] = \begin{bmatrix} 0 \ldots, 0, 1\end{bmatrix}$$
Hence $$\pi^T = \begin{bmatrix} 0 \ldots, 0, 1\end{bmatrix}[B, e]^{-1}$$
that is $\pi^T$ is the last row of $[B, e]^{-1}$.


Good malware removal tool(s) for windows XP/Vista/7?

Question: The goal for this Wiki is to extablish a list of known good tools for cleaning up those pesky malware / virues that haunt windows clients. What tools do you like and what are their strengths and weaknesses?
I'll post my own favorite as an answer.
UPDATE: Not really sure why this was marked as off topic as desktops in the enterprise do get malware, and sometimes we have to clean them up.
Comment: We don't do lists of products - this doesn't belong here or on SU.
Comment: Looks like SU already has this http://superuser.com/questions/5478/user-safe-malware-removal-tools
Comment: @Nixphoe: That's over 2 years old.  I suppose it could be updated, but ...
Comment: Not really sure why this was marked as off topic as desktops in the enterprise do get malware?
Comment: @Alan: One doesn't "clean up" compromised machines. You reinstall them from known-good media. Anything less is risking that a persistent malicious program will remain.
Comment: Sometimes you do... depends on the situation doesnt it? In this reinstalling the OS was not an option. I ended up using malware bytes to clean it up.
Answer: I tend to find a Windows installation CD to be the best tool for removing malware. Backup the system. Format the system. Reinstall the system. Restore the backup. Fixes them EVERY time.
Comment: Nuke from orbit. That's the only professional method, IMHO.
Answer: Ultimate Boot CD for Windows has about 12 different tools for virus & malware removal.  The best part of using this boot CD is that it is out-of-band and therefore no viruses on the system can interfere with scanning and removal.  You can also install it to a bootable USB stick and keep the definitions updated.
Comment: I'll give you the answered for effort - despite the fact it only lasted 5 mins.


Views 3 Template or UI question

Question: I have a text field that contains multiple values. That field does not always contain any values. The field needs to have a label when displayed.
IOW, the row should look like one rows below
CoAuthor: Person X, Person Y
or
CoAuthor: Person X
Here is my issue: When I use the view UI to add the label I get
CoAuthor: Person X, CoAuthor: Person Y
When I use the template,
print $fields['field_coauthor']->content;

I can not hide the field when empty so I end up with
CoAuthor: (and no value)
Is there a way to add a conditional to the template so that I do not end up with a label and no data? Or configure the view to include the label once... and not add it for every entry?
Answer: I am actually a bit puzzled by your View result, because the default settings for fields should give you:

CoAuthor: Person X, Person Y

when there is more than one author (and this I presume, is what you want?)
And since Views also have a setting: "Hide if empty" under *No results behavior", it should be trivial to get this right using fields.
Anyway, this is how I've set this up using Views:
First, I click on Format - Show: Content and switch that to Fields.
Second, I tick Provide default field wrapper elements and Hide empty fields.
Third, under Fields I click Add and add the "CoAuthor" field. I tick Create a label, and Place a colon after the label. Under Multiple field settings, I tick Display all values in the same line.  I also tick Simple separator and make sure it is ,  (comma followed by space, which is the default).Then under No results behavior, I leave No results text blank, and tick Hide if empty and Hide rewriting if empty.
Fourth, I navigate to Format - Show: Settings and tick to make sure CoAuthor is an inline field.
After doing all this, the output should be nothing if there are no CoAuthor, and for the other two cases:

CoAuthor: Person X
CoAuthor: Person X, Person Y

As for using a template, you should be able to wrap the PHP generating the output in a test that checks for a non-empty field, e.g.:
if (!empty(print $fields['field_coauthor']->content)) {

I not sure where the template fragment you post come from, so I haven't posted the full code, but I hope you get the idea.

Views 3 Template or UI question


Proving an inequality of three sequences

Question: Let two sequences ($u_n$) and ($v_n$):
\begin{align}
u_n &= \sin(1/n^2) + \sin(2/n^2) + \ldots + \sin(n/n^2)\\[0.2cm]
v_n &= 1/n^2 + 2/n^2 + .... + n/n^2
\end{align}
In the previous parts of my exercise, I proved that $v_n$ is decreasing, convergent and its limit towards $+\infty$ is $\frac12$. I also proved that the following functions are all increasing and strictly positive in the interval $(0,+\infty)$
\begin{align}
f(x) &= x - \sin (x)\\
g(x) &= -1 + \tfrac12x^2 + \cos (x)\\
h(x) &= -x + \tfrac16x^3 + \sin (x)
\end{align}
Then, using these informations, I must prove the following inequality:
$$v_n - \frac16 \cdot\frac1{n^2} \leq u_n \leq v_n$$
before inferring that $u_n$ is convergent and $u_n$'s limit.
The problem is that I really don't know how to manage this part of my exercise : how to prove this inequality of sequences?
Thanks for your answers.
Answer: You have done the difficult part which is to calculate the limit of the $v_n$ and to show that $h(x),f(x)\ge0$. Just as an observation: $h'(x)=g(x)$ and $h''(x)=g'(x)=f(x)$. Now, for any $1\le k\le n$ $$0\le h(k/n^2)=-\frac{k}{n^2}+\frac16\cdot\frac{k^3}{n^6}+\sin{\left(k/n^2\right)} \implies \frac{k}{n^2}-\frac{k^3}{6n^6}\le\sin{\left(k/n^2\right)}$$ and summing up over $k$ \begin{align}\sum_{k=1}^n\left(\frac{k}{n^2}-\frac{k^3}{6n^6}\right)\le \sum_{k=1}^n\sin{\left(k/n^2\right)}&\implies v_n-\frac{1}{6n^6}\cdot\frac{n^2(n+1)^2}{4}\le u_n \\[0.2cm]&\implies v_n-\frac16\cdot\frac{1}{n^2}\le u_n\end{align} Similarly $$0\le f\left(k/n^2\right)=k/n^2-\sin{\left(k/n^2\right)}\implies \sum_{k=1}^{n}\sin(k/n^2)\le \sum_{k=1}^nk/n^2 \implies u_n\le v_n$$ Putting these together and using the Squeeze Theorem you have that \begin{align}\lim_{n\to +\infty }\left(v_n-\frac16\cdot\frac1{n^2}\right)\le \lim_{n\to+\infty}u_n\le \lim_{n\to+\infty}v_n&\implies \frac12-0\le \lim_{n\to+\infty}u_n\le \frac12 \\[0.2cm]&\implies\lim_{n\to+\infty}u_n=\frac12\end{align}

Although the result already obtains with the lower bound $$v_n-\frac{1}{6n^6}\frac{n^2(n+1)^2}{4}$$ it is only a straightforward calculation to show that $$v_n-\frac{1}{6n^2}\le v_n-\frac{1}{6n^6}\frac{n^2(n+1)^2}{4}$$ for any $n\ge 1$ in order to bring it in the form that the exercise requires.


Render picture module image in a custom module

Question: I am trying to render a responsive picture module image from within a module. I cant find any functions that I can pass the picture mapping into.
If I render the whole node from within the module it works fine but if I just render the image it does not work.
Any thoughts would be great.
Answer: Here is my solution to build the render array of the drupal 7 picture module v2
<code>//Load picture renderable array

$picture_name = 'mapping_name'
$fallback_image_style = 'large';

$image = $node->field_image[LANGUAGE_NONE][0];

$picture_mappings = picture_mapping_load($picture_name);

$breakpoint_styles = picture_get_mapping_breakpoints($picture_mappings, $fallback_image_style);

$picture = array(
        '#theme' => 'picture',
        '#width' => isset($image['width']) ? $image['width'] : NULL,
        '#height' => isset($image['height']) ? $image['height'] : NULL,
        '#style_name' => $fallback_image_style,
        '#breakpoints' => $breakpoint_styles,
        '#uri' => $image['uri'],
        '#alt' => isset($image['alt']) ? $image['alt'] : '',
        '#attributes' => isset($image['attributes']) ? $image['attributes'] : NULL,
        '#timestamp' => $image['timestamp'],
      );

print render($picture);
</code>
Comment: Note the `$image` value if you only have a system path you can use `image_get_info('public:image/in/files.png')`
Answer: You could use the field_view_field() function.
eg.
<code>$output = field_view_field('node', $node, 'field_name');
</code>
read more about the correct way to render node fields at this blog post
Comment: I have tried this but it does not give the Picture module responsive version of the image, just the original.
Answer: Adding 'default' to the functions arguments sorted it out
<code>$field = field_view_field('node', $node, 'field_image', 'default');
</code>


Summernote - Adding images with file-size limit

Question: I've been googling everywhere to find a way to prevent any images bigger than 500kb but haven't found a single solution. The reason why I'm trying to limit the file size of images is for mobile users using limited data plans.
I ended up believing that it's impossible because summernote saves images as text something like this.....

and generate back as an image when needed.
Do I still need to limit the file size even if I store them as text in DB?
If I have to, is there an api for this?
Comment: Just to answer myself - I found this article http://stackoverflow.com/questions/11402329/base64-encoded-image-size.   Base64 is about 137% bigger than the actual image file.
Answer: You can limit the picture size in summernote plugin by adding these options:
$('.summernote').summernote({
    // your options... and
    maximumImageFileSize: 500*1024, // 500 KB
    callbacks:{
        onImageUploadError: function(msg){
           console.log(msg + ' (1 MB)');
        }
    }
});

Answer: Check this link: https://github.com/summernote/summernote-rails/issues/22
$('.summernote').summernote({
  maximumImageFileSize: 1048576
});
Answer: If i understand correctly you use this https://github.com/summernote/summernote/blob/develop/src/js/settings.js please check the maximumFileSize: 'Maximum file size', parameter in the image option. In there you can set the limit you want.
Comment: Hi check this link https://github.com/summernote/summernote/blob/develop/src/js/bs3/settings.js under maximumImageFileSize are available callbacks. You probably need a callback for onImageUpload and onImageUploadError, for example onImageUpload: function(files) {
      //// check file size against maximumImageFileSize
    } ,   onImageUploadError: function() {console.log("Error uploading image");} Some more ideas can come up from here http://summernote.org/deep-dive/#onimageupload
Comment: It's working for me, but if the user select a file with bigger size that specified in maximumFileSize, the summernote will not add the image, but also there is no notification or error to the user to tell him, the image size is bigger, any idea?


Why models often benefit from reducing the learning rate during training

Question: In Keras official documentation for ReduceLROnPlateau class they mention that

Models often benefit from reducing the learning rate

Why is that so? It's counter-intuitive for me at least, since from what I know- a higher learning rate allows taking further steps from my current position, and if I'll reduce the LR I might never "escape" a certain minimum.
Answer: In ML methods where terms are added consequently (e.g. boosting) a learning rate below 1 is equivalent to shrinking coefficients of predictors towards 0. So reduced learning rate works for the same reason lasso and ridge regression work: regularization. In situations with high predictor-to-observation ratio, regularization reduces model variance at the expense of introducing a relatively small bias. Since the overall predictive error follows the rule
$$
\text{Mean-error Error} = \text{Bias}^2 + \text{Variance},
$$
the predictive error benefits from regularization.
Answer: A more complete quote is:

Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates.

(my emphasis).
There are two main reasons why your learning might seem to be stuck:

You are around a local minimum and in every direction you might go you'd increase your error. In that case, as you correctly state, increasing the learning rate might allow you to "jump out" of the local minimum.

You are in a steep valley and are oscillating between the walls. At one point the gradient points steep left; you make a large step in that direction and find yourself on the other side with the gradient pointing steep right. You are basically jumping back and forth far above the minimum. Here, decreasing the learning rate might allow you to descend into the minimum.

The above quote refers to this second case.
Comment: With regards to 2nd point, does this apply even for optimizers such as SGD, mini-batch SGD or their momentum variants? I can understand the oscillations intuition for vanilla GD
Comment: @adosar That's a good question to which I don't know the answer. It seems to me that SGD and its variants might change the *direction* in which you're going, but the step size could still be too large and lead to the "opposite wall of the gorge". Maybe you should post your comment as a question.


Product of sums and loss of generality

Question: I am struggling with seemingly simple algebraic manipulations with expressions containing finite sums. It is a physics based case but the interpretation of terms does not play any role now. Just note that the dot denotes the time derivative.
It starts with
$$
\left[ \sum_{n=1}^N n q_n \cos (n \sigma) \right] \left[ \sum_{n=1}^N n \dot{q}_n \cos (n \sigma) \right] + \left[ \sum_{n=1}^N \dot{q}_n \sin (n \sigma) \right] \left[ \sum_{n=1}^N n^2 q_n \sin (n \sigma) \right] = \ ...
$$
There are multiple ways to deal with these expressions. I have chosen a dummy way on purpose since it has the lowest risk of an error:
$$
... = \sum_{r=1}^N \sum_{s=1}^N r s q_r \dot{q}_s \cos (r \sigma) \cos (s \sigma) + \sum_{r=1}^N \sum_{s=1}^N r^2 q_r \dot{q}_s \sin(r\sigma) \sin(s\sigma)
$$
Up to this step I am pretty confident. But in the next one I have made a mistake surely:
$$
... = \sum_{r=1}^N \sum_{s=1}^N q_r \dot{q}_s \left[ r s \cos  (r \sigma) \cos (s \sigma) + r^2 \sin(r\sigma) \sin(s\sigma) \right]
$$
I cannot merge the sums since the index choice must remain arbitrary and I have made it bound.

Am I correct?
What is a proper remedy? Leaving four independent indices?
Answer: I don't see any mistake. You add two products of sums. Each product, when you use the distributive law (first step that you are confident in) will get a double sum that has terms $q_r\dot{q}_s$ with a factor where both $r$ and $s$ vary from 1 to $N$. And why do you think you cannot combine those sums into one, as you did?
It may not make any sense for the physics involved, but mathematically this is sound.
Addition to answer Victor's remark:
@Victor: You are right, you could choose $r,s$ the opposite way for the second sum, or could choose $r,s$ for the first sum and $i,j$ for the second sum. Then you could not apply the mathematical formalism that you used.
But the choice of index name is arbitrary, it doesn't matter what you call them, the term $1\times2q_1\dot{q}_2\cos(\sigma)\cos(2\sigma)$ will always be a part of the first sum, and $1^2q_1\dot{q}_2\sin(\sigma)\sin(2\sigma)$ will always be a part of the second sum, and you can always combine them to $q_1\dot{q}_2(2\cos(\sigma)\cos(2\sigma)+\sin(\sigma)\sin(2\sigma))$.
The 'right' choise of index names makes the formalism applicable and leads to the combined formula. It's like choosing the 'right' coordinate system for a mechanical probem (like a tilted plane): Doing so allows the math (like the differential equation from Neton's laws) to be simple and easily solvable. That doesn't mean that using the 'wrong' one leads to a different solution. It just means that the math may be more complicated (like coupled variables) and that you may not be able to solve it with what you know.
Comment: The opposite choice for the second sum would give you something like $\sum_{r=1}^N \sum_{s=1}^N \left[ q_r \dot{q}_s r s \cos  (r \sigma) \cos (s \sigma) + \dot{q}_r q_s s^2 \sin(r\sigma) \sin(s\sigma) \right]$; the only thing is that this version doesn't let you factor out $q_r \dot{q}_s$ inside the sum. But the value is still the same.
Comment: I think I cannot combine them cause the opposite choice of $r$ and $s$ indices (which is perfectly possible according to the distributive law) would lead to a different result ($\dot{q}_r q_s \neq \dot{q}_s q_r$). Isn't it right?

Product of sums and loss of generality


How to organise children menu links as tabs in D7?

Question: I'm using Drupal 7 and now I have a regular dropdown menu like this:
Link 1

sub-link 1
sub-link 2

Link 2
But I would like to organize my sub-links as tabs where sub-link 1 and sub-link 2 would  be a content tabs that contain a block content. I tried to use OM Maximenu Modul, it helps to organise parent links as tabs but not sub-links. Could anybody help me in this question?
Comment: So, I've just created a block with tabs jquery and some php code to show certain views in tabs content and attached it to menu item through the modul OM Maximenu. It works but I would like to find the easiest way to attach any block to menu item without modules. Thanks in advance if anybody knows how to do it.
Answer: Instead of OM Maximenu module I used Views Menu module as it easier and I used it only with purpose to attach views block to only one menu link.


Split perfect and Cantor sets

Question: Let $C$ be a  Cantor ternary set. We can write it  as union of $\mathfrak{c}$ many disjoint Cantor  sets as follows:
$$ C\times C= \bigcup_{x\in C} (\{x\}\times C)$$ and clearly $\{x\}\times C$ is Cantor set. Moreover, $(\{x\}\times C) \bigcap (\{y\}\times C)=\emptyset$. So, we can define a homemorhpic  between $C$ and $C\times C$ in the natural way just by sending $x$ to $\{x\}\times C$. We can conclude that $C=\bigcup_{\alpha<\mathfrak{c}} C_{\alpha}$ where $C_{\alpha}$'s are pairwise disjoint Cantor set.  I have two questions. Kindly check if what I did is correct and Also I know the same fact is correct for perfect, that is, every perfect set can be written as union of $\mathfrak{c}$-many  pairwise disjoint perfect sets.
Comment: I don't understand how you can send $x$ to $\{x\}\times C$. Note that $\{x\}\times C$ is a *subset* of $C\times C$, not an element of it. One way to build such a homeomorphism is to first identify $C$ with $2^\omega$(the space of infinite $0,1$ sequences) and then prove $2^\omega \cong 2^\omega \times 2^\omega$ via the map that splits each sequence to it's two odd and even indexed subsequences.
Comment: @ShervinSorouri Yes you are right, I can fix that but how perfect set how this can be done
Answer: The function you defined (at least before any edits you might make after I first posted my answer) is NOT a homeomorphism. Indeed, it's clearly not an injective function. I'll prove the result for perfect subsets of $\mathbb R$ (similar proofs can be used to prove the result for perfect subsets of ${\mathbb R}^n),$ and I'll leave it to you or others for generalizations to an arbitrary metric space or beyond.
Theorem: Let $P$ be a nonempty perfect subset of ${\mathbb R}.$ Then $P$ contains $c$-many pairwise disjoint nowhere dense perfect subsets.
Proof 1: First, map $P$ continuously onto $[0,1].$ For intervals this is trivial; for Cantor sets use a monotone increasing function similar to the Cantor function; if both types appear, pick one and work within that subset. Then follow this with a continuous mapping of $[0,1]$ onto the unit square (use a Peano curve). Now observe that the inverse images of the vertical fibers $\{r\} \times [0,1],$ as $r$ varies over $[0,1],$ gives continuum many pairwise disjoint nowhere dense perfect subsets of the given perfect set.
Proof 2: Since $P$ contains a nonempty compact perfect nowhere dense set (simply carry out a Cantor set type construction process relativized to $P),$ without loss of generality we can assume that $P$ is a nonempty compact perfect nowhere dense set. Since $P$ and $P \times P$ are nonempty totally disconnected perfect compact metric spaces, it follows from a classical topological result that $P$ is homeomorphic to $P \times P$ [Willard's General Topology, Corollary 30.4, p. 217]. Hence, the inverse images of $\{x \} \times P$ for any fixed homeomorphism from $P$ onto $P \times P,$ as $x$ varies over $P,$ gives $c$-many pairwise disjoint perfect subsets of $P.$
The result itself is due to Mahlo (1913) [1] and the first proof above is due to Luzin/Sierpiński (1917) [2].
[1] Friedrich Paul Mahlo, Über teilmengen des kontinuums von dessen mächtigkeit [On subsets of the continuum with its power], Berichte über die Verhandlungen der Königlich Sächsischen Gesellschaft der Wissenschaften zu Leipzig, Mathematisch-Physische Klasse 65 (1913), 283-315.
[2] Nikolai Nikolaevich Luzin [Lusin] and Wacław Franciszek Sierpiński, Sur une propriété du continu [On a property of the continuum], Comptes Rendus Hebdomadaires des Séances de l'Académie des Sciences (Paris) 165 #16 (15 October 1917), 498-500.
Comment: In the case of the first proof, map continuously onto $[0,1]$ using a monotone increasing function similar to the Cantor function, followed by a Peano curve onto $[0,1]^2$ (which is continuous). The composition of these two functions is a continuous function from the perfect set **onto** $[0,1]^2,$ and the inverse image of a closed set under a continuous function is closed, and each of the sets $\{r\} \times [0,1]$ is closed in $[0,1]^2.$ Think about details such as this a bit to get the rest of what you want.
Comment: In the theorem I simply stated that $P$ **contains** $c$-many pairwise disjoint perfect sets [#]. I didn't claim that $P$ is **partitioned** into $c$-many pairwise disjoint perfect sets. ([#] In case you think I overlooked that this wording allows for the empty set to be one of the perfect sets, note that there will still be $c$-many nonempty perfect sets.) It is true that you can get $P$ partitioned into $c$-many perfect sets, and I first stated it this way, but I was in a hurry (I've been working on something else the whole time) and didn't I want to deal with all the extra details.
Comment: This helps a lot thank you so much for your time. On small thing , if $P$ is nowhere dense compact set, how should we do
Comment: I have one question about your second proof. How can you assume that $P$ is none-empty compact nowhere dense set? I know that any perfect $P$ contains such a set, but how do you deal with the remaining part of $P$? In other words, let $C \subseteq P$ be a copy of the Cantor set, how do you deal with $P - C$?
Comment: For example how do you split $P = \mathbb{R}$?
Comment: For the "partitioned" version, I suppose one way would be to first prove a structure result for perfect subsets of the reals, whereby each perfect set consists of a disjoint union of countably many compact intervals and countably many compact perfect nowhere dense sets, each type interlaced with the other type. There is probably a more sophisticated and elegant approach, because I know the result is true in higher dimensions and it would be a mess to prove such versions the "brute force" way, and I'm pretty sure I've never seen the kind of mess I'm thinking of in a book or paper.
Comment: Actually, I'm not sure the "structure result" I implied is correct, as I'm now thinking of situations in which relatively tiny closed intervals are included in lots of the complementary intervals of the Cantor set, such as in every other complementary interval at each of the odd-numbered construction stages, or something equally difficult to imagine as being Cantor sets interlaced between closed intervals. Nonetheless, I think something like this is true and can be proved in a way similar to how one proves every open set of reals is a countable pairwise disjoint union of open intervals.
Comment: @ShervinSorouri [Bankston & McGovern (1979), Theorem 1.14](http://www.mscs.mu.edu/~paulb/Paper/toppart.pdf) proved that $\mathbb R$ can be partitioned into Cantor sets.
Comment: @bof, thanks for the reference. Nice paper in general.
Comment: @DaveL.Renfro, Do you have the second paper in English?
Comment: @00GB: I don't have an English translation of either paper. I don't think any of the many 1910s and 1920s point set theory (classical descriptive set theory) papers have been translated except for Suslin's 1917 paper on analytic sets. (I spent several days in June 2007 preparing a translation of this, with the help of someone because I can only "read" French slowly with a dictionary.)

Split perfect and Cantor sets


How do you create ProjectApiRoot as Customer in Commercetools

Question: I can create a ProjectApiRoot using the Java SDK and perform requests with that using the following code:
private static ProjectApiRoot createProjectClient() {
    ProjectApiRoot apiRoot = ApiRootBuilder.of()
            .defaultClient(ClientCredentials.of()
                    .withClientId(System.getenv("CTP_CLIENT_ID"))
                    .withClientSecret(System.getenv("CTP_CLIENT_SECRET"))
                    .build(),
                    ServiceRegion.GCP_EUROPE_WEST1)
            .build(System.getenv("CTP_PROJECT_KEY"))
    return apiRoot
}

However, I would like to authorize as a specific customer (email and password) and interact with the Commercetools API using the customer. The following code throws an error:
private static ProjectApiRoot createCustomerClient() {
    def tokenUri = "https://auth.europe-west1.gcp.commercetools.com/oauth/*CTP_PROJECT_KEY*/customers/token"
    def projectKey = System.getenv("CTP_PROJECT_KEY")
    def scopes = System.getenv("CTP_SCOPES")

    def credentials = ClientCredentials.of()
            .withClientId("*email*")
            .withClientSecret("*password*")
            .withScopes(scopes)
            .build()

    def apiRootBuilder = ApiRootBuilder.of()
            .withApiBaseUrl("https://api.europe-west1.gcp.commercetools.com")
            .withClientCredentialsFlow(credentials, tokenUri)

    return apiRootBuilder.build(projectKey)
}

Error:
io.vrap.rmf.base.client.oauth2.AuthException: detailMessage: Unauthorized
"message" : "Please provide valid client credentials using HTTP Basic Authentication.",

Answer: By using the withGlobalCustomerPasswordFlow instead of the withClientCredentialsFlow which authenticates the customer prior to doing the request.
But I would advise to do this only in a context where the customer is logging in everytime. Using it in any other context e.g. remembered log in of needs a more sophisticated approach as you need to store the bearer token and refresh token and can't easily use the middleware approach for authenticating the customer but instead do it not as part of an auth flow middleware.
Please see also https://github.com/commercetools/commercetools-sdk-java-v2/tree/main/commercetools/commercetools-sdk-java-api/src/integrationTest/java/commercetools/me
Comment: Thank you. I plan to do it in spock tests where every test starts with logging in.


Consigo fazer com que o documento gerado no código VBA abaixo seja salvo na pasta do arquivo fonte ou que ele peça para salvar em um local especifico?

Question: Estou criando uma macro no Excel que seleciona um texto e cola em outra aba da planilha e gera um .pdf automaticamente.
Quero tentar fazer com que o usuário em outro computado salve esse arquivo ou no mesmo caminho em que a planilha fonte vai está ou então apareça para ele a opção de salvar. (gostaria da primeira opção pois se só tiver a segunda como opção ele terá que fazer isso repetidamente.
Consigo fazer com que o documento gerado no código VBA abaixo seja salvo na pasta do arquivo fonte ou que ele peça para salvar em um local especifico?
Sub imprimirAG2P()
'
' imprimirAG2P Macro
' imprimir AG 2P
'

'
    Range("A3").Select
    ActiveCell.FormulaR1C1 = "AG1 2P"
    Sheets("MEC - 111 - AGITATOR").Select
    Range("G7").Select
    ActiveCell.FormulaR1C1 = "AG1 2P"
    Range("G8").Select
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "D:\00 - MEUS DOCUMENTOS\DOCUMENTOS\01 - DOC CONTROL\01 - FVI - FVM\01 - FVI\03 - FVI PRONTAS\FVI\AG1 2P.pdf" _
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
        :=False, OpenAfterPublish:=True
    Sheets("databank").Select
End Sub

Answer: Descobri aqui que se eu tirar o "Caminho" do arquivo como por exemplo "D:\OUTRO HD" e deixar só o nome do arquivo: AG1 2P.pdf, ele automaticamente salva no "C:\user\fulano\Documents"
´´´
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "AG1 2P.pdf" _
´´´

Isso não resolve totalmente o problema mas já ajuda.
Agora só resta saber se consigo fazer com que o documento seja salvo na pasta do arquivo fonte ou que ele peça para salvar em um local especifico.
Answer: Oi, Marcus!
Pra atender a sua opção basta usar a propriedade ActiveWorkbook.Path, que é o atributo que diz onde a planilha está salva (partindo da premissa que não é um arquivo ainda não salvo)
Então:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        Activeworkbook.path & "\AG1 2P.pdf" _

Se quiser entregar ao usuário um prompt você usa:
Dim f As Object
Set f = Application.FileDialog(msoFileDialogFolderPicker)

f.InitialFileName = ActiveWorkbook.Path
f.AllowMultiSelect = False
f.Show

MsgBox f.SelectedItems(1)

A diferença é que você vai ter que tratar um pouco o que vai aparecer, pra se proteger de seleção vazia ( if f.SelectedItems(1) <> "" then...) e etc
Mas a lógica geral é essa


Combining repeated experiments into one dataset

Question: I hope you all won't mind a basic question.
We are examining the effects of a compound at various concentration on the behaviour of an organism. The compound is administered once at the beginning of the time course.  Observations are made every minute for a period of 2 hours.  Each concentration is applied to 12 individuals.
If we repeat this experiment with different individuals, what is the best way to combine the 2 experiments? The issue that we're having is that although the distribution and shape of the data from each experiment is very similar, the plot of the medians by time is usually significantly shifted up or down between exp1 and exp2.
It will no doubt be very evident that I'm unskilled in statistics. If this question needs more information to be answerable, let me know.
Thanks,
Jen
Answer: Just add "experiment" as an effect to your model, that should account for the shift between experiments and let you gain the power of increased N across experiments to detect effects of concentration and time.
In R, if using ANOVA and treating time as a factor (e.g. not numeric), then do:
library(ez)

ezANOVA(
    data = my_data
    , dv = .(my_dv)
    , wid = .(individual)
    , within = .(time)
    , between = .(concentration,experiment)
)

However, this:

treats experiment as a fixed effect, whereas it might more reasonably be considered a random effect (thanks Henrik!)
treats time as non-continuous
assumes sphericity across the levels of time

An approach that solves all three issues is to employ a mixed effects model. If you think that the effect of time is linear, then leave time as a numeric variable and do:
library(lme4)

lmer(
    data = my_data
    , formula = my_dv ~ time*concentration+(1|individual)+(1|experiment)
)

If you don't think time is linear, you could convert it to a factor and repeat the above, or use generalized additive mixed modelling:
library(gamm4)
fit <- gamm4(
    data = my_data
    , formula = my_dv ~ time+concentration+s(time,by=concentration,bs='tp')
    , random = ~ (1|individual) + (1|experiment)
)
print(fit$gam)

That assumes that experiment only shifts the time function, but lets concentration change the shape of the time function. I have a hard time figuring out how to visualise the results from single gamm4 fits, so I usually obtain the fitted model's predictions across the fixed-effects space then bootstrap (in your case, sampling individuals with replacement within each experiment) confidence intervals around these predictions.
Also, all of the above assume that residuals are gaussian; if you're dealing with anything different (eg. binomial data), then you need to change the "family" arguments of lmer and gamm4 (ezANOVA can't do anything but gaussian).
Comment: I have never heard of this approach, but it seems somehow reasonable. But, "experiment" should rather be a random factor, than a fixed one. These two experiments are just two randomly drawn from the population of possible experiments with this design. They are in no way fixed.
Comment: Ah, you're indeed correct that experiment should be a random factor. I'll update the answer to reflect this. Thanks!
Answer: I think a way in which you could analyze the two experiments together is by defining a multilevel/hierarchical model. The individuals are nested within each experiment.
The standard for this approach is Gelman's book (I think).
The Journal of Memory and Language had a special issue on analyzing data in 2008 which covered hierarchical models and even some examples in R.
Other's here can probably provide good web-resources as well.
Comment: Baayen's textbook, *Practical Data Analysis for the Language Sciences with R*, may still be found at http://bit.ly/aQ1KGb
Comment: Thanks. I just had it in a kind of unusable Version with "Draft" in the background.


Integrating Ext.ux.touch.Grid with Sencha 2.0

Question: I want to display data in some grid view format in Sencha 2.0.When i hunted for this I found
http://www.mindstick.com/Forum/989/Grid%20view%20data%20format%20in%20Sencha%20touch
Sencha Touch does not provide any grid control or any other control to display data in grid format so you have to use the User Extension.
I want to know the steps for integration of Ext.ux.touch.Grid like where to put these file etc.
Thanks in advance
Answer: Ext.grid.Grid is available since Sencha Touch 2.3.0: Here you can find how to integrate it in your App.
Create a folder packages in your main project folder:

Add the path to Ext.Loader:
//<debug>
Ext.Loader.setPath({
    'Ext': 'touch/src',
    'YourAppNamespace': 'app',
    'Ext.ux': './ux',
    'Ext.grid': 'packages/sencha-touch-grid/src/grid'
});
//</debug>

And then you can extend it in your application:
Ext.define('YourAppNamespace.view.AdvancedGrid', {
    extend: 'Ext.grid.Grid',
    config: {
    // ...
});

Comment: Is it posibble with sencha 2.0
Comment: When i tried to use the grid it throws error "Uncaught TypeError: Cannot read property 'features' of undefined    List.js"
Comment: Hi, when reviewing edits, such as [this post](http://stackoverflow.com/review/suggested-edits/3893214), which does improve the post but does not make any effort to fix other glaringly obvious issues with a post, these should be rejected as "too minor", as it takes up too much reviewer time, and it's also rather stupid to fix only one part and leave another bit still not fixed up. For examples, fixing one minor capitalisation issue while not fixing the others would definitely be "too minor". For more information, see [this meta post](http://meta.stackexchange.com/q/147946). 'Thanks!
Answer: From what I can tell, Ext.grid.Grid is only available if you pay Sencha $4k plus for Sencha Complete or the bundle. It does not come with the 2.x vanilla download...If someone knows otherwise, please post where you find this package, because it is no showing up in my touch src folder. I shart when I saw the $4k price tag...greed will never leave.


Prove that $\dim L(F)+\dim\ker(L)=\dim(F+\ker(L))$ for every subspace $F$ and every linear transformation $L$ of finite dimensional vector space $V$

Question: Prove that $\dim L(F) + \dim \ker(L)=\dim(F+\ker(L))$ for every subspace $F$ and every linear transformation $L$ of finite dimensional vector space $V$.
Any idea would be appreciated.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be put on hold. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Have you already learned the [rank-nullity theorem](https://en.wikipedia.org/wiki/Rank%E2%80%93nullity_theorem)? Because it is an immediate consequence of it.
Comment: I know rank-nullity theorem but i dont know how to use it to solve this problem.
Comment: Please see my answer below.
Answer: Hint
Apply rank-nullity to the linear map induced by $L$ from $F + \ker(L)$ to $L(F)$.
Comment: Thank you very much sir.It`s really helpful.
Answer: Hint:
Consider the short exact sequence
$$0\longrightarrow \ker L\longrightarrow F+\ker L\longrightarrow (F+\ker L)/\ker L\longrightarrow 0 $$
and use the second isomorphism theorem: $\;(F+\ker L)/\ker L\simeq F/(F\cap\ker L)$, and observe that $\;F/(F\cap \ker L)\simeq L(F)$ by the first isomorphism theorem.


Show that $\frac{1}{(n+1)!}(1+\frac{1}{(n+1)}+\frac{1}{(n+1)^2}+\frac{1}{(n+1)^3}+\cdots)=\frac{1}{n!n}$

Question: Show that $\frac{1}{(n+1)!}(1+\frac{1}{(n+1)}+\frac{1}{(n+1)^2}+\frac{1}{(n+1)^3}+\cdots)=\frac{1}{n!n}$, (here $n$ is a natural number)
Maybe easy, but I cannot see it.
Thanks in advance!
Alexander
Comment: What is the sum $1+q+q^2+q^3+\dotsb$ for $\lvert q\rvert < 1$?
Answer: Hint:
$$\sum_{k=0}^\infty \left(\frac1{n+1}\right)^k=\frac1{1-\frac1{n+1}}\ldots$$
Comment: Ok, I can solve it now, thanks!
Answer: Since $$1+x+x^2+\cdots=\frac1{1-x}$$
Therefore,
$$1+\frac1{n+1}+\frac1{(n+1)^2}+\cdots=\frac1{1-\frac1{n+1}}=\frac1{\frac{n+1-1}{n+1}}=\frac{n+1}{n}$$
Now,
$$\frac1{(n+1)!}\cdot(1+\frac1{n+1}+\frac1{(n+1)^2}+\cdots)=\frac1{(n+1)!}\cdot\frac{n+1}{n}=\frac1{n!n}$$


Como passar variável para AJAX?

Question: Tenho uma tela onde listo várias músicas e ao lado tenho uma imagem que chama o AJAX para adicionar essa música numa playlist. Minha dúvida é como passar o ID dessa música para o AJAX, uma vez que não posso usar a URL, pois essa tem que estar com #.
    while($consulta2 = mysql_fetch_array($result2))
    {;
      echo"
$consulta2[nr_faixa].  $consulta2[nm_musica]";
      if ($consulta2["nm_som"] != '') {
        echo "
        ";
      }
    echo "

";
    }

Answer: Acredito que seja o caso de imprimir, a partir do próprio PHP, o código da música no botão de adicionar. Mas antes, só uma coisa que eu reparei: é id ou class, na primeira linha do trecho abaixo?
echo "
      ";

Acredito que você queira trocar para class; mas, de qualquer maneira, isto não está relacionado à sua pergunta. Vamos a ela: a modificação que você teria que fazer seria algo como:
echo "
      <input type='hidden' value='$consulta2[id_musica]' />
      ";

Para ser franco, existem diversas outras maneiras de servir os dados (neste caso, o ID da música no banco de dados) para o lado cliente: atributos de dados (data attributes), se você estiver lidando com HTML5; injeção dos dados em outros elementos que não o <input />; etc.
De qualquer forma, uma vez servidos os dados via PHP, chega a parte do JavaScript de coletá-los -- ou seja, procurá-los no DOM. Dentro do elemento  de cada botão "Adicionar à playlist", existe um <input /> hidden que contém o código da música. Por isso, na função de callback do seu listener de cada botão, deverá haver algo semelhante a isto:
(O HTML teve de ser levemente modificado em relação à marcação acima, mas o código JS serve para ambos os casos)

// Aqui é apenas um exemplo de como adicionar o listener a todos os botões:
var botoes = document.getElementsByClassName("addMusicaPlaylistLink");
for(var i = 0; i < botoes.length; i++) botoes[i].addEventListener("click", function(e){

    // ...

    // Este trecho busca o código da música cujo botão foi clicado:
    var musica_id = e.srcElement.getElementsByTagName("input")[0].value;

    // ...

    // Hora do AJAX! O ID da música estará na variável 'musica_id'!

    // ...

    // O trecho abaixo simplesmente mostra o código capturado, por motivos didáticos:
    var p = document.createElement("p");
    p.innerHTML = "O usuário requisitou que a música " + musica_id + " fosse adicionada à playlist.";
    document.body.appendChild(p);
});

    <input type='hidden' value='1234' />
    Adicionar música 1234

    <input type='hidden' value='1235' />
    Adicionar música 1235

O trecho acima não deve ter problemas para rodar no IE9 e outros mais modernos; se você implementar outro tipo de listener mais compatível, provavelmente este código é capaz de rodar em browsers antiquíssimos :)
Vale notar que este JS está amarrado à minha sugestão em PHP; outros tipos de marcação exigem modificações na procura DOM realizada pelo JavaScript, então não esqueça de hackear este código até conseguir extrair seu ID para o AJAX.
Comment: obrigado! Ali é ID mesmo, ele chama uma função jQuery. Não sabia que tinha como inserir um input hidden em um . Vou testar e qualquer coisa te falo... Abs
Comment: add um alert dentro desse JS só pra ver se realmente estava chamando corretamente, e não aparece nada.. Abs
Comment: Alterei umas coisas e agora ele mostra o primeiro alert "OK", sinal que está entrando, mas o segundo não mostra, sinal que não está recuperando o valor do hidden:  document.getElementById("add-musica-playlist-link").addEventListener("click", function(e){
  alert ('OK');
  var musica_id = e.srcElement.parentElement.getElementsByTagName("input")[0].value;
  alert(musica_id);
 });
Comment: O único problema é que esse código está dentro de um while, ou seja, pode ter mais de 1 input hidden, e nesse caso apenas o primeiro está funcionando. Será que é porque eles tem o mesmo ID? Vlw
Comment: Com certeza é por causa do ID, Ricardo :)

Troca por class, conforme eu chamei atenção no começo da minha resposta, e depois ajusta o JavaScript para buscar por classe (`getElementsByClassName("classeBotaoAdicionar")`) que vai dar certo! Só não esqueça que esse método retorna uma LISTA de elementos encontrados, será necessário iterar e adicionar o listener a cada um!
Comment: Ah, agora entendi, acho que o problema está em tratar essa LISTA, pois tanto ID ou CLASS só muda o tipo da busca, a resposta é a mesma, certo?
Comment: Peço desculpas, Ricardo, pela mancada: na verdade havia mesmo um erro, que não ficou evidente no teste que eu fiz porque só havia um único elemento com *listener*. Estava sobrando um `parentElement` dentro da função de `callback`. Aproveitei e reescrevi o trecho para funcionar com `class` ao invés de `id`. Espero que ajude! Abraços!
Comment: mudei pra CLASS, fiz exatamente como você reescreveu, ele trás o botoes.length = 3, mas simplesmente não entra no FOR.. Abraços
Comment: Talvez o `i` esteja sendo usado no meio do listener, para outra finalidade, e assim atrapalhando o loop... Ou realmente não entra? Já experimentou fazer `for(var i = 0; i < botoes.length; i++) console.log(botoes[i]);` pra testar?
Comment: Pior que não estou usando o i. Testei: for(var i = 0; i < botoes.length; i++) alert(i); e ele deu 0 1 2, certinho...
Comment: Experimenta com o console.log, que não interfere no fluxo do programa, e passando o mouse em cima dos elementos printados (pelo menos no Chrome) você consegue ver se selecionou os caras certos :D
Mas, de qualquer forma, o exemplo agora funciona e está mais próximo do seu caso... Se for necessário, abra outra pergunta com este novo problema, beleza? :)
Comment: Valeu! Vou postar uma nova pergunta... Abs e Obrigado

Como passar variável para AJAX?


Difference-in-difference and panel data models

Question: I understand that according to the observations you have (two independent cross-sections in two or more time periods or the same individuals observed in two different periods), then difference-in-difference (DiD) models are employed by estimating, respectively, ordinary least squares (OLS) or a fixed-effects model.
My question is: in the second case, does it make sense to estimate a DiD model using a random-effects model?
Answer:
I understand that according to the observations you have (two independent cross-sections in two or more time periods or the same individuals observed in two different periods), then difference-in-difference (DiD) models are employed by estimating, respectively, ordinary least squares (OLS) or a fixed-effects model.

You can use ordinary least squares (OLS) in both cases. In settings where you observe the same entities over multiple time periods, a fixed effects model is still estimated via OLS. Put differently, we simply employ the OLS estimator on the time demeaned data.

My question is: in the second case, does it make sense to estimate a DiD model using a random-effects model?

I depends upon your research goals. But, in general, no.
A difference-in-differences model is, by design, a within model. In the simple setting involving two groups (i.e., treatment group versus control group) and two discrete time periods (i.e., before treatment versus after treatment), you're restricting attention to the within-group time variation in the outcomes.
If you want to proceed by treating your panel level effects as random, then be mindful you're estimating two different models. Under random effects, your estimand of interest is obtained by averaging the within and between-unit effects. As a consequence, you may now obtain estimates on certain time-constant covariates; they may be of substantive interest.
In practice, however, we worry the selection of units into a treatment or control condition is based upon some of these time-constant attributes. The choice of which units receive some intervention is often not under the control of the unit of observation. Employing DiD methods will help you overcome some of these selection concerns. This is why DiD is very popular in the evaluation of experimental programs aimed at aggregate level units.


What is the true impact of Panels Everywhere on theming and layout duties?

Question: From an answer on another question:

If you have chosen Precision because it is minimalist, then you might
  want to consider adding the 'Panels Everywhere' module. This module
  works very well with Panels (same authors) and allows you to bypass
  the Drupal Theming process altogether. This greatly simplified my
  styling work.

Does this mean regions and blocks are completely ignored with Panels Everywhere (PE) in favor of panels only?
If so, does it mean one has to recreate some layout for standard pages such as node edition and publishing for example? I have an editor user profile to create specific content. Do I loose all the layout of existing Drupal screens the user could access?
After enabling PE, what configuration is expected regarding layout and theming (CSS) on standard pages delivered by Drupal?

Fact is, when trying PE with the Precision theme, I lost layout on all standard pages, but I want to know if this is a configuration issue or not.
Answer: From my own findings:

Yes. In fact, one can set a site template which (more or less) replaces the concept of regions.
No, one should set a site template and not forget to have a Page Content pane.
None, except for the site template itself. Eventually, some can be set on the Page Content too.


How to handle unpredictable and unwanted pop up appears in selenium webdriver even t is not expected behavior

Question: In our application we are getting pop up some times but it is not expected behavior, once this pop up displayed remaining scripts will get fail as focus is on pop up. So can you please guide me to resolve this issue
Comment: You should raise a bug in the product you're testing, and work on a clean branch, not try to work around the problem in your tests. That just complicates your tests, and conceals the problem rather than helping it get fixed.
Answer: If it is happening in the same place a lot you can deal with it like this...
public boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } // try
    catch (Exception e) {
        return false;
    } // catch
}

Now, you can check whether alert is present or not by using the method written above as below:
if (isAlertPresent()) {
    driver.switchTo().alert();
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();
}

I wouldn't put this everywhere though because it will really slow down the tests.
Answer: What you need to do is -
Create a function that will be used to access any element for ex-
getButton("xpath of your desired xpath").click();

getButton(String Xpath){
if(driver.findElement(By.xpath()).isVisible)
return driver.findElement(By.xpath())
else{
if (isAlertPresent()) {
    driver.switchTo().alert();
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();
}
return driver.findElement(By.xpath())
}

}

MAke sure you always make call to this function to access any element from UI .


Passing On Values Between Functions

Question: Hi i'm working on a program where a user selects an image, then it gets turned into an ASCII version of the picture, which displays in both the console and then gets saved to a notepad .txt file. The code below currently does this but I think the way I am using my returns in the functions is messing up the code. Instead of asking for the image and background colour once, it asks for it 3 times before actually drawing out the ASCII image. Then after it has drawn it, it again asks for a 4th time for the image and background colour, before finally asking for the name to give the .txt file then creating the text file.
How do I change this so that it only asks each question once without repeating itself(and what exactly is this happening?). Thanks
def inputs():
    image = input('What image file?')

    return (image)

def pictureConvert():

    a = inputs()
    # codefollows

Comment: You just wasted everyone's time with this question. -_-
Comment: Sorry I should of just made a small scale but similar example doing the some core problem. Thanks for the help though.
Answer: Call the inputs function only once, and store that everywhere. This ensures that the user will be asked for input only once:
def inputs():
    image = input('What image file?')

    return (image)

def pictureConvert():

    a = inputs()
    # codefollows

Passing On Values Between Functions