single measure of a fixed factor for each level of a random effect

Question: I have a population animals, and am looking at the effect of (yearly) environmental temperature on date of birth and litter size. Births in the population have been monitored for 15 years (one litter per year), consequently, many females have been repeatedly observed giving birth over this time. Environmental temperature is the same for all animals within each year.
I am currently modelling this as a linear mixed model, with yearly temperature as a fixed effect and maternal ID as a random effect, to account for repeated measures of mothers.
A reviewer has recommended that I fit the model with Year as a random effect as well. However, because only a single yearly temperature applies to all mothers within each year, this drastically changes the results. - Essentially, the random effect of year soaks up all the variation due to temperature, rendering the effect of temperature nonsignificant. For temperature to not have an effect would be VERY surprising since experiments manipulating temperature directly show a strong effect.
What is the best way to proceed?
Thanks,
summary of LMM without Year as a random effect:
     AIC      BIC   logLik deviance df.resid
 10378.6  10399.7  -5185.3  10370.6     1419

Scaled residuals:
     Min       1Q   Median       3Q      Max

-2.35860 -0.60767 -0.02228  0.57020  3.08272

Random effects:

 Groups   Name        Variance Std.Dev.

 TrueID   (Intercept) 39.22    6.262

 Residual             58.43    7.644

Number of obs: 1423, groups:  TrueID, 679

Fixed effects:
             Estimate Std. Error        df t value Pr(>|t|)

(Intercept)   36.3515     0.3320  582.1000 109.476  < 2e-16

CritTemp.c    -3.0817     0.3757 1238.7000  -8.203 4.44e-16

Correlation of Fixed Effects:

           (Intr)

CritTemp.c 0.010

summary of LMM with Year as a random effect:
     AIC      BIC   logLik deviance df.resid

  9819.7   9846.0  -4904.8   9809.7     1418

Scaled residuals:

    Min      1Q  Median      3Q     Max

-3.2943 -0.4964  0.0186  0.4700  3.4843

Random effects:

 Groups   Name        Variance Std.Dev.

 TrueID   (Intercept) 39.16    6.258

 Year     (Intercept) 27.80    5.273

 Residual             31.73    5.633

Number of obs: 1423, groups:  TrueID, 679; Year, 16

Fixed effects:

            Estimate Std. Error     df t value Pr(>|t|)

(Intercept)   36.550      1.358 16.900  26.917 2.66e-15

CritTemp.c    -2.757      1.976 16.145  -1.395    0.182
---

Correlation of Fixed Effects:

           (Intr)

CritTemp.c -0.095

Comment: Please include the `summary(model)` output for both models (with and without `year` as a random effect)
Comment: @Robert Long Have added model results
Comment: Are the variables critTemp and year highly correlated? The second model tells you that after you accoutn for the variation of the years, the temperture becomes non-significant, since year explains all that temp explained before.
Comment: Are you sure that the reviewer wanted random intercepts for `Year` and not random slopes ? Random slopes might make more sense - but you should code the `Year` variable as numeric, not a factor.
Comment: @Robert Long    Year is coded as a factor because I am controlling for repeat measures within years, not the effect of time per se. I'm pretty sure the reviewer only wanted random intercepts. Nevertheless, running with year as numeric and with random slopes still results in NS effect of temperature.
Comment: @user2974951 Year is a factor but, only one temperature is recorded for all individuals within each year. It doesn't surprise me, therefore, that after accouting for the variation of years, the temperature becomes non-significant, since, within years, all individuals have the same temperature.
Answer: As fleshed out in the comments, if you don't expect any overall effect for Yearand you are not interested in the individual Year estimates, then indeed  random intercepts are a better model. In this case you can talk about the variance expained by each level. One major benefit is the greater degrees of freedom in the random intercepts model. Do check the residuals at all levels and do the usual fit tests.
Oh and you can always report the results for both models.
Comment: @ElectricMonk if my answer answers your question, please can you mark it as accepted. If not, do you have a further related query ?
Comment: Thanks, but how should I interpret the output? As I say above, theory, other analyses, and experimental work all point to temperature having a significant effect on date of birth (these are reptiles). Including Year as a random effect causes Temperature to appear non-significant because all the variation due to Temperature is sucked up by Year. Is it appropriate (as the reviewer has suggested) to include a random effect for Year when the fixed effect has a common value for all records in that Year?
Comment: You can interpret the random intercepts model in terms of variance partitioning, and you can report the fixed effects model in terms of individual estimates. The 2 models are complementary. In general, with clustered observations, where the only requirement is to control for correlations within clusters, then both fixed effects, or random intercepts will do that. For the random intercepts model, it doesn't make much sense to also include `Year` as a fixed effect - it is either one or the other.
Answer: I'm sure this was resolved a while back, but I just posted a very similar question here and wanted to share what I found.
I recommend checking out the link, but to summarize briefly: As best as I can tell, if you fail to include a random effect of year, the model will wrongly assume that every row represents an independent temperature measurement, that is, it will think you have a larger sample size than you actually do. This will result in underestimation of standard error for your temperature fixed effect, and inflate your significance. My understanding is that if there is a true, strong effect of temperature, it should remain significant even as you add the random effect of year.
There are some alternative methods you can use, though, if you want to double check. Those are, again, given in the answer to my post linked above.


Relationship between a function's limits at infinity and its derivative's ones

Question: Doing some exercise on continuity and differentiability I was wondering if there is some connection between a function's limits at $\pm \infty$ and the limit of its derivative? To be more formal suppose we have a real valued continue and differentiable $n$ times function $f$. We know the limits of the function at $\pm \infty$, can we say something about the limits at $\pm \infty$ of its derivative $f'$ in the following cases:
1) The limit is finite say $l \in \mathbb R$;
2) The limit is infinite (I guess the sign doesn't matter in this case);
3) We additionally know that a function is convex/concave and we are in one of the 2 cases already mentioned.
Any example/counterexample or source is greatly appreciated.
Answer: Let $g(x)=(1-x^2)^2$ if $x\in[-1,1]$ and $0$ for $|x|>1$. Show that $g(x)$ is differentiable and, in fact, the derivative is continuous. $g(x)$ can be seen as a differentiable "bump" that starts rising at $x=-1$, reaching a peak value of $1$ at $x=0$, and returning to $0$ at $x=1$.
Now, define $f(x)$ as:
$$f(x)=\sum_{k=1}^{\infty} \frac{1}{k}g(k^2(x-k))$$
$f(x)$ can be seen as a function which is mostly zero except with bumps with a maximum of $1/k$ in the intervals $(k-1/k^2,k+1/k^2)$, where $k$ is a positive integer.
Claim: $\lim_{x\to\infty} f(x) = 0$ and $\lim_{x\to\infty} f'(x)$ does not exist.
Proof: Now, $f(k)=\frac{1}{k}$ for all positive integers $k$, and if $x>k$, then $0\leq g(x)<\frac{1}{k}$. This shows that $f(x)\to 0$ as $x\to\infty$.
Also $f(k-1/k^2)=0$. By the mean value theorem, this means that for some $c\in (k-1/k^2,k)$, $f'(c)=\frac{f(k)-f(k-1/k^2)}{1/k^2} = k$. This shows that $f'(x)$ does not converge to zero. In fact, it is not even bounded.
However, if $f(x)$ converges to a finite value, and $f'(x)$ converges at all, then $f'(x)$ converges to zero. You can prove this again with the mean value theorem. See the proof later in the answer.
If $f(x)$ is concave or convex, then $f'(x)$ is monotonic. That means that if $f'(x)$ does not converge to any value, then for some $N$, we have $f'(x)>1$ for all $x> N$ or $f'(x)<-1$ for all $x>N$. This is easily shown to not be possible if $f(x)\to L$, since it would mean that $|f(x+1)-f(x)|>1$ for $x>N$.
This means that $f'(x)$ converges, and thus it must converge to $0$.

Originally, I wrote that it was true if $f(x)$ was monotonic, but I don't think that's so.
If we define $h(x)=\sum_{k=1}^{\infty} g(k^3(x-k))$ and $f(x)=\int_0^x h(t)\,dt$ then $f'(x)=h(x)$ does not converge to zero, but $f(x)$ is monotonically increasing, and $f(x)$ is bounded by $2\sum_k \frac{1}{k^2}$, so $f(x)$ converge, but $f'(x)$ does not converge.
We could even make $h(x)$ unbounded by making it $h(x)=\sum_{k=1}^{\infty} kg(k^4(x-k))$.
If you want a counterexample with $f$ strictly increasing, use $1-e^{-x} + \int_{0}^x h(t)\,dt$.

One last thing I didn't prove: If $f'(x)$ and $f(x)$ both converge to finite values, then $f'(x)$ converges to $0$.
The key is the result:

Lemma: If $f$ is differentiable and $\lim_{x\to\infty} f(x)=L$, then $\liminf_{x\to\infty} |f'(x)|=0$.

Proof:
This follows from the mean value theorem.
Since $f(x)\to L$, here is an $N$ so that for $x>N$, $|f(x)-L|<1/2$. Thus, for $x>N$, and any $D>0$, $|f(x+D)-f(x)|<1$.
Now, given any $\epsilon>0$ and any $M$ pick $x>\max(M,N)$ and set $D=\frac{1}{\epsilon}$.
By the mean value theorem, there must be a $c\in[x,x+D]$ such that $$f'(c)=\frac{f(x+D)-f(x)}{D}=\epsilon(f(x+1/\epsilon)-f(x))$$ and thus $|f'(c)|<\epsilon$.
So $\liminf_{x\to\infty} |f'(x)|=0$.
Corollary:

If $f(x)$ and $f'(x)$ converge to finite values as $x\to\infty$, then $\lim_{x\to\infty} f'(x)=0$.

Proof: Since $\lim_{x\to\infty} |f'(x)|=|\lim_{x\to\infty} f'(x)|$, and $\liminf |f'(x)|=\lim |f'(x)|$ when the right hand exists, you have the result.

Finally, if $f(x)\to\infty$ you can get any values for $\alpha=\liminf |f'(x)|$. For example, $f(x)=\alpha x$ for $\alpha\neq 0$ give $f'(x)=\alpha$. $$f(x)=\begin{cases}\log x&x\geq1\\
x-1&x<1\end{cases}$$
has $f(x)\to\infty$ as $x\to\infty$ but $f'(x)\to 0$.
For concave $f$, you always have $\lim f'(x)$ in $[-\infty,\infty]$, but without concavity, you can get any values $\alpha\leq\beta$ for $\alpha=\liminf f'(x)$ and $\limsup f'(x)$.
Comment: I hope I don't face such functions in the future.
Comment: Yeah, analysis counterexamples are really unpleasant.
Comment: What else can I say? Thank you a lot! Very interesting answer, helped me clear my mind a lot!
Answer: Generally, no.

