A doubt concerning the fundamental theorem of arithmetic

Question: Will a prime $p^{0}$ be considered a unique prime in prime decomposition of a number?
If the answer to the above question is yes then it breaks the uniqueness which the Fundamental Theorem of Arithmetic proposed.
If the answer is no, which I think is true, then why don't we count it.
Isn't it also the power of a prime?
That way I can say $4=2×2$ or $2×2×3^{0}$ and so on.
Comment: decomposition is unique up to units (and order of factors) and $p^0$ is a unit, so you can add/remove how many units you want without breaking essential uniquiness of factorization
Comment: See [this answer](http://math.stackexchange.com/a/539536/28900) for a discussion.
Comment: The question should be in the body, not just in the title. Please edit accordingly.
Comment: Lol! Sorry guys. Don't know what was going on in my mind that I ended up doing something like this. I will see to that.
Comment: Looked to that Gerry . Thanks Cameron and Danae for clearing my doubt!
Comment: What?? Now the first line of the body is starts, "If the answer to the above question...", but there is no "above" question! Please edit so things make sense.
Comment: For the purposes of the fundamental theorem of arithmetic, the prime factorisations of $4$ the forms $2^2$ and $2^2 \times 3^0$ are equivalent, in the same way as the prime factorisations of $12$ such as $2^2 \times 3^1$ and $3^1 \times 2^2$ are equivalent
Answer: I'd like to elaborate on the Hardy-Wright standard form which Bob mentioned.
Given a positive, composite number $n$, its prime factorization is $$n = p_1 p_2 \ldots p_k$$ where $k$ is what we now usually call the "big omega" function $\Omega(n)$, prime factors of $n$ counted with multiplicity.
"The primes ... are not necessarily distinct, nor arranged in any particular order," write Hardy and Wright. "If we arrange them in increasing order, associate sets of equal primes into single factors, and change the notation appropriately, we obtain" $$n = {p_1}^{a_1} {p_2}^{a_2} \ldots {p_k}^{a_k}$$ where now $k$ is the "little omega" function $\omega(n)$ which counts distinct prime factors of $n$. Hardy and Wright also give the conditions $a_1 > 0, a_2 > 0, \ldots$ and reiterate algebraically that the primes are now given in ascending order as $p_1 < p_2 < \ldots < p_k$. This is what they call standard form.
On the next page, they state the fundamental theorem of arithmetic this way: "The standard form of $n$ is unique; apart from rearrangement of factors, $n$ can be expressed as a product of primes in one way only."
So then $p^0$ is deliberately excluded. They don't bother to assert that each $a_i$ has to be an integer, but this can be safely assumed. So if you had read Hardy and Wright, I think your doubt would have been addressed before it could even rise to the level of an objection.
As far as I can tell, they never felt the need to declare that $1$ is not a prime number. But as you expand your study of the prime numbers beyond the positive integers, you will need to know the definition of a unit. In $\mathbb Z$, the only units are $1$ and $-1$ (this is true of almost every imaginary quadratic ring as well). Neither rearranging prime factors nor multiplying by units changes uniqueness of factorization.
Comment: Very good answer, but you should clarify that although unique factorization applies to negative integers as well and to many real quadratic rings, only very few imaginary quadratic rings have unique factorization. I can't say much about cubic rings, they haven't been studied with the same zeal as quadratics.
Answer: A typical statement of the Fundamental Theorem of Arithmetic is this one from Wikipedia:

Every positive integer $n > 1$ can be represented in exactly one way as $n = p_1^{\alpha_1} p_2^{\alpha_2} \dots p_k^{\alpha_k}$ where $p_1 < \dots < p_k$ are primes and the $\alpha_i$ are positive integers.

0 is not a positive integer so powers $\alpha_i =  0$ are not allowed in the representation described here.  You are correct that if 0 powers were allowed, the representation would no longer be unique.
It is true that $1 = 3^0$ is a power of prime.  The error is in thinking that the FTA asserts that $n$ can be represented uniquely as a product of powers of primes.  It claims only that it can be represented uniquely as a product of primes to positive powers.
Comment: I'd upvote if it weren't for the Wikipedia link. May Jar'Edo Wens bless you.
Answer: The use of exponents is merely a convenience, as is sorting the primes into ascending order. Multiplying by units and/or reordering the primes does not create distinct factorizations. So for example $1 \times 1 \times 2 \times 3 \times 2 \times 1 \times 1$ and $(-1)^2 \times 2^2 \times 3$ are not distinct factorizations of 12, though neither is what Hardy and Wright would call "standard form." (By the way, the number 1 has never been prime, because it has always lacked a lot of properties the true primes have; though I concede that maybe it was the fundamental theorem of arithmetic that forced mathematicians to finally accept this truth barely a century ago).
Because exponents in factorizations are just a shorthand for writing a prime a number of times and that number of times is a positive integer, only positive integers are valid exponents for primes in a prime factorization. This means you can do things like $p^5$, $p^{15643424564}$, etc., but not things like $p^{\pi + e}$, $p^\sqrt{2}$, $p^\frac{7}{2}$ etc. (By the way, this also holds when you're operating in a domain in which a prime could be an irrational number: the exponents still need to be purely real, rational positive integers).
You could get all fancy and sophisticated and claim that $p^0$ means writing the prime $p$ zero times and thus giving the "empty product." But the fact is that $p^0 = 1$ and that's a unit, not a prime. Therefore $2^2 \times 3^0 \times 5^0 \times 7^0 \times 11^0 \times \ldots$ does not create a distinct factorization of 4.


Nailcare for guitarists?

Question: I know that having your nails too long or short is bad, particularly for classical/fingerstyle guitarists,
but what constitutes to having 'good' nails?
Bonus points for pictures/external articles
Answer: This video has some good advice on shape and how this affects the sound, and also how to shape it. It is from a classic guitar point of view, where it is important to have a broad contact with the string to create a high quality sound.

Additionally this article has some good theories about what to consider when forming your nails, and emphasize the different needs for different classical playing styles:
http://www.thisisclassicalguitar.com/fingernails-on-classical-guitar
This second video is more aimed at electric guitar which is more of a practical approach for supporting different playing techniques, where you may not have the same length as for classical.
Answer: I have some perhaps-unorthodox ideas that I've formed over the years. I started with pointy tips and they'd always break if played too aggressively. So I (foolishly) tried putting lots of polish on them to keep them from breaking (and look cool).
But when I started concentrating on tremolo technique and real demands for speed and articulation, pointy tips is a drag (and polish is stupid). You want just a bit of nail, with a soft curve. If you practice the Apoyando (Rest Stroke), where you use both the flesh and the nail, and where your finger comes to rest against the next string, you will naturally discover the proper length. Too long and you can't touch the strings easily with the flesh of your finger tips. This is bad for speed because your fingers have more difficulty finding the strings. Too short, and your tone won't have the desired attack.
The way to look at the nails to examine their length is not from the top (the part that you polish), but from the bottom. Turn the palm of your hand toward you and look at how much nail is peeking-out past the tip. This is the way the strings will see it.

Nailcare for guitarists?


Integrating $x^{x^x}$

Question: Although one cannot find an elementary antiderivative of $f(x)=x^x$, we can still give a series representation for $\int_0^1 x^x dx$, namely:

$$I_1=\sum_{n=1}^\infty \frac{(-1)^{n+1}}{n^n}=0.78343\ldots$$

One can even find an expression for the complete antiderivative in terms of infinite sums and the incomplete gamma function $\Gamma(a,x)$:

$$\int x^x dx =\sum_{n=1}^\infty \left(\frac{(-1)^{n+1}\Gamma(-n\ln(x),n)}{n^n \Gamma(n)}\right)+C$$

Considering special, non-elementary function, series, infinite products, etc. , is this also possible for $\int_0^1 x^{x^x} dx$?
Thank you in advance!
Comment: A bit of humor: the suffix "integrating-xxx" of the [link](https://math.stackexchange.com/questions/3601774/integrating-xxx) is... well, perfect ;)
Answer: $$x^{x^x}=\exp(x^x\ln(x))=\exp(\ln(x)e^{x\ln(x)})$$
$$\exp(\ln(x)e^{x\ln(x)})= \sum^{\infty}_{n=0} \frac{\big(\ln(x)e^{x\ln(x)}\big)^n}{n!}$$
$$\int_0^1 x^{x^x}dx=\int_0^1\sum^{\infty}_{n=0} \frac{\big(\ln(x)e^{x\ln(x)}\big)^n}{n!}dx$$
Now using Fubini's theorem we swap the integral and sum
$$=\sum^{\infty}_{n=0} \frac{1}{n!} \int_0^1\big(\ln(x)e^{x\ln(x)}\big)^ndx$$
Now we evaluate the integral
$$\int_0^1\big(\ln(x)e^{x\ln(x)}\big)^ndx=\int_0^1 \ln^n(x)e^{nx\ln(x)}dx=\int_0^1 \sum^\infty_{n=0} \frac{\ln^n(x)(nx\ln(x))^n}{n!}dx$$
$$= \sum^\infty_{n=0} \int_0^1 \frac{\ln^n(x)(nx\ln(x))^n}{n!}dx=\sum^\infty_{n=0}\frac{n^n}{n!} \int_0^1 x^n \ln^{2n}(x)dx$$
Evaluating the integral using Bernoulli's proof
$$\int_0^1 x^n \ln^{2n}(x)dx= \Bigg[\frac{x^{n+1}}{n+1}\sum_{i=0}^{2n} (-1)^i \frac{(2n)_i}{(n+1)_i} (\ln(x))^{2n-1}\Bigg]_0^1$$
Therefore
$$\int_0^1 x^{x^x}dx=\sum^{\infty}_{n=0} \frac{1}{n!} \int_0^1\big(\ln(x)e^{x\ln(x)}\big)^ndx=
\sum^{\infty}_{n=0} \frac{1}{n!}\sum^\infty_{n=0}\frac{n^n}{n!} \int_0^1 x^n \ln^{2n}(x)dx$$
$$=\sum^{\infty}_{n=0} \frac{1}{n!}\sum^\infty_{n=0}\frac{n^n}{n!} \Bigg[\frac{x^{n+1}}{n+1}\sum_{i=0}^{2n} (-1)^i \frac{(2n)_i}{(n+1)_i} (\ln(x))^{2n-1}\Bigg]_0^1
$$
I don't know how to do the closed form  for this integral but I hope this helps
Comment: @TymaGaidash I believe one would have to use limits. I just used the Wikipedia page linked and substituted $m=n$ and $n=2n$ to the equation
Comment: $\int_0^1(\ldots)^n\,dx=\sum_{\color{red}{n}=0}^\infty\ldots$ is a mistake that ruins the rest of the answer. You should use a different index.
Comment: @metamorphy What would the rest of the answer be if a different index was used?
Comment: @TymaGaidash: Obviously, this would result in a double summation. Less useful, but *at least correct*.

Integrating $x^{x^x}$


looping through a array of hashes that nested in another array

Question: I have the following Hash with a array inside a array inside the hash. The inner array is a array of hashes. I am having trouble figuring out how to access them.
{"AssetWarrantyResponse"=>
    [{"AssetHeaderData"=>
        {"BUID"=>"11", "ServiceTag"=>"GH3RV12", "ShipDate"=>"2014-06-05T00:00:00", "CountryLookupCode"=>"US", "LocalChannel"=>"45", "CustomerNumber"=>"127963428", "ItemClassCode"=>"RK003", "IsDuplicate"=>false, "MachineDescription"=>"OptiPlex 3020", "OrderNumber"=>"631899941", "ParentServiceTag"=>nil},
      "ProductHeaderData"=>
        {"SystemDescription"=>"OptiPlex 3020", "ProductId"=>"optiplex-3020-desktop", "ProductFamily"=>"Desktops & All-in-Ones", "LOB"=>"OptiPlex", "LOBFriendlyName"=>"OptiPlex"},
     "AssetEntitlementData"=>[
        {"StartDate"=>"2022-06-07T00:00:00", "EndDate"=>"2022-06-08T00:00:00", "ServiceLevelDescription"=>"Dell", "ServiceLevelCode"=>"DL", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"999-0036"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-05T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0052"},
        {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-7368"},
        {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7738"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-6888"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7718"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0008"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9491"},
        {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9982"}
    ]}
],
"InvalidFormatAssets"=>{"BadAssets"=>[]}, "InvalidBILAssets"=>{"BadAssets"=>[]}, "ExcessTags"=>{"BadAssets"=>[]}, "AdditionalInformation"=>nil}

The following code returns the full array of hashed instead of looping through the hashes.
@hash['AssetWarrantyResponse'][0]['AssetEntitlementData'].each do |k| k['StartDate'] end

returns:
[{"StartDate"=>"2022-06-07T00:00:00", "EndDate"=>"2022-06-08T00:00:00", "ServiceLevelDescription"=>"Dell", "ServiceLevelCode"=>"DL", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"999-0036"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-05T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0052"}, {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-7368"}, {"StartDate"=>"2015-06-06T00:00:00", "EndDate"=>"2017-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"EXTENDED", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7738"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"Next Business Day Onsite", "ServiceLevelCode"=>"ND", "ServiceLevelGroup"=>5, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"UNY", "ItemNumber"=>"939-6888"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2015-06-05T23:59:59", "ServiceLevelDescription"=>"ProSupport", "ServiceLevelCode"=>"TS", "ServiceLevelGroup"=>8, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"939-7718"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"422-0008"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9491"}, {"StartDate"=>"2014-06-05T00:00:00", "EndDate"=>"2022-06-08T23:59:59", "ServiceLevelDescription"=>"Dell Digitial Delivery", "ServiceLevelCode"=>"D", "ServiceLevelGroup"=>11, "EntitlementType"=>"INITIAL", "ServiceProvider"=>"DELL", "ItemNumber"=>"421-9982"}]

Could someone point me in the right direction? I want to loop through each hash.
Comment: If you were looking to print the start date then just simply add ``puts`` behind ``k['StartDate']``
Answer: Array#each returns the original array. In calling each with a block on the "AssetEntitlementData", you'll call the block on each hash in the array, and then return the original array. If you're trying to return an array of "StartDate" values, try this:
@hash['AssetWarrantyResponse'][0]['AssetEntitlementData'].map do |h|
  h['StartDate']
end

Array#map will return an array with the result of calling the block on each element.


Is there anyway to do math on a MySQL query?

Question: I have two fields, one with the purchase date and one with the lifespan of an item. I am wondering if there is any way to determine if the current date is past the lifespan. So, pretty much if MySQL could test if current_date is > purchase_date + lifespan.
The purchase date is a date formated yyyy-mm-dd and lifespan is an integer of months. Is there any way to perform this calculation?
Comment: Need to know what is stored in `lifespan` - days, weeks, years?  Then it's a matter of using [DATE_ADD](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add)
Comment: Give it a try and see what MySQL tells you.
Comment: @OMGPonies, "lifespan is an integer of months"
Comment: It appears DATEDIFF only returns days...If you put INTERVAL field MONTHS in it it gives a Syntax error.
Comment: DATEDIFF is for days only, So I accomplished the task I needed by `code`DATE_ADD(a.date_acquired,INTERVAL  a.life_span  MONTH) < NOW()`code`  Thanks to the manual @feeela gave and to the rest of you for giving me ideas. :)
Answer: You might try:
SELECT * FROM table WHERE NOW() > (purchase_date + INTERVAL lifespan MONTH)

But you might use
SELECT * FROM table WHERE NOW() > date_add(purchase_date, INTERVAL lifespan MONTH)

Or DATEDIFF
SELECT * FROM table WHERE DATEDIFF(NOW(), purchase_date) / 30 < lifespan

Comment: This one, I believe, complains about a syntax error. Correct me if I am wrong.
Comment: @Travis, what's the syntax error? Have you tried the updated answer using `DATEDIFF`?
Comment: let me see if I can replicate it, but I think it was complaining about MONTHS and I tried MONTH too.
Comment: Opps, it's supposed to be [`MONTH`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_adddate) (with no S)
Comment: Yes it says "check manual...for the right syntax to use near MONTHS)" and if you use just MONTH it says "check manual...for the right syntax to use near )"
Comment: @Travis, you might need to use `CURRENT_DATE` in place of `NOW()`?
Comment: @Dirk let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/1389/discussion-between-travis-pessetto-and-dirk)
Answer: How about using DATEDIFF?
Your query would be something along these lines:
SELECT * FROM table WHERE DATEDIFF(NOW(), purchase_date) < lifespan

Forgive me if my syntax is a little off, I don't have an SQL instance to test on right now
Comment: I believe this one is missing the MONTHS interval and instead calculates for days.
Answer: Yes it is possible, using the MySQL date and time functions.
Comment: I think it may be possible to use DateDiff in some way
Comment: Well, what should I say. The exact answer to the question may be found within the examples on the linked manual:
`DATE_ADD('2008-01-02', INTERVAL 31 DAY);` Which then may be compared like any other value in MySQL… Are you searching for an answer, or for pre-coded-copy-and-paste-please-do-my-work-snippets?
Comment: No, I just didn't know where to look in the Manual.  The most advanced QUERYs I have done are SELECT * FROM table WHERE colum='value...with LIKE.
Comment: @Travis Pessetto: the last comment was meant to @OMG Ponies
Comment: I do like this link to the manual, because it explains the exact syntax.  At first glance of dateDiff I thought it just returned days, now it is more clear it returns what I need.


How to add field content as class in Twig?

Question: I want to add the content of a field (i.e. "workshop") as a class in field-html.twig
i tried
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'icon-' ~ item.content,
  ]
%}

but it only shows "icon-" as a class.
Comment: You know when you enable Devel's submodule Kint you can put `{{ kint() }}` to inspect variables onpage?
Answer: item.content works only in the items loop, but don't try to put rendered output in a class name. Use the field value instead, which you can get through the field object #items stored in a field template inside of the variable element:
{{ element['#items'].value }}

or from a different field of the parent entity:
{{ element['#object'].field_example.value }}

Depending on the field type replace .value with a different property, for example for a reference field to get the target id or the label of the target with .target_id or .entity.label.
When you have found the field value build your class name:
{%
  set classes = [
    ...
    'icon-' ~ element['#items'].value|clean_class,
  ]
%}

Comment: and how should i add this as a class?
Comment: replace the rendered output `item.content` with the field value: `'icon-' ~ element['#items'].value|clean_class,`
Comment: thank you, but is gives "icon-array"
Comment: You didn't provide any details what field type this is. Can you provide a kint output of the variable to see what is in it?
Comment: it's a taxonomy reference field. i'll try give asap a kint output. thx.


Meta Regression- Average AGe

Question: I want to conduct a meta-regression, using the variable.
The studies in my meta-analysis include studies, that compore two indipendent groups.
My question: to calculate average age of a study - is it enough to simply to add up the age of the two indipendent groups and divided it by two? Or are there any other, better ways to get the average age?
Comment: That will give you the average age. But what do you want to do with the average age when you've calculated it?
Comment: I would like to use it as a moderator variable, in a meta-regression.
Comment: and the two samples are usually not the same size, I guess thats a problem
Comment: I found the right solution in the meantime
Comment: Xa= population size of group A
Ya= average of group A
Xb= population size of group B
Yb= average of group B

(Xa/(Xa+Xb))*Ya + (Xb/(Xa+Xb))*Yb = Yc (the average of the combine population)
Answer: Your procedure works if the group sizes are equal. If they are not then you need
$$
\frac{n_1 \bar{x_1} + n_2 \bar{x_2}}{n_1 + n_2}
$$
where $n$ is a sample size and $\bar{x}$ is a mean.
But note that if you use this as a moderator in your meta-regression it is only an ecological analysis, you are looking at the effect of being enrolled in a study of people of a certain average age not the effect of age itself.
Comment: You need the individual data. Search for the term individual participant data meta-analysis to find out more.
Comment: Thank you very much! If I want to look at age itself, how should I proceed?
Comment: Thank you very much!

Meta Regression- Average AGe


CSHTML Razor @Html.NavItem In-Line CSS Style

Question: I'm trying to avoid a writing a CSS Class and specify a style for a @HTML.NavItem In-Line and looking for a way to do it.
@Html.NavItem("Card", "Cards", "Card", new { @class = "left-menu-item"})

I want to add display:none to this Nav Item. Couldn't find any help for this on online.
Comment: Oh, you just want to use an inline style?  Wouldn't that be the same syntax you use for the class?  Try: `@Html.NavItem("Card", "Cards", "Card", new { @class = "left-menu-item", style = "display: none;"})`
Comment: To apply a style it would either be inline or via CSS.  Why don't you want to use either of those options?  Alternatively, if your logic to show/hide is server-side then you can wrap this line in a conditional statement which checks that logic.
Comment: I want to hide it initially and then control its visibility from javascript. I'm able to control the visibility from Js but just want to hide it on load
Comment: In that case you'd either use an inline style or target it from your CSS styling (which doesn't have to be by a class, it just has to identify the element in some way).  Currently you're basically trying to use CSS without using CSS, which doesn't make a lot of sense.
Comment: I think i confused you. left-menu-item is a CSS class with few styles. I'm trying to write a inline and trying to figure out the syntax to do it.
Comment: Thank you!! When i typed in style, VS didn't recognize it and made me confused. Thanks a lot!!!
Answer: The syntax for an inline style is essentially just adding another attriute to the resulting HTML element, exactly like the class attribute you add now.  So where you have this:
@Html.NavItem("Card", "Cards", "Card", new { @class = "left-menu-item"})

You'd do this:
@Html.NavItem("Card", "Cards", "Card", new { @class = "left-menu-item", style = "display: none;"})

That anonymous object in the new { } can contain anything you like and its properties will become attributes on the resulting HTML element.  (The only reason class has an @ before it is because in C# class is already a reserved word.  This @ syntax tells C# that this is an identifier and not a keyword.)


Global IIS Issue due to Exception in Application Pool

Question: Is it possible that an exception in an aspx application of one application pool can cause problems for other application pools as well?
I have experienced problems with an IIS v7.5 where whole IIS got unresponsive after some application error and all http requests have timed out. However, the log files are not revealing much information about such an issue during the downtime.
If yes, under what circumstances might this happen?
Comment: Not an answer as such, but have you tried using something like DebugDiag (http://www.microsoft.com/en-gb/download/details.aspx?id=42933) to help diagnose the problem?
Answer: Not typically, but it depends on the reason for the exceptions, and whether the root cause is in (or is breaking) a shared resource.
In a typical, shared-nothing, default-web-site world, each W3WP has its own memory space, handle table and associated resources, and these are unique to the process. One crashes, nobody cares. (Aside: Actually, if it's really the default web site i.e. static content only, a crash would be stunningly weird and a good indicator that something really wrong is happening on the box).
If the web app chooses to use resources (say, a database table, or a file somewhere on disk) and multiple web apps consume the same resource, then a problem in one can indirectly lead to a problem in others.
For example: that massively expensive SQL query you launched in process A, which you didn't catch the timeout exception from, is still tying up the same poor database server used by processes B C and D, which are heading for a timeout too...
Or, if a web app makes HTTP calls to another App Pool on the same box, then yeah, that's a clear dependency and a clear case where there's a problem!
But generally, where there's a case where everything goes wrong all at once, if you're running more than one web application they're unlikely the cause... the cause is more likely to be some other software, 90% of the time with a kernel mode component, running on the box.
Key examples are: Stuff which relies on SMB shares (i.e. content on \server\share ), particularly when the target is a non-Windows SMB emulator (so not bug compatible) or another interesting IO filter driver is in use... which neatly brings us to antivirus and filter drivers of that nature... K-mode drivers pick up file access, reroute the request via a u-mode process which gets busy or crossed up, causing a delay on k-mode IO, causing endless fun). (Honourable mention to authentication difficulties caused by auth infrastructure outages).
Still, this is all just guesswork without any data, so the best first step is to grab memory dumps (DebugDiag or Task Manager), feed them to DebugDiag or a friendly Windbg-capable frolleague, and get them to try to identify whether there's a user-mode cause for the delay.
If there isn't, then you move to k-mode troubleshooting, and things get a bit messier (most commonly, bluescreening the box to get a k-mode crash dump while weirdness is afoot).


Karoubi envelope of a ring as a category

Question: Given a (not necessarily commutative) ring $R$. We can consider $R$ as an additive category $\mathcal R$ with one object $*$ and homomorphisms $\hom(*,*)=R$. One can form the idempotent completion of $\mathcal R$ (aka its Karoubi envelope), which is the universal category where every idempotent of $\mathcal R$ splits.
Question: What is the idempotent completion in this special case? Is there any ring-theoretic description of it? Is it, for instance, again a ring?
Comment: You may find [this](https://ncatlab.org/nlab/show/Ab-enriched+category#as_a_generalisation_of_rings) interesting.
Comment: No, it won't be a ring, unless for the pathetic ring where $0=1$, we will have at least 2 different objects in the resulting category, one for $0$ and one for $1$ (and further objects for further idempotents).
Answer: For a small category $C$, the idempotent completion can be identified with the full subcategory of presheaves on $C$ which are retracts of objects in $C$.
In your case, a functor $F:R\to Set$ is simply a set $S:=F(\ast)$ equipped with a left $R$-action. The yoneda embedding of the unique object $\ast\in R$ is simply $R$, viewed as a set equipped with the obvious $R$-action. If $S$ is a retract of $R$, then there are morphisms of lets $R$-sets $i:S\to R$ and $r:R\to S$ such that $ri={\rm id}:S\to S$.
Since $i$ and $r$ are in particular functions, $i$ must be injective. Since $i$ is a map of left $R$-sets, the image of $i$ must be closed under the $R$-action. Moreover, $i(S)$ must actually be a principal ideal in $R$, since $r:R\to S$ is surjective and therefore $i(r(1))\in i(S)$ must generate $\ i(S)$. Even more, $i(r(1))$ must be idempotent, since $rir=r$.
So the category you are looking for is the category of principal ideals, generated by idempotents in $R$, with morphisms given by $R$-module maps between them.
Notice that if you have an idempotent $e\in R$, then the corresponding map in the idempotent completion is multiplication on the left by $e$:
$$e:R\to R$$
This idempotent is split since we can take $S=eR$ and then $e=i\circ e$ and ${\rm id}=e\circ i$.
Comment: Note that an idempotent in a ring corresponds to a projection out of a direct product decomposition, which gives a somewhat more concrete description of your category: it's the category of all direct factors of $R$.


Getting same price for RDS Reserved Instance at 1yr or 3yr

Question: I was looking at pricing some reserved instances for one of our organisation's mssql DBs. When I head into the console the appropriate options, such as product (sqlserver-se), size (m5.xlarge), etc, Amazon is giving the same price for an upfront payment for 1yr & 3yr!
I'm baffled. As a test, if I select a small instance, with mssql-web it does change the price when I change between 1 & 3 yrs.
Anyone know what might be happening? I don't see any other options on the page.
Screenshot attached.
Comment: Per https://aws.amazon.com/rds/sqlserver/pricing/, `db.m5.large` (and all the other `m5` generation instances) only has one year terms listed. I do see three year terms for `db.m4` instances; I suspect they're doing away with the longer option in more recent generations.
Comment: @ceejayoz - if you put that into an answer I'll mark it as accepted.
Comment: Ah I see. That was quite puzzling. They really should display a message to say 3 yr is unavailable rather than allow selection. Thanks a million @ceejayoz!
Comment: I am curious about what happens if you purchase a three year term via the UI - whether it just drops down to a one year, or if you wind up buying three sequential. You're right - it should grey out the three year option if you select an `m5` instance.
Comment: Same here - I'm a but if a chicken giving the up front payment involved ;-)
Answer: Per https://aws.amazon.com/rds/sqlserver/pricing, db.m5.large (and all the other m5 generation instances) only has one year terms listed. I do see three year terms for db.m4 instances; I suspect they're doing away with the longer option in more recent generations.


Visual Studio: How to get name before - of a file

Question: How do I get the part before the - in the filename and put the outcome in a variable?
For example a filename: test.adress-12.txt
But I only want test.adresss
I have tried searching but couldn't find anything, only things how I can find and replace something within Visual Code itself.
Comment: Don't want to be rude, but this is very trivial case of string manipulation. If you find this hard, consider taking a course (online or not or whatever form) to learn the language
Comment: I'm voting to close this question because the answer is very trivial. It show either a lack of understanding the language or a lack of minimal research to find the answer
Comment: Seems like you also didn't read my question as well that I have searched but didn't find my answer. I would never open a question without searching first. Only this time I couldn't find and that's probably because of using wrong search terms at the time the term "split" didn't came to me. To to be fair I think you are rude! How hard is it to give someone with a question a push in the right direction. My normal language isn't VB but unix related and this time I needed to change something in an existing vb project.
Comment: Since I needed it in more places then I thought I put it in a function.
```Shared Function nodash(ByVal value As String) As String  Return value.Replace("-", "")  End Function```
And yes I never can get the formatting right here whatever I try for parts of code.
Answer: If you always know there will be a single - and you are using C#, then you can use string.Split('-') and take the 0th element.
C#
string fileName = "test.adress-12.txt";
string[] results = fileName.Split('-');
string result = results[0];

Here is the VB documentation for Strings.Split and here is an example of the same code in the C# example converted to VB.
VB
Dim fileName As String = "test.adress-12.txt"
Dim results As String() = fileName.Split("-"c)
Dim result As String = results(0)

Comment: I'm only using VB and not C#
Comment: Converted it with a code Converter:
`Dim fileName As String = "test.adress-12.txt"
Dim results As String() = fileName.Split("-"c)
Dim result As String = results(0)`


How to filter webform results

Question: Can someone kindly tell me how to filter the webform results page? For example how can I show only the submissions where column X has value Y.
I am new to drupal but I am an experienced PHP programmer. If someone kindly points out he right webform hooks I will try to figure out the rest.
Suprisingly, google could not help me. But I'm sure that others have faced the same problem before. Please assist.
Answer: I am not sure if you still need this information, but for the benefit of others...

You might want to look into the webform_mysql_views module.
If you are using drupal 7+, you can create a simple view of the "Webform Submissions" type. Then, under Fields you should be able to find Webform Submissions: Data Value field. Select that and then add the field you want to show up in your table. Do this for the rest of the fields you want. Finally, add the filters and/or sorts the very same way. NOTE: You might have to add a relationship (the very right drop-down) or two to show you relevant results.

Hope this helps!
Answer: There is a Drupal contrib module called Webform Selectable Filters that extends views which will help you to create a view with dropdown list exposed filters instead of textfields.

Download: https://www.drupal.org/sandbox/neschi/2522034
Step by step guide: http://www.neschi.com/blog/webform-selectable-filters

How to filter webform results


Finding local maximum of f(m,n)

Question: Let $ n,m \in \mathbb{N} \text{ and } m \geq n \gt 1$
Let $ f(n,m) = \frac{m-n+1}{2(n-1)}$ and therefor:
$\frac{\partial f}{\partial m}(m,n) = \frac{1}{2(n-1)}$
$\frac{\partial f}{\partial n}(m,n) = -\frac{m}{2(n-1)²}$
Since the two partial derivatives do not have a solution such that they both equal to zero, how can I get the local maximum? Is there a problem in my reasoning?
Thanks in advance
Comment: Which reasoning?
Comment: Is it even possible in this situation to find a local maximum, or it is not defined?
Comment: Why not? The sequence $\left(\sqrt[n]n\right)_{n\in\mathbb{N}}$ has an absolute maximum at $3$, although $x^{1/x}$ has non-zero derivative at $3$.
Comment: But how would one calculate such a maximum in that case?
Comment: For $m=0$ it is a constant $-1/2$; Further differentiation determines if it is maximum, minimum etc.
Comment: It follows easily from the fact that $x^{1/x}$ increases in $(0,e)$ and decreases in $(e,\infty)$.
Answer: If your domain is discrete, then you have to define the notion of "local." One way to think of it is the $8$ lattice points/neighbors that surround the given point $(m,n)$ and then you can say $(m,n)$ is a local maximum if it's greater than or equal to those $8$ values $f$ is evaluated at. But that would not work because incrementing $m$ by $1$ will always increase your function.
More generally, there is no such notion even if you extend the immediate neighborhood to a greater a raduis because $f$ is strictly increasing in $m:$
$$f(m+1,n) - f(m,n) = \dfrac{1}{2(n-1)} > 0.$$
As a last resort, it might be possible to define some weird, discrete topology for which a neighborhood of $m$ does not include $m+1,$ but I am not aware of such things.
Comment: Yes I guess I meant more like a global limit. The thing is I can think that it is certainly n = 2 and m = +inf, just dont really see how to formally prove it, considering all the caveats

Finding local maximum of f(m,n)


How is such an instrument called?

Question: Recently we took an empty Pringles chips can (a long cylinder), filled it with groats and now can use it to play rhythms or imitate the sound of rain. How is such an instrument called and where could I read more about playing it?
I've heard about rainsticks, can my thing be called so?
Answer: It falls into the large family of 'shakers'.
'A rainstick is a long, hollow tube partially filled with small pebbles or beans that has small pins or thorns arranged helically on its inside surface. When the stick is upended, the pebbles fall to the other end of the tube, making a sound reminiscent of rain falling.'
If you feel your instrument matches that specification, by all means call it a rainstick.  Does it give a gradual 'rain falling' effect when inverted?  If it lacks this defining feature of a rainstick - the internal obstructions that delay the contents from moving all at once - and needs constant shaking maybe better to call it just a shaker.

How is such an instrument called?


vulnerability issue in ASP.NET

Question: In our vulnerability report there is one vulnerability which I have mentioned below.
"it was found that the Microsoft ASP.NET validate Request filters could allow a remote attacker to bypass it's filters and conduct cross-site scripting attacks using a less-than slashand less-than tilde slash (<~/) sequence. These vulnerabilities are described in CVE-2008-3842 and CVE-2008-3843."
We are using windows server 2008r2 service pack1 enterprise edition. Our current .Net framework is 4.0.30319 and  for creating  application pool we are using .Net framework 2.0.50727 because this is the developer requirement.
Please suggest your opinion to resolve this issue.
Answer: Microsoft has yet to actually confirm this issue it seems as far as I know but it's best to filter data yourself. They're just saying if you rely on native built-in XSS protection, you may be disappointed.
As for how to protect against XSS:
OWASP covers XSS well here, even with a prevention sheet, but the rule of thin is to just not trust user input to any real degree and implement checks and filtering to ensure whatever they enter is what they're supposed to enter (e.x. %s and

tl;dr best practices in your code means this vulnerability is of minimum impact to you. Poor practices means you may have an XSS vector on your hands. Whoever is running the site should just be aware of how to avoid XSS vectors.
Comment: Also in the future this MIGHTTT be better off in security stack exchange

vulnerability issue in ASP.NET


Windows CA Certificate Request via Commandline

Question: I have a non-domain PC (windows 7) attempting to obtain a cert from a Windows 2008 R2 Enterprise CA. I have the root ca and crl's installed on the non-domain client.
I'm working on a script that will create a certificate request file (.inf), take that request file and turn it into a .req binary, and then submit to a CA. How would I go about submitting the a certificate request via the command line? I've tried using the command below but it errors with "The certificate authority is invalid or incorrect 0x80072f0d (Win32: 12045).
certreq -submit -Username domain\user -p password -PolicyServer "https://192.168.1.10/ADPolicyProvider_CEP_Kerberos/service.svc/CEP"  -config "https://192.168.1.10/caname_CES_Kerberos/service.svc/CES"  -attrib "CertificateTemplate:Computer"  C:\cert1.req C:\cert.cer

Answer: I found the answer. This command will submit BinaryRequest.req to the CA (which is set to autoenroll) and save it as newcert.cer
certreq -submit -f -config "192.168.1.10\caname" BinaryRequest.req newcert.cer


Fourier serie property for $\sum_{n=1}^\infty \frac{1}{n^2}=\frac{\pi^2}{6}$

Question: If $$f(x) \sim \frac{1}{2} a_0 + \sum_{n=1}^\infty (a_n\cos nx+b_n \sin nx)$$
For $x\in[0,2\pi)$, how can I show that:
$$ \sum_{n=1}^\infty \frac{b_{n}}{n} = \frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x) f(x)\,dx$$
Find the Fourier coefficients of $f(x)=\pi -x$, $x\in[0,2\pi)$ and deduce that (using the first part of this problem):
$$\sum_{n=1}^\infty \frac{1}{n^2}=\frac{\pi^2}{6}$$
I do not know how to prove this, I tried computing the coefficients of the series but I am really mess with this proof. Please if you can, help me.
I tried this but I do not know if it is correct...
And for the other part I tried this:
Comment: I assume they will want you to integrate by parts then to deduce the result. Just replace the $f(x)$ in the integral with your summation formula for Fourier series.
Comment: I'm not sure what the question is?
Comment: Ok, let me edit for be more specific
Comment: Why are you computing the integral of $(\pi - x) f(x)$? Your $f(x) = \pi - x$. You should be integrating $(\pi - x) \sin(nx)$ and $(\pi - x) \cos(nx)$ to find the coefficients.
Comment: This is an exercise form sneddon Fourier analysis I copied and this is why I do not understand, it is from chapter 3 ex. 2
Answer: As Mattos said, You need to calculate:
$\frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x) f(x)\,dx$, by substituting into this integral,
$f(x) =\frac{1}{2} a_0 + \sum_{n=1}^\infty (a_n\cos nx+b_n \sin nx)$
Use integration by parts for the xcosnx and xsinnx terms.
You should get $\sum_{n=1}^\infty \frac{b_{n}}{n}$ as a result (everything else will cancel).
Then for the second part, after you get the fourier terms of $f(x)=\pi-x$, substitute $f(x)=\pi-x$ and the $b_n$ formula into
$\sum_{n=1}^\infty \frac{b_{n}}{n} = \frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x) f(x)\,dx$
Evaluate the integral on the right hand side, and do a little simplification and you should get:
$\sum_{n=1}^\infty \frac{1}{n^2}=\frac{\pi^2}{6}$
EDIT, here's the integral for the first part:
I'll calculate the integral in pieces. First the $a_0$ term:
$\frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x)(\frac{1}{2}a_0)\,dx$
$=\frac{a_0}{4\pi}\int_{0}^{2\pi}(\pi -x)dx$
$=\frac{a_0}{4\pi}(\pi x -0.5x^2)$ (from 0 to 2$\pi$)
$=0$
Now the $a_n$ part:
$\frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x)a_ncos(nx)\,dx$
$=\frac{a_n}{2\pi}\int_{0}^{2\pi}(\pi -x)cos(nx)\,dx$
$=\frac{a_n}{2\pi}\int_{0}^{2\pi}\pi cos(nx)\,dx-\frac{a_n}{2\pi}\int_{0}^{2\pi}x cos(nx)\,dx$
The first integral goes to 0. So we have:
$=-\frac{a_n}{2\pi}\int_{0}^{2\pi}x cos(nx)\,dx$
Use integration by parts
$u = x$
$dv = cos(nx)dx$
this gives $v = \frac{1}{n}sin(nx)$
So using $\int udv = uv - \int vdu$
We have:
$\int_{0}^{2\pi}x cos(nx)\,dx = \frac{x}{n}sin(nx)$ (from 0 to $2\pi$) - $\int_{0}^{2\pi}\frac{1}{n}sin(nx)\,dx$
this comes out to 0.
Now the $b_n$ part:
$\frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x)b_nsin(nx)\,dx$
$=\frac{b_n}{2\pi}\int_{0}^{2\pi}(\pi -x)sin(nx)\,dx$
$=\frac{b_n}{2\pi}\int_{0}^{2\pi}\pi sin(nx)\,dx-\frac{b_n}{2\pi}\int_{0}^{2\pi}x sin(nx)\,dx$
The first integral goes to 0. So we have:
$=-\frac{b_n}{2\pi}\int_{0}^{2\pi}x sin(nx)\,dx$
Use integration by parts
$u = x$
$dv = sin(nx)dx$
this gives $v = -\frac{1}{n}cos(nx)$
So using $\int udv = uv - \int vdu$
We have:
$\int_{0}^{2\pi}x sin(nx)\,dx = -\frac{x}{n}cos(nx)$ (from 0 to $2\pi$) + $\int_{0}^{2\pi}\frac{1}{n}cos(nx)\,dx$
this comes out to $-\frac{2\pi}{n}$.
So:
$-\frac{b_n}{2\pi}\int_{0}^{2\pi}x sin(nx)\,dx = (-\frac{b_n}{2\pi})(-\frac{2\pi}{n}) = \frac{b_n}{n}$
Now just add the summation sign.
EDIT For the second part, calculate
$\frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x)^2\,dx$
$\frac{1}{2\pi}(\frac{x^3}{3}-\pi x^2+\pi^2x)$ evaluated between $2\pi$ and 0.
This comes out to:
$\frac{1}{2\pi} (\frac{8\pi^3}{3}-4\pi^3+2\pi^3)$
$=\frac{\pi^2}{3}$
$f(x) = \pi-x$, calculate fourier components
$a_0 = \frac{1}{\pi}\int_{-\pi}^{\pi}(\pi-x)dx$
$a_0 = 2\pi$
$a_n = \frac{1}{\pi}\int_{-\pi}^{\pi}(\pi-x)cos(nx)dx$
$a_n = 0$
$b_n = \frac{1}{\pi}\int_{-\pi}^{\pi}(\pi-x)sin(nx)dx$
$b_n = -\frac{sin(nx)+n(\pi-x)\cos(nx)}{\pi n^2}$ (evaluation at $\pi$ minus evaluation at -$\pi$)
$b_n = \frac{2}{n}$
So finally, substituting into:
$\sum_{n=1}^\infty \frac{b_{n}}{n} = \frac{1}{2\pi}\int_{0}^{2\pi}(\pi -x) f(x)\,dx$
we have
$\sum_{n=1}^\infty \frac{2}{n^2} = \frac{\pi^2}{3}$
divide both sides by 2
$\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}$
Comment: Instead of doing the whole integral at once which would be a big mess... I'm splitting it up into three parts which get summed.
Comment: I've edited my answer with the solution for part 2.
Comment: I've edited my answer.
Comment: I got that the integral that you put not the b_n's is 4/3 pi^2 - 2 pi^3 + pi^4
Comment: And the b_n = 1/n then when I sum this is equivalent to the serie 1/n^2 but it is not clear why 4/3 pi^2 - 2pi^3 + pi^4 = pi^2/6?


