How to verify this function is continuous?

Question: Recently, I'm reading a paper "Spaces with a regular Gδ-diagonal" of A.V.Arhangel'skii's. I can't understand the function $d$ in the example 9 is continuous. Could someone help me? Thanks ahead:)
Comment: The example to which you refer looks involved, but if you added a description of it here I think that would better your chances of getting an answer.
Comment: I've three books edited by Arkhangel'skii, none of which is the one you mention. If you don't write down that example the ammount of people understanding what you are talking about might be, I'm afraid, pretty reduced and, thus, the probability to get some help is going to be pretty tiny.
Comment: The paper is linked, and appears to be open-access (I wasn't asked for any credentials).
Comment: I've tried, however it is a little complex to descripte here indeed.
Comment: @DonAntonio: I included the description in my answer, which makes the whole thing self-contained.
Answer: The space is $X=X_0\cup X_1\cup U$, where $X_0=\Bbb R\times\{0\}$, $X_1=\Bbb R\times\{-1\}$, and $U=\Bbb R\times(0,\to)$. For $x=\langle a,0\rangle\in X_0$ let $x'=\langle a,-1\rangle\in X_1$. For $n\in\Bbb Z^+$ and $x=\langle a,0\rangle\in X_0$ let
$$V_n(x)=\{x\}\cup\left\{\langle s,t\rangle\in U:t=s-a\text{ and }0<t<\frac1n\right\}$$ and
$$V_n(x')=\{x\}\cup\left\{\langle s,t\rangle\in U:t=a-s\text{ and }0<t<\frac1n\right\}\;.$$
The topology $\tau$ on $X$ is obtained by isolating each point of $U$ and taking the families $\{V_n(x):n\in\Bbb Z^+\}$ and $\{V_n(x'):n\in\Bbb Z^+\}$ as local bases at $x\in X_0$ and $x'\in X_1$, respectively.

Added: In other words, $X$ is the closed upper half-plane with the $x$-axis doubled. Points in the open upper half-plane are isolated; basic open nbhds of points in one copy, $X_0$, of the $x$-axis are spikes diagonally up and to the right; and basic open nbhds of points in the other copy, $X_1$, of the $x$-axis are spikes diagonally up and to the left.

Now define $d:X\times X\to\Bbb R$ as follows.

If $x\in X_0$ and $y=\langle s,t\rangle\in V_1(x)\setminus\{x\}$, let $d(x,y)=d(y,x)=t$.
If $x'\in X_1$ and $y=\langle s,t\rangle\in V_1(x')\setminus\{x'\}$, let $d(x',y)=d(y,x')=t$.
For distinct $y=\langle s,t\rangle,z=\langle u,v\rangle\in V_1(x)\setminus\{x\}$, let $d(y,z)=\max\{t,v\}$.
For distinct $y=\langle s,t\rangle,z=\langle u,v\rangle\in V_1(x')\setminus\{x'\}$, let $d(y,z)=\max\{t,v\}$.
For all other distinct $x,y\in X$ let $d(x,y)=1$, and of course $d(x,x)=0$ for all $x\in X$.

The claim in the paper is that $d$ is a continuous symmetric that generates $\tau$. That it's a symmetric is obvious, and it's not hard to check that it generates $\tau$.
$X$ is first countable, so it suffices to show that that if $\langle x_n:n\in\Bbb Z^+\rangle\to x$ and $\langle y_n:n\in\Bbb Z^+\rangle\to y$, then $\langle d(x_n,y_n):n\in\Bbb Z^+\rangle\to d(x,y)$. This is easily done by cases.

If $x$ and $y$ are isolated points, we may assume without loss of generality that $x_n=x$ and $y_n=y$ for all $n\in\Bbb Z^+$, so that $d(x_n,y_n)=d(x,y)$ for all $n$, and the result is trivial.
Suppose that $x\in X_0$ and $y=\langle s,t\rangle\in V_1(x)\setminus\{x\}$. Then $y$ is an isolated point in $X$, so we may assume that $y_n=y$ for all $n\in\Bbb N$. Either $\langle x_n:n\in\Bbb N\rangle$ is eventually constant at $x$, in which case the result is trivial, or we may assume (by passing to a subsequence if necessary) that $x_n=\langle s_n,t_n\rangle\in V_n(x)\setminus\{y\}$ for $n\in\Bbb Z^+$. But then $$d(x_n,y_n)=d(x_n,y)=\max\{t_n,t\}=t=d(x,y)$$ for all sufficiently large $n$, since $\langle t_n:n\in\Bbb Z^+\rangle\to 0$. The case of $x'\in X_1$ and $y\in V_1(x)\setminus\{x'\}$ is exactly similar.
Suppose that $x$ and $y$ are distinct points of $X_0$. If both sequences are eventually constant, the result is trivial, so assume that the sequence $\langle x_n:n\in\Bbb Z^+\rangle$ is non-trivial. As before, we may assume that $x_n=\langle s_n,t_n\rangle\in V_n(x)$. We may further assume that $y_n\in V_1(y)$ for all $n\in\Bbb Z^+$. Then for all $n\in\Bbb Z^+$ we have $y_n\notin V_1(x)$, so $d(x_n,y_n)=1=d(x,y)$ by clause (5) of the definition of $d$. The case of distinct points of $X_1$ is exactly similar.
Suppose that $x\in X_0$ and $y=x'\in X_1$. Then for each $u\in V_1(x)$ and $v\in V_1(x')$ we have $d(u,v)=1$, since $u$ and $v$ don't fall under any of the first four clauses in the definition of $d$, and the result is trivial.
Finally, suppose that $x\in X_0$, $y\in X_1$, and $y\ne x'$. The sets $V_1(x)$ and $V_1(y)$ intersect in at most one point, and there is an $n_0\in\Bbb Z^+$ such that $V_{n_0}(x)\cap V_{n_0}(y)=\varnothing$. Thus, we may without loss of generality assume that $x_n\in V_{n_0}(x)$ and $y_n\in V_{n_0}(y)$ for all $n\in\Bbb Z^+$. But then, just as in Case 3, $d(x_n,y_n)=1=d(x,y)$ for all $n\in\Bbb Z^+$, and we're done.


Capistrano 3 sudo task

Question: I want to write a recipe with Capistrano 3 executing a task on the remote server with sudo.
With Capistrano 2 this could be done for example:
default_run_options[:pty] = true

task :hello do
  run "#{sudo} cp ~/something /something"
end

With Capistrano 3 I found:
set :pty, true

But I could not get to execute a task running with sudo.
How can I run a task with sudo?
Comment: @Rubyman `:use_sudo` is not a valid setting for Capistrano 3. See this [related ticket](https://github.com/capistrano/capistrano/issues/920)
Answer: The Capistrano 3 guide recommends the use of passwordless sudo. This allows your less-priveleged user execute the sudo command without having to enter a password via the PTY.
You can use the task that Kentaro wrote above, and add something like the following to your /etc/sudoers file:
deploy ALL=NOPASSWD:/bin/cp ~/something /something

http://www.capistranorb.com/documentation/getting-started/authentication-and-authorisation/#toc_8
Comment: And if  your policies dictate that you must use a password?
Answer: I usually write like this:
task :hello do
  on roles(:all) do |host|
    execute :sudo, :cp, '~/something', '/something'
  end
end

Edit
Capistrano 3 does not support sudo with password.
However, I created a small gem, which enables you to use sudo with password in Capistrano 3 task.
Add sshkit-sudo to your application's Gemfile:
# Gemfile
gem 'sshkit-sudo'

And require 'sshkit/sudo' in you Capfile:
# Capfile
require 'sshkit/sudo'

Now, you can execute a command with sudo as follows:
task :hello do
  on roles(:all) do
    sudo :cp, '~/something', '/something'
  end
end

Comment: I already tried this to. The console displays this:                INFO [5d8e920e] Running /usr/bin/env sudo cp ~/something /something on example.local
DEBUG [5d8e920e] Command: /usr/bin/env sudo cp ~/something /something
DEBUG [5d8e920e]  [sudo] password for main:                   I can also insert my password, which is displayed by the way, but the task does not continue on return.
Comment: If you really want to use sudo with password, you should use capistrano 2.
Comment: This works. Thanks. If someone is looking to do apt-ge with sshkit-sudo try `sudo :'apt-get', '-y install curl'`
Comment: `sudo` instead of `execute` did the job for me. thx
Answer: To resolve this issue I needed to add set :pty, true to my deploy.rb file.
I can now run the following:
# config valid only for Capistrano 3.1
lock '3.1.0'

set :application, 'APP_NAME'
set :pty, true
set :ssh_options, {:forward_agent => true}

namespace :deploy do

  desc 'Restart NGINX'
  task :restart do
    on roles(:app), in: :sequence, wait: 1 do
       execute :sudo, "./restart.sh"
    end
  end

end

This task basically runs a shell script called restart.sh that has a command within sudo service nginx restart.
Comment: When I do this it asks me for my password, but I cannot "enter" it, it just gives me newlines..
Comment: Yes, only after setting `set :pty, true` can you execute sudo commands with capistrano 3. Otherwise you will get `sudo stderr: sudo: no tty present and no askpass program specified` errors.
Comment: @TimBaas were you able to solve your issue ? I am also stuck with the same problem
Comment: @aelor did you solve that problem, I'm stuck in the same place
Comment: @ArianFaurtosh @aelor - make sure you've added `set :ssh_options, {:forward_agent => true}`
Comment: @ArianFaurtosh basically the log that you are seeing is not an interactive shell. So you cannot input anything. Now, to solve this, you can do either of two things: a) add your user to with no password access inside sudoers file or b) do a `bundle install --deployment`, the deployment flag makes sure that the gems get installed within the vendor directory for which the user already has access. The latter solved my issue
Answer: you want "as user do end", like
as "root" do
  execute :something
end

Comment: I think this is the Capistrano 2.x syntax?
Comment: AFAIK as-user-do is a new cap 3 construct. I could be wrong but I have been using cap since its infancy and cannot recall ever seeing this construct until the newer version. But- my memory is certainly fallible.
Answer: If you really need to use sudo you can always map the command like SSHKit.config.command_map[:rm] = 'sudo rm' which will make execute :rm into the proper rm command invoked with sudo. If your deploy user is in the sudoers things will work as expected.

Capistrano 3 sudo task


Using Infinite Scroll module with Views paging: Detrimental to Google SEO?

Question: I love using the Infinite Scroll module with Views. But does Google limit indexing to to only those first bunch of nodes which appear in the view?
I'm guessing that when using a regular pager, Google will dig deeper and index all subsequent pages in the view. But what does it do when ajax is used to move forward to the next batch of nodes as is the case with Infinite Scroll?
Answer: No it's not detrimental (well, not in the way you're thinking at least) - the standard pager links are hidden with infinite scroll, but still in the markup, so there's no problem from that perspective. Google will find and visit the subsequent pages as with a normal views pager.
The only question is whether Google apply some sort of penalty to the pages linked to from those hidden links. But that's something you'd need to get out of Google :)
Comment: The trick I've seen was to keep the links not simply hidden, but just below user's viewport. Other one was a link "view more", that's a link to next page and happens to turn on infinite scrolling if js is enabled. I guess both methods was implemented to make site work better with search engines.


How exactly is the value of $\frac{1}{y\sqrt{y^2+\frac{l^2}{4}}}$ as $y \gg l$ calculated?

