How to pass arguments in kubernetes to start a rq-worker container

Question: I'm working on a microservice architectural project in which I use rq-workers. I have used docker-compose file to start and connect the rq-worker with redis successfully but I'm not sure how to replicate it in kubernetes. No matter whatever I try with command and args, I'm thrown a status of Crashloopbackoff. Please guide me as to what I'm missing.Below are my docker-compose and rq-worker deployment files.
rq-worker and redis container config:
...
  rq-worker:
    build: ./simba-app
    command: rq worker --url redis://redis:6379 queue
    depends_on:
      - redis
    volumes:
    - sharedvolume:/simba-app/app/docs

  redis:
    image: redis:4.0.6-alpine
    ports:
      - "6379:6379"
    volumes:
      - ./redis:/data
...

rq-worker.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rq-worker
  labels:
    app: rq-worker
spec:
  selector:
    matchLabels:
      app: rq-worker
  template:
    metadata:
      labels:
        app: rq-worker
    spec:
      containers:
      - name: rq-worker
        image: some-image
        command: ["/bin/sh", "-c"]
        #command: ["rqworker", "--url", "redis://redis:6379", "queue"]
        args:
          - rqworker
          - --url
          - redis://redis:6379
          - queue
      imagePullSecrets:
      - name: regcred
---

Thanks in advance!
Edit:
I checked the logs using kubectl logs  and found the following logs:
Error 99 connecting to localhost:6379. Cannot assign requested address.

First of all, I'm using the 'service name' and not 'localhost' in my code to connect rq and redis. No idea why I'm seeing 'localhost' in my logs.
(Note: The kubernetes service name for redis is same as that used in my docker-compose file)
redis-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  labels:
    app: redis
spec:
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis:4.0.6-alpine
        ports:
        - containerPort: 6379
---

apiVersion: v1
kind: Service
metadata:
  name: redis
spec:
  type: ClusterIP
  selector:
    app: redis
  ports:
   - port: 6379
     targetPort: 6379

Answer: You do not need the /bin/sh -c wrapper here.  Your setup reads the first args: word, rqworker, and parses it as a shell command, and executes it; the remaining words are lost.
The most straightforward thing to do is to make your command, split into words as-is, as the Kubernetes command:
      containers:
      - name: rq-worker
        image: some-image
        command:
          - rqworker
          - --url
          - redis://redis:6379
          - queue

(This matches the commented-out string in your example.)
A common Docker pattern is to use an ENTRYPOINT to do first-time setup and to make CMD be a complete shell command that's run at the end of the setup script.  In Kubernetes, command: overrides Docker ENTRYPOINT; if your image has this pattern, then you need to not use a command:, but instead to put this command as you have it as args:.
The only time you do need an sh -c wrapper is in unusual cases where you need to run multiple commands, expand environment variables, or otherwise use shell-only features.  In this case the command itself must be in a single word in the command: or args:.
command:
  - /bin/sh
  - -c
  - rqworker --url redis://redis:6379 queue

Comment: Thank you so much @DavidMaze for your detailed explanation and help. Really appreciate it! Finally got it working.


How to notice if the device GCM registrationID is expired?

Question: I know that the registrationID of my device is not stable in GCM and it might be expired on google server.
When registrationID is expired I should renew it and send it to my GCM server.
My Android app saves its first registrationID and use it. How can I notice in my Android app if registrationID has been expired in google server for renewing it and sending to GCM server?
Comment: Did you get any result with new `GCM` library? I'm in a same scenario!
Answer: According to the docs

Google may periodically refresh the registration ID, so you should
  design your Android application with the understanding that the
  com.google.android.c2dm.intent.REGISTRATION intent may be called
  multiple times. Your Android application needs to be able to respond
  accordingly.

Also Note:

The registration ID lasts until the Android application explicitly
  unregisters itself, or until Google refreshes the registration ID for
  your Android application.

So you need to update the registration ID on your server when you recieve the com.google.android.c2dm.intent.REGISTRATION intent.
Also you can have a code in your launcher/main activity that checks whether you are registered on GCM as follows
String regid = getRegistrationId(context);
if (regid.length() == 0) {
    registerBackground();
}

Answer: There is no such function or API available to check for it, you need to define the a certain period of time for periodically refreshing it inside the client.


redirect Javascript syntax errors and console.log to somewhere else

Question: I'm trying to send whatever would normally appear in the javascript console to my own custom functions.
I've tried the following
window.console.error = window.console.debug =  window.console.log
window.console.log=mylog;

function mylog(msg){
    //send it somewhere just using alert as an example
      alert("log="+msg);
}
console.log("yo");
var x=y;//a syntax error

Using the code above I only see the following alert
"yo"
In the console log I see
"x is not defined"
How do I redirect the syntax errors?
Comment: have u tried using try catch???
Answer: You can use onerror it is designed to catch syntax errors.
window.onerror = function(message, source, lineno, colno, error) {
   alert(message);
}

Offical docs on MDN
Comment: That was what I was looking for. Thanks.
Answer: Here's a thread on this. Note the answer that shows how to "hijack" console.log() and send it wherever you want: Capturing javascript console.log?


How can I Always open server?

Question: I have code (my c++ socket server) but I don't know How can I always open. My server will close. when It already send to client It will close itself. But I want it to wait others client and never closed. How can I do it ? Oh I use multi-threaded too.
please,Help me.
and here is my code
int main(void)
{
  HANDLE hThread[3];
  DWORD dwID[3];
  DWORD dwRetVal = 0;

  hThread[0] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadTwo,NULL,0,&dwID[0]);

  dwRetVal = WaitForMultipleObjects(3, hThread, TRUE, INFINITE);

  CloseHandle(hThread[0]);

 return 0;
}

long WINAPI ThreadTwo(long lParam)
{
  WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET,
           ClientSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    hints;
    char recvbuf[DEFAULT_BUFLEN];
    int iResult, iSendResult;
    int recvbuflen = DEFAULT_BUFLEN;

    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    printf("Waiting for client\n");

    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    printf("Client acctped.\n");

    closesocket(ListenSocket);

    do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);

            recvbuf[iResult] = '\0';
            printf(recvbuf);

            char* testsend = "222 333\n444 555\n666 777" ;

            iSendResult = send( ClientSocket, testsend , strlen(testsend)+1 , 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed with error: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }
    system("pause");

    closesocket(ClientSocket);
    WSACleanup();

  return 0;
}

thank again.
Comment: `closesocket(ListenSocket);` -- is that intentional? What'll let you `accept()` on the next client...?
Comment: Should I delete closesocket(ListenSocket),that is closeSocket, and replace with accept() ??
Comment: No It's not work. I think I should put some loop somewhere.
Answer: You have to use a loop for that :)
Basically, the server main code must be in a loop, that will go forever ... while you do not stop it.
you should have :
// That's close to pseudo code :)

while(notStoppedByMaster)
{
    // [...]
    ClientSocket = accept(ListenSocket, NULL, NULL);
    handleRequest(ClientSocket);
}

// close the listen socket here

The handleRequest should handle the request in another thread. Be attentive to synchronization :)
my2c
Comment: I'm trying that.Wait a minutes : )
Comment: Special emphasis on the last two sentences!
Comment: @Thorsten: yes. A programmer's lifetime to make this right ;)
Answer: Firstly, it looks like you are creating a console application. If I were you I would create a WIN32 application instead. This means you'll have a GUI but more importantly, a message loop. The message loop allows you to use Asynchronous sockets, it takes a little more understanding but it gives much better and cleaner results.
Read about WSAAsyncSelect:
http://msdn.microsoft.com/en-us/library/ms741540%28VS.85%29.aspx
Also read socket tutorial:
http://msdn.microsoft.com/en-us/library/ms738545%28v=VS.85%29.aspx
Secondly, if you HAVE to use synchronous (blocking) sockets, yes you'll have to be running each on its own thread. You Need to have a loop in which you wait for connections, and then have client sockets like you did, being assigned from your accept(). Then let the client sockets run on their own thread.
Also you are closing your listensocket for some reason in the middle of the code.
Comment: thank you. Now I must to go home and I will come to ans my result. thank anyway all :)
Comment: Oh and I try to creating way to send value from C++ app to Flash (I use flash to display result.) (OpenCV C++ to Flash Model)
Comment: Oh I got it all. Thank you again.

How can I Always open server?


Uniform convergence of $f_n(x) = \left(1-\frac{x^2}{n} \right)^n$

Question:

For $x\in \mathbb{R}$ we define $f_n(x) = \left(1-\frac{x^2}{n} \right)^n$. Determine if $f_n(x)$ is uniformly convergent on:  1.
$[-A,A]$ for $A>0$  2.
$\mathbb{R}$

Sol for 1:
First of all, we know $f_n$ is pointwise convergent to $f(x) = e^{-x^2}$. By definition of uniform convergence we need to look at $\lim_{n \to \infty } \sup_{x\in [-A,A]}\left| f_n(x)-f(x)\right|$ and check whether it's $0$ or not.
$$\lim_{n \to \infty } \sup_{x\in [-A,A]}\left| f_n(x)-f(x)\right|=\lim_{n \to \infty } \sup_{x\in [-A,A]}\left|\left(1-\frac{x^2}{n} \right)^n-e^{-x^2}\right|$$
I'm not sure how to find the limit (I get confused because there are 2 variables $n,x$).
I'd appreciate if you could help me with this. Thank you!
Comment: @HallaSurvivor No, Note that there are discussing about different expression. Also, I ask about uniform convergence in $\mathbb{R}$ and not only $[-A,A]$.
Comment: **Hint :** For 1., write $\left(1-\frac{x^2}{n} \right)^n = \exp\left( n \ln \left(1-\frac{x^2}{n} \right) \right)$ and use the inequality $\ln(1+u) \geq u-u^2/2$. For 2., an option is to prove that a uniform limit of polynomial over $\mathbb{R}$ is necessarily a polynomial.
Answer:
Notice that, for any $n$, $$\sup_{x\in[-A,A]}\left|\left(1-\frac{x^2}{n}\right)^n-e^{-x^2}\right|=\sup_{x\in[0,A^2]}\left|\left(1-\frac{x}{n}\right)^n-e^{-x}\right|.$$
(I'm only making this step to make things less messy, it's not strictly necessary). Now, for all $A$, for all large enough $n$ and all $x\in[0,A^2]$, we have $1-\frac{x}{n}>0$, so we can take the logarithm of $1-\frac{x}{n}$, and, in particular, we have
$$\left|\left(1-\frac{x}{n}\right)^n-e^{-x}\right|=\left|e^{n\log(1-x/n)}-e^{-x}\right|=\left|e^{-x}\left(e^{n\log(1-x/n)+x}-1\right)\right|\leq\left|e^{n\log(1-x/n)+x}-1\right|.$$
$n\log(1-x/n)+x\leq 0$ for all $x\in[0,A^2]$, and is decreasing, since it is equal to $0$ at $x=0$ and its derivative is $1-\frac{n}{n-x}$ which is at most $0$ for all $x\geq 0$. Hence the supremum of $\left|e^{n\log(1-x/n)+x}-1\right|$ on $[0,A^2]$ occurs at $x=A^2$, where it equals
$$1-e^{A^2}\left(1-\frac{A^2}{n}\right)^n\to 1-e^{A^2}e^{-A^2}=0$$
as $n\to\infty$, so we have the desired uniform convergence.