How to find a function with given requirements?

Question: I am trying to come up with a function $f(x): \mathbb{R} \to \mathbb{R}$ which satisfies following requirements:

$f(x)$ is continuous and differentiable
$f(x) \ge 0$ for every $x$
$f(x) = h \cdot b^x$ for every integer $x$ ($h, b \in \mathbb{R}, h \gt 0, 0 \lt b \lt 1$)
$f'(x) = 0$ for every integer $x$
$f(x) = 0$ for every $x \in \{0.5, 1.5, 2.5, 3.5, ...\}$

I came up with $ f(x) = h \cdot b^x \cdot \frac{\cos{2\pi x} + 1}{2} $ by intuition. Even though it satisfies requirements 1, 2, 3 and 5, it fails at the requirement 4.
So what would be a correct approach to this problem? Also, what would be a correct approach to problems of this type in general? Thank you.
Answer: You can change your guess a bit to obtain a function satisfying the properties:
$$ f(x) = hb^{\lfloor x+\frac{1}{2}\rfloor} \cos^2(\pi x). $$
The discontinuities of $hb^{\lfloor x+\frac{1}{2}\rfloor}$ at half-integers do not matter, because the derivative of $\cos^2(\pi x)$ vanishes at those points. Below is the picture of the graph of $f$ and $f'$ when $h = 1$ and $b = 1/2$.
Comment: That is an interesting solution and it perfectly suits the purpose. Thank you!