Question: I am having trouble understanding if a particular calculation is or is not a limit calculation. I suspect it is not, but a particular set of notes from an MIT OCW physics course (problem starts on page 18, the limit is on page 20) seem to imply the calculation in question is a limit. The calculation is relatively simple, but I would really like to understand exactly what is being done to reach the result.
Note that I've slightly adapted the expressions to remove the parts that are specific to the physics domain (electromagnetism).
Consider the following expression for $E_p$:
$$E_p=\frac{1}{y\sqrt{y^2+\frac{l^2}{4}}}\tag{1}$$
I'd like to know what happens to this expression when $y$ is large relative to $l$.
The notes I am following state that "in the limit where $y \gg l$, the above expression reduces to the (point-charge) limit:"
$$E_p=\frac{1}{y^2}$$
As far as I can tell, if we take the limit of $(1)$ when $y \to \infty$ we get $0$.
I believe what is happening is that a linear approximation is being used in the denominator.
Here's what I came up with:
Rewrite $E_p$
$$E_p = \frac{1}{y\sqrt{y^2+\frac{l^2}{4}}}$$
$$=\frac{1}{y\sqrt{y^2(1+\frac{l^2}{4y^2})}}$$
$$=\frac{1}{y^2\sqrt{1+\frac{l^2}{4y^2}}}$$
Consider the term in the denominator $1+\frac{l^2}{4y^2}$
$$s=\frac{l}{2y}$$
$$1+(\frac{l}{2y})^2=1+s^2 = f(s)$$
$$y>>l \implies s \approx 0$$
I believe I can use a first order Taylor's expansion
$$\implies f(s) \approx f(0) +f'(0)s,\text{ near s=0}$$
$$\implies f(s) \approx 1$$
$$E_p \approx \frac{1}{y^2}$$
On the other hand I could have simply started by considering the limit of $E_p$ when $\frac{l}{y} \to 0$. In this case my question is: how does one calculate this limit? It's clear that the term in the square root goes to zero, but what should we say happens to the $y^2$ term?
Is this latter limit somehow connected or equivalent to the linear approximation I used, and was my calculation correct?
Answer: Assuming $y>0$, you can rewrite your expression as
$$
f(y)=\frac{1}{y^2}\Bigl(1+\frac{l^2}{4y^2}\Bigr)^{-1/2}
$$
and we can use the Taylor expansion:
$$
f(y)=\frac{1}{y^2}\Bigl(1-\frac{1}{2}\frac{l^2}{4y^2}+o(l^2/4y^2)\Bigr)
$$
If $y\gg l$, you may decide to neglect also the second term inside the parentheses to find $f(y)\approx 1/y^2$; otherwise you may say that
$$
f(y)\approx\frac{1}{y^2}-\frac{l^2}{8y^4}
$$
or use more terms if appropriate.
Comment: @evianpring It's the Taylor expansion of $(1+x)^{-1/2}$ at $0$, for $x=l^2/(2y^2)$
Comment: You are here :-))))))...
Comment: About which value of $y$ is the Taylor Series expansion done here?
Answer: (You asked how to take the limit as $l/y \rightarrow 0$.)
The "problem" with taking the limit as $l/y \rightarrow 0$ is that either $l$ is getting smaller, $y$ is getting larger, or both.  Since we want to have an expression with $y$s and not $l$s, we need to arrange for all appearances of "$l$" to be in the combination "$l/y$".  This is not initially the case.
Also, recall that $\sqrt{x^2} = |x|$ for any real $x$ (since the square root can only give you nonnegative values).
\begin{align*}
E_p &= \frac{1}{y\sqrt{y^2 + \frac{l^2}{4}}}  \\
    &= \frac{1}{y\sqrt{y^2 \left( 1 + \frac{l^2}{4y^2} \right)}}  \\
    &= \frac{1}{y|y|\sqrt{1 + \frac{l^2}{4y^2}}}
\end{align*}
Now, we have all instances of $l$ in $l/y$ combinations, so we can take the limit, leaving an expression in $y$s only.
$$  \lim_{l/y \rightarrow 0} \frac{1}{y|y|\sqrt{1 + \frac{l^2}{4y^2}}} = \frac{1}{y|y|\sqrt{1 + \frac{0^2}{4}}} = \frac{1}{y|y|}  \text{.}  $$
And, actually, we want $y|y|$ here -- the $E$-field should be pointing away from the origin above and below the $x$-axis, not always pointing upwards.  I don't see that we are working only on $y \geq 0$ and getting the lower half by reflection, so the usual explanation for why we get to confine our attention to $y \geq 0$ is missing.
Answer: By Taylor,
$$\sqrt{y^2+1}=y\sqrt{1+\frac1{y^2}}=y\left(1+\frac1{2y^2}+o(y^{-2})\right)=y+\frac1{2y}+o(y^{-1})=y+o(1).$$
The correction term is negligible for large $y$.


Porting sched.h to Windows

Question: I am going to port linux program into windows. but I do not know what is the equivalent to sched.h header in Windows. Anyone can help ?
Answer: libpthread is an implementation of POSIX threads for Windows.
It contains a sched.h compliant to that part of POSIX.
You can see its source here.
Comment: once I used that, there is unresolved external error due to the function sched_setscheduler().
Answer: You should use either MinGW or Cygwin as environment for the program, and then compile it newly with gcc from this toos. Then it runs under Windows. The difference is: API to the OS. MinGw and Cygwin offer an Unix-API running on Windows.
The other possibility is, but only for non-PC-Programming: I have created an own OSAL level (Operation System Adaption Level) and implement OS accesses both for Linux and Windows. I can run the Linux adaption with GCC or Cygwin under Windows, but can also run immediately with the WIndows-OSAL version. But this OSAL is for embedded programming, to adapt any embedded environment to the programs. It is not for typical PC programs. See https://vishia.org/emc

Porting sched.h to Windows


Onde fica a pasta com os fontes no servidor? Team Foundation Server

Question: Eu baixei e instalei no servidor da empresa o Team Foundation Server, subi um projeto nele através do Visual Studio e tudo certo.
Gostaria de saber em qual pasta fica o fonte do projeto no servidor?
Eu procurei e não achei.
https://www.visualstudio.com/pt-br/tfs/
Obrigado.
Comment: O que você está procurando exatamente e por quê?
Comment: Era para saber onde ficava os fontes para mapear em uma pasta que fazemos backup.
Comment: Você configurou o backup pela ferramenta no Team Foundation Server Administration Console? É a melhor maneira de ter bons backups, e não fazer pelo SQL Server! Qualquer coisa, posta outra pergunta!
Answer: Todos os fontes, definições de build, de release, os artefator (work items) ficam no servidor SQL Server, nada fica em pastas.
Essa é uma feature do TFS, ter tudo em banco de dados, de maneira integrada e com backup.
Comment: Obrigado @egomesbrandao.


MySQL: How to get percentage difference between rows based upon date

Question: ID     report_Date     total_points
---    -----------     -------------
123    2016-07-01      300
123    2016-07-02      600
333    2016-07-01      234
333    2016-07-02      434

Looking how to do a MySQL / SQL query that would find the percentage different of total_points based upon two dates provided.
So if I queried it for 2016-07-01 and 2016-07-02 it would give me:

ID
Percentage_Difference between the 2016-07-01 total_points and 2016-07-02 total_points

Results like:
ID    Percentage_Difference
---   ---------------------
123   100
333   85.47

Suggestions on the best way to handle?
Comment: What would the result look like?
Comment: Please edit your question accordingly
Comment: @Strawberry updated. thanks.
Comment: Always 2 dates?  could there be more? would you want difference on a line by line or just between the min/max?  ordered by report date?  too many unknowns to really address.
Comment: @xQbert ... the goal is to query a database around 1:00am every morning and look up and compare the results from the previous two dates. So if I queried it tomorrow (July 27) I would want it to compare the total_points from 2016-07-25 with 2016-07-26 and get the percentage difference.
Comment: And what query have you tried? You need to at least try and ask how to fix it. Otherwise i appears that you are just asking us to do free coding. By the way report_date hold just date?
Answer: SELECT x.id
     , ((y.total_points-x.total_points)/x.total_points) * 100 pct
  FROM my_table x
  JOIN my_table y
    ON y.id = x.id
   AND y.report_date = '2016-07-02'
 WHERE x.report_date = '2016-07-01';

x.report_date can be calculated from the y.report_date if you wish, but that requirement wasn't in your original question.
Note that 'ID' usually implies a surrogate PRIMARY KEY. In this instance, you appear to have a compound PRIMARY KEY.
Comment: Thank you! Works perfect. Also thank you so much for walking me through the submission process and making my request clearer.


Why does my computer repeatedly query a non-existent SRV record when I open "AD Users and Computers"?

Question: I have replaced my domain with example.com. I have 3 domain controllers: FARORE (primary), NAYRU, and DIN. The site name is DataCenter. In the course of trying to figure out why "AD Users and Computers" is unusable slow when accessed over the VPN I noticed these messages in wireshark:
No such name SRV _ldap._tcp.DIN.example.com SOA DIN.example.com
No such name SRV _ldap._tcp.DataCenter._sites.DIN.example.com SOA nayru.example.com

On my desktop at work it queries the domains in this order

_ldap._tcp.DataCenter._sites.DIN.example.com (fails)
_ldap._tcp.DIN.example.com (fails)
_ldap._tcp.DataCenter._sites.dc._msdcs.example.com (returns an SRV record)

On my laptop on the VPN it just queries the first two over and over. I have tested via nslookup that I can query the same SRV record at _ldap._tcp.DataCenter._sites.dc._msdcs.example.com from my laptop.
I'm mostly telling you about the VPN thing for background. My main question is: what are the two records ending in DIN.example.com? Should they exist? If not, why does AD Users and Computers query for them?
Answer: All these queries are related to Locating a Domain Controller with DNS-Based Discovery, and there's even quite some more variations documented. In short, in the first two records a client tries to locate a LDAP server, and in the third a domain controller (DC).
Something might still be wrong, as normally naming context in these queries is still example.com instead of DCNAME.example.com, whereas you have the following (it's normal that the first two don't exist):

_ldap._tcp.DataCenter._sites.DIN.example.com

DIN.example.com is the naming context N and
DataCenter is the site name Y in

To locate an LDAP server hosting NC N in site Y, the client machine
issues a DNS query for the SRV record _ldap._tcp.Y._sites.N,
constructed from the NC name (N) and the site name (Y).

_ldap._tcp.DIN.example.com; DIN.example.com = N in

To locate an LDAP server hosting NC N, the client machine issues a DNS
query for the SRV record _ldap._tcp.N, constructed from the NC name
(N).

_ldap._tcp.DataCenter._sites.dc._msdcs.example.com

example.com is the naming context N and
DataCenter is the site name Y in

To locate a DC hosting NC N in site Y, the client machine issues a DNS
query for the SRV record _ldap._tcp.Y._sites.dc._msdcs.N, constructed
from the NC name (N) and the site name (Y).

To debug this discovery process, reading Mitchell Grande's Domain Controller Selection could be a good start, and it also introduces some helpful commands:

echo %logonserver% - This shows the DC that was used to authenticate and log in the current user
nltest /dsgetsite - This shows the AD site that the current server has detected that it's in
nltest /dclist: (include the colon at the end) - This shows the list of DCs in the current domain, including which site each is in.

To address the slowness of the AD administration tools over VPN I'd suggest:

Check that the VPN subnet is added to the nearest site in AD Sites and Services.
I've experienced similar problems when someone had an OpenVPN client from an UTM appliance in use. It happened to be that this client was using an older OpenVPN TAP adapter driver, and replacing it with recent OpenVPN Connect solved this issue (among others).


Microsoft CA certificate templates expires sooner than expected

Question: The certificates my Microsoft CA is generating do not match the time period indicated in the template used. How can I resolve this?
I recently created a new certificate template for use on my Linux boxes on my Microsoft CA (2008 R2 Enterprise). This template is approved for server and client authentication purposes with a validity period of 10 years - the expected lifetime of our Linux boxes - and the subject name supplied in the request. I have checked both the intermediate and offline CA - both have more than 10 years of life listed. The certificates are exactly two years.
Is there some kind of hard limit I'm hitting here?
Comment: What validity lifetime are they getting instead of 10 years?
Comment: @ShaneMadden added.
Answer: By default ADCS is set to issue certs for a maximum of 2 years (regardless of template or request).
To change that just run the following two commands (modify as desired):
certutil -setreg CA\ValidityPeriod "Years"
certutil -setreg CA\ValidityPeriodUnits 10

