Difference between a process signal mask, blocked signal set, and a blocked signal?

Question: Learning about signals, and I was wondering about the subtle differences between the process signal mask, a blocked signal set, a signal handler, and a blocked signal.
The questions involve (on Debian):

sigprocmask(2)
sigsetops(3) related functions

Each process has it's own signal mask (a long which contains the signals being blocked). And a signal set can be obtained by calling sigprocmask(2) with a NULL argument for the *set variable, will result in the old process mask to be put into *oldset, unchanged:
#include <string.h>
#include <signal.h>

void show_signals(const sigset_t exmask)
{

    int exsignals[43];

    exsignals[0] = SIGABRT;
    exsignals[1] = SIGALRM;
    exsignals[2] = SIGBUS;
    exsignals[3] = SIGCHLD;
    exsignals[4] = SIGCONT;
#ifdef SIGEMT
    exsignals[5] = SIGEMT;
#else
    exsignals[5] = -1;
#endif

    exsignals[6] = SIGFPE;

#ifdef SIGFREEZE
    exsignals[7] = SIGFREEZE;
#else
    exsignals[7] = -1;
#endif

    exsignals[8] = SIGHUP;
    exsignals[9] = SIGILL;
#ifdef SIGINFO
    exsignals[10] = SIGINFO;
#else
    exsignals[10] = -1;
#endif

    exsignals[11] = SIGINT;
    exsignals[12] = SIGIO;
    exsignals[13] = SIGIOT;

#ifdef SIGJVM1
    exsignals[14] = SIGJVM1;
#else
    exsignals[14] = -1;
#endif
#ifdef SIGJVM2
    exsignals[15] = SIGJVM2;
#else
    exsignals[15] = -1;
#endif

    exsignals[16] = SIGKILL;
#ifdef SIGLOST
    exsignals[17] = SIGLOST;
#else
    exsignals[17] = -1;
#endif

#ifdef SIGLWP
    exsignals[18] = SIGLWP;
#else
    exsignals[18] = -1;
#endif

    exsignals[19] = SIGPIPE;
    exsignals[20] = SIGPOLL;
    exsignals[21] = SIGPROF;
    exsignals[22] = SIGPWR;
    exsignals[23] = SIGQUIT;
    exsignals[24] = SIGSEGV;
    exsignals[25] = SIGSTKFLT;
    exsignals[26] = SIGSTOP;
    exsignals[27] = SIGSYS;
    exsignals[28] = SIGTERM;
#ifdef SIGTHAW
    exsignals[29] = SIGTHAW;
#else
    exsignals[29] = -1;
#endif
#ifdef SIGTHR
    exsignals[30] = SIGTHR;
#else
    exsignals[30] = -1;
#endif
    exsignals[31] = SIGTRAP;
    exsignals[32] = SIGTSTP;
    exsignals[33] = SIGTTIN;
    exsignals[34] = SIGTTOU;
    exsignals[35] = SIGURG;
    exsignals[36] = SIGUSR1;
    exsignals[37] = SIGUSR2;
    exsignals[38] = SIGVTALRM;
#ifdef SIGWAITING
    exsignals[39] = SIGWAITING;
#else
    exsignals[39] = -1;
#endif

    exsignals[40] = SIGWINCH;
    exsignals[41] = SIGXCPU;
    exsignals[42] = SIGXFSZ;
#ifdef SIGXRES
    exsignals[43] = SIGXRES;
#else
    exsignals[43] = -1;
#endif

    int exsignals_n = 0;

    for (;exsignals_n < 43; exsignals_n++) {
        if (exsignals[exsignals_n] == -1) continue;
        static char *exsignal_name;
        exsignal_name = strsignal(exsignals[exsignals_n]);
        switch(sigismember(&exmask, exsignals[exsignals_n]))
        {
        case 0: break;
        case 1: printf("YES %s\n", exsignal_name); break;
        case -1: printf("could not obtain signal\n"); break;
        default: printf("UNEXPECTED for %s return\n", exsignal_name); break;
        }
    }
}
const sigset_t getmask(void)
{
        static sigset_t retmask;
        if ((sigprocmask(SIG_SETMASK, NULL, &retmask)) == -1)
                printf("could not obtain process signal mask\n");

        return retmask;
}

At the beginning of my program, I realize that the process signal mask, has not blocked any signals. I then place a signal handler into the program.
static void sig_abrt(int signo)
{
    printf("Caught SIGABRT\n");
}

int main(void)
{
    show_signals(getmask());

    signal(SIGABRT, sig_abrt);

    show_signals(getmask());

    return 0;
}

So now there is a signal handler for SIGABRT, but if I were to call sigprocmask(2) again, as above, SIGABRT will not be in the process signal mask. I tried checking with sigismember(3), but the process signal mask will only be modified once I have called sigaddset(3) or another function which modifies the signal mask.
If I block SIGABRT with sigaddset(3), will the signal handler sig_abrt not receive the call when the SIGABRT is delivered? Does it mean that the signal mask affects which signals are delivered? What is the difference?
Also, is there a way to block a signal in a process without using the sigsetops(3) and sigprocmask(2) functions?
Comment: I remember finding a good wikipedia article that had information on the types of signals.
Answer:
Each process has it's [sic] own signal mask (a long which contains the signals being blocked)

Well, no. The signal mask is actually thread-specific. (In a multithreaded program, you must use pthread_sigmask() to manipulate the signal mask for the current thread; in a single-threaded program, you can use sigprocmask().)
Also, it's not "a long". It is of type sigset_t, which might be an array, structure, or union type. In any case, one should consider it simply as an unordered bit set, one bit per signal.

So now there is a signal handler for SIGABRT, but SIGABRT will not be in the process signal mask.

Correct. Whether or not you have assigned a signal handler or not, does not affect the signal mask at all.

If I block SIGABRT with sigaddset(3), will the signal handler sig_abrt not receive the call when the SIGABRT is delivered? Does it mean that the signal mask affects which signals are delivered? What is the difference?

If all your threads block SIGABRT, it will not be delivered until either the signal is unblocked (removed from the signal mask). If the signal is consumed using sigwait(), sigwaitinfo(), or sigtimedwait(), the signal handler will not be invoked at all.
A short summary:

Signals can be directed to a process group (kill() with pid == 0 or pid == -pgid), a specific process (pid), or a specific thread in a specific process (pthread_kill() within the same process, tgkill system call in Linux in general).
If a signal is directed to a process group, each process in that group receives "a copy" of the signal.
The signal mask defines whether signals are blocked, or delivered immediately.
In each process, each signal

can have a signal handler, or
be ignored (SIG_IGN "handler"), or
have the default disposition (ignored (Ign), terminates the process with (Core) or without (Term) a core dump; or it can stop (Stop) or continue (Cont) the execution of the target thread or process). See man 7 signal for details.

If some, but not all threads, block a signal, and the signal is not targeted to a specific thread, the kernel directs the signal to one of the threads that are not blocking the signal (at random).
There are two ways of catching a signal:

Using a signal handler. The signal gets delivered to a signal handler only when the signal is not blocked. If the signal is blocked, the delivery of the signal is pending until not blocked (or caught by the other option below).
sigwait(), sigwaitinfo(), or sigtimedwait(). These functions check if any signals are pending, and if so, "catch" it. The set of signals they check is defined by a function parameter of sigset_t type.

When the kernel sends/forwards a signal to a process, it first checks if the process has a thread that is not blocking that signal. If there is such a thread, it delivers it via that thread. (If the signal has a signal handler, that signal handler gets invoked in that thread; otherwise, the effect is dictated by the signal disposition.)
If the signal is blocked, the kernel leaves it pending for the process.
If the process calls sigwait(), sigwaitinfo(), or sigtimedwait() with the pending signal in the specified signals set, it receives the information on that signal, and the signal is caught. (It will no longer be pending, and it will not cause a signal handler to be invoked; it is "consumed".)
If the process changes its signal mask, so that the pending signal becomes unblocked, it is delivered by the kernel (just as if it was sent at that point in time).

Also, is there a way to block a signal in a process without using the sigsetops(3) and sigprocmask(2) functions?

No. (You can implement your own sigsetops() and a syscall wrapper for sigprocmask(), but that's about it.)

Here is an example program, example.c, you can use for exploring signal handlers, catching signals, and the signal mask, in a single-threaded process:
#define  _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>

/* Async-signal safe write-to-standard error function.
   Keeps errno unchanged. Do not use stderr otherwise!
*/
static int wrerrpp(const char *ptr, const char *end)
{
    const int  saved_errno = errno;
    ssize_t    chars;

    while (ptr < end) {
        chars = write(STDERR_FILENO, ptr, (size_t)(end - ptr));
        if (chars > 0)
            ptr += chars;
        else
        if (chars != -1) {
            errno = saved_errno;
            return EIO;
        } else
        if (errno != EINTR) {
            const int  retval = errno;
            errno = saved_errno;
            return retval;
        }
    }

    errno = saved_errno;
    return 0;
}

/* Write the supplied string to standard error.
   Async-signal safe. Keeps errno unchanged.
   Do not mix with stderr!
*/
static int wrerr(const char *ptr)
{
    if (!ptr)
        return 0;
    else {
        const char *end = ptr;
        /* strlen() is not async-signal safe, so
           find the end of the string the hard way. */
        while (*end)
            end++;
        return wrerrpp(ptr, end);
    }
}

/* Write the supplied long to standard error.
   Async-signal safe. Keeps errno unchanged.
   Do not mix with stderr!
*/
static int wrerrnum(const long  value)
{
    unsigned long  u = (value < 0) ? (unsigned long)-value : (unsigned long)value;
    char           buf[40];
    char          *ptr = buf + sizeof buf;
    char *const    end = buf + sizeof buf;

    do {
        *(--ptr) = '0' + (u % 10uL);
        u /= 10uL;
    } while (u > 0uL);

    if (value < 0)
        *(--ptr) = '-';

    return wrerrpp(ptr, end);
}

/* Async-signal safe variant of strsignal().
   Only covers a small subset of all signals.
   Returns NULL if the signal name is not known. */
static const char *signal_name(const int signum)
{
    switch (signum) {
    case SIGHUP:    return "HUP";
    case SIGINT:    return "INT";
    case SIGQUIT:   return "QUIT";
    case SIGKILL:   return "KILL";
    case SIGSEGV:   return "SEGV";
    case SIGTERM:   return "TERM";
    case SIGUSR1:   return "USR1";
    case SIGUSR2:   return "USR2";
    case SIGCHLD:   return "CHLD";
    case SIGCONT:   return "CONT";
    case SIGSTOP:   return "STOP";
    default:        return NULL;
    }
}

/* Signal handler that reports its delivery immediately,
   but does nothing else.
*/
static void report_signal(int signum, siginfo_t *info, void *ctx)
{
    const char *sname = signal_name(signum);

    wrerr("report_signal(): Received signal ");
    if (sname)
        wrerr(sname);
    else
        wrerrnum(signum);

    if (info->si_pid) {
        wrerr(" from process ");
        wrerrnum(info->si_pid);
        wrerr(".\n");
    } else
        wrerr(" from kernel or terminal.\n");

}

/* Install report_signal() handler.
*/
static int install_report_signal(const int signum)
{
    struct sigaction  act;

    memset(&act, 0, sizeof act);

    sigemptyset(&act.sa_mask);

    act.sa_sigaction = report_signal;
    act.sa_flags = SA_SIGINFO;

    if (sigaction(signum, &act, NULL) == -1)
        return errno;

    return 0;
}

int main(void)
{
    sigset_t    mask;
    siginfo_t   info;
    const char *name;
    int         signum;

    if (install_report_signal(SIGINT) ||
        install_report_signal(SIGCONT)) {
        const char *errmsg = strerror(errno);
        wrerr("Cannot install signal handlers: ");
        wrerr(errmsg);
        wrerr(".\n");
        return EXIT_FAILURE;
    }

    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR1);
    sigaddset(&mask, SIGUSR2);
    sigaddset(&mask, SIGHUP);
    sigaddset(&mask, SIGTERM);
    sigprocmask(SIG_SETMASK, &mask, NULL);

    printf("Process %ld is ready to receive signals! Run\n", (long)getpid());
    printf("\tkill -USR1 %ld\n", (long)getpid());
    printf("\tkill -USR2 %ld\n", (long)getpid());
    printf("\tkill -HUP  %ld\n", (long)getpid());
    printf("\tkill -TERM %ld\n", (long)getpid());
    printf("in another terminal; press Ctrl+C in this terminal; or press Ctrl+Z and run\n");
    printf("\tfg\n");
    printf("in this terminal.\n");
    fflush(stdout);

    /* Almost same as blocked mask, just without SIGUSR1 and SIGUSR2. */
    sigemptyset(&mask);
    sigaddset(&mask, SIGHUP);
    sigaddset(&mask, SIGTERM);

    do {
        do {
            signum = sigwaitinfo(&mask, &info);
        } while (signum == -1 && errno == EINTR);
        if (signum == -1) {
            const char *errmsg = strerror(errno);
            wrerr("sigwaitinfo(): ");
            wrerr(errmsg);
            wrerr(".\n");
            return EXIT_FAILURE;
        }

        name = signal_name(signum);
        if (name)
            printf("main(): Received signal %s from ", name);
        else
            printf("main(): Received signal %d from ", signum);

        if (info.si_pid == 0)
            printf("kernel or terminal.\n");
        else
            printf("process %ld.\n", (long)info.si_pid);
        fflush(stdout);

    } while (signum != SIGTERM);

    return EXIT_SUCCESS;
}