Disable login at all

Question: I want to disable login at all on my drupal site, even better also hide the form. If i need login i will enable it from a ssh session and after working disable again.
I will prefer to do this with rewrite rules in .htaccess but i cannot figure out the right rule.
Update (as this seems to be a popular question)
I ended up with .htaccess like this:
 # disable well known Drupal user login endpoints
  RewriteCond %{QUERY_STRING} q=user
  RewriteRule ^/?$ http://%{HTTP_HOST}/? [R=307,L]
  RewriteRule ^user$ http://%{HTTP_HOST}/ [R=307,L]
  RewriteRule ^user/register$ http://%{HTTP_HOST}/ [R=307,L]

  # goto user login with that "secret" URL
  RewriteRule ^op9__P87? /user [NC]

Comment: This can be a little complicated, depending on your setup.  Where can users login from?  Just /user or also is the login form on /admin and other pages?
Comment: It is just /user and /?q=user
Answer: Another way is set the access to false to the login form. Whenever you want to re-enable the login, just comment out the hook.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#access'] = FALSE;
  }
}

Answer: Maybe the Login Disable module will help?

Prevent users from logging in to your Drupal site unless they know the secret key to add to the end of the ?q=user login form page. If a user does find out about the secret key they will still have their user account role checked during authentication .If they do not have the 'bypass disabled login' granted they will be refused access and displayed a customisable "denied" message.
Comment: http://drupal.org/node/19855 this shows how to remove the form altogether.
Comment: That shows the form. It will even better not show the form at all ...
Answer: The problem is more of a Apache config issue, rather than a Drupal issue.  It also relies on the user login form just being on one page.
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().