$\sin(x^2)/x$
$x + \sin(x)$

The graphs of these make this obvious.
Answer: $1)$ consider a sine function with decreasing amplitude and increasing frequency. Also $arc tan x $. So nothing can be said accurately about limit of derivative.
$2)$ consider $x^x$, and identity function. Again nothing can be said about limit of derivative.
I have no idea about third case.


Migrating on an AWS Instance

Question: I am given the task of migrating a Drupal 7 site to Drupal 9. I have been given a "mirror" site/exact copy that is being held on an AWS instance. Because the mirror site is up and running, I am assuming a LAMP stack has been installed. Could someone briefly outline how to install D9 onto this instance and migrate content over from D7 to D9? So far I have:
-updated the LAMP stack to make sure it's fully up to date.
-Downloaded D9 through Terminal in a separate folder away from the current D7 files.
-Create a new database in MariaDB.
I am following this tutorial: https://www.drupal.org/docs/installing-drupal
Step 4 has me stuck; do I need to do this since the instanced is fully up and functioning as it's a mirror copy?
Thanks for your help in advance!
Comment: Migrating a D7 to D9 is a very complex task that can't be answered here. You have to make a lot of changes and is heavy dependant of the modules and data you have.
Comment: That's a super broad request. I recommend you get a copy of the D7 site running on your local machine. Then install a fresh D9 (or D8) site. And then gamble around as much as you want on your local machine always having a backup of the D7 database at backhand.
Answer: To answer your specific question on the tutorial: if your Drupal 7 site is functioning, you don't need to do step 4 anymore. PHP is functioning.
You may proceed with step 5.
Indeed you will need to investigate what modules you use in the Drupal7 site and look if these have been ported to D9, or if there are interchangeable modules. Perhaps it's better to go for D8 first if you get stuck finding the appropriate modules and you're not able to make them yourself.

Migrating on an AWS Instance


certain drupal modules not working

Question: I've installed drupal several times and I'm still having the same problem. Some modules aren't working.
E.g:
Admin menu - They don't always appear. It only shows in random moments.
Wysiwyg and CKeditor - is not visible when I'm creating the content.
These are the modules I have installed and I'm using Marinelli theme:

admin menu
Wysiwyg
IMCE Wysiwyg bridge
IMCE - this is for images
IMCE Mkdir
Pathauto
Chaos tools
insert
Mega menu
Comment: just to confirm, did you set the editor for any of the Input format such as Filtered HTML and Full HTML in Administer >> Site Configuration >> Wysiwyg Profiles (admin/settings/wysiwyg/)?
Comment: The modules you mention all need JavaScript to work. Check in your browser if you have JavaScript errors.
Answer: You might have a JQuery version conflict. Do you have the JQuery Update module? Or did you include some script not compatible with Drupal's version of JQuery?
Comment: No I dont have the JQuery update module. Should I install it? and forgive me but I'm just a newbie but I really like this cms.
Comment: Yeah, try that module and see if your problem is solved. That's usually the first thing I install.

certain drupal modules not working


How do I print a view table?