Compile it using for example
gcc -Wall -O2 example.c -o example

I suggest you prepare two terminals. In one terminal, run the compiled program, using
./example

and observe its output. It will be something like

Process 843 is ready to receive signals! Run
       kill -USR1 843
       kill -USR2 843
       kill -HUP  843
       kill -TERM 843
   in another terminal; press Ctrl+C in this terminal; or press Ctrl+Z and run
       fg
   in this terminal.

The KILL and STOP signals cannot be caught. KILL will always kill the process, and STOP will always stop ("pause") the process.
If you press Ctrl+C in that terminal, the kernel will send an INT signal to the process. (This will be delivered via the report_signal() signal handler.)
If you press Ctrl+Z in that terminal, the kernel will send a STOP signal to the process. The shell detects this, pushing ./example under job control, and lets you input new shell commands. The fg command brings ./example back to foreground, with the shell sending it the CONT signal, so that ./example will continue execution.
USR1 and USR2 signals are blocked, so they are never delivered to the report_signal() signal handler.
HUP and TERM signals are also blocked, but they are received by the main thread via sigwaitinfo().
The program exits, when it receives a TERM signal.
Comment: @seanlum: Your example program had other issues -- especially using `printf()` in a signal handler, which is a no-no: it simply may not work in some cases, while it might work just fine on most cases, as `printf()` is not an async-signal safe function as listed in [`man 7 signal`](http://man7.org/linux/man-pages/man7/signal.7.html) -- so I added an example program that uses safe and sound approaches, for you to experiment upon. Happy investigations!
Comment: I believe sigset_t is an 'unsigned long'
    /usr/include/x86_64-linux-gnu/asm/signal.h:typedef unsigned long sigset_t

And, thank you very much for this explanation. Very detailed and thorough.
Comment: @Zub: Thanks for pointing out the formatting errors. I applied those I made, but kept the one by OP (marked [sic]). The one I skipped was not an error: it indeed should be *"a long"* and not *"along"*, since `long` is the name of the type implied by OP.
Comment: @seanlum: On x86_64. Linux runs on a large number of architectures. Making an assumption that `sigset_t` is of `unsigned long` type would make your code strictly limited to x86-64 and x86-64-like architectures. This is to say, the type is `sigset_t`, and you must treat it as an opaque bit set type, and not as an integer type. My point is, claiming it is a long is incorrect, even though *it happens to be `long`* on some architectures.
Comment: Thank you for the clarification, that has changed the way I see variables now.
Comment: It is possible to manage signals synchronously with signalfd() and a call to select() or poll().


ASDM unable to launch device manager from

Question: I can't access to my Cisco asa 5505 from my Windows 7 64bit.
The problem is that i can connect on it using the ASDM from another PC (WinXP 32bit), and i can connect using my win7 64bit to another Cisco ASA5505.
I guesse this a java/windows security problem.
I have disabled my Win 64 bit firewall, but no success.
I get many jdk and jre installed on my win7 64bit:
C:\Program Files (x86)\Java\jre6\
C:\Program Files (x86)\Java\jdk1.6.0_41\

C:\Program Files\Java\jre6\
C:\Program Files\Java\jdk1.6.0_41

I tried also to modify the java path into link of ASDM, for example:
"C:\Program Files (x86)\Java\jre6\bin\javaw.exe" -Xms64m -Xmx512m -Dsun.swing.enableImprovedDragGesture=true -classpath lzma.jar;jploader.jar;asdm-launcher.jar;retroweaver-rt-2.0.jar com.cisco.launcher.Launcher

or
"C:\Program Files\Java\jre6\bin\javaw.exe" -Xms64m -Xmx512m -Dsun.swing.enableImprovedDragGesture=true -classpath lzma.jar;jploader.jar;asdm-launcher.jar;retroweaver-rt-2.0.jar com.cisco.launcher.Launcher

Here is log of ASDM:
    Java Web Start 1.6.0_41
Utilisation de la version JRE 1.6.0_41-b02 Java HotSpot(TM) Client VM
Répertoire d'accueil de l'utilisateur = C:\Users\my_session_name
----------------------------------------------------
c:   effacer la fenêtre de la console
f:   finaliser les objets de la file d'attente de finalisation
g:   libérer la mémoire
h:   afficher ce message d'aide
m:   imprimer le relevé d'utilisation de la mémoire
o:   déclencher la consignation
p:   recharger la configuration du proxy
q:   masquer la console
r:   recharger la configuration des politiques
s:   vider les propriétés système et déploiement
t:   vider la liste des threads
v:   vider la pile des threads
0-5: fixer le niveau de traçage à <n>
----------------------------------------------------
Application Logging Started at Sat Apr 13 18:04:26 GMT+01:00 2013
---------------------------------------------
java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.sun.deploy.net.proxy.AbstractAutoProxyHandler.getJSFileFromURL(Unknown Source)
    at com.sun.deploy.net.proxy.AbstractAutoProxyHandler.init(Unknown Source)
    at com.sun.deploy.net.proxy.DynamicProxyManager.reset(Unknown Source)
    at com.sun.deploy.net.proxy.DeployProxySelector.reset(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.cisco.launcher.ClassUtil.a(Unknown Source)
    at com.cisco.launcher.ClassUtil.initExecutionEnvironment(Unknown Source)
    at com.cisco.launcher.s.if(Unknown Source)
    at com.cisco.launcher.Launcher.main(Unknown Source)
Local Launcher Version = 1.5.56
Local Launcher Version Display = 1.5(56)
OK button clicked
Trying for ASDM Version file; url = https://192.168.1.254/admin/
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
    at com.cisco.launcher.y.a(Unknown Source)
    at com.cisco.launcher.y.if(Unknown Source)
    at com.cisco.launcher.r.a(Unknown Source)
    at com.cisco.launcher.s.do(Unknown Source)
    at com.cisco.launcher.s.null(Unknown Source)
    at com.cisco.launcher.s.new(Unknown Source)
    at com.cisco.launcher.s.access$000(Unknown Source)
    at com.cisco.launcher.s$2.a(Unknown Source)
    at com.cisco.launcher.g$2.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Trying for IDM. url=https://192.168.1.254/idm/idm.jnlp/
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.cisco.launcher.w.a(Unknown Source)
    at com.cisco.launcher.s.for(Unknown Source)
    at com.cisco.launcher.s.new(Unknown Source)
    at com.cisco.launcher.s.access$000(Unknown Source)
    at com.cisco.launcher.s$2.a(Unknown Source)
    at com.cisco.launcher.g$2.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Perhaps i blocked this ip somewhere without my attention, where can i find if the ASA ip is blocked from jre ?
Can some one help me ?
Thank you
ASDM 7.1 (1)
Windows seven 64 bit
Many jre/jdk 6
Comment: Can you try 32 bit java? 64 bit always causes issues for me...
Comment: @GerryEgan This what i did, i used 32bit java as you can see on my answer.
Comment: Sorry, i meant on my question
Answer: I just deleted the ASDM cache and everything goes ok.
Cache path:
%USERPROFILE%\.asdm

Answer: Java 7 doesn't work with the ASDM launcher. Java 6 does. A workaround is to browse to the Cisco ASA's IP address... https://ip.of.asa
From there, you can run the ASDM as a "Web Start" application. Don't bother with the ASDM launcher.
Comment: But, i'm not using java7 !?


Regular Expression to Match non HTML tags

Question: This is my RegEx that matches all HTMl tags. https://regex101.com/r/bDHD9z/3
<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>

I want to create opposite one, which matches everything but HTML tags. This regex should match inside and link from following text:
inside
">link

I have tried to use negative lookahead https://regex101.com/r/bDHD9z/4 It doesn't really do the opposite as I would expect.
HTML parser as some people suggested is not possible as I need to match other criteria using Regex
Comment: Get a HTML parser. Working XML or HTML with a regular expression is just asking for brittle code.
Comment: Simply use 'Replace on the match with an empty string, then you have the opposite
Comment: The best way is to use `(*SKIP)(*FAIL)` on the tags.
Comment: @PoulBak I want to use regex for match. If I use it with empty strings, I would not be able to run functions on the matched result and keep the HTML tags.
Comment: @sin I do not understand what you mean by `(*SKIP)(*FAIL)`
Comment: @Robert I do not think that I can use HTML parser as the text could also be something else for example `{value, plural, one {# book} other {# books}}` and I have to match book and books https://github.com/lingui/js-lingui/issues/296#issuecomment-416610667 Let me know if I am wrong.
Comment: Use skip/fail if you're using the PCRE or Perl engines.
Comment: Don't! Please, just don't! I've learned this the hard way and didn't understand why parsing HTML with regex is a terrible idea until I read [this](https://stackoverflow.com/a/1732454/4934172) and [this](https://stackoverflow.com/a/590789/4934172). `I need to match other criteria using Regex` Wouldn't it be easier to use an HTML parser and then use Regex to match whatever left to be matched?
Comment: I do not think so, because I have to pass results to library and I can not do it one by one. As I said I do not have to cover all html tags. The tags are coming from i18n and I only want to add pseudolocalization. There are certain tags that are supported and they are easily testable.
Comment: @AhmedAbdelhameed How is [this answer](https://stackoverflow.com/a/1732454/3390419) any useful? It's a bunch of rubbish.
Comment: @UnbearableLightness It's intended to look like this _in order to emphasize the hell you would go through if you decided to parse HTML with regex_. If you don't like it, [the other answer](https://stackoverflow.com/a/590789/4934172) have a "more gentle" explanation. There are also other good answers in both questions.
Comment: Yeah, I just don't find that answer educational at all. Yeah I agree, some of the other answers in that question are actually useful. The first one should just be removed in my opinion.
Answer: If you can not use a HTML parser, you can try this regex:
(?:>)(?:\s*|([^><]+))(?:<)

https://regex101.com/r/fSbZe9/3
Comment: It does not work if the text is outside HTML tags https://regex101.com/r/fSbZe9/2
Comment: I used this variant `(?:>\s*)([^><\n\r]+\s*)(?:<)` as the text after a new line is not match with the original regex. See example https://regex101.com/r/1n0xHn/1


How to check if redis server is running using Predis library in PHP

Question: I am integrating Redis cache with one of my website, I am using Predis as client side. I have created a static class for initializing.
I need to check if the redis server is running or not.
I have tried so many thins but it did not work, it is not able to catch the exception.
My code is
public static function checkRedisConnection()
{
    self::initialize();
    $client = new Predis\Client();
    try
    {
        $client->connect();
    }
    catch (Predis\Network\ConnectionException $exception)
    {
        exit("whoops, couldn't connect to the remote redis instance!");
    }

    $client->info();
}

The above function in a class is not able to catch the error, instead it is showing the error on whole site.
What to do in this situation?
Answer: Your try / catch block cannot intercept the exception for a very simple reason: the class Predis\Network\ConnectionException doesn't exist, the correct one is Predis\Connection\ConnectionException (see also here)
Comment: Thanks, Yes you are correct, I used catch (Predis\Connection\ConnectionException $exception)


Determining if a subgroup is an ideal

Question: I need some clarification on this problem. These are my answers and I was wondering if they are correct or not. Any help is appreciated.
Determine whether the indicated set A is an ideal in the indicated ring R.
a). $A = \Bbb Q$ in $R = \Bbb R$
$\sqrt3 \in \Bbb R, r \in \Bbb Q, r \sqrt 3 \notin \Bbb Q$ This is not an ideal.
b). $A = 2 \Bbb Z$ in $R = \Bbb Q$
$r = 2 \in 2 \Bbb Z, s = \frac {3}{2}, rs = 3 \notin 2 \Bbb Z $ Not an ideal.
c). $A = {0, 2, 4, 6, 8}$ in $R = \Bbb Z_{10}$
$r=8 \in A, s = 9 \in R, rs = 72 \notin A$. Not an ideal.
Comment: 72 mod 10 = 2$\in A$
Comment: Oh I didn't realize that we have to take the modulus for $rs$.
Comment: don't you like my ultrashort answer? : )
Comment: @janmarqz lol I did. I just fell asleep. Usually everyone is pretty serious on here.
Comment: hehehee, i was crying a river XD
Answer: a) and b) are correct, except that you have to exclude $r = 0$ in a). c) is wrong, as $72 = 2$ in $\mathbb{Z}_{10}$. The given set is an ideal for the same reason $2\mathbb{Z}$ is an ideal in $\mathbb{Z}$: multiplication of a number by an even number always yields an even number.
Answer: (a) and (b) are correct but (c) is wrong. In $\mathbb{Z}_{10}$, the element $72$ is equal to the element $2$ because we are working modulo $10$. This means $rs=72=2\in A$, so your example doesn't work. It actually turns out that $A$ is an ideal in this case.