Each $f_n$ is unbounded on $\mathbb{R}$, yet the pointwise limit is bounded on $\mathbb{R}$, so the convergence cannot possibly be uniform.
Comment: Can you explain why $n\log(1-x/n)+x$ is decreasing? Is it obtained from $1-\frac{n}{n-x}$? how do you show $1-\frac{n}{n-x}\le 0$ ?
Comment: Just to make sure, you get $\sup_{x\in[-A,A]}\left|\left(1-\frac{x^2}{n}\right)^n-e^{-x^2}\right|=\sup_{x\in[0,A^2]}\left|\left(1-\frac{x}{n}\right)^n-e^{-x}\right|\le1-e^{A^2}\left(1-\frac{A^2}{n}\right)^n\to 0 $ and in conclusion $f_n \xrightarrow[]{u}f$?
Comment: @Lior, you prove that $n\log(1-x/n)+x$ is decreasing using the derivative $1-n/(n-x)$ as you mentioned. You show that $1-n/(n-x)\leq 0$ by multiplying both sides by $n-x$, noting that this won't flip the inequality if $n$ is large enough, since $x$ is bounded above by $A^2$. Your summary of the argument in the second comment is correct.


Angular 4 "Property does not exist on type component"

Question: This last week I've started learning Angular 4 and TypeScript, and I've hit my first roadblock.
I'm trying to make a simple date and time component. From a Javascript view I can't see anything wrong, but I think I'm not working with scope the way Angular wants, so I'm looking for some guidance. The error is:
Failed to compile very/long/file/path/date-time.component.ts (35,18): Property 'date' does not exist on type 'DateTimeComponent'.
I suspect I'm not putting my methods in the right place, or I need to declare my properties outside of setTime(). Any advice much appreciated.
date-time.component.ts:
export class DateTimeComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {
    this.setTime();
  }

  checkTime(i) {
    return (i < 10) ? "0" + i : i;
  }

  setTime() {

    let month = ["January", "February",
    "March", "April",
    "May", "June",
    "July", "August",
    "September", "October",
    "November", "December"];

    //date
    let date: Date = new Date(); // this only accessible within setTime() method
    let d: any = date.getDate();
    let m: any = date.getMonth();
    let y: any = date.getFullYear();
    //time
    let h: any = date.getHours();
    let min: any = date.getMinutes();
    let s: any = date.getSeconds();

    let newMin: any = this.checkTime(this.min);
    let newS: any = this.checkTime(this.s);

    let myDate: any = d + " " + month[this.m] + " " + y;
    let myTime: any = h + ":" + newMin + ":" + newS;

    let t: any = setTimeout(() => {
      startTime()
    }, 500);

  }

} //end of class

date-time.component.html:

{{ myDate }}

{{ myTime }}

Comment: What @Dummy said. Also none of your variables are being declared. You're also trying to access those variables incorrectly (`eg. d = this.date.getDate()`). There's a lot wrong here.
Comment: what tutorial are you looking at? there is so much wrong with this that i dont know where to start. for example, first of all, in your html, thats not how you use an angular component in angular2+. its how you would bind a controller to a div in angularjs(angular1). Also, you dont have to declare all variables outside the methods. but you do have to declare them, at least locally, if you want to use them. also, your functions `checkTime()` and `setTime()`  are being declared inside `ngInit()`, which it shouldnt be. It should be outside of the `ngInit()` within the scope of the component itself
Comment: If you pay a little more attention to your code inside `ngOnInit`, you will see the problem
Comment: @JunKang the tutorials I've seen declare some variables like `i = "thing"` and it works just fine. Adding `var` to mine seemingly makes no difference. Should I be declaring all variables outside of the methods, with set types? If so it seems rather overdone.
Comment: @JunKang I've updated my code, hope it's an improvement. Really appreciate that info on how things should be structured.
Answer: Here's a plunker showing your thing working in an Angular environment. This isn't a good way to accomplish what you're trying to do.
Instead, you should do something like this better plunker that I made that actually uses Angular to its full potential.
My version of your code is like 99% shorter, and accomplishes the goal.
myDate: Date;

ngOnInit() {
  this.myDate = new Date();
}

With the HTML

{{ myDate | date:'d MMMM y'}}

{{ myDate | date:'hh:mm:ss'}}

Comment: The first plunker does work, and shows how your code should be formatted to work. So you can still go off that to learn a little bit of what you're doing. The reason your code wasn't working before was for a few reasons. 1. Your variables `myDate` and `myTime` need to be declared publicly within the scope of the component itself, so it can be referenced in the html. 2. When updating those variables in the function `setTime()`, you need to use `this.myDate` and `this.myTime` because that's how you access variables declared in the scope of the component inside your functions.
Comment: 3. Since you declared the function `checkTime()` in the scope of the component, you also call that function with `checkTime()` when calling it inside the function `setTime()`. 4. Yes, all the variables need to be declared within the function `setTime()` itself if you want to use them. Using `let` declares the variables within the scope of the block you're using it in, as opposed to `var` which declares it globally within the scope its being used in. Using `var` is fine. Using `let` is also fine, in this context.
Comment: 5. In your html, the div should not have the property `ng-controller` on it at all. That's how controllers are defined using AngularJS (Angular 1). Not Angular (Angular 2+ (currently on version 4)). 6. You don't NEED to define a variables type, like `myDate: Date` but it's good to when its not implicit. E.g. If you do `myDate = new Date()`, it's not necessary to define the variable as a Date, because it is implicitly a date. But in my version, I did `myDate: Date;` with `this.myDate = new Date();` in the `ngOnInit()` function because at the time that `myDate` was declared, it wasn't implicit.
Comment: I really like the efficiency here, but I really need to learn how to use methods, etc. I need to grasp the fundamentals of so many things and using code as clean as this would teach me little.

I think it would be best if I accept this as the answer as it works so well, and go study my brains out till I think I can build something once again. Hopefully when I come here for help next I'll have problems aside from code that is god awful.
Comment: btw in number 3, I said "you also call that function with `checkTime()`". That should be `this.checkTime()` because `checkTime()` is declared in the scope of the component.
Comment: What do you think of this? I am making a new Date object every half-second, I'm wondering if it's efficient. https://jsfiddle.net/nj7fmLvp/
Comment: How we can do with string and another data type like an array, Object
Answer: The reason you have not declared the variable date on your component.

export class DateTimeComponent implements OnInit {

  constructor() {

  }

  private date: Date; // This is accessible to this entire file
  private month: string[];
  private d: any;
  private m: any;
  private y: any;
  private h: any;
  private min: any;
  private s: any;
  private newMin: any;
  private newS: any;
  private myDate: any;
  private myTime: any;
  private t: any;

  ngOnInit() {

  }

  checkTime(i) {
      return (i < 10) ? "0" + i : i;
    }

    setTime() {
      this.month = ["January", "February",
      "March", "April",
      "May", "June",
      "July", "August",
      "September", "October",
      "November", "December"];

      //date
      this.date = new Date();
      this.d = this.date.getDate();
      this.m = this.date.getMonth();
      this.y = this.date.getFullYear();
      //time
      this.h = this.date.getHours();
      this.min = this.date.getMinutes();
      this.s = this.date.getSeconds();

      this.newMin = this.checkTime(this.min);
      this.newS = this.checkTime(this.s);

      this.myDate = this.d + " " + this.month[this.m] + " " + this.y;
      this.myTime = this.h + ":" + this.newMin + ":" + this.newS;

      this.t = setTimeout(() => {
        startTime()
      }, 500);
    }

} //end of class

export class DateTimeComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {
  }

  checkTime(i) {
      return (i < 10) ? "0" + i : i;
    }

    setTime() {
     let month = ["January", "February",
      "March", "April",
      "May", "June",
      "July", "August",
      "September", "October",
      "November", "December"];

      //date
      let date: Date = new Date(); // this only accessible within setTime() method
      let d: any = date.getDate();
      let m: any = date.getMonth();
      let y: any = date.getFullYear();
      //time
      let h: any = date.getHours();
      let min: any = date.getMinutes();
      let s: any = date.getSeconds();

      let newMin: any = this.checkTime(this.min);
      let newS: any = this.checkTime(this.s);

      let myDate: any = d + " " + month[this.m] + " " + y;
      let myTime: any = h + ":" + newMin + ":" + newS;

      let t: any = setTimeout(() => {
        startTime()
      }, 500);
    }

} //end of class

There two approaches to this, snippet 1 show file wide declaration, this what you would mostly use in your app. The Snippet 2 show method based declaration and its only accessible to that method, as far as files concerns, that variable doesn't exist.

private

If you stick private in front of a variable or method, that will only be accessible to the .ts file (itself), not even the HTML has access to that.
Comment: @nicowernli I was going to but wan't sure whether OP has relevant libraries  in the app, thats why left `any` I shall change it. Thanks
Comment: @Draxy Sorry it was my fault, I didn't pay attention other variables. I have made changes to both snippets, this should work. Don't forget to replace `any` with appropriate Types. I.E `string[]` (array of strings)
Comment: as you know that `this.date` is going to be type Date, better if you use the type in the definition `private date: Date`
Comment: When `let date = new Date();` (Snippet 2) is used I get `Property 'date' does not exist`. Am I doing something else wrong? I can't think of how to make this object any more declared than it already is.
Comment: It might be because of this `this.date`. Word `this` reffers to a variable like on Snippet 1. It used to go up a level to the file level and look for the variable. If you remove it, it will use the one in the method
Comment: @PraveenM All this declaring and `Property 'min' does not exist` still, I'm starting to think I'm in over my head haha
Comment: Have you added `let` in front of the `min`? Assuming you're using the second snippet approach
Answer: note that you are setting date try using date.whatever not this.date.whatever
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'date-time',
  templateUrl: './date-time.component.html',
  styleUrls: ['./date-time.component.css']
})
export class DateTimeComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {

    checkTime(i) {
      return (i < 10) ? "0" + i : i;
    }

    setTime() {
      month = ["January", "February",
      "March", "April",
      "May", "June",
      "July", "August",
      "September", "October",
      "November", "December"];

      //date
      let date = new Date();
      d = date.getDate();
      m = date.getMonth();
      y = date.getFullYear();
      //time
      h = date.getHours();
      min = date.getMinutes();
      s = date.getSeconds();

      newMin = this.checkTime(this.min);
      newS = this.checkTime(this.s);

      myDate = this.d + " " + this.month[this.m] + " " + this.y;
      myTime = this.h + ":" + this.newMin + ":" + this.newS;

      t = setTimeout(() => {
        startTime()
      }, 500);
    }

  }

} //end of class

that should work
Comment: By the way, you forgot to declare every other variable after `date`.


