Solve $\lim_{x \rightarrow 0} (a^x + b^x - c^x)^\frac{1}{x}$

Question: I need to solve the limit
$$\lim_{x \rightarrow 0} (a^x + b^x - c^x)^\frac{1}{x}$$
when $a,b,c \gt 0$.
I'm looking for ways to avoid $\frac{1}{x}$ power.
Comment: I formatted your question. Please make certain I have done so faithfully. In particular, you mention "sqrt of $x$" in your question, but it did not appear in the limit you wrote down. Are you referring to the "$\frac{1}{x}$ power"?
Comment: Yes Austin that is correct thank you.
Comment: The answer (if I am not wrong) is $\frac{ab}{c}$. I'll try to punch in a solution soon.
Comment: @Nunoxic I went to my board, did the calculations and got the same. My comment'd have been the same as yours.
Answer: Note that
$$
\lim_{x \rightarrow 0} (a^x + b^x - c^x)^\frac{1}{x}
=\lim_{x \rightarrow 0}\,e^{\left(\displaystyle\frac1x \log(a^x+b^x-c^x)\right)}.
$$
So we only need to calculate
$$
\lim_{x \rightarrow 0}\frac1x \log(a^x+b^x-c^x).
$$
Since the expression inside the log goes to $1$ as $x\to0$, we can apply L'Hôpital, to get
$$
\lim_{x \rightarrow 0}\frac1x \log(a^x+b^x-c^x)
=\lim_{x\to0}\frac{a^x\,\log a+ b^x\,\log b-c^x\,\log c}{a^x+b^x-c^x}
=\log a+ \log b-\log c.
$$
Then
$$
\lim_{x \rightarrow 0} (a^x + b^x - c^x)^\frac{1}{x}=e^{\log a+ \log b-\log c}=\frac{ab}c
$$
Added: as suggested by Aryabhata, it remains to justify that one can actually apply L'Hôpital. For the rule to apply, we need to have a quotient $f(x)/g(x)$, with both $f$ and $g$ differentiable at $0$, with $g'(x)\ne0$ on a neighbourhood of $0$, such that $f(0)=g(0)=0$ (less is needed, in fact, only that they go to $0$) and such that $\lim_{x\to0}f'(x)/g'(x)$ exists (it equals $ab/c$ in this case). Here $f(x)=\log(a^x+b^x-c^x)$, $g(x)=x$. The function $x\mapsto a^x+b^x-c^x$ is differentiable everywhere; for $x$ near $0$, the values of this function approximate $1$; on any neighbourhood of $1$ that doesn't contain $0$,  $\log$ is differentiable, and then so is the composition $f(x)=\log(a^x+b^x-c^x)$. And $g'(x)=1\ne0$ for all $x$.
Comment: This seems circular: LHospital assumes that the derivative exists at $0$. But the limit you are trying to find is exactly the derivative at $0$! (This is what I was hinting with my answer).
Comment: @Aryabhata: I'm using L'Hopital to find the value of the limit, not to prove that the derivative exists. The function $\log(a^x+b^x-c^x)$ is C$^\infty$ on small enough neighbourhoods of $0$.
Comment: Finding a limit also entails proving its existence (implicitly or explicitly). Otherwise, all you have done is, "if the limit exists, then it is so and so", which is incomplete.
Comment: @Aryabhata: L'Hôpital is exactly about the existence of the limit.
Comment: You missed mentioning that $g'(x) \ne 0$ in a neighbourhood of $0$, but that is fine here as $g(x) = x$. Sure, Lhopital also proves existence, but that was not my point.
Answer: Another hint: Let $f(x) = \log (a^x + b^x - c^x)$
What is $f(0)$?
What is $f'(0)$? (The derivative at $0$).
Comment: f(0) is 0 and f(tag)(0) is minus infinity..trying to think what this tells me
Comment: @TOm: What is the definition of $f'(0)$ in terms of limits?
Comment: @Tom: Are you sure about $f'(0)$?
Answer: HINT:
$$
  \left( a^x + b^x - c^x \right)^\frac{1}{x} = a \left( 1 + \left(\frac{b}{a}\right)^x - \left(\frac{c}{a}\right)^x \right)^\frac{1}{x} = a \left( 1 + x \cdot \frac{\left(\frac{b}{a}\right)^x - \left(\frac{c}{a}\right)^x}{x} \right)^\frac{1}{x}
$$
Compute $\lim_{x \to 0} \frac{\left(\frac{b}{a}\right)^x - \left(\frac{c}{a}\right)^x}{x}$, then use the golden limit $\lim_{x\to 0} \left( 1 + \alpha x\right)^\frac{1}{x}$.
Comment: @Peter: I am pretty sure Sasha is not doing that, but people who are just learning these things might think that that is what Sasha is doing. Just pointing out the potential pitfall.
Comment: This needs some justification. For instance consider limit of $(1+x)^{1/x}$ as $x \to 0$ (which is $e$). We just cannot replace $(1+x)$ by $1$ because $x \to 0$.
Comment: @Aryabhata Sasha is not suggesting that.
Comment: this looks like magic but yet again the limit to compute when x approaches 0 is hard for me to do
Answer: Where you start is to realize that $1^\infty$ is an indeterminate form, so you can use L'hopital's rule after you rewrite it as,
$$e^{\left(\lim\limits_{x \rightarrow 0} \frac{\ln(a^x + b^x - c^x)}{x}\right)}$$
Answer: If you want to avoid L'Hopital: Write $(a^x + b^x - c^x)^{1 \over x}$ as $a(1 + ({b \over a})^x - ({c \over a})^x)^{1 \over x}$, so that it suffices to find
$$\lim_{x \rightarrow 0} (1 +({b \over a})^x - ({c \over a})^x)^{1 \over x}$$
Taking logs, it's enough to find
$$\lim_{x \rightarrow 0} {\ln(1 +({b \over a})^x - ({c \over a})^x) \over x}$$
$$=\lim_{x \rightarrow 0} {\ln(1 +({b \over a})^x - ({c \over a})^x) - \ln(1 +({b \over a})^0 - ({c \over a})^0) \over x - 0}$$
This is the difference quotient for the derivative of $\ln(1 +({b \over a})^x - ({c \over a})^x)$ at $x = 0$. Using the chain rule to find this derivative and plugging in $x = 0$ gives you $\ln(b/a) - \ln(c/a) = \ln(b/c)$. Going backwards, the original limit is ${\displaystyle ae^{\ln(b/c)} = {ab \over c}}$.


Display {{pager}} to twig file

Question: i am kinda new to drupal 8 so don't judge to hard...
 i have made template for drupal, that is in plain html,css and js...  than i imported it to drupal correctly as drupal documentation says whit his info.yml, libraries.yml and etc files at this moment everything is OK...
i have one page--front.html.twig file, that i have placed my main html mark-Up
with correct regions and so on. On other hand i have views-view.html.twig file that it has:
 set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id, ]%}

  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}

      {{ header }}

  {% endif %}

  {{ exposed }}
  {{ attachment_before }}

  {{ rows }}
  {{ empty }}
  {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}

      {{ footer }}

  {% endif %}

  {{ feed_icons }}

the code of {{ pager }} is in pager.html.twig and i contains this information:
{% if items %}