RewriteRule ^user$ - [G,L]
RewriteRule ^q=user$ - [G,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

The q=user rule may require some tweaking, as an artificial URL with q=user in it will end up at the login page.
Note, that there are a few modules that disable user login (such as @Jonathan Rowny suggests), which may be a better option, depending on your scenario.
Answer: You can use Disable Login module to disable the login page, and secure it with secret key.
Ref: https://www.drupal.org/project/disable_login

Disable login at all


Nginx: Redirect a IP range to a file if it exists

Question: I want to redirect users to a maintenance.php file if it exists, but not our internal address.
Now i got this working through if-statements, but these are considered evil within the location block..
This is the config now:
<code>if (-f $document_root/maintenance.php) {
    return 503;
}

error_page 503 @maintenance;

location @maintenance {
    if ($ourips = 0) {
        rewrite ^(.*)$ /maintenance.php last;
    }
    if ($ourips = 1) {
        rewrite ^(.*)$ /app.php/$1 last;
    }
}

location / {
    # try to serve file directly, fallback to rewrite
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    # rewrite all to app.php
    rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|clear|maintenance)\.php(/|$) {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;
}
</code>
Any alternative way to do this without the two if-statements in location @maintenance?
Answer: Got it working, uses some if's but they shouldn't be evil in this context as far as i'm aware..
<code>    if (-f $document_root/maintenance.php) {
            set $test A;
    }
    if ($ourips = 0) {
            set $test "${test}B";
    }
    if ($test = AB) {
            return 503;
    }

    error_page 503 @maintenance;

    location @maintenance {
        rewrite ^(.*)$ /maintenance.php last;
    }
    location / {
            # try to serve file directly, fallback to rewrite
            try_files $uri @rewriteapp;
    }
    location @rewriteapp {
            # rewrite all to app.php
            rewrite ^(.*)$ /app.php/$1 last;
    }
    location ~ ^/(app|clear|maintenance)\.php(/|$) {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
    }
</code>
nginx.conf
<code>    geo $ourips {
      default 0;
      xxx.xxx.xxx.xxx 1;
    }
</code>


Four (simple) questions on real number series

Question: I'm trying some exercises on real number series, in which I have to see if the series are convergent or not:
$$a) \sum_{n=1}^\infty \ (-1)^n \frac{2n+1}{3^n}$$
$$b) \sum_{n=0}^\infty \ (-1)^{n+1} \frac{1}{(n+1)(2n)!}$$
$$c) \sum_{n=1}^\infty  \ \frac{1}{n} - \ln(1+ \frac{1}{n})$$
$$d) \sum_{n=1}^\infty \sin \frac{1}{n(n+1)}$$
For the first three series I've found that:
a) is divergent (solved it using both the ration criterion and Dirichlet criterion as to verify the $1^{st}$ solution);
b) is divergent (solved same as $a)$);
c) is convergent (solved using the ration criterion).
For these three I'm not sure of my results and I hope that somebody here would point out if I'm mistaken regarding any of them. If that's the case, then I would kindly ask for an idea/ steps of a solution.
At last,
d) I've no idea how to solve it. I'd be very grateful if anyone could offer a solution for it, or just the main steps.
Thank you in advance!
Comment: All four series are _absolutely_ convergent.
Comment: @DanielFischer Well, crap... could you also provide some step solutions?
Comment: But (3) doesn't response to ratio cri.
Comment: @MyGlasses Then what criterion would you suggest? Dirichlet?
Comment: This series is gamma euler.
Answer: All four of these series are absolutely convergent.
For $n \geqslant 3$ we have $2n+1 < 2^n$, so the term of the first series is majorised by $\bigl(\frac{2}{3}\bigr)^n$, and comparison with a geometric series shows absolute convergence.
We have $\frac{1}{(n+1)(2n)!} \leqslant \frac{1}{(n+1)!}$ since $n! \leqslant (2n)!$, and comparison with the exponential series shows absolute convergence.
For $x > 0$ we have
$$0 < x - \ln (1+x) < \frac{x^2}{2},$$
so comparison with $\sum \frac{1}{n^2}$ shows the convergence of the third series.
We have $\lvert \sin x\rvert \leqslant \lvert x\rvert$ for all $x\in \mathbb{R}$, so comparison with $\sum \frac{1}{n(n+1)}$ shows the convergence of the last series.
Comment: I had no idea about the relation between sin and abs. Thank alot, mate!
Comment: One could say so. Since I argue for absolute convergence, I (tacitly) look at the absolute value of the terms. For the first two series that amounts to dropping the $(-1)^n$ resp. $(-1)^{n+1}$, for the last two, it amounts to nothing since the terms are positive anyway.
Comment: Quick question: For a) and b), when contructing the comparison series, did you just elude the $(-1)^n$