Number of solutions for equations with complex variables

Question: A question about the number of solutions for the following equation:
$$z^2+(1-i)z-3i=0$$
So the solutions are:
$$z_{1,2}=\frac{-1+i \pm \sqrt{10i} }{2}$$ But $\sqrt{10i}$ has two options with itself: $\sqrt5+\sqrt5i$ and $-\sqrt5-\sqrt5i$, so the equations has 4 solutions?!
Thank you for any answer about this, quite confused.
Comment: there are only two. $z_\pm = \frac{(-1+i) \,\pm\sqrt{5}(1+i)}2$
Comment: No it still has two because the square roots are opposite to each other so $\pm$ becomes $\mp$
Comment: AH right! thanks
Answer: No, just $2$ solutions. The $\pm\sqrt{\Delta }$ is to make reference at the two square root of $\sqrt {\Delta }$. Actually, as you can see, if you take the two square root, you will arrive two time twice at the same value (and thus in your 4 solutions, you will have the same solutions two times).
The best is: try and you'll see :-)
Answer: use this formula to get the all roots
$$\frac{1}{2}(1+i)^2=i$$
$$\sqrt{\frac{1}{2}(1+i)^2}=\sqrt{i}$$
$$\frac{1}{\sqrt{2}}|1+i|=\sqrt{i}$$
for your question,
$$\sqrt{10i}=\frac{\sqrt{10}}{\sqrt{2}}|1+i|=\sqrt{5}|1+i|$$
$$\sqrt{10i}=\pm \sqrt{5}(1+i)$$
Answer: The fundamental theorem of algebra states that a polynomial of degree $n$ has $n$ roots, no less, no more.
If the proposed equation had four distinct roots, you could factor it as $(z-z_0)(z-z_1)(z-z_2)(z-z_3)$, a fourth degree polynomial !
So without even looking at why your conclusion is wrong, you can be sure that it is wrong.


Trigonometry gymnastics

Question: The teacher is as usual jumping a million miles between steps, I appreciate if someone can break down how this step is done:
$$\frac{\partial r}{\partial s}\times\frac{\partial r}{\partial t}=\det
\begin{pmatrix}
i & j & k \\
-\sin(s)(2+\cos(t)) & \cos(s)(2+\cos(t)) & 0 \\
-\cos(s)\sin(t) & -\sin(s)\sin(t) & \cos(t) \\
\end{pmatrix}=$$
$$=\begin{pmatrix}
\cos(s)\cos(t)(2+\cos(t))\\
\sin(s)\cos(t)(2+\cos(t))\\
\sin(t)(2+\cos(t))\\
\end{pmatrix}$$
What trigonometry magic is used to get to that last line $\sin(t)(2+\cos(t))$? I've spent several hours now trying to get it.
Thanks for your time.
Answer: That's abbreviated notation for saying that the coefficient of $i$ is the algebraic complement, that is,
$$
\det\begin{bmatrix}
\cos s(2+\cos t) & 0 \\
-\sin s\sin t & \cos t
\end{bmatrix}=
\cos s\cos t(2+\cos t)
$$
Similarly, the coefficient of $j$ is
$$
-\det\begin{bmatrix}
-\sin s(2+\cos t) & 0 \\
-\cos s\sin t & \cos t
\end{bmatrix}=
\sin s\cos t(2+\cos t)
$$
and the coefficient of $k$ is
\begin{align}
\det\begin{bmatrix}
-\sin s(2+\cos t) & \cos s(2+\cos t) \\
-\cos s \sin t & -\sin s \sin t
\end{bmatrix}&=
\sin^2s\sin t(2+\cos t)+\cos^2s\sin t(2+\cos t)\\
&=(\sin^2 s+\cos^2s)\sin t(2+\cos t)
\end{align}
You're probably forgetting a "det" in front of the matrix with $i$, $j$ and $k$ (or it's assumed in that context); it's a "formal" determinant, of course.
Comment: You are absolutely right that is it an determinant/curl/rot or whatever one like to call it. It seems I've gotten something wrong in my calculation of $k$, thank you for your answer!
Answer: Remember the identity $$\sin^2 x + \cos^2 x = 1 $$
Comment: Oh I've tried to use that in every way I can.

Trigonometry gymnastics


Prod build of React App allows React Dev Tools and show components in source tab inside Browser

Question: Actually, I'm developing a React App and I'm using React Script 2.0 to build it. The weird thing is after I compiled with the react-scripts build command and serve the app with Nginx I'm still allowed to check the state with React Dev Tools, also if I go to Source in Chrome I can see my components as if they weren't compiled.
Does anyone know what I'm doing wrong?
Comment: This is expected behaviour. The app is built with source maps.
Comment: Welcome to Stack Overflow! What is the image link in the last line for? Anyway, try to remove the React Dev Tools for production: https://github.com/facebook/react-devtools/issues/191. To solve the source issue, delete the `*.map.js` files from the built folder or change the parameter `devtool` of Webpack
Comment: Thanks both of you for your reply :D
Answer: Just add GENERATE_SOURCEMAP=false in you .env file then it will stop making *.map files and browser will not show folders in source tab

Run this command for create .env file and write GENERATE_SOURCEMAP=false in it
echo GENERATE_SOURCEMAP=false > .env
Happy coding...!


Absolutely convergent infinite product

