How do I include my library on the page?

Question: I have an Angular app I want to use as a Drupal 8 theme but when I try to attach it with a YAML file, Drupal doesn't register that any JavaScript is being added to the theme.
ng.libraries.yml
base:
  version: 8.x
  css:
    css/styles.09e76a721be8ced0c439.bundle.css: {}
  js:
    js/inline.6375acbd4540ff168f58.bundle.js: {}
    js/polyfills.62cd0a749311c6ac36ca.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}

However, when I reference the script locations directly in my template, it works fine:
html.html.twig
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hand of Death</title>
    <link href="themes/ng/dist/styles.09e76a721be8ced0c439.bundle.css" rel="stylesheet" />

    <app-root></app-root>

From what little I can make sense out of the docs, somewhere I'm going to have to call Drupal.behaviors.myBehavior, but that would not actually work in my situation.
Is there a way to get JavaScript to work without hardcoding it in the template?
EDIT: I've reverted this to the original so the corrections make sense to future users and went ahead and opened a new question with the most recent code.
Comment: Not the same files: js/inline.6375acbd4540ff168f58.bundle.js vs inline.cad96cf6be5b6cfb5176.bundle.js - Those files seems to be dynamically generated, with varying filenames. Drupal libraries are for static files.
Comment: Thanks for catching that error. However, even when the libraries reference the static files, it doesn't work.
Answer: So you defined a custom library that includes CSS and JavaScript. This is done by creating the ng.libraries.yml file and adding the base library definition.
Next, you need to tell Drupal to include this library and attach it to all the pages, if your ng theme is used for rendering the output. You can do so by adding a libraries section to your theme's ng.info.yml file:
libraries:
  - 'ng/base'

After clearing your caches, the library should be included.
Additionally, you may want to have a check for the syntax of the .libraries.yml file. CSS inclusion should follow the syntax:
css:
  theme:
    css/styles.09e76a721be8ced0c439.bundle.css: {}

Observe the theme part.
EDIT:
After you also added your html.html.twig template, another issue seems a missing js-bottom-placeholder tag. It will be replaced by any JavaScript that is not attached to the head region:
<js-bottom-placeholder token="{{ placeholder_token }}">

Comment: Sorry, I should have given more detail. I've updated my post to include my ng.info.yml.
Comment: I added 'theme' under css but it didn't make a difference.
Comment: Would you mind to also include your html.html.twig file without your hard-coded paths? Possibly the JS and CSS placeholders missing? Compare the core/themes/classy/templates/layout/html.html.twig file.
Comment: I updated it with html.html.twig
Answer: You did just one part of the job, another part is adding your libraries to some pages or to all pages.
in YOUR_THEME.info.yml file add your defined library
libraries:
  - 'ng/base'

Part of Drupal Documentation about Attaching Libraries to a theme :

Attaching libraries to page(s): Some libraries you load may not be
  needed on all pages. For faster performance don't load libraries where
  they are not being used. Below are examples of how to selectively load
  libraries.
Attaching a library via a Twig template You can attach an asset
  library to a Twig template using the attach_library() function in any
  *.html.twig, file like so:
{{ attach_library('fluffiness/cuddly-slider') }} Some fluffy
  markup {{ message }} Attaching a library to all pages To attach
  a library to all the pages that use your theme, declare it in your
  theme's *.info.yml file, under the libraries key:

 name: Example
 type: theme
 core: 8.x
 libraries:
   - fluffiness/cuddly-slider

List as many libraries as you want, all of them will be loaded on every page.
After editing the *.info.yml or the *.libraries.yml file, remember to
 clear the cache so that the new information is loaded into Drupal.

Attaching a library to a subset of pages In some cases, you do not
  need your library to be active for all pages, but just a subset of
  pages. For example, you might need your library to be active only when
  a certain block is being shown, or when a certain node type is being
  displayed.
A theme can make this happen by implementing a THEME_preprocess_HOOK()
  function in the .theme file, replacing "THEME" with the machine name
  of your theme and "HOOK" by the machine name of the theme hook.
For instance, if you want to attach JavaScript to the maintenance
  page, the "HOOK" part is "maintenance_page", and your function would
  look like this:
function fluffiness_preprocess_maintenance_page(&$variables) {
  $variables['#attached']['library'][] = 'fluffiness/cuddly-slider'; }
  You can do something similar for other theme hooks, and of course your
  function can have logic in it — for instance to detect which block is
  being preprocessed in the "block" hook, which node type for the "node"
  hook, etc.
Important note! In this case, you need to specify the cacheability
  metadata that corresponds to your condition! The example above works
  unconditionally, so no cacheability metadata is necessary. The most
  common use case is likely where you attach some asset library based on
  the current route:
function fluffiness_preprocess_page(&$variables) {
  $variables['page']['#cache']['contexts'][] = 'route';
  $route = "entity.node.preview";
  if (\Drupal::routeMatch()->getRouteName() === $route) {
    $variables['#attached']['library'][] = 'fluffiness/node-preview';
  }
}

I strongly recommend take a look at  Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme
Comment: I've updated my question to include 'ng.info.yml'. I looked at the network requests, and the libraries successfully load, but nothing renders.
Comment: @MMBB would you please revert your changes and ask this in another question? if you change your question completely our answers not valid anymore and this means wasting time and efforts of others. also maybe in future, somebody has a problem like this and it might current answers help them. by the way, I'm here to help Drupalists.
Comment: I've gone ahead and opened a new question with the code as it stands now.
Answer: You forgot the bottom JS placeholder token in html.html.twig:
<!DOCTYPE html>

    ...
    <js-placeholder token="{{ placeholder_token|raw }}">
    ...

    ...
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">

Drupal has 2 different tokens for JS libraries: Usually it places all JS files at the end of the body, except you explicitly move them to the header in your libararies.yml.
Comment: Seems you have been faster than my editing. StackExchange via mobile isn't fun. ;)
Comment: I went back and added the second one but it still doesn't work.
Comment: Not according to your edit @MMBB. You used the same placeholder twice
Comment: @Clive thanks for that. I updated it but it's still not working. Neither is the CSS.
Comment: The CSS is still wrong too, you haven't added the `system`/`module`/`theme` key (see https://drupal.stackexchange.com/a/253250/2800)


Van Kampen theorem?

