jQuery drag-and-drop DIV selection with images and text

Question: I'm using the jQuery tableDnD plugin to make a drag-and-drop list out of a table displaying a list of images for the user to rearrange. The plugin uses an ID on the  tag of the formatting table to rearrange the cells.
When I drag and drop specifically clicking on a spot inside the table cell with no images/content, it works fine. However, when I click on the image (or inside a div containing text) withgin the table cell and try to drag+drop, the text/image gets selected and the rearrange script is not triggered. Neither blocking the select function with css or javascript has worked - any idea?
Example tableDnD code: http://tablednd.googlecode.com/svn-history/r12/trunk/index.html
Sample rows from the table in question:

images/6/PICT0001.JPG
[Delete Image]
<input type='text' name='6' value='' size=2 DISABLED>

images/6/PICT0006.JPG
[Delete Image]
<input type='text' name='6' value='' size=2 DISABLED>

Answer: Don't use jQuery use dom-drag it's much better and more functional.
Add this code:

Sorry I misunderstood the question :(


Characteristic method for McKendrick-von Foerster age structure model

Question: The well-known age-structure/transport equation by McKendrick and von Foerster has the form:
$$\frac{\partial }{\partial t} u(t,x) + \frac{\partial }{\partial x} u(t,x) = -\lambda u(t,x), \quad \quad \text{for }t>0 \text{ and } 0<x<\tau,$$
which is subjected to the boundary and initial conditions:
$$u(t,0) = cq(t), \quad u(0,x) = f(x)$$
Here, $q(t), f(x)$ are known smooth functions. Using the method of characteristic, I get
$$\frac{dt}{ds} = 1, \quad \frac{dx}{ds} = 1, \quad \frac{dz}{ds} = -\lambda z,$$
with initial conditions $t(r,0) = r, x(r,0) = 0,$ and $z(r,0) = cq(r)$.
Solving the ode's, I obtain
$$x(r,s) = s, \quad t(r,s) = s+r, \quad z(r,s) = cq(r)e^{-\lambda s}.$$
Thus, $s = x$ and $r = t - x$. Together, I obtain:
$$u(t,x) = z(t-x,x) = cq(t-x)e^{-\lambda x}.$$
Looking at the "trivial" solution, I find that this is only half of the solution, which corresponds to $t>x$. The other half is important because it helps to prescribe the "history" of the solution (e.g. transform into delay equation). Please point me to how I can find the other half when $0<t\leq x$. Thank you!
Comment: Yes, I edit to include the initial condition.
Answer: The analysis looks correct. For characteristics starting at the boundary $t=0$, $x>0$, we must set $t(0,r) = 0$, $x(0,r) = r$, and $z(0,r) = f(r)$. Solving the ODEs, we find
$$
t(s,r) = s, \qquad x(s,r) = r+s, \qquad z(s,r) = f(r) e^{-\lambda s} .
$$
Thus, $s=t$ and $r=x-t$. Together, we find:
$$
u(t,x) = z(t,x-t) = f(x-t)e^{-\lambda t}
$$
for $t<x$. Here is a sketch of the characteristics in the $x$-$t$ plane:


Gulp not transpiling SCSS into CSS

Question: I can't get gulp to automatically compile my SASS code into CSS. What am I missing?
file structure:
public
-css
--styles.css
-index.html
sass
-styles.scss
gulpfile.js
package.json

Gulpfile:
var gulp = require('gulp'),
    browserSync = require('browser-sync').create(),
    sass = require('gulp-sass');

  gulp.task('serve', function() { browserSync.init({ server: "./public" });

  gulp.watch("scss/**/*.scss", ['sass']);
  gulp.watch("public/*.html").on('change', browserSync.reload);

});

gulp.task('sass', function() {
return gulp.src("scss/styles.scss")
  .pipe(sass().on('error', sass.logError))
  .pipe(gulp.dest("public/css/styles.css"))
  .pipe(browserSync.stream());
});

gulp.task('default', ['sass', 'serve']);

Package.json:
{
  "name": "gulptest",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "dependencies": {
    "autoprefixer": "^9.3.1",
    "browser-sync": "^2.26.3",
    "cssnano": "^4.1.7",
    "gulp-postcss": "^8.0.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^2.6.4"
  },
  "devDependencies": {
    "gulp-sass": "^4.0.2"
  },
  "scripts": {
    "dev": "gulp"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Comment: What errors are you receiving?
Comment: You are watching `"scss/**/*.scss"`, but your file structure is `sass/styles.scss`.... should you be watching `sass/*.scss`?
Comment: Iam not receiving any errors... The browserSync is working just fine. But when I write SASS code it will not watch and auto write CSS for me. very frustrating. I have tried watching for sass/*.scss also with no luck.
Answer: You have two issues:
As @cale_b said you are watching the wrong directory and your source in the sass task is wrong.  So use this:
gulp.task('serve', function() { browserSync.init({ server: "./public" });

  //gulp.watch("scss/**/*.scss", ['sass']);
  gulp.watch("sass/**/*.scss", ['sass']);

  gulp.watch("public/*.html").on('change', browserSync.reload);
});

gulp.task('sass', function() {

  //return gulp.src("scss/styles.scss")
  return gulp.src("sass/styles.scss")

   .pipe(sass().on('error', sass.logError))

   // and dest takes directories only, not file names
   // sass will automatically produce styles.css
   .pipe(gulp.dest("public/css"))

   .pipe(browserSync.stream());
});

Comment: Your code is commented out - followed by my code.  scss -> sass in both cases because you are using sass/styles.scss not scss/styles.scss
Answer: This is my working gulp sass setup:
gulp.task('sass', function() {
  gulp.src('scss/*.scss')
          .pipe(sass())
          .pipe(gulp.dest('public/css/'));
});
gulp.task('watch', function(){
  gulp.watch(['scss/*.scss'], ['sass']);
});

It seems like it has source redundancies, but it works.

Gulp not transpiling SCSS into CSS


Redirecionar para Tab especifica

Question: Bom dia pessoal, tenho uma aba onde possuo um form que é enviado via Ajax para meu controller e quero que depois da resposta do Ajax a pessoa seja redirecionada para outra tab depois de recarregar a pagina, preciso que al clicar em calculate a pessoa vá para Analysis Results alguém pode me dar uma luz?

Codigo da TAB:

        Data Input

        <input class="button" onclick="calculate()" type="submit" name=""
     value="Calculate" style="margin-top:5px;">

        Analysis Results

        Graph

Comment: Saudações Jeison. Você deve ter percebido que o [pt.so] segue a estrutura de perguntas e respostas em que há uma distinção bem clara entre ambas. O que é pergunta fica na pergunta, o que é resposta fica na resposta. Então, por favor, evite colocar a solução na pergunta. Se conseguiu resolver o problema e a solução ainda não foi postada por outro usuário, você pode responder colocando-a. [Não é errado responder sua própria pergunta](https://pt.meta.stackoverflow.com/q/422/5878).
Answer: Use o window.location.href = "http://seusite.com";
Apos a resposta do seu Ajax
Answer: Não sei se entendi direito mas tenta isso:
Na parte .done(... do metodo ajax depois que você redireciona para essa pagina.
if ($('#tabCalc').hasClass('show')) { // verifica se a tab esta sendo
mostrada
  $('#tabCalc').removeClass('show'); // remove a class show da tab
  $('#tabAna').addClass('show');     // add Class show na tab desejada
}
// ou você pode tentar assim mais simples poem ao meu ver uma forma
ruim ou vc verifica todas com if acimae faz isso :D
  $('#tab1').removeClass('show');
  $('#tab2').removeClass('show');
  $('#tab3').removeClass('show');
  $('#tab4').removeClass('show');
  $('#tabDesejada').addClass('show');

após editar a pergunta novas opções podem ser vistas como no código abaixo:
// Após o retorno do método Ajax para redirecionar para o local da pagina desejado
window.location.href = "http://index.html#Analise";
// ou forçar um click no elemando analise que tbm o levará para o local desejado
document.getElementById('analise').click();

Provavelmente exitem formas melhores para se fazer isto.
espero que isto lhe ajude agora. pois pelo que entendi da pergunta erá isso que você queria
Comment: não funcionou, vou editar e deixar o codigo da tab, talvez ajude
Comment: vc quer apenas setar a tab selecionada ou o conteúdo dela tbm?
Comment: tenta> window.location.href = "http://pt.stackoverflow.com#Analise"; <
ps: desculpa isso provavelmente não irá funciona talvez, porem se vc quer que ele seja redirecionado para o aparte do conteúdo que está na pagina isso certamente servira se o conteúdo não estiver oculto. agora se o conteúdo estiver o culto e vc estiver trabalhando com 'tabs' e o click na 'Analise Result' apenas vá para o conteúdo vc pode tentar tbm > document.getElementById('analise').click(); <;
Comment: modifique tbm o aria-controls="Analysis Results" dos gráficos para o nome certoestá com o mesmo da Analise Result. vo editar a resposta. tbm
Comment: consegui resolver simulando um click com java Script, vou atualizar pra deixar registrado, obg pela ajuda.
Comment: Que bom :D
desculpa não ter a melhor método, para lhe ajudar .
Answer: Meu Problema foi solucionado da seguinte forma:
clique aqui.

Redirecionar para Tab especifica


JavaScript: register a custom script type and define a handler?

Question: HTML  elements with a unique custom type attribute are ignored by the browser. Sometimes these are used by template engines. How do I define what happens when such a script element is loaded/created? (either while loading the page or when inserted dynamically)
In other words, does an onCreateElement event of some sorts exist in the DOM?
I could quite easily iterate through all script elements with attribute type=text/mycustomtype when the DOM loads using for instance the querySelector and then parse them with a function. This however does not work when a new script element is created and appended programatically. Is this currently possible?
var d = document.createElement('script')
d.setAttribute('type', 'text/mycustomtype')
d.innerHTML = 'define foo = 1;' // some code in some custom language
document.body.appendChild(d)

In this case, nothing will happen because the browser will ignore this unknown type. Can I somehow define a handler function for this? Thanks in advance.
Comment: Can you provide more context? Why do you need to add these elements after the DOM loaded? If the DOM and scripts have a lready been loaded, why wouldn't you just call the handler directly? `myHandler('define foo = 1;')` ?
Comment: I think my question is pretty straightforward. I want to define a new script type that will be interpreted by a custom function the moment it is initialized.
Comment: I understand. I don't that's possible so I'm suggesting alternatives.
Comment: If you'd really like to do this for whatever reason and detect changes in the document, have a look at Mutation Observers.
Comment: @yezzz I already did. However I could not make it work by observing the document element. Can you provide an example?
Comment: Unfortunately I have little experience with it. You could edit your question or create a new one with the observer code you tried.
Answer: I recently saw python script running in a browser using brython.  View source and I see:

I wanted to know how this is possible.  I googled for the answer, and found the dreaded stackoverflow question that's exactly what I want - with no answers.
I found a good answer in: Everything I Know About The Script Tag.  It's exactly as you predicted when you say iterate through all script elements.
Their example looks like this:


clang-format keeps moving control blocks to single line

Question: I cannot figure out how this started.  I don't even think I changed anything.  Maybe I updated it?  Using clang-format version 15.0.7 in vim writing C. Invoking via:
map <C-K> :py3f /usr/share/clang/clang-format.py<cr>

... But does the same thing from the standalone program.
if (x >= y)
{
    return 0;
}

keeps changing to
if (x >= y)
{ return 0; }

All relevant options (as far as I know):
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: None
AllowShortLoopsOnASingleLine: false
...
BraceWrapping:
  AfterCaseLabel: false
  AfterClass: false
  AfterControlStatement: Always
  AfterEnum: false
  AfterExternBlock: false
  AfterFunction: false
  AfterNamespace: false
  AfterObjCDeclaration: false
  AfterStruct: false
  AfterUnion: false
  BeforeCatch: false
  BeforeElse: true
  IndentBraces: false
  SplitEmptyFunction: true
  SplitEmptyNamespace: true
  SplitEmptyRecord: true

Answer: wtf... The mystery config was setting:
AfterFunction: True

That is completely unrelated and must certainly be a bug.  Leaving here for anyone else who has this issue.


List Comprehension.. am I crazy?

Question: I have a list of phone numbers
phone_numbers = [000-000-0000, 000-000-0000, 000-000-0000]

for number in phone_numbers:
   x = list(filter(str.isdigit, number.strip()))
   t = "".join(x)

Gives me my desired outcome of 0000000000
Is it possible to use list comprehension for this purpose or am I completely off?
[list(filter(str.isdigit, x.strip())) for x in phone_numbers]
Comment: Btw do you realize that you got list of *results* of subtraction rather than phone numbers?
Answer: Yes you can use list comprehension.
["".join(filter(str.isdigit, number.strip())) for number in phone_numbers]

Answer: Here are some solutions,
import re

phone_numbers = ["000-000-0000", "000-000-0000", "000-000-0000"]

>>> ["".join(re.findall("\d+", p)) for p in phone_numbers]

['0000000000', '0000000000', '0000000000']

OR
>>> ["".join(x for x in p if x.isdigit()) for p in phone_numbers]

['0000000000', '0000000000', '0000000000']

List Comprehension.. am I crazy?


stunnel vpn traffic and ensure it looks like SSL traffic on port 443

Question: I am trying to make my outgoing and incoming traffic look as legitimate as close to SSL traffic as possible. Is there a way to DPI my own traffic to ensure it looks like SSL traffic and not OpenVPN traffic? And based on my config setup does all traffic use port 443 which is the SSL port?
My configuration is as follows:
STUNNEL on laptop:
[openvpn]
# Set sTunnel to be in client mode (defaults to server)
client = yes
# Port to locally connect to
accept = 127.0.0.1:1194
# Remote server for sTunnel to connect to
connect = REMOTE_SERVER_IP:443

OPENVPN CONFIG ON laptop:
client
dev tun
proto tcp
remote 127.0.0.1 1194
resolv-retry infinite
nobind
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
persist-key
persist-tun

STUNNEL CONFIG ON SERVER:
sslVersion = all
options = NO_SSLv2
;chroot = /var/lib/stunnel4/
; PID is created inside the chroot jail
pid = /stunnel4.pid
; Debugging stuff (may useful for troubleshooting)
 debug = 7
 output = /var/log/stunnel4/stunnel4.log
setuid = root
setgid = root
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
compression = zlib
[openvpn]
accept = REMOTE_SERVER_IP:443
connect = REMOTE_SERVER_IP:11440
cert=/etc/stunnel/server.pem
key=/etc/stunnel/server.key

OPENVPN CONFIG on server:
local REMOTE_SERVER_IP
port 11440
proto tcp

Comment: You can answer the 2nd question with wireshark running on your laptop and probably learn a lot more on the way
Comment: Trying to learn new aspects with VPNs and understanding network protocols along with analysis ect...
Comment: Not that you should probablye disable TLS compression (because of CRIME) and restrict the number of TLS protocols and cryptosuites avaiable in order to avoid simple attacks on your TLS tunnel ([server side](http://mozilla.org/Security/Server_Side_TLS) and client side) if your really want to use this in the real world.
Comment: you can user other ports for SSL/TLS.  i even do it over SCTP and IPv6.
Answer: OpenVPN over TLS
Your VPN is using TCP as a transport protocol. The stunnel instance is used to encapsulate the content of the TCP stream in TLS/TCP. You get this protocol stack:

[IP     ]<------------------------>[IP     ]
[OpenVPN]<------------------------>[OpenVPN]
            [TLS   ]<~~~~~>[TLS]
[TCP    ]<->[TCP   ]<----->[TCP]<->[TCP    ]
[IP     ]<->[IP    ]<----->[IP ]<->[IP     ]
[       ]   [      ]       [   ]   [       ]
 Server      stunnel      stunnel  Client

Between the stunnel instances you have this protocol stack on the wire:

[IP      ]
[OpenVPN ]
[TLS     ]
[TCP(443)]
[IP      ]
[...     ]

As the TLS encrypts its payload, an attacker can only see:

[???     ]
[TLS     ]
[TCP(443)]
[IP      ]
[...     ]

So yes, it is plain TLS traffic (it could be HTTP/TLS, SMTP/TLS, POP/TLS or anything else for someone looking at the traffic but it looks a lot like HTTP/TLS as the TCP port 443 is used). You can check this by using wireshark: record the traffic between the stunnel instances. In the wireshark UI (right button on a packet of the stream), you can ask wireshark to interpret the traffic as TLS: it will recognise it as TLS traffic (you will see the different TLS messages but not the payload of the TLS session).
You might want to use SNI in the client in order to look like what a modern browser would do. You might want to use ALPN as well but stunnel currently does not handle that.
OpenVPN with builtin TLS
In comparison, if you are using OpenVPN, you will have something like this:

[IP      ]
[OpenVPN ]
[TCP     ]
[IP      ]
[...     ]

Which looks like this:

[???     ]
[OpenVPN ]
[TCP     ]
[IP      ]
[...     ]

The builtin TLS layer does not encapsulate the (IP, Ethernet) packets but is only used for setting up the session and authenticating:

[TLS     ]
[OpenVPN ]
[TCP     ]
[IP      ]
[...     ]

In this case, your traffic does not look like a plain TLS traffic but is obviously OpenVPN. If you interpret this traffic as OpenVPN in wireshark, you will recognise the OpenVPN messages and inside of them the TLS messages (but not the payload).
Warning
You should be aware that if a passive attacker will not be able to tell that your remote server is in fact an OpenVPN server, an active attacker will be able to find this out: simply by connecting to your server over TLS, he will be able to confirm that it is not a HTTP/TLS server. By trying to speak the OpenVPN protocol, he will be able to detect that your server is a OpenVPN/TLS server.
OpenVPN over TLS with client authentication
It you are worried about this you could enable TLS client authentication: an attacker will not be able to initiate a working TLS session and will not be able to guess which payload is encapsulated over TLS.
Warning:* I'm not talking about the builtin TLS support in OpenVPN (see above for en explanation about why it won't help you).
Multiplexed OpenVPN/TLS and HTTP/TLS
Another solution is to serve both HTTP and OpenVPN over the TLS session.  sslh can be used to automatically detect the payload of the protocol and dispatch either to a plain HTTP/TCP server or you OpenVPN/TCP server. The server will look like standard HTTP/TLS server but someone trying to speak OpenVPN/TLS with this server will be able to detect that it is in fact a OpenVPN/TLS server as well.

        either OpenVPN/TCP
          or HTTP/TCP
[1].---------.     .------.HTTP/TCP.-------------.
-->| stunnel |---->| sslh |------->| HTTP server |
   '---------'     '------'|       '-------------'
                           |       .----------------.
                           '------>| OpenVPN server |
                        OpenVPN/TCP'----------------'

[1]= Either OpenVPN/TLS/TCP or HTTP/TLS/TCP

OpenVPN over HTTP CONNECT over TLS
Another solution is to use a standard HTTP/TLS server and use HTTP CONNECT/TLS to connect to the OpenVPN server: it will look like a standard HTTP server. You can even require authentication of client in order to authorise the HTTP CONNECT request (squid should be able to do this).
OpenVPN has an option to use a HTTP Proxy:
http-proxy proxy.example.com

You should be able to combine this with a stunnel instance connecting to a remote HTTPS PROXY:
http-proxy 127.0.0.1 8443
remote vpn.example.com

Which would implement this protocol stack:

[IP     ]<------------------------>[IP     ]
[OpenVPN]<------------------------>[OpenVPN]
            [HTTP  ]<------------->[HTTP   ]
            [TLS   ]<~~~~~>[TLS]
[TCP    ]<->[TCP   ]<----->[TCP]<->[TCP    ]
[IP     ]<->[IP    ]<----->[IP ]<->[IP     ]
[       ]   [      ]       [   ]   [       ]
 Server    HTTPS PROXY     stunnel   Client
Comment: Can you please elaborate on the HTTP CONNECT approach? Where can I find a guide to setting this up?
Comment: kobtextify: added some details about a possible implementation of OpenVPN/HTTP_CONNECT/TLS.
Comment: Thanks! How would the web server or Squid part look?
Comment: I guess somthing like «acl VPN_SERVER dstdomain vpn.example.com » « acl VPN_PORT ports 1194 » « acl CONNECT method CONNECT» « http_access allow VPN_SERVER VPN_PORT CONNECT » « http_access deny all ».
Answer: ysdx's answer is great, and describes very well how the traffic will look on the wire.
Left unmentioned, however, is that traffic analysis can go a long way toward identifying applications.
Let's assume that your OpenVPN connection looks just like an https connection on the wire, so an attacker cannot read the byte stream and know what kind of connection it is.
A typical https connection won't live too awfully long.  Maybe your browser keeps a connection open to your mail server, I don't know.  In general though, there will be lots of relatively short connections to a lot of diverse remote servers.
OTOH, the OpenVPN connection might live for hours or days, and will send a lot of data back and forth to the openvpn server.
You could mitigate the long-lived connection by periodically dropping and restarting the connection.  This presumably has implications for your application traffic, but might be workable.   The pattern of lots and lots of traffic going between you and the openvpn server, however, is going to be a lot harder to camouflage.
Comment: Yes. What's more, I guess it might be possible to look at the shape of the traffic (such as its "burstiness") and compare it to a standard HTTP/TLS, IMAP/TLS, POP/TLS, OpenVPN/TLS. You might try to classify a given TLS traffic with those profiles of traffic and have an idea of the type of traffic encapsulated in your TLS connection.


What model should I use to fit an arbitrary continuous distribution for each data point?

Question: My problem is, for each input data $x$ I have some corresponding output samples $y\sim p(y|x)$, where $p(y|x)$ can be an arbitrary continuous distribution.
I don't think a least squares model will work, because say if $p(y|x)$ has two peaks then least squares is likely to find some midpoint between the peaks. Probably an "exclusive divergence" loss will work better as at least it can find one peak.

I have in mind two solutions, the first is to use a Gaussian mixture model to fit more peaks.
The second is to discretize the space into cells, then hopefully somehow it can be solved as a classification problem.
What is the common approach for such problems? Are there any examples/papers to look at?
Thanks in advance :)
Update
Some clarification updates (thanks user20160 for the questions)
1) $x$ and $y$ are both high dimensional continuous vectors
2) there might be probably less than ten $y$s for each $x$, so I don't think it's enough to estimate a distribution separately for each each $x$
3) I need to estimate a function over the whole input space that gives $p(y∣x)$ for any $x$, instead of a fixed set of observed $x$ values.
Jan Kukacka's answer mentioned variational inference, it's not clear to me how it could be applied to my problem.
Comment: Is x 1-dimensional?
Comment: @Denziloe no, but I'd love to hear any suggestions for the 1-dimensional case as well, thanks
Comment: 1) Is $y$ a scalar or vector? Is $x$ real or discrete? 2) It sounds like you have multiple/repeated samples at each $x$ value. How many? 3) Is the problem to estimate $p(y \mid x)$ at a fixed set of observed $x$ values, or do you need to estimate a function over the whole input space that gives $p(y \mid x)$ for any $x$?
Comment: @user20160 hi thanks for replying, 1) $x$ and $y$ are both hd continuous vectors, 2) there might be probably less than ten $y$s for an $x$, so I don't think it's enough to estimate a distribution using only less than ten samples, 3) I need to estimate a function over the whole input space that gives $p(y∣x)$ for any $x$ :)
Answer: I think you are looking for Variational inference.
Shortly, Variational inference is trying to find a function $q(y)$ approximating (intractable) $p(y|x)$. It relies on optimization of the (exclusive) $\mathrm{KL}(q||p)$ that you mentioned, so in multimodal case it will converge to a single mode. As Variational inference texts never forget to mention, you reduce an intractable inference problem to optimization (tuning parameters of $q$).
There are good introductory chapters on VI in K. Murphy: Machine Learning, A Probabilistic Perspective, Chap. 21, and in C. Bishop: Pattern Recognition and Machine Learning, Chap. 10. For more in-depth overview, see for example Blei et al.: Variational Inference: A Review for Statisticians. There are more great tutorials by David Blei around the internet.