MVC Application using ADFS 3.0 and ARR URL Rewrite getting incorrectly redirected after authentication

Question: I have pretty much the same problem as mentioned in this question
SSO ADFS redirection issue with reverse proxy with ARR. However, I have tried the solution without success. The 302 from ADFS still goes to the private site instead of public.
I have also tried using wreply to explicitly define the public endpoint. I checked using browser Debug Tool and I can see that the ADFS request has the correct wreply value, however, redirection from ADFS is ignoring this.
I have verified the RP identifier in ADFS and it is correct.
Everything works fine in local environment when I host both the proxy and application in a single server and use the same ADFS endpoint for SSO.
The redirection from ADFS also works fine when I use idpinitiated sigon to login to the application.
Where could I be going wrong?
Answer: ARR changes the base URL after authentication happens. You need to restore the ADFS Base URL. I made it working using below ARR Rules.
You can use ADFS Rule mentioned in below rule set
<code><rewrite>
      <rules>
        <clear />
        <rule name="ApplicationRule" stopProcessing="true">
          <match url="^dnApplication/?(.*)" />
          <action type="Rewrite" url="https://application.cloud.azurewebsites.net/dnApplication/{R:1}" logRewrittenUrl="true" appendQueryString="true" />
        </rule>
<rule name="AdfsRule" stopProcessing="true">
          <match url="^.*adfs/?(.*)" />
          <action type="Redirect" url="https://gfs.private.companyName.com/adfs/{R:1}" logRewrittenUrl="true" />
        </rule>
</rules>
      <outboundRules>
        <rule name="RedirectToHomeDNS" preCondition="3xx Redirect">
          <match serverVariable="RESPONSE_LOCATION" pattern="^https://application-dv1.azurewebsites.net/" />
          <action type="Rewrite" value="{HTTP_URL}" />
        </rule>
        <preConditions>
          <preCondition name="3xx Redirect">
            <add input="{RESPONSE_STATUS}" pattern="3[0-9][0-9]" />
          </preCondition>
        </preConditions>
      </outboundRules>
    </rewrite>
</code>


What type of In-App Purchase choose for removing ads for one of iOS game app

Question: I have implemented ads in one of my game apps and its free but I want to make a in-app purchase feature to remove ads
now i don't have any idea about which type of IAPs option to choose (Consumable, Non-Consumable, Automatically Renewable Subscriptions, Free Subscription, Non-Renewing Subscription). also how much do i need to charge for that.
So can someone helps what kind of in-app purchase is suitable for above and also according to Apple Rules regarding in-app purchase.
Answer: You want a non-consumable in-app purchase. This means that the user only has to purchase it once, and they then own it forever (regardless of deleting & re-installing the app).
However, it doesn't seem like your that familiar with the workings of in-app purchases, so I suggest you have a good read of the Apple docs on it.
When it comes to pricing, that's entirely up to you.


Homework question: get probability from distribution / table

Question:
Josefina is the star athlete on her college soccer team. She especially loves to score goal(s), and she does this on a regular basis. Suppose, the random variable X = the number of goals Josefina will score tonight. The probability distribution of X is given.
<code>X       0       1       2       3
P(X)    0.25    0.35    0.25    0.15
</code>
The probability that Josefina will score fewer than 1 goals tonight is _____.

