Define $P_{n+1}(x) = P_{n}(x)+\frac{x^{2} - P_{n}(x)^{2}}{2}$. Show $P_{n}$ converges uniformly on $[-1, 1]$

Question: Let $P_{0} = 0$ and for $n = 0,1,2,...,$ define $P_{n+1}(x) = P_{n}(x)+\frac{x^{2} - P_{n}(x)^{2}}{2}$. Show that $P_{n}$ converges uniformly on $[-1, 1]$ and find its limit.
For proving that two claim we have to prove
Claim 1:
$0 \leq P_{n}(x) \leq P_{n + 1}(x) \leq \vert x\vert \leq 1$ for $x\in [-1, 1]$
, proved easily.
Claim2: $0 \leq \vert x \vert - P_{n}(x) < \frac{2}{n + 1}$. This is difficult for me. I get a help form web note where they first prove
$0 \leq \vert x \vert - P_{n}(x) \leq \vert x \vert \left(1 - \frac{\vert x \vert}{2}\right)^{n}$ and I understand the rest of the proof.
My question is where they get intention to prove $0 \leq \vert x \vert - P_{n}(x) \leq \vert x \vert \left(1 - \frac{\vert x \vert}{2}\right)^{n}$ ?
Answer: Do it by summing:
$P_{n+1}(x) = P_{n}(x)+\frac{x^{2} - P_{n}(x)^{2}}{2}$
so
$\sum^n_{k=1}P_{k+1}(x)- P_{k}(x)=\sum^n_{k=1}\frac{x^{2} - P_{k}(x)^{2}}{2}\ge\sum^n_{k=1}\frac{|x|^{2} - P_{n}(x)^{2}}{2}$.
Then, if $x\neq 0,$
$P_{n+1}(x)-P_1(x)\ge\frac{n|x|^2}{2}-\frac{n}{2}P_n(x)^2\Rightarrow$
$ |x|-P_n(x)\le\frac{2}{n}\cdot\frac{P_{n+1}(x)-P_1(x)}{|x|+P_n(x)}\le \frac{2}{n}\cdot\frac{|x|-P_1(x)}{|x|+P_n(x)}\le \frac{2}{n}\cdot\frac{|x|-P_1(x)}{|x|+P_1(x)}\le \frac{2}{n}.$
If $x=0,$ then $P_n(x)=0$ for all integers $n$ and the result is trivial: $0\le \frac{2}{n}$.
Comment: Is $\vert x \vert + P_{n}(x)$ is always non zero. In the last line.
Comment: Yes. the case $x=0$ has to be considered separately. Thanks!
Comment: also in the 2nd line how the sum is independent of k on the rhs
Comment: because $n$ is fixed.
Comment: No, it's a mistake. You did not replace $n$ by $k$ under the second summation. (Is it intended to be an *in*equality?)
Comment: Yes, I miswrote the sum originally. The proof is ok now.
Answer: It appears that you already read a proof and would like to know the intention of certain step. For simplicity, let $y_n=P_n(x)\geq 0$ (assuming that claim 1 has been proven), one has $$y_n=y_{n-1}+\frac{x^2-y_{n-1}^2}2,n\geq 1.$$ Since $y_n$ is increasing and bounded above by $|x|$, it is natural to check if the limit of $y_n$ is $|x|$, so one may proceed to estimate $$|x|-y_n=(|x|-y_{n-1})\left(1-\frac{|x|+y_{n-1}}2\right)\leq (|x|-y_{n-1})(1-|x|/2),$$ hence by recursion $$|x|-y_n\leq (|x|-y_0)(1-|x|/2)^n=|x|(1-|x|/2)^n,~(*)$$ which also works when $n=0$.
Now consider the $n+1$ numbers: $n|x|/2,(1-|x|/2),\cdots,(1-|x|/2)$. Applying AM-GM inequality, one gets $$n/(n+1)\geq \sqrt[n+1]{(n|x|/2)(1-|x|/2)^n}$$
$$\Rightarrow |x|(1-|x|/2)^n\leq \frac 2 n(\frac n{n+1})(\frac n{n+1})^n<\frac 2 {n+1}.~(**)$$ Combining (*) and (**), $y_n\rightarrow |x|$ uniformly on $[-1,1]$.
Answer: The idea is simple. From $P_{n+1}(x) = P_{n}(x)+\frac{x^{2} - P_{n}(x)^{2}}{2}$ we obtain $$|x|-P_{n+1}(x) {= |x|-P_{n}(x)-\frac{x^{2} - P_{n}(x)^{2}}{2}\\=\left[|x|-P_n(x)\right]\cdot \left[1-{|x|+P_n(x)\over 2}\right]\\
}$$Since $0\le P_n(x)\le |x|$ (based on claim 1) we obtain $$0\le1-|x| \le 1-{|x|+P_n(x)\over 2}\le 1-{|x|\over 2}$$which leads to $$|x|-P_{n+1}(x) \le \left(|x|-P_{n}(x)\right)\left(1-{|x|\over 2}\right)$$and consequently

$$|x|-P_{n}(x)\le \left(|x|-P_0(x)\right)\left(1-{|x|\over 2}\right)^n=|x|\left(1-{|x|\over 2}\right)^n$$


How to find the conditional variance?

Question: Suppose I have the following time series process with $a_t$ being an independent white noise with mean $0$ and variance $\sigma^2$:
$$
z_t = \frac{1}{3}a_t + \frac{1}{3}a_{t-1} + \frac{1}{3}a_{t-2}
$$
How do I compute the variance conditional on $a_{t-2} = 5$
Also, the unconditional variance in this problem is $\frac{\sigma^2}{3}$ correct? Thank you!
Comment: Are you looking for the variance (conditional or unconditional) of what? Of $z_t$?
Comment: Yes. The variance of $z_t$ conditional on $a_{t-2} = 5$
Answer:
$\frac{1}{3}a_t$ has variance $\frac19\sigma^2$

$a_t,a_{t-1},a_{t-2}$ are mutually independent so

$\mathrm{Var}(z_t)=\frac39\sigma^2=\frac13\sigma^2$
$\mathrm{Var}(z_t\mid a_{t-2}=5)=\frac29\sigma^2$
Comment: So Basically since $Var(a_{t-2})$ is given we exclude it when calculating the variance of $z_t$ which is then just the sum of the variance of the other two random variables that were not given?
Comment: Yes - since the three are independent, fixing one removes its contribution to the variance of the sum but does not affect the others
Comment: Thank you very much! How would I calculate the $Cov[z_t,z_{t-1}]$?
Comment: $\mathrm{Cov}[z_t,z_{t-1}] $ $= \mathrm{Cov}\left[\frac{1}{3}a_t + \frac{1}{3}a_{t-1} + \frac{1}{3}a_{t-2},\frac{1}{3}a_{t-1} + \frac{1}{3}a_{t-2}+ \frac{1}{3}a_{t-3}\right] $ $= \mathrm{Var}\left[  \frac{1}{3}a_{t-1} \right] +\mathrm{Var}\left[  \frac{1}{3}a_{t-2} \right] $ $=\frac29\sigma^2$
Comment: You're real one. I greatly appreciate you!

How to find the conditional variance?


Running "composer update" leads to errors with coder

Question: ...
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/coder (8.2.12 => 8.3.1)    The package has modified files:
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc.fixed
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.php
    D coder_sniffer/Drupal/Test/Array/DisallowLongArraySyntaxUnitTest.php
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/DisallowLongArraySyntaxUnitTest.1.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/disallow_long_array_d7.info
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc.fixed
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/disallow_long_array_d8.info.yml
    D coder_sniffer/Drupal/Test/Classes/ClassCreateInstanceUnitTest.inc

  [ErrorException]
  A non-numeric value encountered

I have tried with errors
$ composer require drupal/coder ^8.3
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package symfony/debug (locked at v4.1.7, required as ^3.4.0) is satisfiable by symfony/debug[v4.1.7] but these conflict with your requirements or minimum-stability.
  Problem 2
    - Conclusion: remove doctrine/annotations v1.6.0
    - Conclusion: don't install doctrine/annotations v1.6.0
    - Can only install one of: doctrine/annotations[v1.2.0, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.1, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.2, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.3, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.4, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.5, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.6, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.7, v1.6.0].
    - Installation request for doctrine/annotations (locked at v1.6.0, required as ^1.2) -> satisfiable by doctrine/annotations[v1.6.0].
    - Installation request for doctrine/annotations 1.2.* -> satisfiable by doctrine/annotations[v1.2.0, v1.2.1, v1.2.2, v1.2.3, v1.2.4, v1.2.5, v1.2.6, v1.2.7].

Installation failed, reverting ./composer.json to its original content.

Also tried with errors
rm vendor/ -rf
composer update
....
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package doctrine/annotations 1.2.* exists as doctrine/annotations[v1.6.0] but these are rejected by your constraint.

but always end up with other errors
Any thoughts ?
Comment: `composer require drupal/coder ^8.3` mising the colon on the version number? Also shouldn't it be `^3.0` for the module version?
Comment: @Kevin you are right I have also tried `composer require drupal/coder:^3.0` with similar results.  The wrong  `composer require drupal/coder ^8.3` was probably out of desperation.  I don't remember where I picked it up.   Thanks for the comment, I think I have found a way and I will post soon.
Answer: What worked is the following commands
rm composer.lock
rm vendor -rf
composer clear-cache
composer require --dev drupal/coder
composer update

with last command perhaps not needed as the previous composer command does an implicit update
Answer: You should not really rm anything it is not required.

composer remove drupal/coder
  composer require --dev drupal/coder

Also for a bonus point it's often a good idea to include the hash in the composer file incase an unstable dev is released you won't have to worry about changes that have come after.


How to limit access to certain nodes to certain users only?

Question: I am considering Drupal for a project with following features:

I need two content types: Supplier and Client.
I want my clients to be able to follow the progress of their orders (each order will be a node).
My suppliers will have access to their invoices, documents, etc. (which are nodes as well)

Any ideas on how to achieve this?
Example:

Client Alpha will have access to node/34 and node/46 only.
Supplier Beta will have access to node/38 and node/50 and their attached files only.
And so on ...

Is this possible with Drupal (6, 7) ? If so how can I do this, do I need custom coding or are there any other solutions for it?
Answer: Depending on how much more deep you want to take the logic of your project, you might not even need custom coding.

Start with Drupal 7 minimal installation profile
Install the modules views, entity, entity reference and their dependencies.
Create the content type "order" and add the fields you need to it. Add other content types as well like "invoice" and document, these last you might want to add a "reference" field to the order content type if they are connected.
Setup the user roles "client" and "supplier" and you might want to install the "ACL" and "content access" modules as well to define who has access to what, like "only"3 the author of the node can see it, edit it and delete it.
To make it easier for the user to see the nodes they have access to, you can create a tab on their user account using views listing only the node where they have access or where they are the authors.