Then restart certificate services:
net stop  certsvc
net start certsvc

Comment: Ugh.. thanks. Did that on the offline CA but likely forgot it on the intermediate.


Abels theorem/Integral Test to show divergence

Question: Hi is it possible to use Abel's Theorem for series to show the following:
If $\{x_{n}\}_{1}^{\infty}$ is a positive sequence such that $\lim\limits_{n \rightarrow \infty}x_{n} = 0$ and $\sum_{n=1}^{\infty}x_{n}$ diverges. Prove that the series $$\sum_{n=1}^{\infty}\frac{x_{n}}{x_{n}+1}$$
diverges. I have already proved this result by other means but am interested if you can use Abel's Theorem or the Integral Test to show this.  Thanks.
Answer: Since $\displaystyle \lim \limits_{n \to +\infty} x_{n} = 0$ and $(x_{n})_{n \in \mathbb{N}^{\ast}}$ is a sequence of positive real numbers, note that :
$$ \frac{x_n}{1+x_n} \, \mathop{\sim} \limits_{n \to +\infty} \, x_{n} $$
Therefore, the series $\displaystyle \sum_{n \in \mathbb{N}^{\ast}} \frac{x_n}{1+x_{n}}$ and $\displaystyle \sum_{n \in \mathbb{N}^{\ast}} x_{n}$ have the same behavior. Since $\displaystyle \sum_{n \in \mathbb{N}^{\ast}} x_{n}$ is divergent,$\displaystyle \sum_{n \in \mathbb{N}^{\ast}} \frac{x_n}{1+x_{n}}$ diverges too.
Comment: Thanks for your response. I am though specifically interested in knowing if we can use those two tests to show the divergence of the series.
Comment: I do not see how to apply the integral test here since it only concerns series of the form $\displaystyle \sum_{n \in \mathbb{N}} f(n)$ where $f$ is a decreasing, non-negative function. Here, we do not know $x_n$ explicitly. Therefore, $\displaystyle \sum_{n \in \mathbb{N}^{\ast}} \frac{x_n}{1+x_{n}}$ is not of the form $\displaystyle \sum_{n \in \mathbb{N}} f(n)$.
Comment: Yeah I think so too. Specifically since we can't say whether it is decreasing? On a side point does it follow necessarily that if $\{x_{n}\}$ is a positive sequence such that $\lim_{n \rightarrow \infty}x_{n} = 0$ then $\{x_{n}\}$ is a decreasing sequence?
Comment: Not necessarily. Consider $\displaystyle x_{n} = \frac{1+\sin(n)}{n}$. $x_{n}$ is positive and $\displaystyle \lim \limits_{n \to +\infty} x_{n} = 0$ but $(x_{n})$ is not decreasing.
Comment: @jibounet I don't think it has to be given explicitly. You have $f(n) := \frac{x_{n}}{1 + x_{n}}$. I think it's more important if it satisifes the conditions of as you stated non-negative and decreasing.
Comment: @JohnDoe : The function $f$ has to be defined on an interval $I$ of $\mathbb{R}$ and continuous, in order to integrate $f$ on bounded intervals of the form $[k,k+1]$. With your definition, $f$ is only defined on $\mathbb{N}$.
Comment: @jibounet Yeah I think you are right. Do you know what the generally used definition of Abel's theorem is? I find [this](http://en.wikipedia.org/wiki/Abel's_test).
Comment: @JohnDoe : The Abel theorem I know is this one : http://en.wikipedia.org/wiki/Abel%27s_theorem It is usually used to prove the convergence of power series (say, of convergence radius equal to $1$) at a point on the frontier of the convergence disc.
Comment: @jibounet Are you sure the integral test requires that $f$ is continuous? Check [this definition](http://en.wikipedia.org/wiki/Integral_test_for_convergence).
Comment: @JohnJack : the page says " non-negative function f defined on the unbounded interval [N, ∞), on which it is monotone decreasing"
Comment: @jibounet Do you think a simple proof like $\sum \frac{x_{n}}{x_{n}+1} = \sum 1 - \sum \frac{1}{x_{n}+1}$ and since $\sum 1 \rightarrow \infty$ and by the term test since the sequence $\frac{1}{x_{n}+1} \rightarrow \infty$ it follows then that $\sum \frac{x_{n}}{x_{n}+1}$ diverges. What do you think?
Comment: @JohnJack : It is not true that $\displaystyle \frac{1}{x_n + 1} \to +\infty$. Be careful, for example : let $u_{n} = 1$, $\displaystyle v_{n} = 1 - \frac{1}{n^2}$. Then $\displaystyle \sum_{n \in \mathbb{N}} u_{n}$ diverges and $\displaystyle \sum_{n \in \mathbb{N}} v_{n}$ diverges too but $\displaystyle \sum_{n \in \mathbb{N}} \big( u_{n} - v_{n} \big)$ converges.
Comment: @jibounet I don't understand the counterexample you mentioned previously which you defined as $x_{n} = \frac{1+ \sin(n)}{n}\cdot x_{n}$, would you mind motivating it? Thanks for all the assistance.
Comment: My example was : $x_{n} = \frac{1+\sin(n)}{n}$ (sorry for the dot after the fraction). It was just to show that $(x_n)$ is not necessarily decreasing.


Batch file ancorado

Question: Como consigo fazer que um batch fique ancorado em uma pasta para uma operação de backup em um pendrive na qual a letra da unidade sempre muda exemplo:
@echo off
mkdir ..\subs
move /y .\*.srt ..\subs
pause
exit

Comment: O que você quer dizer com ancorado?
Comment: não sei o porque mas quando vc simplesmente executa o bat o cmd executa partir da pasta de usuário `c:\users\joao` e não da pasta na qual se encontra o bat.
Answer: Você pode usar o comando pushd para alterar o diretório de trabalho, passe %~dp0 para indicar o diretório do arquivo .bat, veja um exemplo:
@echo off

echo Diretorio atual %cd%
echo Diretorio do script %~dp0

REM Altera o diretório atual de trabalho
pushd %~dp0

echo Diretorio atual %cd%
pause

Ao usar pushd %~dp0 você indica que o diretório atual é o local onde o arquivo está localizado.
Saída:

Diretorio atual C:\Users\<usuario>
Diretorio do script C:\Users\<usuario>\local\do\batch\
Diretorio atual C:\Users\<usuario>\local\do\batch\

Pressione qualquer tecla para continuar. . .

Answer: O pendrive tem que ter alguma marca para ser checada. Pode ser assim:
Você cria a pasta \subs no pendrive que vai usar para backup e coloca o código abaixo na pasta.
@echo off
if EXIST d:\subs\*.srt set PENDRIVE=D:&goto backup
if EXIST e:\subs\*.srt set PENDRIVE=E:&goto backup
if EXIST f:\subs\*.srt set PENDRIVE=F:&goto backup
if EXIST g:\subs\*.srt set PENDRIVE=G:&goto backup
rem Acrescente outros Drives se quiser
echo NENHUM PENDRIVE ENCONTRADO.
goto fim
:backup
move /y .\*.srt %PENDRIVE%\subs
:fim
pause

Batch file ancorado


Anonymous access to paid downloads using unique link

Question: Is anyone aware of a solution using Drupal Commerce (or alternatives) whereby I can have a product which can go through the following sequence:

anonymous user places in cart
anonymous user goes to checkout
payment is completed
a unique token/string is assigned to the email address provided in purchase
a url from which an anonymous user can download the purchased file is created and emailed to the address provided as well as displayed on checkout completion screen
after a defined period of time the link would expire
non-expired links could then be retrieved via a form by supplying email address to resend them

I can achieve most of the above with commerce_file but it seems that it requires logging in to the user account to access paid for downloads.
Seems like this would be a use case that would not be completely unique so hoping someone has an idea of how best to achieve this without having to roll my own solution.
Thanks in advance
Rich
Answer: Drupal commerce has a permission to complete the checkout process, that might be your issue there, check the permissions page (admin/people/permissions) and grant anonymous users the "access checkout" permission
Comment: This allows anonymous users to complete the checkout process but doesn't solve the problem of accessing the purchased file after completing the payment unfortunately.
Comment: Are you using commerce file 2.x with commerce license? check out https://www.drupal.org/node/1395488 and docs in https://www.drupal.org/node/2043917
Comment: Ok so I now get a link on the checkout complete page that allows the downloading of the file. Just need to work out how to have that link sent to the user in an email and remain valid for the duration of the licence... if that's possible
Comment: You've got rule events on checkout complete that can trigger emails, adding the link in there I guess can be accomplished by tokens. You can user commerce_bily to generate an invoice in case you want that too.
Comment: The checkout provided link only works for that session, I'm not sure of the exact mechanism by which this works but is looking increasingly like there is no clean solution for what I was hoping to be able to do.
Comment: You need to build custom parts, yes, but that doesn't mean is not a clean solution. I guess it depends on how you validate whether the token is valid or not, right? I'm afraid that from this distance (:)) I won't be able to help further.


HTML data attributes on the same page are not working for countdown script

Question: I used this script: http://keith-wood.name/countdown.html
I have more than one 'data-time' attributes on the same page like you see in the code.
The first data-time attribute is 17 nov and the second one gives data-time attribute 18 nov:

University Convocation

Mauris in erat justo. Nullam ac urna eu felis dapibus condimentum sit amet a augue. Sed non neque elit. Sed ut imperdiet nisie tiam pharetra, erat sed fermentum feugiat, velit mauris egestas quam.

John Doe

Saturday 10:00 AM

University Convocation

Mauris in erat justo. Nullam ac urna eu felis dapibus condimentum sit amet a augue. Sed non neque elit. Sed ut imperdiet nisie tiam pharetra, erat sed fermentum feugiat, velit mauris egestas quam.

John Doe

Saturday 10:00 AM

But now, the javascript code:
    if($('.defaultCountdown').length){
        var date1 = $('#defaultCountdown').data('time');
        var date = new Date(date1);
        $('.defaultCountdown').countdown({ until: date});
    }

Now i have a problem that the timer is showing the same countdown. Maybe because the id is the same on the 2 blocks?
I thought that there was something wrong with my javascript and i searched for something else but its also not working. I don't know of this is in the right direction:
if($('.defaultCountdown').length){
$('[data-time]').each(function() {
   var $this = $('.defaultCountdown'), finalDate = $(this).data('time');
   $this.countdown(finalDate, function(event) {

     var date = new Date(finalDate);
     $('.defaultCountdown').countdown({ until: date});
   });
});
}

Answer: I think this will work:
$('[data-time]').each(function() {
    var $this = $(this), finalDate = new Date($(this).data('time'));
    $this.countdown({ until: finalDate});
    // or all in one line
    // $(this).countdown({ until: new Date($(this).data('time'))});
});

I think that the problem with what you've tried is that you were using:
$('.defaultCountdown').countdown({ until: date});

Instead of:
$this.countdown({ until: date});

You were setting the countdown to all the elements with class defautlCountdown instead of setting it to the current element $this.
Comment: The timer is the same on all elements now but its a wrong countdown. So if i switch on the first block the date-time to Nov 18 and the second date-time to Nov 20 it is the same countdown what's is wrong and from today it gives 34 minutes and not the days. So it's not good. Any other solution? I don't know of the javascript is correct here.
Comment: @Brecht27 I've changed my answer to convert the `date-time` `String` value to a `Date` object. Give it a try now to see if it works.
Comment: Thats it! Thanks for helping me out here! +1


What is the common ingredients of a machine learning algorithm?