Is there a way to suppress Python M2Crypto's RSA.gen_key output?

Question: I'm using the Python M2Crypto package to generate RSA keys.
>>> import M2Crypto
>>> rsa = M2Crypto.RSA.gen_key (2048, 65537)
.............................................................+++
............................+++
>>>

Notice that "openssl stuff". To suppress writing to stdout/err I usually do:
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')

That has no effect in this case. I'm assuming this has to do with the way M2Crypto is wrapping OpenSSL.
Is there a way to stop it?
Answer: I looked at the source /M2Crypto/RSA.py, found out what your issue was, and then realized I could have just read the docs. Always check the documentation first!!!
According to the docs for RSA.gen_key, gen_key has an optional argument called callback which allows you to specify a function to call whenever gen_key is called (ostensibly to provide feedback to the user). The default value for this call back prints stuff to stdout. Change your function call to:
>>> rsa = M2Crypto.RSA.gen_key (2048, 65537, callback=lambda x, y, z:None)

And it should do the trick.
EDIT
Below is the relevant code from the M2PyCrypto source. Comments added by me.
def keygen_callback(p, n, out=sys.stdout): #sys.stdout is bound to `out` at definition time
    """
    Default callback for gen_key().
    """
    ch = ['.','+','*','\n']
    out.write(ch[p])
    out.flush()