Notes:
You might want to test the system before going live to make sure the right person can access the right content. Also if no anonymous user is meant to use the system disable content access to the anonymous users.
Answer: Seems like what you're trying to do is perfectly possible using the Content Access module. Here is a quote from its project page:

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

After you've enabled this module, you would typically configure which access rules you want to be applied automatically for your Suppliers, and similarly for your Clients. For that you could define 2 roles, named (eg) Supplier and Client. Once you have those roles in place, you simply start granting the appropriate access to your content types of Orders, Invoices and Documents, which IMO should be 3 separate content types also.
It also appears that, for your case, and for each of these content types, you'd want to use the special facility that this module offers, which is "*
Per content node access control settings*". Some more details about this (from the admin page that contains this setting):

Optionally you can enable per content node access control settings. If enabled, a new tab for the content access settings appears when viewing content. You have to configure permission to access these settings at the permissions page.

For anything that has the same access permissions (eg read access to "Terms & Conditions"), you may not have to use the above Per content node access control settings (which take time to maintain for each node ...). E.g. if you'd use another content type the same access rule could apply to all such nodes.
Rebuild permissions
Sometimes you'll need to "Rebuild permissions" ... Any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "enable" of a module, when rebuilding permissions is also required.
Integrations with other modules
Content Access also has all sorts of integrations with the Rules module, which you may use to make all sort of custom business logic happen (only using the Admin UI, no custom code needed, unless you insist ...). For a typical example of this, refer to my answer to "How to revoke edit access to the node's author after publishing a node?".
On top of that, if you want to start using the Content Access module for an existing sites (where you need to mass grant the appropriate permissions), you can use an approach as explained in my answer to "How to create a bulk grant view form for the node access module?".


Comparing classifier performance

Question: I used a SVM to perform classifications on the same sample and I get the following results:
Good classifications:
<code>        baseline : 78%
transformation 1 : 79%
transformation 2 : 63%
</code>
I do not know which test to use to tell if the performance difference is significant (ie. is the transformation 1 really better than transformation 2?). Which is the adequate test?
Note: transformations are transformations performed on datas (i.e. : different imputation method for missing values).
Comment: Are these figures classification accuracy on an independent test set?  How big is the test set?
Answer: As usual, I would propose to cross-validate both models (not only use a single test) and use the data from individual folds to get the spread required for making an equality test.
Of course this method  requires to repeat the imputation in each fold.
Answer: I don't know of ways to find SEs for SVM (they're not my thing), but if you want to compare the imputation methods, you can at least do each imputation 1000 times and find an estimate for the SE of the correct classification percentage from the variance over your repeated imputations.
To be correct, you'd need to add a variance component from the method (SVM) itself, but if the difference is already smaller than (the desired multiple) of your SE, you know the difference is not significant.
Little and Rubin provide this approach in much more detail.

Comparing classifier performance


Trapezoidal rule

Question: The trapezoidal rule is given by the following formula:
 $\int_{a}^{b}f(x) \approx \frac{b-a}{2}[f(a)+2\sum_{i=1}^{n-1}f(x_i)+f(b)] $
I have been given a question which wants me to evaluate the trapezoidal rule for two points, does this mean I evaluate the above equation for n=0 or n=2 ?
Answer: It means
$$\int_a^b f(x)dx=\frac{b-a}{2}\left[f(a)+f(b)\right]$$

Trapezoidal rule


What are some Servlet Container pros and cons for a Solr installation?

Question: The SolrInstall wiki page lists seven different server / Servlet Containers compatible with Solr:

Tomcat
Jetty
Resin
JBoss
WebSphere
Weblogic
Glassfish

I'm sure that "best" is subjective, so I'll just say my criteria are: easiest to set up, best for search performance with a smallish, infrequently-updated dataset, and with the fewest number of gotchas.
Jetty and Tomcat both have apt-get solr packages, so they're clearly the frontrunners for some.  Jetty is used in the demo install, but there's some notes that Jetty has some difficulties handling Unicode in some cases.  Tomcat is a common choice but my understanding is that it's not as lightweight and has a lot of features not needed by Solr.
Is it worth considering any of the others?  Are there some important pro's and cons I should be aware of?
Comment: I never had unicode problems with jetty ...
Comment: Evidently it's only with the extended multibyte character set.
Answer: In Solr versions less then 4, the version of Jetty was patched to deal with the unicode issue, in fact the Solr dev team found the bug.  In Jetty 7 and 8 the patch was applied.  Solr 4 now uses Jetty 8.
As far as Jetty versus Tomcat, I've always found it a matter of preference, I haven't seen anyone show a real performance difference between the two!
Answer: The latter 4 can be excluded automatically - they are full-blown application servers which is not required by Solr. If Jetty has problems with unicode, then it's out too. You leave with Tomcat and Resin. Both being full-featured servlet containers, I'd go for the more widely-used - Tomcat. It is lightweight enough.
Answer: In a recent discussion, many solr developers indicated that the recommend using Jetty, specifically the Jetty version that ships with solr. That is the version most tested against and most used.
Comment: yes but if you already deploy your app in tomcat & need to keep Solr on same machine, should you run another separate container Jetty or just use Tomcat ? See.. http://stackoverflow.com/questions/19123885/is-it-bad-to-have-two-webapps-on-a-machine-each-on-different-servlet-container-t
Answer: Following Solr5, Solr should be used as a blackbox.

https://cwiki.apache.org/confluence/display/solr/Major+Changes+from+Solr+4+to+Solr+5
http://grokbase.com/t/lucene/solr-user/15772hc1jd/jetty-in-solr-5-2-0