Question: I have read about the definition of the product
$$\prod_{j\in J}a_j\in[1,+\infty]$$
when $a_j\in[1,+\infty)$ for all $j\in J$, where $J$ is any set, possibly infinite. It is defined as the supremem of the set:
$$S = \left\{\prod_{i\in I}\mid I\subset J\text{ is finite}\right\}.$$
However, this does not cover the famous
$$\zeta(s)=\prod_p (1-p^{-s})^{-1}$$
because $(1-p^{-s})^{-1}$ are not real numbers. How is the definition of infinite product extended to cover this famous case? Also, what is absolute convergence?
Comment: See Rudin's RCA for  a thorough discussion of infinite products of complex numbers.
Comment: @Kavi Rama Murthy Thank you for your recommendation.
Answer: Here's one way to define it (not the most general possible definition, but enough to cover the case that you ask about). If $a_n\neq 0$ for all $n\geq 1$ then the infinite product $\prod_{n=1}^\infty a_n$ is defined to be the limit of $\prod_{n=1}^Na_n$ as $N\to\infty$ if this exists and is not zero.
It follows from this definition that (provided none of the $a_n$ are zero) $\prod a_n$ exists if and only if $\prod a_n^{-1}$ exists, and that
$$ \prod a_n^{-1} = \left(\prod a_n\right)^{-1}.$$
It follows from the limit existing that $\lim_{n\to \infty}a_n=1$, so we often change variables and instead talk about $\prod (1+a_n)$. This converges absolutely by definition if $\prod(1+\lvert a_n\rvert)$ converges, which happens if and only if $\sum \lvert a_n\rvert$ converges.
Therefore, for example, you can define
$$ \prod_{p} \left(1-\frac{1}{p^s}\right)^{-1} = \left( \lim_{N\to\infty} \prod_{p\leq N}\left(1-\frac{1}{p^s}\right)\right)^{-1},$$
which exists (and is neither zero nor infinity) for $\Re (s)>1$ because the product converges absolutely, because $\sum_p \frac{1}{p^\sigma}$ converges when $\sigma>1$.
This definition is trying to capture the intuition that `$\prod (1+a_n)=\exp(\sum\log (1+a_n))'$, which one needs to be slightly careful of because you're taking complex logarithms (this is easily avoided by taking a suitable choice of logarithm, but I prefer the approach above). The relevance of $\sum \lvert a_n\rvert$ converging is that it is a sufficient (but not necessary) condition for $\sum \log(1+\lvert a_n\rvert)$ to converge.
Comment: Thank you for your answer. In the defn, we have the $a_n$ nicely ordered by $n=1,2,3\ldots$, however later we have the primes $p$ not ordered this way, instead $p\le N$ is considered. This is confusing. I get the gist of it, but still I am uncomfortable. Shouldn't the defn be extended notationally to include an expression like $p\le N$? Also, I do not get what the last paragraph is saying, would you please explain more?

Absolutely convergent infinite product


Why does semidirect product give a complete classification of small groups

Question: The key theorem involved is:
Suppose $G$ is a group with subgroups $H$ and $k$ such that $H$ is normal in $G$ and $H \cap K=1$. Let $\phi: K \to Aut(H)$ be the homomorphism defined by mapping $k \in K$, TO THE automorphism by conjugation by $k$. Then if $G = HK$, we have $G$ is the semidirect product of $H$ and $K$ with respect to $\phi$.
I am just confused about how to use this to classify groups of small orders. Say for instance I have a noncommutative group with order $pq$, $p$ prime, $q$ prime, $p < q$. Then Let $H$ be the $q-$sylow subgroup of $G$, $K$ be a $p-$sylow subgroup of $G$. Then $H \cap K = 1$, and $H$ is normal in $G$. It is also not hard to show that $G = HK$. Then by the theorem shouldn't we naturally have that $G$ is the semidirect product of $H$ and $K$ with respect to the homomorphism induced by conjugation?
However, all illustrations on this example start by describing all the possible homomorphisms from $Z_p \to Z_{q-1}$. I am totally lost here, why should we care about homomorphisms other than the one induced by the conjugation?
Answer: The semidirect product can be defined with respect to any homomorphism $\phi$ from $K$ to the group of automorphisms of $H$. The trivial homomorphism (everything goes to the identity) gives the direct product, which always exists. The automorphisms of $H$ in the image of $K$ need not all be inner automorphisms, and even if the image of the homomorphism consists of inner automorphisms, $\phi$ need not be the homomorphism defined by conjugation.
It therefore has to be proved that, where non-abelian groups of order $pq$ exist, they are all isomorphic. In this simple case this is not hard to do.
Comment: So the only place where this technique is useful is when all of them are isomorphic?
Comment: @Vanstar I think it is more useful than that. You are seeing this from a particular perspective - but a bigger question is how you can extend one group by another, and semidirect products are important in that context. When groups get larger, the possibilities increase.
Answer: We're trying to describe all groups of order $pq$. We don't know anything about the group $G$ other than it has order $pq$, so the homomorphism induced by conjugation could be any homomorphism. So we have to consider them all to make sure we exhaust all possibilities for groups of order $pq$.
Comment: Okay, in this case it happens to be that all homomorphisms other than the trivial one give us the same group. But what if different homorphisms produce different products? How will you know which is the one given by the conjugation?
Comment: @Vanstar I don't understand your question. By the definition of a semidirect product, *any* homomorphism can define a semidirect product, and that homomorphism becomes conjugation within the semidirect product.  The real problem is to determine which homomorphisms give isomorphic groups.


Can we assign a Win + D Function in VBA?

Question: I am currently working on a userform where i have disabled X (close button) on the forms and have added two buttons one of which will run a sendkey function to do ALt+Tab. For the other one I want to assign Win+D
The Win + D not seems to be working, it just activates Windows but not capturing the D. Following is the code:
Application.SendKeys ("^{ESC}D")

I am not sure if this is even possible. I tried the internet search over and over but wasn't fruitful.
Comment: Does this answer your question? [Minimize workbook/sheet but keep form opened](https://stackoverflow.com/questions/40679441/minimize-workbook-sheet-but-keep-form-opened)
Answer: Instead of trying to use Excel Application.SendKeys you could use Shell.Application
Excel Macro
Sub ShowDesktop()

    CreateObject("Shell.Application").MinimizeAll

End Sub


KKT Conditions for thresholds?

Question: My main question is that when I use Lagrange Multipliers/KKT conditions to perform optimization with threshold constraints, I seem to get contradictory FOC.
Here is a characteristic example:
take an optimization problem like the following:
$$
\begin{align*}
&\max_{x,y} 2x+y-(x-y)^2\\
&s.t.\\
&x,y \geq 0\\
&x+y \leq I
\end{align*}
$$
For some value $I>0$. If I translate this directly to a lagrangian I believe the KKT conditions should give that I need to optimize:
$$
\mathcal{L}(x,y,\mu_1, \mu_2, \mu_3)=2x+y-(x-y)^2 + \mu_1(-x) + \mu_2(-y)+\mu_3(x+y-I)
$$
However partial derivatives w.r.t $\mu_1, \mu_2,\mu_3$ gives:
$$\begin{align*}
&-x=0\\
&-y=0\\
&x+y-I=0\\
\end{align*}$$
which gives a contradiction for $I>0$.
Could someone help me understand why I seem to get this contradiction?
Answer: Instead of differentiating w.r.t. the multipliers you should properly write the complementary slackness condition (defined in your link). In your case this is
$$-\mu_1 x=0$$
$$-\mu_2 y=0$$
$$\mu_3 (x+y-I)=0$$
This says that either the constraint binds with equality or the multiplier is zero. If you just differentiate with respect to $\mu_1$ for instance you would incorrectly conclude that always $x=0$, while this can be strictly positive.
Comment: Ahh got it. So at an optimum we check for FOC for the term we wish to optimize but complementary slackness for inequality terms?
Comment: @naveace Yep correct.

KKT Conditions for thresholds?


Migration of database in Rhomobile

Question: How do you migrate the data from your database with Property bag model to the application you build in Rho-mobile.
To illustrate this let I have an application in which I have a model Products and three attributes Name,Brand and SDK. I have inserted a number of values into the Products model while it was in development phase and running on emulator.But after building the application I don't see the data which I had inserted while running on the device.
Answer: There are several caveats when trying to pre-populate information into the database of the app (such as file size in older Android versions and such), but if you are determined, this is the link to the documentation of how to do it:
http://docs.rhomobile.com/faq#how-to-pre-populate-client-database
Comment: Moved to http://docs.rhomobile.com/en/2.2.0/faq#how-to-pre-populate-client-database
Answer: Incase the docs move again, I'll copy it here:

How to pre-populate client database
Run application on target emulator, insert objects to database(locally or get data from server)
Copy all files from 'db' folder on emulator to '/platform\shared\db\res\db'. Here is how to find 'db' emulator folder:

iPhone: look inside log to find paths with guid – this is where
application store files on emulator. Or run search by
'syncdbuser.sqlite' from disk root
Android: difficult since emulator
is virtual machine and files stored inside emulator. Use adb command
line to find path to application package
Windows Mobile: open device
explorer from ActiveSync or 'Mobile Device center', navigate to
'Program Files//rho/db'
Blackberry: open on computer file system –
'/components/simulator/sdcard/Rho//db Build application, now all db
files are in the application package

From my own experience with Android, it's easiest to open the DDMS perspective in Eclipse while an instance of the app is running on an AVD. In the File Explorer tab, navigate to /data/data/your.packagename.app/rhodata/db, and you'll find the database files to copy to the target directory.

Migration of database in Rhomobile


What is the relationship between: the first raw moment, location, expected value, mean in general, arithmetic mean for any sensible distribution?

Question: I am a bit confused by the several sources telling that:

the first raw moment is by definition the arithmetic mean
expected value of any random variable is exactly the arithmetic mean

The expected value and the arithmetic mean are the exact same thing.
  source: How does the expected value relate to mean, median, etc. in a non-normal distribution?

at the same time, on Wikipedia, I can see that for a log-normal distribution, the "mean" (not specified which one), which is a link redirecting to "expected value" is different: exp{μ+σ^2/2} than the arithmetic mean

I do not know, how the μ is expressed? In the normal distribution it is the arithmetic mean, but here?

Then I read about the log-normal distribution, where the geometric mean is the exp(arithmetic_mean(log(normally_distributed_data))). Is this the expected value for log-normal? Is this the first raw moment? Is this something different?
If the arithmetic mean is the first raw moment of any distribution (that has it defined) and is also the expected value (but look at point 3), then what is the point in using geometric mean for the log-normal distribution?
What about the location parameter? Is this the first moment? The mean? Arithmetic mean? Geometric mean? Median? Expected value? Or maybe it can be characterized by them in certain distributions?

Please, help me to organize my knowledge on the relationship between these terms.
Comment: Take a look at [this question](https://stats.stackexchange.com/questions/115286/barx-versus-mathbbe-barx) and see if it clears anything up for you.
Comment: Thank you for your answer, but it does not clarify it. I was told the first raw moment is always the arithmetic mean and the expected value, while, for, say, the log-normal, Poisson, Weibull, and all others, the Wikipedia shows a totally different formula for the expected value, which does not correspond with this claim.
Answer: The source of your confusion seems to stem from the difference between a statistic and a parameter. Consider a continuous random variable $X$ with density function $f(x)$. The expected value (or equivalently the raw population moment) is
$$\mu = E(X) = \int_{\mathbb R}xf(x)dx.$$
On the other hand, the raw sample moment (or equivalently the arithmetic mean) is
$$\bar{x}_n = \frac{1}{n}\sum_{i=1}^n x_i.$$
These are clearly two different concepts. The first one is a parameter of the distribution of $X$ and the second is a function of the data and thus a statistic. Of course they are related to each other via the Law of Large Numbers, which essentially states that the sample mean (i.e. arithmetic mean or raw first sample moment) converges in probability to the expected value.
$$\bar x_n \stackrel{P}{\rightarrow} \mu$$
as $n\rightarrow \infty$.

For instance, if $X \sim \text{Lognormal}(\mu, \sigma)$ then the expected value/first population moment is
$$E(X) = e^{\mu +\sigma^2/2}$$
and the sample mean/arithmetic mean/first sample moment $\bar{x}$ converges in probability to this quantity as $n\rightarrow \infty$.

Edit to address question in the comment: The population geometric mean of a positive random variable is $\exp E(\log(X))$. This is generally not the same as $E(X)$ due to Jensen's inequality. I have never seen this used as an estimator for the mean (i.e. expected value) of a RV. It does come up however... the MLE of $\mu$ in a lognormal distribution is
$$\hat\mu = \frac{1}{n}\sum \log X_i.$$
This is precisely the logarithm of the geometric mean. Equivalently, the MLE for $e^\mu$ in this example is the geometric mean.
Similarly, the median is not used (generally speaking) as an estimate for the expected value. An interesting exception however, is the double exponential (or Laplace) distribution. Since the distribution is symmetric, the expected value and population median are both equal to $\mu$. The Maximum Likelihood estimator for this parameter is the sample median and (I believe) has smaller MSE for $\mu$ than the sample mean.
Comment: Thank you very much for this clarification. This is what I was looking for. So my last question is: is the geometric mean (not a moment) also an estimator of the expected value, but "better"? I know that the arithmetic mean is BLUE, so the best. The geometric mean cannot be "better than best", so it must be "worse"... But, from the other side, it is about "asymmetric" distribution, "multiplicative", so maybe it's not the best unbiased linear estimator, but rather best unbiased non-linear one? So I believe also median and any other kind of mean (and mode) is an estimator of t he E(X) too?
Comment: Thank you very much. Your update is detailed and very helpful. Let me explain why I  asked for this. I saw numerous places, where geometric mean was used to summarize the right skewed distribution, which was confirmed to come from a log-normal distribution. I also saw articles saying why it is better for skewed data, especially if we know it is of multiplicative nature. Similarly - the harmonic mean. So I wanted to relate this measure to the more general terms, like expected value, estimator of central tendency. So I asked myself "what is the geometric mean" (and SD)? Is the GM the expected
Comment: value for the log-normal distribution? But the expected value is the first raw moment, expressed as the arithmetic mean. Then I found a term "moment generating function", which shows how the moments are calculated for each distribution having them. So was double confused - why is it necessary, if the first moment, for example, IS the arithmetic mean, actually? How can be the geometric mean called "the expected value" for the log-normal in Wikipedia (please see where the "Mean" link navigates). Am I right the geometric mean is the best sample estimator of the pop. expected value for log-normal?
Comment: Not quite. The geometric mean is an estimator of the quantity $e^\mu$, which is the population geometric mean. The geometric mean is not a good estimator for the expected value, especially when $\sigma$ is large since the bias is $e^\mu(1-e^{sigma^2/2})$.
Comment: Thank you very much, knrumsey. So, actually, does the geometric mean have any advantage? I saw many articles on "why we should use the geometric mean on right skewed distributions", especially when the data are log-normal, multiplicative, when it's about concentrations, especially because it is equal to the median here. Other people write a lot that the median is much better than the arithmetic mean in right skewed data, which also justifies the geometric mean. But if the statistical properties of the geometric mean are so poor, should we even care about anything else than the arithmetic mean?
Comment: @guazalli, the geometric mean may have some advantages as a measure of center. Just don't forget that it measures something different from the expected value. This comment thread is getting quite long, you might consider posting this as a new question.


How to run different server on same port?

Question: I have created 2 server with express and node.js and now I want to run both the server on the same port which is localhost:8000 with different end points.
How it can be done or what can be the approach for it?
Attaching the server code for reference:-
Server1:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');

app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;

app.get("/WeatherForcast", function (req, res) {
  axios.get('https://localhost:7173/WeatherForecast')
  .then(response => {
    res.status(200).json({ success: true, data: response.data});
  })
  .catch(error => {
    console.log(error);
  });
});

app.listen(PORT, function () {
  console.log(`Server is running on ${PORT}`);
});

Server2:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');

app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;

app.get("/UserData", function (req, res) {
  axios.get('https://localhost:7173/UserData')
  .then(response => {
    res.status(200).json({ success: true, data: response.data});
  })
  .catch(error => {
    console.log(error);
  });
});

app.listen(PORT, function () {
  console.log(`Server is running on ${PORT}`);
});

Currently when I run it, one server runs and for other server an error is displayed that port 8000 is already in use.
Comment: Does this answer your question? [Can two applications listen to the same port?](https://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port)
Answer: You can't run two servers on the same port.  The OS and TCP stack won't allow it.
The easiest solution is to use two endpoints on one server.
If you have to have two separate servers, then you would run them both on separate ports (neither of which is the public port) and then use something like nginx to proxy each separate path to the appropriate server.
So, the user's request goes to the proxy and the proxy examines the path of the request and then forwards it to one of your two servers based on the path of the request (as setup in the proxy configuration).
Answer: it is not possible to run different servers on same port
Answer: Two different servers can not be hosted on same port as it will give the error i.e "this port is currently is use" something like this.
The thing that can be done is instead of creating multiple server you can create a single server and define different endpoints to manage the code flow.


Mixed effect model and sample size

Question: I have a small sample size of participants (n=8) who were enrolled in a study to evaluate the change in one of the urine metabolites over time. The concentration of this metabolite in the urine was measured in three different occasions (baseline or time zero, after three months and then after six months.
I would like to study the change in this metabolite concentration over time. I am uncertain about the utility of the mixed effect model in such a small sample size, especially since there were concerns raised in the literature about the accuracy of this type of analysis.
http://www.joophox.net/publist/methodology05.pdf

In addition:
Snijders, T.A.B. & Bosker, R.J. (2012). Multilevel Analysis: An Introduction to Basic and Advanced Multilevel Modeling. London: Sage Publishers.

Hox, J. (2010). Multilevel Analysis: Techniques and Applications. New York: Routledge.

I would like to inquire about the correct method to be used in such case. Is the mixed effect model still the best approach? Is ANOVA a better choice for the difference over time in such a small sample size?
Answer: 8 groups is not great for a random effect, but it's probably better than the alternative of using a fixed effect for each of them - especially if you are expecting group-level variation in more than the intercept. Perhaps more appropriate would be to switch to a Bayesian framework and specify your priors; the lack of data would just mean that the data will (probably) have a weak effect on your posterior, and you would have less cause to be concerned that the error estimates are poor.
But that would not be my biggest concern with this analysis. With 3 data points through time, you would have to be very confident that the metabolite will change in a specific way (e.g. linearly, exponential decay, etc). Deviation from this expected shape would be very difficult to pick up in your analysis.

Mixed effect model and sample size


guitar, six string, steel strings, what gauge will provide noticeably lighter action?

Question: My strings are old and don't remember their gauge. Either standard or on the heavy side as I like the tone of heavier gauge.
Anyway, now I want to restring the guitar for my son who is just beginning. I though lighter gauge would be easier to play. Is that the case? At what gauge is it actually noticeable?
I can always just look for whatever is lightest and just try it out.
I have to double check, but I think this is the model. Just a cheat entry level six string acoustic. It has an adjustable truss rod, but the bridge and nut and just plastic, non-adjustable.
Judging from the head stock it's a Legend Law 25. But the bridge, nut, truss rod details are the same as the other model.
If going to light gauge isn't really do-able on a cheap-o guitar like this, that's OK. But still I am curious at what gauge does action feel lighter?
Comment: @AlbrechtHügli, I had that thought, I can give it a try. But for some reason his entry point for interest in guitar is Mötley Crüe! Not sure if he'll be keen on the classical guitar. He is 14.
Comment: I have used a "custom" string set to set up many guitars for beginning students who have an acoustic guitar similar to yours.  The details can be found in this Answer on Stack Exchange. (https://music.stackexchange.com/a/29842/16897)
Comment: This is impossible to answer without the sort of guitar in question being known. Please furnish us with that relevant information! It's useful to know what the original gauges are - so a caliper gauge (that I use all the time) would be a useful addition to the armoury.
Comment: I agree with Tim.  This is a real red herring.  It also depends on how you set the bridge up, and truss rod adjustments.  In short you could put a gauge 17 on the high e string and still have very light easy to play action.  Bending might be hard but playing not.  Also, if you drastically change gauge (say 13 down to 9 or 9 up to 13) you will need a complete set up.
Comment: I don't have the guitar with me right now, but I updated with what I think it is.
Comment: How old is your sun? As this is an acoustic guitar, why not let him play on  nylon strings. It won't damage the guitar ... but it might be much more comfortable to a beginner.
Comment: playing  MÖTLEY CRÜE will always afford a little bit of masochism  ;) (btw.: Most of my pupils of that age wanted to learn at first the of smoke on the water  riff ...
Answer: You can usually step an acoustic guitar down to a lighter gauge of strings without causing too much trouble. The overall tension that the strings put on the guitar will drop, and you should have a lighter feel to the stings and a closer action on the guitar overall.
Possible problems could arise if the guitar was strung with larger gauge strings, and the truss rod had been adjusted to account for the extra tension that those strings have in standard tuning. In moving to lighter strings, the neck may not be bowed (or pulled) forward/upward as much as with the heavier strings, and in turn, the strings may run closer to the fretboard. This behavior can cause some of the strings to buzz, or even sound the wrong note on certain frets if it's bad. If that occurs, it can usually be fixed by carefully reducing the tension on the truss rod. If you are unfamiliar/uncomfortable with truss rods and their adjustment, taking the guitar to a shop to get it set up might be another option.
Answer: From your description, I think it's a fair guess that you have "medium-heavy" 12s on there now. Anything heavier than 12s on an acoustic is pretty niche.
Consequently, a set of 11s will be a little easier on the fingers without being drastically different.
With a set of 10s, you'll start to notice easier bending and an overall lighter feel.
With 9s, they'll be very pliable under the fingers. But you'll start to notice a loss of projection and volume.
With 8s, this would be a very extreme change and @whofferbert's answer would certainly come into play.
tldr;
Assuming you have 12s, get a set of 10s. They'll be lighter but (hopefully) not too light and flimsy on a normal scale length.
Comment: I appreciate that rundown of gauges. I might go with the 9s and just be aware of the consequences. Thanks!
Comment: I agree with this answer 100%; I also string 10's on acoustics. You can shred, and it still sounds reasonably good.


In Flutter, How can I detect the change if the headset is suddenly plugged

Question: I'm trying to find the method about detecting headset in Flutter.
I want to hide AlertDialog when the headset is connected.
I know that I can detect connection by using 'Initstate()'.
But, I think It's not appropriate using Initstate.
Because If user see the Alertdialog, they can plug their headset anytime and then allowed to close the Alertdialog.
I use GetX. Is there any method for this situation?
Answer: You can use the headset_connection_eventpackage: https://pub.dev/packages/headset_connection_event
It work both with physical headset plug and with blutooth headset.
Implementation example:
import 'package:flutter/material.dart';
import 'package:headset_connection_event/headset_event.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _headsetPlugin = HeadsetEvent();
  HeadsetState? _headsetState;

  @override
  void initState() {
    super.initState();

    /// if headset is plugged
    _headsetPlugin.getCurrentState.then((_val) {
      setState(() {
        _headsetState = _val;
      });
    });

    /// Detect the moment headset is plugged or unplugged
    _headsetPlugin.setListener((_val) {
      setState(() {
        _headsetState = _val;
      });
    });
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Headset Event Plugin'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.headset,
                  color: this._headsetState == HeadsetState.CONNECT ? Colors.green : Colors.red,
                ),
                Text('State : $_headsetState\n'),
              ],
            ),
          ),
        ),
      );
}


How would I sum this $\sum_{k = 0}^{\infty} \frac{(-1)^k \cos(x + 2ky)}{(2k+1)!}$?

Question: I'm studying for an admission test. One of the problem asked in a previous exam I'm looking at asks to find the sum of the series $$\sum_{k = 0}^{\infty} \frac{(-1)^k \cos(x + 2ky)}{(2k+1)!}.$$
This is not related to anything I have studied very recently and would appreciate if someone can help me with this. Thank you.
Answer: $$(-1)^k\dfrac{\cos(x+2ky)}{(2k+1)!}$$
is the Real part of
$$=\dfrac{i^{2k}e^{i(x+2ky)}}{(2k+1)!}=\dfrac{e^{ix}}{ie^{iy}}\cdot\dfrac{(ie^{iy})^{2k+1}}{(2k+1)!}$$
Now $$2\sum_{k=0}^\infty\dfrac{a^{2k+1}}{(2k+1)!}=e^a-e^{-a}$$
How to prove Euler's formula: $e^{it}=\cos t +i\sin t$? should be handy
Comment: That was fast. Thanks so much.
Comment: sir i really appericiate your answer but still it is labouring to separate the real


How to I add a column to a table, that combines strings from other columns?

Question: I am using Mysql Browser.
I have a table called "users". I am looking to create a column called, "opp". I know how to do this, with a simple Alter Table, Add statement. Where I am struggling is figuring out how to add data to the column. I want the column to be a combination of strings using concat().
The column should end looking like:
"Team(name)" where name is data from a column titled "name" in the table "users".
I have tried a Insert into statement like this:
Insert Into users (opp)
VALUES ('Team', '(', name, ')')
But that did not work. It tells me there is no such column as "name", even though there is...
Thanks for the help!
Comment: See [Why should I provide a Minimal Reproducible Example for a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query)
Answer: Once you have altered  the table you should use an UPDATE
update  users
set opp = concat( 'team(',name ,')' )
;

anyway  column like this should not be store  ..  because you can obatin this with  simply
select  concat( 'team(',name ,')' ) opp from user

Comment: @RaymondNijland  . may  be  ..  i see you ahve already asked for a sample  ..
Comment: Great @JordanFreundlich that you found you answer can you next time add a data example in your question.. Like "required" by the stackoverflow [helpdesk](https://stackoverflow.com/help/how-to-ask) guidelines ?   As that would also help stopping poeple from willing to voteclose your question as unclear
Comment: Maybe he meant that the column name needs to be concated it is not very clear what the topicstarter meant..
Comment: Got it. Thanks for the help!
Answer: Why bother adding a column?  You can use a view:
select u.*, concat('team('name , ')') as opp
from u;

Comment: Not sure about the theory, again new to databases. But It is a db of sports teams. There is an opponent column in a table that looks like "Team(name)", so I figured I needed to create an id code for all the teams, so that I can run some analysis on matchup data.


Lavaan SEM How to build the latent variable by using categorical variables

Question: In my study, I want to investigate the influence of job skills on psychology. Job skill, as an exogenous latent variable, is composed of 3 categorical variables (V1, V2 and V3 here). Psychology, as an endogenous latent variable, is composed of 4 categorical variables (V4, V5 and V6 here).
V1-V3 are nominal variables (1-4). According to the tutorial, I should divide them into three dummy variables (V1.1, V1.2, V1.3, V2.1, V2.2, V2.3, V3.1, V3.2, V3.3). V4-6 are binary variables (0 or 1).
I don't know how to build a model, especially to associate dummy variables with latent variables. I have tried like this. Is this right?
model <- '

  skills =~ V1+V2+V3

  Psy  =~ V4 +V5 +V6

  V1 ~ V1.1 + V1.2 +V1.3

  V2 ~ V2.1 +V2.2 +V2.3

  V3 ~ V3.1 +V3.2 +V3.3

  Psy ~ skills
'
fit <- sem (model, data=data, ordered =T)

Comment: Not sure what tutorial you are referring to, but factor analysis in general and `lavaan` specifically do not have measurement models for nominal indicators.  There is an IRT model (the nominal response model) that can be fitted with M*plus* (a commercial SEM software package) or an R package for IRT (e.g., `mirt`).
Comment: Thanks for your answer! The tutorial means 'lavaan' description. I will try to use 'mirt'.
Answer: As @Terrence says, "factor analysis in general and lavaan specifically do not have measurement models for nominal indicators. Nominal factor analysis models can be estimated in mplus (e.g., see Revulta, Maydeu-Olivares, & Ximénez 2020)$^1$.
@Terrence also correctly points out that measurement models with nominal indicators are typically estimated using item response theory (IRT) models. Below is some code to help you get started using the mirt package$^2$.
library(mirt)
fit <- mirt(Science, 1, 'nominal')

$^1$Note, however, that there are important differences between nominal factor analysis and other factor analysis models for categorical data. For example, the estimation of nominal factor analysis models in mplus can only be done using maximum likelihood(ML).
$^2$Note that all competent IRT software packages (e.g., flexMIRT, IRTPRO, and mirt) can estimate the (IRT) nominal response model (e.g., see Thissen, Cai, & Bock 2011).
References
Revuelta, J., Maydeu-Olivares, A., & Ximénez, C. (2020). Factor analysis for nominal (first choice) data. Structural Equation Modeling: A Multidisciplinary Journal, 27(5), 781-797.
Thissen, D., Cai, L., & Bock, R. D. (2011). The nominal categories item response model. In Handbook of polytomous item response theory models (pp. 53-86). Routledge.
Comment: Thank you for your answer, very helpful to me
Comment: I also have a question:  Can both nominal variables and  binary variables be calculated
by using package 'mirt' at the same time?
Comment: @sword_k No problem. Yes, the mirt package can accommodate multiple item types simultaneously! Also, please accept and upvote the answer since you found it helpful!


How can one know if a set is compact?

Question: How can one know if a set is compact? From the definition, a set is compact if for any open cover, there exist a finite subcover. However, it is not possible to list out all the open covers to a set. So is there any way one can know if it is a compact set? In the case $R^n$ it is easy as one only needs to check the set is closed bounded but what about other metric space or other spaces?
Comment: I guess there isnt
Comment: @Mathematics: That is certainly not compact, since the sets $\{f\mid \sup |f| < n\}$ for $n\in\mathbb N$ cover the space but don't have a finite subcover.
Comment: @Mathematics: See [here](http://www.mast.queensu.ca/~speicher/Chapter10.pdf) for examples.
Comment: Do you have an example of a space that u want to show that it is compact
Comment: @Amr Is there any general way to do it?
Comment: Or a generL way might be checking the definition itself. But I don't know if there exists an equivalent definition that is somehow much easier to check
Comment: This relationship is 'iff'. The true power of defining it this way - and there has historically been debate about the best way of defining compact - is to use it if compact, then open cover... Using it the other way round can be tricky. I suggest you take amr up on what probably was an offer to show you how to use it to show compactness. This takes a bit time to sink in, but you'll soon find it natural.
Comment: @Amr What about a set of all continuous function in the interval $[0,1]$ with supremum norm metric?
Answer: An equivalent condition in the case of metric spaces is sequential compactness: Every sequence in the space has a convergent subsequence.
There exist a number of other characterizations, but they are usually not that easy to verify (such as being complete and totally bounded).
Often, one can use basic properties of compactness to show a given space is compact. For example, a closed subset of a compact set is compact and the forward image of a compact set under a continous function is compact.
There are many results for showing that some spaces are compact. These include the Arzelà–Ascoli theorem, the Banach–Alaoglu theorem, and a number of other results. These results are important precisely because it is in general often nontrivial to show that some space is compact.

How can one know if a set is compact?


Generalization of monotonicity and condition

Question: Consider a function $f: \mathbb{R} \to \mathbb{R}$. As usual, $f$ is non-increasing if $f(x) \geq f(y)$ for all $x < y$. We also have the condition $f'(x) \leq 0$ $\forall x$, provided that $f$ is differentiable.
I can think of various generalizations of the notion of monotonicity:

There exists a finite positive number $h > 0$ such that for all $x$, there exists $y$ such that $x \leq y \leq x + h$ and $f(x) \geq f(y)$.
There exists a finite non-negative number $h \geq 0$ such that for all $x$, $f(x) \geq f(y)$ $\forall y \geq x + h$.

My questions are:

Is there any generalization of monotonicity, similar to those above and has been studied in the literature? Any pointer to references would be much appreciated.
If there is, then is there any condition in the line of the above derivative condition?
Answer: Of course your condition 1 holds for all functions because you allow $y=x$ and $f(x)=f(y)$.
With the much stronger condition

For all $x$ and all $h>0$ there exists $y$ with $x<y<x+h$ and $f(x)\ge f(y)$

even such wild functions as
$$f(x)=\begin{cases}e^x&x\in\mathbb Q\\0&x\notin\mathbb Q\end{cases}$$
would be "pseudo-monotonic non-increasing". Therefore I doubt that this kind of property is a useful concept / has been investigated in the literature.
Your second idea, however, seems quite useful as it can describe something like "noisy" decreasing functions.
Answer: I saw Property 2 used under the name of $\varepsilon$-monotonicity, where $\varepsilon$ is what you denoted by $h$. It appears in Caffarelli's work on the regularity of free boundaries, specifically in his paper A Harnack inequality approach to the regularity of free boundaries. II. Flat free boundaries are Lipschitz in Comm. Pure Appl. Math. 42 (1989), no. 1, 55–78. The book by Caffarelli and Salsa, A Geometric Approach to Free Boundary Problems, treats it on pages 205-207.
Be warned that the usage of various "[letter]-monotone" concepts is not at all consistent in the literature.


How to invoke an editor to specific line and character position relative to the line?

Question: I am working on an application that supports the ability to launch an external editor on XML validation errors, where the validation error will include the specific line and character offset in the line the error occurs.  For example, "74:62" represents the 74th line and 62nd character of that line, which is also said as, "line 74, column 62".
The problem I am having is that editors treat "column" differently.  For Vim, column 62 is a character position.  While in Oxygen XML Editor, Notepad++, and Emacs, column is a rendered position.
Why does this distinction matter? If the target line has tab characters, Notepad++ and Emacs "column" no longer represents character offset, and for those editors the cursor gets located differently: Notepad++ treats tab as 4 columns and Emacs as 8 (by default).
Here are the commands I use for each editor, where 'L' is the line number, 'C' is the column number, and 'FILE' is the file to open:

gvim "+call cursor(L,C)" FILE
oxygen FILE#line=L;column=C
notepad++ -nL -cC -lxml FILE
emacs +L:C FILE (See @Rorschach's answer below for method that does work)

For Notepad++ and Emacs, are there command-line invocations that will place the cursor at a character position relative to the line?
Edit
Oxygen XML Editor behaves as expected, where column parameter is interepreted as a character offset from line.  See @Rorschach's answer below regarding Emacs, I do not have a solution for Notepad++.
Comment: characters can have different displayed widths, eg. control characters might have a width of 2 or 4 in emacs - the [usual display table](https://www.gnu.org/software/emacs/manual/html_node/elisp/Usual-Display.html) has emacs defaults, perhaps just setting `tab-width` to 1 would be good enough for emacs? something like `emacs --eval "(setq tab-width 1)" ...` (untested)
Comment: @Rorschach Looks like the following works instead to get tab width to 1: `--eval "(setq-default tab-width 1)"`. Using this, the cursor will now be on the desired character position. Not sure how I feel about mucking with tab-width setting, but for now, seems like only thing that will provide desired behavior.
Comment: you could add a hook after emacs loads as an alternative, Ill add an example
Answer: As a workaround for different character display widths in emacs you could add a hook to run after the file loads.
# assuming there are some variables (eg. shell)
# holding the line/column as in the normal command
L=4
C=2
emacs --eval "(add-hook 'emacs-startup-hook (lambda () (goto-line $L) (forward-char $C)))" input_file.xml

Comment: Excellent! That does appear to work nicely. Looks like emacs problem is solved, but unsure if there are solutions for the other editors.
Answer: I work for Oxygen XML Editor and as far as I know Oxygen places the caret at that specific character offset, so we do not use the visual tab width representation for anything in this context.
One thing you should be aware is that in Oxygen by default if you press the "Tab" key you actually insert 4 spaces, if you want to insert the "Tab" character instead, in the Preferences->"Editor / Format" page there is a setting named "Indent with tabs" which needs to be checked.
Comment: Using a command line like this:

      oxygen.exe file:/...path/to/file.xml#line=5;column=2

on a "file.xml" which at line 5 starts with a tab character, will place the cursor after the first tab character. Indeed the editor status will show a larger column number (5 in this case) but the placement of the caret will be done as if the tab is a single character.
Comment: Dealing with XML data that can have tab characters in it, so origin may not be controled by Oxygen. As for character offset, it does appear tabs do affect how `column` is interpreted. You can observe this in the editor itself by using the keyboard to move cursor over on a line with tabs in it. You will see the column number jump by the configured tab display width. Side note, my tool will use `element` instead if possible to focus cursor in the XML, but there are cases where only line:column are available.
Comment: Looksl ike you are correct. I misinterpreted the status information to what I was expecting, but from what I observe, oxygen is placing the cursor in the expected location. I initially thought that was case, but was thrown off by the status line. FYI, Vim provides both the character position and rendered column position.


Correct way to access field values? field_view_value after field_get_items?

Question: So I want to get some field values that I need as input, sometimes for rendering.  According to this page:
http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way
It is a mistake to hard-code 'und' for internationalization, so to avoid this the author says that we should use field_view_field().
I personally, don't need all info related to the field, just the value.  So I opt for field_get_items() and then field_view_value() as outlined in the blog post.  But this seems a lot of work just to get a single value of a field (plus we have to find and load the node).  Do we really have to do so many steps to get a simple field value?  I would have thought that this would be a very common function that users need.
I'm wondering that, barring any simple method, I could just grab the value directly from field_get_items()[0]['value'].  Maybe the drawbacks are that it doesn't pass through any sanitation routines?   You can see more info here (trying to grab 'axis1t'):

Just looking for possible alternatives because my code is becoming somewhat bloated to keep getting field values this way along with the fact that they are burried inside field_collections.
Comment: I've always wondered the same thing. There must be a better way?
Answer: If you are worried about bloat, just write your own field processor and keep it all on the level. That way you are using safe values, your site won't trip over if the language settings wiggle about and you can reuse your code in your next site.
You would call it wherever you like and because you know what you're expecting to get back, you could work with it immediately.
Something like:
<?php
/* get the values out of a field */
function magic_field_values($node, $field_name, $delta = null){
  $field_items = field_get_items('node', $node, $field_name);
  /* if a delta value is supplied, render that item otherwise, send the lot
  back. */
  if ($delta){
    return field_view_value('node', $node, $field_name, $field_items[$delta]);
  } else
  return $field_items;
}
?>

Then call it with:
<?php
$cheese_samples = magic_field_values($node, 'field_cheese_samples');
foreach $cheese_samples as $sample {
//do stuff
}
?>

Comment: ...`$field_items[$delta]`


Lower bound on the volume of the intersection of two unit hyperspheres

Question: My task is to show the following: Given $x \in \mathbb{R}^d$ and let $v_d$ be a constant represent the volume of the unit hypersphere in $\mathbb{R}^d$, show that
$$\int_{\mathbb{R}^d} 1_{\{ \lVert x + b \rVert < 1 \le \lVert b \rVert\}}db \le \min\left\{v_d, \frac{\pi}{2} v_{d - 1} \lVert x \rVert\right\}$$
where $\lVert{}\cdot{}\rVert$ is the usual Euclidean norm on $\mathbb{R}^d$.
This integral can be thought as the volume of the unit ball centered at $-x$ that is outside the unit ball centered at the origin. Little bit of algebra can transformed the integral into:
$$\int_{\mathbb{R}^d} 1_{\lVert x + b \rVert < 1, \lVert b \rVert < 1}db \ge  \max\left\{0, v_d - \frac{\pi}{2} \lVert x \rVert v_{d - 1}\right\}$$
What I have done is to first prove this in the case when $d = 2$. Then, in this case $v_2 = \pi$ and $v_1 = 2$, and the integral becomes:
$$\int_{\mathbb{R}^2} 1_{\{\lVert x + b \rVert < 1, \lVert b \rVert < 1\}}db \ge \max\left\{0, \pi(1 - \lVert x \rVert)\right\}$$
Obviously, when $\lVert x \rVert \ge 1$ or $x = 0$, $\displaystyle\int_{\mathbb{R}^2} 1_{\{\lVert x + b \rVert < 1, \lVert b \rVert < 1\}}db \ge 0$. Now, consider the case $0 < \lVert x \rVert < 1$, and change the integral into polar coordinate, we need to show that
$$\int_0^1 \int_0^{2\pi} 1_{\{\vert -x_1 + r\cos \varphi \vert^2 + \vert -x_2 + r\sin \varphi \vert^2 < 1\}}rd\varphi dr \ge \pi(1 - \lVert x \rVert)$$
If we rewrite $x$ in the polar coordinates: $x = (\widetilde{r}\cos \widetilde{\varphi}, \widetilde{r}\sin \widetilde{\varphi})$ with $\widetilde{r} \in (0, 1)$, $\widetilde{\varphi} \in [0, 2\pi)$, then it becomes:
$$\int_0^1 \int_0^{2\pi} 1_{\{r^2 + \widetilde{r}^2 - 2r\widetilde{r}\cos(\varphi - \widetilde{\varphi}) < 1\}}rd\varphi dr \ge \pi(1 - \widetilde{r})$$
Here is where I got stuck and I don't know how to progress this. So, if you have any idea to progress this, I'd love to hear. Thank you.

Update 1: After tinkering a bit in R code, I find that the circle centered at the midpoint $-x/2$ with radius $\sqrt{1 - \lVert x \rVert}$ lies perfectly in the intersection:

Here's the code I use to generate this image:
<code>r = runif(1, 0, 1)
phi = runif(1, 0, 2*pi)
x1 = r*cos(phi)
x2 = r*sin(phi)
b1 = c()
b2 = c()
for(i in 1:10^5){
r = runif(1, 0, 1)
phi = runif(1, 0, 2*pi)
if((x1 + r*cos(phi))^2 + (x2 + r*sin(phi))^2 < 1)){
b1 <- c(b1, r*cos(phi))
b2 <- c(b2, r*sin(phi))}
}
flag = (b1 + x1/2)^2 + (b2 + x2/2)^2 < 1 - sqrt(x1^2 + x2^2)
plot(b1[!flag], b2[!flag], col = 'red')
points(b1[flag], b2[flag], col = 'blue')
</code>
So now, it is only sufficient to show that for $b \in \mathbb{R}^2$, $\left\lVert b + \dfrac{x}{2}\right\rVert < \sqrt{1 - \lVert x \rVert}$, then we must have
$$\begin{cases}
\lVert b \rVert < 1\\
\lVert x + b \rVert < 1
\end{cases}$$

Update 2: I'll start a bounty on this question since I can't generalized my answer below from $\mathbb{R}^2$ into $\mathbb{R}^d$.
Answer: Ok, so after the first update, I have my own answer now (at least in the case when $d = 2$). I'll show that if $\left\lVert b + \dfrac{x}{2} \right\rVert \le \sqrt{1 - \lVert x \rVert}$ then
$$
     \begin{cases}
          \lVert b \rVert < 1\\
          \lVert x + b \rVert < 1
     \end{cases}
$$
This is true since
$$
       \lVert b \rVert \le \left\lVert b + \dfrac{x}{2} \right\rVert + \left\lVert \dfrac{x}{2} \right\rVert < \sqrt{1 - \lVert x \rVert} + \dfrac{1}{2}\lVert x \rVert < 1 \ \forall x, 0 < \lVert x \rVert < 1
$$
and similarly,
$$
      \lVert x + b \rVert \le \left\lVert b + \dfrac{x}{2} \right\rVert + \left\lVert \dfrac{x}{2} \right\rVert < 1 \ \forall x, 0 < \lVert x \rVert < 1
$$
Therefore, the intersection of two circles contains a circle with radius $\sqrt{1 - \lVert x \rVert}$, and hence the area of the intersection needs to be at least greater than the area of this circle, i.e $\pi(1 - \lVert x \rVert)$
Answer: $\def\d{\mathrm{d}}\def\R{\mathbb{R}}\def\y{\tilde{y}}\def\ge{\geqslant}\def\le{\leqslant}\def\Ω{{\mitΩ}}\def\peq{\mathrel{\phantom{=}}}\def\T{^{\mathrm{T}}}$This answer proves that:

For any $x \in \R^d$,$$
\int\limits_{ \substack{ \|y\| > 1 \\ \|y - x\| \le 1 } } \d y \le \min(v_d, \|x\| v_{d - 1}).
$$

(Note that $\dfrac{\pi}{2} > 1$.)
Proof: It's trivial that $\displaystyle\int_{ \substack{ \|y\| > 1 \\ \|y - x\| \le 1 } } \d y \le v_d$.
Now since it's the Euclidean norm, it can be assumed without loss of generality that $x = (x_1, 0, \cdots, 0)\T$, where $x_1 \ge 0$. (See Appendix.) Thus $\|x\| = x_1$. For any $y \in \R^d$, denote by $y_1$ the first coordinate of $y$, and by $\y$ the point in $\R^{d - 1}$ formed by the last $d - 1$ coordinates of $y$.
For any $y \in \R^d$,\begin{align*}
&\mathrel{\phantom{\implies}}\begin{cases}
\|y\| > 1\\
\|y - x\| \le 1
\end{cases} \iff \begin{cases}
y_1^2 + \|\y\|^2 > 1\\
(y_1 - x_1)^2 + \|\y\|^2 \le 1
\end{cases}\\
&\implies \begin{cases}
\|\y\| \le 1\\
y_1 \in (-\infty, -\sqrt{ 1 - \|\y\|^2 }) \cup (\sqrt{ 1 - \|\y\|^2 }, +\infty)\\
y_1 \in [x_1 - \sqrt{ 1 - \|\y\|^2 }, x_1 + \sqrt{ 1 - \|\y\|^2 }]
\end{cases}\\
&\stackrel{ x_1 \ge 0 }{\implies} \begin{cases}
\|\y\| \le 1\\
\sqrt{ 1 - \|\y\|^2 } \le y_1 \le x_1 + \sqrt{ 1 - \|\y\|^2 },
\end{cases}
\end{align*}
therefore\begin{gather*}
\int\limits_{ \substack{ \|y\| > 1 \\ \|y - x\| \le 1 } } \d y \le \iint\limits_{ \substack{ \|\y\| \le 1 \\ \sqrt{ 1 - \|\y\|^2 } \le y_1 \le x_1 + \sqrt{ 1 - \|\y\|^2 } } } \d y_1 \d \y\\
= \int\limits_{ \|\y\| \le 1 } \d \y \int_{ \sqrt{ 1 - \|\y\|^2 } }^{ x_1 + \sqrt{ 1 - \|\y\|^2 } } \d y_1 = x_1 \int\limits_{ \|\y\| \le 1 } \d \y = x_1 v_{d - 1} = \|x\| v_{d - 1}. \tag*{$\Box$}
\end{gather*}

Appendix: For $x \ne 0$, augment it into a basis $\{x, u_2, \cdots, u_d\}$ for $\R^d$, and the Gram-Schmidt process yields an orthonormal basis $\{v_1, \cdots, v_d\}$, where $v_1 = \dfrac{x}{\|x\|}$.
Define $\Ω = (v_1, \cdots, v_n)$, $φ(u) = \Ω u$ ($u \in \R^d$), then $φ$ is an orthogonal transformation. Note that$$
φ((\|x\|, 0, \cdots, 0)\T) = \|x\| v_1 = x \implies φ^{-1}(x) = (\|x\|, 0, \cdots, 0)\T.
$$
Denote $D_y = \{y \in \R^d \mid \|y\| > 1,\ \|y - x\| \le 1\}$, then\begin{align*}
φ^{-1}(D_y) &= \{u \in \R^d \mid \|φ(u)\| > 1,\ \|φ(u) - x\| \le 1\}\\
&= \{u \in \R^d \mid \|u\| > 1,\ \|u - φ^{-1}(x)\| \le 1\} =: D_u,
\end{align*}
and the change of variable $y = φ(u)$ yields\begin{gather*}
\int_{D_y} \d y = \int_{D_u} |\det φ'(u)| \,\d u = \int_{D_u} |\det \Ω| \,\d u = \int_{D_u} \,\d u.\tag*{$\Box$}
\end{gather*}
Remark: Technically speaking, only if $\det \Ω = 1$ is $φ$ a rotation, but for this answer it suffices to have $\det \Ω = \pm 1$.
Comment: @ThànhNguyễn The intuitive explanation is that the Euclidean norm is invariant under rotations (that preserves the origin), and a suitbale rotation aligns $x$ with the $x_1$-axis. If you need a rigorous explanation, feel free to ping me again.
Comment: @ThànhNguyễn Appendix added with informative links.
Comment: "Now since it's the Euclidean norm, it can be assumed without loss of generality that $x = (x_1, 0, \ldots, 0), x_1 \ge 0$" : Can you explain this line for me ? With this assumption, how can we make this argument for any $x \in \mathbb{R}^d$ ?
Comment: Yes, I'd love to have a rigorous explanation


Is the defaultdict in Python's collections module really faster than using setdefault?

Question: I've seen other Python programmers use defaultdict from the collections module for the following use case:
from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

def main():
    d = defaultdict(list)
    for k, v in s:
        d[k].append(v)

I've typically approached this problem by using setdefault instead:
def main():
    d = {}
    for k, v in s:
        d.setdefault(k, []).append(v)

The docs do in fact claim that using defaultdict is faster, but I've seen the opposite to be true when testing myself:
$ python -mtimeit -s "from withsetdefault import main; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)];" "main()"
100000 loops, best of 3: 4.51 usec per loop
$ python -mtimeit -s "from withdefaultdict import main; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)];" "main()"
100000 loops, best of 3: 5.38 usec per loop

Is there something wrong with how I've set up the tests?
For reference, I'm using Python 2.7.3 [GCC 4.2.1 (Apple Inc. build 5666)
Comment: You need to use *much* larger test sets where there is more than 2 values per key.
Comment: did one test file contain `s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]` where the other didn't?
Comment: @Claudiu: read the timeit lines carefully.
Comment: @MartijnPieters: i did. i don't know what is in `withsetdefault.py` and `withdefaultdict.py`. if one of them contains that line and the other doesn't, that could account for the difference
Answer: Yes, there is something "wrong":
You have put the creation of the (default)dict into the statement instead of the setup. Constructing a new defaultdict is more expensive than a normal dict, and usually that's not the bottleneck you should be profiling in a program - after all, you build your data structures once but you use them many times.
If you do your tests like below, you see that defaultdict operations are indeed faster:
>>> import timeit
>>> setup1 = """from collections import defaultdict
... s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
... d = defaultdict(list)"""
>>> stmt1 = """for k, v in s:
...     d[k].append(v)"""
>>> setup2 = """s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
... d = {}"""
>>> stmt2 = """for k, v in s:
...     d.setdefault(k, []).append(v)"""
>>> timeit.timeit(setup=setup1, stmt=stmt1)
1.0283400125194078
>>> timeit.timeit(setup=setup2, stmt=stmt2)
1.7767367580925395

Python 2.7.3 on Win7 x64.
Comment: Thanks Tim! When I remove the defaultdict constructor from the test statement, it's definitely faster that using setdefault...regardless of the data size.
Comment: You only talk about constructing the (default)dict being the difference, but I'd say you also have a second difference that might be significant: In the original, 60% of all keys were new and required an insertion and used the `[]`. In your version, due to repeating each snippet a million times, it's almost 0%.
Answer: Adding to Tim's answer, when you make multiple defaultdicts, adding elements becomes costlier. Though initialization adds time, the main difference comes from the time taken to add elements to the multiple defaultdicts.
Here's some code to show the observation
import time
from collections import defaultdict

def time_taken_mult_dd(sz):
    t1 = t2 = 0
    for i1 in range(1000000):
        start1 = time.time()
        d = defaultdict(int)
        end1 = time.time()

        start2 = time.time()
        for i2 in range(sz):
            d[i2] += 1
        end2 = time.time()

        t1 += end1 - start1
        t2 += end2 - start2

    print(f"Time taken for initialization {t1:5.2f}e-06")
    print(f"Time taken for addition       {t2:5.2f}e-06")

def time_taken_one_dd(sz):
    t = 0
    d = defaultdict(int)
    for i1 in range(1000000):

        start = time.time()
        for i2 in range(sz):
            d[i2] += 1
        end = time.time()

        t += end - start

    print(f"Time taken for addition       {t:5.2f}e-06")

And here's the output. Observe how initialization time remains same while adding elements become more time consuming
>>> time_taken_one_dd(10)
Time taken for addition        1.59e-06
>>> time_taken_mult_dd(10)
Time taken for initialization  0.41e-06
Time taken for addition        2.64e-06
>>>
>>> time_taken_one_dd(50)
Time taken for addition        6.46e-06
>>> time_taken_mult_dd(50)
Time taken for initialization  0.59e-06
Time taken for addition       11.80e-06
>>>
>>> time_taken_one_dd(100)
Time taken for addition       12.61e-06
>>> time_taken_mult_dd(100)
Time taken for initialization  0.71e-06
Time taken for addition       23.05e-06


What do GC and SSC mean in the context of sprinting?

Question: I was reading the article Speed Play in Techniques magazine Volume 15, number 3 (February 2022) and encountered the following quote:

This explositivity is underpinned by a collection of neuromuscular factors including, but not limited to motor-unit typing, intra- and inter-muscular coordination, rate-coding and neural drive, whic hcollectively work to actualize sprint-movement characteristics. Because of their role in rate and magnitude of force development, these neuromuscular factors serve as prerequisites for proper mechanical actions within critical time frames. For example, sprinters who initiate GC with a stance phase that is more proximal to the center of mass at top-speed are more likely to conserve energy and prioritize elastic behavior through the SSC, a rapid and forceful lengthening of muscle-tendon complex followed by an immediate shortening or contraction (Komi, 2008).

What, exactly, are GC and SSC in this context?
Comment: @Nij I think it's a reasonable question as the article is about sprinting and EJoshuaS is trying to understand it; it answer could be "these are standard biomechanics terms, here's a brief definition". (I'd say the editor at the magazine should have ensured they were defined in the article, but that's a different question entirely...)
Comment: I'm not sure I see how this is about a specific competitive sport, as opposed to general biomechanics. Can you provide some indication as to why this counts either way?
Comment: @Nij Techniques is the (a) official magazine of the US Track and Field coaches association, so it seems to at least be aimed at competitive athletes.  While this may well be a *better* fit with [fitness.se], it's probably okay here.
Answer: SSC is the Stretch Shortening Cycle.  Imagine a spring being compressed before it pops up - that's the SSC phase.
Per Philip Kendall, GC most likely stands for Gait Cycle.
Comment: Not going to write a separate half-answer but GC is almost certainly [Gait Cycle](https://www.sciencedirect.com/topics/engineering/gait-cycle) in this context.
Comment: Hmm, you're probably right (though it's pretty similar to ground contact, so at least my intuition was close!). I'll add it to the answer if you don't mind.  Annoyed that it didn't come up with a fair amount of research into SSC, which is the easier of the two acronyms to search for...
Comment: Absolutely add it! For what it's worth... [gc biomechanics](https://www.google.com/search?q=gc+biomechanics)
Comment: Yeah, that makes more sense, the problem I ran into was there's a common author on SSC-related papers whose initials are, wait for it, GC... so that dominated the papers, and for whatever reason SSC papers usually don't talk about GC (even the paper they linked in the article didn't!).
Comment: One could also point out that SSC is defined in the question - the entire sentence following its only mention.


A Question About Code For Searching For Words Without Certain Letters In A Text File

Question: I'm currently working through a introductory python book called "Think Python". In one of the exercises, I'm supposed to write a program that takes a string of characters, and counts how many words in file called "words.txt" (http://greenteapress.com/thinkpython2/code/words.txt) do not have letters from that string of characters.
My code is here:
fin = open('words.txt')

def avoids(word,forbidden):
    avoided=True
    for i in forbidden:
        if i in word:
            avoided=False
            break #break out of for loop
    if avoided==True:
        return avoided

def number_avoids(forbidden):
    """Finds number of words excluded by character"""
    avoided=0
    for line in fin:
        if avoids(line,forbidden):
            avoided+=1
    return avoided

print(number_avoids("a"))
print(number_avoids("a"))

What I'm confused about though, is why I got two different answers for the same code. For the first print(number_avoids("a")), the result was 57196. For the second one, the program printed out 0. Could someone explain to me why the same code will give out two different answers?
Thanks.
Answer: Problem
When you open a file, there's a cursor which points to the current position in file. At first function call, this cursor is at the starting of the file. So, it reads all the contents and your program works well.
But, when you call the function second time, the cursor is at the End of File. So, there are no more characters to read. You can verify it by adding a print(line) statement inside your loop of number_avoids function.
Solution
There's a builtin function to move the file cursor. You can use it to move your cursor to initial position:
...
print(number_avoids("a"))
fin.seek(0)
print(number_avoids("a"))

It will move your cursor to the start of file. So, all of the file contents will be read and evaluated again.
Note: I have tried to make this answer as basic as I can so that it can be understood by anyone without the knowledge of file handling. Feel free to ask for any clarifications in comments.
Comment: This is a good start, but you may want to consider opening the file in the function, to avoid globals and use proper response management with `with`


Pass cropperjs output to OCR in Django

Question: In my Django App someone uploads an image, makes a box selection, clicks the button crop and the image inside the box is cropped using fengyuachen Cropperjs. I want to pass the cropped image to an OCR (in my case I use Pytesseract. I had two independent apps (one for cropping and one for OCR and both works. Now, I want to join them). So, my questions is :
How can I pass  the cropped Image to the form input that is used by pytesseract to extract the information? I'm new to Javascript so I've been struggling with it.
I think these images could help.
Someone uploads and image, selects the cropping box and then select the button crop. The image is displayed
"Someone" would click on the button Send to OCR and then Django Views recieves the input
HTML and JS code

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.11/cropper.css">

Upload Image to Crop

  <input type="file" name="image" id="image" enctype="multipart/form-data" multiple="true" onchange="readURL(this);" />

  <button id="crop_button">Crop</button>

{% if ....%}

<form method="post" enctype="multipart/form-data"  >
  {% csrf_token %}
<input type="submit" value="Send to OCR" name="cropped_result" >

</form>

<textarea name="dataPath" >{{k}}</textarea>

{% endif %}

Django View used for the OCR
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from PIL import Image
import pytesseract
import os
import csv

 def predictImage(request):

    fileObj = request.FILES['cropped_result']
    fs = FileSystemStorage()
    filePathName=fs.save(fileObj.name , fileObj)
    filePathName=fs.url(filePathName)
    testimage = '.'+filePathName
    k=pytesseract.image_to_string(Image.open(testimage))
    context = {'filePathName':filePathName,'k':k}
    return render(request,'crop.html',context)

Thanks!
Comment: The approach I was taking was "Filling a form" but it doesn't seem to be the proper way. Instead it seems better to maintain both apps separated and communicate them(i.e. send the cropped image to the server using Ajax for example and process it there using the Pytesseract app somehow).
Answer: Post request is sent using Ajax. Then the view is quite straightforward. No need to use base64, blob or any binary representation of the image. (Maybe I'm missing something or Django is really user friendly). Anyway, I hope this could help someone.
from PIL import Image
import pytesseract
import os

def main_view(request):

    form = ImageForm(request.POST or None ,request.FILES or None)
    if form.is_valid():
        instance = form.save()
        path = instance.file
        text = pytesseract.image_to_string(Image.open(path))
        print(text)

    context = {'form':form}
    return render(request, 'main.html',context)

Pass cropperjs output to OCR in Django


Using rsync to rename files during copying with --files-from?

Question: Using rsync, how can I rename files when copying with the --files-from argument? I have about 190,000 files, each of which need to be renamed when copying from source to destination. I plan to have the list of files in a text file to pass to the --files-from argument.
Answer: Unfortunately I don't think rsync has any built-in renaming capability. The first workaround that comes to mind is that you could create a local mirror directory, with (renamed) symlinks to the actual data. Then you could use rsync on the mirror directory, adding the -L option ("transform symlink into referent file/dir"). You'd want to write a quick helper script to automate updating the mirrored structure, but it doesn't sound too scary.
Answer: If your rename would consist of merely adding a suffix to the existing name, then you might be able to use the --backup and --suffix options to rsync.