Determining if a subgroup is an ideal


Armazenar valores representantes do 'sexo' de um usuário em bancos de dados

Question: Tenho algumas duvidas quanto a representação de alguns campos em banco de dados. Como devo armazenar campos como "sexo" em tabelas no banco de dados? Na forma literal "masculino" e "feminino" ou através de números que representam cada sexo como "1" e "2", respectivamente? Esta dúvida se estende a outros campos, por exemplo, há uma necessidade de armazenar a classificação de peso de um objeto em "muito leve", "leve", "médio", "pesado" e "muito pesado". Eu deveria armazenar um numero representante de cada categoria?
Comment: Depende de como vc usar na aplicação. Eu sempre crio uma tabela do tipo Sexo:[id, nome]. Assim tenho ele representado tanto com número como string.
Comment: @RicardoHenrique Como provavelmente são apenas 2 registros ('M' e 'F') você mesmo pode definir o número, e pode ser chave primaria já que nunca vai haver dois números iguais e poderá relacionar com outras tabelas
Comment: @Earendul este id seria dado por mim ou este é um id tipo INTEGER NOT NULL AUTO_INCREMENT usado para ser chave primaria
Comment: @Earendul Eu acho que esse seu comentário vale uma resposta. :) Até porque, armazenar diretamente na forma literal gera dificuldades com localização (apresentação em diferentes idiomas).
Comment: Criar uma tabela para deixar eternamente com 2 registros apenas não seria um tanto quanto inutil ? Não é mais prático, fácil, funcional estabelecer isso via código ? Constante ou Enum ???
Comment: Você vai gastar uma tabela em seu SGDB, terá que fazer a query (selects e os joins), processar a query e o resultado apenas para comprovar algo que você já sabe ? Afinal foi você mesmo que populou a tabela e ela não é alterada...PHP não possui a estrutura Enum, mas podemos facilmente implementa-la desta forma: http://stackoverflow.com/questions/254514/php-and-enumerations
Answer: Depende de cada caso.
O que eu nunca recomendo, mas pode haver exceções, é usar a descrição completa. Não estará errado usar a descrição se tiver um bom motivo para isso. Se não usar a descrição e exista uma que deve ser usada em algumas situações você terá que tratar isso de alguma forma.
Em muitos casos um código basta. Até por força externa, legislação por exemplo, pode ser que o correto seja colocar 1 ou 2 e é só isto que importa. Em outro deve colocar M ou F e não precisa de nenhuma descrição além desta. Então deve usar apenas isto. Ou seja, a coluna já é auto descritiva desta forma.
Mas pode ser que você precise de uma descrição extra. Aí tem três soluções:

Você deixa para uma stored procedure resolver isso ou para a aplicação tratar já que esta descrição não costuma mudar. Muitas pessoas irão criticar esta opção porque o banco de dados não está sendo usado de forma apropriada. Eu concordo com as críticas, mas faço a ressalva que pode haver motivo, especialmente para deixar para a aplicação tratar disto quando a descrição pode mudar dependendo do contexto de execução. Provavelmente não ocorrerá com sexo mas pode ocorrer com outros tipos.
Cria uma tabela auxiliar com as descrições e fazer um relacionamento, uma solução muito comum. Ela é bastante recomendada. Ao contrário do que muitos se esquecem, ainda é necessário outro ponto do banco de dados ou aplicação saber como manipular esta informação e adequadamente se o interesse é receber a descrição do dado. Evidentemente que neste caso um 1 ou 2 será um ID para a tabela referenciada. Este ID costuma ser um número mas não precisa ser, pode ser um caractere e usar o M ou F, parece uma boa chave natural.
Criar uma enumeração, se o sistema usado permite. Alguns criticam o seu uso porque o recurso pode ter limitações. Mas pode resolver bem na maioria dos casos. No fundo é uma forma padronizada do banco de dados de usar uma tabela auxiliar. Ainda terá que fazer algo na recuperação de dados para pegar a descrição.

Como eu disse, eu acho mais organizado e flexível destas formas, especialmente a número 2, assim é a forma normalizada. Mas se quiser facilitar a consulta, dar um pouco mais de performance, então jogar a descrição direto é a solução, assim você já recebe o que quer sem precisar usar artifícios na query.
Mas lembre-se que isso poderá trazer algumas dores de cabeça se tiver alguma razão para alterar estas descrições. Nada que não possa ser resolvido nos casos de dados bem simples como os descritos. Em dados mais complexos pode ser que você nunca poderá desambiguar se houver uma alteração. Não faça isto com nomes de cidades, por exemplo.
Só não vai usar booleano. Já vi isto quando só havia dois valores e está errado.
Tem uma ISO sobre o uso de sexo.
Mais recentemente criaram um conceito de gênero com dados mais flexíveis em que a pessoa pode escolher mais livremente o que ele se considera. Até o momento não foi criado novos sexos e provavelmente não faz sentido ter novos porque é uma questão biológica. Se ele não é mais adequado então deve ser excluído para o gênero tomar lugar.
Coloquei no GitHub para referência futura.
Answer: No caso de informação fixa, como é este o caso. Só existem 3 possibilidades:

Masculino
Feminino
Indefinido (no caso do seu sistema permitir que a pessoa não defina o sexo).

Logo, esses dados são fixos e não precisam de uma tabela em seu banco de dados, isso seria um completo desperdício de recursos.
Crie uma classe com as constantes e pronto.
<?php
abstract class Sexo
{
    const Indefinido = 0;
    const Masculino = 1;
    const Feminino = 2;

   public getStringValue($value)
   {
       switch($value)
       {
           case self::Indefindo:
               return "Indefinido";
           case self::Masculino:
               return "Masculino";
           case self::Feminino:
               return "Feminino";
           default:
               return "Valor não é válido";
       }
   }
}
?>

Quando precisar utilizar basta fazer o seguinte:
<?php
    $meuSexo = Sexo::Masculino;
    //var_dump($meuSexo) => 1

    $string = Sexo.getStringValue($meuSexo);
    //var_dump($string) => Masculino
?>

Comment: Creio que atualmente existam muito mais do que apenas 3 possibilidades, vide o leque de opções do facebook.
Answer: A fim de curiosidade:
No caso de peso de um objeto em "muito leve", "leve", "médio", "pesado" e "muito pesado". Podemos utilizar alguns métodos de estatística pra definir um intervalo.
Portanto se temos 50 produtos, com a seguinte listagem de peso:
1, 1, 1, 3, 4, 4, 5, 5, 6, 6,
7, 7, 7, 7, 7, 8, 8, 8, 9, 9,
10, 10, 10, 10, 11, 15, 16, 16, 16, 17,
18, 18, 18, 18 ,18, 40, 40, 40, 40, 40,
47, 47, 47, 49, 49, 50, 55, 58, 59, 90.