I'm definitely getting stuck at all of it. I need help figuring out how to get the answers I need. This is a homework question, but I need to know how to figure it out.
Comment: Then please edit the question to 1) focus on the question itself without the extraneous details.  2) Tell us what you have tried, what your understanding of the question is, and where you are getting stuck.  3) Add the self-study tag.
Comment: @Nick It's difficult to see where any such formula would come from.  The probabilities are given by the table in the question, not by a formula.
Comment: Either the answer to this is really, really simple or there is some detail which you are not showing us. Or I have misunderstood.
Comment: It is homework, what I'm wanting is the steps to how I get the answer.
Comment: This appears to meet our standards now.
Comment: Sorry, I was wondering how to figure out how many goals she will get?
Comment: Is it the question from before (that I put back in the text)?
Comment: yes, I don't just need an answer, I was hoping for step by step, because I'm not understanding when I read it.
Comment: @Misty, you can begin from the detection of distribution law which correspond to your table. Then re-write your question in probability terms. like this, $P(X<1)=C_n^m p^m q^{n-m}$
Comment: @mdewey It's just a simple homework problem.
Answer: Here's a hint. In order to make fewer than 1 goal, how many goals would she have to make? If you can answer that question, it's just a matter of understanding what the table says.
Comment: In order to make **fewer than 1 goal**, how many goals would she have to make?
Comment: would that be .25+.35?
Comment: You don't count 1, you just take .25?
Comment: Yes, because 1 is not less than 1.


Fingerpicks - which styles are they used for?

Question: I'm currently learning how to use fingerpicks, like these:

The exercises I found are all blues or bluegrass related. I really like the strong sound and speed potencial, but I am more into the mainstream music, not blues.
So I have a question: are fingerpicks used for any other style besides blues and why are they used at all?
Comment: @Hubert Czerski, no, picture has correct fingerpick position
Comment: Shouldn't your 3 fingerpicks (not thumbpick) be worn opposite. In the same place You have fingernails??
Comment: This is news to me too, however I admit to never trying finger picks.  So is the pick attack from an outward flick motion, as opposed to an inward clawing motion?
Answer: Finger picks are used as a preference. Players such as Chet Atkins had a very famous style of picking, where he mainly used a thumb pick I believe (check out Stairway to Heaven by Hayseed Dixie, Mr Sandman by Chet Atkins) Players like Jeff Beck use their fingers mainly, which he has developed a neat playig style. Then about everyone else uses a pick, because it's probably the easiest. So it all depends on your preferences / what you're playing. You could also use your pick and fingers at the same time, and that is done by holding the pick between your thumb and index finger and then using the other three to pluck the strings.
Comment: "Players like Jeff Beck use their fingers mainly". Beck used a pick for years and years, but was adept with his fingers. According to an interview with him, he said he dropped the pick during a concert one night and finished a song without it and decided he wasn't going to bother with it. But, then again, he's Jeff Beck.
Answer: The benefit of using a pick is a louder attack, which is really important when you're purely unamplified and near other, often louder instruments, and where the attack of the note is crucial. Dobro and banjo players are really top ones here, and I understand it's big for pedal steel players.
Classical and flamenco players pick with fingernails, but nylon strings are easier on fingernails than steel strings. I've heard fingerstyle players talk about superglueing slivers of ping pong balls to their fingernails to have something replaceable and more able to withstand the strings, yet more stable on the finger than fingerpicks.
There are players who just use a thumbpick. Nils Lofgren plays rock with a thumbpick and fingers. With electrical playing, especially rock playing, it seems like the benefits of fingerpicks are not more easily handled by amplification. For hybrid playing, picks are allowed but not necessary.
Comment: When playing on thinner strings from electric and steel-string acoustic you don't need to have as lengthy fingernails to have the same "nail attack" like you would have nylon.
Answer: Fingerpicks are used instead of fingernails. I don't think many (or any) classical guitarists use them, but some steelstring guitar players do(blues/bluegrass). Fingerpicks are basically used to get that nail type sound without destroying your nails. As you see on many classical guitarists they have very long nails, sometimes fakenails, which allow them to get a differnet sound. Fingerpicks could be used to get somewhat the same sound...(a bit too general)
As you are more into mainstream music I would suggest putting down the fingerpicks and use your fingers or a pick instead.
Answer: With the caveat that I seem to be kind of an outlier, I'll weigh in: I learned to play guitar starting on a cheap Stella 12-string and copying Lead Belly from old records, so I got accustomed early to using a single index-finger pick and a thumb pick.  I did occasionally use a pick on the middle finger, but on things like Mississippi John Hurt songs it seemed better just to ditch picks altogether for 3- or 4-finger picking.  But at age 68, after using thumb-and-index picks for 53 years, I use them on EVERYTHING sometimes (still prefer bare fingers, but sometimes you have to poke out of loud mixes)---12-string; 6-string; electric (yes, Strat---not super-lightly strung, though---I use .011-.049); bass (yep); banjo; everything.  It does get some interested strange looks from people when I play in public. So from my POV, I'd answer you by saying fingerpicks CAN be used in any style.  Whether you like the result is a matter of personal taste! (I'll invite you, if you like, to check out any of my videos on YouTube---I've got something like 420---that involve this 2-pick method, which is most of them.  On none do I use a third pick, and never just thumb pick with bare fingers.  I'm "Alonzo Garbanzo" there. If you do, you can judge for yourself how effective it is!)  Hope this is at least a tiny bit helpful.


Geometric/Clifford algebra - intuition behind this derivation of a formula that recovers a rotor from a vector basis and its transformation

Question: This short manuscript by Francisco G. Montoya presents and proves a general formula that gives the rotor (up to a sign change) that effects a certain rotation transformation, from a given vector basis and its rotated image. Although I could follow the steps, I can't see how one would come up with summations (3) and (6) as starting points out of the blue. Is there a certain intuition that could take us from the defining equations of a rotor transformation ($u \to R u R^\dagger$) to the summations presented?
The author begins with summation (3), given by
$$\sum_{k=1}^n \sigma_k R^\dagger \sigma_k \quad,$$
where the $\sigma_k$ are the original, non-rotated basis vectors, and
$$R^\dagger = \alpha - \sum_{i<j}^n \beta_{ij} \sigma_{ij} \quad,$$
just the definition of a rotor.
He shows that the first summation is
$$\sum_{k=1}^n \sigma_k R^\dagger \sigma_k = 4 \alpha + (n-4) R^\dagger \quad.$$
He then forms
$$\sum_{k=1}^n\mu_k \sigma _k = R \sum_{k=1}^n \sigma_k R^\dagger \sigma_k = 4\alpha R + (n-4) \quad,$$
where the $\mu_k$ are the rotated $\sigma_k$. So
$$4\alpha R = \sum_{k=1}^n\mu_k \sigma _k  + (4-n) \quad,$$
which means $R$ is a scalar multiple of $\sum_{k=1}^n\mu_k \sigma _k  + (4-n)$ (remember that $\alpha$ is the scalar part of $R$). Enforcing the constraint that $\lVert R \rVert = 1$ means that
$$R = \pm \frac{\sum_{k=1}^n\mu_k \sigma _k  + (4-n)}{\lVert \sum_{k=1}^n\mu_k \sigma _k  + (4-n) \rVert} \quad.$$
(I included the $\pm$).
My question boils down to what thought process sensibly connects a rotor's definition and action on a vector to conjuring up the summation
$$\sum_{k=1}^n \sigma_k R^\dagger \sigma_k \quad,$$
which is the key to the whole proof. I could see how one might come up with the second summation, $\sum_{k=1}^n \mu_k \sigma_k$, after having been presented the first one, but it still looks like a fairly non-obvious development.
Comment: You should write the formula and the relevant steps in your question.
Comment: I could speculate, but it seems like the only way to get the right answer would be to ask the author what the original inspiration was.
Comment: @MarkS. Anything that might bridge my gap in intuition is welcome.
Comment: @NicholasTodoroff Edited the question as requested.
Comment: This formula can't actually be true. Consider $$R = e^{\theta_1e_1e_2 + \theta_2 e_3e_4} = e^{\theta_1e_1e_2}e^{\theta_2e_3e_4}$$ in 4D. This rotation has a pseudoscalar part, not just a bivector part, contradicting the crucial assumption that $R$ is a sum of a scalar and bivector. We could restrict to such rotors, but that seems pretty useless in high dimensions.
Answer: Here is a somewhat weird way to see this. I don't consider this intuitive, so this is more of a long comment than an answer.
Write $R = \alpha + B$; then
$$
  \sum_k\mu_kR^\dagger\mu_k = \nabla R^\dagger x = n\alpha - \nabla Bx = n\alpha - (n-4)B = nR^\dagger - 4(R^\dagger - \alpha) = (n-4)R^\dagger + 4\alpha
$$
The reason the first equality holds is because the basis $\sigma_k$ is its own reciprocal, because it is orthonormal. For any basis $e_k$ with reciprocal $e^k$ and any bilinear function $F({-},{-})$ we always have
$$
  \sum_k F(e^k, e_k) = F(\nabla, x).
$$
If $A_r$ has grade $r$ and is constant, the identities used above look like
$$
  \nabla x = n,\quad \nabla A_rx = (n-2r)\hat A_r
$$
where $\hat A_r$ is grade involution. The last one can be proved using the more basic identity
$$
  \nabla(x\cdot A_r) = (A_r\cdot\nabla)x = rA_r
$$
and then by differentiating
$$
  x\cdot A_r = \frac12(xA_r - \hat A_rx).
$$
These identities can be found starting on page 51 in Clifford Algebra to Geometric Calculus by Hestenes and Sobczyk.

Actually, this shows us that the formula is more general. Let $\mu_k$ and $\sigma_k$ be arbitary (not necessarily orthonormal) and let $\mu^k$ and $\sigma^k$ be their reciprocals. Then $\mu_k = R\sigma_kR^\dagger$ and $\mu^k=R\sigma^kR^\dagger$. Now consider
$$
  \sum_k\mu^k\sigma_k = \sum_kR\sigma^kR^\dagger\sigma_k = R\nabla R^\dagger x = 4\alpha R + (n-4)
$$
so finally
$$
  R \propto 4 - n + \sum_k\mu^k\sigma_k.
$$
We can actually turn this into a matrix computation. Let $G_{ij} = \mu_i\cdot\mu_j$ be the Gram matrix for $\mu_k$, and express $\sigma_k, \mu_k$ in terms of an orthonormal basis $e_k$ (like the standard basis) so that we get matrices with columns $\Sigma = (\sigma_1,\dotsc,\sigma_n)$ and $U = (\mu_1,\dotsc,\mu_n)$. Form the matrix
$$
  \Gamma = UG^{-1}\Sigma^T.
$$
Then the scalar part of $R$ is
$$
  4 - n + \mathrm{Tr}(\Gamma)
$$
and the bivector part is
$$
  \sum_{i<j}(\Gamma - \Gamma^T)_{ij}e_ie_j.
$$


Como criar uma base de dados automaticamente no Laravel com todas as tabelas?

Question: Bem eu preciso de ajuda em um problema, estou desenvolvendo um sistema pela primeira vez em laravel e eu precisaria criar uma base de dados para cada usuário cadastrado no meu sistema, essas base devem ter as mesmas tabelas eu já descobri com alternar a consulta para cada base mas não sei como criar uma base nova já com todas as tabelas automaticamente, já tenho a base com os usuários e nessa base vou guardar qual a base de dados de cada usuário nessa base dos usuários, eu estou usando sqlite atualmente durante o desenvolvimento. Por favor alguém me ajude ou me explique se tenho que fazer de outra maneira. E se possível gostaria de saber com executar migrate em todas as base ou em varias de uma vez.
Comment: Acho que podes começar por perceber bem o que queres: https://www.youtube.com/watch?v=EDNYywKZ6jc
Comment: perfeito esse vídeo cara ajudou muito
Comment: Parece um requisito bem fora do comum, verifique se não está passando pelo caso do  ["problema xy"](https://pt.meta.stackoverflow.com/questions/499/o-que-%C3%A9-o-problema-xy)
Answer: Espero ajudar:
Toda a documentação do Laravel se encontra aqui: https://laravel.com/docs/5.8/installation
Para criar migration, utilize o seguinte comando:
php artisan make:migration create_nomedatabela_table

Ao criar a migration, você vai notar que será criado as funções up() e down().
Na função up(), você colocará os campos da tabela. Abaixo um pequeno exemplo:
public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

Depois de todas as migrations criadas, para rodá-las use:
php artisan migrate

A documentação do laravel referente a migrations está aqui: https://laravel.com/docs/5.8/migrations

==============================================================================
Uma maneira interessante de você realizar migration de forma automática é utilizando este pacote do Xethron/migrations-generator
Para instalar o pacote use o comando:
composer require --dev "xethron/migrations-generator"

Depois cole essas linhas de códigos no arquivo config/app.php:
Way\Generators\GeneratorsServiceProvider::class,
Xethron\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,

Como utilizar:
Você cria suas tabelas no seu banco de dados, conforme você está acostumado, e depois executa os comandos;
a) para criar TODAS as tabelas do banco:
php artisan help migrate:generate

b) Para criar tabelas específicas:
php artisan migrate:generate table1,table2,table3,table4,table5