Question: I am using Drupal 7 with the Print module installed.
I used this module to print nodes, but how can I print a view table?
Is there a module that I can use?
Comment: possible duplicate of [Printing views table](http://drupal.stackexchange.com/questions/27283/printing-views-table)
Answer: Most people just use a stylesheet to exclude layout for printing. it does not rely on any particular module.
The idea is simple, you include a stylesheet in your theme which removes the layout from your site, typically by using style:display:none; etc. You also size the font and remove images where possible to save ink.
You can read a really good tutorial here: http://www.alistapart.com/articles/goingtoprint/
Answer: If you're familiar with the Print module, you could simply embed the view you're displaying into a normal node and use Print to print the page. I didn't try this but I see no reason it wouldn't work.
In your node's tpl.php, do something like this :
print views_embed_view('your_view', 'the_display_you_want');

How do I print a view table?


Immutable state update. Update an array of objects in Redux

Question: I have a state of type array that initially looks like that:
const initialState = {
    spots: []
}

On the first update it gets filled with objects and looks like that:
state.spots = [
    { id: '1', available: 1, path: 'xxx' },
    { id: '2', available: 1, path: 'xxz' },
    { id: '3', available: 1, path: 'xxy' },
    { id: '4', available: 1, path: 'bxy' },
    { id: '5', available: 1, path: 'vxy' },
    { id: '6', available: 1, path: 'fxy' }
]

On all subsequent updates we get all the spots with keys of 'id' and 'available' but not the path.
So the payload looks like this:
payload = [
    { id: '1', available: 1 },
    { id: '2', available: 0 },
    { id: '3', available: 0 },
    { id: '4', available: 1 },
    { id: '5', available: 0 },
    { id: '6', available: 1 }
]

I'm trying to figure out the immutable ES6 pattern to update the state but I cannot seem to get it right.
EDIT:
Best solution I have found so far is the following:
state.spots = state.spots.map( (spot, key) => {
  let new_spot = payload.find(o => o.id === spot.id);
  return { ...spot, ...new_spot }
})

What is the most efficient way to properly update all objects of the array "spots" with the new payload.
Hope it is clear.
Thanks
Comment: Seems like it would be easier if the payload and state were objects with id as key and the rest as value. Is that an option?
Answer: CodeSandbox

You can create a hash map of your payload using each spot's id as the key:
const payload = [
    { id: '1', available: 1 },
    { id: '2', available: 0 },
    { id: '3', available: 0 },
    { id: '4', available: 1 },
    { id: '5', available: 0 },
    { id: '6', available: 1 }
]

// You can adjust the map to how you like.

const map = payload.reduce((acc, entry) => {
    acc[entry.id] = entry
    return acc
}, {})

and then update state.spots in your reducer:
return {
    ...state,

    spots: state.spots.map(e => {
        if (map[e.id]) return { ...e, ...map[e.id] };
        return e;
    })
};


How to add a tabbed menu on group main page (panel)?

Question: I managed to get panels working with og 7.x-2.1 following:
- http://modulesunraveled.com/organic-groups/part-3-organic-groups-layout
- http://www.initsix.co.uk/organic-groups-panels-and-views-drupal-7
Now I'd like to add a tabbed menu on the "main og content", where I mainly divide by content-type (documents, agenda, forum, news..).
I tried to follow http://www.austinprogressivecalendar.com/blog/creating-drupal-panels-tabs in order to create tabs, where each tab is a panel.
However I don't know how to eventually add what would be my (sub) panel to the main content of the group page, and more in general I wander if there is a less cumber stone way to implement it.
Answer: I got a working and straight solution (tabs are panel style) using panels_tabs.
panels_ajax_tab seems more nice (and more clean from a designer point-of-view), but it is also more cumbersome as it only accepts mini-panels as tab elements, and then I'm not sure how to pass the group information down from the main panel to the mini-panel and finally the embedded view panel.
Further panels_tab load all the page at once and then just hide the unused tabs, so if too many views are loaded the page can take pretty much long time to load !


Rails, separate search function within rails form

Question: I want to embed a search function within a form so a user can search for and select products to submit along with a date range to show availability. I am not sure the best way to do this without submitting all the parameters and trying to handle it in the controller. I am sure there is a rails solution for something like this.
Here is a gist of what I am trying to achieve
<code>=simple_form_for [:admin,availability_inspector] do |f|
    = f.text_field :start, type: :text, placeholder: "click to use the date-time picker", class: "form-control auto_picker"
    = f.text_field :finish, type: :text, placeholder: "click to use the date-time picker", class: "form-control auto_picker"
      Stock List Search
      =form_tag new_admin_availability_inspector_path, method: :get do
        =search_field_tag :querystr, params[:querystr], placeholder: "filter", class: "form-control"
        %span.input-group-btn
        =submit_tag "filter", name: nil, class: "btn btn-primary"
  -if @products.any?
    %ul.list-group
      - @products.each do |product|
        = product.title
          = check_box_tag :product_id, product.id

=f.submit "filter", name: nil, class: "btn btn-primary"
</code>
So the idea is, the items searched and listed, the user selects the items, and, with the date field range, the form is submitted.
Comment: I understand your problem. Please confirm if you wanted the following thing resolution to be achieved?
1. When dates are changed, your product list will be updated?
Comment: Hi, thanks for your reply. No, I just need to select products through a search. Selected products are then passed to the form to be searched with the dates. Does this help?
Answer: Add a hidden array field in the form called products. outside the form handle products search,selection and update of that hidden field via Ajax call.
Check this link, Its a similar but simpler example cause he just want to add addresses dynamically while you still have the products searching handled via Ajax first. Please note that the only part you need from his solution is how he updates the form with new fields via JavaScript the rest of details are not relevant.
Comment: can you demonstrate this please?
Comment: You can try this [link](http://archive.railsforum.com/viewtopic.php?id=1129) it is simpler cause he just want to add addresses dynamically while you still have the products searching handled via Ajax first if it does not help I will demo more when near keyboard.
Comment: which link? I dont think you posted it?
Comment: just to be clear the only part you need from his solution is how he updates the form with new fields via javascript the rest of details are not relevant.
Comment: could you mould this into an answer above please? then the green tick is yours ;)
Comment: You mean you are having an issue with the concept or the implementation? ie: you want further explanation or your code isn't working ?
Comment: Hi Peter, the above answer didn't provide much. I was hoping for an gist of sorts or something. Apologies, but this is unchartered territory so I'll require spoon feeding!
Comment: ok will try to provide an example, you want the form to pass the products parameter as a array products[] or something else ?
Comment: ie: what's the relation type between this form and the products.


Proper definition of set between two functions

Question: I have a parameter $\delta \in (0,1)$.
The parameter is further restricted from below and above by the functions $\underline \delta : (0,\ln(4)] \to (0,1)$ and $\overline \delta : (0,\ln(4)] \to (0,1)$ respectively where
\begin{align}
&\underline \delta(r) = \sup\left\{0,1 - \frac{\ln(2)}{r}\right\},\\[2mm]
&\overline \delta(r) = 1 + \frac{\ln(3) - \ln(2+e^r)}{r}.
\end{align}
I want to define the set $A$ that captures all point $(r,\delta)$ such that $r \in (0,\ln(4)]$ and $\delta \in [\underline \delta(r), \overline \delta(r)]$. Is the following definition correct?
\begin{align}
(r,\delta) \in (0,\ln(4)] \times \left\{\delta \in [\underline \delta(r), \overline \delta(r)] \mid r \in (0,\ln(4)] \right\} =: A.
\end{align}
I'm a bit confused, because $r$ and $\delta$ turn up at the left and right hand side of $\in$
Comment: Your definition is confusingly incorrect, because the set after the $\times$ depends on $r.$ Instead, you can define $A$ as in William Elliot's answer, or else as $$A=\bigcup_{r\in(0,\ln 4]}(\{r\}\times[\delta(r),\overline\delta(r)])$$
Comment: By the way, since the set after $\sup$ has only two elements, wouldn't it be more natural to write $\max$ instead of $\sup$?
Answer: A = { $(r,\delta) : r \in (0,\ln(4)], \delta \in [\underline \delta(r), \overline \delta(r)]$ }.


Convergence of a sequence implies convergence of the norm of the sequence

Question:
If $\langle X_n \rangle$ is a sequence in $\mathbb R^n$ then $\lim\limits_{n\to \infty}X_n=A$. Show that $\lim\limits_{n\to \infty} \| X_n \| = \| A \|$ .

My thought process, $\| X_i \|= (\sum_{i=1}^n x_i^2)^{(1/2)}$ therefore be the multiplicative property of limits $x_i^2 = a_i^2$. Therefore the limit of norm of the components is equivalent to the limit of the corresponding limit of each component of the sequence.
Comment: your thought process is correct. The proof relies on the fact that element wise convergence iff convergence and the fact that norm is a continuous function of the components.
Answer: If $x_n \to a$, then by definition $\|x_n - a\| \to 0$.  But we have the subtriangle inequality, so for every $n$ $|\|x_n \| - \|a\| | \le \|x_n - a\|$.  The result now follows by the squeeze theorem.
Comment: I've always seen this referred to as *the reverse triangle inequality.* In any event, +1.
Comment: Ahhh,so clever.
Comment: Why do you need to reference the Squeeze Theorem? Couldn't you argue that $|\|x_n \| - \|a\| | \le \|x_n - a\|$ < $\epsilon$ and then conclude the proof?


How do I dynamically include ouput from an external file?

Question: How do I dynamically include output from another web page?
This is the result of a CGI link along the lines of: http://www.example.com/name.cgi?Arg=argument  I would like to include everything within the html tags that it generates as HTML on my page.
(I own both web pages!)
Comment: This really sounds like a job for PHP's `file_get_contents()` (http://www.php.net/file_get_contents)
Comment: If that doesn't work, ``s come to mind.
Comment: use drupal_http_request(). Here is the link to documentation - https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/7
Answer: There are a couple of modules that can help with this:
Web widgets (http://drupal.org/project/web_widgets): Embed any other web site content in a widget with a simple widget API.
Iframe_filter (http://drupal.org/project/iframe_filter): you just need to add this filter to an input format and the content you create using that format will be displayed inside an iframe created dynamically.
And other iframe projects: http://drupal.org/project/insertFrame, http://drupal.org/project/iframe_page (only dev version available right now for d7).


Cannot match pattern for wordpress empty paragraph tag

Question: For some reason wordpress randomly inserts "blank" paragraph tags on my page. I'm finding it difficult to match the tag.. It seems like it's not completly empty but some weird character I cannot see, it's not there in the source code but generated by javascript so it's very hard to figure out what it is!!
My JS file is loaded last in .
I'm new to regex in javascript..
it looks like this in firebug (not sure if there is a small space/tab/something or not)

My javascript to remove it:
jQuery(window).load(function() {
    var page = jQuery('body').html();
    page.replace('/\
\S*\<\/p\>/', '');
    jQuery('body').html(page);
});

Comment: **What?!** You shouldn't run regex on html, especially in javascript which already has deserialization (converting html code to dom elements) functionality.
Comment: Well, you shouldn't use regex to _parse_ HTML, which is not really something that he's trying to do with a basic text replacement. The solution posted by `ShankarSangoli` is the best one anyway, and doesn't use regex.
Answer: Use jQuery empty selector instead which select all elements that have no children (including text nodes). Try this.
jQuery(window).load(function() {
    jQuery('body').find('p:empty').remove();
});

Comment: Despite me posting a regex solution, this is a much better idea. Upvoting.
Comment: Thanks! I just noticed though that it seems you can't use both jQuery(window).load AND jQuery(document).ready , why is this? Is there a workaround? I don't actually need to right now but it would be good to know for the future!
Answer: You know the exact string, so what's the matter with just matching just that?
page.replace('/\
\<\/p\>/','');

Comment: Sometimes you have characters that have no visible representation or that cannot be displayed in the current environment, I tried str.replace first which failed so I assumed this..


How to close comments with just 1 click?

Question: My site editors want a quick way to close comments on a particular node, i.e. they just want to click a button on an item, rather than having to click edit, then select the comment settings tab, then click the "closed" box.  (This is for Advanced forum, but I guess it could apply anywhere).
I have a feeling this should be fairly easy to do but I can't work out how to do it. Any pointers you can give would be appreciated. (I am using the Flag module and thought flag actions would be a simple way to do this, but closing comments doesn't seem to be an available action).
Answer: You can achieve this by following steps given below:

Create a flag on nodes for administrator only
Add new rule using Rules module
Set React on in Event "A node has been flagged, under
Add action "Set a data value"
Select Data "flagged-node:comment"
Click Continue and set value as 0

Please check Rule given below(exported):
<code>{ "rules_disable_comments" : {
    "LABEL" : "Disable comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_disable_comments" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:comment" ], "value" : "0" } },
      { "drupal_message" : { "message" : "Comments closed" } }
    ]
  }
}
</code>
& Flag given below(exported):
<code>$flags = array();
// Exported flag: "Disable comments".
$flags['disable_comments'] = array (
  'entity_type' => 'node',
  'title' => 'Disable comments',
  'global' => '0',
  'types' =>
  array (
    0 => 'article',
  ),
  'flag_short' => 'Disable comments',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Enable comments',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => 'Disabled comments',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;
</code>


How do I learn to sight-read standard notation chords when I'm playing guitar?

Question: I can sight-read melodies in standard notation on the guitar. Slowly, but I can do it.
I can also sight-read chords in standard notation on the keyboard.  Pretty quickly, in fact.
How do I learn to sight-read chords in standard notation on the guitar in the same voicing as notated?
Comment: How did you learn to sight-read chords on the keyboard? I expect it would be a very similar process of patient practice.
Comment: Sounds like you have the knowledge, you just need practice.  You know know where the notes are on the fretboard and on the score.  The classical study guides mainly say, take your time.  Familiarity comes with practice.
Comment: A keyboard is easy for sight reading as each note has only one position on the keyboard which is arranged in a one dimensional manner.  A guitar is more difficult as each note can have five different positions and the notes are arranged in a two dimensional grid.  Moreover, some chord voicings are unplayable in some positions. Single note lines can be sight read by finding the "sweet spot" on the guitar.
Comment: Check out the A Modern Method for Guitar series from Berklee press. It is focused on sight reading (no tabs) and contain a lot of exercises. Just got my complete volume, so I haven't worked a lot with it, but it looks promising.
Comment: As with the other comments, knowing where your application of knowledge is breaking down will help. For example if you read a chord on a staff as a Cmaj7, is it that you don't know that Cmaj7 is a C,E,G and B? or is it that you don't know where those notes are on the neck? or maybe you just aren't sure which combination of CEGB to grab on the neck? I had/have similar issues and might be able to offer my personal insight!
Answer: I think that memorizing fingerings is very important in playing guitar.
However, for strictly sight-reading music in standard notation, memorizing fingerings can only get you so far.
Obviously if you recognize an open E major voicing written in sheet music, you will know exactly how to play that without looking at every individual note. However, in the real world notated music will typically deviate from standard open chords. Otherwise the composer would give you a chord figure.
Since you have stated that you can read chords fairly quickly on piano, I can assume that you understand the pitches, and simply the frets of the guitar are what give you issues.
I wish there was a secret technique that makes you immediately better at sight-reading, but there really isn't. Similar to just about every aspect of music, practice makes perfect. The more music you are exposed to, the more familiar the shapes will look to you. Then you will have an easier time finding how to voice the chords on the fly.
I can offer a few tips that help me when I read music for guitar:

Prioritize rhythm over pitch accuracy
Memorize the pitches of a few frets on each string (eventually you should have the pitches of all frets memorized)
Look ahead for notes/phrases that you can correct yourself on if you ever get lost
Be confident! Nothing helps sight-reading more than confidence in yourself
Answer: Playing chords on a guitar is different that playing chords on piano because of the way the notes are laid out on the fret board.  Every chord can be played in multiple ways (called voicings) in multiple positions.  But most beginning guitar students start by learning the simple open position or first position chords.  Also, on guitar you can't just move a shape higher up the keyboard to go from say a Cmaj chord to an Fmaj chord.  The fingerings on guitar between those two chords in open or first position are completely different (same applies to most open position chords on guitar).
I learned to "sight read" chords by learning to play songs that were of interest to me.  I started with mostly three or four chord songs.  To learn to play the songs, I had to learn to play the chords in the voicing most appropriate for the particular song (or the suggested voicing on the sheet music).  As a beginning guitarist, I started out learning the easiest to play open position chords.
So if the song I wanted to learn had a G, G7, C and D chord in it, I memorized the fingering for those four chords.  Now I could sight read any music that contained those same chords.  Later maybe I came across a song that had those chords but also an Em chord.  So I learned how to finger a basic Em chord and it stuck in my memory as I continued to play the new song.
It's just a building process of memorizing the fingerings for the various chords, a few at a time, and them applying that knowledge by playing songs using the chords.  Kind of like using a new vocabulary word in a sentence helps you remember the word.
So I recommend just learning to play some songs you like - in keys that contain chords that are easy for you to play on guitar, and play those songs often enough to memorize all the fingerings for the chords used in that song.  Later you can add variations of those chords and memorize them - one at a time.
Many guitar lead sheets or sheet music publications show the chord diagrams on the sheet music itself so it's easy to refer back to as you learn the song.  If you are learning a new song from music that does not have chord charts, you could print the chords you need and have them handy for reference as you learn the chords.
You might want to download a chord chart such as the one on this site (click the link and then download the free e-book called "ultimate guitar chords e-book")
Guitar Chords E-Book
Then if you are learning a new song and it contains a chord you have not learned yet, you can look up the various fingerings for that particular chord and find the one that sounds best that you can actually play without too much difficulty.
If you mean sight read chords by the notes on the staff with no chord letters above the staff, some of the same principals apply.  If you know the chords by sight for keyboard, it's just a matter of memorizing the chord fingerings for guitar.  Based on your keyboard chord knowledge, you should be able to recognize a G major chord from the notes on the staff. So you just need to memorize the fingering on guitar for the G major chord (whichever voicing you choose).  As part of the learning (memorization) process, you might just write the chord names above the chords and copy and paste the chord diagrams you will need into a document and print it out as a cheat sheet until you memorize all the chords used in a particular song you want to learn to play on guitar.  Start with a simple three chord song and then build from there.
Hope this helps.  Good luck!
Answer: You are on the right track to sight reading chords as you can already sight read melodies and sight-read chords on the piano. I think you need to really familiarize yourself with the layout of the fretboard.
Answer: It might seem as I know only one piece: the prelude in C by J.S. Bach.
I pretend that also in your case this would best benefit to solve your problem:
compare the piano sheet music with the guitar tab:
https://www.songsterr.com/a/wsa/johann-sebastian-bach-prelude-no-1-in-c-major-tab-s22025t0
and write the chords as it's usual to show the chord pattern for guitars. but instead of  the fingering or the frets transcribe there the names of the tones respecting  the strings and frets.
this is the way I teach beginners in guitar playing in the aim to understand what they play and learn sight reading by writing.


Finding length of side in triangle

Question: Problem
In the following triangle, show that the length $\text{CD} = \frac{\sqrt3}{2}a$.

My solution
Using the Pythagorean Theorem on a 30-60-90 triangle, we get
$$CD = \sqrt{a^2 - \frac{a^2}{4}} = \frac{\sqrt3}{2}a$$
However, it was pointed out to me that this property of 30-60-90 triangles is outside the curriculum.
Question
Can someone outline or show me another solution to this problem? Apparently, I used the "wrong" one.
Comment: How can triangles $\;30-60-90\;$ be outside **any** geometry curriculum??
Comment: It's ridiculous. It's such a fundamental rule, which apparently I must have picked up elsewhere.
Comment: Yeah, it is absolutely ridiculous, as this value of cosine follows from Pythagoras's theorem. If your solution is considered wrong, the curriculum is all wrong in my opinion. However, if the curriculum simply requires memorization of the main values of sines and cosines, it's kinda okay then.  Just an opinion though.
Answer: By definition of cosine function,
$$
CD = a\cos30^\circ = {\sqrt3\over2}a
$$
from the right triangle BCD. (In this triangle, $a$ is hypotenuse, and $CD$ is the leg adjacent to the $30^\circ$ angle.)
Comment: @DonAntonio Thanks!
Comment: I'm upvoting your answer as it is correct, yet I'm afraid trigonometry might be off the record if $\;30-60-90\;$ triangles aren't in the curriculum...
Comment: How could we get $\cos 30^0$ without $ 30-60-90$ triangle?
Comment: @Narasimham You are right; logically we couldn't get $\cos30^\circ=\sqrt3/2$ without studying the 30-60-90 triangle first. However, it looks like we shouldn't expect too much logic from (some) modern curriculums...
Answer: As a student you have a moral obligation to obliterate the confines of your curriculum:

This equilateral triangle is a nice 'cheat sheet' in case you forget the values of $\sin 60^\circ,\sin 30^\circ$ and the cosine of those angles.  By drawing an equilateral triangle with side lengths $2$, and bisecting it, all the remaining information follows.

Finding length of side in triangle


Rotation of iPad resets animation of views back to start

Question: When I rotate the iPad, all the animated components (e.g. views/buttons) will go back to their original position as to when it was first loaded. Is there any way to prevent this?
Here is how I animate object when I click an button e.g.
<code>- (IBAction)button1Pressed:(id)sender{

    [UIView animateWithDuration:ANIMATION_SPEED
                          delay:0.0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:(void (^)(void)) ^{
                         self.view.userInteractionEnabled = NO;
                         _button1.center = CGPointMake(73.01, 419.0);
                         _button2.center = CGPointMake(750.0, 419.0);
                         _button3.center = CGPointMake(850.0, 419.0);
                         _button4.center = CGPointMake(950.0, 419.0);

                         CGRect theFrame = _loginView.frame;
                         theFrame.size.width = 576.f;
                         _View1.frame = theFrame;
                         _View2.frame = CGRectMake(_button2.center.x + 44.0, _button2.center.y / 2 - 89.0, 0.0, 597.0);
                         _View3.frame = CGRectMake(_button3.center.x + 44.0, _button3.center.y / 2 - 89.0, 0.0, 597.0);
                         _4View.frame = CGRectMake(_button4.center.x + 44.0, _button4.center.y / 2 - 89.0, 0.0, 597.0);
                     }
                     completion:^(BOOL finished){
                         self.view.userInteractionEnabled = YES;
                     }];
}
</code>
I'm still quite new so all the details will be appreciated :)
Comment: Have you designed your view with interface builder and add constraints?
Comment: 'The selected views have no constraints. At build time explicit left, top, width, and height constraints will be generated for the view.' - should they have constraints? :)
Answer: I suggest you to create constraints for the interface you want to animate. Then add reference to your header file for those constraints as for any view element.

When you want to animate a view, you now have to update its constraints and ask to layout the views.
<code>[UIView animateWithDuration:0.2
                         animations:^{
                             //in this case, I add 44 to my button Y position, so it will goes down 44px
                             buttonYConstraint.constant += 44;
                             [self.view layoutIfNeeded];
                         }
]
//Now don't forget to update constraints
[self.view updateConstraints];
</code>
Answer: Turning off auto layout located under the 'Interface builder document' fixed this in quick fashion :)