Question: considered KNN, it seems that a machine learning algorithm does not have to have weights, a training process, loss function or optimization, so, what is the common ingredients of a machine learning algorithm?
it seems that what a machine learning algorithm does have to have includes a training set, prediction functionality, distance metric, what else?
A lot of machine learning books/tutorials use KNN as the 1st example of supervised machine learning without telling the keys we can get from KNN, So, I am trying to figure it out.
Answer: You might want to check the definition of "supervised" & "unsupervised" statistical (machine) learning.
And most importantly check & understand the methods you want to apply.
I wouldn't generalize "machine learning algorithm".
For your example.
KNN is an extremely simple nonparametric method.
It doesn't have to be trained. There is no parameter!.
It just checks the k-nearest neighbor.
You clearly have to find the best "k" though. So you can test different k, calculate e.g. RSS and chose the best k. Guess you can define that as a loss-function :-)
Comment: I would argue that a KNN classifier definitely has parameters, in fact an unbounded number: it needs to save all of its training data.
Comment: Does the training change "saving the training data"?
The data is known, hence not a parameter to be estimated.
I would argue that this is just required to run KNN. But there is no training involved but computational resources. It is nonparametric per definition I would say. The only unknown hyperparameter is k. And finding a reasonable one is described above.
Comment: Thanks for your answer. In the context of supervised machine learning, What do KNN and other supervised machine learning algorithms both have in common?
Comment: I would say the task :-).
Classification or regression (categorical or numerical response).
For KNN it doesnt make sense to split your data in a training, test, validation set as it just decreases the performance.
As said, there is no training required as kNN is nonparametric.
But I am not sure if this answer helps, or if there is a good answer to that question...
Comment: Your answer is very helpful. A lot of machine learning books/tutorials use KNN as the 1st example of supervised machine learning without telling the keys we can get from KNN, So, I am trying to figure it out.


Solução para while em estrutura HTML

Question: Alguém tem uma solução simples para loop while em PHP para a seguinte estrutura HTML?
Basicamente quero que a cada 3 divs haja um
 separando-as para que o slide possa funcionar corretamente, já que cada
 funciona como "nova página". A página modelo, se analisarem o código-fonte, está bem completa e de fácil entendimento.
Código PHP
<?php
$fotosEmpresa = $conn->prepare("SELECT * FROM imgs_global WHERE TipoImg = ? ORDER BY rand()");
$fotosEmpresa->execute(array("QuemSomos"));
if($fotosEmpresa->rowCount() > 0): ?>

        <?php while($rowFotoEmpresa = $fotosEmpresa->fetch(PDO::FETCH_OBJ)): ?>

                        <a href="administracao/imagens/quemsomos/imgG/<?php echo $rowFotoEmpresa->NomeImg; ?>" class="zoom">
                            <img alt="" src="administracao/imagens/quemsomos/<?php echo $rowFotoEmpresa->NomeImg; ?>">

        <?php endwhile; ?>

<?php endif; ?>

Estrutura em HTML

John Smith

                    Webdesigner

Mike Smith

                    Founder of a Company

Donald Smith

                    Development

John Smith

                    Webdesigner

Mike Smith

                    Founder of a Company

Donald Smith

                    Development

Vimos que a cada
 que se repete uma nova "página" é gerada para o slider, ou seja, na estrutura ela precisa tratar que a cada um número X de registros ele gere um
, algo do tipo.
Comment: Esclareça seu problema específico ou acrescente outros detalhes para destacar exatamente o que precisa. Do modo como está escrito aqui, é difícil saber exatamente o que você está perguntando. Consulte a página Como perguntar para obter ajuda no esclarecimento desta pergunta.
Comment: De onde vem o conteudo dessas `h2` e `span`? as imagens são todas iguais, esse conteudo também é diferente a cada `team-post`? (o seu link não funciona para mim...)
Comment: Basicamente o que ele quer é, olhando a estrutura acima, que a cada 3 divs elas fiquem separadas por uma li para poder chegar no resultado do slide que ele colocou como modelo.
Comment: Aí se encaixaria em outro motivo para suspender a pergunta, por ser baseada em opiniões.
Comment: Posta teu código(php) que você tentou, e assim, poderemos te auxiliar.
Assim parece mais uma pergunta do tipo, "faz pra mim".
Comment: Sim, entendemos o que ele quer, o problema é exatamente este.
Além que de querer uma resposta pronta, sem ter trabalho, não postou nem os detalhes para podermos ajudar a dar uma resposta, a sua resposta por exemplo, seria completa se ele informasse corretamente, os dados do banco, como está o php dele, etc.
O SOpt ou SOen, são totalmente contra fornecer trabalho pronto, não somos uma comunidade de programação gratuita.
Comment: @MarceloAymone concordo contigo, ta muito vago a pergunta.
Comment: Eu tenho o código php, apenas não consigo mais editar a pergunta pois colocaram em suspensão. O que quero é muito simples e o @DiegoVieira entendeu corretamente, a estrutura html é um modelo mas obviamente em php as imagens e textos vêm do banco. Acredito que a pergunta foi muito simples e de fácil entendimento mas, tenho o código php, e não foi uma pergunta do tipo "faz pra mim", foi do tipo, colaborem com sugestões por favor.
Answer: Estou mantendo a mesma estrutura de código que você usou, onde o php e html estão misturados, para resolver essa questão você pode usar o operador % nessa situação ele vai verificar se já foram processados 3 registros, para isso ele vai dividir a variável $i por 3 e verificar se o resto é 0, quando o resto é 0 significa que o número é múltiplo, pois conseguiu executar uma divisão exata, no seu caso especifico. Isso vai acontecer a cada três registros ou quanto o contador for 0 (0 dividido por qualquer número é 0, portanto divisão exata).
<?php

    $i=0; // Essa variável será usada como contador, vai permitir saber quantos registros foram processados
?>

            <?php
                while($rowFotoEmpresa = $fotosEmpresa->fetch(PDO::FETCH_OBJ)){

                // Essa é a parte responsável por fazer com que a cada 3 registros gere um novo li, o zero também é um múltiplo, mas temos que remove-lo do contrário ele irá criar um li sem nenhum registro
                if($i % 3 == 0 && $i != 0){
            ?>

            <?php
                } // Essa parte é responsável por encerrar a verificação do contador
                $i++; // Aqui é incrementado o contador, para informar que um novo registro foi processado
            ?>

                        <a href="administracao/imagens/quemsomos/imgG/<?php echo $rowFotoEmpresa->NomeImg; ?>" class="zoom">
                            <img alt="" src="administracao/imagens/quemsomos/<?php echo $rowFotoEmpresa->NomeImg; ?>">

        <?php } ?>

A cada 3 registros processados ele vai incluir uma tag para fechar a li atual e irá abrir uma nova tag li. Qualquer dúvida deixa um comentário.

Uma dica que não tem a ver diretamente com o post, tente começar a
  separar as camadas, separar o php do HTML, usar MVC. Existem
  frameworks para Template como o twig e até classes com php puro
  para quem quer usar apenas código nativo, isso torna o código mais
  limpo, mais fácil de ler e de dar manutenção além de ser uma forma
  mais padronizada de trabalhar. Se quiser ver mais a fundo sobre
  frameworks veja o Symfony, Zend e para ORM o Doctrine, existem outros, esses são apenas alguns exemplos
Comment: Perfeito, não havia pensado nisto tão simples e prático. Obrigado. o `;` no fechamento do `while` é algum erro? Testei com/sem ele, acaba por não influenciar em nada.
Comment: @TiagoBoeing  nesse caso o ; não é necessário, foi um erro na hora de transcrever o código. pode ficar apenas
Comment: Sem problemas, até ia editar a resposta retirando o `;` mas achei que poderia ter algum motivo especial. Vou dar uma olhada nessa sua sugestão, achei interessante.

Solução para while em estrutura HTML


Generating an equivalence relation out of another relation?

Question: I'm preparing for an exam in discrete mathematics and found the following question in my course materials.
Let c be the equivalence relation generated by $\{(6,3), (0,2), (2,1), (4,9), (8,3), (1,7)\}$ on [0,9]. Determine $[7]_c$.
I know how to determine $[7]_c$ once I have the equivalence relation. But how do I get the equivalence relation? What does this generated mean? I don't get it. Could you please give me an hint?
Comment: I suppose a sensible way to interpret it would be this: all given pairs are pairs of your relation, and then you add all other pairs required to make it an equivalence relation.
Comment: That sounds too simple
Comment: Well, that's exactly what we do when we generate topologic spaces. Not everything has to be hard, you know? :) The equivalence relation generated by any relation is the smallest equivalence containing it...
Comment: For example, since $(6,3)$ is there, then you must add $(3,6), (3,3), (6,6)$. It might help to draw a graph (and transitive closure thereof) to see the equivalence classes.
Comment: And since $(8, 3)$ is also there, you must add $(6, 8)$, and all the other relevant relations...
Answer: If one is given a subset  $S \subset A \times A$, then there is a 'smallest'
equivalence relation $\sim$ such that if $(a,b) \in S$, then $a \sim b$. The
resulting equivalence relation is called the equivalence relation generated by $S$.
By smallest, I mean finest.
First, the relation  $\sim_* $ defined by $a \sim_* b$ iff $a,b \in A$ is
an equivalence class that is compatible with $S$.
Now suppose $E=\{ \sim_\alpha\}_\alpha$ is a collection of equivalence relations on $A \times A$, then we can define the
relation $\sim_E$ by $a \sim_E  b$ iff $a \sim_\alpha b$ for all $\alpha$.
(Note that $\sim_* \in E$ so $E$ is non empty.)
It is easy to establish that this is an equivalence relation.
So, let $E = \{ \sim | \sim \text{ is compatible with } S \}$ and let $\sim_E$
be the relation as defined above. Then $\sim_E$ is the smallest or finest equivalence relation that is compatible with $S$.
One way of generating the equivalence relation for a finite $A$ is to start with a graph that has vertices $A$ and add an undirected edge for each pair
$(a,b) \in S$. Now compute the transitive closure of the graph and read off the equivalence classes (the connected subsets).
So, one starts with
\begin{eqnarray}
(6,3), (8,3) & &\\
(0,2), (2,1), (1,7)& & \\
(4,9) & &
\end{eqnarray}
from which we can read off the equivalence classes $\{ 3,8,6 \}$,
$\{ 0,1,2,7 \}$, $\{4,9\}$.
Comment: Just draw dots for each number $0,1,2,3,4,6,7,8,9$. Connect two dots if they are in the original list. Then group all the connected collections together. For example, there is a line joining $6,3$ and $8,3$ (and no others connected to all three dots) so that means $3,6,8$ lie in one class.
Comment: Thank you very much for your detailed answer. But I don't see how to draw the graph. In the above example, is (0,2) the root? Sorry i'm really new to this. Could you please provide another example of a graph? This method sounds very interesting.
Answer: Hint:
$$
(7\sim 1) \land (1 \sim 2) \Rightarrow 7 \sim 2
$$
$$
(7\sim 2) \land (2 \sim 0) \Rightarrow 7 \sim 0
$$
so:$[7]_C=\{0,1,2,7\}$


Is there a way to trigger a callback when an object creates or modifies a key/value in JavaScript?

Question: I am trying to figure out how to create an object in JavaScript that will trigger events on creation and change of arbitrary key/values. Here is some psuedocode:
var User = function () {
    var user = {};

    function keyAdded() { /* trigger an event */ }
    function keyChanged() { /* trigger an event */ }

    return user;
},
u = new User();

u.test = "testing"; // I want this to trigger an event (keyAdded)
u.test = "more testing"; // I want this to trigger another event (keyChanged)

