PHP 7.2.8 PDO Fails to Connect to MySQL 8.0.12 (GA) in AWS EC2 LEMP Stack

Question: I'm testing a new LEMP webserver built with Ubuntu Server 18.04 LTS, NGINX 1.14, PHP 7.2.8, and MySQL 8.0.12. It is an AWS EC2 instance using the official Canonical AMI. Web and PHP work as intended aside from database connection. But I cannot connect to a MySQL database using PDO settings and functions that have worked well in other (MySQL 5.7 via PHP 7.1) cases.
I can connect reliably on server (MySQL via SSH) in the terminal using the same credentials as the PDO attempts to use. Also reliably from remote using MySQL Workbench and the same credentials. There is no on-server firewall. Firewall is via Amazon's Security Groups only. With port 3306 wide open, PHP still won't connect using a PDO. Haven't tried using MySQLi, but one purpose of this is to determine and document how to connect via PDO in this environment. So that wouldn't be a solution.
I understand the password security changed with MySQL 8 (and I chose to use the new stronger default password during install). But I also got the impression from http://php.net/manual/en/ref.pdo-mysql.php that as of PHP 7.2.4, this should work... I don't really understand what they are trying to say in the relevant paragraphs there though...
Is this not expected to work yet?
EDIT: Removed config and troubleshooting info that turned out to be irrelevant. Hoping this cleaner/shorter edit of the question is more useful to those that find it later.
Comment: How does codehawkins.com resolve on that system? Is Postgress listening on that IP address? Is there a firewall preventing db connection?
Comment: Sorry. Forgot to mention, no firewall directly on the server. It is at AWS using AWS security groups. port 3306 is open, and I can connect from my desktop using the same account with either DataGrip or MySQL Workbench. Connection works from remote by either domain or IP.

nslookup shows:
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   codehawkins.com
Address: 220.127.116.11

That last address is correct. I tried putting the IP address directly into the website config just to be sure, but no luck there either.  :-(
Comment: So, on that AWS system, you can run a "telnet codehawkins.com 3306" that doesn't hang?  You didn't answer my "is postgress listening ...".   "lsof -Pn | grep LISTEN | grep 3306" gives what?  The timeout is 30 seconds, certainly reminds me of a network problem.
Comment: "lsof -Pn | grep LISTEN | grep 3306" gives many rows similar to this (though none with IPv4 in the line):
mysqld  879  908  mysql  20u  IPv6  19421  0t0  TCP *:3306 (LISTEN)
mysqld  879  908  mysql  23u  IPv6  19652  0t0  TCP *:33060 (LISTEN)

"telnet codehawkins.com 3306" does hang, but it resolves the address. output is:

Trying 18.104.22.168...

Thanks.
Comment: Sorry about the postgress, "what the heart is full off", eh?
Comment: Can you connect through a command line client?
Comment: The error message mentioned on the manual page is a different one. All Connection timed out errors are firewall-related. So you need to make sure that all other nethods are apparently work and reflect this fact in your question,
Answer: The text on the PHP documentation page you linked to is:

MySQL 8
When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password plugin to mysql_native_password or else you will see errors similar to The server requested authentication method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.
This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP (mysqlnd) releases. Instead, change it by setting default_authentication_plugin=mysql_native_password in my.cnf. The caching_sha2_password plugin will be supported in a future PHP release. In the meantime, the mysql_xdevapi extension does support it.

This doesn't mean that PHP currently supports caching_sha2_password. It does not. It means that PHP no longer throws fatal errors when connecting to a MySQL 8.0 server that advertises support for caching_sha2_password.
You can install the named PECL extension if you wish, but it has a different API to mysqlnd, so it is not a drop-in replacement, and will not work with existing PHP code that uses mysqlnd's API.
For the moment, until a new version of PHP mysqlnd is released that actually supports authenticating with caching_sha2_password, your only option is to not use it, going back to mysql_native_password as documented.
Comment: Appreciate and am upvoting this. Accepting Gerard's also correct answer as it came in and solved the issue first, though an edit review and a time zone issue delayed that showing up until now. Thanks much!
Answer: Further investigation allowed us to learn that PHP doesn't support caching_sha2_authentication as yet, mysql had to revert to native.
NOTE: One cannot simply create accounts WITH mysql_native_password, but must set the default to mysql_native_password.
EDIT: Cut info that turned out to be unrelated to the issue.
Comment: This looked like the answer... I've set bind-address = 0.0.0.0 (any IPv4) just to test. I'm guessing it solved part of the problem, but it still refuses to connect. If I do "lsof -Pn | grep LISTEN | grep mysqld | grep", I now get many lines with IPv4 such as:  "mysqld    1796 1807            mysql   20u     IPv4              29908      0t0        TCP *:3306 (LISTEN)"
Comment: Oddly, "bind-address = 0.0.0.0" is supposed to mean IPv4 and only IPv4. However, I still see many rows similar to  "IPv6  26492  0t0 TCP *:33060 (LISTEN)"

Also, this was a complete default install... Very odd that it would not be listening on IPv4 3306 from the start. I used mysql --help to identify all the .cnf files, and none of them had a bind-address line until I added it.
Comment: So, I just checked again... I could before and can still connect with no problem using the IPv4 address (or FQDN) from a remote workstation using the domain name or IP address. Wondering how that is possible if it was not listening on IPv4 3306 (though lsof said not?). This is a single server running the full LEMP stack... Would it be something to do with having PHP and MySQL on the same machine? (Many thanks for your thoughts!)
Comment: "IPv6 26492 0t0 TCP *:33060 (LISTEN)" is not 3306!
Comment: Right... But the IPv4 lines are all 3306. Was wondering about that, but did not pursue since I am trying to connect with IPv4.
Comment: Can you add "netstat -rn" output to your question.  I'm looking for something (eg. a firewall) that prevents a client on the AWS to connect to the server on the same system.
Comment: So, everything goes to 172.31.32.1 ??   What does "ifconfig eth0" show?
Comment: according to your phpinfo, server address is 172.31.37.13, which your route config does not allow to reach.  Your MySQL is not running in a docker or something?
Comment: Editing the question to clarify environment. Not Docker, but it is AWS EC2 (a virtual server).
Comment: "route -v add -net 172.31.37.0 netmask 255.255.255.0 dev eth0"  and use 172.31.37.13 as host for PDO.  When you run "ifconfig", do you see the loopback connector?  Can you ping localhost?
Comment: I wonder if this shouldn't be handled through the AWS Management Console.  Perhaps you configured your DB as being publicly accessible only.
Comment: Tried rout -v add and the private IP with no luck. I'm confident this is not an AWS config issue, as AWS is external to the server and the same systems that would potentially cause problems, do not interfere with other (Datagrip, etc) connections. Regarding configuring the server for public only, I dropped all testuser logins and remade them for 'localhost', 127.0.0.1, 172.31.37.0, 18.104.22.168, and codehawkins.com. Then tested both local (localhost) and remote via FQDN.
Comment: At this point, I'll be happy to redeploy a server to continue testing if significant new info is found... I want to understand this. But toward having a working system I am going to shelf this and roll to earlier known-good technology.
Comment: I'll try and configure an aws comparable to yours, and get back to you with the results. That'll be during the day, it's 1 am here. Still wondering if you have loopback connector.
Comment: Sorry... I can ping localhost and do have loopback. Adding ifconfig info to the question. Also putting a link to the exact setup steps used for this server in latest addendum.
Comment: I thought to open a "free tier account" on AWS, but they want my credit card data.  I'm not willing to hand that to mr. Beezos, he's rich enough as it is.
Comment: Do you know the "RDS management console"?  "You do need to set the VPC security group to ensure that you can access the database", says https://www.dummies.com/programming/cloud-computing/amazon-web-services/access-aws-rds-management-console/
Comment: Regarding RDS, this build is not using it. RDS is an alternate (seperate server) way of hosting a DB. This system is just using an EC2 instance, which is simply a virtual server. There really isn't anything at Amazon to get in the way of it, except for their firewall. And other successful connections from outside the firewall corroborate the idea that it is not the problem.
Comment: I am happy to give you root access if you are interested in poking around. If/when a solution is found, I plan to wipe it out and rebuild to confirm and document the process of getting this working. There is nothing confidential on the server, etc.

I don't see a way to send private messages on StackExchange. I have a nearly obsolete email you could contact me on if you like... firstname.lastname@example.com. I don't want to post my regular email publicly, due to the spam that invites.
Comment: That is great, I'm really curious what is going on. Send me a pm, use one of my addresses, ghpille at hotmail or gmail dotcom.  But I'll have some sleep first.
Answer: You can change MYsql8's default authentication method in MySQL Workbench by:

Opening MySQL workbench as an administrator
First going to Options File screen highlighted with a 1 next to it in the linked screenshot.
Scrolling to then changing the authentication method with the drop-down highlighted with a 2 next to it and hitting apply in the lower right.


If A is an nxn matrix of complex numbers such that some power of A is identity, then i want to prove that A is diagonalizable over C

Question: If A is an nxn matrix of complex numbers such that some power of A is identity, then i want to prove that A is diagonalizable over C. How the proof will be followed from the jordan canonical forms?
Comment: Let $J$ be the JCF of $A$, and $S \in GL_n(C)$ such that $A=SJS^{-1}$. Then for some $k \geq 1$, $I_n = A^k = (SJS^{-1})^k = SJ^kS^{-1} \Rightarrow J^k = I_n$. Can you argue now that all of the Jordan blocks in $J$ are 1x1?
Comment: @ah11950, you should polish very little your comment and make it into an answer.+1
Comment: Done. Gosh that matrix was exhausting to typeset...!
Answer: Let $J$ be the JCF of $A$, and $S \in GL_n(\mathbb{C})$ such that $A=SJS^{−1}$. Then for some $k \geq 1$, we have
$$I_n=A^k=(SJS^{−1})^k=SJ^kS^{−1} \Rightarrow J^k = I_n.$$
Can you argue now that all of the Jordan blocks in $J$ are $1\times1$ blocks?
If we have
$$J=J_{r_1}(\lambda_1) \oplus \ldots \oplus J_{r_i}(\lambda_i)$$
Where $J_{r_{j}}(\lambda_{j})$ is the Jordan block of dimension $r_j$ corresponding to eigenvalue $\lambda_j$, then
$$J^k = J_{r_1}(\lambda_1)^k \oplus \ldots \oplus J_{r_i}(\lambda_i)^k$$
because of the way block matrices power up. Thus, we can study how a single Jordan block behaves when powered. You'll want to work out the details yourself, but a block $J_r(\lambda)$ of size $r$ for eigenvalue $\lambda$ satisfies
$$J_r(\lambda)^N = \begin{bmatrix} \lambda^N & {N \choose 1}\lambda^{N-1} & {N \choose 2}\lambda^{N-2} & \ldots & \ldots & \ldots & {N \choose r-1}\lambda^{N-r+1} \\
0 & \lambda^N & {N \choose 1}\lambda^{N-1} & \ldots & \ldots & \ldots & {N \choose r-2}\lambda^{N-r+2}\\
\vdots &  & & \ddots& & & \\
\vdots &  & & & \ddots& & \vdots \\
\vdots & & & & & \ddots & \vdots\\
0 & \ldots & \ldots & \ldots & \ldots & \ldots & \lambda^N\end{bmatrix}$$
You should be able to see that therefore the only way for us to have $J^k = I_n$ is if all Jordan blocks in $J$ are of dimension 1.
Comment: As for the last part, there seems to be a simpler approach, since each Jordan block has lower triangular form (so why is the matrix $J_r(\lambda)$ there an upper triangular one?), its power will remain lower triangular, for the latter to be diagonal, we must (must we?) have $r_i=1$ for all $i$.


Python - multithreading + csv

Question: Estou tentando escrever arquivos csv utilizando uma Thread para cada arquivo. O código itera uma lista gerada pelo groupby e chama uma thread para cada grupo.
Chamando a função diretamente os arquivos são salvos normalmente:
[save_csv(uf[0]+'.csv', header, uf[1]) for uf in ufs]
Utilizando Threads, os arquivos são salvos apenas com o cabeçalho, mesmo a funcão sendo executada até o fim
[threading.Thread(target=(save_csv), args=(uf[0]+'.csv', header, uf[1])).start()  for uf in ufs]
Função save_csv:
<code>def save_csv(file, header, content):
    with open(file, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, delimiter=';', fieldnames=header)
        writer.writeheader()
        writer.writerows(list(map(vars, content)))
</code>
Existe algum motivo pra que isso ocorra?
Obs.: O código está utilizando orientação a objetos e threads por exigência da lista de exercícios.
Answer: as variáveis "vars" e "content" são globais então serão acessadas em paralelo em todas as threads.
Você não fala e nem mostra como são criadas, não tem como saber e nem dar a resposta correta.
Só é possível adiantar que como você não passa como parâmetro, todas as threads " vão enxergar o mesmo conteúdo da variável "contents". Se você usar "multiprocessing", sim, uma "foto" das estruturas de dados globais é tirada no momento em que um subprocesso é criado, e toma vida de forma independente. Com threads, todas as threads enxergam a mesma variável.
Comment: Esclareceu a dúvida, muito obrigado!

Python - multithreading + csv


3d position to screen coordinates not working properly three js [r100]

Question: I have this really simple test scene to place a bunch of html labels on the position of a 3d object in my scene. But when ever i try converting the 3d coordinates to the screen location i get weird values that do not at all corrosponded with the position of my 3d object. See below for the code with which i generate a scene and place a label:
var CanvasContainer = document.getElementById("KettingContainer");

function CameraSetup(container){
    var camera = new THREE.PerspectiveCamera( 50, container.offsetWidth / container.offsetHeight, 1, 300 );
    camera.position.set( 0, 0, 100 );
    camera.lookAt( 0, 0, 0 );
    return camera;
}

function SceneSetup(){
    var scene = new THREE.Scene();
    return scene;
}

function RenderSetup(container) {
    var renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.autoClear = false;
    renderer.setClearColor( 0x000000, 0 );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( container.offsetWidth, container.offsetHeight );
    container.appendChild( renderer.domElement );
    return renderer;
}

function OnWindowResize(container){
    camera.aspect = container.offsetWidth / container.offsetHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( container.offsetWidth, container.offsetHeight );
}

var kraalLabels = document.getElementById('kraalLinkLabels').getElementsByTagName('div');

function Animate(){
    requestAnimationFrame(Animate);

    Render();
}

function Render(){
    renderer.render( scene, camera );
}

function createScreenVector(pos, camera, width, height) {
    const hw = width/2, hh = height/2;
    var pos2d = pos.clone();
    pos2d.project(camera);
    console.log(pos2d);
    pos2d.x = ( pos2d.x * hw ) + hw;
    pos2d.y = - ( pos2d.y * hh ) + hh;

    return pos2d;
}

function positionLabels(positions, camera, width, height){
    for( var i = 0; i < kraalLabels.length; i++ )
    {
        const d = createScreenVector(positions, camera, width, height);
        kraalLabels[i].style.left = d.x + "px";
        kraalLabels[i].style.top = d.y + "px";
    }
}

var camera = CameraSetup(CanvasContainer);
var scene = SceneSetup();
var renderer = RenderSetup(CanvasContainer);

console.log("fc: ", camera.position);

const geometry = new THREE.SphereGeometry( 10, 32, 32 );
const material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
let sphere = new THREE.Mesh( geometry, material );
sphere.position.set(20, 20, 0.1);
scene.add( sphere );

positionLabels(new THREE.Vector3(20, 20, 0.1), camera, CanvasContainer.offsetWidth, CanvasContainer.offsetHeight);

window.addEventListener("resize", function(){ OnWindowResize(CanvasContainer); }, false);
Animate();

See below a screenshot of the camera position, the canvas container size, and the screen location for each of the labels:

As you can see the positions of the labels are huge way bigger then the canvas itself. And the positions are all in the negative...
Even doh my object is just a bit to the top and left of the center of the screen..
I am completely stuck at this time i have no clue what i am doing wrong :(
If extra information is needed i am happy to clarify!
Answer: After searching for a solution for houres upon hours i finally found the problem before you do the vector3.project(camera); you have to update the camera matrix like so: camera.updateMatrixWorld(); this will fix the problem with weird values.
Hopes this helps someone in the future!


Service: v1.Service.Spec: v1.ServiceSpec.Selector: ReadString: expects " or n, but found t

Question: kubectl create -f redis.yaml
Error from server (BadRequest): error when creating "redis.yaml": Service in version "v1" cannot be handled as a Service: v1.Service.Spec: v1.ServiceSpec.Selector: ReadString: expects " or n, but found t, error found in #10 byte of ...|service":true}}}
|..., bigger context ...|79,"protocol":"TCP"}],"selector":{"redisservice":true}}}
|...