How to solve the warning of CAPTCHA session resuse attack

Question: I am using captcha module (7.x, 1.0 v), When i select the image & click on upload button. Then image uploaded successfully but show this warning message also.

How to solve this issue. Please help. Thanks.
Comment: I'm voting to close this question as off-topic because it was a bug report (see answer below) which should have been reported and tracked via Captcha's issue queue.
Answer: This is a bug in CAPTCHA module you are using. Module should be compatible with core, and file upload is one of the core functionalities of Drupal. Please report this bug to module's issue queue.
But you are not helpless. As a workaround, you can use Multi-Step Registration module. Keep CAPTCHA on first step only, and put profile photo in a second step. It will keep conflicting fields on separate forms, preventing them from interfering with each other.


The localhost page isn't working in xcart 4.6.7Gold

Question: I have downloaded live (live site-currently working) x-cart 4.6.7 Gold files from cpanel to localhost
Provided permission and i have changed config file as per localhost information for db credentials and path.
But I am unable to open the link as per live link in localhost
I am getting this error

The localhost page isn't working.localhost is currently unable to
  handle this request.500
Comment: Firstly check your local server is either running or not. According to W3 protocol, 500 Error is for internal server error. Check here https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Comment: Yes Ananda. Since other php file is working fine, local server is working. This x-cart folder only is not working
Comment: x-cart 4.6.7 have some server requirements, did your local server accepts all the requirements? Please check or review the documentation. I think your x-cart is not supported by your local server, that means you are using a un-matching version. Please check here for requirements. https://help.x-cart.com/index.php?title=X-Cart:Server_Requirements_(X-Cart_4.5,_4.6,_4.7)
Comment: I have checked with requirement, some requirement is satisfied and i have added requirement which is not satisfied. But x-cart 5 working fine. I don't know why this "x-cart 4.6.7" version not working.
Comment: Any error checking code or script is available to find what  the error is encountered in that?
Comment: As far as I can infer that No. Buy not sure. But I can imagine that the problem is due to PHP version. Are you using Xamp server on Windows PC?
Comment: No, I am using PHP7 xampp server in linux ubuntu
Comment: Yes. So problem is there, I think. x-Cart-4.6.7 is supported by PHP 5.3~5.6 possibly. Please check. `PHP7 is recommended for X-Cart versions 4.7.6 and later for better performance`.
Comment: In this link "https://help.x-cart.com/index.php?title=X-Cart:Server_Requirements_(X-Cart_4.5,_4.6,_4.7)" it is mentioned as "X-Cart 4.5.3-4.6.6: PHP version 5.2.0 or later is required.
X-Cart 4.7.0 and later: PHP version 5.3.0 or later is required. PHP versions below 5.3.7 are not recommended for security reasons. PHP7 is recommended for X-Cart versions 4.7.6 and later for better performance."
Answer: 1)Check your xcart_dir/var/log directory
or
2)Enable development mode and debug mode
https://help.x-cart.com/index.php?title=X-Cart:Config.php#Development_mode_and_debug_mode_settings
We recommend the following settings for development:
$debug_mode = 3;
define('DEVELOPMENT_MODE', 1);
or
3)Try to open a page like this
http://demo.x-cart.com/demo_goldplus/check_requirements.php?checkrequirements=1&auth_code=BG6GJH39
$installation_auth_code(BG6GJH39) can be found in the config.php file
or
4)Check you \xampp\apache\logs\error.log apache logs
Where does PHP's error log reside in XAMPP?
PS
Do you mean X-Cart 4.7.6 ?

The localhost page isn’t working in xcart 4.6.7Gold


Need condition which will make functions both true

Question: Let $f:X\mapsto Y$ Let $A \subset X, B \subset  Y$
What condition on $f$ can make
$A=f^{-1}(f[A])$. and  $B=f(f^{-1}[B])$ both true?
For the first ,its $f$ being 1-1, the second
it's $f$ being onto. But both I am somewhat
perplexed .
I know both can be solved separately. The info is on MSE.
The only other condition I can think to make it work on both if $f$ is a bijection.
If I assume $f$ is a bijection,I have to show $f$ is invertible for both ,correct?
Please don't Downvote me if it's a duplicate.I checked and
couldn't find it
Help?
Comment: What was the point of introducing $X, Y$ in the opening line, when you make no other mention of them anywhere in your question? Apparently $f$ is a map. But your conditions with $A$ and $B$ are exactly the same. Did you actually mean $$B = f(f^{-1}(B))$$?
Comment: Yes that is what l meant . I corrected the question.
Answer: The definition of "$f$ is a bijection" is that $f$ is both injective (aka "1-1") and surjective (aka "onto"). And it is an almost trivial fact that $f$ is invertible if and only if it is a bijection. So no, if you know $f$ is a bijection, it is not necessary to prove it is invertible (though you should go through that proof once just to understand why it is an almost trivial fact).
Now