I am stuck. Any ideas?
Comment: Someday browsers may support: http://stackoverflow.com/questions/1063813/listener-for-property-value-changes-in-a-javascript-object
Comment: @epascarello, I think [ECMAScript Harmony Proxies](http://stackoverflow.com/questions/2266789/is-there-an-equivalent-of-the-nosuchmethod-feature-for-properties-or-a-way-t/3757676#3757676) will be implemented before `watch`,  which isn't part of any *draft* standard.
Answer: function User() {
    this.assign = function(key, value) {
        if ( !this.hasOwnProperty(key) ) {
            this[key] = value;
            alert("key added");
        } else {
            this[key] = value;
            alert("key changed");
        }
    };
    return this;
}

u = new User();

u.assign("test", "testing"); // will alert "key added"
u.assign("test", "more testing"); // will alert "key changed"

Answer: You should define a getter and setter on User.
That way, accessing properties on that object will fire those functions.
Check out the Mozilla documentation about them.


Python: required kwarg, which exception to raise?

Question: One way to ensure that a method is called with a particular kwarg would be like:
def mymethod(self, *args, **kwargs):
    assert "required_field" in kwargs

Raising an AssertionError doesn't seem like the most appropriate thing to do. Is there an agreed upon builtin exception to handle this with a nice error message?
More info: there are 3rd-party subclassing issues where *args and **kwargs kinda' need to be passed so making "required_field" a positional argument is not really a good option.
Comment: I think the standard thing is to not make it a 'default argument'.
Comment: there are already positional arguments that I don't want to mess with.
Comment: More generally, there are also cases were kwargs can may accept numerous keys with some being required only if specific conditions are met with respect to the presence or values of other key word arguments.
Answer: >>> def foo(bar): pass
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'bar'

I'd just go with TypeError..
Answer: +1 for TypeError. This is what Python 3 raises for required keyword-only arguments:
>>> def foo(*, x):
...     pass
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() needs keyword-only argument x
>>> foo(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 positional arguments (1 given)
>>> foo(x=2)

(TypeError suggestion was already given (and accepted); I wrote this answer to mention this Python 3 feature).
Comment: Mentioning the Python 3 keyword-only arguments is extremely helpful here; people might be coming to this question thinking they should do the exception handling themselves when the language itself supports required keyword arguments (unless they are unfortunate enough to be stuck with Python 2, of course).
Comment: I ended up here googling for the syntax of required kwargs, so +1 from me as well.
Answer: The standard library seems to like to raise TypeError when it gets the wrong number of arguments.  That's essentially your problem, so I'd raise that.
That said, **kwargs essentially fill in for default arguments most of the time, so having a required default argument seems a little surprising/confusing.
Note that python will happily let you call positional arguments by keyword:
>>> def foo(a, b):
...     print a, b
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

but I suppose that then they all have to be referenced by keyword (foo(2, a=2) doesn't work) which you may not want.
Comment: "`**kwargs` is essentially fill in for default arguments most of the time". Not really. That's one use, but `**kwargs` has several other important uses: 1) in superclasses where subclasses may want different behavior, 2) when you have a long argument list where you don't want the client to have to memorize the order of the arguments `**kwargs` avoids a lot of clutter. There are no doubt others, but those are the first ones that come to mind. The former (superclass) was what ended up leading me to this thread.
Answer: I think KeyError would be the most appropriate, because **kwargs is a dict.
>>> def foo(**kwargs):
...  print kwargs['abc']
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
KeyError: 'abc'

If the field is actually required, you could check for it
try:
  kwargs['required']
except KeyError:
  raise KeyError('required is a Required Argument')

Comment: `KeyError` usually applies directly to a data structure, whereas the OP wants to notify a misuse of the function signature.
Answer: If you need it to be a required keyword, do something like:
def mymethod(self,myrequired=None):
    if myrequired==None:
        #raise error
    #do other stuff down here

You shouldnt really need to pull it from kwargs.
Comment: just add `*args,**kwargs` :)


Shift a graph's isomorphic complement vertices to make it look like its original graph

Question: So, I was searching for an algorithm to see if you are given given a self-complementary graph(it's isomorphic), how can we shift the vertices of its complement to arrange it to look like the original graph?
Eg. below:
First graph:

Its complementary graph:

After moving the second graph's vertices a bit, you get the same image as the first graph:

Is there an algorithm for this process? If so can you point me in the right direction please? I have searched everywhere and I can't find any.
Thank you.
Comment: Terminology: the second graph is not "the first's graph self-complementary graph", just the first graph's *complement*, which happens to be isomorphic to the original graph because because the original graph is self-complementary.
Comment: You probably want to ask: "If you are given a self-complementary graph, how can we shift the vertices of its complement to arrange it to look like the original graph?". A broader similar question is "If you are given two isomorphic graphs, how can we shift the vertices of one to arrange it to look like the other?"
Comment: @MishaLavrov exactly that, how can this be achieved?
Comment: @bof so do you have any idea on the algorithm to find the right permutation?
Comment: No, I have no idea. Trial and error?
Comment: What I don't understand here is _why_ you want to do this? It seems like you want the layout (coordinates) of the first graph given the second one. However, you already have the first! Are you animating the process, or...
Comment: @gilleain it's a small part of a bigger problem that's being part of a contest. I've figured the algorithm for the rest of the problem, but the last part of the problem basically comes down to this permutation that I don't know how to generate.
Comment: Which contest? Is it still running, or is it over?
Comment: @DanielFischer it's over, I was just curious as I couldn't complete this part of the problem. I just couldn't think of an algorithm to check if a permutation matches its original graph.
Answer: If you just want to check for an isomorphism between the graphs, it should be as simple as:

Say the permutation is $\phi$ = [1, 4, 2, 5, 3]
Permute the edges of the complementary graph by $\phi$
Compare these to the original

So, for your example, we have an edge list of (1:3, 1:4, 2:4, 2:5, 3:5) and these are permuted as (1:5, 1:2, 2:3, 3:4, 4:5) - which is the same as the original.
To permute an edge with $\phi$, just consider it as a mapping that you are reversing. So for edge (1:3),  $\phi$[1] = 1, and $\phi$[3] = 2 which gives you 1:2. In other words, the permutation gives for each vertex (1 to 5) in the original the corresponding vertex in the complementary graph.
I'm aware that there is a more mathematical way to express this as the inverse of the permutation ($\phi^{-1}$ = [1, 3, 5, 2, 4]) where you just apply it as a function. That might be more straightforward to use.
Comment: How exactly do you permute (1:3, 1:4, 2:4, 2:5, 3:5) with $ϕ$ to give you (1:5, 1:2, 2:3, 3:4, 4:5) ? I can't seem to spot how to do that calculation.
Comment: Sorry, I think it was a bit of a roundabout route. I learned about this things a bit pragmatically, rather than mathmatically/formally so my explanation may be a bit off.
Comment: It's a really good explanation, it might work. Now the only thing remains to figure out how to generate $ϕ$ for large graphs, if you have 20+ vertices, doing backtracking on all permutation and for every permutation doing what you discribed it's not feasible. Thank you!


How to create a content tagging system for two models in Django?

Question: Edited my question to make it more clear. And I am sorry if what i'm asking is obvious or easy to solve, I am just starting out.
Hello, I am developing a website which has 2 models for the content: Article and Comic. Now I want a system that allows me to tag Articles and Comics with certain keywords. These keywords can then be used to retrieve a list of objects from both the models and display them.
At first, I set up the system as follows:
class Article(models.Model):
    .....
class Comic(models.Model):
    .....
class Tag(models.Model):
    tag = models.CharField(max_length = 25)
    article = models.ForeignKey(Article)
    comic = models.ForeignKey(Comic)

However, this did not work out.
Then I tried implementing 2 different tag models for the 2 different models: ArticleTag and ComicTag, in the following way:
class Article(models.Model):
   .....
class ArticleTag(models.Model):
   tag = models.CharField(max_length = 25)
   article = models.ForeignKey(Article)

class Comic(models.Model):
    .....
class ComicTag(models.Model):
    tag = models.CharField(max_length = 25)
    comic = models.ForeignKey(Comic)

This also did not work, as I was able to get a list of tags of an article, but I could not get a list of articles that had the same tag. And also it was using 2 different tag models so that was also not preferable.
A user suggested a ManyToManyField based on the previous information I had provided. However, how would this exactly work?
Now, what is the best way to create a content tagging system using Django? It should preferably work with just 3 models: Article, Comic and Tag, not 4 like I tried. In conclusion, I want a system that lets me get a list of objects from 2 models using one single tag. So, I would really appreciate help of any kind as I am an amateur programming (pretty obvious) and I am completely stumped by this problem.
Answer: You could use a ManyToManyField.
Basically something like the following. It's more intuitive if you change the name of ArticleTag.tag to ArticleTag.name. I've also added a related_name field to the M2M relationship so you can retrieve an article based on its tags using Article.objects.filter(tags__name="tag_name_here"). In the reverse direction, you could get all the tags for an article using ArticleTag.objects.filter(article__title="article_name_here").
class Article(models.Model):
    title = models.CharField(max_length=140)
    .....
class ArticleTag(models.Model):
    name = models.CharField(max_length = 25)
    articles = models.ManyToManyField(Article, related_name="tags")

[EDIT based on your updated question]
Based on your update, you could do this:
class Article(models.Model):
   .....

class Comic(models.Model):
    .....

class Tag(models.Model):
    tag = models.CharField(max_length = 25)
    articles = models.ManyToManyField(
        Article,
        related_name="tags",
        blank=True,
        null=True
    )
    comics = models.ManyToManyField(
        Comic,
        related_name="tags",
        blank=True,
        null=True
    )

This way an Article/Comic can have many different tags, and any one tag can tag many different articles/comics. The blank=True, null=True means that you don't have to have an associated comic/article with a given tag, i.e., one tag could happen tag only comics but no articles.
To get a list of articles with the same tag:
Article.objects.filter(tags__name="your_tag_name")

Comment: Wait, won't Article.objects.filter(tags__name = 'tag_name_here') get me a list of articles with that tag?
Comment: @TahmidKhanNafee you're correct - updated my answer, thanks!
Comment: Oh now it makes sense, anyway, I updated the question with more information as the previous one was pretty lackluster. However, thanks for this answer.
Comment: @TahmidKhanNafee updated - just FYI generally you should post a new question if your edit makes it that much different - you'll get more traffic for it. Hope this helps!
Comment: Oh damn, I thought it was against the rule or something. Oh and thank you again for the updated answer, I will try it out.
Comment: It works! Although I did add the manytomanyfield relationship to both Article and Comic model separately instead of Tag. It made it much easier to manage the content from admin. Thanks a lot.
Comment: ideally that is how it needs to be, as in it makes more sense to think articles/Comics containing tags.


simplifying creating multiple world raster in r

Question: can I simplify this using a loop? I need to make over 50 of them and I am currently doing it manually (e.g., r, r1, r2, r3, r4 ...).
Is there a way I can do all 50 in a simpler code?
r   <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)
r1  <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)
r2  <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)

Comment: Is it help? https://www.w3schools.com/r/r_for_loop.asp
Answer: You can map the function assign on a sequence:
library(raster)
library(purrr)

my_raster <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)

seq(50) %>%
  walk(~ assign(x = paste0("r", .x), my_raster, envir = globalenv()))

Please keep in mind that this will mess up your global environment quite much. It is much cleaner to group the rasters into one list:
my_rasters <-
  seq(50) %>%
  map(~ paste0("my_raster_", .x)) %>%
  set_names() %>%
  map(~my_raster)

# access one raster
my_rasters$my_raster_23

Comment: what do you mean by ```list```? what does envir = globalenv() do? I tried to look it up but there is this discussion that says not to use it? https://stackoverflow.com/questions/9726705/assign-multiple-objects-to-globalenv-from-within-a-function
Comment: Values are stored in buckets called environments. If you need to access them from everywhere without defining the env explicitly, you need to create them in the global env. I added a statement about messyness in my answer. Creating global vars will have side effects so things get complicated.
Comment: how do I group them by ```list```? is this different?
Comment: Use `map` instead of `walk`: `my_rasters <- seq(50) %>% map(~ my_raster)` Note that the function `rep`  only works for S3 objects.
Comment: is it possible to rename them so the output is my_raster1, my_raster_2 etc. this comes as [[1]]
Comment: @L55 Yes: I updated my answer accordingly.