What does this error mean?
apiVersion: v1
kind: Service
metadata:
  name: redis
spec:
  selector:
    redis-service: yes
  ports:
  - protocol: TCP
    port: 6379
  - protocol: TCP
    port: 26379
  - protocol: TCP
    port: 16379

Answer: Yaml yes values evaluate to a boolean. So should  be quoted...
redis-service: "yes"


Why are my nested styles not working (using node-sass version 4.13.0)

Question: I'm doing a portfolio site with scss, but it is giving me an error when I try to do nested styles. I'm using node-sass version 4.13.0 with the script "node-sass --include-path public/css src/scss/style.scss public/css/style.css" to compile.
Here's my code:
.project-container{
  width: 100%;
  height: 30vh;

  img: {
    display: block;
    width: 100%;
    height: 100%;
  }
}

this is generating
.project-container {
  width: 100%;
  height: 30vh;
  img-display: block;
  img-width: 100%;
  img-height: 100%; }

when I try replacing img with a class name, it throws an error:
{
  "status": 1,
  "file": "D:/Tara/local_repos/web_dev/tarabryn/src/scss/style.scss",
  "line": 107,
  "column": 16,
  "message": "Invalid CSS after \"  height: 30vh;\": expected \"}\", was \".project-image: {\"",
  "formatted": "Error: Invalid CSS after \"  height: 30vh;\": expected \"}\", was \".project-image: {\"\n        on line 107 of src/scss/style.scss\n>>   height: 30vh;\r\n   ---------------^\n"
}

Answer: : after img
in
.project-container{
  width: 100%;
  height: 30vh;

  img: {
    display: block;
    width: 100%;
    height: 100%;
  }
}


usort array of arrays - list songs alphabetically

Question: So I have this set of functions that I wrote that will take the array bellow and sort all the songs alphabetically. The problem is that all it does is spit out the songs of the artist in the same order they were placed in the array.
The functions
function arraySort($a, $b){
    return $a['title'] > $b['title'];
}

function sortSongs($artist){
    $count = count($artist);
    if($count == 2){
        foreach($artist as $album=>$trackListing){
            sortSongs($artist[$album]);
        }
    }else{
       foreach($artist as $key=>&$value){
           usort($artist[$key], 'arraySort');
           print_r($artist);
       }
    }

}

sortSongs($music['Creed']);

The Array
$music = array(
    'Creed' => array(
        'Human Clay' => array(
            array(
                'title' => 'Are You Ready'
            ),
            array(
                'title' => 'What If'
            ),
            array(
                'title' => 'Beautiful'
            ),
            array(
                'title' => 'Say I'
            ),
        ),
        'Full Circle' => array(
            array(
                'title' => 'Overcome'
            ),
            array(
                'title' => 'Bread of Shame'
            ),
            array(
                'title' => 'A Thousand Faces'
            ),
            array(
                'title' => 'Suddenly'
            ),
            array(
                'title' => 'Rain'
            ),
            array(
                'title' => 'Away in Silence'
            ),
        ),
    ),
);

Note: I shortened the array for reading purposes.
So all that I am doing is saying, if the artist I pass in has 2 albums, then we pass the album name in and then  use usort on the songs of that album....All I get back is the exact same array I showed you, unsorted.
Comment: Thank you for properly formatted code.
Comment: @phpisuber01 your comment has not helped me
Answer: This is pretty crazy code.. But since you have so many nested arrays I don't really see a better way without looping over everything. Check it out. Ideally, you can take from this what you want. If you spend more time on the concept you could make some very nice array_walk functions or similar to complete the work more neatly.
Key Functions:
natsort
ksort
PHP
arraySort('Creed', $music);
echo '
';
print_r($music);
echo '
';

function arraySort($artist, &$music) {
    // Validate we have an array
    if(is_array($music[$artist])) {
        // Sort the albums the best we can (natsort not natually available for keys)
        ksort($music[$artist]);
        // Loop through the artists albums
        foreach($music[$artist] as $album_name => $album) {
            // Loop through the songs
            foreach($album as $songs)
            {
                // Let's build a new helper array of songs
                $new_array = array();
                foreach($music[$artist][$album_name] as $title)
                {
                    $new_array[] = $title['title'];
                }
                // Natural sort the songs
                natsort($new_array);

                // Reset the Songs array
                $music[$artist][$album_name] = array();

                // Replace the songs as they're sorted back into the music array
                foreach($new_array as $stitle)
                {
                    $music[$artist][$album_name][] = array('title' => $stitle);
                }
            }
        }
    }
}

Output
Array
(
    [Creed] => Array
        (
            [Full Circle] => Array
                (
                    [0] => Array
                        (
                            [title] => A Thousand Faces
                        )

                    [1] => Array
                        (
                            [title] => Away in Silence
                        )

                    [2] => Array
                        (
                            [title] => Bread of Shame
                        )

                    [3] => Array
                        (
                            [title] => Overcome
                        )

                    [4] => Array
                        (
                            [title] => Rain
                        )

                    [5] => Array
                        (
                            [title] => Suddenly
                        )

                )

            [Human Clay] => Array
                (
                    [0] => Array
                        (
                            [title] => Are You Ready
                        )

                    [1] => Array
                        (
                            [title] => Beautiful
                        )

                    [2] => Array
                        (
                            [title] => Say I
                        )

                    [3] => Array
                        (
                            [title] => What If
                        )

                )

        )

)