Espero ter ajudado.
Abraço
Comment: vlw cara mas n é exatamente o que eu queria


How to send message/data from broadcast receiver (process1) to Service thread (process2) in android?

Question: I am developing an android application. This application architecture is divided into 5 modules with 2 modules having multiple features. To develop this app, I am creating 2 process with multiple threads in them as required and 3 other threads. I have a some questions regarding this implementation:
Is this a good model? If not, why not? Right now I am considering only modularity.
I need to send a message from broadcast receiver in process1 to Service thread in process2, what is the best way to do it?
what is the best IPC mechanism in android? I tried to use this link, http://androidapps.org.ua/androidintro_ipc_intent.html which suggests startActivity and startActivityForResult, but these options are not available in broadcast receiver and service does not have startActivityForResult option.
Thank you.
Answer: Use Custom BroadcastReceiver
Write this in ActivityA.java
 Intent intent = new Intent();
 intent.putExtra("message","hi");
 intent.setAction("com.android.activity.SEND_DATA");
 sendBroadcast(intent);

Write this in ServiceA.java
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
   // Extract data included in the Intent
   String message = intent.getStringExtra("message");
   Log.d("receiver", "Got message: " + message);
  }
};

Now register Receiver
LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,
  new IntentFilter("com.android.activity.SEND_DATA"));

Comment: Hey Rstar, I need to send a message from Broadcastreceiver's onReceive function to a service and they are located on different services. I can do the latter part i.e. create another Broadcast receiver in service. But for the first part I do not see the option, sendBroadcast in Broadcastreceiver's onReceive function.
Comment: You don't want to send a broadcast intent just to pass data to a service. You can do this directly.
Comment: @DavidWasser is right if you don't want to use BroadcastReceiver
Comment: @Rstar Can I send Broadcast from service instead of activity. or else do I have to make changes in sendBroadcast .
if yes then this is Exactly what I was Looking for
Answer: Just create an Intent in the BroadcastReceiver, add your data as extras, can call startService() with the Intent:
Intent intent = new Intent(context, MyService.class);
intent.putExtra("message", "whatever data you need to pass to the service");
context.startService(intent);