Wagtail: Is there a way to get all pages a snippet is used on?

Question: I am using Wagtail 1.7 and need to retrieve a list of all the pages a snippet is used on. I looked at get_usage, get_usage_url but that didn't seem to be quite what I needed. I am using the sites framework with wagtail and need show different search results based on which site you are on (using elasticsearch). The snippets are the only thing fouling that up at the moment.
Answer: get_usage uses a generic utils function called get_object_usage
https://github.com/wagtail/wagtail/blob/master/wagtail/admin/utils.py#L55
This function

"Returns a queryset of pages that link to a particular object"

As this is just a queryset, you could then append a filter using the in_site filter as per docs.
Example of using this in your serve method
my_model_instance = my_snippets.objects.all().first() # depends on how you want to get your snippet
query = 'foo'
current_site = request.site # or get this inside your search function
usage_pages = my_model_instance.get_usage() # this is a queryset
usage_pages_for_site = usage_pages.in_site(current_site)
usage_pages_for_site.search(query) # remember search must be done last on a queryset because it does not return another queryset. This searches the pages, not the snippets.

Example of using this inside a template tag
Create a new assignment tag for use inside your templates. eg. /myapp/templatetags/snippet_tags.py
This assignment tag is provided a snippet and because takes_context is set to true on the register.assignment_tag decorator we also get the current context from wherever this tag is used. We can then get the current site from the context and pass that into our queryset that is returned from get_usage.
from django import template

register = template.Library()

@register.assignment_tag(takes_context=True)
def snippet_usage_in_current_site(context, snippet):
    """Return queryset of pages in current site that use the provided snippet."""
    current_site = context['request'].site
    pages_in_current_site = snippet.get_usage().in_site(current_site)
    return pages_in_current_site

Load the templatetags file and use in your template eg. myapp/templates/search_results.html
{% load snippet_tags %}

    {% snippet_usage_in_current_site my_snippet as snippet_pages %}

      {% for linked_page in snippet_pages %}

{{ linked_page }}

      {% endfor %}

This will generate a list of pages used by my_snippet on the current site only. Where my_snippet is whatever snippet you want to show the relevant results for.
Comment: Maybe this is a fluke of the site I am working on but all snippets return an empty array for this get_usage().
Comment: To clarify you are suggesting to call this on the snippet model, right?
Comment: I have updated the answer with a bit more clarity and a better example for how to use this inside a template tag. Hope that helps.
Comment: Hey thanks so much for all this and I hope it helps people with similar questions in the future. I think something else is going on since I can't get anything but an empty array from get usage.
Comment: Are you linking your snippets with Streamfields or via Snipper Chooser Panels? Snippets used in Streamfields will not show up using get_usage, but there is a WIP Pull Request that will likely solve that in a future version: https://github.com/wagtail/wagtail/pull/3954


Is the emmeans R package performing causal inference G-computation?

Question: So I am trying to get an understanding of causal inference and how it differs from the usual contrasts. I regularly use the emmeans package in R, and I am wondering when the function emmeans() mentions it has averaged over the covariates is this essentially performing G-computation? At least for regular OLS or identity link GLM models it seems like that
One possible difference I see is that G-computation takes place on the response scale, so I wonder if you use the transform argument in emmeans when working with GLMs with a non-identity link, then would it be performing the G-computation? It seems like it does the delta method to convert the SEs to the response scale from the link scale.
And then if I modeled the treatment probability, inverted it, and used it as a covariate in a model, and then used emmeans -- would this be doubly robust estimation?
As my reference I am using the book here https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/ pages 163-167.
Edit 09/07/22: Anyone wondering about the connection --it is written about here https://vincentarelbundock.github.io/marginaleffects/articles/gformula.html. The marginaleffects package can do this
Comment: There is nothing inherently causal about the output of a linear, generalized linear, mixed or any other kind of model. The thing that makes an estimate causal comes from assumptions about the setting that are external to the statistical model. This means that there is no way that R (or anything else) could do causal inference without you knowing about it.
Comment: As emmeans developer, I do understand what it does but am not an expert on causal inference so not so sure of that. It does seem that you might want to look at the cov.reduce argument (see help for ref_grid), which does provide some flexibility in setting covariates at their predicted values from another model. See also the "framing" example in the vignettes. I have tried to document things pretty clearly and the vignettes n general should help.
Comment: I don't really understand what `emmeans` does, but I was able to replicate g-computation results for linear models (you need to specify `type = "prop"` in the call to `contrasts()`, though). For logistic regression models, I could not get the results to agree. I would recommend not using `emmeans` for g-computation. The `stdReg` package does a good job for most purposes and provides correct standard errors.
Answer: Re-reading your question, my understanding is that you are asking if emmeans() does G-computation as part of what it ordinarily does. And based on my very limited understanding of causal models and G-computation, I would say the answer is NO. That is simply because we don't treat covariates in any special way. For a numerical covariate, the default action is to compute its mean and use that as a reference value for all subsequent estimates, regardless of whether it is regarded as a mediator or not. We just treat it as a direct effect.
There may be some options in emmeans() that do allow the user to treat covariates in a different way. For example, we can fit a model y ~ treat + M where treat is a treatment and M is a mediator. Then suppose we subsequently do
emmeans(model, "treat", cov.reduce = M ~ treat)

This instructs emmeans to not use the average value of M, but rather to use lm() to fit the model M ~ treat (with the same dataset) and use its predictions for the value of M. In that way, the reference value of M is different for each treatment level. This is equivalent to creating a covariate C that is equal to the residuals of the M ~ treat model, fitting the model y ~ treat + C, and using emmeans() in the ordinary way by using C's mean (which is zero) as the reference value. Perhaps this is similar to what G-computation does -- I am not sure, but perhaps someone else can shed some light on this. But at least it does something special with covariates thought to be mediators, and that seems more akin to what is needed in causal inference.
Addendum
A comment to this answer suggests doing something like emmeans(model, "treat", cov.reduce = FALSE, weights = "prop") but that this is very inefficient as it creates a huge reference grid. I believe that the following may do the same thing:
emmeans(model, "treat", submodel = ~ treat)