{{ 'Pagination'|t }}

      {# Print first item if we are not on the first page. #}
      {% if items.first %}

            {{ 'First page'|t }}
            {{ items.first.text|default('« First'|t) }}

      {% endif %}
      {# Print previous item if we are not on the first page. #}
      {% if items.previous %}

            {{ 'Previous page'|t }}
            {{ items.previous.text|default('‹ Previous'|t) }}

      {% endif %}
      {# Add an ellipsis if there are further previous pages. #}
      {% if ellipses.previous %}

…

      {% endif %}
      {# Now generate the actual pager piece. #}
      {% for key, item in items.pages %}

          {% if current == key %}
            {% set title = 'Current page'|t %}
          {% else %}
            {% set title = 'Go to page @key'|t({'@key': key}) %}
          {% endif %}

              {{ current == key ? 'Current page'|t : 'Page'|t }}

            {{- key -}}

      {% endfor %}
      {# Add an ellipsis if there are further next pages. #}
      {% if ellipses.next %}

…

      {% endif %}
      {# Print next item if we are not on the last page. #}
      {% if items.next %}

            {{ 'Next page'|t }}
            {{ items.next.text|default('Next ›'|t) }}

      {% endif %}
      {# Print last item if we are not on the last page. #}
      {% if items.last %}

            {{ 'Last page'|t }}
            {{ items.last.text|default('Last »'|t) }}

      {% endif %}

{% endif %}

here is mu question... when i put the {{ pager }}  to my page--front.html.twig than nothing happens... why? why dose views-view.html.twig can execute the  {{ pager }}  and it can't views-view.html.twig? what am I doing wrong?
 thanks in advance
p.s: I forgot to say that in the front page i have activated the pager... and it shows correctly but i want it to be on aver location than it is right now
Answer: If you take a look in /core/themes/stable/templates/views
In views-view.html.twig at the top, there is a commented out part that says:

Available variables:
attributes: Remaining HTML attributes for the element.
css_name: A css-safe version of the view name.
css_class: The user-specified classes names, if any.
header: The optional header.
footer: The optional footer.
rows: The results of the view query, if any.
empty: The content to display if there are no rows.
pager: The optional pager next/prev links to display.
exposed: Exposed widget form/info to display.
feed_icons: Optional feed icons to display.
more: An optional link to the next page of results.
title: Title of the view, only used when displaying in the admin preview.
title_prefix: Additional output populated by modules, intended to be
displayed in front of the view title.
title_suffix: Additional output populated by modules, intended to be
displayed after the view title.
attachment_before: An optional attachment view to be displayed before the
view content.
attachment_after: An optional attachment view to be displayed after the
view content.
dom_id: Unique id for every view being printed to give unique class for
Javascript.
*
@see template_preprocess_views_view()

As you can see pager is listed under Available variables

While in /core/themes/bartik/templates
page.html.twig

Available variables:
General utility variables:
base_path: The base URL path of the Drupal installation. Will usually be
"/" unless you have installed Drupal in a sub-directory.
is_front: A flag indicating if the current page is the front page.
logged_in: A flag indicating if the user is registered and signed in.
is_admin: A flag indicating if the user has permission to access
administration pages.
*
Site identity:
front_page: The URL of the front page. Use this instead of base_path when
linking to the front page. This includes the language domain or prefix.
*
Page content (in order of occurrence in the default page.html.twig):
node: Fully loaded node, if there is an automatically-loaded node
associated with the page and the node ID is the second argument in the
page's path (e.g. node/12345 and node/12345/revisions, but not
comment/reply/12345).
*
Regions:
page.header: Items for the header region.
page.pre_content: Items for the pre-content region.
page.breadcrumb: Items for the breadcrumb region.
page.highlighted: Items for the highlighted region.
page.help: Dynamic help text, mostly for admin pages.
page.content: The main content of the current page.
*
@see template_preprocess_page()
@see html.html.twig

As you can see pager is NOT listed under Available variables

The correct solution is that you need to modify/create the views-view--frontpage.html.twig and not the page--front.html.twig
So go to core/modules/views/templates and copy views-view.html.twig and rename it to views-view--frontpage.html.twig and make changes that you need. The views-view--frontpage.html.twig needs to go in /theme/yourtheme/templates folder.
Comment: @GeorgeChanturia `so can i use {{ pager }} to any html.twig files (if yes, than how?)` Yes it is possible, you would have to create a custom twig variable using a preprocess function which will render the pager programmatically.
Comment: thanks a lot for replying so fast... the information that you prove is very useful.... but i am interested of using specific code in specific region, so can i use {{ pager }} to any html.twig files (if yes, than how?) or this is impossible?
Comment: @GeorgeChanturia as I mention in my answer, since `{{ pager }}` is not listed under Available variables in page.html.twig, you cannot use `{{ pager }}` here. Furthermore, the pager belongs to the frontpage view and not the front page. So front page wouldn't know what `{{ pager }}` is.
Comment: thank you so mach and sorry for damu questions... I will try what you say and will reply... thanks...
Comment: @NoSssweat please give us a pointer as to how one can render a pager in a preprocess function

Display {{pager}} to twig file


Is it legal to ice your own kicker?

Question: In the NFL a Coach can call a timeout right before the kicker kicks the ball in order to affect the kicker's chance of succeeding. In many cases, the kicker will take the kick twice, once right after the timeout is called (this one doesn't count) and a second time after the timeout.
Is an NFL coach allowed to plan a staged timeout with the their own kicker to give them a practice kick? Or is this illegal since a kicker normally doesn't have the chance to take a practice attempt before the actual kick.
Answer: Yes, it is legal. In fact, Jason Garrett did this.

But what about when a coach ices his own kicker?
That's essentially what Dallas Cowboys head coach Jason Garrett did on
Sunday during a game against the Arizona Cardinals. With the score
tied at 13, and just seven seconds left in regulation, Dallas rookie
kicker Dan Bailey lined up for a potential game-winning 49-yard field
goal. Right before the snap, Garrett called timeout. Bailey kicked it
anyway, and nailed it. His second attempt? Not so good — he shanked it
wide left. The game went into overtime, and Dallas ended up losing
19-13.
Here's how Garrett explained his decision during his post-game press
conference:
"The play clock was running down. We just wanted to make sure that he
had a real clean opportunity at it," Dallas coach Jason Garrett
explained. "It was at about 6 (seconds) and we were still getting
settled in, so we banged a time out to give him the opportunity to get
the snap, hold and kick as clean as possible."

In summary, Garrett "iced his own kicker" because the offense wasn't quite ready for the play, which was a "practice attempt" that backfired on the actual field goal attempt.

Is it legal to ice your own kicker?


What is the significance of the mirror numbers?

Question: I'd like to hear insights and theory of the mirror numbers and their possible significance in mathematics and geometry. With mirror numbers I mean these four examples:
<code>432 -> 234
123 -> 321
153 -> 351
987 -> 789
</code>
Sum of 432 & 234 is 666 and sum of 153 & 351 is 504, which are famous numbers from historical perspective, namely from Pythagoras, Plato, Archimedes and Revelation of John.
Supplementing questions arose on a chat with Dan:
1) How to determine if a number x can be represented as n + rev(n)?
2) How to determine possible n & rev(n) for number x?
Comment: See [OEIS sequence A067030](https://oeis.org/A067030).
Comment: Um, a $4-3-2$ triangle is congruent to a $2-3-4$ triangle.
Comment: But of course. I was thinking triangles with 90 degree corner first, but it seems triangles are not very good geometrical presentation of these numbers as they look same, until orientation is regarded.
Comment: A $4-3-2$ triangle has no 90 degree angle.
Comment: Any scalene triangle could be presented with two right triangles. Would the properties of these two triangles in 4-3-2 be congruent with two right triangles of 2-3-4? I guess they would...
Comment: Seems to be an exact match, @Robert Thanks for reference and heads up for 5 years old issue.
Answer: This is not terrifically profound, but if $y$ is the mirror of $x$ in base $b$, then $x \equiv y \mod b-1$, while $x \equiv \sigma y \mod b+1$ where $\sigma = 1$ if $x$ and $y$ have an odd number of base-$b$ digits and
$-1$ if they have an even number of base-$b$ digits.
Comment: Looks interesting, but statement should be deciphered a little bit to be understandable for me :) What is sign ≡ in this case?
Comment: Look up modular arithmetic: http://en.wikipedia.org/wiki/Modular_arithmetic
Comment: That's a really nice hand. Mentioned numbers are supposedly precessional numbers, thus part of the cycle of the precessional year. So at least modulo 12, 72, 360 could be used here, if I understood correctly. 153 was the fractional part of the square root 3 used by Archimedes and I'm pondering if it really is just a random consequence, that it adds up with mirror number to the number Plato used for ideal citizenship units. Or if there is some other mathematical correlation between these. Geometrical topic I brought here for possible visual demonstration purposes.
Comment: PHPGAE, I think you are grasping at straws.
Comment: "grasping at straws. Fig. to depend on something that is useless; to make a futile attempt at something." Is that what you mean with the statement Dan?
Comment: Yes, you are referring to numerology which won't lead to any knowledge.
Comment: Well then you need to speak of usefulness to yourself only. I'm studying and applying numbers to my own interests which are useful to me, so please don't mind that.
Comment: @PHPGAE that is understandable.  I meant mathematical knowledge as I see it.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/6362/discussion-between-dan-brumleve-and-phpgae)
Answer: Such pairs of numbers have no intrinsic mathematical significance (although related numbers are studied; see palindromic numbers) due to the arbitrary choice of base $10$.  I don't know of any geometric connection but I would expect it to be very subtle, not as direct as what you are suggesting.  The fact that there is both a 2-3-4 triangle and a 6-6-6 triangle is a coincidence emboldened by the choice of a relatively large base.
Comment: No, palindromes are numbers that are their own mirrors.
Comment: Misread the question and jumped the gun.  Fixed, I think.
Comment: Base 10 is actually a good point. How does situation change if we treat given numbers base 60? It's likely given numbers and results should be actually treated base 60, because ancient cultures used Sexagesimal system: http://en.wikipedia.org/wiki/Sexagesimal

Of course for the question I'm looking for math connection on mirror numbers in general, but as talking number base here, I think it's good background information.

I hope that people who don't like these historical connections, will just pass them and contribute from plain math view of point, if they have something to say.
Comment: Base 2 would be a better place to start with more fundamental meaning.  The smaller the base the better the theorem.  The historical connections are interesting but consider the context: 60 and 360 are used as bases because of their smoothness, not because of any digital consummations.
Answer: Subtract the small mirror from the large mirror & divide by 9. It's fun and very symbolic. Mirrors without and within.
For example:
2559591 - 1959552 = 600039
600039 / 9 = 66671
8883 - 3888 = 4995
4995 / 9 = 555
5832 - 2385 = 3447
3447 / 9 = 383
25367473251-15237476352 = 10129996899
10129996899/9 = 1125555211
Try things like year of birth & another year:
5891 - 1985 = 3906
3906 / 9 = 434
7102 - 2017 = 5085
5085 / 9 = 565
565 + 434 = 999
Comment: There is a rule of nine. Transpose digits of the number in any base. Substract and result should be divisible by base - 1. Above mirror feature is a special case of such much more general feature.


Using menu tab for each panel variant

Question: I'm trying to use Panels to arrange content on my site. I've made some strides in creating a panel that displays a view of images based on different criteria.
I added a page (panel) which allows me to tap into Drupal's menu system and make a tab called Photos. Now I want to add a number of variants to this panel, and I want links to those variants to show up in the sub-tab (MENU_DEFAULT_LOCAL_TASK). Since there does not seem to be any way to add a menu item for each variant, I'm wondering what is the best way to do this.
I see two possibilities, both of which don't seem ideal:

I could write a module, that adds the  default local tasks to the menu item.
I could add a separate panel page for each variant, and use the menus there.

It seems like there should be an easy solution to this. Can anyone help me?
Comment: Possible duplicate of [How to create a tabbed view in a panel without a menu entry?](http://drupal.stackexchange.com/questions/94421/how-to-create-a-tabbed-view-in-a-panel-without-a-menu-entry)
Comment: Those two questions are not a duplicates, but why I can't just mark the question as a related?
Comment: @graceman9 : if you just add a comment with an hyperlink to http://drupal.stackexchange.com/questions/94421 (like I do in this comment), it will show up as "linked". So don't flag it as a duplicate if you think it is not a duplicate. OK?
Comment: OK, I think you should also "delete" your first comment (since it contradicts your 2nd ...).
Answer: I sort of figured out a way to do this.

Add a variant within the Panels module
Add a visibility rule so that different variants show at different URLs (clean URLs and paths required), for example, example.com/paneltitle/variant1, example.com/paneltitle/variant2.
Create a custom module to hook into the menu. There is a great example of a menu module in the module code samples on drupal.org. A example here for above variants:

`
<code>function custom_module_menu() {
  $items['paneltitle/variant1'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['paneltitle/variant2'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}
</code>
This seems to have worked for me.
Answer: You can use the Views module to implement this feature.
Using Views, you can set sub menu task also.
Comment: More detailed explanation here http://drupal.stackexchange.com/a/94422/2789
Answer: @user379468, could you share your code? I cannot seem to implement the page callback in hook_menu() properly (step 3. in your answer).
Comment: Never minder, I got it. A page callback isn't necessary.

Using menu tab for each panel variant


Segment a data group into 3 that have lowest possible equal standard deviation

Question: Let's say
I have 9000 customers with different number of orders. I would like to segment them into 3 consistent groups so that I will run different marketing campaigns for each of them.
So that I have to split into 3 different groups which has close (similar) standard deviation between each other.
One group can have 1000 customer other may be 500 maybe the other one has 7500. But I would like to choose even ( similar ) audience
What is the best way of doing this?
Comment: If you want the best design for an experiment comparing marketing campaigns, you should try to have group sizes, group means, and group standard deviations all about about the same for the three groups.
Answer: An easy way to get three groups of about the same size and with about the same mean and standard deviation is as follows: (1) Sort the data from smallest to largest, (2) Take observations 1, 4, 7, 10, etc. for Group 1, observations 2, 5, 8, 11, etc. for Group 2, and observations 3, 6, 9, 12, etc. for Group 3.
Here is an example, using $n = 90$ to illustrate. (This is from R statistical
software. Numbers in brackets are indexes of the first number in each row of output.)
Simulate 90 observations:
x = round(rnorm(90, 100, 15), 1); x
 [1] 103.6  97.0  84.5 107.2  88.1 120.1  92.0 102.2  97.8 101.6
[11]  79.7 127.0 124.6  95.3  96.8 102.6 101.4  86.8  83.3 136.2
[21] 117.8  90.9 111.9  76.9 109.1 110.6 117.3 118.1 124.4  82.9
[31]  89.8 114.3 114.2 116.3 105.2  96.1 120.5  97.3 100.4 124.7
[41]  89.6 109.5 105.1 106.4  92.1  98.2 110.0 120.3  88.4 109.2
[51]  77.6 101.4  78.9  80.2  86.0  78.1  74.4  73.9  93.3  82.2
[61] 116.2  92.3 129.9  81.7  89.3  83.5  95.5 126.4 127.1  95.1
[71]  80.3  83.3  89.7  84.3  91.1  82.6  96.2 110.3  86.4  97.5
[81]  99.2  77.5 109.1  79.6  80.9  92.2 116.8 121.3  84.1 135.9

The overall sample mean and standard deviation are:
mean(x);  sd(x)
[1] 99.51778
[1] 15.97716

Sort observations:
x0 = sort(x); x0
 [1]  73.9  74.4  76.9  77.5  77.6  78.1  78.9  79.6  79.7  80.2
[11]  80.3  80.9  81.7  82.2  82.6  82.9  83.3  83.3  83.5  84.1
[21]  84.3  84.5  86.0  86.4  86.8  88.1  88.4  89.3  89.6  89.7
[31]  89.8  90.9  91.1  92.0  92.1  92.2  92.3  93.3  95.1  95.3
[41]  95.5  96.1  96.2  96.8  97.0  97.3  97.5  97.8  98.2  99.2
[51] 100.4 101.4 101.4 101.6 102.2 102.6 103.6 105.1 105.2 106.4
[61] 107.2 109.1 109.1 109.2 109.5 110.0 110.3 110.6 111.9 114.2
[71] 114.3 116.2 116.3 116.8 117.3 117.8 118.1 120.1 120.3 120.5
[81] 121.3 124.4 124.6 124.7 126.4 127.0 127.1 129.9 135.9 136.2

Separate into three groups, each with mean about 100 and standard deviation
about 16.
x1 = x0[seq(1, 88, by=3)];  x1;  mean(x1);  sd(x1)
 [1]  73.9  77.5  78.9  80.2  81.7  82.9  83.5  84.5  86.8  89.3
[11]  89.8  92.0  92.3  95.3  96.2  97.3  98.2 101.4 102.2 105.1
[21] 107.2 109.2 110.3 114.2 116.3 117.8 120.3 124.4 126.4 129.9
[1] 98.83333
[1] 15.91439

x2 = x0[seq(2, 89, by=3)];  x2;  mean(x2);  sd(x2)
 [1]  74.4  77.6  79.6  80.3  82.2  83.3  84.1  86.0  88.1  89.6
[11]  90.9  92.1  93.3  95.5  96.8  97.5  99.2 101.4 102.6 105.2
[21] 109.1 109.5 110.6 114.3 116.8 118.1 120.5 124.6 127.0 135.9
[1] 99.53667
[1] 16.24751

x3 = x0[seq(3, 90, by=3)];  x3;  mean(x3);  sd(x3)
 [1]  76.9  78.1  79.7  80.9  82.6  83.3  84.3  86.4  88.4  89.7
[11]  91.1  92.2  95.1  96.1  97.0  97.8 100.4 101.6 103.6 106.4
[21] 109.1 110.0 111.9 116.2 117.3 120.1 121.3 124.7 127.1 136.2
[1] 100.1833
[1] 16.2856

Addendum: The method above has a very slight bias for the sample means to increase from Group 1 to Group 3, which will be less pronounced for larger sample sizes. Perhaps (depending on the population sampled) it may also produce a slightly smaller standard deviation for Group 2.
Choosing the groups at random (without replacement) eliminates the bias, but
may yield larger (random) variations among the group sample means and standard deviations.
To implement this method, I randomized the indices and picked every third index for Group 1, and so on. (In R %% stands for modular arithmetic: a method of
sampling every third value according to the randomly permuted indexes.)
y = x0;  i = 1:90
ip = sample(i)                        # randomly permute indexes
y1 = x0[ip%%3==0];  mean(y1);  sd(y1)
[1] 100.4333
[1] 16.29746
y2 = x0[ip%%3==1];  mean(y2);  sd(y2)
[1] 96.94667
[1] 13.51152
y3 = x0[ip%%3==2];  mean(y3);  sd(y3)
[1] 101.1733
[1] 18.01955

For example here is Group 3 according to this method:
y3
 [1]  74.4  77.6  78.9  79.6  80.2  80.9  82.9  83.5  84.5  86.4
[11]  90.9  91.1  95.5 100.4 101.4 101.4 102.2 106.4 110.0 110.3
[21] 114.3 116.2 116.3 117.8 118.1 120.1 120.5 121.3 135.9 136.2


How to easily play a trill on the high G on the flute?

Question: In "God Rest Ye Merry Mallets," the flute part comes with a high G with a trill: G and A. However, there's a diminuendo, and I've noticed that when I try to diminuendo the trill, it starts off with high G and high A, then low and low A. Can anybody give me tips on how to produce a smooth trill between high G and A without the sound lowering to the low G and A?
By the way, the "high G" is the last and highest G shown in the image.
Comment: I understand the question.  Not being a wind player I will post this idea as a comment not an answer:  Focus on breath control.  Also, even though this passage is decrescendo-ing, you can postpone your decrescendo, i.e. don't start it out right exactly where marked.
Comment: I'm having trouble following your description. Could you post an image of the measure that's giving you trouble? Most importantly, what G do you mean by high G? The G immediately above the staff, or the one an octave above that?
Comment: @Karen Sorry for the confusion. The G is the last one in the image, the highest G shown in the G major scale ascending, treble clef.
Answer: It's likely that you are playing the high notes by simply blowing harder until the octave changes. Using this method, you have very little volume control in the second octave, as you've found, and the highest note you can play will be much lower than you'll need if you want to play more advanced music. It's a very common problem for beginners, and as you get better, it will feel like it improves naturally.
Here's an exercise to work on to fix the problem. Instead of blowing harder, you need to learn to focus to angle of your breathe. Do this by playing long tones. Pick a note, and play it as long as you can. Focus the shape of your mouth to make the sound as pure and un-breathy sounding as possible. Try doing this across a whole scale, if you have the patience. The exact best shape will vary for each note, but you'll have to experiment to find out just what it feels like. The higher the note, the more precisely focused your breath needs to be.
You'll know you've made really good progress when you can sustain high and low notes for equal amounts of time, and control the volume of both.
Comment: Thank you so much! This has really helped me, since I am a beginner at flute, and I've gotten extremely better at sustaining high notes.


Android Studio 3.2: How to remember Android XML code style?

Question: I have to go to Preferences... > Editor > Code Style > XML to select Use custom formatting settings for Android XML files again and again everytime I create a new project.

I'm using Android Studio 3.2.1, macos 10.14.
Comment: Hey Danh!. I am facing the same problem and I think it is happening because I am using git and I have ignored .idea/ directory. I have tested that if I don't ignore .idea directory then Android studio does remember the last configuration.
Answer: You can create you own codeStyle:

Just export your codeStyle to file and use in each project. Or you can Copy to IDE... and it will remain in the IDE.
Comment: Thanks for your answer! It still could not remember the configs.


Duvida com AngularJS

Question: O que tem de errado com esse código? Estou tentando executar ele, mas de forma alguma ele me mostra os dados vindos do banco!

var app = angular.module('app', []);

app.controller('clienteController', ['$scope', '$http', clienteController]);

function clienteController($scope, $http) {
  $http.get('http://localhost:3091/api/ClientesWebAPI/Getcliente')
    .success(function (data) {
      $scope.listaclientes = data;

    })
    .error(function () {
      $scope.erro = "Erro: Nao foi possivel carregar.";
    });
}

Listagem de Clientes

Lista de clientes

                    {{erro}}

                                ID
                                Nome
                                Email
                                Idade
                                Data nascimento
                                Data cadastro

                                {{ cliente.id_nome }}
                                {{ cliente.nome }}
                                {{ cliente.idade }}
                                {{ cliente.sexo }}

Answer: Falta voce colocar o ng-app="app" para o angular iniciar e renderizar na sua página.
Aonde está

Deve ficar

Não esqueça de verificar se você colocou as referências para os arquivos do AngularJS na sua pagina.

Abaixo segue um exemplo funcionando:

var app = angular.module('app', []);

app.controller('clienteController', ['$scope', '$http', clienteController]);

function clienteController($scope, $http) {
  $http.get('http://localhost:3091/api/ClientesWebAPI/Getcliente')
    .success(function (data) {
      $scope.listaclientes = data;

    })
    .error(function () {
      $scope.erro = "Erro: Nao foi possivel carregar.";
    });
}

Listagem de Clientes

Lista de clientes

                    {{erro}}

                                ID
                                Nome
                                Email
                                Idade
                                Data nascimento
                                Data cadastro

                                {{ cliente.id_nome }}
                                {{ cliente.nome }}
                                {{ cliente.idade }}
                                {{ cliente.sexo }}

Comment: mesmo assim, nada ainda... que foda!
Comment: quando voce clica no executar da minha resposta nao faz nada?
pra mim aqui faz: ele tanta comunir o service que ta rodando na porta 3091 do localhost ... verifica se seu servico esta rodando nessa porta mesmo e se ele esta respondendo.
Comment: verifica tambem se no seu DevTools ... se está dando alguma mensagem de erro quando voce carrega a pagina. Confere se voce fez a referencia para o angular.js , igual foi feito no exemplo que eu postei ...
Comment: agora deu certo. O que estava causando o erro era nada mais nada menos que as bibliotecas
**

**

obs: Estou desenvolvendo no visual studio, dai certa dificuldade!! Obrigado André :D
Comment: essas bibliotecas estao na resposta justamente pra que o codigo funcione aqui no site. mas na sua versao, ou voce mantem essa ou declara voce msm... mas se resolveu o seu problema, está valendo!!! o que era no final das contas? de fato faltava o `ng-app`?
Comment: tambem, mais o principal problema era o link das bibliotecas declaradas em cima... não tinha elas auhauhauhauahuah erro de iniciante!!
Comment: Então vou atualizar a resposta e aí vc marca!! Fechou!

Duvida com AngularJS


How secure does my home windows network really need to be?

Question: I've got what I suspect is pretty close to the "standard" nerd home setup these days - I've got a Windows PC or two, a media PC hooked up to my TV, and a pair of iPhones, all sitting behind a wireless router/NAT/DSL Modem.  No server and no Domain, just classic windows peer-to-peer networking.
Since this is a home network there isn't anything much more valuable than Doctor Who episodes and word processor documents on the systems.  In a best case scenario, we wouldn't have any security at all so my wife and I could move files and such around without hassle, but we'd really just as well not have any black hats decide to p0wn the system.
Currently, we've got the full security turned on with the wireless - and that's about it.  The default accounts on the windows boxen are Administrator level accounts without passwords.  Shared folders on the network are fully shared without needing any credentials.
So, the question is, how much do I really need at home?  Can I turn off the Windows Firewall?  Can I turn on remote desktop given that the accounts all have a password of <enter>?
To put it succinctly, for home use, do I really need anything stronger than just a WPA2 wireless router password and a hardware NAT?
Comment: I will allow it for now under the banner of sysadmins / IT pros relating their home setups..
Comment: A prime question for superuser.com when it opens!
Comment: @Copas - True!  Still, we'll get the pumps primed here at serverfault, I suppose.  Mostly, I wanted to see what the rest of the professional IT crowd actually had at home.
Answer: Once upon a time, I was walking by my poor little Linksys router on a Sunday afternoon, and noticed that the activity lights were blinking like mad.  Since no one in the house was actively using a PC at the time, I thought it merited some investigation.
Network setup at that time:
DSL Modem -> Linksys wireless router with WEP key and Mac filtering -> 2 Windows XP boxes without remote desktop enabled, and a poor, long-suffering PII-333 running FreeBSD sitting in the DMZ.
Further review of the logs on the FreeBSD system indicated that I was being portscanned rather enthusiastically from about 12 different IPs from two different country codes.
Bonus headache points:   the one friend I gave a shell account to, so that he could SSH in from his workplace?   Yeah, he used a bad password.   Silly me.
Steps I took at the time:
- Stopped broadcasting the SSID for the wireless
- Implemented MAC filtering at the wireless router
I use the wireless so infrequently, and from only one device that this made sense for me.

Turned wireless off by default
... it's not that much more effort to kick one of the kids off a WinXP desktop and enable the wireless on the AP via the admin interface before I retreat to the couch with the laptop.
Told myself repeatedly that stuff doesn't need to live in the DMZ without a Good Reason

Who knew it was that easy to open ports on my Linksys so that I could properly enjoy a game of Team Fortress?   READ YOUR ROUTER'S DOCUMENTATION.

Moved SSH to a non-default port on my UNIX box

I'm still seeing at least two portscans per day on my home DSL connection, and friends in the neighborhood who have same provider have also indicated they're seeing portscans on a regular basis.    Thanks to laziness, they're only scanning commonly used ports.

Moved to using SSH keys instead of passwords on the UNIX box.
If they find my SSH port, they need my SSH key.

Steps I'm planning to do when I get time:
- Set up a pfsense-based firewall/router again.   Previous one had a HD failure, and I put the linksys back into service as the router.
Answer: My thoughts ...
1- DSL Router: standard NAT, turn off external access to web admin, turn off Universal Plug-n-Play, use ShieldsUp to make sure that you are locked down.
2- Wireless: If you use wireless then encrypt with WPA2.  Don't bother hiding the SSID; that is useless comfort.  Use MAC-address locking if you won't add devices often.  I have friends and the kids friends over a lot, so I don't.
3- External Access: I would use a VPN rather than just boring firewall holes for SSH or other remote access.  Some consumer routers have them (or see my note about the Astaro below).
4- Passwords:  I would put relatively strong passwords on the systems, even if they are all the same thing or all known by the family.
5- Admin-level: Come on now .. surely you know better!  I would avoid running at Admin-level for regular use, even if everyone knows the password.
6- Backups: What are you securing?  You indicated that all you have to lose is some media.  I would challenge that.  Do you do your finances?  Do you have family pictures?  You need to have backup handled .. see this question for a discussion on home backups.
If you want to have some fun and get even more secure and granular, get the (free for home use) Astaro Security Gateway software and put it on an old PC with two NICs.
Comment: The most important data in the world is my wife's digital pictures.  OK, maybe my boss' wife's digital pictures!
Answer: It's a "superuser.com" question, but the same principles apply to a home network w/ respect to least-privilege, keeping backups, etc.
Remember that all the programs you run (either on purpose, or when a bug causes arbitrary code to be executed on your computer) gets whatever rights you have. That might make you think about using non-privileged user accounts.
If you care about keeping your data when you accidently run a worm, trojan horse, etc, you might also consider keeping offline backups. The trojan can smash all the files your least-privileged user account has access to, but it can't touch files on a disconnected hard disk drive sitting on a shelf (or better, in some other building that won't burn / blow away / flood when your house does).
Perhaps you don't have any data you care about being made public, but give a thought to what the thieves are going to get when they steal your computers. You might re-think using encryption with strong passphrases for at least some of your files.
Answer: I would leave on the windows firewalls and add exceptions as necessary. Have multiple layers of security. Do you upgrade your modem/router firmware regularly?
remote desktop is okay to open, but for sure use authentication.
Cheers,
-Mathew
Answer: Your setup is very similar to mine.  Only differences is I leave firewalls on (with exceptions added) and I add MAC address filtering to the WPA2 wireless security.
Comment: @Brad I also disable broadcast on my wireless router.  It's just one more step toward securing the environment.  I also run a domain on my home network with Windows Server 2k3 just for fun with login scripts, enterprise anti-virus, etc.
Answer: I don't run a firewall on any of my home computers, even though they have fully routable IP addresses, mostly because I have a firewall in front of them, which only lets in the smallest amount of traffic necessary.
I don't encrypt my wireless either, because it's on a separate subnet to my main network and is mac-address locked to access the Internet.
It's a matter of how happy you are with your protection and how much damage anyone could cause. How important is your data? Is it backed up? How much work would it be to recover it?
Comment: yes, MAC Address spoofing is trivial ... to a tiny proportion of the population. All you've got is some Internet access. I'm happy with that risk.
Comment: MAC Address spoofing is trivial


Getting arguments from a bundle

Question: I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);

        DetailActivityFragment fragment = new DetailActivityFragment();

        Bundle bundle = new Bundle();
        bundle.putString(INTENT_EXTRA, message);

        fragment.setArguments(bundle);
    }

I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments() from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();

        if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
            forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
        } else if (bundle == null) {
            Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
        }

    }

The upper method displays a Toast message "Error" when I run the app...
Comment: you are creating different DetailActivityFragment instance  somewhere (without arguments) ... and using it instead this one
Comment: **Which** is the error you get? Can you post your **logcat**, please? Are you using any **transaction**? can you **show it** to us?
Comment: where is the FragmentTransaction ? Did you declare the Fragment in the Manifest ?
Answer: The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
public static myFragment newInstance(String param1, String param2) {
    myFragment fragment = new myFragment ();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

And then on create set your global arguments:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

on your main activity you will create the fragment like
myFragment __myFragment = myFragment.newInstance("test","test");

That should work
Comment: Should have been the accepted answer because it instantiates the fragment, sets and gets arguments through bundle state in the right way.
Answer: This is a correct approach
Send (in the Activity):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

final DetailActivityFragment  frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);

final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);

ft.commit();

Receive (in the Fragment):
final Bundle bdl = getArguments();

String str = "";
try
{
    str = bdl.getString("yourKey");
}
catch(final Exception e)
{
    // Do nothing
}

Comment: It works but at the same time it throws this exception:

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

Do you know why this happens?

Thanks for your answer!
Comment: **1** - Make sure you have this import: `import android.os.Bundle;`. **2** - Don't forget to add this line `final Bundle bdl = getArguments();` or your Bundle reference would be **null**.
Comment: Yes I have them both. But it is strange. It does work and it does pass the right arguments (I see them on my results) but at the same time it says that the bundle is null. Weird stuff!
Comment: I'm assuming that you run the receiving code in the Fragment's `onCreateView()` method. Otherwise, the Bundle might still not have been passed completely.

Getting arguments from a bundle


How to automatically post a message with the discount on the site?

Question: I have a store with Commerce 2 and Drupal 8.
In my store I created a reminder of 20% on the whole site.
I want a message to be posted on my site with the conditions, the percentage, the end date and the description of the discount.
A bit like this :

How can I do this ?
Thank you
Answer: There is no tool for general messages like this, because every site will construct its front-end differently. If this is only an occasional matter, you'd be best just creating the content manually. If it's going to happen with some regularity, you may just be best using custom code to define a template that can load a promotion entity and fill in the offer details from its fields.
Comment: I finally found a solution using the description field of the discount in my view.
Comment: I created a discounted view. Can not display the amount of the discount, there is nothing in the view. How to do ?
Comment: My recommendation was for custom code b/c I wasn't sure how integrated into Views all the parameters of a promotion are. How in control of the theme layer are you?


Cython: why "duplicate symbol"?

Question: I'm new to Cython, so please forgive me if this is a noob question. I'm trying to modify the primes example into a pure c++ (.h/.cpp) implementation which then is wrapped by a .pyx file.
primes.h:
#include <list>

std::list<int> primes2_c(int maxn);

primes.cpp:
#include "primes.h"

#include <list>

std::list<int> primes2_c(int maxn) {
    int n;
    std::list<int> ret;
    n = 2;
    while (n < maxn) {
        auto it = ret.begin();
        for (; it != ret.end() && n % *it != 0; it++);
        if (it == ret.end()) {
            ret.push_back(n);
        }
        n++;
    }

    return ret;
}

primes.pyx:
cdef extern from "primes.h":
    list[int] primes2_c(int)

def primes2(kmax):
    ret = primes2_c(kmax)
    return ret

primes.setup:
from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(
    name='primes',
    ext_modules=cythonize(Extension(
        'primes',
        ['primes.pyx', 'primes.cpp'],
        language='c++',
        extra_compile_args=["-std=c++11"],
        extra_link_args=["-std=c++11"],
    ))
)

Then I run the compilation and see this error:
[cython (master)]$ python primes.setup build_ext --inplace
running build_ext
building 'primes' extension
/usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Users/.../venv/cython/include -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c primes.cpp -o build/temp.macosx-10.6-intel-3.5/primes.o -std=c++11
/usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Users/.../venv/cython/include -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c primes.cpp -o build/temp.macosx-10.6-intel-3.5/primes.o -std=c++11
/usr/bin/clang++ -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/temp.macosx-10.6-intel-3.5/primes.o build/temp.macosx-10.6-intel-3.5/primes.o -o /Users/.../cython/primes.cpython-35m-darwin.so -std=c++11
clang: warning: libstdc++ is deprecated; move to libc++ with a minimum deployment target of OS X 10.9
clang: warning: libstdc++ is deprecated; move to libc++ with a minimum deployment target of OS X 10.9
duplicate symbol __Z9primes2_ci in:
    build/temp.macosx-10.6-intel-3.5/primes.o
ld: 1 duplicate symbol for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command '/usr/bin/clang++' failed with exit status 1
[cython (master)]$

My understanding is that primes.pyx only reads the API of primes2_c() but not the implementation. So the only implementation provided for the same function should be from the reference to primes.cpp in primes.setup.
Comment: I'm not familiar with `Cython.build`, but from the build log you can see that it's compiling `primes.o` from `primes.cpp` *twice*, and then when it tries to build the `.so` it's trying to link in `primes.o` twice.
Comment: Your observation is correct. I also observed that. My OP was trying to ask "why implementation in primes.cpp is linked twice".
Answer: Could you rename primes.cpp to e.g. primesc.cpp?  I think primes.pyx is compiled to primes.cpp by Cython as part of the build, so there's a filename clash.
Comment: Indeed, as you said, naming both `.cpp` and `.pyx` using the same primary filename was the problem. However, it's unexpected for me, and I'd like to think it's an issue on Cython side, since it generates a build folder anyways, and I'd expect any intermediate file to be placed into the build folder. But anyways, thank you for your answer!
Comment: I further discovered that the `.pyx` file should have the same name as the package name, since renaming it into something like `wrapper.pyx` will lead to `ImportError: dynamic module does not define module export function (PyInit_prime)`. The hardcoded naming rules here are quite easy to miss for newbies IMHO.

Cython: why "duplicate symbol"?


Erro ao ler todos os registros de um arquivo.txt em C

Question: Alguém sabe me dizer porque esse meu código apenas retorna o primeiro registro várias vezes, ao invés de retorna todos os registros?
Função no Código
void listarDados(int quantidadeContatos) {
    char caracteres;
    FILE *arquivo = fopen("contato.txt", "rb");
    struct contato *vPtrContato = &contato_ref;

    if (arquivo == NULL) {
        printf("Erro, nao foi possivel abrir o arquivo\n");
    } else {
        while (!feof(arquivo)) {
            rewind(arquivo);
            fread(vPtrContato, sizeof (contato_ref), 1, arquivo);
            printf("Nome: %s\n", contato_ref.primeiroNome);
            printf("Sobrenome: %s\n", contato_ref.segundoNome);
            printf("Telefone: %s\n", contato_ref.numeroTelefone);
            printf("E-mail: %s\n", contato_ref.email);
            printf("==================================\n");
            fclose(arquivo);
       }
    }
}

Answer: A função rewind() (falando grosseiramente) serve para retornar ao começo do arquivo, ou seja fread passa adiante mas o rewind volta para o começo.
Comment: Tirei o rewind e mesmo assim ainda retorna apenas o primeiro registro. Só que repetidas vezes.
Comment: Não havia visto, você fecha o arquivo dentro do while, apague a linha do fclose() e veja.
Answer: Código com a listagem completa de todos os registros do arquivo txt
void listarDados() {
    FILE *arquivo = fopen("contato.txt", "rb");
    struct contato *vPtrContato = &contato_ref;

    /*se o arquivo nao existir, mostra msg de erro*/
    if (arquivo == NULL) {
        printf("Erro, nao foi possivel abrir o arquivo\n");
    } else {
        /*caso o arquivo exista, leia-o ate o fim do arquivo*/
        printf("==================================\n");
        printf("Resultado da pesquisa\n");
        printf("==================================\n");
        while (!feof(arquivo)) { //enquanto não chegar no fim do arquivo, continue lendo
            /*funcao para ler arquivo
             referencia do elemento que sera lido, que no caso e a referencia d struct
             * a quantidade de dados que sera lida, que no caso e o tamanho da struct
             * referencia do arquivo
             */

            fread(vPtrContato, sizeof (contato_ref), 1, arquivo);

            printf("Nome: %s\n", contato_ref.primeiroNome);
            printf("Sobrenome: %s\n", contato_ref.segundoNome);
            printf("Telefone: %s\n", contato_ref.numeroTelefone);
            printf("E-mail: %s\n", contato_ref.email);
            printf("===================================\n");
        }
        fclose(arquivo);
    }
}

Answer: O problema está sendo causada pela função rewind, pois ela possui o papel de voltar para o começo do arquivo.


How would I make a recursive trace print out like this?

Question: So I am trying to print out a trace of a recursive function of the Fibonacci sequence.
My output should be like this:

However, I am unsure of how to format this. I don't really know where to start.
I've tried this:
private static int fibCount;

public static long fibonacci(int n) {
    fibCount++;
    long result;
    if (n == 0 || n == 1) {
        result = n;
        System.out.printf("fib(%s)-->%s%n", n, result);
    } else {
        result = fibonacci(n - 1) + fibonacci(n - 2);
        System.out.printf("fib(%s)%n", n);
    }
    return result;
}

public static void main(String args[]) {
    fibonacci(5);
}

Which prints out
fib(1)-->1
fib(0)-->0
fib(2)
fib(1)-->1
fib(3)
fib(1)-->1
fib(0)-->0
fib(2)
fib(4)
fib(1)-->1
fib(0)-->0
fib(2)
fib(1)-->1
fib(3)
fib(5)

I feel like I need to use that fibCount variable (I made it just because I thought the indentations would rely on it), but I don't know if I should, or how.
Answer: Try the following:

Split up your recursive calls (so you can print current call in between)
pass in a depth parameter to keep track of how much to indent

public static long fibonacci(int depth, int n) {
    String indent = new String(new char[depth]).replace('\0', ' ');
    long result;
    if (n == 0 || n == 1) {
        result = n;
        System.out.printf(indent + "fib(%s)-->%s%n", n, result);
    } else {
        long first = fibonacci(depth+1, n - 1);
        System.out.printf(indent + "fib(%s)%n", n);
        long second = fibonacci(depth+1, n - 2);
        result = first + second;
    }
    return result;
}

public static void main(String args[]) {
    fibonacci(0, 5);
}

Output:
    fib(1)-->1
   fib(2)
    fib(0)-->0
  fib(3)
   fib(1)-->1
 fib(4)
   fib(1)-->1
  fib(2)
   fib(0)-->0
fib(5)
   fib(1)-->1
  fib(2)
   fib(0)-->0
 fib(3)
  fib(1)-->1

Answer: You need to pass in the level of indentation with each call.  Each time you recourse you can increased the indentation.
public static long fibonacci(int n) {
    return fibonacci(n, 1);
}

public static long fibonacci(int n, int indent) {
    System.out.printf("%"+indent+"s", "");
    long result;
    if (n == 0 || n == 1) {
        result = n;
        System.out.printf("fib(%s)-->%s%n", n, result);
    } else {
        result = fibonacci(n - 1, indent + 2) + fibonacci(n - 2, indent + 2);
        System.out.printf("fib(%s)%n", n);
    }
    return result;
}

Comment: You can't pass `0` as width in a format string. Also, OP was after "infix" printout of current call.
Answer: You should keep a sort of  indentation counter that gets incremented every time you enter your fibonacci function and decremented every time you leave it.
Then, when printing, put as many spaces as the current value of this counter just before the actual printing. For better viewing you can put twice as much spaces, but this is just a personal choice.
Answer: I'm assuming that in the real world, you'd only put in a trace like this (and particularly one using a static variable) as a temporary debugging measure, and delete the code before you put it into production.  If you want to leave it in production code, I'd look for a different solution.
First, if you're going to use a static variable for this, you need to make sure each recursive invocation restores its value afterwards.  It might be best to do this in a finally block, to make sure that the restoration always happens even if there's a return hidden somewhere inside the code (or in case of an exception):
public static long fibonacci(int n) {
    int saveFibCount = fibCount;
    fibCount++;
    try {
        fibCount++;
        long result;
        if (n == 0 || n == 1) {
            result = n;
            System.out.printf("fib(%s)-->%s%n", n, result);
        } else {
            result = fibonacci(n - 1) + fibonacci(n - 2);
            System.out.printf("fib(%s)%n", n);
        }
        return result;
    } finally {
        fibCount = saveFibCount;
    }
}

Second, to get this into your indentation: Unfortunately, Java doesn't have a built-in method to return a string of n spaces.  You can write one easily enough (or use methods available in Apache Commons, I think), and use them this way:
        if (n == 0 || n == 1) {
            result = n;
            System.out.printf("%sfib(%s)-->%s%n", blanks(4*fibCount), n, result);
        } else {
            result = fibonacci(n - 1) + fibonacci(n - 2);
            System.out.printf("%sfib(%s)%n", blanks(4*fibCount), n);
        }

where blanks(b) returns a string of b blanks.  You can use StringBuilder to create the blank string, or something like:
String blanks = String.format("%" + numOfBlanks + "s", "");

[Note: according to a comment on another answer, this does not work if numOfBlanks is 0.]
Or you can replace fibCount with a String fibIndent, and instead of fibCount++ use
fibIndent += "    ";

after saving the previous version.
Another thing to consider: if this were production code, I would recommend passing another parameter to the recursive routine, instead of using static variables.  Trying to handle static variables with a recursive routine is just messy and error-prone, even in single-threaded programs.  The recursive parameter should be a value parameter or an immutable object that is copied by each invocation before passing it to the next one.  In this case, the "recursive depth" (your fibCount) could be the parameter.  I don't recommend passing a reference to an object that all recursive invocations would share, because that is almost as error-prone as using a static variable (although more thread-safe).
[Note: I've spend much of my career working on a recursive-descent compiler, so a lot of these issues are very familiar to me.]
[Finally: I know this is just for practice, but don't use recursion to compute Fibonacci numbers.  Doing so gives you an exponential algorithm, instead of a linear algorithm as a straightforward loop would be.  This is because the recursive algorithm performs a huge amount of redundant work, computing the result for the same argument many multiples of times.]


Cannot switching view back in iPhone

Question: I have a problem with switching the views in iPhone simulator.I had written a code that can switch views back and forward but now when I had run it in the simulator I found that the app only switches the view forward but I am unable to switch the view back. I am unable to trace out the problem in my code. Will be thankful if anyone had helped me trace out the problem with my code.
My code is :
SwitchingViewsViewController.h
<code>#import <UIKit/UIKit.h>

@interface SwitchingViewsViewController : UIViewController
{

}
-(IBAction)switchback:(id)sender;
@end
</code>
SwitchingViewsViewController.m
<code>#import "SwitchingViewsViewController.h"
#import "secondview.h"

@interface SwitchingViewsViewController ()

@end

@implementation SwitchingViewsViewController

-(IBAction)switchback:(id)sender
{
    secondview *second = [[secondview alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:second animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:  (UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
</code>
secondview.h
<code>#import <UIKit/UIKit.h>

@interface secondview : UIViewController
{

}
-(IBAction)switchview:(id)sender;
@end
</code>
secondview.m
<code>#import "secondview.h"
#import "SwitchingViewsViewController.h"

@interface secondview ()

@end

@implementation secondview

-(IBAction)switchview:(id)sender
{
    SwitchingViewsViewController *second = [[SwitchingViewsViewController alloc]  initWithNibName:nil bundle:nil];
    [self presentModalViewController:second animated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
</code>
Thanks in advance.
Comment: What do you know so far? Have you confirmed that -switchview and -switchback are both called when you expect them to be? Perhaps more importantly do you realize that those methods both push _new_ modal view controllers? Assuming those are called you seem to be trying to build an ever deeper stack of modals. You probably want the top controller to dismiss itself instead.
Comment: if you got the solution make habit of accept the answer.
Comment: Thanks a lot pratik...i just resolved it..was working on some other app and am very new to stack overflow :) .Thank you very much.
Answer: use this in second view
<code>-(IBAction)switchview:(id)sender
{
[self dismissModalViewControllerAnimated:YES];
}
</code>
Answer: <code>@implementation secondview

-(IBAction)switchview:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}
</code>

Cannot switching view back in iPhone


Every projective module is a direct summand of free module.

Question: I was reading "Serial Rings" by Gennadi Puninski. There it is written that , "Since every module is a homomorphic image of a free module, every projective module is a direct summand of free module".(ie. if $P$ is a  projective module, there exists a free module F such that,
$ F=P \oplus T$ for some module $T$.)
But I can't understand how "Every module is a homomorphic image of a free module" implies that "Every projective module is a direct summand of free module".
(I have found a proof for "Every projective module is a direct summand of free module" but the first part of the above mentioned sentence wasn't used there.)
Comment: The linked questions go very much into detail about every aspect of this problem.  They seem to answer your question thoroughly, and with the same methods given in the answer you accepted here.
Answer: Let $P$ be a projective module. We wish to show that it is the direct summand of a free module. Let $\varphi : F \to P$ be a surjection, where $F$ is a free module.
Consider the following diagram below.

Since $P$ is projective, there exists a map $\psi : P \to F$ making the following diagram commute.

It now follows that $F = \operatorname{im} \psi \oplus \ker \varphi$. But $\varphi \circ \psi = \operatorname{id}_P$ implies that $\psi$ is injective and thus, $\operatorname{im} \psi \cong P$, as desired.
Comment: @SuchandraKundu: I have used the fact when I said "Let $\varphi : F \to P$ be a surjection". Existence of such a $\varphi$ and $F$ is precisely the same as $P$ being the homomorphic image of a free module.
Comment: Okay thank you very much for clarifying. I am new to all these.
Comment: If someone can replace the images with code for the appropriate commutative diagrams, please feel free to do so.
Comment: Thank you very much sir. But can you prove it using the fact that, "Every module is a homomorphic image of a free module."?


Determinant and Measure

Question: The determinant of the matrix of its vectors gives the measure of an $n$-dimensional parallelogram.
For example, in $2$ dimensions, the area spanned by vectors $v$ and $w$ is
\begin{array}{|cc|}
v_1 & w_1 \\
v_2 & w_2 \\
\end{array}
and so forth for a $3$ or more -dimensional parallelogram.
How is possible to visualize that, or understand that intuitively?
Comment: Have a look at "Linear Algebra via Exterior Products" by S. Winitzki: http://sites.google.com/site/winitzki/linalg , pagg.30-31.
Answer: You can see the determinant when changing variables of integration in two or three dimensions. The determinant can be viewed as the Jacobian of the transformation
$$ (x,y) \mapsto (v_1x+v_2y,w_1x+w_2y)$$
and this maps the unit square onto the parallelogram spanned by $(v_1,v_2)$ and $(w_1,w_2)$. The unit square has area 1 and therefore the determinant balances the equation.

Determinant and Measure


Finding eigenvalues of a block matrix.

Question: Suppose $A\in M_n(C)$ and define $B = \begin{pmatrix}O & A\\ A & 2A\end{pmatrix}$. Find eigenvalues of $B$ in terms of $A$.
I know that to find eigenvalues of $B$ we have to solve $det(B-xI)=0$. Also, $B$ has square blocks of the same order so based on Determinant of Block matrices:  $det \begin{pmatrix}-xI & A\\A & 2A-xI\end{pmatrix}= det((-xI)(2A-xI) -A^2)$.
But I don't know how to solve the equation.
Comment: Please not that in general $\det\begin{bmatrix} A & B \\ C & D \end{bmatrix} \neq \det(AD - BC)$. It holds here since the 1,1 block is mutiple of $I$. I am not sure if you really ment it like this but the parenthesis suggest that a bit so I am leaving this here for completeness.
Comment: can you factorize the quadratic formula in the determinant? (write it as $det(A-yI)det(A-zI)$)
Answer: The quick approach is to simply note that $B$ is the Kronecker product $B = M \otimes A$, where
$$
M = \pmatrix{0&1\\1&2}.
$$
Because the eigenvalues of $M$ are $1 \pm \sqrt{2}$, the properties of the Kronecker product imply that the eigenvalues of $B$ will be of the form $\lambda (1 \pm \sqrt{2})$ for all eigenvalues $\lambda$ of $A$.
Alternatively, we can continue your approach to note that
$$
\det(M - xI) = \det(-xI(2A-xI) -A^2) = \det(x^2 I - 2x A - A^2)\\
= \det([xI - (1 - \sqrt{2})A][xI - (1 + \sqrt{2})A]).
$$
Answer: Let $(V_k,\lambda_k$) be the eigenpairs of $A$, meaning that:
$$AV_k=\lambda_kV_k\tag{1}$$
Let us look for eigenvectors of $B$ under the following form:
$$\begin{pmatrix}O & A\\ A & 2A\end{pmatrix}\begin{pmatrix}V_k\\ aV_k\end{pmatrix}=\mu_k\begin{pmatrix}V_k\\ aV_k\end{pmatrix}$$
which is equivalent (due to (1)) to the fact that:
$$\begin{cases} a\lambda_kV_k&=&\mu_kV_k\\
 (1+2a)\lambda_kV_k&=&a\mu_kV_k\end{cases} \ \implies \ \begin{cases} a\lambda &=&\mu_k\\
 (1+2a)\lambda_k&=&a\mu_k\end{cases}\tag{2}$$
therefore, we have the proportionnality:
$$\dfrac{1+2a}{a}=a$$
a quadratic equation with roots $a'=1-\sqrt{2}$ and $a''=1+\sqrt{2}$.
Therefore, using the fact that $a\lambda_k=\mu_k$, the $a'\lambda_k$ and the $a''\lambda_k$ are eigenvalues with specific eigenvectors.
As $B$ is a $2n \times 2n$ matrix, we have thus found all of them.
Remark: The idea to look for eigenvectors having the given form comes from the habit to work on the Kronecker form as in the solution given by @Ben Grossmann.
Comment: @Korf Thank you very much.

Finding eigenvalues of a block matrix.


Finding the number of distinct sequences of length 10, with 5 consecutive 1s or 0s

Question: I'm trying to find the number of distinct 10-length sequences that contain at least 5 consecutive 1s or 0s.
My thoughts: For precisely 5 consecutive 1s, we have:
111110xxxx
0111110xxx
x0111110xx
xx0111110x
xxx0111110
xxxx011111
(where X can be either 1 or 0). There are $2^4+2^3+2^3+2^3+2^3+2^4 = 64$ combinations.
For 6 consecutive 1s:
1111110xxx
01111110xx
x01111110x
xx0111111x
xxx0111111
Total = 32
For 7 1s:
11111110xx
011111110x
x011111110
xx01111111
Total combinations = 12
For 8 1s:
111111110x
0111111110
x011111111
Total combinations = 5
For 9 1s:
1111111110
0111111111
Total combinations = 2
For 10 1s:
Total combinations = 1
If we add up all the combinations, we get 116 combinations. Now, we can A or B with at least 5 consecutive occurrences, so we multiply this by 2 to give 232.
However, the actual answer is 222, and I don't know why my method isn't working.
Comment: Suppose you have a sequence $111110xxxx$ but the $xxxx$ part actually runs $0000$  You have double counted those, and need to exclude the cases with two sequences in them.
Answer: Your xx0111111x in "6 consecutive" should be xx01111110, changing your calculation
An alternative approach
11111xxxxx  32 ways
011111xxxx  16 ways
x011111xxx  16 ways
xx011111xx  16 ways
xxx011111x  16 ways
xxxx011111  16 ways

$32+5\times 16 = 112$. Double to give $224$ and subtract $2$ because 0000011111 and 1111100000are double counted
Answer: Your six consecutive should give $8+4+4+4+8=28$, not $32$, so that reduces your count to $112$.  Doubling that for five zeros gets you to $224$.  Then you have double counted $0000011111$ and $1111100000$ because you counted them once for the five ones and once for the five zeros, so subtract two.  That gives $222$.


Fourier series for $\cos( \frac x2)$

Question: I am trying to get the Fourier series for $\cos( \frac x2)$ from $[- \pi, \pi]$.
I know the general equation for a Fourier series. Since this is an even function, I know that the coefficients for $\sin(nx)$ are zero.
But I'm having difficulty solving for the coefficients for $\cos(nx)$. I know that I can't just say that the coefficient is $1$ when $n = \frac 12$, because $n$ is only integers.
Answer: We just need to evaluate the integral
$$\int_{-\pi}^{\pi}\cos(x/2)\cos(nx) dx$$
for integer values of $n$. Since the integrand is even, the integral is equal to
$$2\int_0^{\pi}\cos(x/2)\cos(nx) dx$$
We can now apply the trigonometric formula
$$\cos(a)\cos(b) = \frac{1}{2}(\cos(a+b) + \cos(a-b))$$
to obtain
$$\int_0^{\pi}\cos((n+1/2)x)dx + \int_0^{\pi}\cos((n-1/2)x) dx$$
which is simply
$$\begin{aligned}
\left.\frac{1}{n + 1/2}\sin((n+1/2)x)\right|_{0}^{\pi} + \left.\frac{1}{n - 1/2}\sin((n-1/2)x)\right|_{0}^{\pi}
&= \frac{\sin((n+1/2)\pi)}{n+1/2} + \frac{\sin((n-1/2)\pi)}{n-1/2} \\
\end{aligned}$$
If $n$ is even, then $\sin((n+1/2)\pi) = \sin(\pi/2) = 1$ and $\sin((n-1/2)\pi) = \sin(-\pi/2) = -1$.
If $n$ is odd, then $\sin((n+1/2)\pi) = \sin(-\pi/2) = -1$ and $\sin((n-1/2)\pi) = \sin(\pi/2) = 1$. So we can cleverly rewrite the above as
$$\frac{(-1)^n}{n+1/2} + \frac{(-1)^{n+1}}{n-1/2}$$
which you can further simplify as desired.

Fourier series for $\cos( \frac x2)$


Binding in Master View Model

Question: I have two view models in Knockout.js and I am aware that i can bind them separately, however is it possible for me to add them both in a Master View Model and bind it once. Something like ko.applyBindingings(MasterViewModel); Any help or advice is much appreaciated. Thanks a ton.
  var ViewModel1 = {
        id: ko.observable(""),
        name: ko.observable("")}

var ViewModel2 = {
        id: ko.observable(""),
        name: ko.observable("")}

Right now I bind it as folllows:
        ko.applyBindings(ViewModel1 , document.getElementById('div1'));
        ko.applyBindings(ViewModel2 , document.getElementById('div2'));
Answer: The other answer (@PatrickD) is correct except it has syntax errors.  The MasterViewModel is an object literal so it should be written like this:
var MasterViewModel = {
    ViewModel1 : {
      id: ko.observable(""),
      name: ko.observable("")
    },
    ViewModel2 : {
      id: ko.observable(""),
      name: ko.observable("")
    }
 };

Answer: Sure thing. In your JavaScript:
 MasterViewModel = function() {
    this.ViewModel1 = {
      id: ko.observable(""),
      name: ko.observable("")
    }

    this.ViewModel2 = {
      id: ko.observable(""),
      name: ko.observable("")
    }
 }
 ko.applyBindings(new MasterViewModel(), document.getElementById('masterDiv'));

In your HTML Markup:

You'll have to reference your ViewModels by name in your data-binding markup. This allows you to determine which ViewModel's properties to bind to.
Answer: var MasterViewModel = {
    var ViewModel1 = {
      id: ko.observable(""),
      name: ko.observable("")
    }

    var ViewModel2 = {
      id: ko.observable(""),
      name: ko.observable("")
    }
 }

 ko.applyBindings(new MasterViewModel(), document.getElementById('masterDiv');

You could also simplify your markup by using the with binding

Binding in Master View Model


Tensorflow fails to initialize batch normalization layer

Question: I'm running Tensorflow 1.12 on GPU in a conda environment. I have several batch norm layers as part of convolution blocks defined in this way:
Conv=lambda NumFilter, Input, FilterSize=PARAMS['FilterSize'] : tf.layers.conv2d(Input, NumFilter, FilterSize, strides=1, activation=None, padding='SAME', use_bias=True, kernel_initializer=PARAMS['KernelInit'])

def OneConv(layer,FilterNum,FilterSize,training):
    activate=tf.nn.relu(layer)
    norm=tf.layers.batch_normalization(activate,axis=-1,training=training)
    conv=Conv(FilterNum,norm,FilterSize)
    return conv

def ConvBlock(BlockInput,name, FilterNum, training):
    with tf.name_scope(name):

        conv1=OneConv(BlockInput,FilterNum,PARAMS['FilterSize'],training)
        conc1=tf.concat([BlockInput,conv1],axis=-1)

        conv2=OneConv(conc1,FilterNum,PARAMS['FilterSize'],training)
        conc2=tf.concat([BlockInput,conv1,conv2],axis=-1)

        BlockOut=OneConv(conc2,FilterNum,1,training)

        return BlockOut

Which I use to build the Forward function. Whenever I try to test the network with:
X=tf.Variable(np.random.randn(1,128,128,1),dtype=tf.float32)

init=tf.global_variables_initializer()
test=Forward(X)

with tf.Session() as sess:
    init.run()
    print(test.eval())

I get an error:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value BatchNorm_12/beta
       [[node BatchNorm_12/beta/read (defined at /home/riccardo/.anaconda3/envs/Tenso/lib/python3.6/site-packages/tensorflow/contrib/framework/python/ops/variables.py:277)  = IdentityT=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]]
       [[{{node ConvBlockUp1_1/conv2d_2/BiasAdd/_7}} = _Recvclient_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_520_ConvBlockUp1_1/conv2d_2/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

I can't quite figure out why the global initializer fails to initialize the batch norm layers, I also tried passing on specific initializers for the batchnorm parameters to tf.layers.batch_normalization but it did not change anything. Any idea what I am missing?
Answer: You need to create the variables initializer after you have created your model. Try:
X=tf.Variable(np.random.randn(1,128,128,1),dtype=tf.float32)

test=Forward(X)
init=tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print(test.eval())

Comment: Yes, that did it, thanks! I wasn't even looking for something that simple.


How to run a PAC proxy script in Node?

Question: I am trying to write a node program (suggestion for other language are welcome) that can parse and run a corporate proxy script PAC and return the appropriate proxy server to use programmatically.
Are there any existing solutions that can do this? (or is this only possible through a browser)
It seems like PAC files assume certain global functions exist in the execution context such as
shExpMatch()
myIpAddress() // interestingly the nodejs ip package return the true LAN DHCP assigned IP instead of a VPN IP

The goal is to resolve the right proxy server each time a shell is launched (or not set it at all if not behind a proxy)
any tip is greatly appreciate it.
Answer: If you're sticking with Node, I'd recommend using something like pac-resolver for this.
const pac = require('pac-resolver');
const fetch = require('node-fetch');
const ip = require('ip');

fetch('http://<proxy_host>:<proxy_port>')
  .then(res => res.text())
  .then(body => {
    // to handle a bug when pinging 188.8.131.52 will time out
    // see: https://github.com/TooTallNate/node-pac-resolver/issues/18
    findProxy = pac(body, { sandbox: { myIpAddress: ip.address }, });
    return findProxy('http://google.com/'));
  })
  .then(proxy => console.log(proxy))
  .catch(err => console.error(err));

In any case, you can look at the repo to see which global functions need to be defined and how that would be done in JavaScript.
If you can use other languages, look at pacparser.
The list of standard global functions, by the way, is here:

dnsDomainIs
shExpMatch
isInNet
myIpAddress
dnsResolve
isPlainHostName
localHostOrDomainIs
isResolvable
dnsDomainLevels
weekdayRange
dateRange
timeRange
alert

How to run a PAC proxy script in Node?


Swift Cannot construct string with argument type Int64

Question: I am making a game that involves a Game Center leaderboard. I want to make a custom leaderboard UI rather than using the default interface.
I am trying to convert the values stored in a Game Center leaderboard into a string so that I may display them using an SKLabelNode. However, I get an error saying that:

Cannot invoke initializer for type 'String' with an argument list of type '(Int64?)'

I am accessing the Game Center scores using
leaderboard.scores[i].value

When I use the String(describing: ) method, my label node reads "optional(10)", with whatever the score is being inside the parenthesis. I am wondering how to cleanly convey the data store in Game Center into a number in string format.
Answer: Try optional binding:
if let unwrapped = leaderboard.scores[i].value {
    let string = String(unwrapped)
    print(string)
}

Or use the guard statement if you want to use the unwrapped value in the rest of the scope:
guard let unwrapped = leaderboard.scores[i].value else {
    fatalError("Couldn't unwrap the score value")
}
let string = String(unwrapped)


the relationship between fractional difference and ACF of a time sequence

Question: When reading the GARCH modeling part of book Analysis of Financial Time Series, I read the following statement. In specific, I do not understand how does the author get that statement marked with yellow. How to get the relationship between the fractional difference with the ACF of $u_t$.
Answer: using binomial expansion the fractional difference operator $(1-L)^d$ can be rewritten as
$$(1-L)^d = \sum_{j=0}^\infty a^d_j L^j$$. One can show that the coefficients $a_j^d$ satisfy
$$a_j^d \sim \frac{1}{\Gamma(d)} j^{-1-d} \qquad\text{for } j\rightarrow\infty.$$ As a result, the acf of $u_t$ shows the same asymptotic behavior. For more details, see for example Time Series: Theory and Methods by Brockwell and Davis.


Formulas for prime counting between $n$ and $n^2$

Question: Primes less than $n$ are known, are there some formulas counting primes between $n$ and $n^2$?
For sample formula, Primes less than $5$ is $2, 3$, number of primes between $5$ and $5^2$ is $5^2*(1-1/2)*(1-1/3)-1=7.333$, so there's approximate $7$ primes between $5$ and $5^2$.
Comment: actually $(5^2-5)\cdot(1-{1\over 2})\cdot(1-{1\over 2})=6+{2\over 3}$
Comment: What values of $n$ is the formula for? If $n$ is large, by the approximation to the [prime-counting function](https://en.wikipedia.org/wiki/Prime-counting_function) we have $\frac{n^2}{\ln n^2} - \frac{n}{\ln n} = \frac{n^2 - 2n}{2 \ln n}$.
Comment: @Roddy MacPhee Ok, $(4^2 - 4)*(1-1/2)*(1-1/3) = 4$, there's exact 4 primes between $4$ and $4^2$.
Comment: That work because the length is divisible by 6.
Comment: @Toby Mak $n$ maybe small.
Comment: Your best bet to to find a polynomial which minimises the least-squares distance to the function. A graphing tool like Desmos will do it for you. If the range is between $5$ and $5^2$, are the first and the last numbers included as well (if they are primes)?
Comment: By the way, a quadratic fit or exponential fit will only work within a given range, which means you cannot extrapolate the approximation to any larger numbers. See my [Desmos graph](https://www.desmos.com/calculator/o6n3mxrzh0).
Comment: @Toby Mak $n$ should be included if  $n$ is prime.
Comment: @Roddy MacPhee   See the exact counting method: https://math.stackexchange.com/questions/3446280/how-to-prove-this-prime-counting-method-is-correct
Answer: One notes, that you actually have to multiply by the distinct prime divisors of the difference to get an upper bound.
For example, in any set of 20 consecutive numbers you can only find at most: $$20\cdot(1-{1\over 2})\cdot(1-{1\over 5}) = 8$$ primes. This goes down, depending on where you start in the values, etc.
In $n^2-n$ you'll only have: $$\varphi(n-1)\cdot \varphi(n)$$ at the most (loose bounds). This gives the following bounds:
$$\begin{array}{c|c|c}n & n^2 & \varphi(n-1)\cdot\varphi(n)\\\hline 2 &4&1\\\hline 3&9&2\\\hline 4 &16&4\\\hline 5&25&8\\\hline 6&36&8\\\hline 7&49&12\\\hline 8 &64&24\\\hline 9&81&24\\\hline 10&100&24\\\hline 11&121&40\\\hline 12&144&40 \\\hline 13 &169&48\\\hline 14&196&72\end{array}$$
A more rigorous bound for some ( like the last few in the table), is using that there are only 8 in every 30, to conclude that there can't be more than 43 in 156, not 48. Likewise, there can't be more than more than 49 in 182, etc.
These are more bounds than an actual formula though. But, they are good enough in most cases I'd deal with. you might try to see what the prime number theorem says though.


Masking pixels for a CNN

Question: I'm trying to implement a CNN with RGB and depth images. But my depth images are a little sparse. So I would like to mask out those neighborhoods in the RGB image where the depth neighbors are empty.
I would like to mask the input feature map, i.e. wherever the neighbor pixels are empty, multiply this with zeros. While I have not yet thought out the specifics of this operation, I have a broader question.
Is masking a "safe" operation? Can I mask out random portions of my input? I believe that this is similar to dropout, but dropout has its own backprop operations.
Does it make sense to mask out input feature map, without writing a custom backward operation? If so, what are some specifics I need to keep in mind?
My ultimate goal is just to ignore the portions that have no corresponding depth value.
Thanks
Edit: Please do not suggest State of the work art on RGB+Depth fusion, that combine the two in a fancy way. I'm purely just interested in the effects of masking
Answer: The operation of putting a value to zero, removes the gradients (see the ReLU activation function). You might want to consider that by putting a large part of your image to zero, you are giving the neural network a quite skewed input distribution.
I would normally put this down as a comment, but I dont have enough reputation.
Comment: Yes, I was concerned that it may skew the distribution, and that I may have to do something like negative mining for them. Thanks for confirming them! Is there anything else that I need to perhaps keep in mind?
Comment: You might want to be careful with data augmentation and make sure that it does not undo the masking. But I consider masking parts of the input to be quite a save operation ;)

Masking pixels for a CNN


Regex allows only 1 character

Question: $rex = '/^[^<,"@?=>|;#]$/i';

I'm having trouble with this regular expression. The idea is that the input fields are checked for certain characters and if present, throw an error.
This regex is throwing errors for every string longer than 1 character. Can anyone tell me what I'm doing wrong?
EDIT: People are saying they don't see what I want to do with this regex. What I want to do is refuse the input if one of the following characters is part of the entered string:
< > , " @ ? = | ; #
EDIT2: JG's "valid" regex does the trick.
Answer: You have the $ after your expression and the ^ in the beginning, which means you are accepting exactly one character.
EDIT (based on the comments):
You can try to see if your input fields only have valid characters, by matching it against this (if it matches, it means there are no invalid characters):
$rex = '/^[^<,"@$?=>|;#]+$/i'

You can also do the reverse, that is, test if your input fields have any invalid characters, using the regex provided by chaos:
$rex = '/[<,"@$?=>|;#]/';

This way, if the regex matches, then it means you have invalid characters.
Comment: You can try to see if your input fields only have **valid** characters, by matching it against this: `'/^[^<,"@$?=>|;#]+$/i'`. You can also do the reverse, that is, test if your input fields have any **invalid** characters, using the regex provided by chaos: `$rex = '/[<,"@$?=>|;#]/';`. This way, if the regex matches, then it means you have invalid characters.
Comment: You probably want to remove both the ^ and the $. If you remove the $ while keeping the ^, you will only match one of the characters at the beginning of the expression.
Comment: Removing both the ^ and $ means it'll validate any string, as long as it contains a valid character, and is thus not what is needed.
Comment: The invalid regex shows no matches, no matter if I enter a correct or incorrect input. My username for instance, is a false preg_match()
Answer: What you probably actually need is:
$rex = '/[<,"@$?=>|;#]/';

Then your error case is when this regex matches, not when it doesn't.
This is equivalent to doing what you're currently doing with this small change to your regex:
$rex = '/^[^<,"@?=>|;#]*$/i';

This is kind of nonsensically overcomplex, though.  Like trying to find out whether there's an elephant in the room by counting how many things in the room aren't elephants, then seeing if that number is the same as the number of things in the room.  (And the /i modifier is not, at any time, accomplishing anything.)
Answer: You'll want '/^[^<,"@$?=>|;#]+$/i' or '/^[^<,"@$?=>|;#]*$/i'.
For an example:
$valid = 'Hello';
$invalid = 'h<i';
$regex = '/^[^<,"@$?=>|;#]+$/i';

print "'$valid' gives ".preg_match($regex, $valid)."\n";
print "'$invalid' gives ".preg_match($regex, $invalid)."\n";

Which outputs:
'Hello' gives 1
'h<i' gives 0

What I simply did was take your expression and add a + or * after your character group.
In regular expressions, * means match 0 or more occurences, and + means match 1 or more.
Since ^ means the beginning of the string and $ the end, without a + or *, you tell it to match a string the consists of exactly one occurrence of a non-special character, thus why it errors if your string is longer than one character.
If you wish, you can also remove the i at the end of the expression, as you don't need to do a case-insensitive match when no letters are involved in your expression.
For more information on regular expressions, take a look at Regular-Expressions.info.
Comment: Now nothing matches. No character on my keyboard provides a match.
Comment: That seems quite strange to me. I will edit in a sample that works for me.
Answer: You're asking for only one character. If you want multiple characters, get the pattern repeated, either like this (one or more times):
 $rex = '/^[^<,"@?=>|;#]+$/i';

or like this (zero or more times):
 $rex = '/^[^<,"@?=>|;#]*$/i';

Answer: ^ means beginning of line
$ means end of line
[] means match one out of a group of character
You will match lines containing one and only one among that list.
Comment: So I'll have to escape the dollar sign in the middle?
Comment: No, so you have to qualify the set to ask for multiples. Put either + or * after the exclusion set to say you want one-or-more or zero-or-more, respectively.
Answer: maybe "/(.*?)[^<,"@$?=>|;#]/i" or "/^[^<,"@$?=>|;#].*+$/i"
don't know exactly what you are trying to do
Comment: All those random character are characters I wish to forbid. If any single 1 of them appears, the input is refused. If non present, the input is accepted.

Regex allows only 1 character


How can I prove $(a+b+c)!>a!b!c!$

Question: In fact, I couldn't prove the inequality because I don't know which method is used for this.
The condition for this inequality is  $$(a+b+c)>1$$
Comment: First Prove $(a+b)!\gt a!b!$
Comment: I know what you have mentioned
Comment: The inequality fails when $a=b=0$. Are there any conditions that you forgot to mention?
Comment: @Ehegh, for $a=b=0$, it reads: $c! > c!$.
Comment: @Ehegh see second part of Milly's answer
Comment: This statement is false. (0 + 0 + 2)! = 0!0!2! = 2. A stronger condition is necessary (at least 2 are positive).
Answer: $$\frac{(a+b+c)!}{a!b!c!} $$
is the number of ways to arrange $a$ (indistinguishable) amber balls, $b$ blue balls and $c$ cyan balls in a line. Your goal is to show that this number is $>1$. This is the case as soon as at least two of $a,b,c$ are positive.
Comment: @Ehegh: What precisely is your objection against the argument? Hagen realized the number in question as the cardinality of a set which by direct inspection can be seen to have more than one element. For me that counts as a proof.
Comment: Ok, but you proved the inequality by itself, this is impossible.
Comment: I mean that the $$\frac{(a+b+c)!}{a!b!c!}>1$$ need a proving
Comment: @Ehegh: Hagen is arguing that 1) the inequality is equivalent to a certain quantity being larger than one, 2) this quantity reflects the correct counting for a certain set of objects, 3) this set of objects contains more than one object if at least two of $a,b,c$ are positive integers. If you think at least one of these steps isn't justified, you should specify which one.
Comment: My question was permutation and the proving of Hagen also was permutation. If you prove the $\frac{(a+b+c)!}{a!b!c!}>1$ is right the proving will become right.I mean that the Hagen inequality needs proving.
Comment: @Ehegh Indeed. He is inviting you to prove that yourself since it is quite easy to do so. If you have the balls in question, can you show that the number of ways to order the balls will be more than one? All you have to do is show that there are at least two ways to order them to prove the statement.
Comment: @Hanno: For me, that even counts as a nice proof. :)
Answer: This will help:
$$(a+b)! = a!(a+1)(a+2)...(a+b)<a!(1)(2)...(b)=a!b!.$$
Your turn to prove it for $(a+b+c)!$...
$$(a+b+c)! = a![(a+1)(a+2)...(a+b)][((a+b)+1)((a+b)+2)((a+b)+c)].$$
Comment: I did this, but how I do for three. Can you write the solution as with two.
Comment: Now you just need to do the "less" step.
Answer: Show that $(x+y)! > x!y!$:
Divide by $x!$ to get $(x+1)(x+2)(x+3)\dots(x+y) > y! = (1)(2)(3)\dots(y)$, which is true for $x > 0$ (compare terms pairwise!)
Let $x = a, y = b+c$. Then we have $(a+b+c)! > a!(b+c)!$
Furthermore we have $(b+c)! > b! c!$, so $(a+b+c)! > a!(b+c)! > a!b!c!$.
Answer: $(a+b+c)!$ and $a!b!c!$ are both products of $a+b+c$ terms. Can you see a way of comparing them individually?
Answer: Hint:
$$(a+b+c)!= a! \prod_{k=a+1}^{a+b} k! \prod_{j=a+b+1}^{a+b+c}j!, $$
where $\prod_{k=a+1}^{a+b}$ is products of $b$ terms each of which is at least $b$,
hence $\prod_{k=a+1}^{a+b}\geq b^b>b!$...
Similarly for $\prod_{j=a+b+1}^{a+b+c}j!>c!$.
Answer: Use induction to show that $(a+b)! > a!b!$. You'll need to induce over both a and b. Note that this is for $a \ge 1, b \ge 1$.
Answer: An adaptation of this answer. If you have $a$ adults, $b$ boys, and $c$ girls, then $(a+b+c)!$ counts the number of ways you can line everyone up, while $a!b!c!$ counts the number of ways you can do so with the additional requirement that all adults come before all children, and all boys before all girls. Then $(a+b+c)!\geq a!b!c!$ always holds, while $(a+b+c)!>a!b!c!$ holds as soon as at least two categories are non-empty, since then there will be some line-up that violates the additional requirement.

How can I prove $(a+b+c)!>a!b!c!$


Find minimum (where $0<x,\:y,\:z<1$), $\sqrt{x^2+y^2-2y+2}+\sqrt{x^2+z^2-2x+2}+\sqrt{y^2+z^2-2z+2}$

Question: I would appreciate if somebody could help me with the following problem:
Q: Find minimum (where $0<x,\:y,\:z<1$)
$$\sqrt{x^2+y^2-2y+2}+\sqrt{x^2+z^2-2x+2}+\sqrt{y^2+z^2-2z+2}$$
My work: Just as an expression with two roots can be interpreted as a distance in a plane,
$$(x,1,0),\:(0,y,1),\:(1,0,z)$$
the above expression is interpreted as a distance in space to find a value that minimizes the sum of the distances, but it does not work. Please let me know how to solve it algebraically or geometrically. thank you
Comment: Notice the symmetry of the problem.  Also, for any $~0 < k < 1,~$ the expression $~k^2 + (1-k)^2~$ is minimized at $~k = \dfrac{1}{2}.~$  This should **informally** suggest an optimum value for each variable $~x,y,z.~$  Then, you would have to **prove** that this informal suggestion is optimal.
Comment: You can still use the Minkowski's inequality to turn this into a single-variable optimization problem which nicely happens to be minimized at the unique triplet the aforementioned Minkowski's application is also an equality.

Geometrically, this might have a cute solution by some extra constructions of the cube on the some of its faces, like the geometric solution for [Fermat point](https://www.cut-the-knot.org/Generalization/fermat_point.shtml)
Answer: By the Cauchy–Schwarz inequality, we have:
$$\sqrt {x^2+(1-y)^2+1^2}\sqrt {(\frac{1}{2})^2+(\frac{1}{2})^2+1^2}\geq \frac{x}{2}+\frac{1-y}{2}+1 \\ \implies \sqrt {x^2+(1-y)^2+1^2} \geq \sqrt {\frac{2}{3}}(\frac{1-y+x}{2}+1).$$
Similarly,
$$\sqrt {z^2+(1-x)^2+1^2} \geq \sqrt {\frac{2}{3}}(\frac{1-x+z}{2}+1), \\ \sqrt {y^2+(1-z)^2+1^2} \geq \sqrt {\frac{2}{3}}(\frac{1-z+y}{2}+1).$$
Therefore,
$$\sqrt {x^2+(1-y)^2+1^2}+\sqrt {z^2+(1-x)^2+1^2}+\sqrt {y^2+(1-z)^2+1^2} \geq \\\sqrt {\frac{2}{3}}(\frac{3}{2}+3)=3\sqrt {\frac{3}{2}}. $$
The equality happens at $x=y=z=\frac{1}{2}$.


Double exponential function

Question: Suppose $X$ has an exponential distribution with parameter $1$ and $Y=ln(X)$. The distribution of $X$ will be $f(x)=e^{-x}$. Now I want to find the distribution of $Y$. So say:
$y=x^{\frac{1}{\alpha}}$ so $x = e^y$ with $x'=e^y$. Now the distribution function of $Y$ will be: $g(y) = e^{-e^y} \cdot e^y$.
Why is this not correct? Because we now the double exponential function in this form as: $g(x) = 1-e^{-e^{-x}}$. Even if we evaluate the integral of above expression from $0$ to $x$, we get:
\begin{align}
\int\limits_0^x e^{-e^y} \cdot e^y dy = \frac{1}{e} - e^{-e^y}.
\end{align}
Answer: Since $\log$ is a strictly increasing differentiable function, we have
$$\begin{align*}F_Y(y) &= \mathbb P(Y\leqslant y)\\
&= \mathbb P(\log X \leqslant y)\\
&= \mathbb P(X\leqslant e^y)\\
&= F_X(e^y)\\\end{align*}$$
The density of $Y$ is obtained by differentiating:
$$\frac{\mathsf d}{\mathsf dy}F_X(e^y) = F_X'(e^y)\frac{\mathsf d}{\mathsf dy}e^y =  e^{-e^y}e^y = e^{y-e^y}. $$
Answer: If $$X \sim \operatorname{Exponential}(\lambda)$$ such that $$f_X(x) = \lambda e^{-\lambda x}, \quad x > 0, \lambda > 0,$$ and $$Y = g(X) = \log X,$$ then the density of $Y$ is given by $$f_Y(y) = f_X(g^{-1}(y)) \left| \frac{dg^{-1}}{dy} \right|.$$  In this case, $g^{-1}(y) = e^y$ and we find $$f_Y(y) = \lambda e^y \exp(-\lambda e^y ) = \lambda \exp(y - \lambda e^y), \quad -\infty < y < \infty.$$  This shows that $-Y$ is a Gumbel distribution (also known as an extreme-value distribution, or double-exponential distribution).

Double exponential function


timeToLiveSeconds and timeToIdleSeconds ehcache configuration

Question: My app sometimes goes unused for 24 hours or more but when it does get a request, it is very slow because the data has to be fetched from database. Here is the current ehcache configuration:
<code> timeToIdleSeconds="120"
 timeToLiveSeconds="120"
</code>
I am considering using the following configuration:
<code> timeToIdleSeconds="172800"
 timeToLiveSeconds="0"
</code>
i.e. it never expires according to timeToLiveSeconds and the cache waits 48 hours (48*60*60=172 800) after last access before expiring.
Does that make sense at all?
Thanks in advance,
Julien.
Answer: That makes sense, the default settings of 120/120 are definitely not working for you.
Also make sure you set eternal="false", since having it true overrides the timeToIdle and timeToLive settings.