($f$ is bijective) $\implies (f$ is injective$) \implies A = f^{-1}(f(A))$
($f$ is bijective) $\implies (f$ is surjective$) \implies B = f(f^{-1}(B))$

So $f$ is bijective is indeed a single condition that is sufficient for both of the implications you want.
But it is not necessary. In fact all that is required for $A = f^{-1}(f(A))$ is that $f(A)$ and $f(X\setminus A)$ are disjoint. And all that is required for $B = f(f^{-1}(B))$ is $B \subset f(X)$. Neither full injectivity nor full surjectivity is needed.


Using another sound engine

Question: Im currently working on a project where the audio is a big thing. I have about 20-30, 3-4 secound clips as is supposed to be played (Max two at a time). (Clips are max 180kB each) And im also planing to pitch these clips in real-time.
The standard mediaplayer in android is stable but doesnt have the funcitonality as i want, such as pitching.
I´ve also tried Soundpool. SoundPool supports pitching but is very unstable. With soundpool im using OGG soundfiles, but i keep getting the error: AudioFlinger could not create track, status: -12. I guess its because these clips are too large?
Im wondering if there are any other alternatives for another sound engine?
Or if anyone has tips how to avoid soundpool running out of memory?
Answer: Have a look at JetBoy in android SDK samples. It is using JetPlayer
Comment: Thanks for the answer. Tried it for a while, but it couldn't really handle the clips. More of a MIDI-player

Using another sound engine


pariwise comparison when test of effects not significant

Question: I am making a full factorial repeated measure test in SPSS, and the Test of Within-Subjects Effects/multivariate tests are all non-significant.
In this case would estimated marginal means pairwise comparison make sense since I would use a model that is not significant?
Answer: No.  You should take at 'face value' the ANOVA result that the factor does not contain significant differences. Although not common, it could happen that an ad hoc "test" would "find" a bogus significant difference between two levels of a non-significant factor.
Depending on circumstances, this might be due to using a different measure of differences than in the main ANOVA or it might be a chance 'false discovery' due to multiple testing of the same data.
Properly done, you should not even look for such  differences, but if you do look and think you have found something, you should ignore your mistake.
Comment: Ok basically nothing be said about the data since no factors are significant? What if I fit a submodel and something is significant. Would this be bad practice as the full factorial is not signf?
Comment: Not sure what you mean by fitting a submodel. If it is truly a sub-model, why was significance not found initially? Even if the main model is significant (say barely at 5%), all _ad hoc_ tests should be use a method that protects against false discovery (perhaps requiring significance at 2% or 1% level). // If you do 20 independent _ad hoc_ tests at 5%, chances are one will reject.
Comment: for example the model where nothing is significant has 12 parameters while the submodel has 10 of the 12 parameters but shows something is significant
Comment: On what basis did you choose those 10, in particular, out of 12. There are ${12\choose 10} = 66$ possible subsets of 10, why that particular one?


Confusion about euler path,trail,circuit?

Question: What's the difference between a euler trail, path,circuit,cycle  and a regular trail,path,circuit,cycle since edges cannot repeat for all of them anyway?
And can vertices be repeated in a euler path?
Clarification will be much appreciated.Thanks.
Answer: Definitions taken according to Diestel's text Graph Theory:

A path is a nonempty graph $P=(V,E)$ with $V=\{x_0,x_1,x_2,\dots,x_k\}$, $E=\{x_0x_1,x_1x_2,x_2x_3,\dots,x_{k-1}x_k\}$ where all $x_i$ are distinct.  The path's length is the number of edges, $k$.
A cycle is a path of length $k\geq 2$ along with an additional edge included between $x_0$ and $x_k$.  The cycle's length is the number of edges (including this new one).
A circuit is essentially a cycle with the slightly different nuance that we are specifically referring to the edge-set as an element of the edge space when viewing this through the lens of linear algebra, not the graph itself.
A walk (also called a trail) is a nonempty alternating sequence of vertices and edges $v_0e_0v_1e_2v_2e_2\dots e_{k-1}v_k$ where $e_i$ is an edge between $v_i$ and $v_{i+1}$ for all $i<k$.  A walk is closed if $v_0=v_k$.

Note that a walk/trail may repeat vertices and edges while a path may not repeat vertices (and hence cannot repeat edges either) and neither can a cycle (not counting starting and ending vertices).  Also note that circuits often refer to the same thing as cycles in common practice as not everyone follows strict naming conventions.

A graph is called Eulerian if it there exists an Eulerian Tour, a closed walk which visits every edge exactly once.
A graph is called semi-eulerian if it has an Eulerian Walk, a walk which visits every edge exactly once, but not such a closed walk.

You will often see people refer to Eulerian cycles, Eulerian circuits, Eulerian paths, and Eulerian trials.  Often times, either they have defined these terms differently, or they simply mean Eulerian Tours and Eulerian Walks respectively while using an incorrect word.  (That is to say, an "Eulerian Cycle" is not necessarily a "cycle" in that we allow vertices to repeat)

In recap: Euler <insert object here> are like regular <insert object here> except they must use every available edge in the entire graph (and could possibly repeat vertices which is otherwise not allowed depending on strictness of naming conventions followed by that person).  It is not strong enough to simply not repeat edges, but rather all edges in the graph must be used.
Comment: @DeanP a cycle is just a special type of trail.  A graph with a Euler cycle necessarily also has a Euler trail, the cycle being that trail.  A graph is able to have a trail while not having a cycle.  For trivial example, a path graph.  A graph is able to have neither, for trivial example a disjoint union of cycles.
Comment: I have a related question. A graph may have a Euler Trail or not. It may have a Euler cycle or not. However, is it the case that they may have both? Or neither?


Proving if equations are products of XOR

Question: I have to prove analytically to see if these equations are exclusively or.
$$A⊕ A=0$$

Do I solve this by using the truth table?
<code>A A Output
----------
0 0   0
----------
0 1   1
----------
1 0   1
----------
1 1   0
----------
</code>
How I am supposed to prove that this equation is a product of XOR?
$$A⊕B⊕A.B= A+B$$
Answer: Yes, you can solve it by using the truth table. Consider $A\oplus A$, for instance; the truth table tells you that if $A=0$, then $A\oplus A=0\oplus 0=0$, and if $A=1$, then $A\oplus A=1\oplus 1=0$. These are the only possibilities, so it's always true that $A\oplus A=0$.
You can do the same thing for the second problem; it just takes longer.
$$\begin{array}{c|c|c}
A&B&A\oplus B&A\cdot B&(A\oplus B)\oplus A\cdot B&A+B\\ \hline
0&0&0&0&0\oplus 0=0&?\\
0&1&1&0&1\oplus 0=1&?\\
1&0&1&0&?&?\\
1&1&0&1&?&?
\end{array}$$
I'll leave it to you to fill in the rest and decide whether the last two columns really are equal.
Comment: Following what you demostrated is this what the table is suppose to look like?@Brian M. Scott
Comment: $$A⊕B⊕A.B= A+B$$

$$\begin{array}{c|c|c}
A&B&A\oplus B&A\cdot B&(A\oplus B)\oplus A\cdot B&A+B\\ \hline
0&0&0&0&0\oplus 0=0&0\\
0&1&1&0&1\oplus 0=1&0\\
1&0&1&0&0\oplus 1=1&0\\
1&1&0&1&1\oplus 1=0&1
\end{array}$$
Comment: @Leo: I'm afraid not. In the fifth column the last two entries should be $1\oplus0=1$ and $0\oplus1=1$: the two numbers being XORed come from the $A\oplus B$ and $A\cdot B$ columns. For the sixth column you need to review the table for $+$: you've filled in the values for $A\cdot B$, not $A+B$. All cases of $A+B$ are $1$ except $0+0$, which is $0$.
Comment: Oh, I see what I did wrong. I get it thanks!
Comment: @Leo: Great! (Just as a final check, your last two columns should both end up being $0,1,1,1$, verifying the identity.)


Zend Framework - redirect without echo before doesn't work

Question: The code below DOESN'T redirect:
return $this->_helper->redirector->gotoUrl('/customer/');

but this one DOES redirect:
echo 'redirect';
return $this->_helper->redirector->gotoUrl('/customer/');

Any ideas? They both work on my localhost but only the second works on my client's machine.
I could add echo 'something' before every redirect call but not sure why it works that way.
Comment: Sounds kind of odd. Is there something different about the clients setup?
Comment: Can you be more specific about "doesn't redirect"? Once we know that we may have some clues where it actually fails.
Answer: Try once like this :
$this->_redirect("/customer/");

It will surely work.
Answer: In your controller you should redirect using...
$this->_redirect('/customer/', array('exit' => true, 'code' => 301));
Comment: why would this be preferred over the redirector helper? I mean the defaults for the redirector helper are  exit = true code = 302.
Comment: this is just the way that I've always redirected in ZF and I've never had any issues


Best session storage in ExpressJS - NodeJS

Question: I'm building my first (and rather big) NodeJS application. I need excellent performance since it's a big all AJAX (AngularJS) interface with a lot of requests from a lot of users.
I'm building the login system, and I need to choose which storage engine I will use. I narrowed down my search to 4 choices :

connect-mongo : read a lot of nice things about it, but requires the installation of MongoDB
connect-redis : read a lot of nice things about it, but requires the installation of Redis
connect-pg : don't know the performance but that's the DB we're using so no additional installation needed
cookieSession : according to this post is very fast, but I'm a bit confused at to why it's so fast and everywhere I look people seem to ignore this option

Which setup should give me the best performance possible? Without of course impacting functionality.
Thanks!
Comment: redis can be added in one line from npm, not sure about the others...
Answer: The right answer is clear by following your links and looking at the number of stars and forks. cookieSession is unacceptable because it doesn't work across multiple machines, which you will absolutely need. connect-mongo doesn't make any sense because it's not worth installing and maintaining mongo just for cookies.
connect-pg would probably be fine for you, but why risk slowing down your database when there is no need. Redis is an incredibly well-written, easily installable, highly regarded piece of software. It's free and universally available. It's also the most popular option on Github. Go with connect-redis.
Comment: Convinced me, I'm going for redis! Thanks
Answer: This question is asked all the time in the big-data world and there are a lot of biased opinions about the merits of each.  I recommend using whichever one you are most comfortable with.
With that said, I prefer Mongo with Node because of the ease of conversion from JS objects to MongoDB rows and back.
Comment: Your answer is for a different question.  OP isn't asking about what engine to use to store data in general, this is about where to store expressJS Sessions.  There are various adapters which leverage data stores.  OP mentioned they weren't using MongoDB for other data storage, which means that using connect-mongo might not make sense.