Answer: It looks like you are passing usort an array of 1 item, i.e. usort(array('title' => 'Rain'), arraySort);
So you're getting the same array back, because you're essentially telling it to sort nothing.
To correct the problem, you should try sending it the whole album array, so instead of artist[$key], pass it just $artist.
And as a warning your recursion base case seems very finicky, it's not a great way to test whether to recurse or not. Testing for a count of 2 will basically only work in cases where you have an array identical to the one you present, it's not a general base case.
Comment: I would accept your answer too....but I can only accept one D: I wish we could accept the primary answer and then take the secondary as "information" because his code makes sense, your explanation makes more sense.
Answer: You are right on track there, just don't need foreach for album there.
function sortSongs($artist){
$count = count($artist);
if($count == 2){
    foreach($artist as $album=>$trackListing){
        sortSongs($artist[$album]);
    }
}else{
       usort($artist, 'arraySort');
       print_r($artist);
}

}
Comment: Is there a way to do this in reverse? like instead of alphabetically how could I do it reverse z-a?
Comment: Yes, just swap `$a` and `$b` in the return/comparison line of `arraySort()`.


Can I extract html from mysql table instead of plain text?

Question: I'm using this code to extract text from the database and it works well but strips all the HTML tags.
$this->data['getshorty'] = utf8_substr(strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8')), 0, 640);

I would much rather be able to extract the string with html tags included and then choose to stop at the first or second paragraph break instead of counting 640 characters. Is this do-able?
Answer: The function strip_tags() removes all the  HTML. Remove this function from the line and it should be fine.
$this->data['getshorty'] = utf8_substr(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8'), 0, 640);

Comment: That works great... any idea how I could limit to displaying only the first couple paragraphs instead of counting to 640?


Fundamental group of quotient spaces of $SO(3)$

Question: I am trying to figure out the fundamental group (actually simply connected or not will suffice) of the following quotient space of $SO(3)$:
Let $X = SO(3)/E$, where $E$ is the equivalence relation defined as follows:
$E \equiv M \sim {S_{A}}^{i} * M * {S_{B}}^{j}$ where ${S_{A}}^{i} \in $ Crystallographic point group $A$ and ${S_{B}}^{j} \in $ Crystallographic point group $B$, $M \in SO(3)$.
$*$ represents the multiplication operation (matrix multiplication if rotations are represented as $3 \times 3$ special orthogonal matrices)
Crystallographic point group is defined here: http://en.wikipedia.org/wiki/Crystallographic_point_group
"In crystallography, a crystallographic point group is a set of symmetry operations, like rotations or reflections, that leave the crystal invariant (hence a symmetry)."
Only consider the point groups with rotational symmetries. There exist 11 crystallographic point groups for three-dimensional crystals. Let us start with just considering cyclic point groups. They are the following:
(a) $C_1 = \{I \}$   where I is the identity rotation.
If $Z_{\omega}$ is a rotation of angle $\omega$ about the $Z-$axis.
(b) $C_2 = \{I, Z_{\pi} \}$
(c) $C_3 = \{I, Z_{\frac{2\pi}{3}}, Z_{\frac{4\pi}{3}} \}$
(d) $C_4 = \{I, Z_{\frac{\pi}{2}}, Z_{\pi}, Z_{\frac{3\pi}{2}} \}$
(e) $C_6 = \{I, Z_{\frac{\pi}{3}}, Z_{\frac{2\pi}{3}}, Z_{\pi}, Z_{\frac{4\pi}{3}},  Z_{\frac{5\pi}{3}} \}$
For example if Crystallographic point group of A is $C_2$ and B is $C_3$, the equivalence relations are:
$ M \sim M * Z_{\frac{2\pi}{3}} \sim M * Z_{\frac{4\pi}{3}} \sim Z_{\pi}* M \sim Z_{\pi} * M * Z_{\frac{2\pi}{3}}  \sim Z_{\pi} * M * Z_{\frac{4\pi}{3}} $
There exists literature for cases when one of the point groups is $C_1 = \{ I \}$. In this case it is a group action on $SO(3)$ and the space $X = SO(3) / G$ where $G$ is one of the 11 crystallographic point groups. These spaces fall under the so-called spherical 3-manifolds ( http://en.wikipedia.org/wiki/Spherical_3-manifold ). When $G$ is one of the cyclic groups above, $X$ is a lens space. $L(2n,1) \cong SO(3)/ C_{n}$. I am not able to figure out how to think of these spaces when there are two point groups involved.
Progress so far: Even when there are two point groups acting on $SO(3)$, which if we refer to as $ G_{1} \backslash SO(3)/ G_{2}$ where $G_{1}$ is crystallographic point group of $A$ and $G_2$ refers to system $B$, there exists a finite subgroup of $\Gamma$ of $SO(4)$ such that  $ G_{1} \backslash SO(3)/ G_{2} \cong S^{3}/ \Gamma$. In the case $G_{1} = C_{1}$, it turns out that $\Gamma$  acts properly discontinuously and hence the fundamental group of that space is $\Gamma$ itself (from literature). But I am not sure how to check if $\Gamma$ acts "properly discontinuously" or not. And I am not sure how to check if the space is simply connected or not if $\Gamma$  does not act properly discontinuously.
Any help appreciated.
Thank you.
To answer Aaron's question: do you know how to obtain this group $\Gamma$ explicitly?
I use the quaternion representation for rotations. Let $M = (q_0, q_1, q_2, q_3)$. I also use the following fact: Each 4D rotation $R$ is in two ways the product of left- and right-isoclinic rotations $R_L$ and $R_R$. $R_L$ and $R_R$ are together determined up to the central inversion, i.e. when both $R_L$ and $R_R$ are multiplied by the central inversion their product is $R$ again. (from wiki: http://en.wikipedia.org/wiki/SO(4) ). So for any operation ${S_{A}}^{i} * M * {S_{B}}^{j}$, I can find $\Gamma_{ij}$ such that
${S_{A}}^{i} * M * {S_{B}}^{j} = \Gamma_{ij}*[q_0 \ q_1 \ q_2 \ q_3]'$.
The collection of all such $\Gamma_{ij}$ (and $\Gamma_{ij} * -I_4$, where $I_4$ is the $4 \times 4$ identity matrix) forms a finite subgroup $\Gamma$ of $SO(4)$. I used the definition provided by Aaron below for free action and found that at least for the cases where crystallographic point groups of $A$ and $B$ are the same (e.g. $C_2 \backslash SO(3) / C_2$), the action of finite subgroup $\Gamma_{C_2,C_2}$ is not properly discontinuous. Even though I tried to generalize the problem I am more interested in the cases when the crystallographic point groups of A and B are the same. So, how can I say whether this space $C_2 \backslash SO(3) / C_2$ is simply connected or not, especially now that i know that the action of $\Gamma$ is not properly discontinuous ??
Any ideas ?
Answer: This is cool.  Are you doing chemistry?
So, a slightly more standard notation might be $G_1\backslash SO(3)/G_2$ -- this indicates that you're left-multiplying by elements of $G_1$ and right-multiplying by elements of $G_2$.
A "properly discontinuous" action of a group $G$ on a space $X$ is one where every point $x\in X$ has a neighborhood $U$ such that $g(U)\cap U=\emptyset$ unless $g=1$; that is, $G$ not only acts freely (no nonidentity element has fixed points), but the nonidentity elements of $G$ take every point "sufficiently far away from itself".  This may seem vacuous, but in fact when you're working with Kleinian groups and things this can be an important condition.  However, in your case what is immediately true (since your space $SO(3)$ is Hausdorff and your groups are finite) is that any free action is automatically properly discontinuous.  So the only thing you need to check is that your actions have no fixed points.
So I guess the question becomes, do you know how to obtain this group $\Gamma$ explicitly?  If it's cyclic, it probably will be taken to be a subgroup of the circle, which acts freely on $S^3$.  (This is $S^1\subseteq \mathbb{C}$ acting on $S^3\subseteq \mathbb{C}^2$ by multiplication.)
If $\Gamma$ doesn't act properly discontinuously, things are harder.
Comment: Materials Science to be more precise. And the space $X$ is called the misorientation space. It is the rotational difference between two crystals $A$ and $B$ of different orientations. Since each crystal system has symmetries, there exist symmetrically equivalent descriptions of orientations and hence symmetrically equivalent descriptions of misorientations as given by equivalence relations $E$
Comment: Sorry I'm way late to the game, but quotienting can turn a nonsimply connected space into a simply connected one.  Take your space as $S^1$ and your group $\mathbb{Z}/2\mathbb{Z}$ acting by reflection.  Then $S^1/(\mathbb{Z}/2\mathbb{Z})$ is homeomorphic to $[0,1]$, so is contractible.  I'll try and think about Srikanth's general problem a bit.
Comment: FYI, I edited the question showing how I explicitly find $\Gamma$
Comment: Sorry to take so long.  Hopefully you'll get a notification about this.  Anyways, this is a silly question, but are your copies of $C_n$ acting in the same way?  If so, you may as well consider it as just a quotient by a single action.  In any case, if I had to guess I'd say that this is probably *not* simply-connected, just because it's an (admittedly non-free) finite quotient of a non-simply-connected space.  Intuitively, I don't see how quotienting could de-essentialize an essential loop...
Comment: You're right, I'm not sure what I was thinking (all those years ago).  Obviously, any transitive group action on a space has contractible quotient!  Thank goodness people invented stacks...


Problema quando tento salvar dados no banco Mysql no Android

Question: Estou fazendo um projeto Android que utiliza a biblioteca Ion para se comunicar com o banco de dados Mysql, porem, quando tento salva os dados, aparece este erro:
Log:
<code> 08-20 09:23:28.981 2365-2895/com.lp3bmobi.app.controlechamados W/IonConscrypt: Conscrypt initialization failed.

   java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/security/ProviderInstaller;

      at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.initialize(ConscryptMiddleware.java:58)

      at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.initialize(ConscryptMiddleware.java:75)

      at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.getSocket(ConscryptMiddleware.java:103)

      at com.koushikdutta.async.http.AsyncHttpClient.executeAffinity(AsyncHttpClient.java:301)

      at com.koushikdutta.async.http.AsyncHttpClient.access$100(AsyncHttpClient.java:51)

      at com.koushikdutta.async.http.AsyncHttpClient$1.run(AsyncHttpClient.java:190)

      at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)

      at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)

      at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)

      at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)

      at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)

      Caused by: java.lang.ClassNotFoundException: Didn't find class
      "com.google.android.gms.security.ProviderInstaller" on path:
      DexPathList[[zip file
      "/data/app/com.lp3bmobi.app.controlechamados-
      1/base.apk", zip file
      "/data/app/com.lp3bmobi.app.controlechamados-
      1/split_lib_dependencies_apk.apk", zip file
      "/data/app/com.lp3bmobi.app.controlechamados-
      1/split_lib_slice_0_apk.apk", zip file
      "/data/app/com.lp3bmobi.app.controlechamados-
       1/split_lib_slice_1_apk.apk", zip file
       "/data/app/com.lp3bmobi.app.controlechamados-
        1/split_lib_slice_2_apk.apk", zip file
       "/data/app/com.lp3bmobi.app.controlechamados-
        1/split_lib_slice_3_apk.apk", zip file
        "/data/app/com.lp3bmobi.app.controlechamados-
         1/split_lib_slice_4_apk.apk", zip file
         "/data/app/com.lp3bmobi.app.controlechamados-
         1/split_lib_slice_5_apk.apk", zip file
         "/data/app/com.lp3bmobi.app.controlechamados-
         1/split_lib_slice_6_apk.apk", zip file
         "/data/app/com.lp3bmobi.app.controlechamados-
          1/split_lib_slice_7_apk.apk", zip file
         "/data/app/com.lp3bmobi.app.controlechamados-
         1/split_lib_slice_8_apk.apk", zip file
         "/data/app/com.lp3bmobi.app.controlechamados-
         1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=
         [/vendor/lib, /system/lib]]

         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

         at java.lang.ClassLoader.loadClass(ClassLoader.java:511)

         at java.lang.ClassLoader.loadClass(ClassLoader.java:469)

         at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.initialize(ConscryptMiddleware.java:58)

         at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.initialize(ConscryptMiddleware.java:75)

         at com.koushikdutta.ion.conscrypt.ConscryptMiddleware.getSocket(ConscryptMiddleware.java:103)

         at com.koushikdutta.async.http.AsyncHttpClient.executeAffinity(AsyncHttpClient.java:301)

         at com.koushikdutta.async.http.AsyncHttpClient.access$100(AsyncHttpClient.java:51)

         at com.koushikdutta.async.http.AsyncHttpClient$1.run(AsyncHttpClient.java:190)

         at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)

         at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)

         at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)

         at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)

         at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)

         Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.security.ProviderInstaller

         at java.lang.Class.classForName(Native Method)

         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)

         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)

         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)

         ... 12 more

        Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
       08-20 09:23:58.971 2365-2365/com.lp3bmobi.app.controlechamados D/AndroidRuntime: Shutting down VM

        java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonElement com.google.gson.JsonObject.get(java.lang.String)' on a null object reference

        at com.lp3bmobi.app.controlechamados.activity.NovoClienteActivity$1$1.onCompleted(NovoClienteActivity.java:48)

        at com.lp3bmobi.app.controlechamados.activity.NovoClienteActivity$1$1.onCompleted(NovoClienteActivity.java:45)

        at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:107)

        at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:141)

        at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:124)

        at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:244)

        at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:60)

        at android.os.Handler.handleCallback(Handler.java:739)

        at android.os.Handler.dispatchMessage(Handler.java:95)

        at android.os.Looper.loop(Looper.java:135)

        at android.app.ActivityThread.main(ActivityThread.java:5254)

        at java.lang.reflect.Method.invoke(Native Method)

        at java.lang.reflect.Method.invoke(Method.java:372)

        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>