Question: So I'm trying to use Van Kampen theorem to prove that a space is null-homotopic.
The thing is I got it down to this $\langle a\mid a=1\rangle$, however I'm confused what does this mean.
For calculating the the torus you get it down to this $\langle a,b\mid a^{-1}b^{-1}ab=1\rangle \cong \mathbb{Z} \times \mathbb{Z}$.
But, was thinking does the brackets mean $\langle 1\rangle \cong \mathbb{Z}$ . I'm confused as normally the $\langle$ , $\rangle$ brackets means the generating set.
Comment: $\langle a\;|\;a=1 \rangle$ is the group with one generator $a$, which satisfies $a = 1$, hence the trivial group. BTW, what does it mean for a space to be null-homotopic? Did you mean simply connected?
Comment: In the brackets we have generators G and relations R: . If there is no relation and one generator, then this group is isomorphic to $\mathbf{Z}$.
Answer: More in general with Van Kampen theorem one have to deal with notation of the following kind
$$\langle g_1,\dots,g_s \mid m_1(g_1,\dots,g_s) = n_1(g_1,\dots,g_s);\dots; m_k(g_1,\dots,g_s) = n_k(g_1,\dots,g_s) \rangle$$
where $m_i(g_1,\dots,g_s)$ and $n_j(g_1,\dots,g_s)$ are strings containing as symbols $g_i$ or $g_i^{-1}$.
This notation is called a finite presentation of a group:
it simply denote the biggest group having $s$ generators, named $g_1,\dots,g_s$ for which the relations
$$m_i(g_1,\dots,g_s) = n_i(g_1,\dots,g_s)$$
hold.
More formally  the notation above denote the quotient group of the free group with $s$-generators by the smaller normal subgroup containing the elements of the form
$$m_i(g_1,\dots,  g_s) \left(n_i(g_1,\dots,g_s)\right)^{-1}\ \text{.}$$
In this group the equalities $m_i=n_i$ hold and every other group for which $m_i=n_i$ is a quotient of this group, thus the attribute bigger.
Some additional notes: in your examples $\langle a \mid a = 1 \rangle$ means the group with one generator with is equal to the identity, the group with this property is the trivial group $\{1\}$ that contain just the identity (so this proves that you space is indeed simply connected. In the case of the torus $\langle a,b \mid aba^{-1}b^{-1} = 1\rangle$ is also the group $\langle a,b \mid ab=ba\rangle$, this group is the biggest group having two generators which commute, i.e. it is the free abelian group with two generators.
Answer: The notation $\langle a|a=1\rangle$ would usually mean the group generated by $a$ subject to the relation $a=1$, so in fact it is the trivial group and your space is null-homotopic as you require. What the notation is really saying is that it's the quotient of the free group on $a$ by itself, which is clearly trivial.
Comment: Here I'm reading "null-homotopic" as "simply connected", i.e. every loop is null-homotopic. Thanks to Alexander Thumm for pointing this out in his comment.

Van Kampen theorem?


Exploding indexes and unix timestamp

Question: Each of my entities consist of a number of single-value properties and one array.
In each entity there is a unix epoch timestamp and a user id.
My problem is I'd like to be able to do this kind of query
SELECT * FROM <kind> WHERE time >= value AND time <= value and userId = value
The issue is I have to create a composite index but I've also read about exploding indexes and storage space but I cannot quite understand it.
Can someone please explain to me if creating such composite index is it an "exploding index" and if the query is good or not.
Answer: The exploding indexes problem (and the associated storage usage growth) is only applicable when multi-value (array/repeated) properties are included in the index. Since your particular query only refers to single-value properties (time and userId) the corresponding index won't be an exploding one.
But you may have a potential problem you need to consider: the monotonic time property can cause trouble at high read/write rates. From Indexes:

Do not index properties with monotonically increasing values (such as a NOW() timestamp). Maintaining such an index could lead to
  hotspots that impact Cloud Datastore latency for applications with
  high read and write rates. For further guidance on dealing with
  monotonic properties, see High read/write rates for a narrow key
  range below.

And

Likewise, if you need to query on a monotonically increasing (or
  decreasing) property using a sort or filter, you could instead index
  on a new property, for which you prefix the monotonic value with a
  value that has high cardinality across the dataset, but is common to
  all the entities in the scope of the query you want to perform. For
  instance, if you want to query for entries by timestamp but only need
  to return results for a single user at a time, you could prefix the
  timestamp with the user id and index that new property instead. This
  would still permit queries and ordered results for that user, but the
  presence of the user id would ensure the index itself is well sharded.
Comment: Thank you for your reply, I have a few follow-up questions. 1. Each entry has an array with multiple different phone numbers and as you said the composite index is only exploding if the array is part of the composite index. Is the array on its own with two regular indexes exploding? 2. The amount of phone numbers is different, from 1 to 100 will the array cause the same slowdown because they're numbers? 3. Regarding monotonically values. So I just prepend the timestamp like this userIdString_timestamp. That should fix the bottleneck and still allow for less/greater/equal operators?
Comment: I don't think I understand #1, please clarify. For #2 it's the number of possible values that makes the index potentially exploding, not the fact that the values are numbers - the same would happen if they'd be strings for example. Also - the exploding indexes don't cause read/write showdowns, they can only cause longer eventual consistency durations and storage increases. Yes, that timestamping solution should address those issues.
Comment: I'm sorry if my question wasn't clear. About #1, each entry has a property which is an array with phone numbers and it varies how many numbers from 1 to 100. If this property is not within a composite index but just its own normal index, is this array causing exploding index? Another question: since the array contains phone numbers in either string or number type will that array potentially cause a hotspot at high read/write?
Comment: For #1 - no, that simple index for the array property won't be an exploding one. The phone numbers could theoretically raise the hotspot issue, but really - what are the chances of that actually happening in real life? Maybe during testing, while you pre-populate the datastore in batch mode with a pile of entries. I wouldn't worry too much about it. If you do - you can always apply the same technique as for the timestamps.
Answer: Exploding index isn't just a composite index issue. When you create a composite index, you are creating just another index for a set of attributes instead of just one. Normally, you would only be storing one copy of your data unless one or more attributes in the entity is a repeated/nested field. Exploding index is when you erroneously index every attribute of your entity for giggles and not realizing that if you have a REPEATED or NESTED field, you are indexing it multiple times.
Example: If you save this Entity kind with 3 String attributes:
Name & Hobbies & Favorite Color. Even if you index every attribute, you are at most storing 3 tables sorted by each attribute, no big deal.
However, if hobbies and favorite color were stored as repeated or nested fields, now you have 6 hobbies and 7 colors... Now every row is stored 6*7=42 times! That's what you need to avoid. If a nested field does not need to be queried and sorted against, don't index it.

Exploding indexes and unix timestamp


How many ways can a slate of 4 (distinct) officers from 20 people, etc.

Question: In how many ways can a slate of 4 officers (president, vice-president, secretary, treasurer) be selected from among 20 people?
$$4! {20 \choose 4}$$
In how many ways can a committee of three be selected from among 10 people?
$$3! {10 \choose 3}$$
I wanna make sure I'm doing the questions above correctly, any feedback is greatly appreciated
Comment: The first answer is correct, because the order matters. But in the second, different orders of the committee members does not appear to matter.
Comment: for the second should be just ${10 \choose 3}$ because the order doesn't matter.
Answer: Your first answer is correct, and as you accounted for, the order of the four people selected to be officers matters.  We have 4 distinct officer positions to fill, and there are $4!\dbinom{20}{4} = (20\cdot 19\cdot 18\cdot 17)$ ways to do that.

Your second answer is incorrect:  The number of ways a committee of three can be selected from ten people is simply $$\binom{10}{3} = \dfrac{10!}{7!3!} = \frac{10\cdot 9\cdot 8}{6} = 120$$
If the three chosen consist of person A, person B, and person C, any permutation of those three people will not change the committee.  If we represent the three chosen from ten as $(A, B, C)$, then order does not matter: if you're in the committee you are in the committee, period. So $$(A,B,C) = (A,C,B) =(B,A,C) = (B,C,A) = (C,A,B) = (C, B, A).$$
Answer: You already have the answer in the Comment of @ThomasAndrews. This is just
to show some terminology and notation. While I was typing this another very nice
explanation from @amWhy appeared (+1). Please leave a Comment to say whether you
now understand the distinction between the two problems, or Accept one of the
answers to indicate the same thing.

The first problem is to choose an ordered sample: Pres, VP, Sec, Treas.
Some books call this a permutation problem.
Ways to choose Pres: 20
Then ways to choose VP: 19
So answer is
$${}_{20}P_4 = 20\cdot 19\cdot 18\cdot 17 = 20!/16! = 4!\frac{20!}{4!\cdot 16!}
= 4!{20 \choose 4} = 4!({}_{20}C_4).$$
The second problem is to choose an unordered sample.
Some books call this a combination problem: ${}_{20}C_3 = {20 \choose 3}.$


Integrating $\operatorname{arsech}$

Question: Just found the following exercise from an old book (Bostock & Chandler: Further Pure Mathematics, Functions, Chapter 4, Misc. Ex Q35(b)):
"Prove that $\int_{\frac{4}{5}}^1 \operatorname{arsech}x = 2 \operatorname{arctan} 2 - \frac{\pi}{2} - \frac{4}{5} \log 2$. "
I get the (indefinite) integral to be $x\operatorname{arsech}x + \arcsin x$ (by parts, letting $dv=1$ and $u=\operatorname{arsech} x$), giving the solution $\frac{\pi}{2} - \arcsin \frac{4}{5} - \frac{4}{5}\log 2 $.
It's not a problem to show $2 \operatorname{arctan} 2 - \frac{\pi}{2} = \frac{\pi}{2} - \arcsin \frac{4}{5}$ but I'm curious to see if there is an alternative approach that gives $\arctan$ immediately because I've not found one yet and I wasn't able to find a direct relation between $\arctan$ and $\arcsin$, especially when they have different arguments.
It wouldn't surprise me if it really was just a fiendish extra step added in for this particular case but thought I'd ask in case someone could spot the solution more directly.
Thanks in advance for any help.
Post-Mortem
Many thanks to Alann for spotting what now feels like an obvious step (aren't they always?). Using his solution, I've come up with the following, for those of you interested (let me know if you think there's an error).
For $0<\alpha \leq 1$
$ 2\arctan\left( \sqrt{\frac{1}{\alpha^2} - 1} + \frac{1}{\alpha} \right) = \pi - \arcsin (\alpha)$ ($\arctan \infty = \frac{\pi}{2}$ should cover the $\alpha = 0$ case). Plotting on Wolfram suggests that there's a more interesting relation for negative values but I'm happy with this at the moment.
I'll forgive myself for not spotting this relation sooner.
Answer: I'll assume you know that $\text{sech}^{-1}\left(\frac{4}{5}\right)=\ln(2)$.
One way to derive the $\arctan$ is to begin with the substitution $x=\text{sech}(u)$ ($u\geq 0$) and then integrate by parts. This gives
\begin{align*}
\int_{4/5}^{1}\text{sech}^{-1}(x)\text{ }dx &= \int_{\text{sech}^{-1}(4/5)}^{\text{sech}^{-1}(1)}\text{sech}^{-1}(\text{sech }u)\cdot-\text{sech}(u)\tanh(u)\text{ }du\\
&= \int_{0}^{\text{sech}^{-1}(4/5)}u\text{ }\text{sech}(u)\tanh(u)\text{ }du\\
&= \left[-u\text{ }\text{sech}(u)\right]_{0}^{\text{sech}^{-1}(4/5)}-\int_{0}^{\text{sech}^{-1}(4/5)}-\text{sech}(u)\text{ }du\\
&= -\frac{4}{5}\text{sech}^{-1}(4/5)+\int_{0}^{\text{sech}^{-1}(4/5)}\frac{2}{e^u+e^{-u}}du\\
&= -\frac{4}{5}\ln(2)+2\int_{0}^{\ln(2)}\frac{e^u}{(e^u)^2+1}du
\end{align*}
Making the substitution $t=e^u$ gives
\begin{align*}
-\frac{4}{5}\ln(2)+2\int_{0}^{\ln(2)}\frac{e^u}{(e^u)^2+1}du &= -\frac{4}{5}\ln(2)+2\int_{e^0}^{e^{\ln(2)}}\frac{1}{t^2+1}du\\
&= -\frac{4}{5}\ln(2)+2\left(\tan^{-1}(2)-\tan^{-1}(1)\right)\\
&= 2\tan^{-1}(2)-\frac{\pi}{2}-\frac{4}{5}\ln(2)
\end{align*}
which is the desired result.
Comment: Great answer! +1
Comment: Fantastic solution. Thank you, Alann.
Comment: @Phulax-Wolfgang you're welcome!

Integrating $\operatorname{arsech}$


Operations of a group on a set

Question: I've been reading Algebra (Revised Third Edition) by Serge Lang these days.
Proposition 5.1. says "If $G$ is a group operating on a set $S$, and $s\in S$, then the order of the orbit $G_s$ is equal to the index $(G:G_{s})$ "
Proposition 5.2. says "The number of conjugate subgroups to $H$ is equal to the index of the normalizer of $H$ "
In particular, in proposition 5.1., when $G$ operates by conjugation on the set of subgroups, and $H$ is a subgroup, we can get that the number of conjugate subgroups to $H$ is equal to the index $(G:G_H)$. $G_H$ is equal to the normalizer of $H$, also.
What makes me confused is that it seems to be different from the proposition 5.2.
Am I wrong?
Comment: In future, don't use MathJax just to write a single symbol in an expression. Instead, if an expression is a mathematical one, always write the whole thing. So, don't write `s$\in S$` (resulting in "s$\in S$") but instead write `$s\in S$` (resulting in $s\in S$). Also, write names of mathematical objects in mathjax, so you have a group $G$, not a group G. Makes it far easier to read.
Comment: How is this different from Proposition 5.2? They seem to be in perfect harmony, even by what you write.
Comment: I mean why the index of (G:$G_H$) and the index of the normalizer of H are the same.
Comment: @Hsiung If I understand your question correctly, then the reason they're the same is because the normalizer of $H$ is precisely the set of elements $g$ for which $gHg^{-1}=H$, which is exactly the set $G_H$, since this is equivalent to fixing $H$ under the conjugation action.
Answer: You have
\begin{align*}
G_H &= \{ g\in G \mid gHg^{-1}=H \}
    \\ &= \{ g\in G \mid gH=Hg \} = N_G(H),
\end{align*}
so $G_H$ is indeed the normalizer $N_G(H)$ of $H$ in $G$. The first equality is simply by definition of the action: It is by conjugation.
Answer: What may be confusing you is the notation $G_s$. This is a subgroup of $G$, call the stabilizer of the element $s \in S$, that is:
$G_s = \{g \in G: g\cdot s = s\}$.
In the case where $G$ acts on the set $S = \{H: H\text{ is a subgroup of }G\}$ by conjugation, we have:
$g\cdot H \stackrel{\text{def}}{=} gHg^{-1}$
so the stabilizer of a subgroup $H$ is all $g \in G$ such that $gHg^{-1} = H$.
This is the same set (as another answer shows) as the normalizer of $H$ in $G$, $N_G(H)$.
In other words, with a group action (or "operation" as your text says), we think of each group element $g$ inducing a function $S \to S$. Then $G_s$ is the set of all elements of $G$ who have $s$ as a "fixed point" of the induced function.
This often gives a "new way" to look at some group constructions which occur frequently.

Operations of a group on a set


How to build Test APK for Firebase Test Lab

Question: Firebase Test Lab asks to upload two APKs:

App APK
Test APK

How to build test APK?
Answer: Run:
./gradlew assembleDebugAndroidTest
The Test APK will be built in:
app/build/outputs/apk/androidTest/<flavor>/debug/app-<flavor>-debug-androidTest.apk


File permissions question

Question: If I need a php-page to have access to upload images and move images from a folder on the server, what permissions would I set on the folder then?
I know we have "Owner", "Group", and "Others".
But what does the server (or the php-code itself) count as? Owner?
Also, would I need to set the php-page with the upload script with some specific permissions to be able to upload the files? Is it execute permissions?
Thanks
Answer:
It depends on which user the server is run as. The web server is often run as "Other", but that's not always the case so I suggest you ask your sysadmin or hosting provider.
No, you don't need to set any special permissions on the upload script, only on the folder you're uploading to.

File permissions question


views output file alterations

Question: I am using d7 and views.
I've created a view tpl file specific to my view using the the file name of: views-view-fields--cameras.tpl.php
<?php

foreach ($fields as $id => $field): ?>
<?php
$output = '';
$output .=  $field->label_html;
$output .= '
';
if($field->label_html == 'camera_brand_star:')
{
$output .= $field->wrapper_prefix;
$output .= '
hello
';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'camera_price_star')
{
$output .= $field->wrapper_prefix;
$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'brand:')
{
$output .= $field->wrapper_prefix;
$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}

else
{
$output .= $field->wrapper_prefix;
//$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}
$output .= '
';
echo $output;
//echo $field->label_html;
?>
<?php endforeach; ?>

The if conditions are not working at all as its not printing any content. Only it prints the output of     $output .=  $field->label_html;   What am I doing wrong?
Answer: Please provide the markup that's currently produced by this code. The PHP logic looks fine but it's not cleat if $field->label_html has a value that will trigger and of the if statements. As a bare minimum you should be getting:

views output file alterations


turn off wysiwyg for full html filter format?

Question: How do i set it so that the wysiwyg doesn't turn on during full html mode.
I would prefer to hand edit the html during full html filter mode without the wysiwyg editor stripping my html.
I'm using CKEditor.
Comment: Which version of ckeditor?  7.x-1.x or 7.x-2.x?
Comment: the latest so probably 7.x-2.x
Answer: You can switch to HTML display in D8 by clicking on source tab. So that you can retain Full HTML processing and work without output.
Answer: Set your input format to 'Full HTML', edit away, and save. When you come back to the page, it will be in 'Full HTML' format. If, however, you switch it back to Wysiwyg, you will lose your html formatting. Don't switch it back.
Answer: You simply can navigate to admin/config/content/ckeditor there you can see different profiles, there are to profiles which are added by ckeditor called "Advanced" and "Full".
The full profile is the one used when you switch to "Full HTML" you can delete this profile or if you want to keep it, then you can edit it and uncheck "Full HTML" from its list.
in this case when you switch to Full HTML the ckeditor won't show up any more.


More likely to cross confidence limits in short runs than long?

Question: I am a research scientist. This is not homework.
I do not have enough points to post pictures. To see the relevant plots, see this stackoverflow question: Add 95% confidence limits to cumulative plot
On the page referenced are two plots that show coin-toss data. One shows some short runs spliced together. The other shows 100,000 tosses.
Now, I am not a mathematician (I can barely count), but it seems to me that if you link together short runs, as in the combined plot of multiple short runs, you are more likely to get crossings over the 95 percent confidence limits (the blue line), than with the 100,000 plot (where to cross the 95 percent limits is much, much harder).
Is my intuition correct?
Comment: "I am not a mathematician (I can barely count)", I don't know many mathematicians that actually can count more than $1,2,3,\ldots,n,\ldots$
Comment: I don't know if the implication is that mathematicians can count or not. More that I am as far from a mathematician as perhaps somebody can be?
Answer: At any particular point, the probability of being outside the 95% confidence interval is, by definition, 5% (though there are some minor rounding issues in the extremely short term), and this remains the same throughout the process.
So the short-term and long-term probabilities are in that sense the same.  You can see this in the first chart in the accepted answer to the question you linked to, where a similar grey area lies outside the red limits.
In fact, it is almost certain that, at some stage in the extremely long term, the path of the random walk will cross the confidence limits.  This is made more formal in the law of the iterated logarithm.
Comment: Ah, well that was my alternative conclusion. But I wanted an informed opinion. Thanks for the response.


Euler, Heun and Runge-Kutta

Question: Im supposed to use Euler and Heun(improved Euler) method with step size h=0.5 and Runge-Kutta with step size h=1 to find y(2). Meaning three answers
$$\frac{dy}{dx}=2x,~~y(0)=1$$
First Using Eulers:
$$y_1=1+\frac{1}{2}(2*0)=1$$
$$y_2=1+\frac{1}{2}(2*\frac{1}{2})=\frac{5}{4}$$
Then using improved Euler:
$$y_1=1+\frac{1}{4}(2*0+2*\frac{1}{2})=\frac{5}{4}$$
$$y_2=\frac{5}{4}+\frac{1}{4}(2*\frac{1}{2}+2*1)=2 $$
The using Runge-Kutta
$$y_1=1+\frac{1}{6}(2*0+2*2*\frac{1}{2}+2*2*\frac{1}{2}+2*1)=2 $$
$$y_2=2+\frac{1}{6}(2*1+2*2*\frac{3}{2}+2*2*\frac{3}{2}+2*2)=5$$
But it's not the right answer. Any ideas where it goes wrong?
Comment: You didn't explicitly mention this, but is the initial condition $y(0)=0$?
Comment: Wait, sorry bout that,Yes y(0)=1 in fact.
Comment: Unsure, Im doing this as an online test and the only feedback I get is that the total answer is wrong, I get no indication of which part it is.
Comment: Where RK $$y_{n+1}=y_n+\frac{h}{6}(P_n+2q_n+2r_n+s_n)$$
Answer: If you're going to approximate $y(2)$ using Euler and Improved Euler, you're going to need to compute up to $y_4$ since your step size is $h=.5$.  Let $f(x,y) = 2x$, $x_0=0$ and hence $x_i=x_0 + ih= .5i$.  Given that the initial condition is $y(0)=1$, we have by Euler's Method that
$$y_1 = 1 + .5f(0,1) 1 + .5(2(0)) = 1$$
$$y_2 = 1 + .5f(.5,1) = 1+ .5(2(.5)) = 1.5$$
$$y_3 = 1.5 + .5f(1,1.5) = 1.5 + .5(2(1)) = 2.5$$
$$y_4 = 2.5 + .5f(1.5,2.5) = 2.5 + .5(2(1.5)) = 4$$
Thus $y_4=4$ is our approximation for $y(2)$.
Likewise, using Heun's (Improved Euler's) method
$$y_n = y_{n+1} = y_n + \frac{h}{2}\left(f(x_n,y_n) + f(x_n+h,y_n+hf(x_n,y_n))\right)$$
where $f(x,y) = 2x$, $x_0=0$, $x_i=.5i$ and $y_0=1$, computing up to $y_4$ (which I leave to you to verify) leaves us with
$$\begin{aligned}y_1 &= 1.25\\ y_2 &= 2\\ y_3 &= 3.25\\ y_4 &= 5\end{aligned}$$
And thus $y_4=5$ is our approximation for y(2)$.
Finally, for Runge-Kutta, you only need to do two iterations since the step size is $h=1$.  Using the same set up as in the other two iteration methods, we see that $$y_1 = 1 + \frac{1}{6}\left(2(0) + 2[2(.5)]+ 2[2(.5)] + 2(1)\right) = 2$$
$$y_2 = 2 + \frac{1}{6}\left(2(1) + 2[2(1.5)] + 2[2(1.5)] + 2(2)\right) = 5$$
So your calculations for Runge-Kutta were correct.

Euler, Heun and Runge-Kutta


Why doesn't Los Angeles have an NFL team?

Question: The Los Angeles metropolitan area is the second largest metro area in the United States.  It is big enough to support 2 NBA teams (Lakers and Clippers), 2 MLB teams (Dodgers and Angels), and 2 NHL teams (Kings and Ducks).  Why doesn't it have any NFL teams?
I know it used to have the Rams and Raiders, both of whom moved in 1995.  In 1999 and 2002, the NFL added the Cleveland Browns and Houston Texans, respectively.  Why wasn't a team added to the second largest market in the United States?

Editor's Note: When this question was originally asked in 2014, there were no NFL teams in LA.  Since then, two teams have moved to LA: the Rams in 2016, and the Chargers in 2017.
Comment: Once you lose three teams (Chargers, Rams, Raiders) it starts to look like carelessness rather than bad luck.
Comment: Did the Rams & Raiders both move in 1995 ? I'm feeling a lot older than before I read your question
Answer: As you said, Los Angeles is the second largest city in the US, so it seems ridiculous that they do not have an NFL team.  There are lots of opinions as to why this is the case.
In the last few years that the Rams and the Raiders were in LA, both teams were struggling, both on the field and financially.  They both played in aging stadiums, and neither were successful in obtaining a new stadium in the area.
The reasons why both teams struggled financially are debatable.  One reason could be that there aren't enough football fans to support two teams.  (They both left the same year, so this is hard to disprove.)  Another reason could be that, with 6 other major league sports teams in the area, the sports market is already saturated.
Any team that would move to LA would need a new stadium; a team would not move there to play at the Coliseum, the Rose Bowl, or any other old stadium in the area.  This is a hurdle, as both the Rams and the Raiders were unable to get a stadium built.  As time passes, it will be more likely that funding for a new stadium will be able to be obtained.
Today, LA is used as a threat by NFL teams seeking new stadiums.  The Buffalo Bills are one of the latest teams to consider LA.  Tim Graham, writing for the Buffalo News, wrote an article outlining reasons why he thinks that the time is not right for an NFL team in LA.  Among these reasons are an unfavorable business climate in California and a lack of public enthusiasm in funding a new stadium.
It seems to happen every year: a team threatens to go to LA if they don't get a new stadium, and the public funds the stadium to prevent the team from going to LA.  At the end of this upcoming season, the Rams, Raiders, and Chargers, all of whom have been in LA in the past, have expiring stadium leases.  They will all undoubtedly use LA as a bargaining chip in their stadium negotiations.  If not one of these teams, it seems inevitable that at some point in the future, a team will move to LA to give it a try.

Update 1/2016: The Rams, Chargers, and Raiders all applied to move to LA this year.  The NFL has approved the move for the Rams, who will start playing in LA this year (2016) at the Coliseum while their new stadium in Inglewood is built, which is scheduled for completion in time for the 2019 season.  The stadium is designed to support two teams; the Chargers will be given an opportunity to move, and if they decide against it, the Raiders will be allowed to move.  Source: LA Times
Update 1/2017: The Chargers opted to move to LA, and will begin playing at StubHub Center in Carson until the Inglewood stadium, which is now named City of Champions Stadium, is completed in 2019.
Comment: Use of L.A. as a threat in negotiations sounds like a ploy straight out of Bernie Ecclestones book
Comment: We are now up to 2 NFL teams in LA after the Chargers [announced their relocation](https://twitter.com/Chargers/status/819588193687212033).
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ Some of the replies to that tweet are hilarious.
Answer: They do now.  The Rams are back.  They didn't because fans chose to go to the beach and mountains vs football games.  They also wouldn't publicly back buying a stadium for an owner.


postfix virtual_mailbox_maps deliver to two maildirs

Question: I have postfix with configuration like this:
/etc/postfix/main.cf
virtual_alias_maps  =   hash:/etc/postfix/virtual
virtual_mailbox_domains =   /etc/postfix/vdomains
virtual_mailbox_base    =   /VMAIL
virtual_mailbox_maps    =   hash:/etc/postfix/vusers
virtual_minimum_uid =   1000
virtual_uid_maps    =   static:5000
virtual_gid_maps    =   static:5000

/etc/postfix/vusers
email@example.com         domain.com/boss/
firstname.lastname@example.com       domain.com/editor/
firstname.lastname@example.com       domain.com/novini/

/etc/postfix/virtual
firstname.lastname@example.com   email@example.com

It currently works ok, but I want when:
Someone sent mail to firstname.lastname@example.com, the email to be stored in both domain.com/editor/ and domain.com/novini/. Also I want a copy of the email to be forward to person personal email - firstname.lastname@example.com
Same if someone sent to firstname.lastname@example.com, the email to be stored in both domain.com/editor/ and domain.com/novini/. In this case I do not want any email to be sent to  firstname.lastname@example.com
How is easier way to set up this with virtual_mailbox_maps?
Answer: You need to add following in virtual
/etc/postfix/virtual
firstname.lastname@example.com   email@example.com
email@example.com        email@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com
email@example.com        email@example.com, email@example.com, firstname.lastname@example.com, firstname.lastname@example.com

postfix is smart, so it does not "loop".


Independence system/ graph-theory

Question: $ (E,S)$ is an independence system with $ w: E \rightarrow \mathbb{R_+}$.
$E= \{ e_1,...,e_m\} $ is the set of edges with $ w(e_1) \geq....\geq w(e_m), w(e_{m+1}):=0$. Define the set: $ E_i:= \{ e_1,...,e_i\}$ and $ T \subset E$ with $ w'(T) = \sum_{ e \in T} w(e)$.
I will show: $$ w'(T)= \sum_{ i=1}^m |T \cap E_i|\big(w(e_i)-w(e_{i+1})\big)$$
Can somebody give me a hint to do that?
Answer: It is enough to think what is $w'(T_j)$ where $T_j =\{e_j\}$.
Let $$w''(T_j)=\sum_{ i=1}^m |T_j \cap E_i|\big(w(e_i)-w(e_{i+1})\big)$$
then
\begin{eqnarray}w''(T_j) &=&\underbrace{|T_j \cap E_1|}_{=0}\big(w(e_1)-w(e_{2})\big)+...+\underbrace{|T_j \cap E_{j-1}|}_{=0}\big(w(e_{j-1})-w(e_{j})\big) +\\
&+&  \underbrace{|T_j \cap E_{j}|}_{=1}\big(w(e_{j})-w(e_{j+1})\big)+...+\underbrace{|T_j \cap E_{m}|}_{=1}\big(w(e_m)-w(e_{m+1})\big) \\
&=& \underbrace{0+0+...+0}_{j-1}+\big(w(e_{j})-w(e_{j+1})\big)+...+\big(w(e_m)-w(e_{m+1})\big) \\
&=&w(j)-w(e_{m+1})\\
&=&w(j)-0\\
&= & w'(T_j)
\end{eqnarray}
So $w'$ and $w''$ are the same functions on singeltons and now should not be difficult to see that they are the same functions:
For every $T$ and every $i$ we have: $$|T\cap E_i| = \sum _{j\in T}|T_j\cap E_i|$$ so:
\begin{eqnarray}w''(T) &=& \sum _{i=1}^m\color{red}{\Big(}\sum _{j\in T}|T_j\cap E_i|\color{red}{\Big)}\big(w(e_i)-w(e_{i+1})\big)\\
&=& \sum _{j\in T}\color{red}{\Big(}\sum _{i=1}^m|T_j\cap E_i|\big(w(e_i)-w(e_{i+1})\big)\color{red}{\Big)}\\
&= &\sum _{j\in T}w'(T_j)\\
&= & w'(T)
\end{eqnarray}
Comment: Why is it enough to consider only 1 edge $e_j$? Thank you very much for your proof:) I try understand what u have done.

Independence system/ graph-theory


How to copy just the files in a folder in python3?

Question: <code>        source = ('C:\\Qualys Report\\Qualys Data\\')
        dest1 = ('C:\\Qualys Report\\Backup\\')
        for filename in os.listdir(source):
            if filename.endswith('.csv'):
                shutil.move(source+filename, dest1)
</code>
For some reason its moving the folder and csv file i have into the backup folder
Anyway i can just move the file itself?
Comment: Which folder was moved? _source_ or the _folder inside_ the source? Please specify it.
Answer: From the question it seems you are simply trying to copy the csv files from a single source dir (not recursively), you should use copy not move/rename if you wish to keep the original copy in place, with a copy in dest1.
<code>    import os
    source = ('C:\\Qualys Report\\Qualys Data\\')
    dest1 = ('C:\\Qualys Report\\Backup\\')

    for filename in os.listdir(source):
        if filename.endswith('.csv'):
            shutil.copy(source+filename, dest1)
</code>


Using CUDA atomicInc to get unique indices

Question: I have CUDA kernel where basically each thread holds a value, and it needs to add that value to one or more lists in shared memory. So for each of those lists, it needs to get an index value (unique for that list) to put the value.
The real code is different, but there are lists like:
typedef struct {
    unsigned int numItems;
    float items[MAX_NUM_ITEMS];
} List;
__shared__ List lists[NUM_LISTS];

The values numItems are initially all set to 0, and then a __syncthreads() is done.
To add its value to the lists, each thread does:
for(int list = 0; list < NUM_LISTS; ++list) {
    if(should_add_to_list(threadIdx, list)) {
        unsigned int index = atomicInc(&lists[list].numItems, 0xffffffff);
        assert(index < MAX_NUM_ITEMS); // always true
        lists[list].items[index] = my_value;
    }
}

This works most of the time, but it seems that when making some unrelated changes in other parts of the kernel (such as not checking asserts that always succeed), sometimes two threads get the same index for one list, or indices are skipped.
The final value of numSamples always becomes correct, however.
However, when using the following custom implementation for atomicInc_ instead, it seems to work correctly:
__device__ static inline uint32_t atomicInc_(uint32_t* ptr) {
    uint32_t value;
    do {
        value = *ptr;
    } while(atomicCAS(ptr, value, value + 1) != value);
    return value;
}

Are the two atomicInc functions equivalent, and is it valid to use atomicInc that way to get unique indices?
According the the CUDA programming guide, the atomic functions do not imply memory ordering constraints, and different threads can access the numSamples of different lists at the same time: could this cause it to fail?
Edit:
The real kernel looks like this:
Basically there is a list of spot blocks, containing spots. Each spot has XY coordinates (col, row). The kernel needs to find, for each spot, the spots that are in a certain window (col/row difference) around it, and put them into a list in shared memory.
The kernel is called with a fixed number of warps. A CUDA block corresponds to a group of spot blocks. (here 3) These are called the local spot blocks.
First it takes the spots from the block's 3 spot blocks, and copies them into shared memory (localSpots[]).
For this it uses one warp for each spot block, so that the spots can be read coalesced. Each thread in the warp is a spot in the local spot block.
The spot block indices are here hardcoded (blocks[]).
Then it goes through the surrounding spot blocks: These are all the spot blocks that may contain spots that are close enough to a spot in the local spot blocks. The surrounding spot block's indices are also hardcoded here (sblock[]).
In this example it only uses the first warp for this, and traverses sblocks[] iteratively. Each thread in the warp is a spot in the surrounding spot block.
It also iterates through the list of all the local spots. If the thread's spot is close enough to the local spot: It inserts it into the local spot's list, using atomicInc to get an index.
When executed, the printf shows that for a given local spot (here the one with row=37, col=977), indices are sometimes repeated or skipped.
The real code is more complex/optimized, but this code already has the problem. Here it also only runs one CUDA block.
#include <assert.h>
#include <stdio.h>

#define MAX_NUM_SPOTS_IN_WINDOW 80

__global__ void Kernel(
    const uint16_t* blockNumSpotsBuffer,
    XGPU_SpotProcessingBlockSpotDataBuffers blockSpotsBuffers,
    size_t blockSpotsBuffersElementPitch,
    int2 unused1,
    int2 unused2,
    int unused3 ) {
    typedef unsigned int uint;

    if(blockIdx.x!=30 || blockIdx.y!=1) return;

    int window = 5;

    ASSERT(blockDim.x % WARP_SIZE == 0);
    ASSERT(blockDim.y == 1);

    uint numWarps = blockDim.x / WARP_SIZE;
    uint idxWarp = threadIdx.x / WARP_SIZE;
    int idxThreadInWarp = threadIdx.x % WARP_SIZE;

    struct Spot {
        int16_t row;
        int16_t col;
        volatile unsigned int numSamples;
        float signalSamples[MAX_NUM_SPOTS_IN_WINDOW];
    };

    __shared__ uint numLocalSpots;
    __shared__ Spot localSpots[3 * 32];

    numLocalSpots = 0;

    __syncthreads();

    ASSERT(numWarps >= 3);
    int blocks[3] = {174, 222, 270};
    if(idxWarp < 3) {
        uint spotBlockIdx = blocks[idxWarp];
        ASSERT(spotBlockIdx < numSpotBlocks.x * numSpotBlocks.y);

        uint numSpots = blockNumSpotsBuffer[spotBlockIdx];
        ASSERT(numSpots < WARP_SIZE);

        size_t inOffset = (spotBlockIdx * blockSpotsBuffersElementPitch) + idxThreadInWarp;

        uint outOffset;
        if(idxThreadInWarp == 0) outOffset = atomicAdd(&numLocalSpots, numSpots);
        outOffset = __shfl_sync(0xffffffff, outOffset, 0, 32);

        if(idxThreadInWarp < numSpots) {
            Spot* outSpot = &localSpots[outOffset + idxThreadInWarp];
            outSpot->numSamples = 0;

            uint32_t coord = blockSpotsBuffers.coord[inOffset];
            UnpackCoordinates(coord, &outSpot->row, &outSpot->col);
        }
    }

    __syncthreads();

    int sblocks[] = { 29,30,31,77,78,79,125,126,127,173,174,175,221,222,223,269,270,271,317,318,319,365,366,367,413,414,415 };
    if(idxWarp == 0) for(int block = 0; block < sizeof(sblocks)/sizeof(int); ++block) {
        uint spotBlockIdx = sblocks[block];
        ASSERT(spotBlockIdx < numSpotBlocks.x * numSpotBlocks.y);

        uint numSpots = blockNumSpotsBuffer[spotBlockIdx];
        uint idxThreadInWarp = threadIdx.x % WARP_SIZE;
        if(idxThreadInWarp >= numSpots) continue;

        size_t inOffset = (spotBlockIdx * blockSpotsBuffersElementPitch) + idxThreadInWarp;

        uint32_t coord = blockSpotsBuffers.coord[inOffset];
        if(coord == 0) return; // invalid surrounding spot

        int16_t row, col;
        UnpackCoordinates(coord, &row, &col);

        for(int idxLocalSpot = 0; idxLocalSpot < numLocalSpots; ++idxLocalSpot) {
            Spot* localSpot = &localSpots[idxLocalSpot];

            if(localSpot->row == 0 && localSpot->col == 0) continue;
            if((abs(localSpot->row - row) >= window) && (abs(localSpot->col - col) >= window)) continue;

            int index = atomicInc_block((unsigned int*)&localSpot->numSamples, 0xffffffff);
            if(localSpot->row == 37 && localSpot->col == 977) printf("%02d  ", index); // <-- sometimes indices are skipped or duplicated

            if(index >= MAX_NUM_SPOTS_IN_WINDOW) continue; // index out of bounds, discard value for median calculation
            localSpot->signalSamples[index] = blockSpotsBuffers.signal[inOffset];
        }
    } }

Output looks like this:
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  23
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
00  01  02  02  03  03  04  05  06  07  08  09  10  11  12  06  13  14  15  16  17  18  19  20  21
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  23
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
00  01  02  03  04  05  06  07  08  09  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24

Each line is the output of one execution (the kernel is run multiple times). It is expected that indices appear in different orders. But for example on the third-last line, index 23 is repeated.
Using atomicCAS seems to fix it. Also using __syncwarp() between executions on the outer for-loop seems to fix it. But it is not clear why, and if that always fixes it.

Edit 2:
This is a full program (main.cu) that shows the problem:
https://pastebin.com/cDqYmjGb
The CMakeLists.txt:
https://pastebin.com/iB9mbUJw
Must be compiled with -DCMAKE_BUILD_TYPE=Release.
It produces this output:
00(0:00000221E40003E0)
01(2:00000221E40003E0)
02(7:00000221E40003E0)
03(1:00000221E40003E0)
03(2:00000221E40003E0)
04(3:00000221E40003E0)
04(1:00000221E40003E0)
05(4:00000221E40003E0)
06(6:00000221E40003E0)
07(2:00000221E40003E0)
08(3:00000221E40003E0)
09(6:00000221E40003E0)
10(3:00000221E40003E0)
11(5:00000221E40003E0)
12(0:00000221E40003E0)
13(1:00000221E40003E0)
14(3:00000221E40003E0)
15(1:00000221E40003E0)
16(0:00000221E40003E0)
17(3:00000221E40003E0)
18(0:00000221E40003E0)
19(2:00000221E40003E0)
20(4:00000221E40003E0)
21(4:00000221E40003E0)
22(1:00000221E40003E0)

For example the lines with 03 show that two threads (1 and 2), get the same result (3), after calling atomicInc_block on the same counter (at 0x00000221E40003E0).
Comment: I suggest re-verifying the behavior on the latest CUDA version, then [filing a bug](https://forums.developer.nvidia.com/t/how-to-report-a-bug/67911). I don't believe there is a defect in your code that is causing this.  Looks like a bug in CUDA to me.  Specifically, the compiler has recently started implementing atomic aggregation at the warp level. I believe this, perhaps coupled with the rather involved control-flow in your for-loop and volta execution model is bringing this issue to the surface. Really just a guess. I am able to see the issue (it seems intermittent) on CUDA 11.2 with V100.
Comment: Some real code would be helpful. I have never, ever seen atomic operations fail. I would then guess that you are falling victim to compiler optimization. `volatile` is probably mandatory in this usage case
Comment: Don't you want atomic add in that situation? You do understand what operation atomicinc actually performs?
Comment: `atomicAdd(&lists[list].numItems, 1)` has the same problem
Comment: @talonmies added actual kernel code
Comment: please provide a [mcve]   A kernel, by itself, is not one.
Comment: Your first block looks fine; the *only* accesses to the atomic counter are via atomicInc, so assuming it's anything like what you'd expect from that name, that should be safe.  Different threads storing to different indexes in the same array should be safe in any sane memory model (I don't really CUDA specifically, though.)   Your large example is more complicated, using atomic increments on `numLocalSpots` and then later having all threads read it.  Does that part really need atomic increments, or could you just calculate something based on number of threads?  It doesn't seem data dependent.
Comment: @RobertCrovella  Added a full program that shows the problem when executed.
Comment: Just wanted to say that I was able to reproduce the problem on my machine too (CUDA 11.2, VS2019, compiled for sm_75 and running on 7.5 hardware)
Comment: I believe it should be fixed in CUDA 11.3.1 which was recently posted.  However, for code JIT-compiled by the driver, the fix may come a little later. (3312829)
Answer: According to my testing, this problem is fixed in CUDA 11.4.1 currently available here and driver 470.52.02.  It may also be fixed in some earlier versions of CUDA 11.4 and 11.3, but the problem is present in CUDA 11.2.


Why KL divergence close to zero when Q close to P?

Question: I was understanding cross-entropy and ended up understanding KL divergence. I learnt Cross entropy is Entropy + KL Divergence:

H(P, Q) = H(P) + D_KL(P||Q)

Minimizing Cross-entropy means minimizing KL Divergence. I further read that minimizing KL divergence means we are trying to make Q close to P. But, I really wanted to know why this happens? I read from many sources that when Q close to P, DKL close to zero but I didn't find any proper justification for this. I wonder if somebody has better insights on this.
Comment: KL divergence has a relationship to a distance distance, if P and Q are close means distance between them is getting closer to zero. Some useful answers here, relating KL to a metric:  https://stats.stackexchange.com/q/1031
Comment: What is it that you don't understand? If P and Q are identical, Q doesn't diverge at all from P and the KL-divergence is accordingly zero. That's how it's designed. Or is it the math that you don't understand? Have you looked up the definition of KL-divergence?
Comment: @IgorF, yeah I understand KL-divergence will be zero when Q ~ P but I wanted to know what exactly happens when Q approaches P as I have a feeling that KL divergence will also getting smaller and finally becomes zero when Q = P.
Answer: For discrete random variables $P$ and $Q$, the KL-divergence is defined as
$$
D_{KL}(P || Q) = \sum_x P(x) \ln\frac{P(x)}{Q(x)}
$$
So, as $Q \rightarrow P$, the ratio $P(x)/Q(x)$ approaches $1$ for all $x$ and the logarithm $\ln P(x)/Q(x)$ approaches zero. As probabilities are bounded to the range $[0, 1]$, each term in the sum, $P(x) \ln\frac{P(x)}{Q(x)}$ also approaches zero and, consequently, the whole sum also approaches zero.
So far the mathematical formalism. For some intuition behind it, you may consult my answer here.
Comment: I completely agree with you and I am also aware of ratio of P & Q close to one once these distributions close to each other (intuitively as well). However, I am looking for more mathematical proof what exactly happens or how value of D_KL changes when Q approaches to P. I also wanted to understand this scenario for all possible distributions of P and Q. Is there any such analysis or evaluation?


Expected value of tangent of a normal random variable

Question: If $z\sim N(\mu,\sigma^2)$
What is $E[\tan(z)]$ and $E[\tan^2(z)]$?
Generally, it seems that the expectation does not exist. How about if $z$ is bounded $(0,\pi/2)$?
Update: Theoretically, my random variable can change from 0 to $\pi/2$ (the endpoints are excluded). However, practically, its upper bound is smaller than $\pi/3$. That's why, in the comments below, I've jumped to $\pi/3$.
Update 2: By "practically", I mean this: My random variable is in fact a material property. There is no theoretical limitation that avoids this property to approach $\pi/2$. However, nobody has reported any value higher than $\pi/3$  in practice (in nature).
Comment: that is not difficult, $tan(\pi/2)\rightarrow \infty$ then integral is not converging at all
Comment: why this expectation is of interest?
Comment: I am facing it in my research
Comment: Can you accept numerical solution?
Comment: I prefer analytical solution, specially for $(0,pi/2)$. However, if it is difficult/impossible, numerical solution is fine
Comment: this integral does not converge then expectation does not exists
Comment: @Hamed agreed, you may show the integration diverges even in $(0, \pi/2)$.
Comment: What if upper bound is $\pi/3$?
Answer: The behavior of the $\tan$ function as the argument approaches $\pi/2$:

guarantees that unless the density approaches 0 rapidly enough as the argument approaches $\pi/2$, the limit ($\lim_{t\to\pi/2} \int_{0}^{t}\tan(x)f(x)dx$) will not be finite. No normal truncated to $(0,\pi/2)$ can approach 0 in a way that would do that.
If you take $\mu$ well into the negatives or make $\sigma$ quite small, at first glance it can look like it might converge, but it never will:

The distribution of $\tan(z)$ will exhibit somewhat similar upper-tail behavior to a Cauchy distribution.
By pulling the upper bound away from $\pi/2$ the integral will converge to a finite quantity and can at least be done numerically ... e.g. for a standard normal and an upper limit of $\pi/3$ the expectation is about 0.521564. But the Wolfram online integrator can't do the indefinite integral, so I can fairly safely assume I won't be able to; numerical calculation, series approximations, or bounds are probably your main options.
However, your willingness in comments to jump from an upper bound of $\pi/2$ to one of $\pi/3$ suggests that you have not got a well-defined problem (if it can be changed so readily to $\pi/3$, why not something else? If that's so easily changed, why not the distribution, or the function of the random variable whose expectation you're taking? Why this expectation? How do you know you have normality?). It may be better to focus your interest on more carefully identifying and defining the underlying problem here -- it may lead to more productive lines of enquiry.

However, practically, its upper bound is smaller than $π/3$.

Everything depends on precisely what "practically" means here. Again, this suggests the same kind of concern I expressed above about the problem not being clearly defined.
Is there some chance values can exceed $\pi/3$, no matter how small? Is there any chance they can closely approach $\pi/2$, no matter how infinitesimally remote those chances might be? If so, can we really say anything about what the rate of decrease might be at higher values?
Here, for example, is a scaled beta on $(0,\pi/2)$ (though almost none of the probability lies beyond $\pi/3$ and even with many, many observations you might not see any values above $\pi/3$:

The integral for this distribution is finite.
(Yet you'd have a hard time telling that beta distribution apart from a normal with the same mean and variance.)
Comment: Thank you Glen_b. I've updated my question to explain why I decreased the upper bound :-)
Comment: I've updated my answer to explain why I'm still just as concerned about that.
Comment: One more update. Hope it's clear now. Again thanks
Comment: Thanks; that raises the issue -- on what basis is the thing asserted to be normally distributed rather than say *beta* distributed? Or distributed something like $\cos^2(x)$, say (which would give a finite integral)?
Comment: Yes. That's a good point that I need to think about it.
Comment: The assumed tail behavior of the extremely rare events (the ones never observed) is critical


Replace no `contenteditable` não joga o ponteiro pro final

Question: Estou tentando dar um replace no contenteditable, ele substitui mas não joga o ponteiro pro final, mantém sempre no inicio. Não conhecia o contenteditable ainda e não achei nada 'simples' que funcione.
O mesmo exemplo no elemento input funciona corretamente, mas no contenteditable acontece esse 'problema' - não sei se falta algo...
A ideia é substituir algumas palavras e manter o cursor no ponto de digitação.
jsfiddle

$(".elemento").on('input', function( e )
{
    content = $(this).html().replace(/foo/g, 'bar');
    $(this).html( content )
});

  foo bar

Comment: Se quiser delegar a complexidade em algo já feito, utilize a biblioteca [Rangy](https://github.com/timdown/rangy). Vale mencionar que ela tem compatibilidade para vários navegadores, incluindo o péssimo IE.
Answer: Para isso você pode usar o objeto Range e posicioná-lo onde deseja.
Referência https://developer.mozilla.org/pt-BR/docs/Web/API/Range
Aqui um exemplo:

$('#botao').click(function () {
    var div = $("#texto");
    var content = $(div).html();
    var range = document.createRange();
    var sel = window.getSelection();
    // posição do texto
    var pos = content.indexOf("foo");
    // substitiu
    content = content.replace(/foo/g, 'bar');
    $(div).html(content);
    // cria um range, selecionando o primeiro conteúdo do div, na posição do texto "foo".
    range.setStart(texto.childNodes[0], pos);
    range.collapse(true);
    sel.removeAllRanges();
    // posiciona no range
    sel.addRange(range);
    div.focus();
});

  Isso é um teste com foo no texto

<button id="botao">Posicionar</button>


Efficient ndarray operations

Question: I'm converting some Matlab code in Python. I need to do some matrix manipulation. My matrix (A) is (right now) a 65x3 matrix. However, the number of rows is variable depending on what step I'm at in the program.
In Matlab, the code I'm working on is:
output = inv(A'*A) * A';

The following Python code reproduces the expected output just fine. I'm just curious if there is a better (more Pythonic, faster, etc) way to do this? I'm trying to stick only to basic Python and numpy.
output = np.dot(np.linalg.inv(np.dot(np.transpose(A), A)), np.transpose(A))

Thanks to anyone who is willing to help.
Comment: apart from using the shortcut `A.T` for transpose, you can't do much better. (but this really is just eye sugar, won't make any actual difference)
Comment: It looks like you are computing the psuedo-inverse of the matrix `A`.  Unless your application specifically needs to compute the psuedo-inverse, if you can avoid computing the inverse, then don't do it.  This article by John D. Cook should provide insight: http://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/.  If you are trying to find the least-squares solution to an overdetermined (or underdetermined) system of equations, use the [`numpy.linalg.lstsq`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html) method to compute your solution directly.
Answer: You can use a the T attribute (transposes the array). Also, if using Python 3.5, you can use @ for the dot product (see PEP 465 for details).
output = np.linalg.inv(A.T @ A) @ A.T

Comment: Thanks. That was perfect. I knew there had to be a better way of writing it.
Comment: Note that if you are using `inv` a lot, you can do `from numpy.linalg import inv` at the beginning of your file, and then just do `output = inv(A.T @ A) @ A.T`.  Also note that this will not behave the same as the MATLAB version when working with complex numbers, in that case the MATLAB transpose is not a simple array transpose, it also takes the conjugate of the elements.

Efficient ndarray operations


Question about naming conventions for Cocoa/Objective-C for iPhone (with respect to release and autorelease)

Question: Can you describe the naming convention difference between a method that returns an object it has allocated for the caller (and that the caller should release), and a method that returns an autorelease object?
Answer: Methods that return a retained object (which the caller should release) should include the word copy, new, mutableCopy, or alloc (as in an alloc/init pair). Everything else should return an autoreleased object.
Answer: Did you have a look atApple's documentation?
Answer: According to this:

methods that start with -allocXXX or -newXXX, or contains the word "copy" will/should return an allocated object
any method that doesn't follow rule #1 will/should return an autoreleased object
Comment: What about create? Does that prefix retain or autorelease?
Comment: According to Apple's documentation, a create prefix on an objective-c method means you are NOT responsible for releasing the result, whereas  create in a CF... function means you ARE responsible for releasing the result. Weird... http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH
Comment: apple doc link:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html
Answer: If the method has alloc, new, copy or create in the name, it will return a new, retained object, by convention.


Result interpretation for Regression With ARIMA Errors

Question: I am new to time-series analysis.
I am struggling to interpret the result I got from auto.arima().
I've read the highly-recommended blog https://robjhyndman.com/hyndsight/arimax/.
I also read a similar question on ARIMAX vs. Regression With ARIMA Errors but I still got a few more questions.
My code (I was using  auto.arima() to analyze daily ridership data in Boston and I did not do any data manipulation beforehand, like taking log or standard scaling on variables) :
weather_indicators =  df_2019[['Boston Temperature_mean','Boston Precipitation Total','Boston Evapotranspiration','Boston Sunshine Duration','Boston Relative Humidity_mean']]
model2 = pm.auto_arima(df_2019['Total_Daily'], suppress_warnings=True,exogenous = weather_indicators, seasonal=True, m=7)

I used python here but my understanding is that the pmdarima should be very similar to  auto.arima() in R.
And I got a result looks like this:

The above result is pretty rough but still I would like to know:
1. Interpretation on coefficients
The coefficients for the exogenous variables (especially the first 3 weather variables) are much larger than coefficients for AR and MA.
Does that mean the weather is much more statistically significant to the daily ridership number than the time-series factors are? or is it because the auto_arima() is a Regression with ARMA errors, which renders the coefficient for exogenous variables always being much larger than those for AR,MA?
2. ARIMAX vs  multiple linear regression
My focus was on  studying the effect of the exogenous variables.
If time-series factor (coefficients for AR and MA) are not that statistically significant(very low in this case), maybe a multiple linear regression (between daily ridership and different weather variables) would be more appropriate? Or this SARIMAX result is good enough?
Many thanks.
Answer:
Interpretation on coefficients: First of all, $AR(p)$ and $MA(q)$ terms are bounded between $(-1,1)$ or else the process is not stationary. Second, you judge whether a coefficient is statistically significant based on the relevant $t-test$. For example your third exogenous variable, while large on absolute terms, also has large standard error and cannot be considered statistically significant at the $1\%$ confidence level (i.e. there is a chance $>1\%$ that this coefficient is actually $0$). Third, if your exogenous variables are of different scale it is reasonable to have large discrepancies in absolute terms in the coefficients. So the answer is that I cannot judge which coefficient is more important at this stage; this would probably require applying a method such forward or backward selection in order to assess the impact of each predictor separately.
ARIMAX vs multiple linear regression: Good enough is relevant. There are several ways of evaluating a model's performance. Some of them are based on in-sample diagnostics: $R^2$, residual diagnostics and Akaike information criterion among others. In fact I believe that auto.arima() uses AIC as a default for model selection. If forecasting is your goal, you should probably evaluate based on the forecast accuracy on a hold-out set. I would suggest checking the residual diagnostics to get a first assessment of the quality of your model. If your residuals are $i.i.d.$ it would indicate a good fit.


Configure continuum 1.2.3 with maven2 project; "Username isn't defined."

Question: I use continuum 1.2.3 to build maven projects. On a fresh continuum installation, I added a pom by upload.
I try to build, and get the following error:
Exception:
Exception while executing SCM command.

My SCM URL looks like this: (replaced domain name)
scm:cvs:pserver:cvs.example.com:/Projects:car/wheel/

Any idea what went wrong?
Thanks
Answer: I'm guessing the SCM provider couldn't find your credentials so failed. If you run the build with -X switch it should give more details of the failure reason.
Update: from the format for CVS SCM URLs, the expected format for pserver is:
scm:cvs<delimiter>pserver<delimiter>[username[<delimiter>password]@]servername[<delimiter>port]<delimiter>path_to_repository<delimiter>module_name

If you have a : in the path, you should use | as a separator, perhaps on Continuum there is some other processing interfering and using | will resolve it, e.g.
scm:cvs|pserver|[user]|[password]@cvs.example.com|/Projects|car/wheel/

Assuming that is the cause, you don't want to include your SCM credentials in published files. You can configure Maven to use settings for many of the providers. See this answer for more details.
Comment: Providing username and password in scm url, i get the following error: //start of output

Provider message: The cvs command failed.
Command output:

//end of output

In the continuum.log is the following line:
     2009-10-07 14:04:10,955 [pool-1-thread-1] INFO  org.apache.continuum.scm.manager.Slf4jScmLogger  - Executing: cmd.exe /X /C "cvs -z3 -f -d :pserver:firstname.lastname@example.com:/Projects -q checkout -d 3 car/wheel/"

running this on command line (windows) sucessfully checks out the sources. But it doesn't work using continuum. Maybe i must use the native cvs implementation?


How to make .nuget\NuGet.Config file attached to VS solution to be not ignored?

Question: I've created new solution in Visual Studio, enable nuget package restore and got in soluition root .nuget folder which contains the following files needed to make package restore work: NuGet.exe, NuGet.config, NuGet.targets.
But I can't make nuget(as Nuget Visual Studio add-in and \.nuget\NuGet.exe as well) read setting from .\nuget\NuGet.config file - settings are still read from default %appdata%\NuGet\NuGet.config.
What have I tried.
I've tried to look where the path to NuGet.config is specified and haven't found anything like that, and nuget.exe install command that runs during build doesn't have any parameter saying like "take this nuget.config file".
Also I've removed \.nuget\NuGet.config and everything works - packages are restored during Visual Studio build and CI one.
Question.
I've got an impression that \.nuget\NuGet.config isn't used at all.
So essentially the question is:  How to make .nuget\NuGet.Config file to be not ignored?
What am I doing wrong and how to do it write?
Thanks and have a nice %time_of_day% :)
Disclaimer
Everything that I've mentioned above is not a problem/issue - current nuget behavior is completely acceptable for me - I'm asking just because I'm curious and confused at the same time
Answer: I haven't tried this personally, but here is what the official Nuget 2.1 release notes say:

NuGet.config files are searched for in the following order:

.nuget\nuget.config
Recursive walk from project folder to root
Global nuget.config (%appdata%\NuGet\nuget.config)

The configurations are than applied in the reverse order, meaning that
  based on the above ordering, the global nuget.config would be applied
  first, followed by the discovered nuget.config files from root to
  project folder, followed by .nuget

If this doesn't help I'd suggest you write more specifically what you're trying to achieve and which config settings you're changing - knowing more details about the problem may clarify the situation.
Comment: Tip for all that try this: You need to restart Visual Studio after the file was added/changed
Comment: IN Visual Studio 2015, I tried .nuget\nuget.config and .\nuget.config - without success. The configuration file is ignored.
Comment: Global nuget.config where is in ubuntu?
Answer: Did you point the config file that you want to use as ?
In nuget page example;
nuget config -set repositoryPath=c:\packages -configfile c:\my.config
nuget config -set repositoryPath=c:\packages -configfile .\myApp\NuGet.Config
nuget config -set repositoryPath=c:\packages -configfile %ProgramData%\NuGet\Config\VisualStudio\14.0\NuGet.Config
nuget config -set repositoryPath=c:\packages -configfile %ProgramData%\NuGet\NuGetDefaults.Config

Comment: I can't specify the config file when building with studio. In the package manager console, nuget is not known as command, nor is it known in the command window.
Comment: @Slesa to go C:\Program Files (x86)\NuGet\Visual Studio 2015 location and click Ctrl+RightClick select "Open Command Prompt Here". Then you'll use nuget exe to configurate
Comment: But then it would work only on my machine (if so). The buildserver would not work.
Comment: Are you going to build it on other PC or on TFS ?
Comment: It was on PC. The problem was obiously, that I had to restart VStudio to see the changes. Very strange.


Laravel saves temp file as image

Question: I have 3 image field for my products, on save method all working fine, but in update method first image saves temp file in database and the other two update without issue.
Code
Here I share all my 3 images on update method:
//saves temp file instead of file name
if ($request->hasFile('imageOne')) {
            $imageOne = $request->file('imageOne');
            $filename = 'productone' . '-' . time() . '.' . $imageOne->getClientOriginalExtension();
            $location = storage_path('app/public/images/' . $filename);
            Image::make($imageOne)->resize(1200, 600)->save($location);

            if(!empty($product->imageOne)){
                Storage::delete('images/' . $product->imageOne);
            }
            $product->imageOne = $imageOne;
        }
//works with no issue
        if ($request->hasFile('imageTwo')) {
            $imageTwo = $request->file('imageTwo');
            $filename = 'producttwo' . '-' . time() . '.' . $imageTwo->getClientOriginalExtension();
            $location = storage_path('app/public/images/' . $filename);
            Image::make($imageTwo)->resize(1200, 600)->save($location);

            if(!empty($product->imageTwo)){
                Storage::delete('images/' . $product->imageTwo);
            }
            $product->imageTwo = $filename;
        }
//works with no issue
        if ($request->hasFile('imageThree')) {
            $imageThree = $request->file('imageThree');
            $filename = 'productthree' . '-' . time() . '.' . $imageThree->getClientOriginalExtension();
            $location = storage_path('app/public/images/' . $filename);
            Image::make($imageThree)->resize(1200, 600)->save($location);

            if(!empty($product->imageThree)){
                Storage::delete('images/' . $product->imageThree);
            }
            $product->imageThree = $filename;
        }

Any idea?
Answer: Issue is here:-
$product->imageOne = $imageOne;

You are saving $imageOne. But you need to save $filename. Use following code:-
$product->imageOne = $filename;

Comment: bless you <3 :)

Laravel saves temp file as image


Any epi with codomain $P$ is split implies $P$ is projective

Question: I'm struggling to prove that if any epi with codomain $P$ splits, then $P$ is a projective object. The converse direction I proved by factoring the identity to give a right inverse of the pi.
How can I prove this claim?
Comment: Can you be more specific about the environment you're assuming?
Comment: This has now popped up in the "Related" section: http://math.stackexchange.com/questions/135777/different-definitions-of-projective-objects?rq=1 (presumably because the question has been edited to a correct version). I'm inclined to say that this could be a duplicate.
Answer: Here is a counterexample: Consider the category with three objects $P$, $X$ and $Y$, and two non-identity morphisms $f : P \to X$ and $\pi : Y \to X$ (and the only possible composition rules). Then every epimorphism with codomain $P$ splits (there is only one such epimorphism, the identity...). But $P$ is not projective: $\pi$ is an epimorphism, but $f$ does not factor through $\pi$.

Wrong answer below!
I'm pretty sure that you mean "any epi with codomain $P$ splits". Compare with the case of projective modules over a ring: exact sequences $0 \to A \to B \to P \to 0$ split when $P$ is projective. And for example $\mathbb{Z} \twoheadrightarrow \mathbb{Z}/2\mathbb{Z}$ doesn't split even though $\mathbb{Z}$ is projective in the category of abelian groups.
Let $f : P \to X$ be a morphism, and $\pi : Y \to X$ an epimorphism. Take the pullback:
$$\require{AMScd}
\begin{CD}
Y \times_X P @>{f'}>> Y \\
@V{\pi'}VV @V{\pi}VV \\
P @>{f}>> X
\end{CD}$$
Then since epimorphisms are stable under pullbacks (They are not! this argument is wrong.), the projection $\pi' : Y \times_X P \to P$ is epimorphic. By hypothesis it splits, so let $s : P \to P \times_X Y$ be a splitting, ie. $\pi' \circ s = \operatorname{id}_P$. Let $g = f' \circ s : P \to Y$. Then $\pi \circ g = \pi \circ f' \circ s = f \circ \pi' \circ s = f$ and so $f$ factors through $\pi$.

Note: this assumes that pullbacks exist in the category we are considering (generally they do in homological algebra, but one has to be careful). Otherwise the claim is false. (Edit: And the argument is wrong anyway!)
Comment: One needs some hypotheses on the category involved.
Comment: Sorry, corrected domain to codomain.
Comment: @Exterior: scrap the whole thing. I don't know what I was thinking: epimorphism are *not* stable under pullbacks! They are stable under pushouts... (It's monomorphisms that are stable under pullbacks)
Comment: @NajibIdrissi strangely enough, I think I subconsciously remembered Zhen Lin's answer in that question. It is one of the reasons I didn't say the setting is an abelian category. At any rate, I don't mind these extra hypotheses - having pullbacks which also preserve epis.


Funções em Python

Question: Fiz esse exercício de Python, versão 2.7:

Instruções
Primeiro, defina (def) uma função chamada cube (cubo) que
  toma um argumento chamado number (número). Não se esqueça dos
  parênteses e dos dois pontos!
Faça essa função retornar (return) o cubo daquele número (ou seja,
  aquele número multiplicado por si mesmo, e depois multiplicado mais
  uma vez por si mesmo).
Defina uma segunda função chamada by_three que
  toma um argumento chamado number.
Se (if) esse número for divisível por 3, by_three deve chamar
  cube(number) e retornar seu resultado. Caso contrário, by_three deve
  retornar falso (return False).
Não se esqueça que as declarações if e else precisam de um : ao final
  daquela linha!

Aqui meu código:
def cube(number):
    return number * number * number #number elevado ao cubo(3)

def by_three(number):
    if(number % 3 ==0):
        cube(number)
        print "resultado = %d" % number
    else:
        print "number nao e divisivel por 3"
        return False

Mas quando executo ele mostra isso:

Oops, tente outra vez. Sua funcao by_three retorna None com a entrada 3 quando deveria retornar 27. by_three deveria retornar cube(n) se n for divisivel por 3.
Comment: Creio que não...
Comment: Acho que está faltando código aí, não?
Comment: Eu havia lido "Quando **executo**, ele mostra isso", agora que eu li corretamente, percebi que eu não entendi qual é a sua dúvida. Poderia dizer qual que é?
Comment: O código tem uma função que chama outra função(elevado number ao cubo) se ela for divisível por 3, ela mostra o resultado. mas esta dando erro.
Comment: testei no pythonfiddle e deu certo sua função, não deu nenhum erro
 http://pythonfiddle.com/
Answer: O seu problema está nas linhas:
    cube(number)
    print "resultado = %d" % number

Que você chama a função cube() passando o number, mas você se esquece de fazer sua função by_three() retorne algo, como ele não entra no else o código da função roda até o final sem encontrar nenhum return, e por isso o retorno acaba sendo None.
Já o retorno da função cube() é simplesmente perdido. Você deveria retornar o resultado da função cube(), assim:
    return cube(number)

Seu código poderia ficar assim por exemplo:
def cube(number):
    return number * number * number  # number elevado ao cubo(3)

def by_three(number):
    if(number % 3 == 0):
        print "resultado = %d" % cube(number)
        return cube(number)
    else:
        print "number nao e divisivel por 3"
        return False

print by_three(3)

Comment: Ele continua mostrando isso: Oops, tente outra vez. Sua funcao by_three retorna None com a entrada 3 quando deveria retornar 27. by_three deveria retornar cube(n) se n for divisivel por 3.
Comment: Ah, é só por um return no lugar do print então
Comment: Posso printar algo com o return?
Comment: Você pode printar **e** retornar, caso seja do seu interesse
Comment: ok, muito obrigado!!

Funções em Python


PHP SoapClient: Problems with Distributed WSDL File

Question: I have a problem using a distributed WSDL File (scheme / other definitions are declared outside the actual WSDL) with PHP's SoapClient.
This is the fault message I got:
SOAP-ERROR: Parsing WSDL:  'getSomeInfo' already defined.

After some googling, it seems to be a bug inside PHP as someone else discovered exactly the same problem: http://bugs.php.net/bug.php?id=45282
Has there been any bug fix(es)? Any solution to work around this bug?
I think posting a code snippet is senseless, since the invocation of the SoapClient ctor using just the WSDL is the only that fails.
Comment: Re: your code sample.  Posting the WSDL files you're using along with they options you're using for the invokation of the Soap client will let SO users hack on the problem and find a workaround (or discover that you're missing a key namespace option or something)
Answer: I had same issue. The problem was in wsdl and imports, I saved wsdl from site and pointed soapclient to use local file, but all references were original. Soap client each time gets file from remote host, went to parts, and from them back to same file but on remote drive. That caused same file to be loaded twice.
Solution is to use only remote files or to rewrite paths to local (all). SoapUI does that when you hit "export definitions" on project wsdl. Hope that will help others.
Answer: Download a local copy of the WSDL file. Remove duplicate method names. Update your soap client to use the local WSDL file. This has worked well for me in the past.
Answer: I had the same issue while accessing a WCF service providing multiple endpoints through PHP. In my case, it turned out that the main WSDL imports sub-WSDLs for each endpoint, while the sub-WSDLs do include the main-WSDL in turn. This is apparently the reason why PHP reads the main-WSDL twice and comes up with the "already defined"-error. I could avoid this behavior by creating the client with the sub-WSDL URL of the desired endpoint instead of the main WSDL URL.
Answer: The PHP source code (svn) which takes care of the import nodes contains the comment /* TODO: namespace ??? */. Namespaces are ignored which enables the method collisions to occur.
Three solutions are proposed:

Fix the source code to cater for namespaces (which would be very welcome)
Manipulate the WSDL files to prevent such method overlaps (this is likely not an option at all)
Instead of using the original WSDL file, call the imported ones individually (or group ones which do not have method name collisions) with separate SoapClient instances.

Sorry that I can't be of more help.


Can an iterative method converge for some initial approximation?

Question: Studying iterative methods for solving(or approximating) linear equation systems, I came accross the following theorem$^1$:

Let the following be an iterative method:
  $$x^{(0)},\qquad   known\\
x^{(k+1)}=Bx^{(k)}+g,\quad k=1,2,...$$
where B is the iteration matrix and g is a vector.
The iterative method converges, for any chosen initial approximation $x^{(0)}$, if and only if $\rho(B)\lt 1$, where $\rho(B) = max_{i=1,...,n} \left\{|\lambda_i| : \lambda_i \text{ is an eigenvalue of B}\right\}$

So, basically, the method converges, for any chosen initial approximation, iff the maximum absolute value of B's eigenvalues is less than 1.
My question
I'm not entirely sure how to interpret the theorem:

For any chosen $x^{(0)}$: (the method converges $\Leftrightarrow \rho(B) \lt 1$)
(The method converges for any chosen $x^{(0)}) \Leftrightarrow \rho(B) \lt 1$

So, if $\rho(B) \ge 1$, does the method always diverge(interpretation 1), or can it converge for some (but not all) initial approximation (interpretation 2)?

$^1$(translated by me, if some terms are a bit off please let me know)
Comment: 2. Because you if some $\lambda < 1$ ($\rho(B)>1$ )and $g$ is in span of small $\lambda$ you can find an initial $x_0$ such that the method still  converges.
Answer:
The method converges for any $x^{(0)}$ if and only if $\rho(B)<1$.

Inverting the equivalence gives (recall how the quantifiers are negated):

There is an $x^{(0)}$ such that the method does not converge (diverges or stagnate) if and only if $\rho(B)\geq 1$.

Note that the inversion does not say anything about the existence of $x^{(0)}$ for which the method converges. Two scenarios are possible:

You might find an initial guess such that the method converges for some $x^{(0)}$. Note that for the error $e^{(k)}=x-x^{(k)}$, one has $e^{(k)}=Be^{(k-1)}=B^ke^{(0)}$, where $e^{(0)}$ is the error associated with the initial approximation $x^{(0)}$. The method hence converges if $e^{(0)}\in\mathcal{S}$, where $\mathcal{S}$ is some invariant subspace  of $B$ corresponding to the eigenvalues of $B$ with the magnitudes strictly smaller than one.
If all eigenvalues of $B$ are in magnitude larger or equal to one, then the method does not converge for any initial guess (except the trivial case where $x^{(0)}=x$, that is, $e^{(0)}=0$).
Comment: Alright, thank you for the clarification, as well as the extra bit of information (it can converge only if there's some eigenvalue < 1). I was having trouble inverting the equivalence because I wasn't quite sure what the equivalence was in the first place, but your first statement took care of that. Again, thank you.


How to check if a specific property of a struct is null?

Question: Forgive me, I come from a c# background!
I have following struct in Go. We populate this struct by reading in the config from a file, which works well. However Im trying to find out a way to tell if a particular property in the struct, when passed in through the config file is null. As in, explicitly not set at all.
I've struggled for about 3 hours on this. I can do it for type strings etc, but I can't find out how to do it generically, across all types?
package main

import (
    "encoding/json"
    "fmt"
    "os"
    "reflect"
)

// Config type for configuration
type Config struct {
    BatchSize  int    `json:"batchSize"`
    BatchTime  int    `json:"batchTime"`
    DataFolder string `json:"dataFolder"`
    TempFolder string `json:"tempFolder"`

    //Kafka configuration
    Brokers      []string `json:"streamBrokers"`
    TopicJoined  string   `json:"streamTopicJoined"`
    TopicRemoved string   `json:"streamTopicRemoved"`
    Group        string   `json:"streamGroup"`
    ClientName   string   `json:"streamClientName"`

    // Stats configuration
    StatsPrefix string `json:"statsPrefix"`

    //AWS S3 configuration
    AccessKey              string `json:"amazonAccessKey"`
    SecretKey              string `json:"amazonSecretKey"`
    Region                 string `json:"amazonRegion"`
    Endpoint               string `json:"amazonEndpoint"`
    S3Bucket               string `json:"amazonS3Bucket"`
    S3UploadBufferSize     int32  `json:"amazonS3UploadBufferSize"`
    S3UploadConcurrentSize int32  `json:"amazonS3UploadConcurrentSize"`
    S3UploadRetries        int32  `json:"amazonS3UploadRetries"`
    S3UploadRetryTime      int32  `json:"amazonS3UploadRetryTime"`

    //Logging
    StatsdHost string  `json:"statsdHost"`
    StatsdPort int     `json:"statsdPort"`
    StatsdRate float64 `json:"statsdRate"`

    //Test Publishing
    TestMode  bool `json:"testMode"`
    TestCount int  `json:"testCount"`
}

// LoadConfig load config from file
func LoadConfig(configFile string) *Config {
    if _, err := os.Stat(configFile); os.IsNotExist(err) {
        panic(err)
    }

    if config, err := loadFromFile(configFile); nil != err {
        panic(err)
    } else {
        fmt.Println("OneDrive", os.Getenv("OneDrive"))
        msValuePtr := reflect.ValueOf(config)
        msValue := msValuePtr.Elem()
        typeOfT := msValue.Type()

        for i := 0; i < msValue.NumField(); i++ {
            field := msValue.Field(i)
            // TODO: Check if field is null, regardless of type and the value from OS env variables...

        }
        return config
    }
}

func loadFromFile(path string) (*Config, error) {
    var config Config
    file, err := os.Open(path)
    if err != nil {
        return nil, fmt.Errorf("could not open config path %q: %v", path, err)
    }
    defer file.Close()

    decoder := json.NewDecoder(file)
    err = decoder.Decode(&config)
    if err != nil {
        return nil, fmt.Errorf("could not parse config path %q: %v", path, err)
    }
    return &config, nil
}

Comment: In Go, struct properties default to the zero of their type, which is not necessarily nil: https://tour.golang.org/basics/12
Comment: Would I then need to check each value in the `loadFromFile` method?
Answer: In go, a value's default value is its zero value. You may want to make all of your types pointers (eg: *string rather than string) since the zero value of a pointer is nil. Unmarshaling your config file into a struct would preserve nil values for the keys that are missing / have null values.
Note that since slices (eg: []string) are reference types, they act as pointers and are nullable (meaning you wouldn't need to declare the type as *[]string).
I've used this library in the past to help with merging config / setting required keys (and many others exist):
https://github.com/jinzhu/configor
Example of encoding/decoding json - https://play.golang.org/p/DU_5Tuvm5-
Comment: Are you able to give an example at all for me when you say 'Unmarshaling your config file into a struct would preserve nil values for the keys that are missing / have null values.'
Comment: If you ever save this config from Go's end, you will probably want to add the `omitempty` option to the `json` tag e.g. `json:"streamGroup,omitempty"`
Comment: @user1112324 What do you mean an example? If that value is missing from the `json`, it will be `nil`, what is there to give an example for?
Comment: added go playground example - https://play.golang.org/p/DU_5Tuvm5-. Try adding `\"foo\": \"\"` to the string reader body to see another example.


Diferenciar Markers do react-native-maps que possuem a mesma coordenadas

Question: estou montando um mapa que desenherá vários marcadores( Marker). Porém, é possível que alguns marcadores possuam as mesmas coordenadas.
Testando o aplicativo, percebi que marcadores que possuem a mesma coordenadas estão sendo sobrescritos.
<code>Ex:
coord1 : latitute: 10 , longitude:20
coord2 : latitude: 10 , longintude:20
coord3 : latitude: 40 , longitude:50
</code>
No mapa só ficaram visíveis os marcadores de coord2 e coord3. Pois, coord1 foi sobrescrito pelo coord2.
Alguém conhece alguma alternativa para tratar este problema?
Answer: Acabei dando uma solução para ajustar o marker. Desloquei o marker sobreposto 0.001 de latitude e longitude.


O que significa ns3 e ns4 em um arquivo XML?

Question: <ns3:dadoTransporteTransportXml>
  <uuidDadoSerializado>5444429-da1cb4c9-ea75-4149-bb10-def6a6173731</uuidDadoSerializado>
  <tipoDadoSerializado>4</tipoDadoSerializado>
  <codIbge>4205407</codIbge>
  <cnesDadoSerializado>5444429</cnesDadoSerializado>
  <numLote>2</numLote>
    <ns4:fichaAtendimentoIndividualMasterTransport>
      <headerTransport>
        <lotacaoForm>
          <profissionalCNS>137048659790001</profissionalCNS>

Essa é a parte de um arquivo xml que peguei na internet para estudo. Terei que criar um arquivo semelhante a esse para importar em outro sistema. Eu entendi as tags com informações dentro semelhante a html, mas não sei o significado de ns3 e ns4 nesse código. O que quer dizer?
É necessário usar o ns pro xml funcionar?
Vocês podem ver o arquivo completo => AQUI
Answer: é Apenas um Namespace, que no caso do seu arquivo de exemplo, foi colocado apenas nsX acredito que inadequadamente.
Veja a documentação: https://www.w3schools.com/xml/xml_namespaces.asp
Comment: Usar ou não, não é a questão, quis dizer inadequado os termos, ns1, ns2, ns3, .... Rs
Comment: porque inadequadamente? quer dizer que não há necessidade de usá-lo?
Comment: Como é um arquivo exemplo, a numeração deve ser pra facilitar o entendimento. Então no caso,eu posso retirá-lo? veja ele completo aqui https://goo.gl/XPVMyC
Comment: Pensei que fosse algum arquivo "real" que você estava usando como exemplo. Tirar ou não, não sei te falar se pode


Does WCF's reliableSession guarantee that messages are not corrupted by transport?

Question: here's my problem. I am using WCF for communication between two services. I am wondering if the reliableSession option guarantees that a message received by one service is really the same as the message sent by the other service, i.e., that no bit flips or similar happened on the wire?
I know that reliableSession takes care of resending messages etc. if they are not acknowledged correctly, but will it perform CRC checks or something to make sure that messages have been transferred correctly?
Answer: Reliable sessions only take care of ensuring delivery and aspects related to that (i.e. prevention of duplicates, ordering, etc.). It is message level and/or transport level security that ensures the contents of the message itself.
Answer: I'd like to add a second aspect I learned offline in the mean time.
The TCP protocol already contains CRC mechanisms to ensure at packet level that the delivered data is not corrupt. To then, in agreement with the other answer to this question, there would not even be a need for providing this in reliableSessions.
Security, of course, is still needed if you want to make sure that the data has not been tampered with.


Verification of sequence result

Question: Is it true that if a real sequence $\{x_n\}_1^\infty$ has an infimum but no convergent subsequences then the infimum must be the minimum as well?
Secondly, can it be proved that the sequence defined as $x_n = (-1)^{n} + \sqrt{n}$ is a sequence which has no convergent subsequence?
Thanks.
Comment: Isn't that what an infimum is?
Comment: @user166967 Not necessarily, the infimum of a sequence can exist without the existence of a minimum.
Comment: You mean the infimum doesn't have to be a member of the sequence?
Comment: Since $x_n\rightarrow\infty$, $x_{n_{k}}\rightarrow\infty$ for any subsequence $(x_{n_{k}})$ of $(x_n)$.
Answer: Hint: This is indeed the case. Try to prove it by assuming the sequence has a infimum that is not a minimum as well, and show that the sequence has a convergent subsequence.

Verification of sequence result


Mudar informações de acordo com seleção no select

Question: Alguém poderia me auxiliar em como eu possa alterar as informações que estão em azul na imagem abaixo, de acordo com a seleção do select (mensal, trimestral, semestral e anual)?
Eu preciso que mude o valor do produto e o link do button:

O código que eu tenho é esse:

<select class="select-ciclos" name="select" onchange="document.getElementById('selecionado').innerHTML = '' + this.value;">
    <option value="R$9,99/mês" selected="selected">Mensal</option>
    <option value="R$28,77">Trimestral -4%</option>
    <option value="R$54,14">Semestral -8%</option>
    <option value="R$99,99/ano">Anual -16%</option>
</select>

R$9,99/mês

Porém, dessa forma que eu tenho, ele fica apenas em uma das tabelas.
Gostaria de deixar um select único fora das tabelas para que ao selecionar, altere todas de uma vez.
Comment: Bem-vindo! Para que alguém se interesse a te responder, siga as orientações desse post  https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485
Comment: Para cada item no `select` haverá valores diferentes na tabela? Como serão definidos esses valores? Vem de um banco de dados? São calculados pelo JavaScript?
Comment: Anderson, os valores podem ser definidos através de um Javascript, onde ao selecionar o valor "trimestral" por exemplo, no select, ele exibe o valor correspondente que está no js na tabela de planos, conforme ilustração que deixei acima
Comment: Posso deixar como exemplo: https://www.infolink.com.br/hospedagem-de-sites/
Answer: Fiz um exemplo com item que propôs.

Define uma variável chamada precos, ela é um objeto que o índice seria o código do plano e o seu valor mensal padrão, sem desconto;
Criei um evento de escuta do tipo que quando alterar o valor do select, atualiza os preços;
Defini as variáveis para realizar os cálculos, como o próprio item, a escolha do usuário, que é mensal, trimestral... e o desconto de cada um;
Percorre os itens da tela que possuem a classe .periodo-item;
Resgata qual plano este item é e armazeno na variável plano;
Cálculo os preços de cada um;
Procuro pelo elemento que tem a classe .preco dentro do .periodo-item e seto o preço calculo;
Disparo o evento change no select para setar o preço inicial.

Perceba que no HTML coloquei o atributo data-desconto e data-multiplicar O desconto refere ao desconto aplicado e o multiplicar, seria referente aos meses, no caso de mensal 1, trimestral 3 e assim sucessivamente.

$(function() {

  // valores sem desconto
  var precos = {
    1: 10.00,
    2: 20.50,
    3: 31.55,
    4: 40.55
  };

  // Quando trocar...
  $("#periodo").on('change', function() {

    var periodo = this;
    var escolha = $(this).val();
    var multiplicar = $(this).find(':selected').data('multiplicar');
    var desconto = $(this).find(':selected').data('desconto');

    $.each($('.periodo-item'), function(key, value) {
      var plano = $(value).data('plano');
      var preco = precos[plano] * multiplicar;
      var preco_com_desconto = (preco - (preco / 100 * multiplicar)).toFixed(2);
      $(value).find('.preco').text(preco_com_desconto);
    });

  });

  $("#periodo").trigger('change');

});

<select id="periodo">
    <option data-desconto="0" data-multiplicar="1" value="1">Mensal</option>
    <option data-desconto="3" data-multiplicar="3" value="2">Trimestral 3% desc.</option>
    <option data-desconto="6" data-multiplicar="6" value="3">Semestral 6% desc.</option>
    <option data-desconto="12" data-multiplicar="12" value="4">Anual 12% desc.</option>
</select>

Plano 01

    Link 1

Plano 02

    Link 2

Plano 03

    Link 3

Plano 04

    Link 4

Comment: Muito obrigado! Ainda me ajudou com o cálculo de desconto. Era mais do que eu queria, excelente mesmo!
Comment: Por nada @IgorBueno. Tentei fazer da forma mais simples possível, que bom que lhe ajudou. ;)
Comment: Como ficaria para colocar um select para cada div?