pip install nltk command throws import error in Cloudera

Question: I am getting
**ImportError: No module named pip**

when executed
pip install nltk command

I am a Beginner in python. Can anyone please suggest me a solution for this?
Answer: First of all you must install "easy-install" package using ,
curl https://bootstrap.pypa.io/ez_setup.py -o - | python

then install "pip" ,
sudo easy_install pip

Then you are good to go
pip install nltk


Activation function when there are several output labels

Question: If we had a NN to, let's say, clasify images of digits, but each image could contain more than 1 digit (all different), is there any problem in using a 10-dimensional output layer (representing digits 0-9) and the sigmoid activation function in each output neuron?
We cannot use softmax here because, as I say, more than 1 outputs are possible. E.g. if an image contains the digits 3, 5 and 9, the ground truth vector would be [0001010001].
I read some people suggested duplicating the output. I.e: if we can have up to 5 different numbers in an image, we would have 10x5=50 output neurons and apply a softmax activation function to each group of 10. I think this approach is wrong.
I appreciate any other ideas!
Answer: This is sometimes called multi-label classification.
Assuming you have no constraints on the number of labels – e.g. if there are two labels, each of 00, 01, 10, and 11 is possible – your strategy of a separate sigmoid activation for each label is probably the default neural network approach. You could view this as training a separate classifier for each label, but with all of the intermediate hidden representations shared between the classifiers.

I read some people suggested duplicating the output. I.e: if we can have up to 5 different numbers in an image, we would have 10x5=50 output neurons and apply a softmax activation function to each group of 10. I think this approach is wrong.

This approach would indeed be strange; assuming the labels aren't ordered, you'd have to make your loss do a "matching": predictions of (1, 3) and (3, 1) need to be treated the same. Even if you did that somehow, it seems unlikely that this approach would be better than your suggestion, except maybe if you know e.g. that only three of the ten possible labels can be "turned on" for any given instance.


Form 1 in C# hangs up

Question: Ok, here is the complete problem. I've created an simple application in C# which displays the current date & time & it has an "About" button through this button I've made it to open Form2 which displays my name. Everything works fine but whenever I open Form2 & close it(i.e by clicking on the "X" button on Form2 window frame) & again if I click on "About" button Form1 freezes & hangs up.
Here is the code Form1 code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Date
{
    public partial class Form1 : Form
    {
        Form3 SecondForm = new Form3();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.label2.Text = DateTime.Now.ToString(" hh:mm:ss tt");
            label4.Text = DateTime.Now.ToString(" dd-MM-yyyy ");
        }

        private void about_btn_Click(object sender, EventArgs e)
        {
            SecondForm.Show();
        }
    }
}

Here is the Form2 code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Date
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
        }
    }
}

Comment: This is very basic, the SecondForm object got disposed when you closed it.  Showing it again will crash your program with an ObjectDisposedException.  It doesn't "freeze", the debugger displays the problem.  Use an introductory book or tutorial on Winforms programming to avoid making such basic mistakes.
Comment: Your Form2 code has a lot of Form3 in it. Learn early that names are important in programming.
Comment: @HansPassant can you point me to right direction. Can you suggest me an website which teaches all these basic things.
Answer: You need to create your SecondForm each time when you want to show it like this
namespace Date
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        this.label2.Text = DateTime.Now.ToString(" hh:mm:ss tt");
        label4.Text = DateTime.Now.ToString(" dd-MM-yyyy ");
    }

    private void about_btn_Click(object sender, EventArgs e)
    {
        Form3 secondForm = new Form3();
        secondForm.Show();
    }
}
}

Problem in the original code is that when form closes, it tries to destroy controls, data on it, and when you try to call Show again, it can't display it as it already destroyed.
Comment: Thank you for pointing out the mistake I was breaking my head to get it right. Thank you very much.  :) :) :) ...

Form 1 in C# hangs up


What is the best way to delegate requests from third party servers?

Question: We have a third party company that we communicate with; we send them an information request, they send some information back.  The issue is that right now, we only have this working on the production server.  We have several other servers (dev, staging, uat, content editing) that need to make use of this information.  So I make call to the third party with any server, they respond and I need a way to figure out which of our servers made the request.
The third party company will not change their code; we can give them a single server end point to respond to.
I know I can probably write something that does this, but I figure there is something that already does this and I am just not searching for the right terms.
I am using Java with Apache Tomcat.
Comment: Do I understand this correct that you make a request to a third party server, and then the third party makes a request back to your server?
Comment: Correct; the problem is that the third party doesn't know which server. It always replies to the same address. They don't currently offer any dynamic replies.
Answer: Let's divide your problem into two problems.
Your essential problem is splitting the traffic. You can use a tool like Gor for this purpose. I found this tool from here.
Your other problem is filtering: guaranteeing that your traffic goes to the correct destination. This is when you can't simply send all of the traffic to all possible destinations. Some common reasons include high volume or sensitive data.
Filtering is highly dependant on your particular domain, so I don't believe there are any out of box implementations. However, scripting it should be fairly straightforward.
If and how you can do filter the data depends on the API. Sometimes the API generates an unique identifier for each request that you make. Some other API-s let you generate an unique identifier yourself.
For example you can do the outgoing request through some two-way proxy that will remember the machine and unique identifier, and then the proxy filters any incoming requests by that unique identifier.
Comment: Another thing you can do with Gor is it for notifications. You can use its middleware to save the request to a "middle server", and strip down everything except the essential data. Then the destination clients receive only an identifier, and can make a request to the "middle" server for full payload.


Quick question about comparing functions.

Question: Suppose I have functions f and g; is there any theorem or technique that I can use to know if $f(x) \leq g(x)$ or if $f(x) \geq g(x)$ or neither in a given interval?
Comment: Equivalently, you're asking for ways to prove if $h(x)$ is nonnegative or nonpositive within a given interval, where $h(x)=f(x)-g(x)$...
Comment: I can sure have $h(x)=f(x)-g(x)$ but the problems is, I wouldn't know in what interval would it be nonnegative or nonpositive. It's more interesting and convenient if I'd know if it is nonnegative or nonpositive when I $ \underline{already} $ have an interval.
Answer: I don't know if this is helpful and it doesn't solve your general problem, but as an example: if you have sat two real valued (differentiable) functions $f$ and $g$ defined on the same say closed interval $[a, b]$ of the real numbers, you could for example note that say $f(a) > g(a)$ for the left endpoint of the interval and then note that the derivative of $f$ is greater than or equal to the derivative of $g$ on the whole interval. If this is all so, then you would be able to conclude that $f(x) > g(x)$ for all x in the interval. But again, this approach would only apply to a small set of functions.
Another idea could be to (as above) first note that $f$ is greater than $g$ at some point in the interval and then show that $f(x) = g(x)$ does not have any solutions. Then $f$ clearly would be greater than $g$ on the whole interval.
Comment: Oh, yeah I'm getting what you're trying to say. This is similar to the first derivative test. From what I understood: If the derivative of f is greater than g for all values of x in the given interval, then we could say that the values of f is greater than g in the given interval. Is that it?
Comment: Almost. You also need that $f(a) > g(a)$ for a left endpoint of the interval. If you don't have $f$ being greater than $g$ at a point, then it isn't true.
Comment: Oh yeah, I've forgotten that stipulation. Many thanks, you just saved me from all that strenuous graphing work.


Drought index calculation

Question: I am calculating a drought index and I have a set of values.  The next step in the procedure is to standardize the values to  compare across regions and time scales.  The paper that establishes this particular drought index fits their dataset to the log-logistic distribution and uses the probability distribution function to standardize the values.  My dataset does not follow the log-logistic distribution, or any distribution for which I can test.  Is there a procedure to standardize values that do not follow a distribution?
What I am trying to do is calculate the drought index values to use in an attempt to correlate  drought index with irrigation water demand.
Comment: Note that you can still standardize data that is not normally distributed - the question is whether or not the number of standard deviations from the mean (which is what you get when you standardize a variable) is meaningful for your data. What is your purpose for doing this standardization? It may also help to see a histogram or some other graphical display of the distribution of your data.
Comment: Are you comparing across regions and time periods for which you yourself have collected data?  If so, you may be able to make those comparisons without transforming your data.  Why do you think you need to standardize your data to make comparisons?  Presumably you used the same scales for temperature, etc., so what is to be gained by standardizing?  If you want to compare your results to the published results, you should treat your data the way the published data was treated.  Was the published data standardized?  And why?
Comment: @JoelW., I have used daily values to obtain a monthly sum.  The original article for this drought index standardized the data to compare different time scales using the log-logistic probability distribution function.  I am really only interested in one timescale, but since the paper standardized the values, I thought I should as well.
Comment: If you are not planning to make comparisons with the published values, then perhaps you should use the analysis that makes most sense for your data set. That might not involve a transformation.  (In general, I avoid transformations unless there is a compelling reason to do one.)
Comment: I agree with Joel's comment. Further, it might be that if you estimate some sort of seasonal autoregressive model on the drought index, then the residuals might be closer to a distribution you would be familiar with.
Answer: I guess the author is referring to the Standardized Precipitation Index (SPI; McKee et al., 1993) or one derived from it (e.g., SRI (Shukla & Wood, 2008), for runoff; SSI (Hao & AghaKouchak, 2013), for soil moisture; SPEI (Vicente-Serrano et al., 2010), for precipitation and evapotranspiation; etc.). Although each of these indices was originally proposed with a specific probability distribution function (PDF), since their publication other PDFs have been used to compute them. For example, Guttman (1999) found that the  Pearson type III was the best model to compute the SPI for a large data set in U. S.; meanwhile, Lana et al. (2001) found that the Poisson-gamma distribution was the best for the data analyzed in Catalonia, in Spain.
Furthermore, there are non-parametric approaches used to compute this type of drought index. For example, Farahmand & AghaKouchak (2015) proposed the use of the empirical probability estimated with the general formula for plotting positions (Hesel et al., 2020):
$p = \frac{i - \alpha}{n - \alpha - \beta + 1}$
where $i$ denotes the rank of non-zero values in the data set, from the smallest; $n$ is the sample size; and $\alpha = \beta = 0.44$.
Also, Kumar et al. (2016) used  Kernel Density Estimation (KDE)  with a Gaussian kernel to estimate the probability distribution of the data set.
I guess the key idea here is that you're not constrained to use a specific PDF. Rather, use the one that better fits your data, or, if each site in your analysis fits better different PDFs, use a non-parametric approach.
References
Farahmand, A., & AghaKouchak, A. (2015). A generalized framework for deriving nonparametric standardized drought indicators. Advances in Water Resources, 76, 140–145. https://doi.org/10.1016/j.advwatres.2014.11.012
Guttman, N. B. (1999). Accepting the Standardized Precipitation Index: A calculation algorithm. Journal of the American Water Resources Association, 35(2), 311–322. https://doi.org/10.1111/j.1752-1688.1999.tb03592.x
Hao, Z., & AghaKouchak, A. (2013). Multivariate Standardized Drought Index: A parametric multi-index model. Advances in Water Resources, 57, 12–18. https://doi.org/10.1016/j.advwatres.2013.03.009
Helsel, D. R., Hirsch, R. M., Ryberg, K. R., Archfield, S. A., & Gilroy, E. J. (2020). Statistical methods in water resources. https://doi.org/10.3133/tm4a3
Kumar, R., Musuuza, J. L., van Loon, A. F., Teuling, A. J., Barthel, R., Ten Broek, J., Mai, J., Samaniego, L., & Attinger, S. (2016). Multiscale Evaluation of the Standardized Precipitation Index as a Groundwater Drought Indicator. Hydrology and Earth System Sciences, 20(3), 1117–1131. https://doi.org/10.5194/hess-20-1117-2016
Lana, X., Serra, C., and Burgueño, A.: Patterns of monthly rainfall shortage and excess in terms of the standardized precipitation index for Catalonia (Spain), Int. J. Climatol., 21, 1669–1691, 2001.
McKee, T. B., Doesken, N. J., & Kleist, J. (1993). The relationship of drought frequency and duration to time scales. Eighth Conference on Applied Climatology, 179–184. https://climate.colostate.edu/pdfs/relationshipofdroughtfrequency.pdf
Shukla, S., & Wood, A. W. (2008). Use of a Standardized Runoff Index for Characterizing Hydrologic Drought. Geophysical Research Letters, 35(2), 1–7. https://doi.org/10.1029/2007GL032487
Vicente-Serrano, S. M., Beguería, S., & López-Moreno, J. I. (2010). A multiscalar drought index sensitive to global warming: The standardized precipitation evapotranspiration index. Journal of Climate, 23(7), 1696–1718. https://doi.org/10.1175/2009JCLI2909.1