As of Solr6, it is still using Jetty but Solr developers may make their own application server mechanism in the future. Solr should be used as a service, and not as a war anymore.
Answer: The SOLR developers themselves recommend the packaged Jetty (https://cwiki.apache.org/confluence/display/solr/Running+Solr+on+Jetty):

It is recommended that you use the provided Jetty server for optimal performance.

SOLR 5 is planned to be shipped without the WAR, as a stand alone app:
https://issues.apache.org/jira/browse/SOLR-4792


iPhone GPS distance between two points

Question: How to find the distance between from current location to another?
Comment: a useful template is (a) look in SO if the question has been asked before (b) do a web search with your favorite search engine, (c) try the found example by yourself, (d) come here and ask if something is not working or need it explained.
Answer: CLLocation *location = [[CLLocation alloc] initWithLatitude:doubleLattitude longitude:doubleLongitude];

        double distanceDouble;

        if([user_Location respondsToSelector:@selector(distanceFromLocation:)])
            distanceDouble = [user_Location distanceFromLocation:location];
        else
            distanceDouble = [user_Location getDistanceFrom:location];

This way you support both OS 4.0 and 3.0 since getDistanceFrom is deprecated now.
In the above example user_Location is also a CLLocation object.
Answer: There is a method to find the distance between two CLLocations.
CLLocationDistance distance = [firstLocation getDistanceFrom:secondLocation];

Comment: This method has been deprecated since 3.2.
Answer:     CLLocation *locA = [[CLLocation alloc] initWithLatitude:"current location latitude" longitude:"current location longitude";

    CLLocation *locB = [[CLLocation alloc] initWithLatitude:"other latitude" longitude:"other longitude";

    CLLocationDistance distance = [locA distanceFromLocation:locB];

iPhone GPS distance between two points


Matplotlib: Making axes fit shape limits

Question: I'm trying to draw a rectangle in matplotlib using the following code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)

plt.show()

Which results in:

The axes do not fit the rectangle limits in this case. I could solve it with:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

ax.set_xlim(0,width)
ax.set_ylim(0,height)

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)

plt.show()

This gives me the following picture which solves the problem in this case:

However, as I am trying to plot many rectangles and other shapes in the same figure, I need a way that matplotlib smartly determines the proper axes limits itself, like the way it does when plotting normal diagrams.
Answer: You are looking for .autoscale(). You may use .margins(0) to remove any extra space that is added by default.
I.e.
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
width = 20
height = 10

rect = patches.Rectangle((0,0),width, height, linewidth=4,edgecolor='r',facecolor='none')
ax.add_patch(rect)
ax.margins(0)
ax.autoscale()

plt.show()


Find the vector in w in W closest to v.

Question: Let $W$ be the subspace R_3 with basis $\{(1,1,0), (0,1,-1)\},$ and let $v = (2, 0, -4)$. Find the vector in $w$ in $W$ closest to v.
This is what I've tried:
I obtained an orthogonal basis, where $w_1 = (1, 1, 0)$ and $w_2 = (-1/2, 1/2, -1).$
I then used to definition of a projection = $(v, w_1)w_1 + (v, w_2)w_2$. However, there is no answer corresponding to the vector produced this way.
I know the answer is (0, 2, -2) but I have no idea how to get there.
Edit: I forgot a negative sign in the answer. Sorry about that folks
Answer: The mistake is forgetting to divide by the norm squared.
$$\frac{(v, w_1)}{\color{blue}{\|w_1\|^2}}w_1 + \frac{(v, w_2)}{\color{blue}{\|w_2\|^2}}w_2$$
$$\frac{2}{2}(1,1,0)+\frac{3}{\frac32}(-0.5,0.5,-1)=(1,1,0)+2(-0.5,0.5,-1)=(0,2,-2)$$
Note that $(0,2,2)$  is not inside $W$.
$$a(1,1,0)-2(0,1,-1)=(0,2,2)$$
that would mean $a=0$ .
Comment: Nevermind, just saw your edit.
Comment: check that $(0,2,2)$ is not in $W$.
Answer: No, the answer is not $(0,2,2)$ (it doesn't even belong to $W$); it's $(0,2,-2)$.
An orthonormal basis of $W$ is $(e_1,e_2)=\left(\frac1{\sqrt2}(1,1,0),\frac1{\sqrt6}(-1,1,-2)\right)$. So, the answer is$$\bigl\langle(2,0,-4),e_1\bigr\rangle e_1+\bigl\langle(2,0,-4),e_2\bigr\rangle e_2=(0,2,-2).
$$

Find the vector in w in W closest to v.


ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host - getting this error

Question:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

I am getting this error while reading a webpage in the following code:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

myurl = 'https://www.amazon.in/s?k=graphics+card&ref=nb_sb_noss_2'

uClient =uReq(myurl)

Answer: passing a useragent header seems to solve the issue.
try something like this:
from urllib.request import urlopen as uReq, Request

from bs4 import BeautifulSoup as soup

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3"}

my_url = 'https://www.amazon.in/s?k=graphics+card&ref=nb_sb_noss_2'

uClient = uReq(Request(url=my_url, headers=headers))

But do know that if the data you're trying to scrape is dynamic, bs4 wouldn't be of much help. consider using pyppeteer or selenium, etc.. for that.


Safe to delete cache_form table while site is in maintenance mode?

Question: My site has a very large database of 100MB, most of this is in a table called cache_form.
I've tried clearing the cache. When I try and run the cron I just get a white screen.
My site is in maintenance mode, is it safe to delete the contents of this table in PhpMyAdmin? There are clearly some other issues that I need to look into but is it safe to do this as a short term measure to get the site back on its feet? I've had to put it in maintenance mode as aspects of content creation have stopped working properly.
Answer: First off, cache_form is not really a cache table, but a temporary table used to contain data necessary to verify the form being submitted to Drupal is not forged.
If you were to empty that table, users would encounter validation errors for the data they submitted from the form they were using. Since the site is in maintenance mode, that should impact the only users who are allowed to access the site when it is in maintenance mode, which includes you. You just reload the page containing the form, and fill it again; it's not a permanent error.
Answer: You may clear(EMPTY) cache table directly from MYSQL or phpmyadmin etc.
These table will filled with desired data on next request & response.
For preventation keep database backup.


Ec2 Metadata updgrade from imdSV1 to imdSV2 causes 403 and 401 error- kube2iam

Question: I recently updated my ec2 instances to use imdSV2 but had to rollback because of the following issue:
It looks like after i did the upgrade my init containers started failing and i saw the following in the logs:
time="2022-01-11T14:25:01Z" level=info msg="PUT /latest/api/token (403) took 0.753220 ms" req.method=PUT req.path=/latest/api/token req.remote=XXXXX res.duration=0.75322 res.status=403 time="2022-01-11T14:25:37Z" level=error msg="Error getting instance id, got status: 401 Unauthorized"
We are using Kube2iam for the same. Any advice what changes need to be done on the Kube2iam side to support imdSV2? Below is some info from my kube2iam daemonset:
EKS =1.21
image = "jtblin/kube2iam:0.10.9"
Answer: You can modify instances to support imdSV1, but better solution is to use IRSA.
https://github.com/terraform-aws-modules/terraform-aws-eks/issues/1749


Só renderizar meu elemento se ele não estiver vazio com o *ngIf

Question: Tenho a seguinte variável:
listAtributos: any[] = [];

No meu template quero checar se ela está vazia, se estiver, não mostrar o conteúdo, se tiver algo dentro dela, mostrar o conteúdo da div.
Tentei algo como:
<div *ngIf="listAtributos != null"

Nessa condição a div é renderizada, mesmo que esteja em seu estado inicial (listAtributos: any[] = [].
Em algum momento do meu código essa lista é copulada, quando isso acontece, eu quero que essa div seja mostrada. Porém, ela está sendo mostrada com essa condição != null.
Estou aplicando a condição de forma incorreta? Tem algo que eu ainda não percebi? Muito obrigado.
Answer: Tente da seguinte forma:

 0">
//Código

ou

//Código


Enumeration class and array declaration

Question: I'm doing a C++ tutorial that teaches the language through game development.
Within this tutorial there's a piece of code which I do not understand how it works.
First an enum class is declared and an array is initialized:
enum class side {LEFT,RIGHT, NONE};
side branchPositions[NUM_BRANCHES]; / which is a const variable and has the value of 6

Within the main function I have this code:
        for (int i = 0; i < NUM_BRANCHES; i++)
        {
            float height = i * 150;

            if (branchPositions[i] == side::LEFT)
            {
                branches[i].setPosition(610, height);
                branches[i].setRotation(180);
            }
            else if (branchPositions[i] == side::RIGHT)
            {
                branches[i].setPosition(1330, height);
                branches[i].setRotation(0);
            }
            else
            {
                branches[i].setPosition(3000, height);
            }
        }

What it does is, it updates the position of the branch sprites.
When running the code, I get the following result:

After the following function is added and called
void updateBranches(int seed)
{
for (int j = NUM_BRANCHES - 1; j > 0; j--)
{
branchPositions[j] = branchPositions[j - 1];
}

srand((int)time(0) + seed);
int r = (rand() % 2);

switch (r)
{
case 0:
branchPositions[0] = side::LEFT;
break;
case 1:
branchPositions[0] = side::RIGHT;
break;
default:
branchPositions[0] = side::NONE;
break;
}

}

the branches get distributed randomly, like so:

Now, I do not get why this is.
I do understand why the branch at position 0 is either left, right or not visible due to the switch statement. But I don't understand how the for loop in the function interacts with the array and why this leads to the behavior shown in image 2.
I also do not understand what values are stored in the array and what the connection with the enum class is.
Could somebody please clarify ? Thanks
Comment: Do you ever initialize the `branchPositions` array before calling `updateBranches`?  You may just be reading garbage from memory.
Comment: yes it's initialized before running the main loop and outside of the main function to have global scope.
Comment: Also a couple unrelated comments: 1) The `default` case in `updateBranches` is unreachable.  2) Using `time(0) + seed` defeats the purpose of being able to specify a seed at all - seeds are used to make your random numbers reproducible, but the `time(0)` counteracts that.
Comment: Can you edit your post to include the code that does that?
Comment: there's a typo which makes the default unreachable, it should be (rand()%5) instead of 2
Answer: The first for loop in updateBranches will move the branches up the array, so that the branch that was in branch[4] will be stored in branch[5], all the way down to storing branch[0] into branch[1].  Then branch[0] is replaced with a new randomly chosen branch.  Except that srand should only be called once, and not every time the function is called.  And it should use % 3, not % 2, since % 2 will only give you values of 0 or 1.
Comment: great, that clarifies one part. But what values are actually stored in the array when its first initialized? Looking at image 1 it seems that it"s only "Left". I assumed that it should be [left,right,none,left, right,none] b
Comment: @natzer The declaration for `branchPositions` shown will zero initialize it if it is a global variable (which will set everything to `side::LEFT`).  Do you ever initialize its values to something else before you start your game loop?
Comment: no, only the for loop of the updateBranches function is running over it prior to the main loop
Comment: thanks for all the answers. I got it now. Actually the array and it's values are only secondary to the branch positioning. The only thing that influences the position is the updateBranches function which continiously pops out branch[0] and replaces it with a random one. By calling the function multiple times, all branches are replaced by a random one (as explained by 1201ProgramAlarm).

Enumeration class and array declaration


How to find 27 lines on Cayley's nodal cubic surface

Question: Cayley's nodal cubic surface is given by the equation:
$$wxy+xyz+yzw+zwx=0$$
And I want to find all 27 lines on it, but I can only find 9 lines, they are 6 lines of the form:$x=y=0$, and 3 lines of the form:$x+y=z+w=0$. So what are the other 18 lines? How can I find them?
Comment: Singular cubic surfaces do not necessarily contain $27$ lines.
Answer: By symmetry we can assume any such line is given by $x = az + bw$, $y = cz + dw$. Thus
$$acz^3 + (ad + bc + ac + a + c)z^2w + (ad + bc + bd + b + d)zw^2 + bdw^3$$
must vanish identically in $(z, w)$, so each coefficient must be $0$.
From $ac = bd = 0$, accounting for symmetry, there are two cases:

$a = b = 0 \implies c = 0$ and $d = 0$, which gives $x = y = 0$.
$a = d = 0 \implies bc + c = bc + b = 0$, so $b = c$ and $b^2 + b = 0$. So we are either in the previous case or $b = c = -1$, which gives the line $x + w = y + z = 0$.

Accounting for permutations the $9$ lines you have found are exactly the ones on this surface. The Cayley-Salmon theorem does not apply since this cubic surface is not smooth (at $[1:0:0:0]$ and its permutations).


How to debug GLSL Fragment shader (Program Linking error after code change)

Question: (original Title) Please help me debug my glsl lighting shader so that it will compile! This is my first time debugging glsl
Hello I am VERY new to opengl.  I am working on modifying another shader I found online.  The version I found online works just great, however somewhere along in my code I made a mistake while editing.  The problem is I have combed through it and can not see it, I was hoping for some fresh eyes.
To be clear it is not that what is being drawn is incorrect, it flat out wont compile
#version 330 core
struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
    float ambient;
};

struct DirLight {
    vec3 direction;
    vec3 color;
    float strength;
};

struct PointLight {
    vec3 position;
    vec3 color;
    float strength;
    float active;
};

struct SpotLight {
    vec3 position;
    vec3 direction;
    float cutOff;
    float outerCutOff;

    float constant;
    float linear;
    float quadratic;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

#define NR_POINT_LIGHTS 150

in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoords;

out vec4 color;

uniform vec3 viewPos;
uniform DirLight dirLight;
uniform PointLight pointLights[NR_POINT_LIGHTS];
uniform SpotLight spotLight;
uniform Material material;

// Function prototypes
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir);
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir, vec3 fcolor);
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir);

void main()
{
    // Properties
    vec3 norm = normalize(Normal);
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 fragColor = texture(material.diffuse, TexCoords).rgb;
    // == ======================================
    // Our lighting is set up in 3 phases: directional, point lights and an optional flashlight
    // For  each phase, a calculate function is defined that calculates the corresponding color
    // per lamp. In the main() function we take all the calculated colors and sum them up for
    // this fragment's final color.
    // == ======================================
    // Phase 1: Directional lighting
    vec3 result = vec3(0.0f);
    //result = CalcDirLight(dirLight, norm, viewDir);

    // Phase 2: Point lights
    for(int i = 0; i < NR_POINT_LIGHTS; i++)
     {
       result += CalcPointLight(pointLights[i], norm, FragPos, viewDir, fragColor);
    }
    // Phase 3: Spot light
   //result += CalcSpotLight(spotLight, norm, FragPos, viewDir);

    result += material.ambient * fragColor;
    color = vec4(result, 1.0);
}

// Calculates the color when using a directional light.
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
{
    vec3 lightDir = normalize(-light.direction);
    // Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // Combine results
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    return (diffuse + specular);
}

// Calculates the color when using a point light.
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir, vec3 fcolor)
{
    if (light.active == 1)
    {
        // Lighting
        vec3 lighting = vec3(0.0f);
        //  Diffuse
         vec3 lightDir = normalize(light.position - fragPos);
         float diff = max(dot(lightDir, normal), 0.0);
         vec3 result = light.color * diff * fcolor;
         // Attenuation (use quadratic as we have gamma correction)
         float distance = (length(fragPos - light.position)/light.strength);
         result *= 1.0 / (distance * distance);
         lighting += result;

        vec3 reflectDir = reflect(-lightDir, normal);
        float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
        vec3 specular = spec * vec3(texture(material.specular, TexCoords)) * light.color;
        specular *= material.shininess;

        specular *= 1.0 / (distance * distance);

        vec3 toReturn = lighting + specular;
        return toReturn;
    }
    else
    {
        return vec3(0.0f, 0.0f, 0.0f);
    }
}