Temos o maior valor como 90 e o menor como 1, portanto nossa amplitude de amostragem é de AA = 89 (90 - 1).
Em seguida calculamos o i, que teoricamente seria a quantidade de agrupamentos que precisamos ter: i = 1 + 3.3 log 50 = 6,6 ~ 7 (arredondamento normal).
Portanto o ideal seria ter 7 classificações de peso, mas pra este exemplo iremos utilizar os 5 já classificados por você, portanto considere i = 5.
Precisamos agora calcular quais serão os intervalos
AA / i = 89/5 = 17,8 ~ 18 (sempre arredondado pra cima).
Muito Leve: 1 |- 19
Leve: 19 |- 37
Médio: 37 |- 55
Pesado: 55 |- 73
Muito Pesado: 73 |- 91
<?php
abstract class Peso
{
   public getStringValue($value)
   {
       if ($value < 19){
          return "Muito Leve";
       }elseif($value < 37){
          return "Leve";
       }elseif($value < 55){
          return "Médio";
       }elseif($value < 73){
          return "Pesado";
       }else{
          return "Muito Pesado";
       }
   }
}
?>


Contingency table

Question: I'm trying to solve a question regarding contingency table as far as I know contingency table show count not densities,and I'm having hard time comprehending this simple table.
My attempts was basically calculating the marginal distribution but the probabilities didn't sum to 1.
for example I tried solving the first question by:
$$
P(A, B) = \int(P(A,B,C)dC
$$
but I'm missing something is $dC$ probabilities or just count?
Contingency table
Comment: Well, yeah this is the given question with table on the right.
Answer: This is discrete.  You just need to add things up, no integrals required.  For the conditional ones you have to scale by the probability of the given event.
In the one that asks for $\Pr(A,B|C=0)$, we see from that table that $\Pr(C=0)=.45$, by adding up all the entries with $C=0$.  We also know that $\Pr(A=1,B=1,C=0)=.05$.  In the new contingency table, the entry for $A=1,B=1$ will be $\frac{.05}{.45}=\frac19$.  The values in the table always have to add up to $1$.
Comment: Ok, if we sum the $C$ column we will get 4 and thus $0.01*4=0.04...$ and by doing so for the rest of the rows the probabilities won't sum to 1, since it was multiplied by 4.
Comment: No, you sum the probabilities.
Comment: I see, can you please suggest some resources or a book chapter to read about this more?
Comment: I don't know anything about these contingency tables per se, but this is just elementary probability theory.  Any book or website that discusses conditional probability will explain it.

Contingency table


How to remove HTML content from REST API response?

Question: I have started to work with REST APIs - specifically JIRA REST APIs.
I'm using the API to get response to a JIRA query but the JSON response I am getting contains lot of HTML chunk inside it.
It is not clean enough as showcased here
How can I use it in such a way to get a proper JSON response?
Comment: I don't see anything obviously wrong with the JSON block in your "here" link. Did you mean that as a demonstration of what was going wrong, or was it meant to be how you wanted it to appear? Please give us an example of exactly what the response looks like, as well as the URL and headers you are using to request it.
Answer: I think, JIRA response in JSON format only if request is successful, if request has any error than it comes in HTML response. actually that html belongs to the JIRA's error page. So correct your request, you will not get any response in HTML fomat. :)


Permission for ASP.NET application on web server to access shared folder on another server

Question: We have a web server (IIS with ASP.NET) that has a web application deployed to it. Users of the web application can use it to upload files. The web application needs to save the files to another server using a Windows share. A virus scanning engine then accesses the Windows share to scan the uploaded file for viruses. The Windows share is on the virus scanning machine.
The problem: neither the web server nor the virus scanning machine are on the same domain. In fact, they are not part of any domain at all. Therefore it is difficult setting up the share so that the web server can write to it.
What is the best way to establish a trust relationship between the web server and the share on the virus scanning machine so that the web server can write to the share on the virus scanning machine?
(PS The web application is running as NETWORK SERVICE - it is possible that this can be changed too.)
Answer: Here's one way you could it:

Create an account on the web server for the web service to run as.
Create an account with the same username and password on the virus scanning machine.
In the NTFS permissions for the shared folder grant the account you created rights to write to the folder.
In the share permissions on the shared folder set "Everyone / Full Control".
Be sure you have good name resolution between the web server and the machine hosting the shared folder.

Edit:
I've never used the "impersonate" functionality that sparks refers to in his answer. I don't think this is going to do what you want anyway, seeing as how there isn't a way for a standalone machine to impersonate an account from another standalone machine (or from a domain that the impersonating machine is not a member of).
Comment: Thanks. One question though: what do you mean by good name resolution? Do you mean DNS, or is it something else?
Comment: Good name resolution would be the ability to consistently resolve the netbios or dns name properly.  DNS is typically the most reliable if that is an option you have.  Otherwise on a small LAN you should almost always successfully resolve netbios names.
Comment: You just want to be sure that the web server can access the File and Print Sharing service on the remote machine via whatever name or IP address your app is using. If you can logon to the web server w/ the account you create and put \\server\sharename in the Start / Run dialog and access the remote server you'll be good to go.
Comment: Ahh yes, ghetto domain.
Comment: @MatthewC: I prefer to call it the "poor man's trust relationship", but yeah, it's "ghetto domain"... *smile*
Answer: If you want authenticated access for the web server machine to the virus scanning machine, you need an account on the virus scanning machine with the proper rights to the share and the filesystem where the share is located.
The application would need to connect to the share using the correct credentials when it is doing the write operation.
Given that the web server isn't going to be able to run the IIS process using the credentials from the virus scanning machine, you likely will need modifications to the application to support authenticated access as you describe. I would recommend using something other than plain old SMB though for a .NET application as the API support for specifying credentials explicitly is somewhat lacking. FTP or SSH might be a good fit.
Alternatively, depending on your security requirements, you may be able to get away with just allowing anonymous WRITE-only access to the virus scanning share and have the web server talk to it unauthenticated. You could use firewall rules or other mechanisms to limit the exposure here from allowing anonymous access.
Comment: Looks like I forgot about the "use the same username and password on both standalone machines" trick. (or as others are calling it the "ghetto domain") :)
Comment: Never underestimate the power of the poor man's trust relationship! *smile*  If I had a dollar for every time it got me out of an ugly authentication situation...


host static files (images) to 3rd party host such as Amazon Cloud. Any modules can facilitate this?

Question: I want host all images files to the cloud, such as amazon s3.
For example, when creating the node, uploaded automatically upload the files to the cloud, and all images path automatically point to the image stored in the cloud.
Any modules facilitate the CDN transition?
Thanks.
Answer: I would go with the CDN module, also checkout the AmazonS3 module.
Comment: but it seems that it won't upload(sync) the files to CDN site automatically.
Comment: Check out the description from the AmazonS3 module for example: "Image styles are delivered first through the private file system, which generates a derivative on S3 and is served from S3 thereafter."
Comment: The CDN module also allows syncing but you need to use File conveyor: http://fileconveyor.org/
Comment: there are issues with image resizing when using S3:  http://drupal.org/node/1291628
Comment: tried CDN module with File Conveyor method, it works but buggy with D7, for example, the ftp username cannot contain "/".
Comment: I've used the CDN module with File conveyor and its worked perfectly for me, of course it won't work perfectly in every setup. Try using another transfer protocol.
Comment: How do you rewrite URL to point to cdn?
Answer: Media Mover supports staging/moving files to Amazon S3, plus complex file workflows.
Answer: Drupal CDN & Static File Server - The Amazon S3 Way is an oldie but a goodie as well
Comment: Also, you may also want to look into the "s3fs" concept where you mount your s3 bucket as a filesystem on your server...linux based anyway.
Comment: make sure to check with your hosting provider if that's supported. We tried that on Pantheon, got it to work but found out later that it broke the daily backup routine.


Displaying Toast message from user defined variable

Question: How do I pass a user variable as a parameter in the Toast object in android studio to display the value of the variable?
Something like this;
Toast.makeText(userVariable,R.id.textField,Toast.LENGTH_SHORT).show();
Thanks
Answer: Use getViewById() to get the Text input as a View, cast it to a TextInputView and then once you've done that, you can call getText().toString() and pass this into the toast.


Why $\int_{\Omega} u \le \max_{\partial\Omega} |u|$?

Question: I believe the image below is sufficient for understanding the problem but if you need more context, everything can be found at page 42 of https://www.math.ucla.edu/~yanovsky/handbooks/PDEs.pdf

I need to know why the absolute value of each integral is less than the absolute value of the maximum in the integration set. Is this a theorem from calculus?
I first thought about the maximum principle for harmonic functions but I don't think $u$ is harmonic and also I don't see how it involves integrals.
Answer: The title of your post is not correct (and not relevant to the body of your question).
I think the result you are looking for is
$$\int_A |f(x)| \, dx \le \max_{z \in A} |f(z)| \cdot \int_A 1\, dx$$
which comes from bounding $|f(x)| \le \max_{z \in A} |f(z)|$ for any $x \in A$.
The integrals in your question are surface integrals, so the bound is the maximum of the integrand on that set, times the volume/area of the surface (that is the $\omega_n \epsilon^{n-1}$ term).


View of organic groups name list with no activity

Question: I'm running a Drupal 7 site, and I want to create a list view of group names with no activity within last 60 days. For example if user have not created any content with in those groups.
Currently groups (OG) hold different content-types/nodes i.e news, galleries, wikis, and discussions.
Can someone please help me achieve this?
Answer: I suggest you to create a custom table with group id and access timestamp. Whenever you are adding a new content to OG, update the table with group id and current timestamp. Then list inactive groups (by calculating current time from your timestamp saved in table), using theme_table function.


How common is it to omit the I in II V I cadences in Jazz?

Question: I was studying the song 'Satin Doll' by Duke Ellington:

And basically, there many II V in different tonalities. The same happens in Charles Mingus's 'Nostalgia in Times Square' (bars 9-11):

In both examples, there are II V cadences in different tonalities, that don't resolve to I. In another song, the II V would most likely resolve to I, but here we don't see a tonic chord.
How common is that in Jazz and what kind of feeling does it give?
Comment: You might want to check this article: http://www.jazzadvice.com/basic-bebop-reharmonization/
Answer: As you know, the II V I progression is the most important progression in jazz. Since there is a very strong root motion of a descending perfect fifth, not only between V and I, but also between II and V, this II-V-progression has become an independent unit, which is frequently used without the need to resolve to the related I chord.
It is important to realize that any dominant chord may be preceded by its related II chord. Since not every dominant chord needs to resolve down a perfect fifth to its related I chord, the same is true for a II-V unit.
If a II-V unit does not resolve to its related I chord, the two most common directions it may take are as follows:

the V chords behave as sequential dominants, e.g. D7 leads to G7, but both chords are preceded by their related II chord, resulting in the progression

| Am7 D7 | Dm7 G7 | ...

the V chord behaves as a secondary dominant for the following II chord, e.g.

| Am7 D7 | Gm7 C7 | ..., where D7 is the V of Gm7.
In Satin Doll, the first two II-V units establish the key, then the Em7-A7 unit resolves to Am7-D7 as explained in point 1 above (A7 => D7), the D7 resolves to G7, which is replaced by its tritone-substitute Db7 finally resolving to C. The Abm7 is just the related II chord of Db7.
Answer: Very common. Playing a ii-V with no I happens for two main reasons and they're related.
The first is back cycling. Back cycling occurs when you have successive ii-Vs that are separated by a tone or a semitone. By far the most common back cycle is iii-VI7-ii-V7-I. Although this is commonly (and correctly) understood in that form, it can also be correctly interpreted as being a back cycle on the ii-V7-I of the key. This alternate interpretation is useful for analyzing another common back cycle: #iv-VII7-iii-VI7-ii-V7-I. The inclusion of the #iv-VII7 in the progression forces the tune (and later the soloist) to, in a short period of time, address the #4 and the #2.
Back cycling is still somewhat common, but it was far more prevalent in bebop. Behold, the back cycle blues:
BbMaj7 | Ami7b5 D7 | Gmi7 C7 | Fmi7 Bb7
Eb7    | Ebmi7 Ab7 | Dmi7 G7 | Dbmi7 Gb7
Cmi7   | F7        | Dmi7 G7 | Cmi7 F7

The most famous example of these changes is Parker's Blues for Alice. People don't play this so often any more; there are lots of reasons for this, but probably the biggest one is that as solos became slower and more lyrical in the post-bebop era, one bar back cycling to modify the key slightly became less and less relevant to creating interesting solos. When people were blasting out hundreds of notes a minute, the back cycle was a good way to get the solos to follow a contour.
A far more general use of the ii-V without the I is tonicization. Tonicization is differentiated from modulation: whereas modulation is the changing of one key to another, tonicization is the suggestion of one key while staying, in the long term, in the original key. Imagine if you will two (very hokey) chord progressions:
C | Fmi7 Bb7  | Eb | % |
And
C | Fmi7 Bb7 | C | % |
In the first example, we've clearly moved on to Eb. There's a tonic and it would be silly for us to suggest, while sitting on Eb for two bars, that we're in anything but Eb.  In the second example, because we're smart jazz musicians, we know that Fmi7 Bb very strongly suggests Eb, but because we're going to C, we're not in Eb; we're somewhere in between. It is necessary to not simply continue playing in C -- that would be horrible -- but so too would be resolving to Eb, since the notes that make for a good resolution to Eb don't make for a good resolution to C nor do they work over Bb7. The result is that you're somewhere in between changing keys and not changing keys, and your note selection needs to suggest that.
That's a whole different kettle of fish, though. Harmony-wise, what's important to note here is just that ii-Vs with no corresponding Is are sometimes used to suggest another key.
NB: There is considerable overlap between back cycling and tonicization. Look at the example I used earlier. In Bb: Emi7b5-A7-Dmi7-G7-Cmi-7-Bb. In this case, Emi7b5-A7 fits the criteria for both tonicization and back cycling, since it is a tone away from a subsequent ii-V and it suggests a key that you aren't currently in. While it completes the ii-V-I with Dmi7, that Dmi7 goes directly to G7 and is therefore better understood not as a tonic but a subdominant.
Comment: An outstanding answer, in my opinion. Welcome to Music.SE and thanks for contributing to the site!
Answer: As a cadence, it's called imperfect - the opposite of perfect, it doesn't quite arrive back at home like most of us expect. In Satin doll, instead, it goes to other ii-Vs which further confound the listener who feels a modulation to another key. It does actually land at the end of the sequence on bar 7. The middle section then moves to subdom F, then modulates to G, bringing us back to, theoretically to start with C.
Answer: It's a system of delayed gratification!  All the more satisfying when you eventually DO reach the tonic.  Quite common in 'standard' tunes, as often played by jazz musicians.


Problem with custom paging in ASP.NET

Question: I'm trying to add custom paging to my site using the ObjectDataSource paging.  I believe I've correctly added the stored procedures I need, and brought them up through the DAL and BLL.  The problem I have is that when I try to use it on a page, I get an empty datagrid.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs" Inherits="developer_PageTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

        <asp:ObjectDataSource ID="ObjectDataSource1" SelectMethod="GetMessagesPaged" EnablePaging="true"
            SelectCountMethod="GetMessagesCount" TypeName="MessageTable" runat="server" >
            <SelectParameters>
                <asp:Parameter Name="DeviceID" Type="Int32" DefaultValue="112" />
                <asp:Parameter Name="StartDate" Type="DateTime" DefaultValue="" ConvertEmptyStringToNull="true"/>
                <asp:Parameter Name="EndDate" Type="DateTime" DefaultValue="" ConvertEmptyStringToNull="true"/>
                <asp:Parameter Name="BasicMatch" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" />
                <asp:Parameter Name="ContainsPosition" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" />
                <asp:Parameter Name="Decoded" Type="Boolean" ConvertEmptyStringToNull="true" DefaultValue="" />
<%--                <asp:Parameter Name="StartRowIndex" Type="Int32" DefaultValue="10" />
                <asp:Parameter Name="MaximumRows" Type="Int32" DefaultValue="10" />
--%>            </SelectParameters>
        </asp:ObjectDataSource>

        <asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AllowPaging="true" PageSize="10"></asp:GridView>

        <asp:Label runat="server" ID="lblCount"></asp:Label>

    </form>

When I set EnablePaging to false on the ODS, and add the commented out StartRowIndex and MaximumRows params in the markup, I get data so it really seems like the data layer is behaving as it should.  There's code in code file to put the value of the GetMessagesCount call in the lblCount, and that always has a sensible value in it.
I've tried breaking in the BLL and stepping through, and the backend is getting called, and it is returning what looks like the right information and data, but somehow between the ODS and the GridView it's vanishing.
I created a mock data source which returned numbered rows of random numbers and attached it to this form, and the custom paging worked so I think my understanding of the technique is good.  I just can't see why it fails here!
Any help really appreciated.
(EDIT .. here's the code behind).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

public partial class developer_PageTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblCount.Text = String.Format("Count = {0}", MessageTable.GetMessagesCount(112, null, null, null, null, null))
    }
}

Comment: Are you doing anything in the code-behind for the page, a shot in the dark have you disabled viewstate.
Comment: Hi! I added the code behind above... nothing much there.
Answer: Wild stab in the dark: What Happens if you set the StartRowIndex DefaultValue to 1?
<asp:Parameter Name="StartRowIndex" Type="Int32" DefaultValue="1" />
<asp:Parameter Name="MaximumRows" Type="Int32" DefaultValue="10" />

Comment: Hi Luhmann.  Those parameters are only for debugging.  When paging is enabled, the ObjectDataSource automatically supplies those to the BLL.  If I disable paging and just want to test the standard databinding, I have to put those in so that the right method is called.  If I put StartRowIndex to 1, I get the first 10 rows, as expected!  But only when EnabledPaging="false".
Answer: hi Johncc I had the same problem and was finally able to crack the culprit last friday at midnight. Gosh man this problem was giving me nightmares and I am glad I fixed it. The solution is simple.
My count method was returing data. But there is some data type mismatch it seems. If I hardcode the count as .
return 16
it would work but if I bind it to a int variable and return the variable it wouldnt work.
If you hardcode as 16 it is a struct system.Int32 datatype but if you return a int variable it is just a Int32 variable. I think the problem lies here.
public int GetsrchCount(BeginDate,EndDate)
{
    int intrec;
    intrec = 23;
    return intrec;
 }

Then after a long search luckily I found this solution some where. I changed the return type of my count method to static int
public static int GetsrchCount(DateTime BeginDate, DateTime EndDate)
    {
        int intrec;
        intrec = 23;
        return intrec;
     }

There is some mismatch in the datatypes. It works like a breeze now

Problem with custom paging in ASP.NET


MySQL query: How to fix Error 1052 (ambiguous column)

Question: I keep getting an error when I run both of the following queries that the CUST_NUM is ambiguous. How can I fix this?
SELECT  INV_NUM, CUST_NUM, CUST_LNAME, CUST_FNAME, INV_DATE, INV_AMOUNT
FROM    CH08_INVOICE i
INNER JOIN CH08_CUSTOMER c1 ON (i.CUST_NUM = c1.CUST_NUM)
WHERE   CUST_BALANCE>=1000;

SELECT CUST_LNAME, CUST_FNAME
FROM CH08_CUSTOMER c1 JOIN CH08_CUSTOMER_2 c2
ON (c1.CUST_LNAME = c2.CUST_LNAME AND c1.CUST_FNAME = c2.CUST_FNAME);

Comment: If your problem was fixed, don't forget to mark one of the answers as correct or comment/edit to tell everyone on how you solved the issue.
Answer: SELECT i.INV_NUM, i.CUST_NUM, i.CUST_LNAME, i.CUST_FNAME, i.INV_DATE, i.INV_AMOUNT FROM CH08_INVOICE i INNER JOIN CH08_CUSTOMER c1 ON (i.CUST_NUM = c1.CUST_NUM) WHERE i.CUST_BALANCE>=1000;

SELECT c1.CUST_LNAME, c1CUST_FNAME FROM CH08_CUSTOMER c1 JOIN CH08_CUSTOMER_2 c2 ON (c1.CUST_LNAME = c2.CUST_LNAME AND c1.CUST_FNAME = c2.CUST_FNAME);

Please check this query
Answer: Ambiguous column means the database don't know which table it must use the column.
Try using
SELECT  INV_NUM, i.CUST_NUM ...

or
SELECT  INV_NUM, c1.CUST_NUM ...

for explicity defining the table.


Atualizar a página quando fechar popup

Question: Como poderei atualizar uma página após fechar um popup? Após o utilizador abrir o popup, eu dou uma serie de opções que alteram a página onde o utilizador abriu o popup e preciso dessa página atualizada apos o utilizador fechar o popup.
Como poderei fazer?
Answer: A função Location.reload() recarrega o documento:
location.reload();

http://www.w3schools.com/jsref/met_loc_reload.asp
Answer: Em javascript há a boa e velha função reload:
location.reload();

E tem a vantagem de funcionar nos principais browsers. :-)
Answer: Utilizei assim:
//principal.htm

//popup.htm

Comment: David explica mais a sua solução, assim você ajuda mais as pessoas.

Atualizar a página quando fechar popup


Change name of 3D section in Product

Question: I've got a Product in CATIA containing several CATParts.
I use the symbol Sectioning in DMU Review Creation to create a section, to cut the product.
This section is called Section.1.
What I'm looking for is a code to take the name from CATPart 1 ( myPartNumber1) and change the name of the section from "section.1" into myPartNumber1.
This is my code so far in vb.NET:
Sub x()