The above puts a linear constraint on the estimates whereby all the effects other than those of treat are replaced by predictions of those effects from the given submodel. See vignette("xplanations", "emmeans") for the gory details. But in words, what happens is that we are trying to obtain the predictions we would have obtained from the submodel, while still accounting for the reduction in error variance achieved by including the covariate in the model. I think this in fact does relate to some causal-inference methods, but I lack the depth of knowledge in that are to be sure.
In the case of mixed models and generalized linear models, the submodel constraint will not be quite the same as would be obtained by fitting the submodel with the same method. To accomplish this (or at least get closer), one can use a new feature in version 1.6.0 of emmeans to bring in covariate predictions from an external model. Suppose model was fitted using something like model <- lmer(y ~ M + treat + (1|SUBJ), ...)
Mmod <- lmer(M ~ treat + (1|SUBJ, ...)
Mpred <- function(grid)
             list(M = predict(Mmod, newdata = grid, re.form = ~ 0))

emmeans(model, "treat", cov.reduce = extern ~ Mpred)

This is like the original cov.reduce = M ~ treat, except it uses Mmod instead of lm(M ~ treat) to do the predictions of M.
Comment: @Vattaka Please see my addendum. I had to make a couple of corrections to the external cov.reduce part as there were errors
Comment: @Vattaka FYI I have been looking at this recently and have added a `counterfactuals` argument to `emmeans` (actually `ref_grid`) whereby counterfactual predictions are computed for the factors named there. I think that is a step forward in the kind of analysis you are asking about. It's only on GitHub now but will be included in the next CRAN update.
Comment: Thanks, based on the causal inf reference above, page 164, it seems like the G computation (also called standardization) method in the binary treatment case essentially makes 2 additional copies of the dataset but deletes the Ys and changes the treatment to all 0 and all 1 respectively. Then it fits the model on the original dataset and gets predictions on the 2 copies, and the predictions are then averaged and then a difference is computed.

So it seems like G-comp is giving `E(Y|T=1,X) - E(Y|T=0,X)` which looks very similar to a contrast to me, with covariates X averaged out.
Comment: So I found out that using the `cov.keep` argument in `ref_grid` and keeping the continuous variables at their value, then using `weights=proportional` in the call to `emmeans(grid,pairwise~T,weights=proportional)` seems to give the effect estimate as G-comp. But it can be computationally intensive because looks like the ref grid keeps unique values for the continuous variables. To do G-comp, what I need is to average the expected value *after*, and not set the covariate to its average before (so use the empirical distribution of the covariates basically). Wonder if there is a faster way?
Comment: Did you try your proportional weighting with`cov.reduce = M ~ treat`? That does not reduce M to its mean, but instead to different predicted values for each treat.
Comment: Yes, although that does not quite give the same results (though it is more efficient) as G comp since it makes an assumption of the relation between M and treat. Whereas `cov.keep` avoids this assumption. Say the copy of the data is stored in `newdata` and you have a binary treatment T. G comp is artificially setting `newdata$T=1` and then obtaining the prediction `predict(model,newdata)` and then taking the mean of this prediction to get the estimated mean for T=1. The challenge is getting SEs, p-vals  for this without bootstrap, which is what I was trying to use `emmeans` to do.
Comment: Well, I honestly don't understand how your strategy of keeping all the covariate values separate can have worked, other than by coincidence, because this does nothing to account for causal features. It's just expanding the reference grid and changing the weighting. See @dimitriyvmasterov's  comment on the OP, which I agree with.
Comment: I understand now it seems like the "causal" aspect of it is external to whatever method is used. So even G-comp by itself (though mentioned with causal inf) is *not* causal either w/o the various causal assumptions. Otherwise it seems just a fancier modern approach to contrasts which is more broadly applicable (even to regularized GLM or ML models).  I am just trying to replicate the numerical aspect of it. The primary difference is it keeps everything at the same value except the `T` and then takes the diff of the predicted `Yhat`. I wonder if it's possible to have this feature incorporated.
Comment: This post was a while back, but just wanted to point out for anyone wondering how to do this, now the R marginaleffects package can do it https://vincentarelbundock.github.io/marginaleffects/articles/gformula.html. The difference to emmeans is that when nonlinear/interaction terms are present, it averages over the observed data and does not set continuous variables to their  mean.


Is there a library etc that walks joins in property path expression in a Hibernate Restriction property

Question: It seems irritating that property paths that involve joins must be broken down into multiple criteria. This means that code building a HQL is considerably bloated especially when the path has many joins within it. I have been unable to find a library which "internally" expands paths into the right criteria.
Answer: Had to write my own custom code as I couldnt find any library that expanded and inserted joins where necessary etc.


Probability of a random polygon that does not contain the center of a regular polygon

Question: Problem:
Let $m$ be an even number such that $m \geq 6$, and let $n$ be a natural number such that $3 \leq n \leq \cfrac{m}{2}$.
Number each vertex of a regular $m$-sided polygon clockwise as $1,2,\cdots,m$.
Randomly choose $n$ vertices among the $m$ vertices and construct an $n$-sided polygon.
We assume that two $n$-sided polygons that do not share at least one vertex  are different from each other. Congruent polygons anchored on different vertices (rotated or reflected) are considered different.
Let $P_{m,n}$ be the probability that the center of the $m$-sided polygon is not located inside nor on an edge of the $n$-sided polygon.
Then, find the probability $P_{m,n}$.
What I tried:
First, I calculated $P_{m,n}$ for $(m,n)=(8,3),(8,4),(10,3),(10,4)$:
$P_{8,3} = \cfrac{3 \times 8}{_8C_3} \approx 0.4286$
$P_{8,4} = \cfrac{1 \times 8}{_8C_4} \approx 0.1143$
$P_{10,3} = \cfrac{6 \times 10}{_{10}C_3} = 0.5$
$P_{10,4} = \cfrac{4 \times 10}{_{10}C_4} \approx 0.1905$
For example, when $(m,n)=(8,3)$, we can freely choose vertex 1 by symmetry. And we choose two other vertices $v_1, v_2 (v_1 < v_2)$ among the half side of the regular $8$-sided polygon so that we can simply multiply the combinations by 8. For $v_1 = 2$ we must have $v_2 = 3,4$. For $v_2 = 3$ we must have $v_2 = 4$. Therefore, $P_{8,3} = \cfrac{3 \times 8}{_8C_3}$.
For $n=3$, the possible combination of the triangle is:
$m=8 \Rightarrow (1 + 2) \times 8 = 24$
$m=10 \Rightarrow (1 + 2 + 3) \times 10 = 60$
Thus, $$P_{m,3} = \cfrac{m \sum^{(\frac{m}{2}-3)+1}_{k=1}{k}}{_mC_3} = \cfrac{\cfrac{m}{2}(\cfrac{m^2}{4}-\cfrac{3m}{2}+2)}{\cfrac{m(m-1)(m-2)}{3 \cdot 2 \cdot 1}} = \cfrac{3}{4}\cdot\cfrac{m^2-6m+8}{m^2-3m+2}$$
However, I don't know how to generalize it and find $P_{m,m}$.
Could someone help me with this problem?
Comment: Could you clarify: "We assume that two $n$-sided polygons that do not share at least one vertex are different from each other." Does that mean the following? "As long as there exist any vertex of one polygon that doesn't also belong to the other, then we say the two polygons are different". To double check, this also means that congruent polygons anchored on different vertices (rotated or reflected) are considered different, right?
Comment: Yes, that's exactly what I wanted to say.
Answer: I think there has to be a diameter with all chosen points on one side of the diameter.  I can't prove that at the moment.  So there is one point that is furthest clockwise.
You are then free to choose any $n-1$ of the $\frac{m}2-1$ points anticlockwise from the first point.


Prove or disprove that $a^{\phi(n) + k} \equiv a^{k} \mod{n}$

Question:
Prove or disprove that
$$
a^{\phi(n) + k} \equiv a^{k} \mod{n}
$$
  where $\phi(n)$ is Euler's totient function, for all positive integers $a$ and $n$, as long as $k$ is $\geq$ the multiplicity of all the primes in the factorization of $n$.

I saw the above corollary in Brilliant, so how do you prove (or disaprove) it? Because for $a^{\phi(n) + 1} \equiv a \mod{n}$, it seems to work
Comment: Why is the proof provided by Otto Bretscher not satisfying enough? Any answer proving this theorem would basically be a duplicate of his proof.
Comment: You missed the condition that $k\ge$ the largest mulitplicity of the primes in the prime decomposition of $n$ that was in the Brilliant post. That makes the theorem true.
Comment: @user31415 You right, thank you and sorry.
Answer: Without restriction on $n$ or $a$, it's not always true for small values of $k$ (but always true for "big enough" $k$).
For a counterexample, $\phi(9) = 6$ and $3^7 \not \equiv 3^1 \bmod 9$.
For $a,n$ not coprime, $k$ needs to be big enough to "saturate" the biggest shared prime factor. For any $a$ given $n$, $k\ge\alpha_{max}$ is certainly big enough, where $\alpha_{max}$ is the biggest prime exponent in the prime decomposition of $n$.
Comment: That's the additional condition that was in the Brilliant post mentioned in OP. I.e. $k\ge$ the largest multiplicity of the primes in the prime decomposition of $n$.
Comment: @user31415 Yes, I went to look at the article afterwards. Some interesting work there. I see the OP has revised now to include that condition, which thus needs a proof rather than a disproof.
Answer: Let $n=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_k^{\alpha_k}$. Two cases: $\,p_i\mid a\,\stackrel{k\ge\alpha_i}\Rightarrow\, p_i^{\alpha_i}\mid a^k\,\Rightarrow\, a^{\varphi(n)+k}\equiv a^k\equiv 0\pmod{p_i^{\alpha_i}}$
$p_i\nmid a\,\stackrel{\text{ET}}\Rightarrow\, a^{\varphi(p_i^{\alpha_i})}\equiv 1\pmod{\! p_i^{\alpha_i}}$. Raise by $\frac{\varphi(n)}{\varphi(p_i^{\alpha_i})}\in\Bbb N$: $a^{\varphi(n)}\equiv 1\pmod{\!p_i^{\alpha_i}}$. Multiply by $a^k$.
Remarks: ET - Euler's theorem. $\varphi(p_i^{\alpha_i})\mid \varphi(n)$ is because
$p_i^{\alpha_i}-p_i^{\alpha_i-1}\mid \left(p_1^{\alpha_1}-p_1^{\alpha_1-1}\right)\cdots\left(p_k^{\alpha_k}-p_k^{\alpha_k-1}\right)$
We can raise, i.e. $a\equiv b\,\Rightarrow\, a^m\equiv b^m$, because $a^m-b^m=(a-b)(a^{m-1}+\cdots+b^{m-1})$
This is what Bill Dubuque calls Congruence Power Rule (see for another proof).
$a^{\varphi(n)+k}\equiv a^k\pmod{\! p_i^{\alpha_i}}$ for arbitrary $i\in\{1,\ldots,k\}$ iff $a^{\varphi(n)+k}\equiv a^k\pmod{\! n}$


Ajuda em Procv Copiar dados

Question: Tenho uma base de dados em que um funcionário tem três dependentes ou mais, quando faço um PROCV para puxar um dependente de cada vez, só aparece o primeiro e o último.
Como faço para selecionar o primeiro em uma coluna o segundo em outra coluna e assim por diante?
EXEMPLO
Tenho na base dados estes valores:
216 WILLIAN         Filho   BRUNO
216 WILLIAN         Filho   LUIS
216 WILLIAN         Filho   YASMIN
Fiz um PROCV em outra planilha para deixar um pai e em outras colunas os filhos, consegui puxar através do PROCV o primeiro filho e ao ultimo. Mas não consigo puxar o filho do meio.
216 WILLIAN         Filho    BRUNO  Filho   YASMIN
Também fiz um codigo que acredito estar correto na logica, porem não consigo fazer com que ele copie os dados de uma pasta para outra...

Sub limpar()

Dim num As Integer
Dim contChave, contPrincipal As Integer
Dim numDependente As Integer
Dim idAtual As Integer

contPrincipal = 2
contChave = 2
Sheets("Chave").Select
Cells(contChave, 2).Select
Do While ActiveCell.Value <> ""
    num = ActiveCell.Value
    numDependente = 0
    Sheets("SÓCIOS COOP").Select
    idAtual = Cells(contPrincipal, 3).Value

    Do While num = idAtual
        numDependente = numDependente + 1
        Set depAtual = Range(Cells(contPrincipal, 6), Cells(contPrincipal, 8))
        Sheets("Chave").Select
        Set depend = Range(Cells(contChave, (1 + numDependentes * 3)), Cells(contChave, (1 + numDependentes * 3 + 2)))

        depAtual.Copy depend
        contPrincipal = contPrincipal + 1
        Sheets("SÓCIOS COOP").Select
        Cells(contPrincipal, 3).Select
        idAtual = ActiveCell.Value

    Loop
    contChave = contChave + 1
    Sheets("Chave").Select
    Cells(contChave, 2).Select

Loop

End Sub
Comment: É duplicata desta mas o site não permite a sinalização:[Ajuda em Procv para selecionar dados](https://pt.stackoverflow.com/questions/225917/ajuda-em-procv-para-selecionar-dados)
Comment: ok desisto.....
Comment: Não é sua essa pergunta do link?
Comment: Sim, mas não esta errado?
Comment: Não, se você já fez a pergunta, não precisava duplicar. Vi que criou outra conta e por isso não conseguirá editar a outra. Sugiro que crie uma conta fixa e solicite merge(uniao) das contas através desse link: https://pt.stackoverflow.com/contact
Answer: Bom vamos lá, acho que você precisa definir uma variável para salvar, tente isso:
Set depend = Range(Cells(contChave, (1 + numDependentes * 3)), Cells(contChave, (1 + numDependentes * 3 + 2))).Copy

Ajuda em Procv Copiar dados


Can Audacity only delete the stuff I just recorded with backspace instead of all the audio?

Question: Here's the process I go through:

I start recording
I mess up
I stop recording
I press backspace

But backspace deletes all the audio I've recorded in the project - easily undone - but still very annoying. Is it possible to change how backspace functions to only delete the stuff I was just recording?
Answer: According to the information in this online Audacity manual, you can simply press Ctrl-Z straight after recording to Undo Recording.
According to the manual, Ctrl-Z:

undoes the last editing operation you performed to your project. You can undo as many times as you want, all the way back to when you opened the window. To undo many operations, select History... from the View Menu. The name of this menu item will change to reflect what will be undone; if you just recorded some audio, the menu item name will be Undo Record.

I just checked this method; it seems to only delete the material just recorded.
I guess you might be able to change the function of the backspace key, to make it perform an Undo instead, but then it won't function as you expect it to in other situations (for instance, when deleting a section of selected audio). So, it's probably better just to get into the habit of using Undo: Ctrl-Z.


HP B110i controller not seeing storage array. Any ideas?

Question: We got a new HP ProLiant DL160G6 with internal P410 SAS controller, and an additional B110i SAS controller with external ports that is supposed to connect to the HP Storageworks D2600 Drive Array we got too.
The B110i has the battery installed, but no cache module. We switched the SATA mode in BIOS to RAID, like the manual said.
Now, when I boot the server, during boot it sees the P410, which recognizes the two internal drives, then next it sees the B110i, but that claims to have detected no physical devices, and gives me no options to enter into ORCA or CLI config, unlike the P410.
We've tried three SAS cables, and all ports, both on the controller and the array ends, to no effect. Not even the little green light next to the port on the array is lighting up.
We're pretty much at our wits' end. Anyone got any ideas on how to activate the B110i we might have missed before we send the unit back for repair?
Edit:
Thank you very much ewwhite and Chopper3 for your help. After checking the delivery dockets we found that we were supposed to get a P411 in the first place. They put the wrong card in.
Someone's gonna get an angry phone call tomorrow morning...
Comment: Something's not right here. The B110i is a Motherboard Integrated controller (the "i" on the end hints that). The P410 is a PCIe card with 1 internal SATA connection and 0 external (hence the x10 model number); it doesn't support SAS either. With those in the server there would be no external connections for the D2600. Changing modes in BIOS for the B110i would have no effect on whatever you've got going externally. Do you have HP's ACU installed?
Comment: If you have a P410 installed and detecting internal drives then you must have the SAS backplane internally. If you have the D2600 plugged into something you must have a P411 (or similar) card installed. Check out HP's ACU software and see what it has to say about controllers and drives.
Answer: This combination is not compatible. Yell at the people who sold you the equipment...
From the second paragraph of the HP Quickspecs for the D2600,
<code>The D2000 enclosures support direct attach storage to ProLiant Servers with the HP Smart Array P411, P212 and the P812 Controllers.
</code>
Comment: It's not compatible because there'd be no way to plug an external drive array (D2600) into internal-only cards (P410 and B110i <- Which is also a SATA card, not SAS).
Answer: This issue is because, the B110i controller is a SATA controller and not a SAS controller as mentioned in the original query.
It does not support the SAS hard drives, but, only the SATA hard drives.
Answer: The D2600 doesn't support being ran from a B110i sorry, should have checked the quickspecs.
Get it swapped out for a P212, P411 or P812 instead.
Comment: There's no way to plug a D2600 into the on-board B110i SATA controller anyway... Not without some 3rd party bracket installed in the server.
Comment: Hmmm okay... if the B110i is onboard (which I didn't know) then the card installed must be the P411 that was ordered, and it's simply not being seen. Because all that is shown during boot is the P410 and the B110i. Well, either way, gotta get the folks in who sold it to us tomorrow, either the second PCIe-Card is broken OR the wrong part. Thank you Chris S


Decomposition of a diagonal matrix $\Lambda \approx A\Sigma A^T$

Question: I want to decompose a diagonal matrix $\Lambda \in R^{n \times n}$ such that $$ \Lambda \approx A\Sigma A^T $$ where $\Sigma \in R^{k \times k}$ is a diagonal matrix and $A \in R^{n \times k}$ is a dense matrix (or it is non-diagonal matrix), and $k < n$. Is there any decomposition which can be used to solve the above problem?
Edit: Here the approximation implies that  $\|\Lambda - A\Sigma A^T\|_F^2$ should be as low as possible.
Comment: I think it is impossible as we have orthogonal columns... In a slightly circular way of dealing with this we can get the truncated SVD of the matrix $\Lambda \approx U\Sigma V^T$ and that will allow us to select the $\Sigma$ such that it include the maximal absolute values of our $\Lambda$ and $A$ (i.e. $U$) will be just encode the row and the sign of the of the values of $\Sigma$...
Comment: @usεr11852 If I do SVD, then I will get diagonal $A$.
Comment: It won't be necessarily diagonal. Just it will have a single non-zero value per row. But, OK, we are just playing with words now. :)
Comment: Re the edit: as you surely know, the solution to the less restricted problem of approximating $\Lambda$ as $U\Sigma V^\prime$ is given by the SVD.  In this case the SVD yields $\Sigma=\Lambda$ (up to permutation), so all you need to do is remove the smallest $n-k$ singular values, which can be written in the form you require, whence the SVD does the trick.
Comment: @whuber SVD won't give the solution where $A$ is a dense matrix
Comment: You have stated that $\Lambda$ is a *diagonal* matrix.  You haven't specified $A$ in the problem--it's part of the solution.  If you really want $A$ to be "non-diagonal" or "dense," then simply put infinitesimal numbers in the off-diagonal positions.
Comment: Did you find an answer to this question? I'm looking for the same answer.
Answer: For the diagonal matrix $\Lambda$, its rank is the number of non-zero diagonal elements. If $\DeclareMathOperator{\rank}{\text{rank}} \rank(\Lambda)>k$, then equality is impossible since
$$ \rank\left(A\Sigma A^T\right)\le \min\left\{ \rank A, \rank\Sigma , \rank A^T\right \}  \le k
$$
so
$$
   \rank\left\{ A\Sigma A^T \right \} < \rank \Lambda.
$$
But you didn't ask about equality, but used $\approx$ symbol without explaining in what sense there should be approximation. So then the question is unclear, but at least equality is impossible and any approximation would loose rank.
Comment: Yes you are right, there won't be any equality that is why I used approximation. I updated the question to make everything more clear.


Why are the coefficients always equal?

Question: Take the equation $ax^{2} + bx + c = 3x^{2} + 4x + 53$.
Why is it always true that $a = 3, b = 4$ and $c = 53$?
I've seen many examples like this where the coefficients are equated, and was just wondering why that is always true.
Comment: The question as posed is missing the very important words "for all $x$." Without them, you _do not know_ that all coefficients are equal. You could very well have $a=4\neq 3$, $b=4$, $c=52\neq 53$, provided that $x=1$ or $x=-1$. Or to put it another way, if $a\neq 3$ then you have a quadratic equation to solve for $x$ rather than a formula that is true for all $x$; and if $a=3$ but $b\neq 4$ you have a linear equation with a unique solution.
Comment: If you have two elephants and 3 rhino does that equal 0 elephants and 1 rhino?
Comment: What do you mean by $ax^2+bx+c=3x^2+4x+53$?
Comment: That was just arbitrary. I meant why does a = d, b = e and d = f when $ax^{2}+bx+c = dx^{2} + ex = f$
Comment: So we can take also $3=8$ if we are in $\mathbb{Z}_5$.
Comment: @Chinny84 - Good point, but can you explain that to me a little more in depth?
Comment: @OfirSchnabel - What do you mean?
Comment: I mean that you need to say are you talking over a field? can we use the  fundamental theorem of algebra?
Comment: The first respondent seems to have used the FTA. My question was more of a conceptual one, though, so use whatever you need to. Thanks.
Comment: If you are not over a field, you should use the fact that $1,x,x^2...$ are linearly independent.
Answer: Suppose that $ax^{2} + bx + c = 3x^{2} + 4x + 53$ for all $x$, or $ax^{2} + bx + c - (3x^{2} + 4x + 53) = 0$ for all $x$.
$ax^{2} + bx + c - (3x^{2} + 4x + 53) = 0$ is a polynomial with at most degree $2$ so by the fundamental theorem of algebra it has at most $2$ roots if it is not the zero polynomial.
But $ax^{2} + bx + c - (3x^{2} + 4x + 53) = 0$ has infintely many roots (it is zero for every value of $x$), so it must be the zero polynomial. Then we have $a=3$, $b=4$ and $c=53$.
$$ax^{2} + bx + c - (3x^{2} + 4x + 53) = (a-3)x^2+(b-4)x+(c-53)$$
Every coefficient must be equal to zero for it to be the zero polynomial, thus $a-3=0$, and $a=3$. Similiarly, one has $b=4$ and $c=53$.
Comment: Because it is zero everywhere. $ax^{2} + bx + c - 3x^{2} + 4x + 53 = 0$ for all $x$.
Comment: Not that it changes things much, but haven't you made a sign mistake in Line 2?
Comment: $ax^{2} + bx + c = 3x^{2} + 4x + 53$, thus  $ax^{2} + bx + c - (3x^{2} + 4x + 53)= (3x^{2} + 4x + 53) - (3x^{2} + 4x + 53)$, thus $ax^{2} + bx + c - (3x^{2} + 4x + 53)=0$. This holds for all $x$. Thus there are infinitely many roots. Note that $a$ is a root of $P(x)$ if $P(a)=0$.
Comment: Why does it have infinitely many roots?
Comment: @SR1 I forgot to put brackets.
Comment: Why is that true? Sorry for the persistent questions.
Comment: How can you prove there are infinitely many roots?
Comment: Thank you so much. That was the kind of explanation I needed. But why is a = 3?
Comment: I think that the fact that the zero polynomial always has zero coefficient, is equivalent in every regard to the original question. In this context, this must be proven.
Answer: The equation is valid for all $x$ take $x=0$ to get $c=53$. The equation now rewrites as follows $ax^2+bx=3x^2+4x$ and again this is true for all $x$ especially for say $x=-{4\over 3}$ and the equation now looks like ${16a\over 9}-{4b\over 3}=0$ and for $x=1$ we get $a+b=7$ the solution of the system in $(a,b)$ is $(3,4)$
In general if two polynomial are such as $a_nx^n+\cdots+a_0=b_nx^n+\cdots+b_0$ for all x this means $(a_n-b_n)x^n+\cdots+(a_0-b_0)$ has an infinity of solutions while it has degree $n$ and therefore all its coefficients are $0$ which translates into $a_i=b_i\,\forall i$
Comment: Thanks. Exactly what I wanted. But why does the last equation have an infinite number of solutions?
Comment: True. Thank you for your time.
Answer: Here's a cute way of proving it I don't think has been mentioned yet.
If you agree two polynomials are equal, you should also agree that their derivatives are equal.
Let $f(x) = ax^2 + bx + c = 3x^2+4x+53$.
Taking the derivative of $f$, we get:
$f'(x) = 2ax + b = 6x + 4$.
Taking the second derivative, we get:
$f''(x) = 2a = 6$.
Working backwards, we can solve for each variable in turn. The last equation gives $a = 3$. Going to the one before it, we can replace $2ax$ with $6x$ and subtract $6x$ from both sides to get $b=4$. And finally, we go back to the original to subtract $3x^2 + 4x$ from both sides to get $c=53$.
It's not the most efficient way, but it doesn't require any evaluation of the polynomial or talk of its roots.
Comment: You can use mathematical induction for a rigorous proof.
Answer: The set $\{1,x,x^2,...\}$ is a linear independent set in the vector space of real valued polynomials ($+$ and $\cdot$ defined in the obvious way). Then, by definition of linear independence,
$$
\sum_{i=0}^n a_ix^i = \sum_{j=0}^m b_jx^j \iff a_i = b_j \quad \forall i,j<n=m.
$$
Comment: how does one prove that this set is independent. If referring to polynomials, rather than polynomial functions, this does not relate to the OP. If polynomial functions, you need to show what they want to show
Comment: @Shuri2060 yeah good point; this was a long time ago. In any case DanJenks answer is the proof of linear independence.
Answer: To try and give a more general answer to why $a=d$, $b=e$ and $c=f$ given that $ax^{2} + bx + c = dx^{2} + ex + f$.
Rearranging gives $ax^{2} + bx + c - (dx^{2} + ex + f) = 0$, combining factors of $x$ gives $(a-d)x^{2} + (b-e)x + (c-f) = 0$.
It then follows that each of $(a-d)x^{2}$, $(b-e)x$ and $(c-f)$ must equal $0$.
If $x$ can have any value then $a - d = 0$ therefore $a = d$ with the same for $b = e$ and $c = f$.
It should be noted that values can be found that mean $a$ and $d$, $b$ and $e$, and $c$ and $f$ are not equal for specific values of $x$. Such as $x$ = $0$, which allows $a$, $b$, $d$ and $e$ to have any value.

Why are the coefficients always equal?


Sequence to Label Model

Question: I have a dataset with me where the input is a sequence and output is just some labels. (No sequence in that) What is the best model to train that kind of dataset..?
I was using seq2seq model. But the results were very low.
Then I used multi-label svm with (1,7) ngrams. The result were better than seq2seq model. But not very good.
Can someone specify a better model..?
Thank You!!

EDIT 1
Input is actually a set of sequences.
When I was using svm, the set was flatten and considered as a one sequence.
In seq2seq model, the sequences were separated with a special symbol to identify that it is a different sequence.

EDIT 2
Input sequence does not have a finite length. An example is given below.
Say I have

input vocab: AAA, BBB, CCC, DDD, EEE
output vocab: 111, 222, 333, 444

----Input Sequence----------------------Output (Order does not matter)--
    AAA, BBB, DDD                            111, 333
    AAA, DDD, BBB                            222, 333
    DDD, BBB, AAA, CCC                       111, 444, 222
    BBB, DDD, CCC, AAA                       333

Answer: It would be helpful if you could provide some more information about the structure and characteristics of your data, without this any advice is kinda like shooting in the dark. But until then here are some things you could consider:

If all the sequences are of same length $l$, then you could consider using neural nets (with $l$ input nodes), or treating each entry in the sequence as a separate feature and then trying out decision trees (random forests, C5.0) or any sort of classification algorithm to that end, trained on the input sequence with the example labels.

If not:

Think about making them have the same lenght by imputing the missing values/setting them to NA and then continue with the classification approach. For example, decision trees have no problem with missing values in the data.
It is not clear to me if you want to classify your sequences or maybe just find some clusters. You could have a look at methods for clustering of longitudinal data of differing lengths. Dynamic Time Warping could give you reasonable distances between them or Symbolic Aggregate Approximation.

As said, without any further info on the data and your goal, this might be a starting point.
update
As far as i understood - you have variable output length as well. In your last two examples a sequence of length 4 can give you either output of length 3 or 1. I'm not well informed in this type of problems and cannot give you any specific tips.
What comes to mind is setting up a recurrent neural network since you have to deal with sequences. The input vectors would be your input vocabulary, same for the outputs.
Would be interesting to know what approach did you take and how did it work for you.hth.
Comment: you might try looking up LSTM reccurent neural nets for sequence-to-sequence or sequence-to-label modeling.
Comment: I have edited the question..

Sequence to Label Model