// Calculates the color when using a spot light.
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{
    vec3 lightDir = normalize(light.position - fragPos);
    // Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // Attenuation
    float distance = length(light.position - fragPos);
    float attenuation = 1.0f / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
    // Spotlight intensity
    float theta = dot(lightDir, normalize(-light.direction));
    float epsilon = light.cutOff - light.outerCutOff;
    float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);
    // Combine results
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    ambient *= attenuation * intensity;
    diffuse *= attenuation * intensity;
    specular *= attenuation * intensity;
    return (diffuse + specular);
}

And thankfully my program does print out errors on compilation.  This is what is spat out.  Unfortunately the lines it points to are not real.... like they exist but they dont have any problems, heck one of the errors pointed to a line with no code on it....  I havent changed the fragment shader from its origional part so it can't be the issue
Picture of error can be found at: https://app.box.com/s/3nrzjyu3p2smnow5zo8j0q1lbqgdf149

I have tried glslDevil but i cant figure out how to import my shaders.
Thanks much!
EDIT:
Intersting thing i found...
An interesting thing i have noticed is that if you define the Directional light function as so
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
{
    vec3 lightDir = normalize(-light.direction);
    // Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // Combine results
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    return (diffuse + specular);
}

It only throws an error that diffuse, specular , and ambient arent a member of that struct (which is intentional)
Answer: Errors log of yours are not good

it is some linking log from the tool you are using
not the OpenGL compilation log !!!

I put your fragment shader into OpenGL and this is the real compilation log (nVidia used):
[Fragment]
Compiler error
0(94) : error C1009: "ambient" is not member of struct "DirLight"
0(95) : error C1009: "diffuse" is not member of struct "DirLight"
0(96) : error C1009: "specular" is not member of struct "DirLight"

[Program]
Linker error
Fragment info
-------------
0(94) : error C1009: "ambient" is not member of struct "DirLight"
0(95) : error C1009: "diffuse" is not member of struct "DirLight"
0(96) : error C1009: "specular" is not member of struct "DirLight"

you should use glGetShaderInfoLog for every shader/program object you use in OpenGL
I use something like this

It makes sense:
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
{
    vec3 lightDir = normalize(-light.direction);
    // Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // Combine results
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    return (diffuse + specular);
}

After the // Combine results you are accessing struct fields that are not defined in:
struct DirLight {
    vec3 direction;
    vec3 color;
    float strength;
};

[edit1] in C++ I use this class of mine for GLSL:
//------------------------------------------------------------------------------
//--- GLSL program class -------------------------------------------------------
//------------------------------------------------------------------------------
class GLSLprogram       // GLSL program class
    {
public:
    AnsiString log;
    int prog_id,    // whole program
        tesc_id,    // tessellation control
        tese_id,    // tessellation evaluation
        geom_id,    // geometry
        vert_id,    // vertex
        frag_id;    // fragment

    GLSLprogram();
    GLSLprogram(GLSLprogram& a);
    ~GLSLprogram();
    GLSLprogram* operator = (const GLSLprogram *a);
    //GLSLprogram* operator = (const GLSLprogram &a);
    void bind();
    void unbind();

    void set_source_text(AnsiString tesc,AnsiString tese,AnsiString geom,AnsiString vert,AnsiString frag);  // set source texts
    void set_source_file(AnsiString tesc,AnsiString tese,AnsiString geom,AnsiString vert,AnsiString frag);  // load and set source files

    void set1f   (AnsiString name,GLfloat x);
    void set2f   (AnsiString name,GLfloat x, GLfloat y);
    void set3f   (AnsiString name,GLfloat x, GLfloat y, GLfloat z);
    void set4f   (AnsiString name,GLfloat x, GLfloat y, GLfloat z, GLfloat w);
    void set1i   (AnsiString name,GLint x);
    void set2i   (AnsiString name,GLint x, GLint y);
    void set3i   (AnsiString name,GLint x, GLint y, GLint z);
    void set4i   (AnsiString name,GLint x, GLint y, GLint z, GLint w);
    void set1fv  (AnsiString name,GLfloat *p);
    void set2fv  (AnsiString name,GLfloat *p);
    void set3fv  (AnsiString name,GLfloat *p);
    void set4fv  (AnsiString name,GLfloat *p);
    void set1iv  (AnsiString name,GLint *p);
    void set2iv  (AnsiString name,GLint *p);
    void set3iv  (AnsiString name,GLint *p);
    void set4iv  (AnsiString name,GLint *p);
    void set2x2fv(AnsiString name,GLfloat *p);
    void set3x3fv(AnsiString name,GLfloat *p);
    void set4x4fv(AnsiString name,GLfloat *p);

    void get1f   (AnsiString name,GLfloat &x);
    void get2f   (AnsiString name,GLfloat &x, GLfloat &y);
    void get3f   (AnsiString name,GLfloat &x, GLfloat &y, GLfloat &z);
    void get4f   (AnsiString name,GLfloat &x, GLfloat &y, GLfloat &z, GLfloat &w);
    void get1i   (AnsiString name,GLint &x);
    void get2i   (AnsiString name,GLint &x, GLint &y);
    void get3i   (AnsiString name,GLint &x, GLint &y, GLint &z);
    void get4i   (AnsiString name,GLint &x, GLint &y, GLint &z, GLint &w);
    void get1fv  (AnsiString name,GLfloat *p);
    void get2fv  (AnsiString name,GLfloat *p);
    void get3fv  (AnsiString name,GLfloat *p);
    void get4fv  (AnsiString name,GLfloat *p);
    void get1iv  (AnsiString name,GLint *p);
    void get2iv  (AnsiString name,GLint *p);
    void get3iv  (AnsiString name,GLint *p);
    void get4iv  (AnsiString name,GLint *p);
    void get2x2fv(AnsiString name,GLfloat *p);
    void get3x3fv(AnsiString name,GLfloat *p);
    void get4x4fv(AnsiString name,GLfloat *p);
    };
//------------------------------------------------------------------------------
GLSLprogram::GLSLprogram()
    {
    prog_id=0;
    tesc_id=0;
    tese_id=0;
    geom_id=0;
    vert_id=0;
    frag_id=0;
    }
//------------------------------------------------------------------------------
GLSLprogram::~GLSLprogram()
    {
    if (glDetachShader==NULL) return;
    if (glDeleteShader==NULL) return;
    unbind();
    if (tesc_id>0) { glDetachShader(prog_id,tesc_id); glDeleteShader(tesc_id); }
    if (tese_id>0) { glDetachShader(prog_id,tese_id); glDeleteShader(tese_id); }
    if (geom_id>0) { glDetachShader(prog_id,geom_id); glDeleteShader(geom_id); }
    if (vert_id>0) { glDetachShader(prog_id,vert_id); glDeleteShader(vert_id); }
    if (frag_id>0) { glDetachShader(prog_id,frag_id); glDeleteShader(frag_id); }
    if (prog_id>0) {                                  glDeleteShader(prog_id); }
    log="";
    }
//------------------------------------------------------------------------------
void GLSLprogram::bind()
    {
    if (glUseProgram==NULL) return;
    glUseProgram(prog_id);
    }
//------------------------------------------------------------------------------
void GLSLprogram::unbind()
    {
    if (glUseProgram==NULL) return;
    glUseProgram(0);
    }
//------------------------------------------------------------------------------
void GLSLprogram::set_source_text(AnsiString tesc,AnsiString tese,AnsiString geom,AnsiString vert,AnsiString frag)
    {
    if (glCreateProgram==NULL) return;
    if (glShaderSource==NULL) return;
    if (glCompileShader==NULL) return;
    if (glAttachShader==NULL) return;
    if (glGetShaderiv==NULL) return;
    if (glGetShaderInfoLog==NULL) return;
    if (glLinkProgram==NULL) return;

    if (glGetProgramiv==NULL) return;
    if (glGetProgramInfoLog==NULL) return;
    if (glReleaseShaderCompiler==NULL) return;

    const int _size=1024;
    char dat[_size];
    GLint status,siz=0,i;
    const char * TC = tesc.c_str();
    const char * TE = tese.c_str();
    const char * GS = geom.c_str();
    const char * VS = vert.c_str();
    const char * FS = frag.c_str();
    log="";

    if (prog_id<=0) prog_id=glCreateProgram();

    if (tesc_id<=0) tesc_id=glCreateShader(GL_TESS_CONTROL_SHADER);
    else glDetachShader(prog_id,tesc_id);
    if (tesc!="")
        {
        glShaderSource(tesc_id, 1, &TC,NULL);
        glCompileShader(tesc_id);
        glAttachShader(prog_id,tesc_id);
        glGetShaderiv(tesc_id,GL_COMPILE_STATUS,&status);
        log+="[Tessellation control]\n";
        if (status) log+="OK\n"; else log+="Compiler error\n";
        glGetShaderInfoLog(tesc_id,_size,&siz,dat);
        for (i=0;i<siz;i++) log+=dat[i];

        }

    if (tese_id<=0) tese_id=glCreateShader(GL_TESS_EVALUATION_SHADER);
    else glDetachShader(prog_id,tese_id);
    if (tese!="")
        {
        glShaderSource(tese_id, 1, &TE,NULL);
        glCompileShader(tese_id);
        glAttachShader(prog_id,tese_id);
        glGetShaderiv(tese_id,GL_COMPILE_STATUS,&status);
        log+="[Tessellation evaluation]\n";
        if (status) log+="OK\n"; else log+="Compiler error\n";
        glGetShaderInfoLog(tese_id,_size,&siz,dat);
        for (i=0;i<siz;i++) log+=dat[i];

        }
    if (geom_id<=0) geom_id=glCreateShader(GL_GEOMETRY_SHADER);
    else glDetachShader(prog_id,geom_id);
    if (geom!="")
        {
        glShaderSource(geom_id, 1, &GS,NULL);
        glCompileShader(geom_id);
        glAttachShader(prog_id,geom_id);
        glGetShaderiv(geom_id,GL_COMPILE_STATUS,&status);
        log+="[Geometry]\n";
        if (status) log+="OK\n"; else log+="Compiler error\n";
        glGetShaderInfoLog(geom_id,_size,&siz,dat);
        for (i=0;i<siz;i++) log+=dat[i];

        }
    if (vert_id<=0) vert_id=glCreateShader(GL_VERTEX_SHADER);
    else glDetachShader(prog_id,vert_id);
    if (vert!="")
        {
        glShaderSource(vert_id, 1, &VS,NULL);
        glCompileShader(vert_id);
        glAttachShader(prog_id,vert_id);
        glGetShaderiv(vert_id,GL_COMPILE_STATUS,&status);
        log+="[Vertex]\n";
        if (status) log+="OK\n"; else log+="Compiler error\n";
        glGetShaderInfoLog(vert_id,_size,&siz,dat);
        for (i=0;i<siz;i++) log+=dat[i];
        }
    if (frag_id<=0) frag_id=glCreateShader(GL_FRAGMENT_SHADER);
    else glDetachShader(prog_id,frag_id);
    if (frag!="")
        {
        glShaderSource(frag_id, 1, &FS,NULL);
        glCompileShader(frag_id);
        glAttachShader(prog_id,frag_id);
        glGetShaderiv(frag_id,GL_COMPILE_STATUS,&status);
        log+="\n[Fragment]\n";
        if (status) log+="OK\n"; else log+="Compiler error\n";
        glGetShaderInfoLog(frag_id,_size,&siz,dat);
        for (i=0;i<siz;i++) log+=dat[i];
        }

    glLinkProgram(prog_id);
    glGetProgramiv(prog_id,GL_LINK_STATUS,&status);
    log+="\n[Program]\n";
    if (status) log+="OK\n"; else log+="Linker error\n";
    glGetProgramInfoLog(prog_id,_size,&siz,dat);
    for (i=0;i<siz;i++) log+=dat[i];

    glReleaseShaderCompiler();
    }