Answer: Então meu grande, sobre o erro, parece ser um lance de dependencia, verifique se chamou e configurou todas as dependências, se estiver usando o Android Studio ele já irá te informar sobre, senão verifique a versão para o android que deseja compilar e a compatibilidade desse Ion para ele.
Agora se esta usando o MySQL local sugiro usar o Sqlite que será melhor e mais rápido no quesito desempenho, veja mais em https://developer.android.com/reference/android/database/sqlite/package-summary.html
Se está tentando conexão direta com o MySQL em um servidor externo, sugiro o uso de um api/webservice/rpc para lhe ajudar a gerenciar isso e não precisar ficar abrindo conexão mobile direto com seu banco de dados. Dessa forma é melhor pois depois pode até implementar sistema de token e controle de acesso por api.


In handsontable - convert number to date by function and load refresh more data

Question: I am using handsontable for creating a CRUD (create read update delete) interface for my databases which now require these two things.

Able to create/update/delete rows/cells which are changed (and not the whole data set)
Able to load more data from database (as new records are added) or refresh changed rows

-
Part 1 (Solved) - http://jsfiddle.net/p7KwM/
So I added a field name modified as timestamp (INT) to database so that data can be refreshed at user side by checking this modified field, and it is INT so that TZ value can be added as per user. See here http://demo.mgvz.com/.twilio/loader.pl and now I am stuck at that I want to modify this INT to add TZ value and to covert it to date-time format within handsontable. (Can't do it server side) If it can be modified by way of function within handsontable, else the only option is to modify it before giving it to handsontable.
Part 2 (any help appreciated)
Second, I have to add rows which are created on server and update rows which are changed on server, without effecting other unchanged rows, (a user might be editing other rows), and to maintain sorting while adding the rows.
Can anyone guide me about it.
Thanks
Answer: To update data, have a look at setDataAtCell method:
setDataAtCell (row: Number, col: Number, value: Mixed, source: String (Optional))

To add new rows created on server, have a look at the alter method:
alter ('insert_row', index: Number, amount: Number (Optional), source: String (Optional))

You can find more detailed description of those 2 methods here
So to update something that was changed on server:
$container.handsontable('setDataAtCell', rowIndex, colNumber, "New Value");

And to add new:
var rowIndex = 2; //You will need to determine this to maintain sorting, or set to null to add as last row.
var numberOfRows 1; //Only adding one row at a time
$container.handsontable('alter', 'insert_row', rowIndex, colNumber);
//After row is added you can update the values of each column using setDataAtCell as per above
$container.handsontable('setDataAtCell', rowIndex, 1, "FirstName");
$container.handsontable('setDataAtCell', rowIndex, 2, "LastName");
//One line for each column or have a look at the setDataAtCell method for alternative option

You may enocunter issues if the user is for example editing values that need updating, or what happens if you add a row while user is editing?
I hope any of this helps
Comment: Thank you, i will try this `alter`, and also to add multiple rows and keep results sorted. As of now I had turned off sorting ;)


Como usar letras ao invés de números dentro do vetor LETTERS?

Question: O vetor LETTERS funciona da seguinte forma:
LETTERS[1:10]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

Como ajustar este vetor para inserir letras ao invés de números? Algo como:
LETTERS[A:J]
Error: object 'A' not found

Isso evitaria ter de contar as letras do alfabeto para especificar o intervalo de caracteres desejado.
Comment: `LETTERS` é um vetor (objeto), não uma função
Comment: Corrigido. Obrigado.
Answer: Uma opção (longa) seria:
LETTERS[which("A" == LETTERS):which("J" == LETTERS)]
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

Dentro de uma função:
lettersSeq = function(primeira, segunda) {
  return(LETTERS[which(primeira == LETTERS):which(segunda == LETTERS)])
}

lettersSeq("A", "J")
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"


Randomly choosing objects from a set of objects - guarantee all objects are picked at least once?

Question: I got into a debate with someone in class over an experiment that was claimed to be randomized.
The experiment was such that there is a bucket of distinct objects, and objects were being "randomly" (but independently) selected from the bucket. There are $N$ objects in the bucket, and $M$ random selections are made. The experiment was conducted such that $M>>N$, but $M$ is finite.
It was claimed that this experiment (choosing objects $M$ times) was conducted "randomly," and also that the experiment GUARANTEED that all $N$ objects would be chosen at least once. I think that "randomly" and "GUARANTEED" are mutually exclusive in this instance.
I made the argument that if the experiment guarantees that all $N$ objects would be chosen at least once, then the selections are not conducted randomly. To guarantee that all $N$ objects are selected, with a finite $M$ (albeit being much larger than $N$) would remove the randomness in my opinion? Am I right, or is it possible for this to still be random while guaranteeing all objects are selected at least once?
Note that I am not asking what is the probability of selecting all $N$ samples by making $M$ selections, where $M>>N$. I understand the probability here is close to 1. For the probability to be equal to 1, then $M\rightarrow\infty$.
Comment: You can select $M=N$ times randomly from $N$ objects and still guarantee each has been selected: just mix the objects up thoroughly and withdraw them from their population one at a time *without* replacement.  This (standard) example shows that "random" and "guarantee" are not necessarily mutually exclusive properties.
Answer: There's a distinction between asking what you've picked after $M$ draws, vs conditioning on the event that you've picked all $N$ objects after $N$ draws. The latter event is still random, for example, the total number of times each object was chosen will again be random.
Comment: If the selections are independent and random, then definitely there's no guarantee (with probability 1), that each object will be picked at least once.
Comment: Sorry, I don't think I understand. They claimed the experiment GUARANTEED that each of the $N$ objects would be drawn at least once, but that the selections were performed "randomly." I don't see how an experiment that was making $M$ draws can "guarantee" that all $N$ objects are selected at least once?
Comment: Yeah I agree, and that was the point that I was trying to make in the OP as well as during my class debate. The person seemed to suggest that because $M>>N$, this is what "guaranteed" each object was picked at least once. I think he might have used his empirical observations (which showed that each object was drawn at least once for all the experiments they conducted) to make a generalization that the probability is 1. In reality, the probability is probably close to 1, given that $M>>N$, so he may have just been lazy with words.
Comment: Right. There is on the other hand a concept of "waiting time" (or stopping time) in this case which is the first time at which you collect at least one of each object. This time is finite with probability 1.


Buildr won't generate a POM in projects with multiple packages

Question: I have a Java project that uses Apache Buildr as its build tool.  It installs a WAR and two ZIP archives to a Maven repository.  However, with Buildr 1.5.6, it seems that when the instructions to build the ZIP archives are added to the buildfile there is no .pom file generated in the output folder.
To be specific, when executing buildr clean package using this buildfile code:
task :package => [:get_svn_version]
SQL_ARCHIVE = "Project-#{VERSION_NUMBER}-sql.zip"
package(:zip, :file => _(:target, SQL_ARCHIVE)).include("src/main/sql")
CONF_ARCHIVE = "Project-#{VERSION_NUMBER}-conf.zip"
package(:zip, :file => _(:target, CONF_ARCHIVE)).include(_("conf"))
package(:war).with :libs => [PACKAGE_ONLY_DEPS, COMPILE_PACKAGE_DEPS]

...Buildr produces an output folder containing:
atg@host:> ls target
classes  Project-1.1-SNAPSHOT-conf.zip  Project-1.1-SNAPSHOT.war  test
js-test  Project-1.1-SNAPSHOT-sql.zip   resources

Whereas, just this:
task :package => [:get_svn_version]
package(:war).with :libs => [PACKAGE_ONLY_DEPS, COMPILE_PACKAGE_DEPS]

...outputs:
atg@host:> ls target
classes  js-test  Project-1.1-SNAPSHOT.pom  Project-1.1-SNAPSHOT.war  resources  test

As you can see, the .pom file is not generated in the former case, so buildr install cannot subsequently succeed.  My question, therefore, is how can I get Buildr to create a .pom file as well as my WAR and ZIP archives?
EDIT:
The following simple buildfile is enough to reproduce the issue:
# Generated by Buildr 1.5.6, change to your liking
repositories.remote << 'http://repo1.maven.org/maven2'

DUMMY_DEPENDENCIES = 'org.hamcrest:hamcrest-core:jar:1.3'

desc "Test project for stackoverflow.com"
define 'no-pom' do
  project.group = "test"
  project.version = '1.0-SNAPSHOT'

  test.with DUMMY_DEPENDENCIES

  package(:zip, :file => _("target", "configuration.zip")).include(_("conf"))
  package(:war).with :libs => [DUMMY_DEPENDENCIES]

end