Set productDocument1 = CATIA.ActiveDocument

myPartNumber1 = productNumber1.Product.Products.Item(1).Name
Set selection1 = productDocument1.Selection
selection1.Search("Name='Section.1',all")
selection1.item(1).value.Name = myPartNumber1

End Sub

I get a problem in the last line.
Comment: Please copy and paste your code directly instead of inserting a picture... StackOverflow can format & highlight your code. What is the exact problem you have ? What is the error ?
Answer: Sub CATMain()
Set oprod = CATIA.ActiveDocument.Product
Set TheSections = oprod.GetTechnologicalObject("Sections")
Set mySection = CATIA.ActiveDocument.Product.GetTechnologicalObject("Sections")

Set oSection = oprod.GetTechnologicalObject("Sections")
Set selectionpart = CATIA.ActiveDocument.selection

partcount = selectionpart.Count
    for k = 1 to partcount
            Set selectionpart = oprod.Products.Item(k)
    myPartNumber = CATIA.ActiveDocument.Product.Products.Item(k).Name

    sectioncount = oSection.Count
    MsgBox sectioncount
            for i = 1 To sectioncount
                Set oSection = mySection.item(i)
                oSection.Name = myPartnumber
        Next
    Next

End Sub
PROBLEM:
What I get is that all of my Sections get the name of the first Part in Product
What I need ist: first section gets the name of the first PArt, second sections gets the name of the second Part ...
I've obviously written something wrong in my loops.
THX

Change name of 3D section in Product


Scaling tuples using different scales in Python

Question: I am trying to scale three vectors with three different scale for each of the vectors, and then find the  linear combination of the vectors to find a single point.
The vectors are three corners of a quilateral triangle, and the scales are randomly selected.
w_list = np.zeros(3)
sum = 0
for i in range(3):
    w_list[i] = np.random.random_sample()
    sum += w_list[i]

w = w_list/sum  # scaling weights

corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]

x = 0, 0
for i, e in zip(w, corners):   # w contains the three scales
     x += (i * e[0], i * e[1])

However, when I print x I get a number a vector with 7 points when it should just print one point.
(0, 0, 0.0, 0.0, 0.4682062316923167, 0.0, 0.15138058449552882, 0.26219886362572936)

Comment: add `w` to the code as well.
Answer: While not strictly necessary to solve your problem, it might be useful for you to get accustomed to using numpy to its full potential. It is really very powerful and can speed up all your calculations by a factor of a hundred.
import numpy as np
corners = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3/4))])
weights = np.random.random(3)
weights /= np.sum(weights)  # normalization
x = np.dot(weights, corners)

Comment: Nice. Much better than my more limited numpy answer. This is clearly the way to go if using numpy.
Answer: try the below (using list and tuple as x)
import numpy as np
corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]
w = [1,2,3]
x = [0, 0]
for i, e in zip(w, corners):   # w contains the three scales
     x[0]= x[0] + i * e[0]
     x[1]= x[1] + i * e[1]

print(x)

output
[3.5, 2.598076211353316]

Comment: Thanks @balderman, it works! But, I tried with x[0] += i * e[0] earlier and it didnt work.
Answer: You are currently doing tuple concatenation rather than vector addition (note that the final tuple in your question has 8 rather than 7 numbers). Instead, make your x a numpy array:
import numpy as np

w_list = np.zeros(3)
sum = 0
for i in range(3):
    w_list[i] = np.random.random_sample()
    sum += w_list[i]

w = w_list/sum  # scaling weights

corners = [(0, 0), (1, 0), (0.5, np.sqrt(3/4))]

x = np.array([0.0, 0.0]) #don't want an int array

for i, e in zip(w, corners):   # w contains the three scales
     x += (i * e[0], i * e[1])

print(x) #[0.25691217 0.4105851 ]


Proving the generalized intersection of the interval (0, 1/n) is the empty set?