//------------------------------------------------------------------------------
void GLSLprogram::set_source_file(AnsiString tesc,AnsiString tese,AnsiString geom,AnsiString vert,AnsiString frag)
    {
    set_source_text(load(tesc),load(tese),load(geom),load(vert),load(frag));
    }
//------------------------------------------------------------------------------
void GLSLprogram::set1f   (AnsiString name,GLfloat x)                                 { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform1f  (id,x);       }
void GLSLprogram::set2f   (AnsiString name,GLfloat x, GLfloat y)                      { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform2f  (id,x,y);     }
void GLSLprogram::set3f   (AnsiString name,GLfloat x, GLfloat y, GLfloat z)           { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform3f  (id,x,y,z);   }
void GLSLprogram::set4f   (AnsiString name,GLfloat x, GLfloat y, GLfloat z, GLfloat w){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform4f  (id,x,y,z,w); }
void GLSLprogram::set1i   (AnsiString name,GLint x)                                   { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform1i  (id,x);       }
void GLSLprogram::set2i   (AnsiString name,GLint x, GLint y)                          { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform2i  (id,x,y);     }
void GLSLprogram::set3i   (AnsiString name,GLint x, GLint y, GLint z)                 { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform3i  (id,x,y,z);   }
void GLSLprogram::set4i   (AnsiString name,GLint x, GLint y, GLint z, GLint w)        { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform4i  (id,x,y,z,w); }
void GLSLprogram::set1fv  (AnsiString name,GLfloat *p)                                { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform1fv (id,1,p);     }
void GLSLprogram::set2fv  (AnsiString name,GLfloat *p)                                { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform2fv (id,2,p);     }
void GLSLprogram::set3fv  (AnsiString name,GLfloat *p)                                { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform3fv (id,3,p);     }
void GLSLprogram::set4fv  (AnsiString name,GLfloat *p)                                { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform4fv (id,4,p);     }
void GLSLprogram::set1iv  (AnsiString name,GLint *p)                                  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform1iv (id,1,p);     }
void GLSLprogram::set2iv  (AnsiString name,GLint *p)                                  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform2iv (id,2,p);     }
void GLSLprogram::set3iv  (AnsiString name,GLint *p)                                  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform3iv (id,3,p);     }
void GLSLprogram::set4iv  (AnsiString name,GLint *p)                                  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniform4iv (id,4,p);     }
void GLSLprogram::set2x2fv(AnsiString name,GLfloat *p)                                { GLboolean q=true; GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniformMatrix2fv(id, 4,q,p); }
void GLSLprogram::set3x3fv(AnsiString name,GLfloat *p)                                { GLboolean q=true; GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniformMatrix3fv(id, 9,q,p); }
void GLSLprogram::set4x4fv(AnsiString name,GLfloat *p)                                { GLboolean q=true; GLint id=glGetUniformLocation(prog_id,name.c_str()); glUniformMatrix4fv(id,16,q,p); }
//------------------------------------------------------------------------------
void GLSLprogram::get1f   (AnsiString name,GLfloat &x){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,&x); }
void GLSLprogram::get1i   (AnsiString name,GLint &x)  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformiv(prog_id,id,&x); }
void GLSLprogram::get1fv  (AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get2fv  (AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get3fv  (AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get4fv  (AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get1iv  (AnsiString name,GLint *p)  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformiv(prog_id,id,p);  }
void GLSLprogram::get2iv  (AnsiString name,GLint *p)  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformiv(prog_id,id,p);  }
void GLSLprogram::get3iv  (AnsiString name,GLint *p)  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformiv(prog_id,id,p);  }
void GLSLprogram::get4iv  (AnsiString name,GLint *p)  { GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformiv(prog_id,id,p);  }
void GLSLprogram::get2x2fv(AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get3x3fv(AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
void GLSLprogram::get4x4fv(AnsiString name,GLfloat *p){ GLint id=glGetUniformLocation(prog_id,name.c_str()); glGetUniformfv(prog_id,id,p);  }
//------------------------------------------------------------------------------

AnsiString is just VCL string class (self relocable string class) can use anything else like char[] or char* instead but you need to handle operators of coarse...
AnsiString().c_str() returns char* compatible pointer to stored string

usage:
// [variables]
GLSLprogram   shader;
// [init]
shader.set_source_text("","","","your vertex shader source text","your fragment shader source text");
shader.log; // contains the compile/link log ...
shader.prog_id; // contains the OpenGL id for your shader object

// [render]
shader.bind();
// here render
shader.unbind();

[edit2] And also I forget to add:
AnsiString load(AnsiString file)
    {
    int i,hnd,siz;
    char *dat=NULL;
    hnd=FileOpen(file,fmOpenRead);
    if (hnd<0) return "";
    siz=FileSeek(hnd,0,2);
        FileSeek(hnd,0,0);
    if (siz==0) { FileClose(hnd); return ""; }
    dat=new char[siz+1];
    if (dat==NULL) { FileClose(hnd); return ""; }
    FileRead(hnd,dat,siz);
    FileClose(hnd);
    AnsiString s=""; for (i=0;i<siz;i++) s+=dat[i];
    delete dat;
    return s;
    }

Comment: Thankyou!  It was such a stupid errror to make.  Could you link me to how you used this "real compilation log"?
Comment: @ShaderWriter just search the code for `glGetShaderInfoLog` and see how it is used ...


Stochastically bounded Gaussian random variables

Question: Suppose $X_n$ are independent Gaussian random variables with mean $\mu_n$ and variance $\sigma_n^2$.
Prove that $\{X_n\}$ is stochastically bounded iff $\mu_n$ and $\sigma_n^2$ are bounded sequences.
[If the sequences are bounded then the random variables are stochastically bounded. This is probably the easier side and I could solve it.
May I have some hints for the other direction?]
Answer: If $X$ is a standard normal random variable, then
$$ \mathbb{P}(X>x)\sim \frac{1}{\sqrt{2\pi}x}e^{-x^2/2}$$
as $x\to\infty$.
Therefore if $X$ is Gaussian with mean $\mu$ and variance $\sigma^2$, then
$$ \mathbb{P}(X>x)\sim \frac{\sigma}{\sqrt{2\pi}(x-\mu)}e^{-\frac{(x-\mu)^2}{2\sigma^2}} $$
as $x\to\infty$. I think this should be enough to prove the direction you want.
Comment: I just tried that but I am struggling with the case, where both $\mu_n$ and $\sigma_n^2$ are unbounded along a subsequence. Could you please elaborate? probably I am missing something.
Comment: I'd deal with the case when $\mu_n$ is unbounded (regardless of what $\sigma_n$ is doing) looking at something like $\mathbb{P}(|X-\mu_n|<\sigma_n)$. Otherwise $\{\mu_n\}$ is bounded, and the formula in my answer should handle the case when $\sigma_n$ is unbounded.
Comment: To prove that $\mu_n$ is bounded it is enough to write that $P(X_n>\mu_n) =1/2$. To deduce further that $\sigma_n$ is bounded, it suffices to write that the probability $P(X_n > \mu_n +\sigma_n)$ is independent of $n$.
Answer: Evidently $\Bbb P[X_n>x]=1-\Phi((x-\mu_n)/\sigma_n)$, and if $\{X_n\}$ is stochastically  bounded then this quantity must tend to $0$ as $x\to+\infty$, uniformly in $n$. This is the same as $\lim_{x\to +\infty}\inf_n[(x-\mu_n)/\sigma_n]=+\infty$. In particular, given $N>0$, there exists $x_0>0$ such that if $x\ge x_0$ then $x\ge \mu_n+N\sigma_n$ for all $n$. This implies that $\{\mu_n\}$ is bounded above (because $\sigma_n\ge 0$); similar consideration of the left tails $\Bbb P[X_n\le x]$ shows that $\{\mu_n\}$ is bounded below, by $K$, say. Consequently, if $x_0$ corresponds to $N=1$ as above, then $x_0\ge\mu_n+\sigma_n\ge K+\sigma_n$, so $\{\sigma_n\}$ is bounded above (and trivially, below by $0$).


How to test XML file using RSpec?

Question: I have an RSS feed that I am writing an RSpec test for. I want to test that the XML document has the correct nodes and structure. Unfortunately, I can't find any good examples of how to do this in a clean way. I have only found some half-implemented solutions and outdated blog posts. How can I test the structure of an XML document using RSpec?
Answer: Hi I can recommend you to use custom matcher for this.
 require 'nokogiri'
    RSpec::Matchers.define :have_xml do |xpath, text|
      match do |body|
        doc = Nokogiri::XML::Document.parse(body)
        nodes = doc.xpath(xpath)
        nodes.empty?.should be_false
        if text
          nodes.each do |node|
            node.content.should == text
          end
        end
        true
      end

      failure_message_for_should do |body|
        "expected to find xml tag #{xpath} in:\n#{body}"
      end

      failure_message_for_should_not do |response|
        "expected not to find xml tag #{xpath} in:\n#{body}"
      end

      description do
        "have xml tag #{xpath}"
      end
   end

Full example can be found here
https://gist.github.com/Fivell/8025849
Answer: No longer necessary to roll your own.  We deal this problem daily, using the equivalent-xml matcher at https://github.com/mbklein/equivalent-xml .
require 'rspec/matchers'
require 'equivalent-xml'
...
expect(node_1).to be_equivalent_to(node_2)

Has options for edge cases like whitespace-preservation.
Your other option is to use a formal XSD template for strict validation.
Answer: context 'POST #join' do
    it 'does successfully hit join xml route' do
      post :join,
        format: :xml
      response.content_type.should == "application/xml"
      response.should be_ok
    end
end

This worked for me. I didn't realize I had to pass format: :xml. My join route responds to /join.xml and I was testing that this was successful.
Comment: This doesn't really solve the OP's question, but it was helpful for me to just assert you are getting xml without adding gems
Answer: Give Approvals a try, it works with rspec, I have used for testing Json payload, and it is used with Minitest in exercism.io
EDIT
  it "returns available traffic information around me" do
    post '/search_traffic_around', {location: [-87.688219, 41.941149]}.to_json
    output = last_response.body
    options = {format: :json, name: 'traffic_around_location'}
    Approvals.verify(output,options)
  end

the JSON I am verifying against is located in spec/fixtures folder named traffic_around_location.approved.json
Implementation where the above snippet is pulled from is available here
How it works is you supply it an expected Payload, JSON, XML, TXT and HTML this I am sure it supports in spec/fixtures and when you run the test it checks to confirm that the payload received matches the expected(approved) payload the test would pass if it matches else the test fails
Comment: Can you provide an example of how this is meant to be used? I have read through the Approvals readme and it's not very clear.
Comment: I'll give you an up-vote for updating your answer but I'd still like to see some alternatives (or at least some more up-votes indicating this is a popular solution).

How to test XML file using RSpec?


Query Generic List

Question: I have to log FTP activity using VendorID.
Some vendors have multiple FTP user names, but I only need to log one (the latest).
For example:

VendorID 1 (two user names)
Mike
Pete
VendorID 4 (two user names)
Jack
Luis

So I created a class to store the FTP activity:
Public Class VendorClass
  Public VendorID   As Integer
  Public FTPUserName As String
  Public File   As String
  Public Date As DateTime
End Class

I load the file into a list of VendorClass

Question:
How query the list and group by UserID, and return the latest date and time.
Original List
VendorID    FTP UserName    File                Date
1           Mike            BalanceSheet.csv    6/17/2015 10:20
1           Pete            BalanceSheet.csv    6/17/2015 10:40
2           Ron             BalanceSheet.csv    6/17/2015 10:20
3           Julia           BalanceSheet.csv    6/17/2015 14:20:02
4           Jack            BalanceSheet.csv    6/17/2015 11:20
4           Luis            BalanceSheet.csv    6/17/2015 09:20

Grouped result:
VendorID    FTP UserName    File                Date
1           Pete            BalanceSheet.csv    6/17/2015 10:40
2           Ron             BalanceSheet.csv    6/17/2015 10:20
3           Julia           BalanceSheet.csv    6/17/2015 14:20:02
4           Jack            BalanceSheet.csv    6/17/2015 11:20

My function is only able to select 1 vendor at the time:
Private Function FlattenDuplicateEntries(ActivityList As List(Of VendorClass)) As List(Of VendorClass)
    FlattenDuplicateEntries = New List(Of VendorClass)

    For Each vendor In FTPUserNameList
        Dim val As New VendorClass
        val = ActivityList.Find(Function(value As VendorClass) value.VendorID = vendor.VendorID)
    Next
End Function

Comment: You ask for list by `UserId` but there is no `UserId` in your type: do you mean `VendorID`?
Answer: Private Function FlattenDuplicateEntries(ActivityList As List(Of VendorClass)) As List(Of VendorClass)
    Dim filtered As New Dictionary(Of Integer, VendorClass)()
    For Each vendor In ActivityList
        If Not filtered.ContainsKey(vendor.VendorID) Then
            filtered.Add(vendor.VendorID, vendor)
        Else If filtered(vendor.VendorID).Date < vendor.Date Then
            filtered(vendor.VendorID) = vendor
        End If
    Next
    Return filtered.Values.ToList()
End Function

Comment: This line ( filtered.Add(vendor)) gives the following exception: Argument not specified for parameter 'value' of 'Public Sub Add(key As TKey, value As TValue)'
Answer: (As this is tagged C# as well, I won't try and translate into VB.)
Something like:
var lastByVendor = from act in ActivityList
                   group by act.VendorID into grp
                   let last = grp.OrderByDescending(x => x.Date).First()
                   select new {
                     VendorId = grp.Key,
                     Date = last.Date,
                     File = last.File,
                     FTPUserName = last.FTPUserName
                   };

In this I:

Group by VendorID and do the rest for each vendor
Get the last record (no MaxBy operator in the BCL, so using a sort)
The Key of the group is the value from the group by

Query Generic List


Como obter e formatar data e hora atual?

Question: Gostaria de saber como faço para obter a data e a hora atual e então formatar elas em JAVA.
Por exemplo, tenho esses dois valores:
23062017
212010

Quero armazenar cada valor em uma variável, e depois quero formatá-las desse jeito:
23/06/2017
21:20:10

Answer: Para recuperar a data e hora atuais do sistema você pode fazer:
Date dataHoraAtual = new Date();
String data = new SimpleDateFormat("dd/MM/yyyy").format(dataHoraAtual);
String hora = new SimpleDateFormat("HH:mm:ss").format(dataHoraAtual);

Dessa forma você receberá a data e hora nos formatos que deseja e em variáveis separadas.

Para referência, no meu GitHub tem uma classe (um Servlet) que fiz para um trabalho da faculdade que retorna a data e hora.
Comment: @pmargreff mas está como referencia. Inclusive escrevi exatamente: "Para referência". A resposta é o que está em cima da linha horizontal ._.
Comment: boa resposta, mas não aponte links externos, de preferência por copiar o conteúdo aqui e apenas referenciar a fonte original ...
Answer: No título da pergunta é mencionado "data e hora atual", mas no corpo da pergunta são mencionados valores específicos. De qualquer forma, segue uma solução para ambos.

As outras respostas usam SimpleDateFormat, mas a partir do Java 8, você pode usar a API java.time. Nesta API, há classes para manipular apenas a data, ou apenas a hora, que parece ser o que você precisa.
Para ler as Strings mencionadas, você pode usar um java.time.format.DateTimeFormatter, que transforma a String no tipo correspondente (java.time.LocalDate para datas, ou java.time.LocalTime para horas).
Depois, eu uso outro DateTimeFormatter para formatá-las (converter para o outro formato):
// converter 23062017 para 23/06/2017
DateTimeFormatter parserData = DateTimeFormatter.ofPattern("ddMMuuuu");
LocalDate data = LocalDate.parse("23062017", parserData);
DateTimeFormatter formatterData = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dataFormatada = formatterData.format(data); // 23/06/2017

// converter 212010 para 21:20:10
DateTimeFormatter parserHora= DateTimeFormatter.ofPattern("HHmmss");
LocalTime hora = LocalTime.parse("212010", parserHora);
DateTimeFormatter formatterHora = DateTimeFormatter.ofPattern("HH:mm:ss");
String horaFormatada = formatterHora.format(hora); // 21:20:10

Caso queira usar a data e hora atual, você pode usar um java.time.LocalDateTime (que já possui ambas as informações) e formatá-lo:
// data/hora atual
LocalDateTime agora = LocalDateTime.now();

// formatar a data
DateTimeFormatter formatterData = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dataFormatada = formatterData.format(agora);

// formatar a hora
DateTimeFormatter formatterHora = DateTimeFormatter.ofPattern("HH:mm:ss");
String horaFormatada = formatterHora.format(agora);

Repare também que no java.time é possível usar u em vez de y para o ano. A diferença é que o y não funciona para datas AC (Antes de Cristo). Como u funciona para ambos os casos (AC e DC), acaba sendo a melhor escolha. Veja esta resposta do SOen para entender melhor os detalhes.

Se você ainda não usa Java 8, pode usar o ThreeTen Backport, que possui as mesmas classes já mencionadas e funciona basicamente do mesmo jeito. A diferença é que elas estão no pacote org.threeten.bp (ao invés de java.time).
O backport é compatível com JDK 6 e 7.
Se você puder usar esta API ao invés de Date e SimpleDateFormat, faça-o. A nova API é muito superior e corrige vários dos problemas existentes na API antiga.

Se você por algum motivo estiver preso ao Java 5, não é possível usar o ThreeTen Backport. Mas se quiser usar uma API melhor que Date e SimpleDateFormat, uma opção é usar o Joda-Time. Ela é bem parecida com o java.time (pois é a sua predecessora, e ambas foram feitas pela mesma pessoa), apesar de haver algumas diferenças entre elas.
Mas a ideia é essencialmente a mesma, veja como converter as suas strings para uma data e hora no formato desejado:
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

// converter 23062017 para 23/06/2017
DateTimeFormatter parserData = DateTimeFormat.forPattern("ddMMyyyy");
LocalDate data = LocalDate.parse("23062017", parserData);
DateTimeFormatter formatterData = DateTimeFormat.forPattern("dd/MM/yyyy");
String dataFormatada = formatterData.print(data);
System.out.println(dataFormatada); // 23/06/2017

// converter 212010 para 21:20:10
DateTimeFormatter parserHora = DateTimeFormat.forPattern("HHmmss");
LocalTime hora = LocalTime.parse("212010", parserHora);
DateTimeFormatter formatterHora = DateTimeFormat.forPattern("HH:mm:ss");
String horaFormatada = formatterHora.print(hora);
System.out.println(horaFormatada); // 21:20:10

A ideia é a mesma: usar um org.joda.time.format.DateTimeFormatter para converter as strings para um org.joda.time.LocalDate (representando a data - apenas o dia, mês e ano) e para um org.joda.time.LocalTime (um horário).
Em seguida, uso outro DateTimeFormatter para converter o LocalDate e o LocalTime para outro formato. Uma diferença para o java.time é que nas classes do Joda-Time também é possível usar toString() com o formato desejado:
System.out.println(data.toString("dd/MM/yyyy")); // 23/06/2017
System.out.println(hora.toString("HH:mm:ss")); // 21:20:10

E para obter a data/hora atual, pode-se construir um org.joda.time.LocalDateTime, que já possui tanto a data quanto a hora, e a partir daí imprime-se nos 2 formatos:
LocalDateTime dataHoraAtual = new LocalDateTime();
System.out.println(dataHoraAtual.toString("dd/MM/yyyy"));
System.out.println(dataHoraAtual.toString("HH:mm:ss"));

Só lembrando que o Joda-Time é uma alternativa para o JDK 5, já que no seu próprio site há um aviso dizendo que esta API é um projeto "encerrado", não há melhorias previstas e por fim recomenda o uso do java.time (ou seja, o ThreeTen Backport para JDK 6 e 7, e java.time para JDK >= 8).

Isso não invalida as demais respostas que usam SimpleDateFormat e Date. Se não tiver como usar o Java >= 8, ou não houver possibilidade de adicionar uma biblioteca como o ThreeTen Backport ou o Joda-Time, a API legada continua sendo uma opção válida.
Answer: Neste exemplo gera duas strings dia e hora, com o formato para dia 02-03-2018 e string hora 22:21:30
Calendar calendar = Calendar.getInstance();//cria o obj calendar e atribui a hora e data do sistema
Date data = calendar.getTime();//transforma o obj calendar em obj Date

SimpleDateFormat sddia = new SimpleDateFormat("dd-MM-yyyy");//cria um obj de formatação de data
SimpleDateFormat sdhora = new SimpleDateFormat("HH:mm:ss");//cria um obj de formatação de hora
String dia = sddia.format(data);//gera a string final formatada no estilo "dd-MM-yyyy"
String hora = sdhora.format(data);//gera a string final formatada no estilo "HH:mm:ss"

Comment: Só um detalhe, para obter a data atual, é mais simples fazer `Date data = new Date()`. Criar um `Calendar` **só** pra isso é desnecessário, pois `new Date()` já obtém a data e hora atual do sistema :-)
Answer: Opa, blza!?
É possível obter a data atual das APIs clássicas (Date), e também pelas novas APIs de data e hora do java 8 (LocalDateTime e LocalDate).

API clássica
para o java.util.Date:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //01/02/2019 14:08:43

Java 8+
para o java.time.LocalDateTime:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //01/02/2019 14:08:43

para o java.time.LocalDate:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //01/02/2019

Answer: public static void main(String[] args) {

    String dataAtualFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
                                    .format(System.currentTimeMillis());

    //Seta valores da data
    String dataString = dataAtualFormatada.substring(0,10);

    //Seta valores do horário
    String horario = dataAtualFormatada.substring(11,19);

}


On which tournaments the seeding does not follow ATP/WTA ranking?

Question: Wimbledon uses seeding which gives advantage to players that are more successful on grass courts. (Although I am not sure how long have they used seeding in this way.)
For example, in Wikipedia article on 2014 Wimbledon Championships we can read that:

The Gentlemen's singles seeds is arranged on a surface-based system to reflect more accurately the individual player's grass court achievement as per the following formula, which applies to the top 32 players, according to ATP Ranking on 17 June 2013:

Take Entry System Position (ESP) points at 16 June 2014
Add 100% points earned for all grass court tournaments in the past 12 months (16.06.2013 – 15.06.2014).
Add 75% points earned for best grass court tournament in the 12 months before that (12.06.2012 – 15.06.2013)

For the Ladies' singles seeds, the seeding order follows the ranking list, except where in the opinion of the Committee, the grass court credentials of a particular player necessitates a change in the interest of achieving a balanced draw.

Are there some other tournaments which do not follow ATP/WTA rankings? In general, can organizers of a tournament make changes to seeding, if they want to do so?
Answer: Wimbledon is a special case and, to my knowledge, the only event at the ATP/WTA level that uses its own special "recent grass performance" seeding method.
Not many fans that follow tennis closely seem to be a fan of this seeding method because it seems to confuse more than it helps. Personally I don't mind it because it tends not to alter the seeding too dramatically. That aside, in some cases I can see why the players themselves really don't like it because it can possibly mean facing a tougher opponent than they would normally - although the opposite could be an outcome as well (facing a weaker opponent).
The main reason why Wimbledon can get away with doing this is because it is an ITF event (governed by the International Tennis Federation) and not an ATP or WTA event. That still doesn't explain why they do things that way - since all of the 4 majors are ITF events and the Australian Open, French Open and US Open still follow the ATP/WTA rankings for seeding.


How to add body class that carries the menu depth of the current page?

Question: I am on Drupal 7. On the body tag, I need to create a new class that will detect the current page's menu depth. The class could carry the ID of the menu, then something that would detect the current page's menu depth. It could be something like: "primary-depth-0" for the top menu items, then "primary-depth-1", "primary-depth-2" and so forth... Is it easy to code that on template.php? I assume I have to add a new item into the $classes array...
Thank you.
Answer: I did something similar in the past, but I can't remember on which project, so I don't have working code.
Inside a template_preprocess_html, you get the breadcrumb via menu_get_active_breadcrumb.  You then walk the breadcrump  keeping track of depth, comparing the paths against the current path.  When you find a match, you end the walk and then
<code>$variables['classes_array'][] = "menu-depth-" . $depth;
</code>
I am pretty sure this is what I did.
Comment: Thank you! This works. Actually, I think $depth = sizeof($breadcrumb) will give me the depth number I need where $breadcrumb = menu_get_active_breadcrumb()... Is this right? I am using this and it works for me.
Comment: If it works, then it is right.  Couldn't quite remember exactly what menu_get_active_breadcrumb() returned at the $breadcrumb.
Comment: It appears it returns an array with all the elements of the breadcrumb array.


"times 510-($-$$) db 0" not working with my codes

Question: So the code that works fine and produce a 512 bits file is bellow
    org 07c00h
    mov ax, cs
    mov ds, ax
    mov es, ax
    call    DispStr
    jmp $
DispStr:
    mov ax, BootMessage
    mov bp, ax
    mov cx, 16
    mov ax, 01301h
    mov bx, 000ch
    mov dl, 0
    int 10h
    ret
BootMessage:        db  "Hello, OS world!"
times   510-($-$$)  db  0
dw  0xaa55

Then I add few lines and the bin file is 540 bits, which make no sense, the only way to fix this is do times 380 db 0 , which I do the calculation
The nonsense code is bellow
[BITS 16]
[ORG 0x7c00]

jmp     Main

PrintTill0:
lodsb
cmp     al,0
je      Return
mov     ah,0eh
int     10h
jmp     PrintTill0

PrintWithLength:
mov     ah,13h
int     10h
jmp     Return

Return:
ret

Main:
mov     si,msg1
call    PrintTill0

cli
push    SEGment msg2
pop     es
mov     bp,msg2
sti
loop1:
mov     cx,9
call    PrintWithLength
inc     bl
jmp     loop1

cli
hlt

msg1:    db  "Hello, AInoob~~~",0Dh,0Ah,"The future is in your hand, so, what do you want to do?",0Dh,0Ah,0h
msg2:    db  "AInoob~~~"

times 510-($-$$) db 0
dw 0xAA55

Can anyone tell me what's going on? This really drives me crazy
Answer: It looks like you're trying to store the segment base of msg2 into es, and the keyword you're looking for is just SEG, not SEGMENT. Unfortunately, flat binary outputs do not support this, so you need a different solution.
Instead, since you know msg2 is not going to be beyond address 0x10000, you can just set es to zero:
xor ax, ax
mov es, ax

Comment: Thanks for answer, but when I tried SEG, it says binary output format does not support segment base references, no matter I remove Times xxx db 0 or not.


Do you have to alter the database schema in the onUpgrade method of the SQLiteOpenHelper?

Question: I'm trying to write an android app that contains a database that would dynamically change its schema based on user input.
For example, suppose that you initially have a table in which the only column is a column for different breeds of puppies. This would be the primary key. The user can then dynamically add new attributes which would correspond to new columns in this table (e.g. color, has spots, size, etc.)
I was wondering whether the ALTER TABLE query must be executed in onUpgrade or whether I can do it in another method within the SQLiteOpenHelper subclass. I don't really know if it is really necessary to increment the database version every time the user wants to add a new attribute. Thanks!
Answer:
I was wondering whether the ALTER TABLE query must be executed in onUpgrade or whether I can do it in another method within the SQLiteOpenHelper subclass.

You are welcome to execute ALTER TABLE statements whenever you want, though (as with all database I/O) on a background thread, please.
In your case, I do not know why you are using SQLiteOpenHelper, though. The point behind SQLiteOpenHelper is to help developers building apps with fixed (per version) schemas. That is not the route that you are taking, in which case SQLiteOpenHelper may not really be helping much.
Answer: onUpgrade will only be called when the database file already exists but the stored user version is lower than requested in constructor. I have used this function to carry out the changes I  made to the database schema when I release a new version of the app.  But if you want to add columns dynamically, yes you can use the ALTER TABLE command.


How do I find P(a<x<b) with a mean of 10 and a standard deviation of 2 for a normal distribution

Question: Mean = u = 10 std = o = 2
Finding a and b such that P(a<x<b) = 0.90 and |u-a| = |u-b|
So I looked at a Z table and found 0.90 sitting between a Z-Score of 1.28 and 1.29. I added those values up and took the average so that.
1.28 = 0.899727432 and 1.29 = 0.901474671
(0.899727432 + 0.901474671) / 2 = 0.9006010515
Z= 1.285
Then I used the standard normal equation.
Z=(x-u)/o
where x = b
1.285 = (b - 10) / 2
b = 2(1.285) + 10
b= 12.57
Are A and B the same then? I'm not sure I'm approaching this problem correctly.
Comment: I have it figured out thank you.  https://imgur.com/UusNMaQ
Comment: Welcome to stats.SE. You are on the right track in general that you started by letting Z following N(0, 1), trying to find c and d such that $P(c<Z<d)=0.9$ using a z-table, and convert $c,d$ to $a,b$ by taking the inverse of the standard score function. However, you might not have read the z-table correctly - most z-tables give you the probability of seeing values from _negative infinity_ up to your tabled value, and you want to ditch part of the said probability density in your question.
Comment: Do you have access to any of (1) a z-table which shows the z-value for specific quantiles (0.9, 0.95, 0.99), (2) a calculator that calculates $P(c<Z<d)$ or at least $P(Z<d)$ for any given $c$ and $d$, or (3) a programming library that does (2)?
Comment: I have access to  https://www.ztable.net, as to a calculator that calculated P(c < Z < d) I do not as I believe I'm supposed to be learning how to do this by hand.

I believe since the total probabilty is 0.90, the probability of P(ax) = 0.45.
Comment: Your understanding of splitting the probability density of 0.9 into two equal halves is sound, but the way you expressed it (i.e., $P(a<X) = 0.45$ and $P(X<b) = 0.45$)) will lead to something totally different as you have not bounded the values of $X$ correctly. Draw a normal distribution (be it with (mean, variance) = (10, 2) or (0, 1)) on a paper, can you sketch which region you want your 0.9 probability to cover, at what value you are splitting them in two 0.45 halves, and express the probability expressions using the bounds you have found? Hint: the expressions should involve $\mu$.
Answer: P(X<b) = 0.95
Z = 1.645
1.645 = (b-10)/2
2(1.645) + 10 = b
13.25 = b
P(x>a) = 1 - 0.95 P(x<a) = 0.05
Z for 0.05 is -1.64
2(-1.64)+10 = a
a = 6.72
Comment: Thank you, I will come back to this and add more clarifying detail as it will help me also better understand.
Comment: It may be helpful to add more clarifying detail to your answer. Of course showing an answer directly illustrates the solution, but it may benefit others if you explain why it worked :)


How to show there is no magic cube of order 2?

Question: I am reading Richard A. Brualdi's Introductory Combinatorics (Ch1.2).

Three-dimensional analogs of magic squares have been considered. A magic cube of order n is an n-by-n-by-n cubical array constructed out of the integers 1,2, ... , n3 in such a way that the sum s of the integers in the n cells of each of the following straight lines is the same:
  (1) lines parallel to an edge of the cube;
  (2) the two diagonals of each plane cross section;
  (3) the four space diagonals.
  The number s is called the magic sum of the magic cube and has the value (n4 +n)/2. We leave it as an easy exercise to show that there is no magic cube of order 2

I am not sure how to begin and would appreciate a tip on how to approach this
Thanks
Answer: Each layer of a magic cube must be a magic square.  There is no magic square of order $2$, even with the numbers not in series.  Write the square as
$$ \begin {array}{c c}a&b\\c&d \end {array}$$
and note that $a+b=a+d, b=d$, similarly for other pairs, and all the numbers must be the same.
Answer: Hint: The magic sum will be $\frac{2^4 + 2}{2} = 9$, which means that each pair needs to contain exactly one odd number.
Comment: How can we show there is no magic cube using the fact that each pair in the sums will contain exactly one odd number? For example, if I were to take one of the faces I would still have

(a+b=9)
(c+d=9)
(a+d=9)
(c+b=9)

I'm stuck because I don't know the parity of any single digit.
Comment: @kaleidoscope Take any 3 of the cells of the magic cube and say their numbers are $a,b,c$. There's no way to have each pair $(a,b),(a,c),(b,c)$ have exactly one odd value.


How do I emphasize having fun instead of focusing on wins?

Question: I'm coaching a team in a U8 recreational soccer league.
Some of the parents and assistant coaches are way more focused on the team's win-loss record than they are on the kids having fun.
The real challenge is with the assistant coaches.  I need their help in running practices and games, but their focus on winning is putting some of the kids off.  The message the kids get is that it can't be fun if they don't win the game.
At this stage and level of (non-)competitive play, I see my job as inspiring the kids with passion for the game and to enjoy playing on a team.  I would like for them to win some games, but I'm more concerned with making sure they enjoy playing first.
How can I convince my assistant coaches to change their behavior / what they're saying to the kids?

To address some questions:
1) I have already talked with the ass't coaches and pointed out what's going on.  But they're type-A driven individuals and while they say they agree with my points, they haven't shifted their focus.
2) The team didn't win any games last season.  And no, I wasn't involved with the team at that point but the assistant coaches were.
3) I can't replace the assistant coaches as I don't have anyone to replace them with.  And it's a rec league.  And these are their kids, too.
4) And yes, winning is fun, but you can have fun without always winning too.
5) Honestly, I don't know how much latent talent is on the team.  But my first guess is not much at this stage.  And I'll counter that by noting Michael Jordan was cut from his HS basketball team, and I've heard that Pele was just average at this age.  I see those examples as more reasons I want the kids having fun and a passion for the sport before worrying about win-loss.
Comment: Not a complete answer, but did you ever try organizing a team-event not related to soccer (e.g. bowling, movie night, barbecue). This helps for emphasizing the having fun part (in contrast with suppressing the winning part)
Comment: Not sure [Herman Edwards](http://www.youtube.com/watch?v=YNooFZPfmgE) would approve, but if kids (or anyone) are having fun, you'll most likely get the most from them.
Comment: @edmastermind29 - We're certainly not playing futbal at the level Herman coaches football, so I'll happily let him have his opinions regarding winning.
Answer: Try developing a goal setting program to use with your players and coaching staff. It's important to set goals related to performance (e.g., # received passes, shots, etc.) not outcomes (e.g., wins-losses). You can begin by setting one or two performance goals for each practice and game and go from there.
For your assistant coaches, they should be able to understand that if you take care of your performance (what you can control), the desired outcome will follow (a byproduct of good performance that you don't have control over). This way of focusing helps maintain motivation since you can still achieve your goals (success!) despite losing a game.
When you're setting up your goals they should meet the SMART criteria. That is each goal should be:

Specific
Measurable
Attainable
Relevant
Time-bound

You can find some more detail here.
Comment: This still sounds like overkill for an U8 competition!
Answer: Maybe you can try focusing more on detail - parts of a game. I never played soccer seriously, but I imagine it is more than just 2x10 people running after a ball and trying to kick it in the direction of their favored goal.
I don't know how receptive a U8 team is, but maybe you can put the focus on actually being aware of team dynamics, and showing how certain behavior is better than others, depending on the situtation. (Say, better to pass to an open player than try to kick through a wall).
Your praise/chiding would be aimed at these aspects then.

Praise them when they see the big-picture(a team mate running to an open spot, realizing there's 3 opponents coming to your position) - and focus on realizing these things quickly.
Chide them for not watching the field, playing solo.

Maybe you can film the games from a higher point of view(top of the rafters?) and cut out two minutes from each game to show what went good and what didn't. (The high viewpoint might be a cool comparison to professional football coverage : P)
Anecdote: my highschool had subject-profiled classes, and the class soccer tournament was always won by the math/informatics class. I watched the final between them and the econ/business class in one year, and it was even a bit chilling how the scrawnier team endlessly outplayed the 1 year more senior team and beat them 11-2 in a 30 min match.
Answer: In the UK, the Lawn Tennis Association, has various coaching learning sites and one of the concepts they discuss is the difference between outcome and process.
Outcome is something that you can easily measure, you get a result, such as your first serve percentage or your win/loss ratio, or as simple as did you win or lose.
Tennis is an outcome based sport of course.  But particularly when players are starting out, they are not going to immediately win all their matches.  And losing can be de-motivating, particularly if parents or coaches keep emphasising results.  If the first question after your match from your parents is "Did you win?" then that can be very demotivating if you didn't.  Why did'nt they ask "How did you get on?" Or "How did you get on using your new killer forehand?"
Parents and coaches can change the narrative and focus more on the process to build confidence in players.   Process is about how you do something.  Players achieve a feeling of success by engaging in the new techniques they are working on.  For example, did they hit the ground stroke from low to high to give topspin to get the ball over the net.
To get to win you need to follow the process of learning to get the great forehand, better anticipation, improved footwork etc.  Winning is more the longer term goal.  To get there, players need to keep learning.  They have to be patient and of course if they are enjoying practice sessions they will stick at it.
Have you read the book Mindset by Carol Dweck.  She distinguishes between a growth and a fixed mindset which is related.  Players with a growth mindset are more likely to stick with the learning and improve so they get to the stage where they start winning.
You are going to have to educate your assistant coaches and parents.


When talking about a batter, what does shutout mean?

Question: At about 7′30″ into the video linked below, the announcer says "That's shotout to center field."
As far as I know, shutout refers to the act by which a single pitcher pitches a complete game and does not allow the opposing team to score a run strikes, which is obvious not what the announcer means.
So what does shutout there mean?
The link starts at 7′22″.
Answer: The word is "Shot out", not "Shut out".  "Shot out" in this context refers to the meaning of "Shot" similar to "shot from a gun" - i.e., a hard blast as opposed to a soft "bloop" hit.


o setInterval() não estou conseguindo fazer ele funcionar

Question: não estou conseguindo colocar o um tempo pois criei um carousel e queria colocar um intervalo de 4 segundos para iteração .
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

        Voltar

carrosel numero - 1

        Avançar

        Voltar

carrosel numero - 2

        Avançar

        Voltar

carrosel numero - 3

        Avançar

aparece esse erro Uncaught TypeError: Cannot set property 'id' of null
at index.html:34

.container {
  width: 150px;
  height: 150px;
}

.wall {
  display: none;
  width: 100%;
  height: 100%;
}

/* Corzinha de fundo para diferenciar */
.wall-1 {
  background-color: #f00;
}
.wall-2 {
  background-color: #0f0;
}
.wall-3 {
  background-color: #00f;
}

.wall:target {
  display: block;
}

código CSS que mostra o carousel
Comment: no caso como colocaria .
Comment: Essa linha 34 que refere-se ao erro de id não encontrado seria qual parte exatamente ali do script?
Comment: seria essa parte declarada document.querySelector("#wall-1").id = "#wall-1" + x;
Comment: Faça um teste de mesa. Na primeira vez que você executa a sua função, você procura por um elemento com o `id` `wall-1`, então você concatena `x` no `id` desse elemento, resultando no `id` `wall-12`. Na segunda vez que você executa a função, você procura novamente pelo `id` `wall-1`, mas esse `id` não existe mais, ele foi alterado, por isso o erro.
Comment: eu coloquei wall- sem numero mas tb não deu certo
Comment: no caso eu tinha ido pela essa logica
Answer: Tem dois problemas ai

O intervalo da primeira chamada ele aponta corretamente para o #wall-1

document.querySelector("#wall-1").id // Te da o valor de: wall-1
document.querySelector("#wall-1").id = "#wall-1" + x
// Seria wall-1 recebe "wall-1" + 1
// Então estaria id="#wall-11" assim te retornando o erro que não conseguiu obter id de núlo

Então na segunda chamada ele ficaria assim

wall-1 = "#wall-1" + 1 // o seu id estaria como id="#wall-11"

Assim nem mesmo chegando ao #wall-2, pois você está atribuindo uma string á um número
sem contar que o # vai junto no id="#..."
E também não faria muito sentido você tentar atribuir ID existente á um outro elemento..

document.location = "#wall-1";
      var atual = 1;
      setInterval(function () {
        atual++;
        let id = document.querySelector(`#wall-${atual}`).id // id == wall-2, na prox chamada id será wall-3, etc...
        if (atual == 3) {
          clearInterval();
        }
      }, 4000);

Desse jeito ele entra no intervalo, adiciona +1 ao atual sendo atual == 2

É bem ruim você fazer isso com Javascript Puro, a não ser que esteja aprendendo ainda, tente começar com Jquery[1], além de prático vai te dar uma ajuda com relação á animações/DOM em JS.