This is based on the classic Maven2 auto-generated project, with App.java and the "rigorous" AppTest.java.  All I added to it was the conf folder in the project root, which just contains one dummy text file.
If you run the above then you get a WAR and "configuration.zip" created but no .pom file.  If you comment out the instruction to zip the conf folder then you get a .pom file generated along with the WAR file.
Comment: Do you reproduce with earlier versions of Buildr such as 1.5.2?
Comment: Can you create a small reproducible use case?
Comment: Hi Antoine.  I'll attempt with 1.5.2 and get back to you.  I know that on my older dev machine it worked fine, and this version didn't have the `custom_pom.rb` code. Also, for what it's worth, this warning appears when executing the .pom file task:
builder-3.2.2/lib/builder/xchar.rb:111: warning: constant ::Fixnum is deprecated
Comment: Turns out that it's exactly the same result with Buildr 1.5.2.  The `Project-1.1-SNAPSHOT.pom` file task is executed in the same way with the same deprecation warning but no actual .pom file is generated.  I'll try to make a small project to reproduce the bug in due course.
Comment: @AntoineToulme - I have added the test case to reproduce the issue as you requested.
Answer: In the absence of any response to this question or acknowledgement of this as a Buildr bug, I've managed to work around the problem by modifying the offending file in Buildr.
In the file /usr/lib64/ruby/gems/2.5.0/gems/buildr-1.5.6/lib/buildr/java/custom_pom.rb (path may vary depending on Ruby/Buildr version) look for this line:
candidates = project.packages.select{|p| p.classifier.nil? }.collect{|p|p.type.to_s}
It's line 181 for me, so it'll probably be there or thereabouts for most people.  Change it to read as follows:
candidates = project.packages.select{|p|defined? p.classifier &&p.classifier.nil? }.collect{|p|p.type.to_s}
Upon saving the file, you should be able to run buildr clean package and buildr install without any difficulty.
Disclaimer:  I am neither a Ruby programmer nor a Buildr developer, so this may be a breaking change for other areas of the software.  All I can say is that it works for me and has fixed this issue on my machine.


Cubase Elements 9 - 4/3 Time Signature

Question: I'm working with Cubase Elements 9, and I"m trying to designate different parts of my track to have different time signatures. In the tempo editor, I have the song from measure 9 onwards designated as 5/4. I'm trying to designate measures 1-8 as as 4/3. However, each time I try to change the signature from 4/4 to 4/3, it forces it to 4/2. Then, I try again to go from 4/2 to 4/3, and it forces it back to 4/4.
I failed to find a similar issue after a Google search. I also theorized that it may have to do something with quantization, but turning it off/messing with the values did not yield success.
Anyone have any idea as to what might be going on?
Edit: Thank you for all of the responses! The respondents here have clarified that I misidentified as 4:3 polyrhythm as needing to be expressed in a 4/3 time signature. Hopefully, some other poor soul may be saved from the apparent limbo that is x/3 by learning from my mistakes.
Comment: Are you certain that the time signature needs to be 4/3? It's very unusual, so possibly you mean the *rhythm* to be 4 against 3, not a *time sig.* of 4/3
Comment: I've been doing music formally since I was 4, and I don't know how I'd play/sing a meter of x/3.
Comment: @Tim Judging by the other responses I've received, you're probably right. I'm still a noob at this. :)
Answer: 4/3 is what is known as an "irrational" meter. According to the feature request Irrational Time Signature on the Steinberg forum website, Cubase is not able to handle it. However, the Steinberg forum thread Incomplete tuplet brackets in irrational meter shows that the notation can be done, just not the playback.
On this site, Can any score-writer do 'irrational' time signatures? shows how to do it in Sibelius, and MuseScore also has some support.
Answer: Following @Aaron's answer, if Cubase doesn't support such time signature, you can still find a workaround by manipulating the tempo.
E.g. if you want to have the 5/4 section in 120 BPM (120 quarter notes per minute) you can notate the 4/3 section as follows:

set time signature to 4/4
set tempo to 3/4 of the 5/4 section tempo, e.g. 3/4 × 120 BPM = 90 BPM
fill the bar with four quarter notes (rather than four half-note triplets you intended)
Answer: Are you certain that you really mean 4/3 as the time signature you want? There's no way that Cubase can handle this extremely rare, unusual and controversial time signature. It would imply that the beat unit is defined by the triplet half note, and even in my world that does rarely see this kinds of time signatures, times like 4/6 or 4/12 are far more common. And again, that's "far more common" in the context of any already exceedingly rare phenomenon.
I could see how this might have been a cool effect to get an uncommon relationship between two parts, but it's beyond the normal usage of a DAW. Can't you just select the notes that are supposed to be faster and just scale the percentage of durations and time between notes by a percentage to get the different tempo effect?
Oh wait, I see now that you're just trying to effect a tempo change, not simultaneous tempos. Can't you just put in a tempo change and not mess around with time signatures at all?
Comment: @HylianPikachu Ah!! No no, that person is talking about 4:3 polyrhythms, not 4/3 time signatures! 4:3 rhythms—usually pronounced "4 against 3"—happen whenever you have two different subdivisions happening simultaneously, most commonly sixteenth notes at the same time as eight-note triplets. This is really quite unrelated to time signatures, which are about the abstract structure of a measure of music. You can make 4:3 polyrhythms just by writing sixteenths in one part and triplets in another. The resulting composite rhythms is very similar to the phrase "pass the goddamn butter"
Comment: Whoops, I miswrote that. It should have said "signatures." My apologies. I just learned about polyrhythms, and I'm trying to see what I can do with them, so I do expect I'll end up in some... weird... places, to say the least.
Comment: @HylianPikachu I don't think I understand, you did say signatures and that's what my answer is about. And what does anything you're talking about have to do with polyrhythms? I think you're using the wrong terms for things, but I can't quite figure out what you might be intending. What you describe in the question is just a tempo change, so just change the bpm for the first eight measures.
Comment: You said "effect a tempo change," and I noticed that I said "tempos" where I meant "signatures" at some point in my question, so I thought I may have miscommunicated. I brought up polyrhythms because I heard of the notion of 4/3 from this tutorial on polyrhythms, which motivated me to try to use it: https://www.youtube.com/watch?v=c1pejTgLuhA

Cubase Elements 9 - 4/3 Time Signature


Confusion regarding proof that the variance estimator is unbiased for finite population

Question: Going through Sharon L. Lohr's Sampling design book (2nd Edition), I have no issues with the content all the way until it goes into the proof in chapter 2 on SRSWOR that $E[s^2] = S^2$, where $S^2$ is defined as:
$$
S^2 = \frac{1}{N-1}\sum_{i=1}^{N} (y_i - \bar{y}_{U})^2
$$
And the sample variance estimator is:
$$
s^2 = \frac{1}{n-1}\sum_{i\in\mathcal{S}}(y_i-\bar{y})^2
$$
where $U$ is the index set of the finite population:
$$
U = \{1,2,\dotsc,N\}
$$
And $\mathcal{S}$ is the particular sample chosen, a subset consisting of $n$ of the units in $U$.
It says:

and then find the multiplicative constant that will give the unbiasedness:
$$
\begin{align}
E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y})^2\right] & = E\left[\sum_{i\in\mathcal{S}}((y_i-\bar{y}_U) - (\bar{y}-\bar{y}_U))^2\right]\\
& = E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y}_U)^2 - n(\bar{y}-\bar{y}_U)^2\right]\\
& = E\left[\sum_{i=1}^NZ_i(y_i-\bar{y}_U)^2\right] - n\textrm{Var}(\bar{y})\\
& = \frac{n}{N}\sum_{i=1}^N(y_i-\bar{y}_U)^2-\left(1-\frac{n}{N}\right)S^2\\
& = \frac{n(N-1)}{N}S^2 - \frac{N-n}{N}S^2\\
& = (n-1)S^2
\end{align}
$$
Thus,
$$
E\left[\frac{1}{n-1}\sum_{i\in\mathcal{S}}(y_i-\bar{y})^2\right] = E[s^2] = S^2
$$

I have no issues with most of the derivation, except for how the first line turns into the second line.
I assume there must be the intermediary step:
$$
\begin{align}
E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y})^2\right] & = E\left[\sum_{i\in\mathcal{S}}((y_i-\bar{y}_U) - (\bar{y}-\bar{y}_U))^2\right]\\
& = E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y}_U)^2 - \sum_{i\in\mathcal{S}}(\bar{y}-\bar{y}_U)^2\right]\\
& = E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y}_U)^2 - n(\bar{y}-\bar{y}_U)^2\right]\\
\end{align}
$$
But I still can't get from the first line to the second.
My guesses are that either I am getting confused about what the terms mean, the notation, the summation, or I have made an obvious mistake.
Either way, any help would be greatly appreciated.
Comment: FOIL (sry for my american lingo, lmk if youre not familiar with this acronym) the terms in the parens $((y_i-\bar{y}_U))-(\bar{y}_U-\bar{y}))$ and note that $\sum_{i\in\mathcal{S}}(y_i-\bar{y})=0$.
Comment: Does this answer your question? [How exactly did statisticians agree to using (n-1) as the unbiased estimator for population variance without simulation?](https://stats.stackexchange.com/questions/100041/how-exactly-did-statisticians-agree-to-using-n-1-as-the-unbiased-estimator-for)
Comment: I don't think it does? My issue was simply getting from the first line of this specific proof to the second, which was more of an algebra issue on my part.
Comment: This is an algebra FAQ (making it difficult to search for).  It has been asked here on CV several dozen times and always has the same answer: expand the sum and simplify using the fact that the sum of the residuals is zero.
Answer: Following the intermediary step:
\begin{align}
\mathbb E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y})^2\right] & = \mathbb E\left[\sum_{i\in\mathcal{S}}((y_i-\bar{y}_U) - (\bar{y}-\bar{y}_U))^2\right]\\ &= \mathbb E\left[\sum_{i\in\mathcal{S}}(y_i-\bar{y}_U)^2 +n(\bar{y}-\bar{y}_U)^2-2(\bar{y}-\bar{y}_U)\underbrace{\sum_{i\in\mathcal{S}}(y_i-\bar{y}_U)}_{=  n(\bar{y}-\bar{y}_U)}\right] .
\end{align}


Cohomology ring of product of even dimensional sphere with odd sphere

Question: The cohomology ring of an even dimensional sphere is $\mathbb{Z}[\alpha]/(\alpha^2)$ where the degree of $\alpha$ is the dimension of the sphere. From the Künneth formula, the cohomology ring of a product of even dimensional spheres is $\mathbb{Z}[\alpha]/(\alpha^2) \otimes \mathbb{Z}[\beta]/(\beta^2) \simeq \mathbb{Z}[\alpha,\beta]/(\alpha^2,\beta^2)$.
I want to focus on the isomorphism between the above tensor product of polynomial rings with the two variable polynomial ring.
In particular the case of an odd dimensional sphere, according to Hatcher, the cohomology ring of an odd dimensional sphere is the exterior algebra $\Lambda[\alpha]$ where the degree of $\alpha$ is odd. For an exterior algebra of more than one variable, the generators anti-commute which, from my understanding, is the real distinction between an exterior algebra and the polynomial ring $\mathbb{Z}[\alpha]/(\alpha^2)$. In the case of a one variable exterior algebra, it seems there is no difference between the polynomial ring and the exterior algebra.
If, for example, one wishes to compute the polynomial ring of, say, $S^3 \times S^2$, we have by Künneth that the polynomial ring is $\Lambda[\alpha] \otimes \mathbb{Z}[\beta]/(\beta^2)$ where the degrees of $\alpha$ and $\beta$ are 3 and 2, respectively.
My question is, can we say that the above graded tensor product is isomorphic to $\mathbb{Z}[\alpha,\beta]/(\alpha^2,\beta^2)$?
I believe we can, because the cup product multiplication satisfies $\alpha\beta = (-1)^{|\alpha||\beta|}\beta\alpha$ and, because the degree of $\beta$ is even, this means that $\alpha$ and $\beta$ commute.