def gen_key(bits, e, callback=keygen_callback): #keygen_callback is bound to `callback`
    #other code...

Comment: Thanks! Is the out=sys.stdout assignment in the method definition done when the module is loaded in python and not when the method is called? I'm still unsure why setting sys.stdout to /dev/null didn't stop the output.
Comment: @Cory That's exactly what happens the value of that default parameter is set at the time of function definition. See [this answer](http://stackoverflow.com/a/11416002/1142167) to a (somewhat related) concept.


Why does a guitar scale shape have more than 7 notes?

Question: As the title suggests, I wonder the number of notes in a scale shape on guitar.
Let's take the G major scale in 2 octaves: G A B C D E F# G A B C D E F# G, there are 15 notes. I found that in many guitar resources, they play more than 15 notes.
This is called the first position. Play from the first root note (G) to the 3rd root note, there are 15 notes, however they add M2 and M7 (A & F#) into play.

I found that the other scale shapes also have more than 15 notes? So why do they have to add more notes and how can I know which order to play after completing the 2 octaves?
Comment: Your hand written diagrams look pretty accurate but the diagram in the 1:00 position has an extra note that shouldn't be there the D string finger 4, it is a b7.
Comment: (note: John's comment refers to the top-right diagram / 1 o'clock position)
Comment: I feel the title is misleading, I answered with a guitar scale shape that was clearly not 15 notes and the answer got deleted because of that. Isn't it presupposing the antecedent? Many notes have the same pitch on different strings so you can make them almost however you want, including all duplicates or only unique ones.
Answer: Maybe I'm just pedantic, but for me a scale runs from tonic (root) to another tonic one, two, three octaves higher, and often back again. At least that's what's expected in practical music exams. Not sure what the examiner would think if a candidate played two and a half octaves of what was required!
A lot of these portrayed 'scales' are really showing the available notes within a hand span. So, basically, a four fret span on guitar/bass, where no great stretch is required. Often, the perpetrator of those 'scale' patterns will include extra notes, lower and higher , that could be reached with a little stretch, up and/or down. As those notes are diatonic to the key, thus would belong in a scale.
A scale, though, is basically the set of diatonic notes, portrayed in ascending/descending order. So, in actual fact, you may come across one which is in reality a mode of that parent scale - albeit not starting and finishing on the same note. No wonder it's confusing especially for beginners.
The title ought to be 'notes available in a span', rather than 'scale', but maybe that's too pedantic..!
Comment: @trequartista the problem is that people use "scale" in different senses.  Frequently it means "a set of notes that you can use in a solo (or in some similar musical context)" and for that sense neither ordering nor beginning-and-ending points are particularly important.
Comment: That's my point. Whether a scale goes 2,3 or 4 octaves, it really needs to go tonic-tonic. Those boxes merely show available diatonic notes within reach.
Comment: @Tim This makes much more senses to me than the five scale shapes popular on the Internet: https://www.jeffreygoodmanmusic.com/major-scales
In fact, looking at those shapes I don't know where to start and where to finish the series of notes.
Comment: The only context where I've seen a scale have to go strictly from tonic to tonic, or even from a given degree to the same degree, is a music school exam. In any practical application of scales you'll have scales spanning partial octaves. Saying the images depict scales is completely correct in my opinion.
Comment: Thanks, Tim. So, for 2 octaves G major scale there, they should not end up at A (in the 1st string) but to continues high up the string to reach another G (tonic), to get three full octaves? For me personally, a scale doesn't end at the tonic sounds really weird.
Comment: @neonblitzer - we're here to sort out discrepancies, and this seems to be one.
Comment: FWIW scales with N-and-a-half-octaves (eg tonic-dominant) are a thing even in music school exams (eg see page 5 of [this syllabus](https://www.mtbexams.com/wp-content/uploads/2023/09/MTB-Trumpet-Grade-7-All-Files-2023.pdf)); I guess that's likely to happen when a full N+1 octaves of a particular scale don't fit into the instrument's range, or into the expected range of a performer at that level.
Comment: @psmears - that's a new one on me. MTB, only ever used the usual board exams. But still, they go from low tonic up and back to low tonic. Thanks.
Comment: @Tim: Yeah I think MTB are pretty new. Yeah, half-octave scales is one thing, but not starting on the tonic, that's just crazy talk ;-)
Comment: @psmears - maybe they're thinking modes?
Comment: In Italian, the musical term "scale" is the same as "stairs" ("scala/scale"), which is an interesting analogy. One of my harmony teachers once told me: "a stair is something that allows you to easily go from one place to another at a different height". Whether they have two steps or twenty, they are still stairs. Similar to real life stairs, normally used to go between actual *floors*, in the didactic context a scale normally is measured in octaves; you could go up and down three floors or just stop at the mezzanine or between flights, still, you will be walking stairs.
Comment: @musicamante - similarly, in French - gamme, or echelle - a ladder, presumably to go up and down sequentially.
Answer: TL TR; the figures depicted in the question are not scales, these are different positions for a given scale.
Let's try not to be pedantic (pardon me I'm in a joking mood), guitar is one of those instruments that wandered quite far from the classical world, so you will find many (really many) guitar resources that are incorrect on the web and litterature, some plain wrong, some with incorrect terms. It's always good to cross examine multiple references.
From the nature of the instrument (uniform repartition of semitones), many guitarists/bassists will rely on visual structures to identify scales, because the same pattern can be repeated up and down across the board, it will produce the same scale but for a different root note. It is interesting for us to extend this structure to all the notes that are easily playable witout moving the hand, well, because we can use them to stay in that scale without, hum, moving the hand.
You actually had it in the question already, these are called positions. This is why you have numbers on the second image, these are the number of the finger you will use to play. Your example is actually a conterexample: for most scales the standard position will have you start on the root note with the first finger. The major scale has this particularity that it's easier to play in the position you illustrate, starting with second finger on the root to avoid big gaps you see on the second figure of the second image. In all these poitions, you see that the root is highlighted with a color to show you where you can start and end if you want to go up and down a scale in a given position.
The way most of us commoners (non-classical) learn music, we are told not to focus on going up and down scales mechanically, but to focus on the musicality (eg "licks" or "riff" approach), so we tend to consider a scale as a set of notes to play with, rather than a ordered list with a start and end. This is why lots of guitarists tend to confuse terms or use them loosely..
Answer: The scale shapes have more than 2 octaves worth of notes marked on them for the same reason pianos have more than 2 octaves worth of keys. You're supposed to learn to see the shapes on the fretboard so you know where the "right" notes are.
If the scale was a song or a phrase you're supposed to perform like a piece, and then the audience would applaud for a great and touching performance, then maybe it would suffice to only mark one scale run from start to finish. But scales are not full songs. The shapes are for seeing and knowing, not performing.
Comment: IMHO, generally we all agree that a major scale is defined by the formula WWHWWWH (TTSTTTS) so what I'm asking here is not a shortened scale applied in a piece. I'm asking for the consistency of the above definition and the scale shape.
Comment: The shapes are consistent with the definition. They show notes belonging to the scale that lie within playable reach in the given position, and out of those, root notes highlighted with a different color. The shapes are for _seeing_ and _remembering_ when you play various things utilizing the scale. A two-octave scale run exercise ("Play from the first root note...") is one of many things that utilize the shape. If they had said "Play Mary Had a Little Lamb", they wouldn't have drawn a different, even more limited shape having only the notes of that song.
Answer: As you now know, there is a difference between scales and positions. If you want to practice scales, you generally start on the root and play up to a higher root that is either one, two or as many octaves as you can manage, then back down to the original root.
Both have their merits. Scales teach us how to navigate our instruments, learn our fingerboards and hear tonality, among other things. Positions show us all the available scale tones available to us across all six strings in a vertical space 4 to 5 frets wide.
Don't let anyone talk you out of the fact that learning positions is not useful. It is extremely useful in many ways. First things first, melody has this strange habit of not always beginning and ending on the root note of the key you happen to be playing in. The highest and lowest notes of a melody are also not always, or even usually the root note of the scale. This means that our nice sequence of do-re- mi is just a reference for where everything is, it is not music on its own. Here is a simple example, let's say you are playing a melody or solo where you want your high note to be the second degree of the scale. By knowing the position in your first diagram that note is available to you on the high E string.
The other thing about knowing positions is it teaches you to learn where the notes to a given key is on the ENTIRE fingerboard, not just in two or three spots where you feel comfortable playing it.
Here is a similar but better diagram of the scale positions. This particular one eliminates the big stretches in some of yours which I think is better to work with initially. As the caption says, this diagram shows the intersection points where the positions share common notes. The notes you play with fingers 3&4 will be played with fingers 1&2 in the next position, shown by the boxes between the positions. These positions also happen to coincide with the chords of the CAGED system. I've outlined those chords on the diagram in blue for reference. FYI if you use these actual fret numbers all of these positions are the key of G major:

Knowing these positions will give you options of where and in what register you want to either play a melody of solo in. You can play any key anywhere you choose on the fingerboard. Say you have a melody where you want to play a high 5th as your top note. Position 3 is a good choice. They are also useful for learning how to move horizontally across the neck. Here is an example. Starting in position 1, play the first octave but when you get to the octave note on the D string. Instead of using finger 4, slide up and play it with finger 2. Voila, now you're in position 2! You can find an infinite number of ways to shift from one position to another using this basic concept, just try and be as logical and smooth as possible.
The last and very important thing I want to leave you with is I believe the best way to practice and learn positions is to still think of them as relating to the key you are in. For me that means always starting and ending on the root. Start on the lowest root note, even if it is on the D string, play all the way to the top, then back down past the starting root note down to the lowest note in the position, then work your way back up to the original root note and end there. This way you always have the sound of the key you are playing in your head.
Comment: Thank you very much John for your insightful answer. Actually I'm learning classical guitar and practicing scale in various rhythms and positions is one of my goal. What confusing me here is how to connect these shapes if, for example, in the second position you end the series of notes at p4, and what to play next when you reach p4 and you start at the first tonic (G)?
Comment: @trequartista The way I like to practice these positions is to think of them as the notes that are available to me vertically in the part of the neck and in the key I choose to play in. As I mentioned in my answer, in G I would start on the G on the D string, play all the way up to the p4 on the high E string, then descend all the way to the lowest note, the M2 on the low E string, then back up to my starting note of G on the D string. However these scale positions are just information, you can use them in any way you feel would benefit you,
Comment: @trequartista I also explained in my paragraph below the diagram how you can transition from one position to another by choosing a common note between positions and changing fingers to get to the new position. This works both ascending and descending. My example shows how to shift from position 1 to position 2 by switching to the second finger on the octave root note but this can be done anywhere and even more than once.


How to display drupal user page tabs on 3 different page

Question: We want to display a 3 tab  "Create new account(Lawyer Registration)" , "Log In" , "Forgot Password" link on 3 different pages. when we click on log in then they display all 3 tabs.
Actually we have 2 different type of registration process one for lawyer and another one is for normal user. when we click to login then they display above 3 tabs and this is confusing for user. so i want to hide this lawyer registration process form user page and call them to from different page.
So please help me how i can remove them from above tabs and call user/register page from different ways.
Answer: One quick solution to hide the tabs is to change the menu type form tabs to callback:
<code>/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $items['user/login']['type']    = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;
}
</code>
You could render the user register form whatever you want with this:
<code>$elements = drupal_get_form("user_register_form");
$form = drupal_render($elements);
echo $form;
</code>
Comment: I put that code in user.module but nothing happens.
Comment: You need to put the hook function in a new custom module and clear the caché, also rename "yourmodule" with your module name.
Comment: actually i am new to drupal. i dont know how to create a hook menu.please guide me
Comment: Second code is working fine.Now i just need to remove them form user page.
Comment: You can follow this tutorial to create your first module: https://www.drupal.org/node/1074362 :)
Answer: This is perfectly possible with the use of Profile2 module (https://www.drupal.org/project/profile2) in combination with Profile2 regpath module (https://www.drupal.org/project/profile2_regpath)
This way you can setup a specific registration path per profile.


Allow file access to specific users in Drupal (not roles)

Question: I have historical data recorded in pdf files for our clients. Now I am developing a website (in Drupal) from where clients should be able to access this data. The problem is that i don't want this files to be available to anyone else than the user to whom the information belongs.
Since this data is periodically recorded I could store it in a specific folder for each user.
My question is that if it's possible to give access to this folders or its content to specific users in Drupal. Because the alternative would be to create a Role for every user which is not good.
Answer:
Create a new content type and add fields according to your
requirement or user reference field
Disable its Front page publish option.
Create new user Role like "client".
Create view of files and add relationship or contentuxal filter
against user loggin id.
Create block view assign this block into specific region.
Comment: would it make te files unavailable to access for other users?
Comment: yes due to only login user can view their own file
Answer: At the end I found a solution that covers all my needs. I created a custom page template for the page from where i want to access the files (ex. node--4.tpl.php) that catches the username and generates a cookie with it:
global $user;
$username = $user->name;
$cookie_name = 'cookie_name';//
$cookie_value = $username;//
setcookie($cookie_name, $cookie_value, time() + (3600), "/");

Then I create a .htaccess file in each user's folder that contains this code:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !cookiename=username [NC]
RewriteRule .* http://alternativepath/ [L]

So only the user who's username is like the username i ask for in the htaccess can access the folder. In my case I ask for another field, not the username, but this should be enough as a simple example.


Doubt on interpretation of Neyma-Pearson lemma

Question: In my book:
$\mathbf{X}=(X_1,\ldots,X_n)$
$f(\mathbf{x})$ is the joint density, where $f$ is either $f_0 \text{ or } f_1$.
Suppose we want to test $H_0: f=f_0$ or $H_1: f=f_1$. The test, whose test function is
$$\phi(\mathbf{X})=1\text{ if }\frac{f_1}{f_0}\geq k;$$
$$\phi(\mathbf{X})=0 \text{ otherwise,}$$
(for some $0<k<\infty$) is a most powerful test of $H_0$ versus $H_1$ at level $E_0(\phi(\mathbf{X}))$.
My question is how is $k$ defined? Can I interpret the lemma as if $\forall k \in (0,\infty)$ there will be a test function $\phi(\mathbf{X})$ such that it will determine the size for which the test with test function $\phi(\mathbf{X})$ is most powerful?
I'm just trying to understand which kind of relationship $k$ and the size of the test have between each other.
Comment: Please don't cross-post your questions here and on math.stackexchange.
Answer: The value of $k$ determines the size of the test. You have to find the expression for $E_0 \phi(X)$ in terms of $k$, equate it to the desired size, and solve for $k$.


How do you add a PDF attachment to an email?

Question: Goal: I need to send an email with a pdf attachment in Drupal 8.
Progress
I am able to send an email with subject and message but have never been able to get the attachment. When I turn on the logic to attach the file to the email, the email never gets sent but the mail service returns True as if the email was sent anyway. There are no errors and the logs say nothing.
I have the following modules installed:

SMTP
MailSystem
MimeMail

What I've tried

Tried using $message['params']['files'][] = $params['attachments'] instead of $message['params']['attachments'][] = $params['attachments'] like some examples have recommended
Tried changing $file->uri to $file->filepath
Tried attaching the file like so:
$params['attachments']['filecontent'] = $this->generatePDF($foa_list);
$params['attachments']['filename'] = 'MyFormsOfAssistance.pdf';
$params['attachments']['filemime'] = 'application/pdf';

Tried attaching the file by path alone with an array:
$attachment = array(
    'filepath'=>'sites/default/files/MyFormsOfAssistance.pdf',
);

$params['attachments'] = $attachment;

Tried attaching the file a different way:
$attachment = array(
    'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
    'filename' => 'MyFormsOfAssistance.pdf',
    'filemime' => 'application/pdf'
);

$params['attachments'][] = $attachment;

Setup

There is email landing page in which a user enters the recipient's email address, subject for the email, and message for the email.
When user clicks Send button, that data is routed to my Email Controller
Email controller creates the pdf file, attempts to attach the pdf to the email, and then sends the email.
I have the hook_mail() function defined in my module file.

Here is the code for my Email Controller:
public function submit_email($foa_list = null) {
    $lang = "en";
    $email_to = "firstname.lastname@example.com";
    $params['subject'] = "Test subject";
    $params['body'] = "Test body";

    // -------------------- Attachment Logic -----------------------
    // Create pdf file and store file
    file_put_contents('sites/default/files/MyFormsOfAssistance.pdf', $this->generatePDF($foa_list));

    // Attach pdf file to email params
    $file = new \stdClass();
    $file->uri = 'sites/default/files/MyFormsOfAssistance.pdf';
    $file->filename = 'MyFormsOfAssistance.pdf';
    $file->filemime = 'application/pdf';
    $params['attachments'][] = $file;

    // Send email
    \Drupal::service('plugin.manager.mail')->mail('email', 'email', $email_to, $lang, $params);

    $response = new Response();
    $response->setContent("true");

    return $response;
}

Here is the hook_mail() code in my Email module file:
// Note that print_and_email is what my module is called.
function print_and_email_mail($key, &$message, $params) {
    switch($key) {
        case 'email':
            $message['subject'] = $params['subject'];
            $message['body'][] = $params['body'];
            $message['headers'] = [
              'MIME-Version' => '1.0',
              'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
              'Content-Transfer-Encoding' => '8Bit',
              'X-Mailer' => 'Drupal',
            ];
            // $message['params']['files'][] = $params['attachments']; // Note: I have seen other examples implement attachments this way
            $message['params']['attachments'][] = $params['attachments'];
            break;
    }
}

The Drupal 8 documentation isn't really helpful and I would like to be able to figure this out without installing SwiftMailer, like some sources have recommended. Really not sure why this isn't working as it has worked for others. What am I missing?
Answer: FINALLY! 4 weeks later...
So the following code ended up working for me:
    $attachment = array(
        'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
        'filename' => 'MyFormsOfAssistance.pdf',
        'filemime' => 'application/pdf'
    );

BUT, the key was that in the MailSystem Configuration I had to set the Formatter and Sender to "SMTP Mailer". MimeMail's config automatically pulled it's values from my SMTP's configuration.
Comment: @Cadre could you update your full working code so it would be help full.
Comment: I tried your solution, and no luck. How did you figure out that "MimeMail's config automatically pulled it's values from my SMTP's configuration. " ?
Comment: @Srikanth [this tutorial](https://labs.tadigital.com/index.php/2017/07/07/how-to-send-a-mail-with-an-attachment-in-drupal8/) helped me when i had the same problem.
Comment: One important note - the filepath should be without '/' symbol at the beginning.
Answer: Try the Email Attachment Helper module.

This is a module for developers who want to attach files
programmatically to emails send from Drupal 8. This module doesn't
send emails but rather intercepts emails from other modules.
If an 'attachment' or an 'attachments' key is present in the $params
array, it will be converted into an actual MIME attachment. Otherwise,
this module doesn't touch the mail.
This module has no configuration options.

$params['context']['attachments'] = [
  'filecontent' => file_get_contents('sites/default/files/sample.pdf'),
  'filename' => 'Invoice.pdf',
  'filemime' => 'application/pdf',
];

Hook_mail()
$context = $params['context'];
$message['params']['attachments'][] = $context['attachments'];

Answer: $invoice_pdf = File::load($fid); // the file id
$invoice_file = (object) [
  'filename' => 'invoice.pdf',
  'uri' => $invoice_pdf->getFileUri(),
  'filemime' => $invoice_pdf->getMimeType(),
];
$message['params']['files'][] = $invoice_file;

'files' must be an array, that's were I had the most difficulties with. Full code here: Send e-mail with managed file attachment in drupal 8
Comment: This answer seems to be for Swift Mailer, not for Mime Mail. Different mail modules have different ways to add attachments. Some don't allow attachments. The original poster said "I would like to be able to figure this out without installing SwiftMailer"


Is there a way to protect / unprotect a word in Red like in Rebol?

Question: Protect/Unprotect exist in Rebol, they don't seem to exist in Red.
Answer: They are not implemented yet, that should happen in 0.8.0, with the introduction of modules.


C passing pointer to pointer in function

Question: I am reading about pointer to pointer and now I think I know less than previous.
Passing double pointer is needed to change value of that pointer. But, if we have let's say pointer to some structure and we want to change the value of some of its members(fields), then we have to pass a simple pointer. Is the previous statement correct?
for example:
struct A* a;
void func(struct A* arg)
{
   arg->mem1 = 5;
}

and
struct *A a;
void func(struct A** arg)
{
   *arg = malloc(struct A);
   (*arg)->mem1 = 5;
   return;
}

I hope the above examples makes the problem clear.
Comment: We are very confused also.  *Please* show a code example!
Comment: @chqrlie: To be honest: I actually was not. But the idea is quite appealing. At least it would pacify SO and many other forums. And then we care about the near and middle east. Well, at least people here don't kill each other.
Comment: Try compiling. `struct *A` is not valid.
Comment: It is rather simple: C is pass-by-value. If you want to modify an object in the caller, you have to pass a point to it. It that object is a point, the argument has to be a pointer to that pointer, of course.
Comment: `malloc(struct A);` is incorrect, try `malloc(sizeof(struct A));`
Comment: @chqrlie: maybe SO should require compiler warnings enabled and resolved for a C question.
Comment: @Olaf: that would help many programmers indeed. IMHO most warnings should be enabled by default.  Alas, from my experience here, newbies would be at a loss trying to fix the code to silence the warnings, and would still post the same code here with different headings: *Why the compiler gives warning XXXX?*
Comment: @chqrlie: That still would help us to get more precise diagnostic messags than "why does not code not run?" ...
Comment: @Olaf: yes indeed.  What about an automated downvote for questions without an MCVE, with `-Wall` warnings, with random indentation or chaotic style...
Comment: @chqrlie: Feel free to implement such a system. Although there is no general rule about that. Iff you solved that problem, you are a good candidate for a Nobel Price.
Comment: @Olaf: the Turing award is enticing, but it requires a lot more work and insight than this little hopeless challenge `;-)`.  I'm anal about style, correctness, coding rules etc. but not at all qualified for any such advanced academic work.
Comment: @Olaf: I realize you were thinking of the Nobel Peace Price... There is a long list of disputes one would need to solve: C style starters like TABs vs. spaces, K&R / java / GNU braces, `i++` vs. `++i`, `sizeof(x)` vs. `sizeof x`, `C` vs. `C++`, Mac vs. PC, Wndows vs. Linux, emacs vs. vim and a few more deeply rooted conflicts.
Answer: Yes, you are right. You just need to pass a pointer to struct to change the fields inside the structure variable. This is because you are not changing the address but the value stored inside the structure var pointed to by the pointer.
If you need to allocate memory or change the address pointed to by the pointer and if that needs to be reflected in the calling function then your second function holds good.
Comment: Thank you for your comment!
Answer: Yes, you're right.
If you want pass a structure to function that have to change some of its fileds you need the pointer to the struct so the called function knows where the structure is in memory and can access/change the fileds:
void foo(struct a *pStruct)
{
    pStruct->field1 = 0;  //this field will be read modified.
}

Now if you want allocate a structure you have to pass the pointer:
struct Mystruct *ptr;
...
AllocMyStruct(&ptr);
ptr->field1 = 0;

AllocMyStruct can allocate memory so ptr will point to a freshly (dynamically) created struct:
AllocMyStruct(Mystruct **p)
{
    *p = malloc(sizeof(struct Mystruct));
    if (p==NULL)
        Error();
}

A pointer is a variable exactly as all others, so you can assign a value to it. Passing the address of a pointer is like to pass the address of an int or float to allow variable modification from inside a different function.


How can I add objects Cbook to my class CBooks without using lists

Question: Cbooks has an atribute "CTeam[] Teams" and it is of fixed size (8). If I want to add objects to it using this in the Main:
    CBook A1 = new CBook("Title1", "Author1");
    CBook A2 = new CBook("Title1", "Author2");

    CBooks ArrayOfBooks = new CBooks(8);
    ArrayOfBooks.Add(A1);
    ArrayOfBooks.Add(A2);

then position 0 and 1 are ocuppied, and the positions from 2 to 7 are null. What I want to do is, using a variable "int aux=0", count the ocupied positions like this:
for (int k = 0; k < NumberOfTeams; k++)
                {
                    if (Teams[k].Name=="")
                        Aux += 1;
                }

So, Aux in this case would be 2, then I want to do "Teams[Aux] = A" so that A would be in the position 2 and now I should have three objects in my array. But I'm getting "Index out of bound"
Comment: What is the code of `CBooks` class specially its `Add` method?
Answer: Your implementation then should look similar to this:
public class Program
{
    public static void Main(string[] args)
    {
        Element a = new Element("A");
        Element b = new Element("B");

        MyArray array = new MyArray(8);

        array.Add(a);
        array.Add(b);

        Console.WriteLine(array.Count()); //2 Elements are in the array
    }
}

//Sample element class.
public class Element{

    public readonly String MyString;

    public Element(String myString){
     MyString = myString;
    }
}

//Sample array class.
public class MyArray{

    private readonly Element[] myArray;
    private int count; //Use a property here

    public MyArray(int size){
        //Be careful -> check if size is >= 0.
        myArray = new Element[size];
    }

    public bool Add(Element element){
        if(myArray.Length == count) // return false if no more elements fit.
            return false;

            myArray[count] = element;
            count++;

        return true;
    }

    public int Count(){
     return count;
    }

}

So there is no need for creating an extra count loop. Your "count" variable in "MyArray" class holds always the correct value.
Anyway the implementation or use case of this code is a little bit clunky.
Why are you cant use directly a more safe list or something. That would be a better solution.
Answer: What do you need CBooks for? From what I understand, it's just an array of 8 CBook objects so why not use CBook[]?
CBook A1 = new CBook("Title1", "Author1");
CBook A2 = new CBook("Title1", "Author2");

CBooks[] ArrayOfBooks = new CBook[8];
ArrayOfBooks[0] = A1;
ArrayOfBooks[1] = A2;

int aux = 0;
for (int k = 0; k < ArrayOfBooks.Length; k++)
{
    //break the loop because we know there are no more books
    if (ArrayOfBooks[k] == null)
        break;
    aux++;
}

The question doesn't cover what the variables NumberOfTeams and Teams are for but could those be added to the implementation of CBook?
Comment: With this implementation for counting you have a problem with the correctness ;)
What if you have the following:

ArrayOfBooks[0] = A1;
ArrayOfBooks[1] = A2;
ArrayOfBooks[3] = A3; // or something.

Your loop counts only 2 elements not 3 causing by the early "break".
So you need something like:
for(...){
...
if(ArrayOfBooks[k] != null)
aux++;
...
}


Is there the exact same frequency-multiple between any-2 successive keys in any keyboard-instrument?

Question: The pattern of key arrangement in harmonium/keyboard/piano is like this:
, where I can see 2-types of condition between 2 successive keys.
1: black to white (or white to black) (say their freq. (Hz) is X-times different)
2: white to white (say their frequency is y-times different)
(3: There is no 2 black side by side)
Now is x = y ? i.e the frequency-multiplier between any-2 successive keys are same?
I can't conclude this by judging it through ear; because just like each x sounds the same to each y;  from this pattern, if I play only the white-keys; still I sense there difference as the same (i. e m=n); and if I play only the black-keys, I sense (hear) their difference as same, too (i.e. u=v).
(what a bizarre illusion!!! hats of to who designed the scale)
Now any 1 of them is correct. which one?
P.S. As well I'm not a musical person and never learnt music. so please elaborate/hyperlink about terminologies.
Comment: Isn't this where 12edo (12et) comes in? But not the same *frequency difference* but *ratio*. Frequency difference just can't work.
Comment: That would be more in line with what you're trying to establish.
Comment: The downvotes are likely coming from the fact that you'd invented an idea and then asked about that idea, rather than asking directly about the underlying relationship between notes.  It is also quite hard to follow since your graphic and wording seems to be related to the physical distance between keys on the keyboard -- which is both varied and meaningless from a theoretical standpoint -- instead of with regard to actual notes.
Comment: There is also zero innate different between white notes and black notes; it's purely to aid playing, which is why other instruments played differently do not have such an obvious distinction between adjacent semitones.  There are even keyboards where every key is physically identical.  TL;DR: Make fewer assumptions, and start your questions from a more basic level while you learn!
Comment: As for the ratio of 2: A note and its octave differ by a factor of two.  In your diagram, the white key furthest to the left has a frequency that is 1/2 of the white key 3rd from the right, etc.
Comment: U and v cannot be the same frequency distance apart, as u is a minor third whilst v is a major second. The idea is that any interval that is the same as another will have the same relative pitch differential ( if I've phrased it correctly).
Comment: Could you help what to search about  that 'ratio'?
Comment: @Tim please feel free to edit my question to make it more useful.
Comment: @Tim thanks you've understood correctly what I was trying to tell. Should I replace all the "frequency difference" with "frequency multiple"?
Comment: I've improved the question. Still any cause for downvote? I'm not seeking any upvote, I'm just asking for the cause behind this downvote.
Comment: @MatthewRead please feel free to edit the question to make it useful; I had no intention to make any new theory... I've just asked my query, and maybe what I'm thinking as an illusion for me, is merely a poor-observation. However I've got my answer and ticked it. If declaring it as a community wiki is helpful, I could do that.
Answer: In almost all cases the tuning standard for modern keyboards is 12-tone equal temeperament.  This has the feature that the frequency ratio between two successive (chromatic) notes is 2^(1/12) approximately 1.05946309435. Our ears, to a good approximation, hear pitch as the logarithm of the frequency, so each black-to-white (or white-to-black, or between two adjacent white keys w/o a black between them) seems like the same step size.
Due to the characteristics of their strings, in practice the tuning of pianos does not exactly conform to 12-TET, in order that the pianos actually sound good.
Most synthesized sounds more accurately conform to the standard.
Comment: Whilst this answer relates well to modern 12edo tuned instruments, it's actually not a complete answer. More to come, I expect. Even pianos are not tuned to agree with this!
Answer: Another thing to consider about pianos is that most of the notes have multiple strings. I believe each string is also tuned slightly differently to make the notes fit better in relation to different key signatures.
Comment: Check your information source. I think eac of the 2 or 3 strings on a particular note need to be the same pitch, otherwise there will be some beating occurring, which is not necessarily a good sound for a piano note.


Use 2D matrix as indexes for a 3D matrix in numpy?

Question: Say I have an array of shape 2x3x3, which is a 3D matrix. I also have a 2D matrix of shape 3x3 that I would like to use as indices for the 3D matrix along the first axis. Example is below.
Example run:
>>> np.random.randint(0,2,(3,3)) # index
array([[0, 1, 0],
       [1, 0, 1],
       [1, 0, 0]])

>> np.random.randint(0,9,(2,3,3)) # 3D matrix
array([[[4, 4, 5],
        [2, 6, 7],
        [2, 6, 2]],

       [[4, 0, 0],
        [2, 7, 4],
        [4, 4, 0]]])
>>> np.array([[4,0,5],[2,6,4],[4,6,2]]) # result
array([[4, 0, 5],
       [2, 6, 4],
       [4, 6, 2]])

Comment: How does the shape of 2D array relate to that of 3D one?
Comment: It has the same 2D shape, but is only 2D. So the 3D array has the same shape NxN as the 2D array, but has more "layers".
Comment: Are your 2 different matrices repeated numbers like the example? Otherwise, you would need to give more information about how you want the output to look. For example, what do the 0's and 1's mean to you?
Comment: This is currently too broad. Please clarify more about what the output is doing, I can think of at least three different methods to use those three 2D arrays to get that result
Comment: @MatthewMage Use random numbers than those repeated numbers. That is bound to confuse people.
Comment: The 0's and the 1's represent indices the retrieve a value from the "layer" of the 3D matrix.
Comment: @Divakar Is there an easy way to use MathJax here?
Comment: Try : for 2D - `np.random.randint(0,2,(3,3))` and for 3D - `np.random.randint(0,9,(2,3,3))`. And then you could show us the expected output.
Comment: Are you essentially just "masking" the first array of 1's using the array of 0's and 1's with the replacement mask as the second?
Comment: @MatthewMage you would need the column,row, and T you want... a "0" could be the first row and column of the first T, but what do the other 0's mean?
Comment: Input: http://i.imgur.com/X8H6K6N.png
Output: http://i.imgur.com/kQjcLCI.png
Comment: @EastonBornemeier Yes, in a way. Doing a "composite" of multiple layers.
Comment: @MatthewMage Don't post screenshots. Those can't be copied and run. Do something like `Sample run` from my post and show us the expected output. Feel free to edit the question accordingly.
Comment: In this particular case, you can use np.where
Comment: @MatthewMage If it's worth the trouble, for the index array, you can use : `np.random.randint(0,4,(3,3))` and `np.random.randint(11,99,(4,3,3))` for the values array, for the benefit of the readers. Just to clarify on people assuming that you only have 0s and 1s in the index array.
Comment: @Divakar I added some clarification and removed those images. Sorry about that, I'm quite new to SO. Let me know if anything else should be changed.
Comment: @MatthewMage As I said `np.random.randint(0,4,(3,3))` for index array and `np.random.randint(11,99,(4,3,3))` for values array/3D matrix alongwith the expected output would be the best thing for future readers. I guess, it's okay, because it seems your problem has been solved.
Comment: @MatthewMage Took the liberty to edit the text on shape info to match up with the sample data. Hope that looks okay.
Comment: @Divakar yes, thanks.
Answer: It seems you are using 2D array as index array and 3D array to select values. Thus, you could use NumPy's advanced-indexing -
# a : 2D array of indices, b : 3D array from where values are to be picked up
m,n = a.shape
I,J = np.ogrid[:m,:n]
out = b[a, I, J] # or b[a, np.arange(m)[:,None],np.arange(n)]

If you meant to use a to index into the last axis instead, just move a there : b[I, J, a].
Sample run -
>>> np.random.seed(1234)
>>> a = np.random.randint(0,2,(3,3))
>>> b = np.random.randint(11,99,(2,3,3))
>>> a  # Index array
array([[1, 1, 0],
       [1, 0, 0],
       [0, 1, 1]])
>>> b  # values array
array([[[60, 34, 37],
        [41, 54, 41],
        [37, 69, 80]],

       [[91, 84, 58],
        [61, 87, 48],
        [45, 49, 78]]])
>>> m,n = a.shape
>>> I,J = np.ogrid[:m,:n]
>>> out = b[a, I, J]
>>> out
array([[91, 84, 37],
       [61, 54, 41],
       [37, 49, 78]])

Answer: If your matrices get much bigger than 3x3, to the point that memory involved in np.ogrid is an issue, and if your indexes remain binary, you could also do:
np.where(a, b[1], b[0])

But other than that corner case (or if you like code golfing one-liners) the other answer is probably better.
Answer: There is a numpy function off-the-shelf: np.choose.
It also comes with some handy broadcast options.
import numpy as np
cube = np.arange(18).reshape((2,3,3))
sel = np.array([[1, 0, 1], [0, 1, 1], [0,1,0]])

the_selection = np.choose(sel, cube)

>>>the_selection
array([[ 9,  1, 11],
       [ 3, 13, 14],
       [ 6, 16,  8]])

This method works with any 3D array.
Comment: I've updated the answer to generate a 3D array with the exact dimensions as OP, this works as well. np.arange generates a range of values, so that you can see for yourself from which layer the value is selected. OP's title suggests that he is interested in a general case, but uses an example of a 3D array with first axis=2 ('Say I have an array of shape 2x3x3'').
Comment: This is the best answer. I'm not sure of the performance of choose versus ogrid, but the cleanliness is unbeatable
Comment: Can you edit your code to work with the shape mismatch? This method does not work based on the OP's problem.
Comment: In case someone else finds this post, np.choose works perfectly fine for OP's problem, as here illustrated with a range, rather than a random 3D array for clarity. However, in the case of a binary 2D array, and a two-layered 3D array, Daniel F' s smart answer using np.where is faster.
Comment: No it does not work and what range are you talking about? The OP has a variable with shape (2,3,3). If you try to run your code with a non-cube it breaks.


AC dimmer using micropython

Question: I want to control AC Light Dimmer using Micro Python with ESP8266. I am not getting any libraries or examples related to this.Could anyone please help me with this
Thanks in advance!
Comment: Have you thought of connecting a servo to the dimmer knob and just using some basic servo control
Comment: Have you found an arduino example that outlines the hardware, wiring and the logic? If so, that should give you a starting point for your own design.
Answer: Actually, it depends on which type of AC dimmer you have. I would expect something like RobotDyn AC dimmer:
Robodyn AC dimmer
In this case the regulation is not so easy like in the case of standard DC PWM (please don't let youself being confused by PWM pin, it is not real PWM). This module is standard triac dimmer which needs controlled dimming process (see this schematics).
The way how regulation works is based on the fact that you know when AC sine goes through zero (twice per period). Therefore there is Z-C input pin. When voltage goes through zero, you open triac for a while and cut off part of sine. Thats about regulation.
Wave regulation image
And this is what your dimmer driver shall do. This is not easy task in micropython as it requires to involve interrupts. You can see following code which I tried on HW and which was "working":
from machine     import Timer, Pin
from micropython import alloc_emergency_exception_buf
from math        import acos, pi

class Dimmer:
    def __init__(self, pwm_pin, zc_pin, fpulse = 4000):
        alloc_emergency_exception_buf(100)
        self._cnt    = 0
        self._freq   = 0
        self._timer  = Timer(2)
        self._mode   = Timer.ONE_SHOT
        self._pwm    = Pin(pwm_pin, Pin.OUT)
        self._fpulse = fpulse
        self._ppulse = 100.0 / fpulse + 0.11
        self._zc     = Pin(zc_pin,  Pin.IN)
        self._val    = 1
        self._zc.irq(trigger = Pin.IRQ_RISING | Pin.IRQ_FALLING, handler = self._zeroDetectIsr)

    def _zeroDetectIsr(self, pin):
        if 0 == self._freq:
            self._pwm.on()
            return
        if 0 > self._freq:
            self._pwm.off()
            return

        self._cnt += 1

        if 1 == self._cnt:
            self._timer.init(freq = self._freq, mode = self._mode, callback = self._dimmDelayIsr)

    def _dimmDelayIsr(self, _timer):
        if 1 == self._cnt:
            self._pwm.on()
            self._timer.init(freq = self._fpulse, mode = self._mode, callback = self._dimmDelayIsr)
        else:
            self._pwm.off()

        self._cnt = 0

    @property
    def value(self):
        return self._val

    @value.setter
    def value(self, p):
        p = min(1, max(0, p))

        if not self._val == p:
            self._val = p
            p         = acos(1 - p * 2) / pi

            if p < self._ppulse:
                f = -1
            elif p > 0.99:
                f = 0
            else:
                f = 100 / (1 - p)

            self._freq = int(f)

        return self._val

Just note that unlike transistor, triac holds opened state till voltage on it drops to 0, so you can even use just short pulse to open it.
Use of driver is then simple:
from dimmer import Dimmer
dimmer = Dimmer(4, 2)
dimmer.value = 0.3

Unfortunately, micropython on ESP32 is locking interrupts quite often, so whole stuff works only when nothing is happening around. Most visible problems was around print function which was sometimes able to block for several AC sine periods, what caused visible bulb blinking. Unfortunately I would expect something similar in the case of WiFi communication.
The conclusion here is that the best solution is to use some cheep AVR based board and write code in C++ which will just care about dimming and nothing else. Such board can be connected to ESP board over I2C bus and ESP only sends command to set dimmer value.
Answer: Apart from the fact that this code is not very explanatory, it does not (immediately) work. The line:
self._zc.irq(trigger = Pin.IRQ_RISING | Pin.IRQ_FALLING, handler = self._zeroDetectIsr)

is confusing. What is meant (I suppose) is that the trigger = Pin.IRQ_RISING or trigger = Pin.IRQ_FALLING. So the line must be:
self._zc.irq(trigger = Pin.IRQ_RISING , handler = self._zeroDetectIsr)

or
self._zc.irq(trigger = Pin.IRQ_FALLING, handler = self._zeroDetectIsr)

In both cases this program works well.
See also my topic https://forums.raspberrypi.com/viewtopic.php?p=2118520&hilit=dimmer#p2118520

AC dimmer using micropython


Terence Tao, Analysis 1. Exercise 5.3.2. Real Numbers and Cauchy Sequences.

Question: Let $ x = \lim_{n\rightarrow\infty}a_n, y = \lim_{n\rightarrow\infty}b_n$, and $ x' = \lim_{n\rightarrow\infty}a'_n$ be real numbers. Then $xy$ is also a real number. Furthermore, is $x=x'$, then $xy = x'y$.
Here is my attempt.
We need to show that $xy = \lim_{n\rightarrow\infty}a_n b_n$ is a real number.
from the hypothesis we know that $a_n$ and $b_n$. are eventually $\delta$ -steady sequences for every $\delta> 0 $. so we can choose $a_n$ and $b_n$ to be eventually $\sqrt{\epsilon}$-steady sequences.
since $(a_n)_{n=1}$ is eventually $\sqrt{\epsilon}$-steady, we know there is an $N \geq 1$ such that $d(a_n,a_m) < \sqrt{\epsilon}$  for every $n,m > N$. By a similar argument we can say the same for $(b_n)_{n=1}$.
by proposition 4.3.7 (h).
$d(a_nb_n,a_mb_m) < \sqrt{\epsilon}|b_n| + \sqrt{\epsilon}|a_n| + \epsilon $
From here i am not sure where to go, I am pretty sure i am going the right way, as this sort of resembles the definition of a cauchy sequence that is eventually $\sqrt{\epsilon}|b_n| + \sqrt{\epsilon}|a_n| + \epsilon $-close. I think I require something that just involves epsilon.
The second part of the question I havent attempted yet, but I thought I'd include it just in case anyone would like to lend a helping hand.
by the way propostion 4.3.7 (h). states that if x and y are $\epsilon$-close and z and w and $\delta$ close then xz and yw are $(\epsilon|z| + \delta|x| + \epsilon \delta$)-close.
EDIT.
A real number is defined to be an object of the form $ x = \lim_{n\rightarrow\infty}a_n$, where $a_n$ is a cauchy sequence of rational numbers.
Comment: Then you'll need to give a context for what LIM means.
Comment: The capital LIM as oppose to lim is used as a crutch to introduce limits, sorry for not accepting edits.
Comment: If you're using this definition, then actually a real number is an equivalence class of Cauchy sequences of rational numbers.
Comment: Thanks, would any of you guys happen to know where i have messed up?
Comment: $ \lim n \rightarrow \infinity a_n b_n  $
Comment: is how its defined in  the text.
Answer: ${\bf 1.}$ Let $a.$ and $b.$ be two Cauchy sequences of rational numbers. Then
$$a_mb_m-a_nb_n=a_m(b_m-b_n)+b_n(a_m-a_n)$$
and therefore
$$|a_mb_m-a_nb_n|\leq |a_m|\>|b_m-b_n|+|b_m|\>|a_m-a_n|\ .\tag{1}$$
Since Cauchy sequences are bounded there is a common bound $C>0$ for the $|a_n|$ and the $|b_n|$. Let an $\epsilon>0$ be given. Then there is an $N\in{\mathbb N}$ such that the two sequences are ${\epsilon\over 2C}$-steady for $n\geq N$. On account of $(1)$ this implies that
$$|a_mb_m-a_nb_n|\leq C{\epsilon\over 2C}+C{\epsilon\over2C}=\epsilon\qquad(m, \>n\geq N)\ ,$$
which proves that the sequence $c_n:=a_nb_n$ $\>(n\geq1)$ is Cauchy, whence defines a real number.
${\bf 2.}$ A similar argument, using the inequality
$$|a_n'b_n-a_n b_n|\leq C\>|a_n'-a_n|\ ,$$
proves that $x'y\sim xy$ when $x'\sim x$.
Comment: Why is every answer being downvoted?
Comment: Thanks for the clear answer, i never organised a bounty before, i think i have just awarded it to you.... so yeah, thanks!
Answer: Multiplication of Cauchy Sequences
Real numbers are being defined as Cauchy sequences rational numbers.  We can multiply two sequences of numbers to get another sequence.  Will it also be Cauchy?

Lemma: If $a_n$ and $b_n$ are Cauchy, then $a_n b_n$ is also Cauchy

In the case of the real numbers, Cauchy sequences are not just close, they are guaranteed to have a limit. I don't quite remember how the proof goes.

Lemma: If $a_n$ and $b_n$ are Cauchy with limits $x$ and $y$, then $a_n b_n$ is Cauchy with limit $xy$

Finally there is a question of whether two different sequences can represent the same number?  What about:
$$  1- \frac{1}{n} \hspace{0.25in}\text{ vs }\hspace{0.25in} 1 + \frac{1}{n} $$
In your case you just want to subtract the Cauchy sequences, and get $$xy - x'y = (x - x')y = 0\cdot y = 0$$
However $\mathbf{0}$ here means "a Cauchy sequence converging to $0 \in \mathbb{Q}$".  So all the steps here need to be checked carefully.  Can you do that?

Comment In real life sequences are definitely not Cauchy, e.g. $(-1)^n$.  Or in reality $(-1)^{f(n)}$ where $f(n)$ is something totally random and may chance over time.

Think about it for a little bit, for very large $n > M$, then $a_M - \epsilon < a_n < a_M + \epsilon$ and a similar statement for $b_n$.  Then:
$$
(a_m - \epsilon)(b_m - \delta) < a_n b_n < (a_m + \epsilon)(b_m + \delta)  $$
The error term is like $(\epsilon b_m + \delta a_m) + \delta \epsilon$ which is Tao's proposition.  How big is this error?
$$ (\epsilon (b_N + \delta) + \delta (a_M + \epsilon)) + \delta \epsilon
= (\delta a_M  + \epsilon b_N) + 3\delta \epsilon$$
This is getting rather expensive I suspect $\epsilon^\ast = \delta a_M  + \epsilon b_N$.

Summary: to multiply two Cauchy sequences $a_nb_n$ and get to be $\epsilon$-close to $xy$, we must truncate much further than to get $a_n$ to be $\epsilon$-close to $x$ or
$b_n$ to be $\epsilon$-close to $y$.
Answer: Proof Part 1 - Cauchy Sequences are Bounded
Let $\{a_n\}$ be a Cauchy sequence of rationals.  Let $\epsilon>0$.  Observe there exists $N \in \mathbb{N}$ such that for all $n,m>N, |a_n - a_m| < \epsilon$.  Consider the ball $B_\epsilon(a_n)$ which contains $a_m$ for all $m>N$.  Therefore consider the points $\{a_1, a_2, \ldots, a_N\}$.  These points possibly lie outside $B_\epsilon(a_n)$.  Consider now the set of distances $\{\epsilon, d(a_n,a_1), d(a_n,a_2), \ldots, d(a_n,a_N)\}$ and let $M$ be the maximum element of this set.  Then $B_{M+1}(a_n)$ certainly contains all points of the sequence, hence the sequence is bounded.
Proof Part 2 - Product of Cauchy sequences is Cauchy
Let $\{a_n\}$ and $\{b_n\}$ be Cauchy sequences of rationals.  By the proof of part 1, we know that each sequence is bounded, therefore let $A = \sup_n \{|a_n|\}$ and $B = \sup_n\{|b_n|\}$.  If both $A = B = 0$ then define $A' = B' = 1$, otherwise let $A' = A$ and $B' = B$.   We want to check that for all $\epsilon>0$ there exist $N \in \mathbb{N}$ where if $m,n > N$ then $|a_nb_n - a_mb_m| < \epsilon$.  There exists $N_1, N_2 \in \mathbb{N}$ where if $n,m > N_1$ then $|a_n - a_m| < \frac{\epsilon}{A'+B'}$ and $m,n > N_2$ yields $|b_n - b_m| < \frac{\epsilon}{A'+B'}$.  Let $N = \max\{N_1, N_2\}$.  For $n,m > N$ we have
\begin{eqnarray*}
|a_nb_n - a_mb_m| & = & |a_nb_n - a_nb_m + a_n b_m - b_nb_m| \\
& \leq & |a_nb_n - a_nb_m| + |a_nb_m - a_mb_m| \\
& \leq & |a_n|\cdot |b_n - b_m| + |b_m|\cdot|a_n - a_m| \\
& < & A' \cdot \frac{\epsilon}{A'+B'} + B \cdot \frac{\epsilon}{A'+B'} \;\; =\;\; \epsilon.
\end{eqnarray*}
Proof Part 3 - $a_nb_n \to xy$
The argument is similar to part 2.  Let $\{a_n\}$ and $\{b_n\}$ be Cauchy sequences of rationals such that $a_n \to x$ and $b_n \to y$.  Then $\{a_nb_n\}$ is a Cauchy sequence of rationals.  Let $\epsilon >0$.  Let $N_1, N_2 \in \mathbb{N}$ such that for $n>N_1$ then $|a_n - x| < \frac{\epsilon}{A'+|y|}$ and $n>N_2$ yields $|b_n - y| < \frac{\epsilon}{A'+|y|}$, where $A = \sup_n \{a_n\}$ and $A'$ as defined in part 2.  Let $N = \max\{N_1, N_2\}$ and $N>N$. We then find
\begin{eqnarray*}
|a_nb_n - xy| & = & |a_nb_n - a_ny + a_ny - xy| \\
& \leq & |a_nb_n - a_ny| + |a_ny - xy| \\
& \leq & |a_n|\cdot |b_n - y| + |y|\cdot |a_n - x| \\
& < & A'\cdot \frac{\epsilon}{A' + |y|} + |y|\cdot \frac{\epsilon}{A'+|y|} \;\; =\;\; \epsilon.
\end{eqnarray*}
Proof Part 4
Let $\{a_n\}, \{b_n\}, \{a_n'\}$ be rational Cauchy sequences where $a_n \to x, \; b_n \to y,$ and $a_n' \to x'$.  Suppose $x = x'$ and consider
\begin{eqnarray*}
xy - x'y & = & \lim_{n\to \infty} a_nb_n - \lim_{n\to\infty}a_n' b_n \\
& = & \lim_{n\to\infty} a_nb_n - a_n'b_n \\
& = & \lim_{n\to\infty} (a_n - a_n')b_n \\
& = & (\lim_{n\to\infty}a_n - \lim_{n\to\infty}a_n')\cdot \lim_{n\to\infty} b_n \\
& = & (x-x')y \;\; =\;\; 0.
\end{eqnarray*}
Comment: Does someone want to explain to me why this was down voted?
Comment: Your answer is impressive. I upvote you. :)
Comment: Thanks Guillaume!  It's much appreciated.  I do however would like to know people's reasons for down voting.  It would be petty if it were merely about the bounty...


Get Offline Installation ID (Windows 8 or similar)

Question: Is it possible to get the Windows Offline Installation ID (OfflineInstallationId was found in slmgr.vbs)?
This can be achieved on the command-line with:

slmgr.vbs /dti

This returns the Installation ID without spaces or dashes, is it possible to retrieve this in C#?
I want to eventually have each block of the ID (there are 9 blocks, 7 numbers in each block) in their own textboxes on a form.
There are 9 blocks, each with 7 numbers
I looked around, but couldn't find any examples for C#.
Answer: This is possible by querying the WMI (Windows Management Instrumentation)'s Win32_WindowsProductActivation (XP and below) or SoftwareLicensingProduct (Vista or higher) class:
Requires these namespaces to be declared:

System
System.Collections.Generic
System.Management
System.Text

Declare those namespaces at the top of your codefile with using, as per se:
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

then use the following code in a function:
ManagementScope Scope;
Scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT OfflineInstallationId FROM SoftwareLicensingProduct");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
    //Do whatever with the Offline Installation ID here.
}

I noticed that because I used Windows 8.1's 'refresh' feature once, my WMI returned two Offline Installation IDs for me, therefore this should be something you need to consider (the first Offline Installation ID is the valid one):

You may want something similar to this:
static string getOfflineInstallId()
{
    ManagementScope Scope;
    Scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
    Scope.Connect();
    ObjectQuery Query = new ObjectQuery("SELECT OfflineInstallationId FROM SoftwareLicensingProduct");
    ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

    foreach (ManagementObject WmiObject in Searcher.Get())
    {
        if (WmiObject["OfflineInstallationId"] != null)
            return WmiObject["OfflineInstallationId"].ToString();
    }
    return ""; //Making the compiler happy.
}

As mentioned earlier, SoftwareLicensingProduct with OfflineInstallationId only works on Windows versions newer than Vista (e.g, Vista, 7, 8, 8.1, and 10), therefore if you (or the users of your program) wish to use it on XP or earlier, you may be able to use the following, but however as I do not have access to XP I am unable to test this:
ObjectQuery Query = new ObjectQuery("SELECT GetInstallationID FROM Win32_WindowsProductActivation");

If you want to separate each block of the ID and insert into a TextBox into a Windows Form (WinForm), you can use the below code:
string installId = getOfflineInstallId();
StringBuilder sb = new StringBuilder();
bool fRun = false;
for (int i = 0; i < installId.Length; i++)
{
    if (i % 7 == 0)
    {
        if (fRun)
            sb.Append('-');
        else
            fRun = true; //Stops a '-' being added at the 1st position.
    }
    sb.Append(installId[i]);
}
idTextBox.Text = sb.ToString();

Something like this:

Further to this, you'll also need to reference the System.Management libraries by right-clicking on References in Solution Explorer, clicking on Add New Reference, and adding System.Management and System.Management.Instrumentation to the project:

The project used in this example can be downloaded here (requires Visual Studio 2013 or higher).
Comment: Thank you for the code, but I stand on the tube.
Is it possible that you can make the the code a little easier for me, please?
I would like this as a Windows Forms :-)
Comment: I'm very sorry, but I stand a little on the tube. I added the code in WinForms but with error. Do you have maybe the project file that I can see what was wrong? I'm absolutely beginner, I can write only simple stuff in C# but this one is to high for me :-( Thank you and sorry for that but you have a nice solution for WinForms :-)
Comment: @user2422690 What do you mean 'on the tube'? What is the error exactly?. See my edit.
Comment: I meant "on the tube" should be an adage (from a website with adages (German -> English), I don't really understand where to add the code :-( I used the References in Solution Explorer, the items are selected and active. I get following error: "ManagementScope' is a namespace but is used like a type".
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81195/discussion-between-cybermonkey-and-user2422690).
Comment: See my edit. I feel as if you need to consult some good programming books before you continue with your project. Your other questions also have the same result; you get an answer but don't realise what the code does, although it does *what you asked*. You should really have an understanding of the question's subject before asking it.
Comment: Thank you very much. I try to read some books and code, but I wrote so far simple programs.
Comment: @user2422690 Please accept my answer by clicking the green tick next to the voting buttons. You can directly execute the `slmgr.vbs /ipk` command, adding the `MultipleActivationKey` to the `string` object, providing you already have the `MultipleActivationKey`. Ask a new question for this, and I'll answer it.
Comment: OK, Currently I can't create a new question on stackoverflow, message: "You have reached your question limit". I would be happy if I can ask you again :-) Thanks again
Comment: @user2422690 You're currently question-banned since you've asked too many low-quality questions (the system automatically does this). Edit some of your questions (***don't** add fluff!*), and perhaps users will upvote your questions and thus left you out of the question ban.
Comment: OK, thanks for the info, I must look. Is it possible to change the ID? I found WMI Manager and I see the ID under Class Details -> Instances :-) A buddy has a problem with his ID and he can't activate his Windows 8.1 again by phone. He needs a new ID to activate again without new installation.
Comment: @user2422690 No, it's not possible to change the ID.
Answer: Notice, you should also check the Name Or ApplicationID.
If you installed office, you will get two or more OfflineInstallationIds.
Check the Name contains Windows or check the ApplicationID equals 55c92734-d682-4d71-983e-d6ec3f16059f
PS: I dont know if the AppliactionID changes between diffrent version of Windows. I did some Google search and found it seems a static value.
Comment: It appears to be static. I've tested with Windows 10, Server 2008 R2, Server 2012 R2, and Server 2016. So it's probably been static since at least the 7 days.


How to display a busy indicator in a shiny app?

Question: Note : I have read almost all the discussions on this object in shiny googlegroups and here in SO.
I need an indicator that shows the shiny server is busy. I have tried shiny-incubator, however, the problem is that I can't set a max for progress bar.
I don't want something like this : https://shiny.rstudio.com/gallery/progress-bar-example.html
What I need is something that:

shows a busy indicator message and bar (i.e just a simple animated bar, do not need to show a filling bar) as long as the server is calculating
it is shown in no matter which tab you are viewing. (not only in the related tab, but on top of the tabset)
Answer: Update 2018: Currently there is a great package to help you display loaders: shinycssloaders (source: https://github.com/andrewsali/shinycssloaders)
I've been looking for this as well. Most people suggest a conditional panel like so:
conditionalPanel(
            condition="!($('html').hasClass('shiny-busy'))",
            img(src="images/busy.gif")
)

You could always give yourself more control and create the conditional handling (maybe depending on more stuff) like this in your ui.R:
div(class = "busy",
    p("Calculation in progress.."),
    img(src="images/busy.gif")
)

where some JavaScript handles the showing and hiding of that div:
setInterval(function(){
  if ($('html').attr('class')=='shiny-busy') {
    $('div.busy').show()
  } else {
    $('div.busy').hide()
  }
},100)

with some extra css you could make sure your animated busy image gets a fixed postion where it will always be visible.
In any of the above cases i found that the "shiny-busy" condition is somewhat imprecise and unreliable: the div shows for a split second and disappears while computations are still going on...
I found a dirty solution to fix that problem, at least in my apps. Feel free to try it out and maybe someone could give an insight to how and why this solves the issue.
In your server.R you'll need to add two reactiveValues:
shinyServer(function(input, output, session) {

    # Reactive Value to reset UI, see render functions for more documentation
    uiState <- reactiveValues()
    uiState$readyFlag <- 0
    uiState$readyCheck <- 0

then, in your renderPlot function (or other output function where computations go on), you use these reactive values to reset the function:
output$plot<- renderPlot({

    if (is.null(input$file)){
        return()
    }
    if(input$get == 0){
        return()
    }

    uiState$readyFlag

    # DIRTY HACK:
    # Everytime "Get Plot" is clicked we get into this function
    # In order for the ui to be able show the 'busy' indicator we
    # somehow need to abort this function and then of course seamlessly
    # call it again.
    # We do this by using a reactive value keeping track of the ui State:
    # renderPlot is depending on 'readyFlag': if that gets changed somehow
    # the reactive programming model will call renderPlot
    # If readyFlag equals readyCheck we exit the function (= ui reset) but in the
    # meantime we change the readyFlag, so the renderHeatMap function will
    # immediatly be called again. At the end of the function we make sure
    # readyCheck gets the same value so we are back to the original state

    isolate({
        if (uiState$readyFlag == uiState$readyCheck) {
            uiState$readyFlag <- uiState$readyFlag+1
            return(NULL)
        }
    })

    isolate({plot <- ...})

    # Here we make sure readyCheck equals readyFlag once again
    uiState$readyCheck <- uiState$readyFlag

    return(plot)
})

Answer: Alternatively, you can use shinycssloaders package https://github.com/andrewsali/shinycssloaders
library(shiny)
library(dplyr)
library(shinycssloaders)

ui <- fluidPage(
  actionButton("plot","plot"),
  plotOutput("Test") %>% withSpinner(color="#0dc5c1")
)

server <- function(input, output, session) {

  data <- eventReactive(input$plot,{
    rnorm(1:100000)
  })

  output$Test <- renderPlot({
    plot(data())
  })

}

shinyApp(ui = ui, server = server)

Comment: Also, if you don't have dplyr loaded for the pipe %>%, you can use `withSpinner(plotOutput("Test")) `
Comment: This won't work with a proxy update I think, only on the initial ui render?
Comment: works like a charm! even buried within a `renderUI({ withProgress(..., {plotOutput(...) %>% shinycssloaders::withSpinner()})})`
Answer: Using waiter
library(shiny)
library(waiter)

ui <- fluidPage(
  use_waiter(),
  actionButton("plot","plot"),
  plotOutput("Test")
)
server <- function(input, output, session) {
  w <- Waiter$new(id = "Test")

  data <- eventReactive(input$plot,{
    w$show()
    rnorm(1:100000)
  })

  output$Test <- renderPlot({
    plot(data())
  })
}
shinyApp(ui = ui, server = server)

Answer: I found using fadeIn() as opposed to show() helps mitigate this blinking occurence:
setInterval(function(){
                     if ($('html').attr('class')=='shiny-busy') {
                          setTimeoutConst = setTimeout(function(){
                                $('#loading-page').fadeIn(500);
                             }, delay);
                      } else {
                          clearTimeout(setTimeoutConst );
                          $('#loading-page').hide();
                      }
              },10)

Answer: The busy div also appears for split seconds for the latest versions of shiny, even though no apparent calculations are going on (it was not an issue in older versions). Shiny seems to be regularly in its busy-mode for a short time. As a solution (complementing the above discussion), one can include another 2nd delayed validation of the shiny-busy html class for the conditional handling. The JavaScript-part would look something like that (example also includes check for two different div.busy-states depending on the reactive textit):
      if( ($('html').attr('class')=='shiny-busy') ){
                setTimeout(function() {
                if ($('html').attr('class')=='shiny-busy') {
                    if($('#textit').html()!='Waiting...' ){
                        $('div.busy1').show()
                    }
                    if($('#textit').html()=='Waiting...'){
                        $('div.busy2').show()
                    }
                }
                },1000)
              } else {
                $('div.busy1').hide()
                $('div.busy2').hide()
              }
            },100)