Drought index calculation


Why the data isn't saved in the relationship tables?

Question: I've have this DB Model http://www.dropmocks.com/mBgqjs and I'm using CakePHP to build a simple application just for learning where I have this add() method:
public function add() {
    if ($this->request->is('post') && is_uploaded_file($this->request->data['Information']['picture']['tmp_name'])) {
        // Handling file uploads
        $upload_avatar_dir = WWW_ROOT . "uploads/avatar/";
        $new_file_name = $this->createRandomString() . substr($this->request->data['Information']['picture']['name'], -4);
        move_uploaded_file($this->request->data['Information']['picture']['tmp_name'], $upload_avatar_dir . $new_file_name);

        $this->request->data['Information']['picture'] = $upload_avatar_dir . $new_file_name;

        $this->Information->create();

        if ($this->Information->saveAssociated($this->request->data)) {
            $this->Session->setFlash(__('The information has been saved'), 'flash_success');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The information could not be saved. Please, try again.'), 'flash_error');
        }
    }
    $countries = $this->Information->Country->find('list');
    $this->set(compact('countries'));
}

and this is my add.ctp file:

<?php echo $this->Form->create('Information', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data'));?>
<fieldset>
    <legend><?php echo __('Add Information'); ?></legend>

<?php echo __('Personal') ?>

<?php echo __('Other Information') ?>

                    <?php
                        echo $this->Form->input('name', array('label' => __('Name')));
                        echo $this->Form->input('lastname');
                        echo $this->Form->input('email');
                        echo $this->Form->input('countries_id');
                        echo $this->Form->input('mobile_phone');
                        echo $this->Form->input('home_phone');
                    ?>

                    <?php
                        echo $this->Form->input('address', array('cols' => 50, 'rows' => 5));
                        echo $this->Form->input('picture', array('type' => 'file'));
                        echo $this->Form->input('recruitment_status', array('label' => __('Status'),'options'=>array('1'=>__('Call for Interview'),'2'=>__('Rejected'),'3'=>__('Pending for Upcoming Oportunities'))));
                    ?>

            <?php
                echo $this->Form->input('Education.0.education_content');
                echo $this->Form->input('Experience.0.experience_content');
                //echo $this->Form->input('Attachment.attachment_route', array('type' => 'file', 'multiple'));
                echo $this->Form->input('other_information');
            ?>

</fieldset>
<?php
 $options = array(
'value' => __('Save!'),
'class' => 'btn btn-inverse'
 );
?>

 <?php echo $this->Form->end($options);?>

but something is wrong there because the associated data never is saved and can't find what is wrong? Can any help me?
Answer: Make sure your relations are correctly created in the models and use saveAll instead of saveAssociated, as the saveAssociated can't handle saving multiple entries at one time. What saveAll does is basically combining saveMany and saveAssociated into one single save method.
Comment: Well my model for Information is this http://pastebin.com/UGTxPkuK and I think it's fine, take a look please and I'm using also saveAll but without success
Comment: Don't know if it'll fix it, but try changing this:
public $hasMany = array(
    'Educations' => array(
        ...
    ),
    'Experiences' => array(
        ...
    ),
    'Attachments' => array(
        ...
    )
);

to
public $hasMany = array(
    'Education' => array(
        ...
    ),
    'Experience' => array(
        ...
    ),
    'Attachment' => array(
        ...
    )
);
Comment: Wow ... you save my day Caio, thanks a lot. I have another related question can I ask here or need to open another post for this purpose?
Comment: Open up another post. It's good so if someone has the same question they can find it with ease.


Weblogic 14c - webservice-description-name is not unique within weblogic-webservices

Question: I am exposing my stateless ejb as web service using the annotations as follows:
@WebService(
    name = "MyServicePort",
    portName = "MyServicePort",
    serviceName = "MyService",
)
@SOAPBinding(
    style = SOAPBinding.Style.RPC
)
@Stateless(mappedName="MyServiceEJB", name = "MyServiceEJB")
public class MyServiceBean {

To define the context root in weblogic, I've defined the web service in weblogic-webservices.xml deployment descriptor as follows:
<weblogic-webservices
    xmlns="http://xmlns.oracle.com/weblogic/weblogic-webservices"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-webservices http://xmlns.oracle.com/weblogic/weblogic-webservices/1.1/weblogic-webservices.xsd">
    <webservice-description>
        <webservice-description-name>MyService</webservice-description-name>
        <port-component>
            <port-component-name>MyServicePort</port-component-name>
            <service-endpoint-address>
                <webservice-contextpath>/mycontext</webservice-contextpath>
                <webservice-serviceuri>/myservice</webservice-serviceuri>
            </service-endpoint-address>
        </port-component>
    </webservice-description>
</weblogic-webservices>

However, weblogic is throwing the below error while deploying:
[ERROR] weblogic.wsee.ws.WsException: Error encountered while deploying WebService module 'myservice-ejb.jar'.
In weblogic-webservices.xml, webservice-description-name MyService is not unique within weblogic-webservices

Any clue what I am doing wrong here? This is the only bean/service in my web application and there is no other application deployed in weblogic (local instance).
Answer: I am able to resolve the issue by placing the webservices.xml with below contents into META-INF folder (next to weblogic-webservices.xml).
<webservices xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/javaee_web_services_1_4.xsd"
    version="1.4">
    <display-name>MyService</display-name>
    <webservice-description>
        <webservice-description-name>MyService</webservice-description-name>
        <port-component>
            <port-component-name>MyServicePort</port-component-name>
            <wsdl-port xmlns:tns="http://schemas.mycompany.com/webservices/MyService">tns:MyServicePort</wsdl-port>
            <service-endpoint-interface>mypackage.MyServiceBean</service-endpoint-interface>
            <service-impl-bean>
                <ejb-link>MyServiceEJB</ejb-link>
            </service-impl-bean>
        </port-component>
    </webservice-description>
</webservices>

Hope it may help someone facing the same challenge.


Java Hangman won't loop correctly

Question: I am very new to programming and java (as you can see) and am really stuck on a basic problem in programming hangman. My code is not the cleanest I know, but I really would like to some input on where I am going wrong logic wise. My trouble is getting the program to output the 'hangman display' correctly with each guess. I think there is an issue with the way I have triesWrong++ set up. I also can't get the repeated letters to work properly but just can't quite figure it out.
import java.util.*;

public class HangMan
{

public static void main(String[] args)
{
    char[] alphabet =
    {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    };
    String[] words =
    {
        "javascript", "declaration", "object", "class", "failing"
    };
    int randomIndex = (int) (Math.random() * words.length);
    String randomWord = words[randomIndex];
    char[] explodedWord = explode(randomWord);
    char[] censoredWord = new char[randomWord.length()];
    int triesWrong = 0;
    Scanner input;
    char letterGuess;
    boolean letterFound = false;

    for (int i = 0; i < randomWord.length(); i++)
    {
        censoredWord[i] = '_';
    }

    while (!gameWon(censoredWord, explodedWord))
    {
        hangMan(triesWrong, censoredWord, alphabet);
        System.out.println("Please guess a letter: ");
        input = new Scanner(System.in);
        letterGuess = input.next().trim().charAt(0);

        char[] repeatedLetters = new char[26];

        for (int i = 0; i < alphabet.length; i++)
        {
            if (letterGuess == alphabet[i])
            {
                if(letterGuess == repeatedLetters[i])
                {
                    System.out.println("You already guessed this letter, please enter another letter.");
                }
                else
                {
                    repeatedLetters[i] = alphabet[i];
                    alphabet[i] = '_';
                }
            }
        }
        for (int i = 0; i < explodedWord.length; i++)
        {
            if (letterGuess == explodedWord[i])
            {
                censoredWord[i] = letterGuess;
                letterFound = true;
            }
        }
        if (!letterFound)
        {
            letterFound = false;
            triesWrong++;
        }
    }
}

public static char[] explode(String bank) //getWord method for string bank
{
    //create character array called explode that has length of string
    char[] explodedWord = new char[bank.length()];

    for (int i = 0; i < bank.length(); i++)
    {
        explodedWord[i] = bank.charAt(i);
    }
    return explodedWord;
}

public static void hangMan(int n, char[] dashWord, char[] alph)
{
    if (n == 0)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 1)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 2)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|\t|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 3)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|\t|\\");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 4)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|      /|\\");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 5)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|      /|\\");
        System.out.println("|\t|");
        System.out.println("|");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 6)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|      /|\\");
        System.out.println("|\t|");
        System.out.println("|      /");
        System.out.println("|");
        System.out.println("|");
    } else if (n == 7)
    {
        System.out.println("\n\n---------");
        System.out.println("|\t|");
        System.out.println("|\t0");
        System.out.println("|      /|\\");
        System.out.println("|\t|");
        System.out.println("|      / \\");
        System.out.println("|");
        System.out.println("|");
        System.out.println("GAME OVER");
        System.exit(0);
    }

    System.out.println("\n\n");

    for (int i = 0; i < alph.length; i++)
    {
        System.out.print(alph[i] + " ");
    }

    System.out.println("\n\n");

    for (int i = 0; i < dashWord.length; i++)
    {
        System.out.print(dashWord[i] + " ");
    }

    System.out.println("\n\n");
}