Is this logic correct?
Answer: Let's consider $S^{2n}\times S^{2m+1}$, where $m,n\in\Bbb Z^+$, then $H^*(S^{2n}\times S^{2m+1})\cong \Lambda_{\Bbb Z}[\alpha]\otimes \Bbb Z[\beta]/(\beta^2)$, where $|\alpha|=2m+1,|\beta|=2n$.

There is a difference between $\Lambda[\alpha]$ and $\Bbb Z[\alpha]/(\alpha^2)$ (degree odd). The reason is that for the latter quotient ring to make sense, we may expect $\Bbb Z[\alpha]$ to exist, but $\alpha^2=(-1)^{(2m+1)^2}\alpha^2=-\alpha^2\implies 2\alpha^2=0$, which is impossible. It doesn't make much sense to take the quotient of something that doesn't really exist, so I think Hatcher avoids writing exterior algebra generated by one odd degree element as a truncated polynomial ring of $R[\alpha]$ unless $2=0$ is true in $R$, in which case either way is fine. But we still have $\Lambda[\alpha]\cong\Bbb Z[\alpha]/(\alpha^2)$ in any case as $\alpha^2$ gets quotient out, so I think it's more of a matter of 'notation'. When it comes to the structure (operations, etc.), the addition is the same but the multiplication in $\Lambda[\alpha]$ is just the usual multiplication of polynomial with an additional relation $\alpha^2=0$.
It's true that $\Lambda_{\Bbb Z}[\alpha]\otimes \Bbb Z[\beta]/(\beta^2)\cong \Bbb Z[\alpha,\beta]/(x^2,y^2)$, and I think that it can be justified by your observation. Alternatively, we can define the isomorphism, say $\phi$. Let $\psi:\Lambda[\alpha]\to\Bbb Z[\alpha]/(\alpha^2)$ with $\alpha\mapsto\alpha$ be an isomorphism, then $\phi:=\psi\otimes\operatorname{id_{\Bbb Z[\beta](\beta^2)}}$, then it becomes the tensor product of two truncated polynomial rings.
For the same reason as in 1, it makes more sense to write $H^*(S^{2n}\times S^{2m+1})\cong \Lambda_{\Bbb Z}[\alpha]\otimes \Bbb Z[\beta]/(\beta^2)$ than the other way (in Hatcher's book).


gitlab-ctl reconfigure error when creating user/group on initial install

Question: I'm trying to run Gitlab CE on RHEL 7.2 (Maipo).  I've completed the Gitlab install.  However I'm unable to run sudo gitlab-ctl reconfigure.  The error, environment details and what I've tried is outlined below.  Does anyone know what I'm missing or doing wrong?
Error
================================================================================
Error executing action `create` on resource 'user[Webserver user and group]'
================================================================================

Mixlib::ShellOut::ShellCommandFailed
------------------------------------
Expected process to exit with [0], but received '6'
---- Begin output of ["usermod", "-s", "/bin/false", "-d", "/var/opt/gitlab/nginx", "gitlab-www"] ----
STDOUT:
STDERR: usermod: user 'gitlab-www' does not exist in /etc/passwd
---- End output of ["usermod", "-s", "/bin/false", "-d", "/var/opt/gitlab/nginx", "gitlab-www"] ----
Ran ["usermod", "-s", "/bin/false", "-d", "/var/opt/gitlab/nginx", "gitlab-www"] returned 6

Environment
RHEL 7.2 (Maipo), Chef Client, version 12.12.15 (taken for the gitlab-ctl reconfigure output)
What I've tried

Followed install steps here for RHEL 7.
Manually add the gitlab-www user:  When executing this sudo useradd -s /bin/false -d /var/opt/gitlab/nginx gitlab-www I get the error useradd: user 'gitlab-www' already exists.  However I verified a record for gitlab-www doesn't exist in /etc/passwd.
Renamed users in gitlab.rb:  I renamed the following users in /etc/gitlab/gitlab.rb [git, gitlab-www, git-redis, and gitlab-psql].  That does allow me to run gitlab-ctl reconfigure successfully but this seems like a super hack and I don't know what the impact is to the Gitlab installation.  I had to rename all those users because after renaming gitlab-www I would get the same error with the user git, then git-redis and so on.
Answer: When a user is created properly, it gets added to two files - /etc/passwd and /etc/shadow. The former contains info about the home directory, login shell etc; the latter contains the encrypted password for the user.
From your description, I should guess that the user exists in /etc/shadow but not in /etc/passwd.
The simplest solution is to either edit /etc/shadow (using sudo) and remove the line that looks something like
gitlab-www:!!:12345::::::

Another possibility is to manually add the user to /etc/passwd. First, find the UID in the shadow file:
[jenny@finch ~]$ sudo grep gitlab-www /etc/shadow | cut -d: -f3
12345
[jenny@finch ~]$ sudo vi + /etc/passwd

Then add the following line:
 gitlab-www:x:12345:12345:Gitlab WWW user:/var/opt/gitlab/nginx:/bin/false

Comment: I don't see the gitlab-www user in /etc/shadow either.  I checked by [sudo cat /etc/shadow].  Looking for the UID in the shadow with the command you suggested outputs nothing.  Thanks
Answer: Stop the gitlab service first gitlab-ctl stop
Then do gitlab-ctl reconfigure, once its completed, run the command gitlab-ctl start


How to find a pointset with unique distances

Question: Is there a way to arrange N number of 2D points within a box so that the distances between the points are unique?
I have an application where I can measure the distances between points with some accuracy. At the time of measurement I don't know between which points I am measuring. I thus need to match the measured value against an exptected distance and see which is closest.
Taking more and more measurements into account I should be able to rule out which point has a certain id.
But is there a mathematical method to actualy place the points optimally?
Answer: Best known solutions for choosing up to 26 points in a lattice can be found at No Repeated Distances.  It is a very hard combinatorial problem.
Answer: You can easily put the points on a line so that each distance is unique:
If $x_1,x_2,..,x_n$ are your $n$ points, put them on a ray starting at $O$, in this order such that $d(x_{i},O)=2^{i-1}$. It follows that
$$d(x_{i},x_j)=|2^{i-1}-2^{j-1}| \,.$$
And it is easy to prove that $2^a-2^b=2^c-2^d$ implies $(a=c)$ and $(b=d)$.


TCP socket communication failed after the first trial

Question: I have received error message after the client side successful received one message from server side. The error message is: Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
It seems in client class, line = inFromserver.readLine(); would not receive any message from server, making it become "null". But I dont know why.  Could somebody please help me?
Server class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class ConcurrentServer {
   public static void main(String args[]) throws IOException
   {
    int portNumber = 20020;
    ServerSocket serverSocket = new ServerSocket(portNumber);
    while ( true ) {
        new ServerConnection(serverSocket.accept()).start();
    }

}

}

class ServerConnection extends Thread
{
    Socket clientSocket;
    PrintWriter outToClient;

   ServerConnection (Socket clientSocket) throws SocketException
   {
    this.clientSocket = clientSocket;
    setPriority(NORM_PRIORITY - 1);
}

public void run()
{
    BufferedReader inFromClient;
    try{
        inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        OutputStream outToClient = clientSocket.getOutputStream();
        PrintWriter printOutPut = new PrintWriter(new OutputStreamWriter(outToClient),true);
        String request= inFromClient.readLine();
        if(request !=null)
        {
            if(!request.equalsIgnoreCase("finished"))
            {
                printOutPut.write("Receving data");
            }
            else
            {
                printOutPut.write("file received");
            }
        }

        }catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        }

        try
        {
            clientSocket.close();
        }catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            }
    }
}

client class
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;

public class client{

public static void main(String[] args) throws Exception{

    final int PORT=20020;
    String serverHostname = new String("127.0.0.1");

    Socket socket;
    PrintWriter outToServer;
    BufferedReader inFromServer;
    BufferedReader inFromUser;
    byte[] dataToTransfer;
    String line;
    int counter=0;
    int i=0;

    socket = new Socket(serverHostname, PORT);
    outToServer = new PrintWriter(socket.getOutputStream(),true);
    inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    inFromUser = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Simulation of file transferring");
    System.out.println("Enter the file size you want to transfer (Max Size 50MB)");

    int userInput = Integer.parseInt(inFromUser.readLine());

    System.out.println("Transferring start");

    boolean connection = true;
    while(connection)
    {

        //set transfer rate at 1MB/s
        dataToTransfer = new byte[1000000];

        Thread.sleep(1000);

        if(i<userInput)
        {
            outToServer.println(dataToTransfer);
            counter++;
            System.out.println(counter + "MB file has been transferred");
        }
        else
        {
            outToServer.println("Finished");
        }

        line = inFromServer.readLine();
        System.out.println(line);
        if(!line.equalsIgnoreCase("file received"))
        {

        }
        else
        {
            System.out.println("Transfer completed");
            break;
        }
        i++;
    }

    outToServer.close();
    inFromServer.close();
    inFromUser.close();
    socket.close();
}

}

Answer: You are sending byte array from client to server and reading string on server side.
Insert somthing in your byte array and then Convert your byte array into String
String str = new String(dataToTransfer,int offset, 1000000);
then write:
outToServer.println(str);


How do I solve this differential equation with the initial condition?

Question: DE: $$y'\cos x+2y\sin x=0$$
IC:$$y(\pi/2)=1/2$$
Here is my work so far:
Step 1 (divide the equation by $cosx$ and arrange the terms):
$$\frac{dy}{dx}=-2y\tan x$$
Step 2 (separate the variables and integrate):
$$\int\frac{dy}{-2y}=\int\frac{\sin x}{\cos x}$$
Step 3:
$$-\frac{1}{2}\ln y=-\ln|\cos x|+C$$
Step 4 (Plugging in the Initial Condition and find C):
$$-\frac{1}{2}\ln(\frac{1}{2})=-\ln|\cos(\frac{\pi}{2})|+C$$
The problem now is $\ln0$ is on the right side.
Did I solve the DE wrong?
Comment: To repeat what others already mentioned, perhaps more explicitly, if indeed $$y'(x)\cos(x)+2y(x)\sin(x)=0$$ for every $x$ in an unspecified interval containing $x_0=\frac\pi2$ and if $$y(x_0)=\tfrac12$$ then $$1=y'(x_0)\cdot0+2\cdot\tfrac12\cdot1=0$$ which is absurd. Hence this differential equation has no solution such that $y(x_0)=\frac12$ (and actually, no solution such that $y(x_0)\ne0$).
Comment: i have the solution $$y(x)=C\cos(x)^2$$ i think it is the same
Comment: What is C in your case?
Comment: Your **IC** doesn't satisfy your **DE**
Comment: but since $$\cos(\frac{\pi}{2})=0$$ your Logarithmus function is not defined
Comment: The IC is for the solution not the DE.
Comment: Not different. It must to satisfy.
Comment: The IC don't satisfy the DE, ergo, there can't be any derivable function that is solution of the DE and also that satisfices the IC
Answer: Well, we have:
$$\text{y}'\left(x\right)\cdot\cos\left(x\right)+2\cdot\text{y}\left(x\right)\cdot\sin\left(x\right)=0\space\Longleftrightarrow\space\int\frac{\text{y}'\left(x\right)}{\text{y}\left(x\right)}\space\text{d}x=\int\frac{-2\cdot\sin\left(x\right)}{\cos\left(x\right)}\space\text{d}x\tag1$$
Now, use:

$$\int\frac{\text{y}'\left(x\right)}{\text{y}\left(x\right)}\space\text{d}x=\ln\left|\text{y}\left(x\right)\right|+\text{C}_1\tag2$$
$$\int\frac{-2\cdot\sin\left(x\right)}{\cos\left(x\right)}\space\text{d}x=
-2\int\tan\left(x\right)\space\text{d}x=2\ln\left|\cos\left(x\right)\right|+\text{C}_2\tag3$$

So, we get that:
$$\ln\left|\text{y}\left(x\right)\right|=2\cdot\ln\left|\cos\left(x\right)\right|+\text{C}\tag4$$
When we want to solve $\text{C}$, use the initial condition $\text{y}\left(\frac{\pi}{2}\right)=\frac{1}{2}$, but we get:
$$\cos\left(\frac{\pi}{2}\right)=0\tag5$$
And, when we know that:
$$\lim_{x\to\frac{\pi}{2}}\ln\left|\cos\left(x\right)\right|=\lim_{\text{n}\to0}\ln\text{n}\space\space\space\to\space\space\space-\infty\tag6$$
And so, we get:
$$\ln\left|\frac{1}{2}\right|=-\ln(2)\ne\lim_{x\to\frac{\pi}{2}}\ln\left|\cos\left(x\right)\right|=\lim_{\text{n}\to0}\ln\text{n}\space\space\space\to\space\space\space-\infty\tag7$$
Comment: So the conclusion is the two sides don't equal? Why?
Comment: That is strange. Maybe the wrong initial condition?
Comment: @user132522 because $-\ln(2)\approx-0.6931471806$ and that does not tends toward $-\infty$. So when you want to solve $\text{C}$ it will not be a 'number'! So, we can conclude that when we want to solve: $$\ln\left|\frac{1}{2}\right|=-\ln(2)=2\cdot\ln\left|\cos\left(\frac{\pi}{2}\right)\right|+\text{C}$$ there are no solutions for this equation!!! Because we will something like: $$-\ln(2)=2\cdot\left(-\infty\right)+\text{C}$$ And that is really strange (also keep in mind that $-\infty$ or $\infty$ is not defined as a number, so my notation is strange and only to let you see what happend)
Comment: @user132522 Yes, that is the only option left!!
Comment: This repeats the content of the OP and avoids the question asked.
Comment: ?? Well, yes, indeed a factual argument. You should know by now that offtopic and/or actually wrong answers are routinely accepted on the site (your own collection of answers being as good as any database of the phenomenon).


Getting Unkown target for HPA

Question: Am actually new to kubernetes, but as now am good with the terms such as deployment, pods etc.
Well i was trying an example of HPA (Horizontal pod autoscaler), and as prerequisite metrics-servers is already integrated, but after all those things am not able to see HPA working as expected
enter image description here
When execute below cmd-
Kubectl get hpa
Unknown in the target, although i have tried all my luck referring online forum but didn't got any break through
Any help would be really appreciated
Thank you
Comment: try the following, A. kubectl describe hpa # to get more info. B. Do set up manually MENU>kubernetes engine>workloads>your workload>actions>autoscale . C. check metrics agent pods. D. check at monitoring whether you have data
Comment: thanks @danyL for the input, i have cross checked although at UI am able to see the metric data such as cpu and memory utilization for my workload. but the same is not reflecting for hpa to work, also when when executed above cmd (A) it says
Comment: `the HPA was unable to compute the replica count: failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server is currently unable to handle the request (get pods.metrics.k8s.io)
Events: `
Comment: Not sure but this person had a similar case where [cpu request was missing](https://www.fixes.pub/program/916208.html). you will need to translate to english.
Answer: I was getting same issue, fixed after adding cpu requests in my pod defination. Below points can be the reason in most of the cases

Metric server is not installed in your kubernates cluster, you can check with command
(kubectl get deploy,svc -n kube-system | egrep metrics-server)
Check if you have provided resources for deployment/sts/pod definations

Getting Unkown target for HPA


Program a handler for a stop loss

Question: I would like to execute a series of commands every time when a stop loss (or take profit) automatically triggers.
I am not sure how to do it, because I haven't found handlers for these events.
Answer: <code>void OnTradeTransaction(const MqlTradeTransaction& trans,const MqlTradeRequest& request,const MqlTradeResult& result)
   {
    if(trans.type!=TRADE_TRANSACTION_DEAL_ADD)return;
    if(!HistoryDealSelect(trans.deal))return;
    if(HistoryDealGetInteger(trans.deal,DEAL_MAGIC)!=InpMagicNumber)return;
    if(HistoryDealGetInteger(trans.deal,DEAL_ENTRY)!=DEAL_ENTRY_OUT)return;
    if(HistoryDealGetString(trans.deal,DEAL_SYMBOL)!=_Symbol)return;
    long reason=HistoryDealGetInteger(trans.deal,DEAL_REASON);
    if(reason==DEAL_REASON_SL)
       {
        Print(__LINE__,__FILE__," we are afraid SL is hit);
       }
    else if(reason==DEAL_REASON_TP)
       {
        Print(__LINE__,__FILE__," TP is HIT!);
       }
   }
</code>
Comment: just in case it was MQL4/5 question, MQL4 does not support this magic. `OnTradeTransaction()` is basic event so no need to put it anywhere, it is another event handler like `OnTick` or `OnTimer`
Comment: Could you edit your answer with a small explanation? Because "HistoryDealGetInteger(trans.deal,DEAL_REASON);"  always returns 0.
Comment: `https://www.mql5.com/en/docs/constants/tradingconstants/dealproperties#enum_deal_reason` is list of reasons. if you close a deal manually reason is 0. try to wait till sl or tp is hit. You can also convert your reason into `string` using `EnumToString`
Comment: You would first need to cast `reason` from `long` to `ENUM_DEAL_REASON` before using `EnumToString`
Comment: Ok! One more question, is it possible that the handler is executed in the next tick? After debugging, is what I see...
Comment: `OnTradeTransaction` is called independently of `OnTick`. Of course in tester it works one after another, depending on the delay you have set, in real time it is unknown which of the two events comes first.

Program a handler for a stop loss


DNS Error Randomly Takes Down Site All Day

Question: I need some help on why one of my sites constantly goes offline and back online all day like 30 times a day!. The downtime varies from 10 Minutes to 55 Minutes and its really affecting me. I have other sites running just fine on the same server, same Plesk, same IIS.
Here are some details:

The Domain is registered at GoDaddy.com (in case you need me to look up something
Server is Windows 2008 R2
Plesk is the Control Panel 9.x
Running IIS 7

I was told Plesk has its own DNS so the IIS one is Off so leave it off. Not sure if this is true but since all my other sites run just fine, this is probably true.
I would appreciate the help if someone can tell me what I need to fix/add/change to this domain!
Answer: The domain outlooksync.com is registered with two nameservers, NS1.MSWINDOWSHOST.COM and NS2.MSWINDOWSHOST.COM. These are also the nameservers for mswindowshost.com, which requires registrar glue. But no registrar glue has been provided. So this happens:
1) Client wants to find www.outlooksync.com.
2) It has to ask ns1.mswindowshost.com.
3) So it looks up the nameserver for mswindowshost.com and gets ns1.mswindowshost.com.
4) Infinite loop. Oops.
Someone has to fix the registration for mswindowshost.com (by adding glue or changing the nameservers) or someone has to change the nameservers for outlooksync.com.
Update: Right now, the registrar says this:
mswindowshost.com
Domain servers in listed order:
  NS1.MSWINDOWSHOST.COM
  NS2.MSWINDOWSHOST.COM
  NS3.MSWINDOWSHOST.COM

But the nameservers say this:
  mswindowshost.com       nameserver = ns.mswindowshost.com.

Comment: I miss the old days when WHOIS lookups returned the names *and* IP addresses of authoritative name servers.
Comment: I changed the IP of outlooksync.com to a different IP address.  I have let it propogate for 3 days+  and I still have constant, constant downtime for various minutes all day.  now I do want to state I did have a 100% update for 18 hours just yesterday and I thought the issue was solved.  but then it started going in and out again.  Now what else could be wrong?  Strangest thing is that the server also hosts alot of my domains(dedicated server) and they are all OK, except outlooksync.com.  thanks David...in advance...
Comment: You need to fix the actual problem. Read my answer. Nothing has been fixed, I just confirmed the problem is still exactly the same. You have a loop: `outlooksync.com` -> `ns1/ns2.mswindowshost.com` -> `mswindowshost.com` -> `ns1/ns2.mswindowshost.com`. The problem has nothing to do with the IP, it has to do with how a client's nameserver would find the IP addresses of the nameservers.
Comment: then the same settings are on www.brightslides.com  so why does that have no issues?
Comment: Actually, the problem is subtly different. The registrar thinks the nameservers for `mswindowshost.com` are `ns1.mswindowshost.com` and `ns2.mswindowshost.com` and the zone file says it's just `ns.mswindowshost.com`.
Comment: I think I got what you mean!  I added a new host name in go daddy of ns3.mswindowshost.com and attached an IP address of the server to it.  Am I correct?  I folowed directions from here: http://www.zerigo.com/docs/managed-dns/glue_records_at_godaddy   So I just made the changes...we'll check back in a few days ! :)
Comment: Actually, since its already says "ns"....maybe I should Glue the record to "ns" rather than "ns3".....your suggestion?  ( I think I could go back and make the changes.)
Comment: Just make sure the information you give the registrar matches the information in the zone your DNS server is offering. Your zone still has only `ns.mswindowshost.com` for `mswindowshost.com`. Also, your zone serial number is zero, which isn't a good thing to leave it at.
Comment: Issue Solved. Added the IP address/new "ns" entry in GoDaddy under Hosts Summary.  Then I added the newly created ns entry under NameServers.  thanks David after going crazy from it for 3 months!
Answer: Then you need to contact your hosting provider to check what is the issue. Or you can find another hosting provider that have UPTIME Guarantee. You can check it at http://www.microsoft.com/web/Hosting/Home. Good luck
Comment: Its my own dedicated server that hosts a number of my other sites, which are all 100% uptime.  Its only this domain.


How to remove or change "height" at element.style?

Question: I'm marking some image page with figure&figcaption which is sort of gallery slider.
But the height size is all of same automatically in element style figure img, figcaption img as well when I saw the code in Chrome developer tools.
I think I need to change this code.

 for( var i = 0; i < wall.itemsCount; ++i ) {

    var $item = wall.$items.eq( i );

    $item.appendTo( $wallElem );

    var itemH = $item.height(),
     figcaptionH = $item.find( 'figcaption' ).outerHeight( true );

    if( itemH > wallH - wallmargins ) {
     $item.find('img').height( wallH - wallmargins - figcaptionH );
     $item.css( 'top', ( wallmargins / 2 ));
    }
    else {
     $item.css( 'top', ( wallH - itemH ) / 2 );
    }

please give me advice.
Answer: If you want to update the height for only figcaption img, then update your selector to include that
$item.find('figcaption img').height(wallH - wallmargins - figcaptionH);

Comment: Thank you for reply.

I changed the code as you wrote.

but I don't want to change figure size. It has to same size.

http://tympanus.net/Development/3DGalleryRoom/

I'm doing it


Django adds extra columns to group by

Question: I have the following queryset:
Pago.objects.filter(created__range=(self.inicio, self.fin)).values('tipo__nombre').annotate(monto=Sum('monto'))

And it is producing the following SQL:
SELECT "invoice_tipopago"."nombre", SUM("invoice_pago"."monto") AS "monto" FROM "invoice_pago" INNER JOIN "invoice_tipopago" ON ( "invoice_pago"."tipo_id" = "invoice_tipopago"."id" ) WHERE "invoice_pago"."created" BETWEEN 2015-01-01 00:00:00-06:00 AND 2015-06-04 14:18:00-06:00 GROUP BY "invoice_tipopago"."nombre", "invoice_pago"."modified", "invoice_pago"."created" ORDER BY "invoice_pago"."modified" DESC, "invoice_pago"."created" DESC

It is adding the extra modified and created columns that I am not specifying, and i would like to know how to avoid it. It should be noticed that Pago is a derived from the django-extensions TimeStampedModel class.
Thanks in advance.
Answer: I took a look at TimeStampedModeland it set a default ordering in the class meta:
class TimeStampedModel(models.Model):
""" TimeStampedModel
An abstract base class model that provides self-managed "created" and
"modified" fields.
"""
created = CreationDateTimeField(_('created'))
modified = ModificationDateTimeField(_('modified'))

class Meta:
    get_latest_by = 'modified'
    ordering = ('-modified', '-created',)
             # ^^^^^^^^^^^^^^^^^^^^^^^^^^
    abstract = True

see in github
You could overwrite that providing another filter to order by (like tipo__nombre or monto), ex:
Pago.objects.filter(
    created__range=(self.inicio, self.fin)
).values(
    'tipo__nombre'
).annotate(
    monto=Sum('monto')
).order_by(
    'tipo__nombre'
)

Comment: Yup, that was it, i simply added order_by() to remove all ordering, I don't know why I never read about this behavior on Django ORM, it specifically says that it never automatically removes any ordering you specify unless you do this.

Django adds extra columns to group by


how to get matched group number in pcre2

Question: I want to use pcre2 to match string.
For example, I have several string pattern, "a","b","c","d", and "e".
I have a long text "str" to match.
Now I construct a pattern "a|b|c|d|e"  to match "str" use pcre2_match.
How to know which pattern is matched?
I just want to get the matched pattern number, not "a" or "b", as I don't want to compare the matched pattern with "a","b","c","d","e" again.
Answer: Assuming you're using the PCRE2 library directly and have access to all of its features, you have several solutions for this, from the simplest to the most involved:

Use numbered capture groups: (a)|(b)|(c)|(d)
Use named capture groups: (?a)|(?b)|(?<c>c)|(?<d>d)
Use marks: a(*MARK:a)|b(*MARK:b)|c(*MARK:c)|d(*MARK:d)
Use callouts: a(?C{a})|b(?C{b})|c(?C{c})|d(?C{d})
If you really can't modify your input pattern, use PCRE2_AUTO_CALLOUT and find some way to map pattern offsets to branches, then rememeber the last pattern offset seen before the end of the match
Comment: By using numbered capture groups: (a)|(b)|(c)|(d) , how can I get the number of matched group? Where is it stored?
Comment: @johnhypo it's in the [match data block](http://pcre.org/current/doc/html/pcre2api.html#SEC27), more precisely in the *ovector*. Read aboit it [here](http://pcre.org/current/doc/html/pcre2api.html#SEC30). You can tell if the capture group number **n** matched if `ovector[2*n] != PCRE2_UNSET`. **n** starts at 1, as the index 0 designates the full pattern. Alternatively, you can use the return value of `pcre2_match`, which is the highest captured group number which has been set.
Comment: a little correction: the return value of `pcre2_match` is **1+** the highest captured group number.


How to get closest value for each decades in c#?

Question: I am getting data by using timer and adding them to in a listbox or datagridview. I need to get values for each decades such as;10,20,30,40,50..
But not always data comes as much as in order that I want. There is a example data that comes;
10.15
 14.45
 19.65
 22.18
 27.89
 30.15
 31.15
 37.46
 42.01
 ...
According to data above I want to list this data in my code;
10.15 as 10
 19.65 as 20
 30.15 as 30
 42.01 as 40
  ...
As you see I don't want to miss any decade.
In my code label1.text represents velocity, label2.Text represents time and watch is a stopwatch Firstly I am collecting data to lisboxes then take them to datagirview.Here is my code;
private void timer2_Tick(object sender, EventArgs e)
{
    watch.Start();
    var time = watch.Elapsed.TotalSeconds;
    if (Math.Round(Convert.ToDouble(label1.Text)) % 10 == 0)
    {
        listBoxTime.Items.Add(label2.Text);
        listBoxVelocity.Items.Add(label1.Text);
        p = dataGridView1.Rows.Add();
        for (int i = 1; i < listBoxTime.Items.Count; i++)
        {
            dataGridView1.Rows[p].Cells[0].Value = listBoxVelocity.Items[i].ToString();
            dataGridView1.Rows[p].Cells[1].Value = listBoxTime.Items[i].ToString();

        }
    }
}

As I said before, What should I do to get closest data for each decade without missing any decade.
Comment: I expect 10.5, since it is more closer to 10 than 11.5.
Comment: What do you expect 15 to round to? What about 25?
Comment: Would it occur that there's a situation that has a decade missing?
Comment: What version of Visual Studio are you running? What version of .NET Framework are you using?
Comment: I Use visual studio 2013 and .NET Framework 4.5
Answer: You could just divide the numbers by ten, then round them, followed by multiply by ten. Check the difference between the two and compare it to previous ones.
Update: (the previous answer removed)
Now just getting the lowest. Probably not most elegant/generic way, but it should work.
Update2:
Replaced C#6 code
class Numbers {
    public int Rounded { get; set; }
    public double Number { get; set; }
    public double Difference
    {
        get { return Math.Abs(Rounded - Number); }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var numbers = new [] {10.15, 14.45, 19.65, 22.18, 27.89, 30.15, 31.15, 37.46, 42.01};
        var decades = new List<Numbers>();

        foreach (var number in numbers)
        {
            var rounded = (int)Math.Round(number / 10, MidpointRounding.AwayFromZero) * 10;
            var found = decades.FirstOrDefault(x => x.Rounded == rounded);

            if (found == null)
                decades.Add(new Numbers { Rounded = rounded, Number = number });
            else if (found.Difference > Math.Abs(rounded - number))
                found.Number = number;
        }

        foreach (var number in decades)
            Console.WriteLine($"{number.Number} as {number.Rounded}");

        Console.ReadKey();
    }
}

Result:
10.15 as 10
19.65 as 20
30.15 as 30
42.01 as 40

I'm not sure if you want to hold on to numbers that didn't make the cut, but that shouldn't be too hard to add.
Change
public double Difference => MathAbs(Rounded - Number);

C#6 Alternative-1
public double Difference() {
    return Math.Abs(Rounded - Number);
}

C#6 Alternative-2
public double Difference {
    {
        get { return Math.Abs(Rounded - Number); }
    }
}

Comment: My guess is that he's expecting a new array that only contains the values closest to a decade. In his example it would give `[10.15, 19.65, 30.15,  42.01]`
Comment: @mjwills thanks for pointing out the midpoint rounding. I've updated the answer.
Comment: @nGAGE thanks for your reply but in his solution if there is a numbers as 11,12,13,14 , it takes all of them as 10. But I want to get only the closest one so which is 11 for this.
Comment: @Quanthema Sorry, I guess I misunderstood. Hope that update2 helps.
Comment: @nGAGE Thanks you so much for your repsonse but In class Numbers part ` public double Difference => Math.Abs(Rounded - Number);` gives an error.
Comment: @Quanthema Ok, sorry. the syntax is a c# 6 feature. Let me add an example of what the code means/does and should resolve it for you.
Comment: @Quanthema There is an edge-case I can think of that might break the code, but I'm not sure if it will apply. If the source number is 100 or greater, the division & multiplication by 10 part wouldn't work anymore. I am assuming that you're only getting numbers from .01~99.99 though. Is that an accurate assumption?
Comment: Thanks for point this out @mjwills Spotted a difference with my own code and eventually unnecessary fall-through elseif. Updated code.
Answer: The following solution shows one possible approach. To use this, be sure to add this Nuget package to your project.
The code basically rounds to the nearest decade, then chooses the entry which is closest (i.e. smallest difference) as the example.
using System;
using System.Collections.Generic;
using System.Linq;
using MoreLinq;

class Program
{
    private static IEnumerable<DecadeAndClosest> GroupByDecade(double[] input)
    {
        var rounded = input.Select(z => new
        {
            original = z,
            rounded = Math.Round(z / 10, MidpointRounding.AwayFromZero) * 10
        });
        var roundedWithDifference =
            rounded.Select(z => new { z.original, z.rounded, difference = Math.Abs(z.original - z.rounded) });
        var finalResults = roundedWithDifference.GroupBy(z => z.rounded)
            .Select(z => new DecadeAndClosest() { Decade = z.Key, Example = z.MinBy(Y => Y.difference).original });
        return finalResults;
    }

    public class DecadeAndClosest
    {
        public double Decade { get; set; }
        public double Example { get; set; }
    }

    static void Main(string[] args)
    {
        var input = new[]
        {
            10.15,
            14.45,
            19.65,
            22.18,
            27.89,
            30.15,
            31.15,
            37.46,
            42.01
        };

        var finalResults = GroupByDecade(input);

        foreach (var indiv in finalResults)
        {
            Console.WriteLine(string.Format("{0} - {1}", indiv.Decade, indiv.Example));
        }

        Console.ReadLine();
    }
}

Comment: Yes it will work anywhere. I included the complete console app code for you to test it. You can copy and paste `GroupByDecade` and `DecadeAndClosest` into any type of project (as long as it has the Nuget package that I mentioned).
Comment: Thanks you so much for your response but code gives an error at this part `Example = z.MinBy(Y => Y.difference).original`. Also my code works with timer tick and I can't make your code imposed to work with timer interval.
Comment: Did you add the Nuget package? https://www.nuget.org/packages/morelinq/
Comment: `I can't make your code imposed to work with timer interval` What part of it could you not get working with a timer?
Comment: I added Nuget package. For example my label1 .Text changes according to timer. I added your  `var input= new[] {Convert.to(Double.Label1.Text)}` into timer tick part. but it doesn't work . I tried to change your variable `original=Convert.toDouble(label1.Text)` but it gives an error. As a brief Which variables in your code refers my label1.Text. Think that you are in the car and getting faster data comes from gps and you show you velocity in label1 and you want to measure time velocity relations in every decades. to do it I should work with timer.