Question: Prove that the generalized intersection of the interval (0,1/n) is the empty set?
Aka prove that $(0,1) \cap (0, 1/2) \cap (0, 1/3) \cap (0, 1/4) ... = \emptyset$.
I know that I need to prove this by contradiction, by assuming that there exists an x in the intersection and then choosing a positive integer n s.t. 1/n < x.
I'm having trouble putting it all together, especially since I'm supposed to use this fact: For all x in R, there exists k in N s.t. k > x.
When I flip this around, I get that 1/k < 1/x, which isn't what I want. I understand how and why the proof works, I just can't seem to format it with enough rigor.
Answer: Actually it is what you want! You just need to be a bit clever about what to set as $x$.
If you suppose $x_0\in A$ (where $A$ is the intersection) with $x_0>0$, then if we let $x=\frac{1}{x_0}$, there is some $k\in\mathbb{N}^+$ with $k>x\implies k>\frac{1}{x_0}$ which implies that there is some $\frac{1}{k}\in\mathbb{Q}^+$ with $\frac{1}{k}<x_0$.
Comment: I understand how you completed the proof with setting $x$ to be as such, although i am confused and how this proves the intersection to be empty. could you supply some clarification? where is the contradiction?
Comment: to finish, $x_0$ is therefore not in the set $(0,\frac{1}{k})$ and so it cannot be in the intersection. It follows that no $x_0>0$ can be in $A$, hence $A$ is empty.
Comment: i formulated my own proof (https://math.stackexchange.com/questions/2444903/help-finishing-archimedean-property-proof/2444917#2444917) using the concepts in this one. is my proof correct?
Comment: @rover2 Yes. Your proof is equivalent to Dan Rust's proof.
Answer: Suppose there is $x_0 \in A$ where $A$ is the intersection, then there is some $n_0$ where $x_0 = \frac{1}{n_0}$. But then there is some $n > n_0$ that $x = \frac{1}{n} < x_0$, a contradiction.


Empty string supplied as input when parsing HTML in PHP

Question: I'm trying to make a Wordpress plugin, therefore, I'm trying to manipulate my DOM (the post content). Currently I have this code:
<code><?php
function mb_find_my_image( $content ) {
    if( is_home() ) { /* if is home start */

      $dom = new domDocument;
      $dom->loadHTML($content);
      $dom->preserveWhiteSpace = false;

    } /* if is home end */
    return $content;
}
add_filter( 'the_content', 'mb_find_my_image' );
?>
</code>
But I always get the following error:

Empty string supplied as input

I have tried using any other custom string that has html elements and it works. Also I've tried using var_export($content, true ), and this somewhat fixes the problem, but I get errors such as:

Call to a member function getAttribute() on a non-object

What I'm I doing wrong?
I'm running this script on my local computer using WAMP Server.
var_dump($content) gives me:

null
  string post content (actual html that is the post) ... (length=805)
Comment: It seems like you are not passing the parameter correctly. Check where you are calling your function and see what's being passed in.
Comment: @KyleGibbens Could you please tell me how to do that? I'm still new to PHP and Wordpress.
Comment: Inside which file is your `mb_find_my_image` function located?
Comment: I'm not very familiar with Wordpress, but find where the function is being called from (CTRL+F 'mb_find_my_image' on your source code) and var_dump the value passed in. Again, I'm not very familiar with Wordpress. If Wordpress calls the function using that 'add_filter' function, then makes sure your content is valid HTML.
Comment: @dalbaeb this function is located in functions.php file
Answer: I have fixed the problem. The main problem was that I was calling the function (mb_find_my_image) from index.php, after I've removed the calling from index.php everything works as it should.


move files from one device to another

Question: I am trying to automate a remote backup on our centOS server, I run the current command :
nice -n 10 mv -vfb /media/localbackup/* /media/remotebackup/

however when this is ran I get the following error and no files are moved
mv: inter-device move failed: `/media/localbackup/04-21-13' to `/media/remotebackup/04-21-13'; unable to remove target: Is a directory

I have been told it is better to use cp however this won't delete the files afterwards and I need to remove the files upon successful backup.
Comment: Related: [mv: inter-device move makes moving a directory to a directory with same name a different operation?](http://superuser.com/q/215062/87805) at superuser.SE
Answer: I also suggest you using rsync instead of mv, but adding to @Hartmut's answer:
rsync -abmv --remove-source-files /media/localbackup /media/remotebackup/
find /media/localbackup -depth -type d -empty -delete

And 2 additions here:

The -m (--prune-empty-dirs) parameter to rsync, which on my version 3.0.7  protocol version 30 says: prune empty directory chains from the file-list but doesn't do that for some reason. Doesn't error either (not the only one to notice it).
The find command which will delete the empty directories.

now, the reason against cp && rm is that cp might fail half-way through. The next time you want to backup you will be in a weird situation (partially copied files to name the worst case). Also, the next backup will not know what to do with the previously backed up files which were not deleted.
On the other hand rsync covers these aspects just fine.
Also, using a  script (as first answer suggests) to do what rsync already does, but worse, is a no-go (sorry Hauke Laging :-) ). No need to reinvent the wheel here.
Comment: I ended up going for rsync but with an ssh remote server instead, your answer would have been the one I'd have chosen so +rep for you ;)
Answer: I find I often want to do some operation on files, while preserving their directory structure. For this reason I defined a bash function filtercmd. This takes a list of files to operate on as stdin, and as parameters takes the operation (e.g. mv) and the destination directory. Once I've done this I can do things like this as a simple one liner.
filtercmd () {
if [ ! -d "$2" ]; then echo "$2" does not appear to be a directory; return 1; fi
while read f; do
    dir="${f%/*}"
    if [ ! "$dir" = "$lastdir" ]
        then mkdir -p "$2/$dir"; echo "$dir"; lastdir="$dir"; fi
    [ -e "$2/$f" ] || $1 "$f" "$2/$f"; done
}

(cd /media/localbackup && find . | filtercmd "mv -vfb" /media/remotebackup)

This can also be done with rsync. Using rsync's remote protocol can save a lot of bandwidth since the protocol only needs to send changed chunks. However, two advantages of filtercmd over rsync are (1) that you can use your existing mv flags without learning the rsync equivalents and (2) and we can also use filtercmd for more powerful things like:
(z(){ grep . <$1|gzip >$2.gz;};find . -name '*.txt' | filtercmd z ../gz })

Which selectively takes txt files, eliminates empty lines, and gzips them onto the destination directory.
Answer: Your command tries to create an already existing directory. You should make this shell code more robust:
tmpdirname=tmpdir
test -d "/media/remotebackup/${tmpdirname}" &&
  rm -rf "/media/remotebackup/${tmpdirname}"
pushd /media/localbackup/
test -d "$tmpdirname" && { echo Abbruch; exit 1; }
for dir in *; do
  test -d "/media/remotebackup/${dir}" && continue
  mv "$dir" "/media/remotebackup/${tmpdirname}" &&
    mv "/media/remotebackup/${tmpdirname}" "/media/remotebackup/${dir}"
done
popd

This will skip directories which already have been successfully moved.
Comment: @Neo That's an interesting information (would have been interesting as part of the question, too). I recommend to run this `mv` call through `strace` in order to get more precise error messages.
Comment: problem there is the directories don't exist on the remote backup
Answer: I would use rsync command with the --remove-source-files option.
Something like rsync -abv --remove-source-files /media/localbackup/* /media/remotebackup/
Please test before you apply it to your environment.

move files from one device to another


How to auto-generate objects in the Register Model C# ASP.NET MVC 4?

Question: I using the Internet Application template in C# MVC 4 which generates the Account model and controller for you in Visual Studio. This gives me basic form functionality for logging in. I modified the Register class in the Account model to also take a FirstName, LastName, and Email in addition to the username and password. My table with user information is Users. When a user submits their information WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
is ran and it adds the Username to my Users table. So at that point I have my PK Id and Username in the table. My User class definition has a custom object Portfolio. What I am trying to do is when the user registers they get added to the table and then I find that User and set the values for the rest of the data in the table and instantiate the Portfolio object. This would complete my register process.Currently, it adds the user to the table with just the Username adds them to the role and redirects back to index. My var user = _db.Users.Find(userId) is apparently not finding anything for some reason. I even tried to cheat and hardcode the userId because I knew what the next Id would be in the Users table and it still did not modify the table values. FirstName, LastName, Email all remain null in the table and no object is instantiated for Portfolio. I have my context so it should work. I did something similar in my Seed method and it worked fine. I am not sure why it is not working here. Does anyone have suggestions? Thank you.
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model, TeamProject.Models.ProjectDb2 context)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

                var userId = _db.Users
                             .Where(u => u.UserName == model.UserName)
                             .Select(u => u.Id).First();
                var user = _db.Users.Find(userId);
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.Email = model.Email;
                user.Portfolio = new Portfolio
                {
                    Stocks = new List<Stock>
                    {
                    }
                };
                context.Users.AddOrUpdate(user);

                System.Web.Security.Roles.AddUserToRole(model.UserName, "Users");
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }

Comment: You do not appear to be calling `context.SaveChanges` anywhere.
Comment: If it was a snake, it would have bit me. I did something similar in Seed() but you don't have do `SaveChanges` there. Thank you that fixed it!
Answer: As per the above comment:

You do not appear to be calling context.SaveChanges anywhere.
Comment: Marked as answer for you. Appreciate it!


Why can a vuvuzela only play one pitch, while a non-valved bugle can play many?

Question: According to our collective nightmares from the 2010 World Cup Wikipedia, the vuvuzela is a monotone instrument; it famously plays (roughly) the B♭ below middle C.
Why is the vuvuzela restricted to only this pitch, while non-valved bugles can play multiple pitches within the harmonic series?
My question is very similar to Physics behind why a bugle can play several notes, while a whistle only plays one note, but the answers there focus on the fact that a bugle player uses variations in their embouchure and air speed to create different pitches, and these variations are not possible on a whistle.
Yet a vuvuzela seems to have a mouthpiece much like a bugle, which would suggest the ability to have these embouchure and air speed variations and therefore the ability to create different pitches:

So there must be some other difference with the construction of the vuvuzela that prevents it from playing other pitches. What is this difference?
As a subsidiary question, brass players like to say that the instrument only amplifies what they do on their mouthpiece. So if we rigged a trumpet mouthpiece to attach to a vuvuzela, does that mean it could become a multi-pitch instrument?
(I know that this question might blur the line between physics and music. But since such gray-area questions are often allowed here, and since we've already allowed a similar question, I'm assuming this is safely on topic.)
Comment: I think the 'collective nightmare' had more to do with the quality of the English football team than the traditional horn played at the sports events.
Comment: It's entirely possible to attach a trumpet mouthpiece to one end of a hosepipe, a funnel to the other, and play it like a bugle.
Comment: It isn't.  I've hit at least 2 harmonics on this toy.
Answer: Apparently, it is possible to play some melodies on the Vuvuzela, although not in quite the same way as on a trumpet or horn (FAQ). The difference is probably that most football fans are football fans first, taxi drivers/fruit merchants/whatever second, and not professional musicians at all. They can no more use these methods than an ordinary person could get any tone out of a standard trumpet.
Comment: @badjohn I had a toy like that that I could reliably get the seventh harmonic from.  I remember thinking how unusual it sounded, though I didn't appreciate at the time that this was because it was out of tune compared to the notes on the piano.
Comment: Yep.  The shorter and fatter a tube is, the harder it is to play higher harmonics, and the vuvuzela is pretty short and fat.  But like you, I'm sure any good horn or trumpet player could get at least a couple of higher harmonics out of one.
Comment: I remember a toy that was just a flexible tube.  You held one end and spun the other end round to get a note.  It was fairly easy to spin it faster and get the second harmonic.  I could just about reliabley get the third harmonic briefly.  I don't recall ever going above that.
Answer: Oh, it is absolutely possible. I've heard an adventurous trumpet player play a simple melody on it. However, it's not easy and the other notes sound even worse than the one tone. So why bother…


Circle and a line that passes through it

Question: Given a line with equation: $y=ax-3$ that passes through a circle with equation $(x-1)^2+(y-1)^2= 1$. Find the range of values of $a$.
I tried graphing and got: $0<x<2$ and $0<y<2$.
I also tried finding $a$ by substituting $x$ and $y$ into $y=ax-3$
which really confuses me.
Could you help me in solving this problem?
Comment: What happens to the line $y=ax-3$ when $a$ gets really big, and does it pass through the circle? think in terms of the graph
Comment: The line $y=0$ does touch the circle - your circle has center $(1,1)$ and radius $1$. But $y=ax-3$ never actually becomes line $y=0$, it just gets closer and closer to that line. But still if the line is really steep, then it should pass through the circle in two different points. So try imagining $a$ getting smaller and smaller from there - as it gets smaller gradient of line gets smaller, and at some point it must be tangent to the circle. Is that clear?
Comment: well, substitute $y=ax-3$  into $(x-1)^{2}+(y-1)^{2}=1$ and solve the quadratic equation with respect to $a$ and see that for what range of $x$ you  can find $a$ and then I think that you can find the possible range for $a$.
Comment: It doesnt become $y=0$ neither $y=2$ neither $x=0$ neither $x=0$. If it does then it is a tangent to the circle.
Answer: we substitute
$y=ax-3$
in
$(x-1)^2+(y-1)^2= 1$
$(x-1)^2+(ax-3-1)^2= 1$
$(x-1)^2+(ax-4)^2= 1$
$x^2-2x+1+a^2x^2-8ax+16=1$
we have this second degree equation
$x^2(1+a^2)+x(-2-8a)+16=0$
with
$\Delta =(-2-8a)^2-4\cdot(1+a^2)\cdot 16$
if $\Delta <0$
the equation have no solution and the line not intersect the circle
if $\Delta =0$
the equation have one solution and the line is tangent to the circle
if $\Delta >0$
the equation have two solutions and the line intersect the circle in 2 points
$\Delta =4+32a+64a^2-64-64a^2$
$\Delta =32a-60$
so if
$32a-60>0$
$a>\frac{15}{8}$
the line intersect the circle in 2 points
and if
$32a-60=0$
$a=\frac{15}{8}$
the line is tangent to the circle
Answer: The lines with equations $y=ax-3$ all have in common that they intersect the $Y$ axis at $(0;-3).$ Which of those lines intersect the circle with centre $(1;1)$ and radius 1?
The equation of the circle and the (parametric) equation of the line form a system of 2 simultaneous equations with 2 unknowns. One of the equations is nonlinear but the system is easy enough to solve.
At one stage in the solution you will have to use the roots of a quadratic equation. The condition on $a$ that you are looking for, is for the discriminant of that quadratic equation to be nonnegative.
Comment: How do i get the quadratic equation specifically? I'm a 10th grader so I dont quite understand the term "parametric". And also how do I get two unknowns with the circle equation: $(x-1)^2+(y-1)^2=1$ and the line equation: $y=ax-3$? Or does one of them only works with another equation? Thanks!
Comment: If you take the equation of the circle, and replace the (only) occurrence of $y$ in that equation with the expression $ax-3,$ then you get an equation from which the variable $y$ has disappeared and you only need to solve it for the remaining unknown $x.$ Can you solve quadratic equations?
Comment: Of course :) What is the best way to understand linear-algebra? How can i improve?
Comment: You don't need linear algebra for this one. Have you written down the quadratic equation in $x$? In particular, have you got an expression for its discriminant, which involves $a$?
Comment: Another guy passed by and solved it and in addition to your explaination, I guarantee I can solve similar problems.
Answer: Rewrite the system of equations by substituting $y$, giving
$$(x-1)^2+(ax-3-1)^2-1=0=(a^2+1)x^2-(8a+2)x+16.$$
The latter equation has roots when its discriminant is non-negative,
$$(4a+1)^2-16(a^2+1)=8a-15\ge0.$$


Cylindrical limits of integration for a particular triple integral

Question: In cylindrical coordinates, what would be the limits of integration for the triple integral serving to find the volume of the region in $\mathbb R^3$ bounded by:
$x^2 + y^2 = y$ and the sphere of center $O$ and radius $1$, in the first octant?
$\theta$ moves between $0$ and $\pi/2$, and $z$ moves between $0$ and $\sqrt{1 - r^2}$; but what is the behaviour of $r$?
Thanks a lot.
Answer: $x^2+y^2 = y$ describes an infinite cylinder $$x^2 + \left(y - \frac{1}{2}\right)^2 = \left(\frac{1}{2}\right)^2$$
The interior of intersection of two regions is thus given by
$$
   \mathcal{R} = \left\{  x^2 + y^2 + z^2 \leqslant 1, x^2 + \left(y - \frac{1}{2}\right)^2 \leqslant \left(\frac{1}{2}\right)^2, x \geqslant 0, y \geqslant 0, z \geqslant 0 \right\}
$$
which is
$$
     \mathcal{R} = \left\{  x^2 + y^2 + z^2 \leqslant 1, x^2 + y^2 \leqslant y, x \geqslant 0, y \geqslant 0, z \geqslant 0\right\}
$$
Switching to polar coordinates $x = r \cos(\theta)$, $x = r \sin(\theta)$ we have
$$\begin{eqnarray}
   \mathcal{R} &=& \left\{ r^2 + z^2 \leqslant 1, r \leqslant \sin(\theta), 0 \leqslant \theta \leqslant \frac{\pi}{2}, r \geqslant 0, z \geqslant 0\right\} \\
  &=& \left\{0 \leqslant \theta \leqslant \frac{\pi}{2}, 0 \leqslant r  \leqslant \sin(\theta), 0 \leqslant z \leqslant \sqrt{1-r^2}  \right\}
\end{eqnarray}
$$
Therefore the volume
$$\begin{eqnarray}
   \operatorname{Vol}\left(\mathcal{R}\right) &=& \int_0^{\pi/2} \mathrm{d} \theta \int_0^{\sin \theta} r \mathrm{d} r \int_0^{\sqrt{1-r^2}} \mathrm{d} z \\
 &=& \int_0^{\pi/2} \mathrm{d} \theta \int_0^{\sin \theta} r \sqrt{1-r^2} \mathrm{d} r  \\
  &=& \int_0^{\pi/2} \frac{1}{3} \left(1-\cos^3(\theta)\right) \mathrm{d} \theta = \frac{\pi}{6} - \frac{2}{9} \approx 0.301377
\end{eqnarray}
$$
Confirming in Mathematica:
<code>In[1]:= NIntegrate[1,
 Element[xvec,
  RegionIntersection[Cuboid[{0, 0, 0}, {1, 1, 1}], Ball[{0, 0, 0}],
   Cylinder[{{0, 1/2, 0}, {0, 1/2, 1}}, 1/2]]]]

Out[1]= 0.301377
</code>
Comment: Thanks! This is what I did, but I had some error in calculation which made me suspect the r limits.


Taylor series expansion of $(2+3x)^6$

Question: The question is

Find the first 4 terms of de taylor series expansion of $(2+3x)^6$

Is it possible to standard series of $(1+x)^a = 1 + ax + \frac{a(a-1)}{2~!}x^2 +\frac{a(a-1)(a-2)}{3~!}x^3$ ... or do I have to use another method?
Thanks in advance and a nice evening!
Comment: yes, use that. What you you do to adapt your  (2+3x) to this (1+x) pattern ?
Comment: To be more explicit, $(2+3x)^6 = 2^6(1+3x/2)^6$.
Answer: Use the following:
$$(x+y)^n= \sum_{k=0}^n \binom{n}{k} x^k y^{n-k}$$
Answer: what you have is correct. but you can use the standard binomial series/pascal triangle to expand
$$(2+3x)^6 = 2^6 + {6 \choose 1}  2^{5}(3x)^1 + {6 \choose 2}  2^{4}(3x)^2  + \ldots$$
Comment: Yes, this solution is valid. Still, the guy proposed a totally valid way too, and it would be nice to say him so first ! ;-)

Taylor series expansion of $(2+3x)^6$


PHP: "Submit" box

Question: I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");

//Perfom submit function
if(isset($_POST['Submit']))
    fseek($fh, 0, SEEK_END);
    fwrite($fh, "$addres_add") or die("Could not write to file");
    fclose($fh);
    print("Address added successfully. Updated book:

");
    echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>

Comment: I can't see `$addres_add` being declared
Comment: Don't they teach such basic things before giving you assignments?
Answer: You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");

Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");

Otherwise, all the addresses will be on the same line.
Answer: Here is a simpler version of your program.
<?php

$file_path ="address_book.txt";

// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
    echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
    echo("Error opening file. \n");

// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
    // Append the new name (used the newline character to make it more readable)
    $file_contents .= $_POST["any_name"] ."\n";
    // Write the new content string to the file
    file_put_contents($file_path, $file_contents);
    print("Address added successfully. Updated book:

");
    echo($file_contents);
}
else
{
    echo("Both form elements must be set. \n");
}

?>
    //HTML for submission box?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <input type="text" name="any_name">
    <input type="submit" name="submit">
    </form>

Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
Comment: @alex_HG Thanks a bunch for the help, I have one more question regarding this, when entering in a name and address into the submission box, how would I have it formatted in the file the same as the rest of the addresses? For example:
First Last
Street Address
Town, State, zipcode

Currently I can only get the whole address to appear on one line with a break after that.
Comment: You have to add more inputs and process the data in the same way the any_name variable was processed, then just append it to the string using escape characters to make it more readable. For example '\t' will add a tab to the string.

PHP: "Submit" box


Javascript split string based on index

Question: Am new to java script. I have a string variable like the following way
var linkedinid = R3kyEgkyJxlinkedin; // it may sometimes R3kyEgkyJxlinkedincompany

I have to split this string to get the id part only ie "R3kyEgkyJx"
What am planning to do is find index value linkedin or linkedincompany in the string and take the id part only. I tried the following code. Its getting result as expected. But am not sure is it the best way to do it. I don't know is any other better way around. Please guide me in right direction. Your help is much appreciated. Thanks
var str = "R3kyEgkyJxlinkedin"; // R3kyEgkyJxlinkedincompany (sometimes string may contain linkedincompany)
var n = str.indexOf("linkedin");
if(n == -1) {

n = str.indexOf("linkedincompany");
 if(n == -1) {
     // no match found
    } else {

     var id = id = str.slice(0,n);
    }

} else {

 var id = str.slice(0,n);

}

console.log('linked in id', id);

Answer: This should do the trick:
var str = "R3kyEgkyJxlinkedin",
    id = str.replace('linkedincompany', '').replace('linkedin', '');

Basically, just remove "linkedincompany" and "linkedin" from the string.
Or, even shorter:
id = str.replace(/linkedin(company)?/, '');

Or:
id = str.replace(/linkedin.*$/, '');

Comment: or `.replace(/linkedin.*$/,'')`
Answer: You can find the index of "linkedin" and use substring from 0 to that index:
var linkedinid  = "R3kyEgkyJxlinkedin";
var id = linkedinid.substr(0, linkedinid.indexOf('linkedin') );

If there's no "linkedin" substring it will work as s.substr(0, -1) and then id == "".
Answer: If you are sure of the value of the string to be removed:
like in the above case you wish to remove linkedin,whose size is 8,
you may also try:-
var linkedinId = "R3kyEgkyJxlinkedin";
linkedinId = linkedinId.slice(0,-8);  //or linkedinId.slice(0,-15); in case of R3kyEgkyJxlinkedincompany

Javascript split string based on index


Problematic Quotes in Javascript callFunction()

Question: I would like to know how to maintain the ability to have both single and double quotes in text that I am passing to a JavaScript function with callFunction()? All three cases below appears to be failing.
Mixing the single and double quotes will work but I would like to be able to use both single and double quotes in my text blocks. It is curious why the browser is evaluating html special characters before passing it to the Javascript function.
Thanks, Robin
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

Robin's Text

Robin"s Text

Robin's Text

Comment: `'` is the HTML escape code, you need to use the JS one `\u0027` (note the change from dec to hex)
Comment: @david, no OP just needs to use the correct escape characters in JavaScript followed by the correct HTML entities.
Answer: Thank you all for your advice. With it, I have found a workable solution. It appears that using both backslash and HTML Special Characters together will allow it to work. I am not sure why both is required?

Robin's Text

Robin"s Text

Robin"s Text

Answer: Assuming that the input for the JS function will be machine-generated, then you should escape the input from the server, then unescape it in the client-side as below:
HTML:
Robin's Text

Robin"s Text

JS:
function callFunction(text){
    alert(decodeURIComponent(text));
}

See the working code at:
JSFiddle
Comment: When someone has a problem understanding encoding, please don't ever suggest adding another layer of encoding. It's bad enough that OP is trying to HTML encode a JavaScript string, don't make things worse by adding percent encoding into the mix as well.
Comment: Please read the assumption for the suggested solution: "Assuming that the input for the JS function will be machine-generated, ..."
Comment: So what you're saying is that if the code is programmatically generated you should ignore the bugs in how the code is generated and add an extra unnecessary layer of encoding? No, that's exactly what I disagree with. If the code is being generated, fix it so that it's piped through the correct encoder before being output as an attribute value.
Comment: What would be your preferred encoding in such case?
Comment: The contents of the javascript string must be correctly escaped, and then the javascript string itself must be correctly HTML encoded. That is all.
Comment: I believe that we are talking about the same solution here. :)
Comment: `decodeURIComponent` is percent encoding, and unrelated to JavaScript escaping and HTML encoding. I don't believe we are talking about the same thing.
Comment: Then which JS encoding method would you suggest here?
Comment: Comments aren't the place for extended discussion. I thought [my answer](http://stackoverflow.com/a/23191683/497418) was clear enough to explain this concept, but apparently there are at least two people who disagree, so let me know if you still have questions.


HTML5 Video Autoplay em navegadores mobile

Question: O Atributo autoplay na tag VIDEO parece não funcionar em navegadores mobile, pesquisei e parece que isso lhe diz respeito a uma politica de permissões entre o navegador e o usuário final, tentei forçar o autoplay disparando um o evento de click para um botão de play, funciona no navegador desktop mas não no mobile.
A alguma maneira de burlar isso? e configurar o autoplay para tocar nos mobiles.
Comment: Possível duplicata de [Como dar autoplay no video em versão mobile chrome](https://pt.stackoverflow.com/questions/257720/como-dar-autoplay-no-video-em-vers%c3%a3o-mobile-chrome)
Comment: Você não considera utilizar players?
Comment: O vídeo deve auto executar assim que o usuário entrar na pagina , não preciso de controles, só preciso que o vídeo auto execute.
Comment: Sim, mas o youtube dá autoplay, ele é um player não html5...entende? Vc pode usar players e esconder os controles.
Comment: @AnthraxisBR minha pergunta foi feita primeiro a outra pergunta que deve ser sinalizada como duplicata.
Answer: Não é possível dar autoplay em um vídeo em navegadores mobile. Esta é uma limitação imposta por eles.
Esta limitação tem o intuito de se impedir o download não solicitado através da pacote de dados do usuário, economizando assim a franquia dele.
Pelo que eu saiba não existe nenhuma forma de se burlar esta limitação, apenas um evento iniciado pelo usuário, como um toque na tela pode iniciar o vídeo, e isso não pode ser simulador por javascript.
Answer: Se o vídeo estiver em um banner na página, você pode tentar colocá-lo na segunda transição, ou seja forçar o usuário a clicar no próximo banner para poder ver o vídeo, assim, será uma requisição do próprio usuário.
Answer: Utilize os atributos autoplay="" loop="" muted="" playsinline="" autobuffer=""


Calculating decimals

Question: I managed to calculate variables but my question is how do I calculate numbers with decimals?
int Var1;
int Var2;
int Uitkomst;

Var1 = Convert.ToInt16(txtGetal1.Text);
Var2 = Convert.ToInt16(txtGetal2.Text);

Uitkomst = Var1 * Var2;

txtUitkomst.Text = "Uitkomst:" + Uitkomst.ToString();

Comment: [decimal.TryParse](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryparse?view=net-5.0)
Comment: and `int` isn't a `decimal`, they are different types
Comment: " if I try calculating decimals." then you should post the code with the decimals. we cannot help you with working code
Comment: FYI an `int` is an `Int32`. `Int16` is a 16-bit `short`. See [docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types)
Answer: You should declare your Var1 and Var2 and you may use double.Parse() to convert the user input
I changed your code into this:
double Var1;
double Var2;
double Uitkomst;

Var1 = double.Parse(txtGetal1.Text);
Var2 = double.Parse(txtGetal2.Text);

Uitkomst = Var1 * Var2;

txtUitkomst.Text = "Uitkomst:" + Uitkomst.ToString();

Calculating decimals