public static boolean gameWon(char[] dashWord, char[] bigWord)
{
    if(dashWord.length != bigWord.length)
    {
        return false;
    }

    for(int i = 0; i < dashWord.length; i++)
    {
        if(dashWord[i] != bigWord[i])
        {
            return false;
        }
    }
    System.out.println("Congratulations, you win!");

    return true;
}

}

Comment: I would store the hangman figures in text files, that will significantly reduce the amount of code. And increase readability.
Answer:     if (!letterFound)
    {
        letterFound = false;

If !letterFound is true it means letterFound is already false. So no need to set it to false afterwards. That is a logic flaw.
I advise to move letterFound = false; to the start of the while loop. So you start fresh every loop.

Java Hangman won't loop correctly


Motion detection using sound

Question: I was thinking of implementing a motion detection by SOUND, to my app. However I'm still deciding on a good solution for this. One idea would be recording small chunks of sound and somehow comparing them. The other would be non-stop audio rec and somehow "feel" to sound spikes and trigger motion.
I'm talking about detecting motion in the room, ambient motion.
The latter sounds better but is it implementable?
Comment: Why do you want to use sound for motion detection?  Wouldn't an accelerometer be a better choice?
Comment: Relevant: http://www.extremetech.com/computing/128735-microsoft-creates-kinect-like-system-using-your-laptops-built-in-speaker-microphone
Comment: Are you talking about with a peripheral? (i.e. http://www.parallax.com/tabid/768/ProductID/92/Default.aspx) Or with only an android device?
Comment: I want to use the mic to detect motion around the phone, not the motion of the phone itself.
Answer: You could emit some sound and try to detect any differences or changes over time in the Doppler shift, spectrum and amplitude in any reflections returned to the microphone.  A textbook on RADAR technology might explain some of the DSP signal analysis needed.

Motion detection using sound


Is there a way to remove this error in Angular Js?

Question: I am new to Angular JS and I was trying to use routing in it but I am facing some problems.
Here is the error
<!DOCTYPE html>

Main
City 1
City 2

Click on the links.

  Note that each "view" has its own controller which each gives the "msg"
  variable a value.

london.htm

London

London is the capital city of England.

  It is the most populous city in the United Kingdom, with a metropolitan area
  of over 13 million inhabitants.

{{msg}}
paris.htm

Paris

Paris is the capital city of France.
The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.
{{msg}}
Comment: yes, don't make cross origin requests unless they are supported by the other server - however, the error in this case is simpler ... you need to use a http server to serve your page ... `file:///` is not a protocol to use to do any sort of development with ... use `http` at least
Comment: no, you are not doing this from a `http` server ... you're loading the page using `file:///` protocol` - the error you posted does not lie about how you are loading the page
Comment: I am doing this on the local server. I am not requesting any file from the server. I am confused.
Comment: So that means I have to deploy the angular js app
Comment: Can you make fiddle with your code?
Comment: like this - https://jsfiddle.net/4rqyeoxh
Answer: These errors occur because you are not running it under any server or localhost. Angular JS routing will not work if you open the file directly under the browser.
How to Fix This
Install wamp server or any other server. move your files to servers root directory and run it using its address.

If you use WAMP Server copy your files to a folder and move the folder to C:/Wamp64/www/

In your web browser type : http://localhost/<your_folder>
and for reference i also add the code:

index.html

        <title>Angular Sample</title>

Main

        Red
        Green
        Blue

pages/green.html

Green

pages/red.html

Red

pages/blue.html

Blue

Comment: I've been using angular js without any server it works fine. Am I doing something wrong?
Comment: I am using Angular js
Comment: I am following this tutorial https://www.w3schools.com/angular/angular_routing.asp
Comment: usually the the XMLHTTP error is show when you didnot run it on serever.pls wai8 i will send a sample
Comment: i have checked your sample it's working just try running it under a server or a localhost
Comment: Yup, I tried running it on a host and it worked! Thanks!
Comment: I gave you an upvote but my reputation is less than 15 so it's not recorded. Sorry.


Your binary is not optimized for iPhone

Question: I read the answers to questions similar to my question in stackoverflow here, here & here but could not solve my issue.
I get the below error while trying to validate my binary with xCode 5. I sent two month ago another version of this binary and it was accepted and put on the app store. I have the proper launch images for iphone 5 & 6.
It says:

Your binary is not optimized for iPhone 5 - New iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image referenced in the Info.plist under UILaunchImages with a UILaunchImageSize value set to {320,586}. Launch images must be PNG files and located at the top-level of your bundle, or provided within each .lproj folder if you localize your launch images. Learn more about iPhone 5 support....

As you can see this error differs from what was brought up in other questions on this topic.
Any help would be appreciated.
Thanks.
Comment: Did you find an answer? How did you solve this?
Answer: Do you localized your launch images?
If you do, I had some problem for that and found a way to solve it.
https://stackoverflow.com/a/26872153/2632955

Your binary is not optimized for iPhone


Need Help Creating BackUp directory

Question:  $backuparray = implode("|",$songarray1);
 file_put_contents("backups/".microtime("tunes.txt"),$backuparray);

How do I get my backup directory to link  a txt file using microtime , owner id , premissions , and  size?  The file needs to have tunes.txt at the end of the microtime
Comment: not clear what you asking
Comment: I have to a show a backup directory on a page, I have the files showing up using the code provided, but I just need the files to show as a text file, and show the corresponding Owner ID, Permissions and size of the file.
Answer: $dir = "/var/html/uploads";
if (is_dir($dir)) {
echo("
\n");
echo("
Filename	File Size
File Type
\n");
$dirEntries = scandir($dir);
foreach ($dirEntries as $entry) {
    $entryFullName = ($dir . "/" . $entry);
     echo("
" . htmlentities($entry) . "	".
     filesize($entryFullName) . "	" .
     filetype($entryFullName) . "
\n");
}
 echo("
\n");
}
else
echo("
The directory " . htmlentities($dir) . " does not
exist.
");

Need Help Creating BackUp directory


How to use memcached with PHP

Question: How to use memcached server?
I have following script and need to be using memcached:
<code>$dbserver="server";
$dbuser="user";
$dbpass="pass";
$dbname="db";
function dbcon(){
  @$spojenie=mysql_connect($GLOBALS["dbserver"],$GLOBALS["dbuser"],$GLOBALS["dbpass"]);
  mysql_query("SET NAMES utf8");
  if (!$spojenie){
    die('error');
  }
  mysql_select_db($GLOBALS["dbname"],$spojenie);
  return $spojenie;
}
$dbspojenie=dbcon();
$GLOBALS["dbspojenie"]=&$dbspojenie;
</code>
Comment: It is not clear what is asked here. What exactly memcached should be used for?
Answer: Read manual memcache
<code>$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
</code>
Comment: thank you, i had to use new Memcache instead of memcached, because memcached class is not present (should i install it from somewhere?) and i have got error: Fatal error: Call to undefined function mysqlnd_memcache_set()

How to use memcached with PHP


rethinkdb eqJoin matching

Question: Hi I'm using javascript with rethinkdb, and I'm trying to figure out how to use eqJoin when the id of the target is not on the maintable but on the second table.
The examples on the website shows this.
first table /players
[{name: 'anna', gameID:1}]

second table /games
[{id: 1, gameName: 'supergame'}]

But what I want to join is this
first table / players
[{id 1, name: 'anna'}]

second table / games
[{playerID: 1, gameName:'supergame'},
 {playerID: 1, gameName:'megagame'},
 {playerID: 1, gameName:'lamegame'}]

I have read a little about concatMap and tried this but that obviously gives me errors, is there any other way?
And if there is could I even join even more tables?
r.table("players").concatMap(function(play) {
    return r.table("games").getAll(
        play("id"),
        { index:"playerID" }
    ).map(function(games) {
        return { left: play, right: games }
    })
}).run(conn, callback)

Answer: The table on the right has to have an index on the field you're getting.  It looks from your second example like you have an index playerID on games already; if that's the case, then you should be able to just specify index: 'playerId' as an argument to eqJoin.  Something like r.table('players').eqJoin('id', r.table('games'), {index: 'playerId'}).
If that index doesn't exist, you can use indexCreate to create it.
Comment: Thank you! the only thing missing though is that there is one player created for every game, but I would like the games to be attached to the single player it matches, is that possible?
Answer: by some help from slack.rethinkdb.com I got this answer which works great.
this also puts the matching objects in a tree on the object
r.db('test').table("players").map(function(play){
    return play.merge({ "games": r.db('test').table("games").getAll(trans("id"), {"index": "playerID"}).coerceTo("ARRAY")});
})

rethinkdb eqJoin matching


overridey Destroy but keep callbacks

Question: ActiveRecod model which overrides the destroy method to actually just "soft-delete" the object. We do create many before_filters, dynamically but they won't be called, if we override the destroy method.
<code>before_destroy {
  p "before_destroy"
}

def destroy
  soft_delete
end
</code>
Answer: <code>  def destroy
    _run_destroy_callbacks do
      soft_delete
    end
  end
</code>

overridey Destroy but keep callbacks