The method onStartCommand() will be called in your service with the passed Intent.
To answer your other question "what is the best IPC method", the answer (as always) is "that depends". Using Intents is the easiest method, as it is supported for all components out-of-the-box. If you need more complicated interaction between components you can look at using AIDL which will allow you to do remote method calls in a Service. If that still isn't enough, then just implement your own socket protocol between the 2 components.
Comment: David, One more question, let us say I am trying to send data/message to activity (not service) in another process, how to do it?
Comment: Sorry, you call `startService()` on the `context` parameter in `onReceive()`. I fixed my code.
Comment: If you want to send data/message to an activity, you do it exactly the same way. You create an `Intent`, add your data as extras and call `context.startActivity()`. You can start an activity in any process (in fact, when you start an activity, you really don't have any idea or control over what process it will be started in).
Comment: yeah, but what if it the activity is already running? sudhee answered my question i.e. to use flags.
Comment: If activity is already running, the default behaviour would be to create another instance of that activity. However, if you use `Intent.FLAG_ACTIVITY_SINGLE_TOP` or if the activity is defined with `launchMode="singleTop"` then the `Intent` will be delivered to the existing activity using `onNewIntent()`.
Answer: First of all, trying to understand your terminologies.  By process, I presume you mean activity and "service thread", I presume you mean a service.
If you want to send a message from onReceive() broadcast receiver, running in context of Activity 1, to a service which is already active, you can try one of the below:
1) Create a new intent (service class name as the class) and call startService() with the intent. Add the additional parameters you need as intent extras.  It does not matter if your service is already active, the onStartCommand() is still called,  you can have special parameters as intent extras to differentiate a onStartCommand() from onReceive.
2) If your scenario allows this, consider registering to same broadcast event in both your activity and service and act appropriately (then no need to pass messages)
3) Write another broadcast receiver in your service and call sendBroadcast() from the Activity's broadcast receiver
Comment: No, process does not mean activity and yes service thread I meant service. I dont see startService and sendBroadcast options in Broadcastreceiver's onReceive function. Eclipse says these methods do not exist, implement them. I did not understand option 2.
Comment: Do you have manifest defined Broadcast Receiver or a dynamically registered receiver ?
Comment: Dynamically registered using registerReceiver(localFaultDetector, batteryLifeFilter); this method.
Comment: use the context passed as parameter1 of onReceive() ex: arg0.startActivity() or arg0.sendBroadcast()
Comment: clarity on option 2: I meant that you register to the same broadcast event in both your "process" and the service with onReceive() coded in both.  You will receive the broadcast in both places.  However, in case you need some additional processing in your "process" before passing it on to your service, this will not work.
Comment: thank you sudhee... :( I kept trying with Context. or Context(). and it didn't work. with context it works. btw, how to send if the receiver is not service but an activity.
Comment: You can use same methods on activities also, but startActivity will start new instance of the activity, if activity already exists, use flag FLAG_ACTIVITY_REORDER_TO_FRONT(or FLAG_ACTIVITY_SINGLE_TOP as your case is) to bring it to front.
Comment: Thanks, that was the confusion.


Why does `select` continue to think I need to `accept`?

Question: I'm trying to write a simple socket server, for the sake of this example it's an echo server.
This is socket_server.c (note the comment about where it gets stuck)
int fdmax, i, socket_descriptor;
fd_set master, read_fds;
struct timeval tv = {.tv_sec = 0, .tv_usec = 1000};

void socket_server_init(void)
{
    FD_ZERO(&master);
    FD_ZERO(&read_fds);
}

socket_server_socket socket_server_start(char *socket_path)
{
    struct sockaddr_un local;
    int len;
    int socket_descriptor = socket(AF_UNIX, SOCK_STREAM, 0);

    if (socket_descriptor == -1)
        return (socket_server_socket) {.status = SOCKET_SERVER_START_SOCKET_FAILURE, .descriptor = -1};

    local.sun_family = AF_UNIX;
    strcpy(local.sun_path, socket_path);
    unlink(local.sun_path);
    len = strlen(local.sun_path) + sizeof(local.sun_family);

    if (bind(socket_descriptor, (struct sockaddr *)&local, len) == -1)
        return (socket_server_socket) {.status = SOCKET_SERVER_START_BIND_FAILURE, .descriptor = -1};

    if (listen(socket_descriptor, 5) == -1)
        return (socket_server_socket) {.status = SOCKET_SERVER_START_LISTEN_FAILURE, .descriptor = -1};

    FD_SET(socket_descriptor, &master);
    fdmax = socket_descriptor;
    return (socket_server_socket) {.status = 0, .descriptor = socket_descriptor};
}

socket_server_socket socket_server_wait_for_connection(socket_server_socket server)
{
    read_fds = master;
    select(fdmax+1, &read_fds, NULL, NULL, &tv);

    for (i = 0; i <= fdmax; i++)
    {
        if (FD_ISSET(i, &read_fds))
        {
            if (i == server.descriptor)
            {
                // It's getting stuck here.
                socket_descriptor = accept(server.descriptor, (struct sockaddr *) NULL, NULL);

                if (socket_descriptor > fdmax)
                    fdmax = socket_descriptor;

                FD_SET(socket_descriptor, &master);
                return (socket_server_socket) {.status = -1, .descriptor = socket_descriptor};
            } else {
                return (socket_server_socket) {.status = 0, .descriptor = i};
            }
        }
    }

    return (socket_server_socket) {.status = -1, .descriptor = -1};
}

int socket_server_update(socket_server_socket client)
{
    char buffer[256];
    int n = recv(client.descriptor, buffer, 256, 0);
    if (n < 0)
        return SOCKET_SERVER_UPDATE_RECV_FAILURE;

    if (send(client.descriptor, buffer, n, 0) < 0)
        return SOCKET_SERVER_UPDATE_SEND_FAILURE;

    close(client.descriptor);
    return 0;
}

Then in my main program:
    socket_server_init();
    socket_server_socket server = socket_server_start(SOCKET_PATH);
    while (1) {
        printf("wait for conn\n");
        socket_server_socket client = socket_server_wait_for_connection(server);

        if (client.status == 0)
        {
            socket_server_update(client);
        }

        sleep(1);
        printf("%d: Log !\n", (int)time(NULL));
    }

When I run the program I observe:

"Log !" is output on the console
I connect to the server through the socket
I continue to see "Log !" on the console
I sent some data from the client
The client sees the data echo back
"Log !" is no longer being seen on the console
Any subsequent data from the client is not echoed back

I expect the loop to carry on and "Log !" to continue to be output, but it looks like my program is getting stuck at the accept call, but only the second time.
As I understand it, select is only supposed to add the descriptor to read_fds if it needs to be accepted or recv'd. So what seems to happen is:

select adds the server's descriptor to read_fds
It gets accepted
select again adds the servers descriptor to read_fds
There is nothing waiting to be accepted so accept hangs

I've verified that both times when the accept call is reached, the descriptor is the same. So I'm very confused.
What am I doing wrong? I'm sure it shouldn't be hitting accept a second time for the same connection.
Answer: You use a timeout, if this timeout passes, select(2) would return 0, your program doesn't care about its return value and treat it as a successful call ("We have something to read"), but read_fds hasn't  been updated. Therefore, it still hold its previous value ("We have a new client"), then, you call accept and get stuck.
The solution would be very easy: check select(2)'s return value:
 int result = select(fdmax+1, &read_fds, NULL, NULL, &tv);
 if (result < 0) {
     // Handle error.
 } else if (result == 0) {
     // Handle timeout.
 }

To learn more about select and sockets in unix in common, I highly recommend reading Beej's Guide to Network Programming.
Comment: This seems close... I can't follow your suggestion though because that causes select to block while it waits for a connection. I'm using a timeout so that other parts of my program can continue working. I did try `if (select(fdmax+1, &read_fds, NULL, NULL, &tv) < 0) return;` but then I get in a situation where `select` just keeps returning -1 for some reason.
Comment: Keep in mind that you should `FD_CLR` invalid (closed) sockets from your `fd_set`. .  Please try to follow beej's example for a simple chat and compare it to your program. To see why select is returning -1, try to print the last error with `perror`.
Comment: @CameronBall if select returns 0 you have a time out. If it returns <0 you have an *error* and you need to check errno and/or use perror or whatever in irder to see what the error is.


@Html.ActionLink submetendo formulário Post MVC

Question: @using (Html.BeginForm("MinhaAction", "MeuController", FormMethod.Post ))
{

                    Empresa
                    Cliente
                    Situação

                @foreach (var item in Model)
                {

                        @item.Empresa
                        @item.Cliente
                        @item.Situacao

                }

}

É possivel submeter um formulário dessa forma? Qual a solução pra essa questão?
Comment: Não entendi. Qual o problema enfrentado?
Comment: A minha intenção era de que o usuário clicando em qualquer dado da célula desta tabela o sistema teria que guardar esse objeto e passar pra minha View via Post sem que pra isso eu adicione um botão(com submit) nessa tabela.
Answer: Não. Há um confusão feroz de conceitos aí.
Um formulário POST envia informações de um formulário usando o protocolo de submissão de dados. Clicar em um link é uma requisição GET que envia informações através do endereço HTTP requisitado.
O que você quer fazer, provavelmente, é tipificar alguma informação a ser enviada. Isto pode ser feito usando algum componente de informação, como um radiogroup (@Html.RadioButton() ou então @Html.RadioButtonFor()) e tratando o campo na Action.
Não esqueça de colocar o botão de submit:
<button type="submit">Enviar</button>


Do models differ for prediction and inference for same training data?

Question: Here's my idea and doubt
There are two purposes of machine learning, inference, and prediction. In prediction, we are interested in finding a model to give us the best accuracy when we try to find the forecast for a new data point. In inference, the idea is to understand the relationship between input variables and output variables.
However, for a particular problem, we assume to have a single underlying data-generating process. In that case, won't fitting different models for inference and prediction be a violation of this assumption? For example, we can fit linear regression for inference and a normal distribution-based model for prediction but underlying DGP can be only one (in the best possible scenario). In that case, does it make sense to do so?
Answer: No, even when we assume a single data generating process and even when it's a very simple data generating process, it's quite possible for predictive models to be very different from models estimating the effect of a specific variable.
Suppose we have a very simple data generating process
x~Bernoulli(0.5)
z<- x+N(0,1)
y<- z+N(0,1)

where all the arrows represent truly causal relationships.  Under this data generating process, y is independent of x given z, so the best predictive model is y~z. If we put x in this model it would have a coefficient of 0. x is not predictive.
However, if we want to estimate the effect of x on y, this effect is not zero.  Individuals with x==1 have higher y than those with x==0, by 1 unit on average, and this is causal. We need to fit the model y~x and not the model y~z or y~x+z to estimate the effect of x on y.
If you constructed a model describing the full data-generating process, you could derive both the best predictive model y~z and the best model for the effect of x, y~x from it. These models are different, and they would be different whether or not you knew the exact data-generating process.
Comment: So basically we treat prediction vs inference independently. But then there can be the case that the inference model suggests something say(a linear increase of 1000 with a unit increase in z) but the predictive model might not agree (might show a quadratic trend). How do we avoid such scenarios? How can we claim the inference model is correct if the predictive model is not agreeing with the inference claims?
Answer: First of all, I would argue that for making predictions in machine learning in many cases you don't really need to care about the data-generating process. If you are using something like $k$NN regression, the only thing that you're doing is predicting the mean of the most similar datapoints in the training data, it doesn't make any assumptions about the data-generating process. The same applies to most of the other machine learning.
Moreover, keep in mind that the idea of a data-generating process is just an abstraction helping us to formalize the statistical model for the particular data. There is no "the" data-generating process. No data was "generated" from something like Gaussian (or any other) distribution because there is no such thing in nature as Gaussian distribution, it's a mathematical concept.
For the purpose of inference, we want our model to be simple, so it is easy to interpret. For making predictions, we want it to be accurate, possibly at the price of being less interpretable. Neither of the models is single correct, they are both wrong, but each is useful in its own way.
Comment: Thanks for the very informative answer. The second paragraph drives the point almost home. However, I am still having difficulty coming to terms with both being fitted independently. I expect if the inference model says that y should vary linearly, the predictive model should show that trend. On the other hand, if the predictive model suggests that variation is quadratic our inference model should also deal with quadratic terms. The linear model will not make sense. So there is a dependency in both choices in that sense. Is my reasoning correct?
Comment: @mw981 not sure what you mean. It's definitely possible to fit two different models to the same data.
Comment: agreed it's possible. What I mean is suppose we find the best predictive model is a quadratic linear model, in that case, if we derive inference insights from a linear model, will it be correct? Shouldn't I use a quadratic structure for the inference model as well?
Comment: @mw981 how do you define "best"?
Comment: by best I mean the model with the least error on the test set.
Comment: @mv981 that's not the definition that is of any relevance for an inference model since you are not going to use it to make out-of-data predictions.
Comment: I meant that for the predictive model. For the best inference model, my least expectation would be to be consistent with trends that are shown by the predictive model. Suppose we are regressing the number of friends against salary and the best predictive model suggests that the increase in friends with salary is quadratic. Now, suppose we fit linear regression and make a statement that with a unit increase in salary, x is the expected linear increase in the number of friends. But the predictive model suggests a quadratic increase. Shouldn't we fit a quadratic model to infer properly here?
Comment: @mw981 it doesn't "prove" that such a model would be best for inference. Formula 1 may be the fastest, but if you would like to go off-road it would be hardly the best or fastest.


Diferenças entre $('body').on('click',...) e o $('selector').click()

Question: Estou com uma duvida na declaração de click de um elemento com jQuery, eu sei que possa fazer das seguintes formas:
$('body').on('click', '...selector...', function () {...})

ou
$('...selector...').click(function () {...})

Eu sei que da primeira maneira eu não preciso ficar dando rebind sempre que surgir um elemento novo na minha página, porém gostaria de saber:

Se existe alguma diferença de gasto com memoria, processamento e
performance entre essa duas variações
Se exite mais alguma outra diferença entre elas , além da citada anteriormente.
Ou até mesmo, se exite algum motivo que me faça optar a escolher uma das duas alternativas.
Comment: Relacionada: http://pt.stackoverflow.com/questions/5196/qual-a-diferen%C3%A7a-entre-o-onclick-function-e-o-clickfunction
Answer: A diferença básica entre os dois é em quem você atrela o evento de click.
No primeiro caso ele vai capturar o evento quando o mesmo chegar no body e tiver origem no seletor desejado. Como os eventos em javascript propagam, quando o usuário clicar no seletor ele vai propagar até o body e você vai capturar corretamente.
No segundo você atrela o evento diretamente ao seletor. Quando o clique tiver origem nele, você vai capturar o evento.
E qual a vantagem de atrelar ao body? Quando você faz isso, não é necessário que o elemento exista na página. Isso é extremamente útil quando você cria o elemento dinamicamente. Você consegue atrelar o evento a ele sem necessariamente ter criado o elemento ainda.
$('body').on('click', '#botao', carregaItems);
var botao = $('
ola
');
$('body').append(botao);

O click no botão vai disparar a função carregaItems
No segundo caso, você depende que o elemento esteja presente na página para atrelar o evento a ele. Se o código que atrela o evento for executado antes do código que cria o elemento, o elemento fica sem escuta no evento.
$('#botao').click(carregaItems);
var botao = $('
ola
');
$('body').append(botao);

O click no botão não vai disparar a função carregaItems porque for feito o bind do evento em um elemento que não existe no DOM ainda.


What's the best way to update the state manually in Apache Flink?

Question: I'm using Apache Flink in a stock market project to calculate the current price change. The formula is
 price_change = (current_price - previous_close_price) / previous_close_price

previous_close_price is a security's closing price on the preceding day of trading. Everyday before the market opens, I need to update previous_close_price.
Now I've come up with several solutions but I don't know which one is the best.

Store previous_close_price in redis and fetch the price in every calculation. It's easy and flexible to update the price but this solution could kill the performance.
Set the TTL of state to 1 day. Get the new state when the old state is expired. But it's not flexible as the TTL is hardcoded.
Broadcast State Pattern. I'm not sure if this solution works.
Send a special message to flink. When flink receives the message, it updates the previous_close_price.

Any suggestions are appreicated.
Answer: I suggest a variant on #4:
Have two sources, one used only for the closing prices, and the other for the stream of trades. Key both streams by the security, and connect them with a CoProcessFunction. Store the previous_close_price in keyed state, within the CoProcessFunction.
Every day, before the market opens, stream in the updated closing prices.
This could be done with a RichCoFlatMap, but I'm suggesting a CoProcessFunction because you might want to use a side output to report errors (e.g. securities where the previous_close_price is missing).
As for the other approaches:

I don't see any advantage to keeping the previous_close_price data in an external data store.
I don't think this works very well. There's no hook available for triggering the loading of the new data, and moreover, the state will only be cleared when it's accessed.
This doesn't feel like a good use case for broadcast state, unless there's a need for everyone in the cluster to know the closing prices for all securities.
Comment: That's exactly I desired @David Anderson. But should I connect them like tradeStream.keyBy("security").connect(closingPriceStream.keyBy("security")).process(new CoPressFunction(){...})? Does it make sure that the trade stream can share the state with closing price stream if they have the same security?