Issue creating CSP type certificate for use with Microsoft Teams bot

Question: I've been trying to get the a realtime media calling bot up and running in Teams. The example I am using is the Microsoft provided HueBot.
The setup requires you to provide an SSL certificate so I have got one from letsencrypt for the appropriate domains I am using & installed it into the Windows keystore.
After setting up all the configuration and running it I get the following error:
InvalidOperationException:
Cannot access the certificate's private key.
Make sure that the process has enough permissions to access the private key.
Only CSP-stored certificates are supported by the media platform, CNG/KSP certificates are not supported.

Looking into the cert using certutil I can see it is indeed a KSP type key (Microsoft Software Key Storage Provider specifically).
How can I convert this certificate to a CSP type key?
I tried the following command to try convert my .pem files from letsencrypt to a pfx with the correct CSP:
openssl pkcs12 -export -inkey .\privkey.pem -in .\cert.pem -out test4.pfx -CSP "Microsoft Enhanced RSA and AES Cryptographic Provider"

But OpenSSL seems to just completely ignore what is put in the CSP argument, it always generates the Microsoft Software Key Storage Provider cert, and even if I put gibberish in as the argument it doesn't throw any error.
Answer: Check the certificate generated by LetsEncrypt is a supported type. They recently changed the default key type to be ECDSA. You want to use RSA instead.
You can check if this is case by looking at the certificate properties. Click on the Details tab and then check the value of Public Key. It should use RSA (2048 Bits) not ECC (256 Bits).
If you are using certbot you can use the command certbot certonly --key-type rsa to force it to use the correct key type.


Why would Remote Assistance work but not Remote Desktop?

Question: I have managed to get Remote Assistance working between two XP machines, but as soon as I try Remote Desktop I can't even get to the login screen without an error which gives a list of possibilities and concludes with "See your network administrator", which isn't very helpful.
I have ramped up the security level on Remote Desktop including turning on encryption etc.  Could this be the problem?  I will only get a few hours on the machine at a time so I need to be well-prepared before I attack this problem again.  Any ideas?
EDIT:  The error message is as follows, and this occurs before any login screen appears:
alt text http://www.freeimagehosting.net/uploads/7593c90b6e.png
Comment: can you say, what exact error message is ? is two XP-Pro machines in domain or in workgroup ?
Comment: See the error message above. Two XP-Pro machines connected over the internet.
Comment: does thees XP-Pros has the same (latest) service pack ?

is there any errors at event log on remote PC ?
Answer: I suppose that remote desktop is actually enabled on both machines? Remote Assistance tends to be enabled by defualt, but Remote Desktop not nessecarily. If you right-click on "my computer", choose "properties" and view the "remote" tab. Make sure the "allow users to connect..." is ticked.
Simple things first.
Comment: Remote Desktop is enabled and 'allow users to connect' is ticked.  Remote assistance works but Remote Desktop does not.
Answer: Ensure port 3389 is open
Answer: This message will also appear frequently if the same user unlocks the remote machine from another session: for example, if you RDP into the box as "Bob", but then "Bob" logs-in from his desk.


Google Map full screen option disabled?

Question: I am using google map for my site but I can not see the full screen feauture on the map. How can I activate and why I can't see it?
I have add following option to map:
var map = new google.maps.Map(document.getElementById('googleMap'), {
                zoom: 7,
                center: new google.maps.LatLng(this.coordinates[0][1], this.coordinates[0][0]),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                zoomControl: true,
                scaleControl: true,
                zoomControlOptions: {
                    position: google.maps.ControlPosition.LEFT_TOP
                }
            });

Here is my map:
Comment: the width of the map is related with the div  that contain the map ... show the related  html and css code...
Comment: did you try this in your html code
Comment: #googleMap{

height: calc(100vh - 11em);

}
Answer: By default, the fullscreen control is not included on the desktop version of the Google Maps API. Add the fullscreenControl: true property to the object used to initialize the map. Your code should look like this:
var map = new google.maps.Map(document.getElementById('googleMap'), {
 zoom: 7,
 center: new google.maps.LatLng(this.coordinates[0][1], this.coordinates[0][0]),
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 zoomControl: true,
 scaleControl: true,
 fullscreenControl: true
 zoomControlOptions: {
  position: google.maps.ControlPosition.LEFT_TOP
 }
});

Checkout the documentation at https://developers.google.com/maps/documentation/javascript/controls
Comment: strange, I still can't see something after I added fullscreenControl:true
Answer: In the google maps documentation;
"The Fullscreen control offers the option to open the map in fullscreen mode. This control is enabled by default on desktop and mobile devices. Note: iOS doesn't support the fullscreen feature. The fullscreen control is therefore not visible on iOS devices."
This comment is a bit late, but maybe it helps someone.
The article link is; Google Maps Platform
The section is; Controls Overview
Comment: Could you link the article with the section you quoted?

Google Map full screen option disabled?


How many ways are there to place 2 types of objects in n (that varies) spots?

Question: First time posting, all help appreciated. I'm trying to figure out the number of ways to arrange items in spots. The complication is that the number of spots changes with the type of items put in them.
Basically, I want the total of the objects (either 1 or 2) to be some number, say 10. So, if I choose all 1's, there will be ten spots and 1 way to arrange them. If I choose 1 for eight of the spots and 2 for one of them (the total is still 10), I have 9 ways to arrange them (see example below):
2, 1, 1, 1, 1, 1, 1, 1, 1
1, 2, 1, 1, 1, 1, 1, 1, 1
1, 1, 2, 1, 1, 1, 1, 1, 1
etc.
If I choose two 2's, I get even more choices. Inititially I predicted it would be a summing series (n + (n-1) + (n-2) + ... 2 + 1), but when I count it out, that's not what I get. Here is two 2's (and eight spots):
2, 2, 1, 1, 1, 1, 1, 1
2, 1, 2, 1, 1, 1, 1, 1
2, 1, 1, 2, 1, 1, 1, 1
etc.
(When I do it out manually like this, I think there are 13 combinations.)
So how would I calculate how many ways there are to rearrange the rest? Examples: three 2's and four 1's (writing them out, I also got 13 different combinations for this) or four 2's and two 1's (for this, I got 9).
Thanks!
Comment: You are really looking at (a restricted) *partition* of 10
Answer: When there are $k$ 2's, there must be $10-2k$ 1's. So, number of ways to arrange these is ${10-k} \choose {k}$. $k$ can range from $0$ to $5$. So, total way of doing this is:
$$\sum_{k=0}^{5}{{10-k} \choose k}=1+9+28+35+15+1=89$$
You are probably missing some combinations while writing them out. It's not $13$ when there are two $2$'s, instead there are $28$ different combinations.


I can't use $(this) Jquery

Question: Now code is this.
<button id=hine onclick=mo('ppp')>Go!</button>

How can I use $(this) in jQuery ?
Comment: You should handle the event in function `mo` and use event.target to get the `id`
Comment: Try `$(event.target).attr('id')`
Comment: Barmar's answer should solve this.
Answer: Try this

function mo(elem, name){
  alert(name);
  alert($(elem).attr('id'));
}

<button id=hine onclick="mo(this, 'ppp')">Go!</button>
Answer: You need to pass this as an explicit argument.
<button id="hine" onclick="mo(this, 'ppp')">Go!</button>

I can’t use $(this) Jquery


Simulate database I/O behaviour

Question: I'm investigating some performance issue and I need a tool that can mock the same I/O behavior that a typical RDBMS is usually creating.
I don't want to install a full blown RDBMS and mess around with configuration just in order to test this issue.
Is there any tool designaed for this specific need ?
Comment: Completely irrelevant to your question, `sqlio` for Windows does this. The Answer below handles Linux nicely.
Comment: you can use oracle orion, but i think you need a database installed
Comment: Can't see how this question is seeking product,service or material recoomendation. It's seeking for a method to simulate a situation.
Answer: Assuming you know your database block size, number of threads, and percentage of read vs write, iozone can be used to craft IO workloads which might mimic production.
Filebench ships with a large number of "personalities" which can mimic an application workload, including a database application, and even has its own markup language to enable you to write your own workload personality.
Answer: There's also the blktrace (btrecord) approach on Linux. You can capture real I/O activity and replay (btreplay) onto the same device or different device. The fio tool also supports this.

Simulate database I/O behaviour


problema de acentuação quando salva no banco de dados

Question: Está acontecendo um problema comigo, quando eu salvo um valor no banco de dados, ele salva sem acentuação.
Todo o meu código na página está utf8, todo o meu banco de dados está utf8, as tabelas estão utf8 e onde faz o insert está utf8
Quando eu coloco utf8_encode() no código, ele funciona, porém quando resgato o valor, vem com o mesmo problema de acentuação
public function cadastrarResponsavel(){
        try{
            $sql = "INSERT INTO $this->prt_partner_responsible(id_resp,nome,cargo,tel_comercial1,tel_comercial2,tel_celular1,tel_celular2,email1,email2,nota,_id_partner,_ativo,_data_registro )
VALUES (NULL,:nome,:cargo,:tel_comercial1,:tel_comercial2,:tel_celular1,:tel_celular2,:email1,:email2,:nota,:id_partner,:ativo,:data_registro)";
            $stmt = DB::prepare($sql);

            foreach($this->nomeResponsavel as $key => $values) {

                $stmt->bindParam(":nome", $this->nomeResponsavel[$key], PDO::PARAM_STR);
                $stmt->bindParam(":cargo", $this->cargoResponsavel[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_comercial1", $this->telefoneComercial1Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_comercial2", $this->telefoneComercial2Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_celular1", $this->telefoneCelularIIResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_celular2", $this->telefoneCelularIIResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":email1", $this->email1Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":email2", $this->emaiI2Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":nota", $this->comentariosResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":id_partner", $this->idParceiro, PDO::PARAM_STR);
                $stmt->bindParam(":ativo", $this->ativo, PDO::PARAM_STR);
                $stmt->bindParam(":data_registro", $this->datas, PDO::PARAM_STR);
                $stmt->execute();
            }
            return $stmt->rowCount();
        }catch (PDOException $ex){
            $Exc = new ExceptionDatabase();
            date_default_timezone_set('America/Sao_Paulo');
            $dataRegistro = date("Y-m-d H:i:s");
            $this->Caminho = explode("/", $_SERVER['SCRIPT_NAME']);
            $this->arquivo = $this->Caminho[count($this->Caminho)-1];
            $this->arquivoLog = 'log/erros.txt';
            $this->erro =  $ex->getCode();
            $this->mensagem  = $ex->getMessage();

            $Exc->setTipoLog(enum::Error);
            $Exc->setTitleLog($ex->errorInfo);
            $Exc->setDescLog($ex->getMessage());
            $Exc->setDataRegistro($dataRegistro);
            $Exc->setArquivo($this->arquivo);
            $Exc->setArquivoLog($this->arquivoLog);
            $Exc->setErro($this->erro);
            $Exc->setMensagem($this->mensagem);

            $Exc->erro();
        }
    }

Ele salva no banco assim

Querys de conexão
Basicamente tentei de duas formas
Setando o utf8 no config e chamando na class DB
header('Content-Type: text/html; charset=UTF-8'); //ja tinha esse header utf8
define('DB_HOST', 'host qualquer' ); //host
define('DB_NAME', 'banco de dados qualquer'); //nome do servidor
define('DB_USER', 'usuario qualquer');  // nome do usuario
define('DB_PASS', 'senha qualquer');   //nome da senha
define('DB_CHARSET','charset=utf8"');  //codificação

e setar ele na classe de conexao
require_once 'config.php';
class DB{
    private static $instance;
    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            try
            {
                self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS,DB_CHARSET);
                //self::$instance->exec("set names utf8");
                self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            } catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
        return self::$instance;
    }

    public static function prepare($sql){
        return self::getInstance()->prepare($sql);
    }
}

e também colocando o exec direto, não funcionou
require_once 'config.php';
class DB{
    private static $instance;
    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            try
            {
                self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
                self::$instance->exec("set names utf8");
                self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

            } catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
        return self::$instance;
    }

    public static function prepare($sql){
        return self::getInstance()->prepare($sql);
    }
}

nem executa

executa normalmente, mas bagunça toda a codificação
Answer: Defina na conexão do PDO o charset utf8.
Sua string de conexão ficaria parecido com isto:
"mysql:host=$host;dbname=$db;charset=utf8"

Se estiver utilizando uma versão do PHP antiga, esse comando é ignorado, aí você deve setar via comando, como este:
$dbh = new PDO("mysql:$connstr",  $user, $password);
$dbh->exec("set names utf8");

Tente realizar essa configuração e veja se resolve.
Comment: blz, vou tentar
Comment: não funcionou, nem executa a conexão
Comment: Após sua alteração, como ficou sua string de conexão? pode me mandar para verificar?
Comment: vou editar minha questão.
Comment: Olha ai @Bruno Rigolon, editei
Comment: Vamos lá, tente colocar essa linha no lugar da sua:

self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'") );
Comment: ele nem conecta ao banco
Comment: na verdade conecta, mas bagunça a codificação
Comment: Perfeito, deixe assim, agora veja sua página se está em UTF-8. O @Sorack mencionou um post, acredito estar relacionado também. Tem que verificar a página (charset definido no arquivo), conexão com o banco e charsets definidos.
Comment: cara, tudo está em utf8, já conferi tudo]
Comment: Se nada funcionou, sugiro a tentar isolar o problema. Crie um arquivo PHP separado de tudo, coloque o código da sua classe, faça a conexão e liste os dados e veja se vai ocorrer o problema. Neste arquivo simule a inserção dos dados do UTF8 e sem e veja o que vai ocorrer. De acordo com estes dados você vai ter uma ideia melhor do que está ocorrendo.
Comment: o que tu diz, fazer um db, uma tabela, conexão, tudo de teste?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/59686/discussion-between-bruno-rigolon-and-gabrielfalieri).
Answer: Problema solucionado, o erro estava quando eu tentava enviar os dados com o utf8_encode, visto que eu tinha passado tudo pra utf8


What caused the odd strategy n the last race of Sydney 2000 Laser sailing?

Question:

In the video above it looks like Ben Ainslie did something unusual with Robert Scheidt, and I don't understand why or what has really happened.
Why did preventing Scheidt from finishing 21th or higher cause Ainslie to win if he couldn't finish in a better position, and why was Scheidt disqualified in the end?
Answer:
Why preventing the other from finishing 21th or higher would cause him to win if he himself couldn't finish in a better position

The competition was over the course of 11 races.  But only the 9 best finishes for a racer are used in the final scoring.
Going into the final race, Ainslie's second-worst finish was 11th, but Scheidt's second-worst finish was 20th.   If both finish high, they can drop those scores, but if both finish in the back, those scores will count.  That's a 9 point swing and would be sufficient for Ainslie to win gold by one point.  No other racer could win the gold, even if they won the final race.
If Ainslie won the race, Scheidt would have to finish further back than 7th to lose the gold.  That was very unlikely.
Ainslie's tactic was therefore to impede Scheidt as much as possible, letting someone else win, but ensuring Scheidt had to count the 20th place finish.   He did this by getting windward of the other boat and going tack-for-tack exactly with him to keep the wind off Scheidt's sail.

why was Scheidt disqualified in the end?

During one of the turning points, Scheidt made an aggressive move and the two boats made contact.   This was actually the point where Scheidt moved clear and was able to finish without further interference.  Ainslie protested that he had not been given sea room at that point, and the protest was later upheld.  I believe this incident is shown at the turn starting around 5:25 in your linked video.
Per a sail-world.com article:

[Scheidt] then applied some of his own highly skilled tactics but committed a rare breach at a rounding mark which fired a protest from Ainslie...
...
This became a no win situation for the defending Gold Medallist and four times World champion Scheidt when the jury dismissed his protest then disqualified him on the evidence presented by Ainslie.

Scheidt's DSQ had no effect on the final scores (since his 21st place finish on the water would have also been dropped).


Elementos em comum entre listas

Question: Como eu faço pra comparar elementos de 2 listas, e retornar a quantidade de elementos em comum ?
Por exemplo:
a=[1, 2, 3, 4, 5]
b=[6, 7, 8, 9, 10, 1, 2, 11, 22]

Isso deve retornar 2, porque só há 2 elementos em comum.
Comment: As listas podem contem elementos duplicados? Isto é, sem houverem dois números 1 em `a` e `b`, deve ser contabilizado uma ou duas vezes?
Answer: Basta fazer a intersecção das duas listas e depois ver o número de elementos.
comum=len(set(a).intersection(b))

Answer: Defina uma variável num_repetido com valor 0 que servirá como contador:
>>> num_repetido = 0

Faça um loop na lista a verificando se algum dos números se repetem e então adicione na variável num_repetido:
 for num in a:
  if num in b:
   num_repetido += 1

E por último imprima na tela o valor final da variável num_repetido:
>>> print(num_repetido)
Vale ressaltar que existem diversas maneiras de fazer isso, como o amigo acima colocou, tudo depende do que você precisa. Abraço.

Elementos em comum entre listas


How are Makefile variables calculated?

Question: I'm new to using Makefiles & am puzzled by something…
I have the following in a Makefile…
USER_ID := $(id -u)
USER_ID_ESC := $$(id -u)

MAKEFILE := $(realpath $(lastword $(MAKEFILE_LIST)))
ROOT_DIR := $(dir $(MAKEFILE))

x:
    echo $${USER_ID}
    echo ${USER_ID}
    echo $(USER_ID)
    echo $${USER_ID_ESC}
    echo ${USER_ID_ESC}
    echo $(USER_ID_ESC)
    echo $${ROOT_DIR}
    echo ${ROOT_DIR}
    echo $(ROOT_DIR)
    exit 0

Which give the output…
echo ${USER_ID}

echo

echo

echo ${USER_ID_ESC}

echo $(id -u)
502
echo $(id -u)
502
echo ${ROOT_DIR}

echo /Users/toby/src/bitbucket.org/limtool/commissioning-tool-api/
/Users/toby/src/bitbucket.org/limtool/commissioning-tool-api/
echo /Users/toby/src/bitbucket.org/limtool/commissioning-tool-api/
/Users/toby/src/bitbucket.org/limtool/commissioning-tool-api/
exit 0

I understand the use of double $ to escape the use of $, but what I don't understand why using a single $ for realpath & dir commands works, but using it for the id command doesn't.
Can someone help me out in understanding?
Thanks
Comment: `realpath` and `dir` are `GNU make` functions, `id` isn't. If you want to use a shell function inside a Makefile, use `$(shell id -u)`. `realpath` and `sir` aren't escaped, they are correctly interpreted by `GNU make`
Comment: Thanks @TimF Care to add that as an answer so I can accept?
Comment: Sure, I've done it and added some more details and links :-)
Answer: realpath and dir are GNU make functions, id isn't. If you want to use a shell function inside a Makefile, use $(shell id -u). realpath and dir aren't escaped, they are correctly interpreted by GNU make.
See GNU make file name functions as well as GNU make shell function manual pages.
When you write $(id -u) in a Makefile, make will try to look if it's a function or a variable, and since it's none of these it will not expand to anything, hence the empty echos.
Now the reason why your ID was correctly written when you did escape the dollar sign is mysterious and probably due to your shell. What happened is that make didn't try to expand it since the $ is escaped, so echo $(id -u) was sent to the system. You can try it directly in your shell, you should obtain the same result.

How are Makefile variables calculated?


Updating to Angular 9 via CLI - devkit/core and devkit/schematics are not updated

Question: If this question has been asked somewhere else, then I'm sorry for asking it again - I've searched and couldn't find an answer that matches my specific scenario.
So I've just updated my Angular project to version 9, and I didn't get any failures. However, when I run ng --version, I'm seing some information that worries me:

Specifically the @angular-devkit/core and @angular-devkit/schematics, which are listed as version 7.3.10.
I would expect these to be version 9 for my project, so I tried to run a version check in another folder, to check my angular CLI global versions:

As you can see, in my global check, I have the expected version 9.1.8 of both @angular-devkit/core and @angular-devkit/schematics.
Any idea what could cause my local project to not update these? As I understand, the devkit packages are under packades of @angular-devkit/build-angular, so I would expect these to be updated, when I update that package, but it doesn't seem like it.
Would really appreciate if anyone has experience with this, or have a suggestion for what I can do to update my project local versions of these packages.
Thanks in advance!
Comment: Updating from version 7/8 to `Angular 9` is a bit tricky. Get to latest version of `Angular 8` first, Then move up to Angular 9. At least this is how I upgraded mine.
Comment: Part of the update process to 9, is to upgrade to Angular 8 (https://update.angular.io/#8.2:9.0l3), but this doesn't seem to have updated the devkit packages
Comment: So I now got the correct version listed when running ng --version. I did this by manually installing the 2 packages - I'm just worried that this could cause some issues, or I'm not doing stuff in the correct order maybe?
Comment: Instead of upgrading consider creating a new v9 project from scratch and then move over your code to the new project (or use the newly generated `package.json`).
Answer: I'm closing this question - I did get a version match by manually adding these packages, but in the end, it didn't really change the core issue I was experiencing - I suspect that my project hasn't had the correct update process somewhere along the version history.
But if people look to this question for answers, you can manually npm install specific versions of these packages, if they are added in your package.json
Comment: when you added these packages manually, they updated your package.json file. Right? But by default, these packages are part of node modules yet not visible in package.json. Now since you have added these packages manually, they stay mentioned in package.json forever even though thats not the default. Is that correct?


Clustering based on interactions between members of two groups

Question: I have a large dataset from a survey that describes what web pages people use. So for each person I have a list of pages that they visit and how frequently they visit them.
What methods can be used to cluster both the webpages (based on similar users who use them) and the users (who use similar webpages)?
Example:
User A visited web pages a, b, a, c
User B visited a, b, d, b
User C visited page e, e

Conclusion from that would be that pages a,b,c,d are somewhat similar and belong to the same cluster. The other cluster is page e. Also, users a,b are similar, the other user cluster is the one containing User C, who visits different pages.
Answer: If you drop the distinction between users and web pages, any of the common "strongly connected component" algorithms should work for you.
You might be able to do better by finding a similarity on users and web pages independently first, though.
Answer: Several thoughts. Create a variable for each web page. Each user gets 1 or 0 according as he visits the page or not. You can then do a standard hierarchical cluster on either users or pages. See hclust() and dendrogram() in base R. A heatmap() of the result might reveal interesting patterns.
An association rule could be interesting. Check out the arules package in R. It implements the apriori algorithm, amongst other things, which should give you clusters of pages that tend to be visited. arules comes with a very good explanatory manual.


Which algorithm suits this type of outlier detection?

Question: Suppose I have gathered the time a certain user takes to input a four digit PIN from his previous logins as follows :
User A : (10,12,11,13,19.1,12.4,12,16)
Now, User A wants to login again to perform a transaction. This time he took 11.03 to input the four digit PIN. As of now, I found Extreme Studentized Deviate  that it can be used to detect outliers for univariate data, but am not sure of its performance.
Question:

Which method or approach can I use to detect whether 11.03 is an outlier?
What others have done?
Can I use LOF? If so how? A little light will do. Thanks.

PS: Units of time in this case are not important, they are just random values for demonstrating the concept.
Comment: @Giovanrich Why are you focused on Mahalanobis distance? Do you think the sequence of the times matters? Or the number of observations that go into the estimate of central tendency around which  "outliers" are to be evaluated?
Comment: Is the number of observations (8 in your case) for one user realistic ? Or do you have many more for each user ?
Comment: @fcop No, its not realistic. I just want to get to know how the method works then I will apply it on real data.
Comment: When you write "univariate" data, do you mean an outlier relative to User A's past behavior or an outlier formed from an average of many users?
Comment: @DJohnson  Well, I might be lost but by univariate I mean that I am considering one variable - time to imput PIN only. My data is one dimensional.
Answer: Thinking beyond the statistics...
I imagine the goal here is to say: The user took too long to enter the PIN compared to their usual time, so it is likely to be someone else using the password.
But.. Maybe I took longer because I was carrying a baby in my right arm, so had to enter the PIN with my left (non dominant) hand. Or maybe I was outside wearing gloves. Or maybe I got interrupted or was trying to carry on a conversation while entering the PIN. There are lots of reasons why I may enter a PIN slower than usual, so I think it would be a bad way to detect fraud. If you follow this logic, the outlier tests won't be helpful.
Answer: In my opinion, if the data is a time series data, forecasting based confidence intervals give a good idea of whether a point is an outlier or not.
For non time series univariate data, multiple methods can be tried out -

Z-score based method(this resembles your idea of using points farther from the expected value as outliers)
Tukey's Method
MAD(Median Absolute Deviation)

Out of the above methods for univariate data, I would recommend tukey's method because it is relatively robust.
For Multivariate Data, I would recommend methods like LOF, Elliptic Envelope(which uses the Mahalanobis distance internally - implemented in scikit-learn).
Answer: An outlier can be defined as "an observation point that is distant from other observations" . I prefer "an observation point that is distant from expectatations" . I took one of our "teaching moments series" and used your reference  http://www.graphpad.com/quickcalcs/grubbs2/ to obtain  a conclusion about "normalcy of the last observation". I took your 9 values and found that while the most recent values was "normal" two prior values were deemed exceptional  and  . As @forecaster pointed out the work of Tsay and others is often useful.
Comment: When I give a PIN, the events are usually separated in time and the circumstances pretty much independent. So I don't see how time series analysis enters here at all. (Over a very long period I suppose my reaction time increases with age, but I doubt that's central here.)
Comment: Very funny ! Yes even thought this is chronological it definitely may not be even-spaced which would suggest definitely avoiding ARIMA. That being said there is no ARIMA component  (i.e.no time series component) in the model just two possible "unusual values" and a most recent values that doesn't appear to be exceptional.
Comment: There is something broken about any outlier detection method that would identify 16 as an outlier relative to a seven-number sequence spanning 10 through 19.  That is probably because it incorporates strong implicit assumptions.  As @NickCox notes, it is not plausible that all those assumptions apply here.
Comment: What is broken is that after 19 has been detected as anomaly 16 is certainly one .there are no implicit assumptions just a test for a value falling within expectations much like a winsorisiing. 19 is inconsistent with the history and if this is so then 16 is also inconsistent


What does $M$ mean in this context?

Question: Was reading this question which posed the following:

Suppose $f:(a,b) \to \mathbb{R}$ satisfy $\left| \;f(x) - f(y) \; \right| \le M \;\left|\;x-y\;\right|^{\alpha} $ for some  $\alpha > 1$
and all $x,y \in (a,b) $ , prove that $f$ is constant on $(a,b)$.

A basic question:  What does $M$ mean in this context?
The other answerers seemed to know very well what this meant, but that's probably because they've taken a course in real analysis, which I haven't.  I understand everything else above, though.
Comment: It's a generic constant. There should be an "and some $M \geqslant 0$" after the "for some $\alpha \leq 1$" or somewhere else. The assumptions are that there are some $M,\alpha$ such that $f$ satisfies $\lvert f(x)-f(y)\rvert \leqslant M\cdot \lvert x-y\rvert^\alpha$ for all $x,y$. And, by the way, one needs $\alpha > 1$ for the conclusion that $f$ is constant. That has just been corrected, it was erroneously changed by a suggested edit.
Comment: Not really. In case $M = 0$, it is immediate that $f$ must be constant, regardless of $\alpha$. The interesting case is $M > 0$.
Comment: $M$ could even be negative and the statement would still be true :-)
Comment: @Magdiragdag In that case, vacuously. $\lvert f(x)-f(y)\rvert \leqslant M\cdot \lvert x-y\rvert^\alpha$ can only hold for $M < 0$ if $\lvert x-y\rvert^\alpha = 0$.
Comment: I didn't say it was an exciting case :-)
Comment: Thanks @DanielFischer. Magdiragdag's answer says that $M$ is positive. You're saying it's non-negative. Does it matter? (Though I guess if it's zero it's easy to prove?)
Comment: @John : the question is poorly worded.  They probably should have added "for some $M > 0$" or for some $M \geq 0$"(if $M=0$, then $f$ is trivially constant.  $M<0$ is impossible except perhaps if you allow $a=b$, in which case $(a,b)$ is the "empty interval" $\varnothing$ and the condition on $f$ is true because any universal statement about the empty set is true.  I really doubt they meant that.
Answer: It's some arbitrary positive constant.
Comment: correction: NONNEGATIVE CONSTANT

What does $M$ mean in this context?


301 redirect .htaccess parameter php?fr_xyz to php?en_xyz

Question: 1st i have to say: i tried google of course. so many tips about my request - but i dont get it. maybe you can help...
it sounds simple: i want a 301 via .htaccess to a another parameter file
for example:
www.mydomain.tld/ runs without .htaccess to www.mydomain.tld/index.php?de_xyz
but:
what i want is, if you call www.mydomain.tld you get to www.mydomain.tld/index.php?en_xyz
-> ?de to ?en
if i try a simple: Redirect 301 /index.php http://www.mydomain.tld/index.php?xyz i get a redirection error on this side.
i have tried so many ways. dont get it :/
thx for your answer
Answer: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{QUERY_STRING} !(^|&)en_xyz(&|$) [NC]
RewriteRule ^/?$ %{REQUEST_URI}?en_xyz [L,QSA,R=302]

Answer: Have you tried
RewriteRule ^/?$ /index.php?en_xyz [R=301]

Note that 301 is a permanent redirect so the browser might not re-read your configuration if you redirect to a wrong address by mistake while trying.
If not working you might want to add
RewriteLog "/some/path/rewrite.log"
RewriteLogLevel 3

to your vhosts file if you have access (it might not work in .htaccess) and get the details from log.
By the way I'd prefer handling this in index.php:
header('Location: index.php?en', true, 301);


Best practice for Angular ng-repeat with nested data

Question: I have the following code that I admit looks pretty gross. Anyone have a suggest for cleaning it up and making it a bit more scalable without using nested tables?

        {{data.name}}

        {{value}}

        {{value}}

        {{value}}

        {{value}}

        {{value}}

Answer: I think this is what you're trying to achieve, but I'm not entirely sure by looking at your code.

        {{data.name}}

        {{ column.value }}

Answer: What I did was actually flatten data.cols to one array in the controller. Something like this:
var merged = [].concat.apply([], row.cols);
row.cols = merged;
$scope.displayData.push(row);


How to use await in dispatch using contextAPI?

Question: I have a problem while redirecting user to dashboard, I just want to make sure that dispatch is completed and then i start redirecting user to another page. But i don't know how to do that. I am new in react so please help me.
 const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { dispatch } = useContext(AuthContext);
  const location = useLocation();
  const history = useHistory();

  const submit = (e) => {
    e.preventDefault();
    axios
      .post(`${process.env.REACT_APP_API_URL}/auth/login`, { email, password })
      .then((response) => {
        dispatch({
          type: "LOGIN_USER",
          payload: response.data.token,
        });
        let { from } = location.state || { from: { pathname: "/" } };
        history.replace(from);
      })
      .catch((error) => {
        console.log(error);
      });
  };

const reducer = (state, action) => {
  switch (action.type) {
    case "LOGIN_USER":
      sessionStorage.setItem("token", action.payload.token);
      break;
    case "LOGOUT":
      sessionStorage.removeItem("token");
      break;
    default:
      throw new Error();
  }
};

const AuthProvider = (props) => {
  const [state, dispatch] = useReducer(reducer);
  const [isLoggedIn] = useState(!!sessionStorage.getItem("token"));

  return (
    <AuthContext.Provider value={{ state, dispatch, isLoggedIn }}>
     ....

Any solution appreciated!
Answer: The cause is that dispatch will finish in next cycle. So you can't do things right away.
As far as I can see, there might be two ways based on your code.

put history.replace inside LOGIN_USER action. So that after you set token, do redirect.

add a callback function to the payload. After set token, call the callback.

Here's the snippet for using approach 2).
        dispatch({
          type: "LOGIN_USER",
          payload: {
            token:  response.data.token,
            callback: () => {
              let { from } = location.state || { from: { pathname: "/" } };
              history.replace(from);
            }
          }
        });

and in reducer do
    case "LOGIN_USER":
      sessionStorage.setItem("token", action.payload.token);
      action.payload.callback()
      break;

BTW i also notice, your payload needs to be an object, ex .
  { token: ..., }


Check if node is displayed as page?

Question: In Drupal 6 to check if node is displayed as page we can use:
Select the condition to add - > Check a truth value
Truth value - > <?php echo $page ?>
How to do this in Rules 2.x for Drupal 7? I don't see the condition with name Check a truth value
Answer: Assuming I have interpreted what you're trying to do, try adding the Event "Content is viewed", with the Condition "Content is of type" and configure the Condition to be of node type: 'Page'. If you could explain exactly what you're trying to achieve I may be able to suggest a better solution!
Answer: I did it this way
EVENT: Content is viewed of type [...]
Conditions: Execute custom PHP code: "return $view_mode == 'full';" (without the quotes)
Actions: Unflag, flag and so on...

Check if node is displayed as page?


subjectAreaChangeMonitoringEnabled only works on certain camera devices

Question: I've been attempting to use AVCaptureDevice's subjectAreaChangeMonitoringEnabled property to monitor movement with a potential motion-detection application.
For the back-facing camera of both iPhone 4S and iPad 2, I receive AVCaptureDeviceSubjectAreaDidChangeNotifications when I would expect to, however on both devices, when I attempt to enable this on the front-facing camera, I receive no notifications at all.
Why doesn't this work on the front-facing cameras?
Answer: According to an Apple engineer in this Developer Forums response, this is expected behaviour:

subjectAreaChangeMonitoring is meant to tell you if the scene has changed enough that it's probably out of focus, so you should refocus.  Consequently, the feature only works on cameras that support focus.

So you cannot rely on this API for motion detection, at least for the front-facing cameras.


Como criar uma máscara entre uma imagem em QML e um elemento de QtQuick

Question: Como criar uma máscara entre uma imagem importada para QML (ex.: um ícone png, jpeg, svg, etc...), e um elemento de user interface no background (ex.: um rectangle)?
Answer: Podes usar o OpacityMask do Qml.  Exemplo:
<code>import QtQuick 2.0
import QtGraphicalEffects 1.0

Item {
    width: 300
    height: 300

    Image {
        id: bug
        source: "images/bug.jpg"
        sourceSize: Qt.size(parent.width, parent.height)
        smooth: true
        visible: false
    }

    Image {
        id: mask
        source: "images/butterfly.png"
        sourceSize: Qt.size(parent.width, parent.height)
        smooth: true
        visible: false
    }

    OpacityMask {
        anchors.fill: bug
        source: bug
        maskSource: mask
    }
}
</code>
Documentação:
http://doc.qt.io/qt-5/qml-qtgraphicaleffects-opacitymask.html


Modify this class render, change the size of the progress bar to variable?

Question: I have this code:
TableColumn column = jTable2.getColumnModel().getColumn(1);
column.setCellRenderer(new ProgressRenderer());

class ProgressRenderer:
class ProgressRenderer extends DefaultTableCellRenderer {
    private final JProgressBar b = new JProgressBar(0, 100);// I NEED RECEIVE DE VALUE,                //LIKE THIS new JProgressBar(0, MAX);
    private final JPanel p = new JPanel(new BorderLayout());

    public ProgressRenderer() {
        super();
        setOpaque(true);
    b.setStringPainted(true);
        p.add(b);
        //p.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
    }
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Integer i = (Integer) value;

        String text = "Finalizou o Lote";
        if (i < 0) {
            text = "Pausa";
        } else if (i < 100) {
            b.setValue(i);
            return p;
        }
        super.getTableCellRendererComponent(table, text, isSelected, hasFocus, row, column);
        return this;
    }

    @Override
    public void updateUI() {
        super.updateUI();
        if (p != null) {
            SwingUtilities.updateComponentTreeUI(p);
        }
    }
}

Now, I need, When ProgressRenderer call function () difine a parameter which is the maximum of the progress bar, but I can not do, any idea?
Like this:
TableColumn column = jTable2.getColumnModel().getColumn(1);
    column.setCellRenderer(new ProgressRenderer(MAX));

Class ProgressRenderer()
class ProgressRenderer extends DefaultTableCellRenderer {
    private final JProgressBar b = new JProgressBar(0, MAX);// I NEED RECEIVE DE VALUE,                //LIKE THIS new JProgressBar(0, MAX);
    private final JPanel p = new JPanel(new BorderLayout());

    public ProgressRenderer() {
        super();
        setOpaque(true);
...
...

----  Edit ----------
thank you, but now have my big problem, because this:
TableColumn column = jTable2.getColumnModel () GetColumn (1).;
    column.setCellRenderer (new ProgressRenderer (maxValue));//

// How do I know when to add the object to change the maxValue
I'm use this code for insert value in jtable
private LinhasOnline getLinha() {

    LinhasOnline linha = new LinhasOnline();
    linha.setNome("Linha "+j);
            linha.setcont(j*(10));
            linha.setmax(100);

            j++;
            return linha;
}

private void addLinha() {
    getModel().addLinha(getLinha());//
}

//my getmodel
private LinhasOnlineTableModel getModel() {
    if (model == null) {
        model = (LinhasOnlineTableModel) getTblLinhasOnline().getModel();
    }
    return model;
}

//my getTblLinhasOnline()
 private JTable getTblLinhasOnline() {
    if (jTable2 == null) {
        jTable2 = new JTable();
        jTable2.setModel(new LinhasOnlineTableModel());
                    TableColumn column = jTable2.getColumnModel().getColumn(1);
                    column.setCellRenderer(new ProgressRenderer(max)); // need put the value of object( setmax)
    }
    return jTable2;
}

Answer: You can change your class like next :
class ProgressRenderer extends DefaultTableCellRenderer {
    private final JProgressBar b;// I NEED RECEIVE DE VALUE,                //LIKE THIS new JProgressBar(0, MAX);
    private final JPanel p = new JPanel(new BorderLayout());

    public ProgressRenderer(int maxValue) {
        super();
        b  = new JProgressBar(0, maxValue);
        setOpaque(true);
        b.setStringPainted(true);
        p.add(b);
    }
    ...
}

Comment: thank you, but now have other problem, see my edit comment, sorry because so must code, but for me is hard to explain. if you need a better explanation let me know :)


How do i remove "Try again: message after 3rd failed try

Question: I want to remove the "try again" message after it fails on the third try.
chance=0
a=5
while chance<3:
    guess=int(input("input your number"))
    chance = chance + 1
    if guess==a:
        print("You win")
        break
    else:
        print("Try again")
    if chance>=3:
        print("You are out of chances")

Comment: Move the last if into the else and perform the print of "try again" only in *its* else case.
Comment: off-by-one issue: your `chance` count starts with 0, ends at 2. Currently `"You are out of chances"` will never be printed.
Answer: You need to correctly place the if condition statements as follows:
chance=0
a=5
while chance<3:
    guess=int(input("Input your number:\n"))
    chance = chance + 1
    if guess==a:
        print("You win")
        break
    else:
        if chance>=3:
            print("YOu are out of chances")
        else:
            print("Try again")

Output:'
Input your number:
0
Try again
Input your number:
0
Try again
Input your number:
0
YOu are out of chances

Comment: Do we need `else` after break. Wouldn't a separate `if..else` be simpler here?
Answer: Adding 1 extra condition will work
chance = 0
a = 5
while chance < 3:
    guess = int(input("input your number: "))
    chance = chance + 1
    if guess == a:
        print("You win")
        break
    elif chance < 3:
        print("Try again")
    else:
        print("You are out of chances")

I'll implement like this
chance = 0
a = 5
while True:
    guess = int(input("input your number"))
    chance = chance + 1
    if guess == a:
        print("You win")
        break
    elif chance < 3:
        print("Try again")
    else:
        print("You are out of chances")
        break

Comment: @hc_dev you're right, break is not needed for the first program but needed for the second one, Thanks
Comment: Ah, I see the `while True:` which otherwise would bear danger of infinite-loop.
Answer: Issue
The third try is when chance == 2.
Then your last condition if chance >= 3: will never be reached because the while-loop exits before, when chance < 3.
chance = 0  # why not define max chances instead
while chance < 3:
    # ask to guess
    chance = chance + 1   # consider for-loop where you don't need to count
    if guess==a:
        # win and exit
    else:
        print("Try again")

    if chance >= 3:  # will never be greater 3 because while-condition
        print("You are out of chances")

See above, how chance-counting and the proper arrangement of if-else-if makes the loop-body long and complex plus distracts from the loop's main-purpose.
Solutions
Most crucial is the exit-condition of the while-loop. Defined properly it saves you from a break.
Then, either try to have if .. elif .. else for 3 outcomes like:
guess = None  # init guess
chances = 3   # max chances defined once

# while continues if guess not matching and chances left
while not (guess == a or chances <= 0):
    guess = int(input("input your number"))
    chances = chances - 1  # count down

    # output one of the 3
    if guess == a:   # same condition that was negated in while
        print("You win")
    elif chances <= 0:  # same condition that was negated in while
        print("You are out of chances")
    else:
        print("Try again. " + str(chances) + " left.")

Or make the exit-condition even more expressive and extract the 2 exit-states out of the loop-body, towards the end:
Loop reduced to retries
Let's make the loop express its only purpose, tries:
guess = None  # init guess
chances = 3   # max chances defined once

# while continues if guess not matching and chances left
while guess != a and chances > 0:
    guess = int(input("input your number"))
    if guess != a:
        chances = chances - 1  # count down
        print("Try again. " + str(chances) + " left.")

# output one of the 2 final states
if guess == a:   # condition that exits while
    print("You win")
else:  # other condition that exits while
    print("You are out of chances")

Benefits:
This has an expressive while-header expressing the retry condition and a pretty short and simple loop body. Afterwards the 2 post-conditions (exit-conditions) are evaluated. The else: can also be formulated to cite the other exist-condition (elif chances <= 0:).
For-loop
Another variant would be a for-loop to focus on retries in the loop-header but with a complex body: break and separate chances-test:
max_chances = 3  # define the max chances once, here: 3
for chance in range(max_chances):  # e.g. chance counts from 0 to 2
    guess = int(input("input your number"))

    # win test
    if guess == a:
        print("You win")
        break

    # chance test
    if chance + 1 == max_chances:
        print("You are out of chances")
    else:
        print(f"Try again. {max_chances - (chance + 1)} chance(s) left.")

Note the separate if: After the break the game and the loop is over and exits. If not won, we continue with the next if branching into one of our 2 alternative outputs.


My muscle memory is tied to my auditory sense: is there a name for the phenomemon?

Question: When I play a simple melody on my guitar while I strum (to create the  sound) I can quite easily determine  where to put my frethand finger for the next note.
But if I do not create the sound,  currently I can't almost at all recall the fingering sequence. I.e., I can't mock practice the finger sequence silently.
My question is; is there a name for this phenomenon in which auditory experience facilitates the memory for finger sequence??
Comment: I think the concept youre looking for is, "you're a musician". Part of learning to play music is connecting your small muscles and muscle memory with what you hear. It's helpful for guitarists and pianists. It's critical for brass and woodwind players. It's the whole ballgame for singers.
Comment: plz feel free to edit the question title so that it summerise what i am trying to ask
Comment: Disregard the fingering aspect for a moment, can you mentally "hear" the _entire_ melody in your head? Not a vague notion of it, but the complete melody? If not, can you mentally hear some other well known tune like _Happy Birthday_?
Answer: I think audiation may be the topic that relates to your question.
Audiation is sort of like the "inner ear" idea, "hearing in your head", but combined with a deeper understanding of music in terms of meter, harmony, etc. The idea comes from Edwin Gordon.
In Learning Sequences in Music, Gordon writes:

...When students complain about ... a memory lapse while performing
... the most likely cause is that they memorized the music but were
not audiating what they were performing.

I think the typical examples given are someone who can play some passage instrumentally, but can't sing what they can play. Or, quickly forgetting a recital piece, because the person can't audiate the syntactical structure of the music.
You descriptions is a little different, because you seem to be able to play something if actually play the strings and can hear the music. But, what I suspect may be happening along the lines of this: the actual sounds reinforce your performance and both give you positive queues that you're executing the music correctly and act as memory queues to recall the continuation of the performance. Absent those actual sonic queues, you aren't "hearing the music in your head", you have not internalized the musical meaning of the piece, and so your are not audiating the music. And according to Gordon, musical memory problems can stem from a failure to audiate.
In the above text, Gordon describes the ability to play music transposed as evidence of the audiation ability. The idea being if you understand the structure of the music within a key - where is the tonic, essential versus decorative tones, etc. - then you understand the musical meaning of the notes, and then transposing it to another key is merely a mechanical process.
You could try transposing melodies as both a test of and practice for audiation ability. That's just an idea off the top of my head. I don't know how music teachers actually apply Gordon's theory in their teaching.
Answer: When we practice repeatable tasks -whether that is a guitar lick, sewing or riding a bicycle- our brain's neurological pathways for that specific action are reinforced. This phenomenon is called 'muscle memory'. You can read more about it on wikipedia: https://en.wikipedia.org/wiki/Muscle_memory
Comment: AlwaysConfused's muscle memory is tied to auditory memory. The question regards that tying together.


Reasons why WebResources cannot be found

Question: Hi I am having trouble getting an embedded js file to work.
I have tried all of the following:

Running Cassini development server (VS2008, .NET 3.5)
Added [assembly: WebResource("MyNamespace.MyScriptFile.js", "text/javascript")] above the class's namespace declaration.
Script file has build action "Embedded Resource".
Tried registering during OnInit, OnLoad and OnPreRender
Script file is in the same assembly and namespace as the control registering it.
Opened assembly with Reflector and verified the name of the resource is correct.
Does not work using any of the following methods:
ScriptManager.RegisterClientScriptResource(Page, GetType(), "MyNamespace.MyScriptFile.js");

Page.ClientScript.RegisterClientScriptResource(GetType(), "MyNamespace.MyScriptFile.js");

Page.ClientScript.RegisterClientScriptInclude(GetType(), "key",
    Page.ClientScript.GetWebResourceUrl(GetType(), "MyNamespace.MyScriptFile.js"));

Other WebResource.axd files are being found - only this one is not being found.

The request for the resource returns a 404 page with an exception listed: "*[HttpException]: This is an invalid webresource request.*"
Using the ScriptManager.RegisterClientScriptResource produces the exception:
"*Web resource 'MyNamespace.MyScriptFile.js' was not found.*"

Answer: In your example code, you are making a call to GetType()... the type is used as the starting point for the search.  Depending on where you are making your call to GetType(), you may not be getting back what you expect.  Since ASP.NET dynamically compiles types for your pages and custom controls, GetType() may be returning a type defined in a new assembly built by ASP.NET.
You could try doing typeof(SomeType) instead, where SomeType is appropriate based on the location of your resource (ex. the control type you're working with).
Comment: Thanks. It solved my problem where i inherited from one of my controls. Apparantly GetType() returns the type of the inherited control and not the type of the base control adding the script.
Comment: you just saved my day!
Answer: maybe your resource file is located inside folder(s) in project?
if so, you should specify another name/location string in assembly and when you register the script
Page.ClientScript.RegisterClientScriptResource(GetType(), "MyNamespace.Folder1.Folder2.MyScriptFile.js");

[assembly: WebResource("MyNamespace.Folder1.Folder2.MyScriptFile.js", "text/javascript")]

usually that's a common problem
Answer: Try implementing your own ScriptManger and then adding the embedded file from there. Here's an example
public class MyScriptManager : System.Web.UI.ScriptManager
{
    protected override void OnInit(EventArgs e)
    {
            base.OnInit(e);
            RegisterClientScriptResource(this, typeof(ScriptManagerExtension), "MyNamespace.MyScriptFile.js");
    }
}

Comment: That may work but one of the purposes of using embedded resources is that you can package javascript files into assemblies that are then shipped out to different projects. The resources can then be dynamically added by the controls that need them. If I have to make my own ScriptManager then the purpose of using an embedded resource is kind of defeated.
Comment: I disagree with that assessment. Having your own script manager is a way to abstract away the need for "magic strings". If you have to write it more than once, "MyNamespace.MyScriptFile.js" would be a magic string. If I were you, I would use this approach simply because it allows for reuse and it does fulfill your purpose, no?
Comment: I tried out your solution and it is working - thanks! I used a ScriptManagerProxy instead so that I could package and distribute the embedded resource properly.
Answer: An alternate cause of this issue - you've been too heavy handed with your Global.asax, and you've said that everything else after your rules gives you the homepage. Not so clever of me, an hour or two wasted on that!


Add a placeholder to search input text field

Question: How can I add a placeholder for the input text of the search block (Search on my website)?
I've looked around, but on Drupal 8 template.php has been deprecated and it's not an option.
I also need to translate the placeholder.
Copy in red is what I want to do.
Comment: On which page are you referring to ?
What theme are you using ?
A screenshot would help to get appropriate answer.
Comment: @miststudent2011 I am using Bootstrap. I only want to add a placeholder the input text in the block-search-form. The block in all pages of my website.
Comment: That is because template.php is now just (themename).theme.
Answer: Thanks for your help @Kevin
So I edited my (MYTHEME).theme file and added that and it works:
<code>function mytheme_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search on my website');
}
</code>


Triangle and Incircle

Question: Today in class me and my friend were discussing cool problems that we've done. And he asked me to.find with proof something interesting. Triangle ABC has right angle at B and we drop a perpindicular from Point B to AC say point D. Then we draw incircles inside the two triangles BDC and BDA. Let the radius of the two incircles be p and q, respectively. How would we go about finding the radius of the incircle ABC.
EDIT:In terms of P and Q
Answer: Let's denote :$\bar {BC} =a , \bar {AB} =c ,\bar {AC} = b$
Note that triangles $BDC ,BDA, ABC $ are similar ,therefore :
$a : p=c : q = b :r = k \Rightarrow a=k\cdot p , c=k \cdot q , b= k\cdot r$
From Pythagorean Theorem we know that :
$b^2=a^2+c^2 \Rightarrow k^2r^2=k^2p^2+k^2q^2 \Rightarrow r^2=p^2+q^2 \Rightarrow r=\sqrt{p^2+q^2}$

Triangle and Incircle


Using animation (HTML5 Canvas Document) in a slideshow

Question: I want to use 3 different animations within a slideshow. For the slideshow I used the uikit (front-end framework developed in LESS & SASS based on html, css, javascript and jQuery) and I embedded the animations which were created in Adobe Animate CC in an iframe.
Everything works perfect, but the problem is that all 3 animations are loading on the same time. Because all of them include sound elements I can hear 3 different sounds while only the first animation is visible.
Is it possible to define something for the animations itself that the animation timeline starts playing only when the animation is visible?
Let me show a code snippet, maybe this will explain my problem:
Codesnippet

This is the first coding part of the slideshow. The file 'slide01.html' is the first animation, which is displayed to the user directly. Further in the code there is also a slide02.html and slide03.html which are also animations. So I did not build a whole slideshow in Adobe Animate CC, but I created 3 different animations, which are implemented separately. So there are 3 different html files within an iframe, which starts playing once the whole website is completely loaded.
Comment: Please include code within your question instead of at the other end of links. That image contains only HTML. Where's the jQuery you're using?
Comment: I uploaded one of the animation with all files into a .zip file (www.adconcept.de/upload/Manni%20Hula.zip). Maybe this helps. Otherwise I am currently working on a test site where I will include the animation – once I am done I will post the URL here maybe this will also help. I think that somehow I have to restrict that animation 2 and 3 load on page load and then include some code that the first animation stops after the slide is changing to the second animation, which should be played then and so on.
Answer: You can try to create Animation using Java Script

function myMove() {
    var elem = document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame, 10);
    function frame() {
        if (pos == 350) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
}

<!DOCTYPE html>

<button onclick="myMove()">Click Me</button>


Flutter android Codemagic failed since the latest flutter version?

Question: After the latest flutter update(3.10.1) codemagic stops generating apks
Answer: Just use another old flutter version in my case it was(3.7.3) that worked on codemagic


Use GMaps with just one country

Question: I would like to have a map on my website displaying all my stores. That worked out pretty well except for the fact the map is displaying more then just my country.
Is there a way to just show one country?
I made the map undraggable and users are not able to zoom, so the map is pretty much fixed but still, I would like to just show my country.
Is this possible with macro's? And if so, how do I create them?
EDIT:
So my country is Belgium and I would like to hide France and Germany (and if possible highlight Belgium...)
Comment: Not sure if leaflet + osm is an option, but you can do it with that.
Answer: You can not do it through macro's but alternatively you can set the zoom option for the map.
Go to Gmap Setting and set the Default zoom option to your requirement.
Hope it works for you!
Comment: other option is use Google Store Locator module http://drupal.org/project/google_store_locator  on drupal.org. It have the features to customize the map marker pins to be your own custom icon, and you can make the map 'location aware' which allows the user to share their location with the browser, and the map will re-center and zoom based on their location.
Comment: Yes that's what I said. The map is zoomed on my country, but my neighbouring countries are still shown... I want those to be hidden!
Comment: is it possible to post the map screenshot, so that it is easy to understand your requirement
Comment: Sure! Please see my edit!
Comment: Do you mean put some dark layer above other countries? sounds quite fascist ;)
Comment: @drupality, not just a dark layer, I want to hide them :)
Comment: @Bala, Thank you very much for the help already, but I already have custom made markers and I don't really need the location aware-function... I just want to show one country. I don't think that's inevitable...
Answer: I don't think it's possible with Google Maps. But you can try to use Google GeoMap to render a specific country map: GeoMap.
As an example, go to this link and copy paste the code below to render a map of Belgium with only Gent and Brussels with some values.
Javascript code to put in "Edit Code" textarea, then press "Run Code":
<code>function drawVisualization() {
      var data = google.visualization.arrayToDataTable([
        ['City', 'Popularity'],
        ['Gent', 200],
        ['Brussels', 300]
      ]);

      var options = {};
      options['region'] = 'BE';
      options['colors'] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
      options['dataMode'] = 'markers';

      var container = document.getElementById('visualization');
      var geomap = new google.visualization.GeoMap(container);
      geomap.draw(data, options);
}
</code>
GeoMap is usually used to display charts and datas, but it could answer your needs, it's just a suggestion.
Answer: Very near to what @Bala has answered you can opt the following:

Use OpenLayers instead of GMap if your requirements suite and cater to it.
Set zoom level for default map in OpenLayer settings.
Use KML overlay for OpenLayer to highlight the country of your liking.

A sample of what you are looking for from my website: http://indiansnakes.org/content/rat-snake

Use GMaps with just one country


Função is_dir() não funciona como esperado

Question: Saudações!
Estou desenvolvendo um sistema de arquivos para ler os arquivos de um determinado diretório e retornar o valor em JSON. No entanto, pretendo separar nesse JSON se o item é um arquivo ("type":"file") ou uma pasta("type":"folder").
Para isso, estou usando a função is_dir() (tentei também com a função is_file()). Maass... Não funcionou, obtendo o seguinte resultado:

O código que utilizei:
<?php
  header('Content-Type: application/json');

  $path = str_replace("\\", "/", './root');
  $dir  = dir($path);
  $json = array();

  while($file = $dir -> read()){
    if ($file != ".." && $file != "."){
      array_push(
        $json,
        array(
          'path'=>$path.'/'.$file,
          'file'=>$file,
          'type'=>(!is_dir($file)) ? 'file' : 'folder'
        )
      );
    }
  }

  echo json_encode($json);
?>

Comment: OBS: Eu também testei utilizando `dirname(__FILE__)` no lugar de `./` na variável `$path` (por isso está dentro do `str_replace()`)
Answer: Encontrei o problema:
A função is_dir() retorna false se o arquivo especificado não existir e parte da pasta em que o arquivo .php está sendo executado, ou seja, eu estava escaneando os arquivos da pasta ./ e não da pasta ./root.
Encontrei este problema testando com a função file_exists($file) e obtendo também um resultado false.
A solução seria utilizar como parâmetro da função o caminho completo do arquivo. Ou seja: utilizar is_dir($path.'/'.$file) e não apenas is_dir($file), dessa forma o Php encontra o arquivo e se torna capaz de verificá-lo.


nginx error log interpretation

Question: I'm running nginx with php as fastcgi.
From time to time my website goes down and a restart of nginx is required to get it running again.
I find the following in my error log (actual IP's have been replaces for privacy reasons).
Would anyone be able to shed some light into what is actually happening?
Thank you
<code>2011/05/02 06:41:10 [alert] 1686#0: worker process 1690 exited on signal 9
2011/05/02 06:41:20 [emerg] 25259#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/05/02 06:41:20 [emerg] 25259#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/05/29 14:01:08 [alert] 25260#0: worker process 25264 exited on signal 9
2011/05/29 14:01:13 [emerg] 24852#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/05/29 14:01:13 [emerg] 24852#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:10:23 [alert] 24856#0: *14222020 write() to "/var/log/nginx/access.log" was incomplete: 243 of 247 while closing request, client: 184.108.40.206, server: a$
2011/06/16 10:11:27 [alert] 24856#0: *14222228 write() to "/var/log/nginx/access.log" failed (28: No space left on device) while closing request, client: 184.108.40.206,$
2011/06/16 10:12:34 [alert] 24856#0: *14222361 write() to "/var/log/nginx/access.log" failed (28: No space left on device) while closing request, client: 220.127.116.11,$
2011/06/16 10:13:12 [emerg] 7394#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:13:12 [emerg] 7394#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:13:12 [emerg] 7394#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:13:12 [emerg] 7394#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:13:12 [emerg] 7394#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2011/06/16 10:13:12 [emerg] 7394#0: still could not bind()
</code>
Answer: bind() to 0.0.0.0:80 failed - this means it couldnt bind to port 80, this usually means some other application is using port 80, have you potentially also got apache running on this box at the same time by accident?
14222228 write() to "/var/log/nginx/access.log" failed (28: No space left on device) - generally means the disk is full on the volume it writes logs to, its probably a good idea to check your hard drive space usage and do some cleaning of old files or old log files as required
Comment: @Rado He's correct, the 'write()' error means the drive is full, you need to get a bigger/better disk and the 'bind()' error means something else is using port 80, most likely zombied NGINX processes, use `killall nginx` to get rid of them then `service nginx start`. Also you should use `service nginx reload` rather than `service nginx restart`
Comment: Anthony, there's just nginx,  php as fastcgi, imagick php extension and mysql. No apache or anything este installed. Disk should still have space:
/dev/sda1     ext3     19G   15G  3.3G  82%
Comment: The disk is full OR the kernel could have set the filesystem read-only due to a hardware fault. In that case, the command `dmesg` will report drive errors.

nginx error log interpretation


Apollo GraphQL & AppSync: useMutation doing nothing

Question: I'm trying to use the useMutation hook from apollo/react-hooks but there must be something wrong because it just doesn't work (I don't even have an error to work with)
Here is my code :
import { useQuery, useMutation } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
import { API, graphqlOperation } from 'aws-amplify';
import { Button } from '@material-ui/core';

const CREATE_USER = gql`
    mutation Createuserfromcognito(
        $CognitoUsername: String!
        $UserRoles: [UserRole]
        $UserDetails: UserDetailsInput
    ) {
        createuserfromcognito(
            CognitoUsername: $CognitoUsername
            UserRoles: $UserRoles
            UserDetails: $UserDetails
        ) {
            UserId
            CognitoUsername
            UserRoles
            UserIDCard {
                number
                picture_path
                verified
            }
            UserDetails {
                UserEmail
                UserFirstName
                UserLastName
                UserFullName
            }
        }
    }
`;

const TestPage = (): JSX.Element => {

    const [addUser] = useMutation(CREATE_USER);

    return (

            {user.sub}
            <ExchangeRates />
            <Button
                onClick={() => {
                    // API.graphql(
                    //     graphqlOperation(createuserfromcognito, {
                    //         input: { CognitoUsername: 'TEsfsdf' },
                    //     }),
                    // );
                    addUser({ variables: { CognitoUsername: 'TEsfsdf' } })
                        .then(() => console.log('test'))
                        .catch((err) => console.log(err));
                }}
            >
                Test mutation
            </Button>

    );
};

export default TestPage;

I have tried using the amplify graphql implementation and it works, but I would like to understand why the apollo one doesn't.
When I click the button, nothing happens. No request, no console log.
Do you know where I am wrong ?
EDIT : The thing I find the most weird is that useQuery hooks work fine... So I don't think it is an issue about the authentification, endpoint, etc..
EDIT 2 : In fact the issue was with the combination of AppSync and Apollo as stated in my answer below
Comment: No Apollo provider?
Comment: It is defined elsewhere but as I said in my EDIT useQuery hooks work just fine, so I don't think it is the issue.
Comment: missing values for 2 variables ?
Comment: Use the second array element to get useful information like the errors: `const [addUser, { error, loading }] = useMutation(CREATE_USER);`
Comment: Just did that and `{ loading, error, data } = true undefined undefined`. It seems like it is stuck somewhere but I can't find where.
Answer: Ok so I will update my question but my problem wasn't in fact with Apollo but with the combination of Appsync and Apollo. As stated here : https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/448, if you don't set disableOffline to true in you Appsync client, mutations will just hang and do nothing.
Here is my new Client :
const client = new AWSAppSyncClient({
    url: awsconfig.aws_appsync_graphqlEndpoint,
    region: awsconfig.aws_appsync_region,
    auth: {
        type: 'AMAZON_COGNITO_USER_POOLS',
        jwtToken: async (): Promise<string> =>
            (await Auth.currentSession()).getIdToken().getJwtToken(),
    },
    disableOffline: true,
});


Image Inconsistency in Browser

Question: Lately, I've been using HTML Canvas 5 element recently in an attempt to extract image data from a given image on the browser but I've run into a bit of a problem.  When extracting this data using the canvas element's functions such as getDataURL or getImageData(), the results are inconsistent across browser.  I realize this is due to the fact that the browser's native code is different for each, therefore the rendering engine will render the images differently.  However, is there a way to get consistent image results across browser for images of size 500kb-1mB for example?
I'm aware of the AJAX solution, calling the json object of the dataURL of that image from the server as that will be the original source, thus consistent across browser.  Also, loading the dataURL into the browser from the server could be another solution.  The problem with these would be the performance and flexibility.  Is there any other viable solutions?  Did I look over something I could be doing client side?
Thanks all!
Comment: By "consistent" do you mean "visually indistinguishable to the human eye" or "byte-for-byte identical"?
Comment: Byte for byte identical.  They are already visually indistinguishable as I'm using the same image on each browser.
Comment: What data format is it, are they compressed pictures?
Comment: What do you mean by "*calling the json object of the dataURL of that image from the server*"?
Comment: Sorry for the delay, the images are in JPEG/PNG format.
Comment: I mean, I access the data URL of the image from the server as a JSON object.
Answer: Ok, after continuing with my own project I discovered an answer which worked for me and would probably suit your purpose.
toDataURL was the mistake, because that reads the 'binary' data into the canvas and NOT the actual pixels. There are inconsistencies between browsers on interpreting that binary, and anyway that binary data is not giving you the pixel info which I assume you are looking for.
To preserve the data You need to take the image (keep original size) into the canvas then use getImageData(x,y,w,h) to load the RGBA pixel data into an array.  You can then simply loop through the now 'real' pixel data and process that.
I tried scaling down the image into a manageable size but that wasn't always consistent across browsers. I only needed a section of the image anyway so this method served my purpose, perhaps you could hide the full scale canvas you are working on and present a representative scaled down canvas to the user.

Image Inconsistency in Browser


Block visibily condition programatically

Question: I want to display a block I implemented in a module when <code>$_SESSION['Group_id']</code> is set.
How can I achieve this?
Answer: In the block ::build() method, return an empty array() if the condition is false.


mutating object as singleton?

Question: I am not sure, if anyone has asked this question before (If so apologies).
code copied from wikipedia.
public class Singleton {
   private static final Singleton instance = new Singleton();

   private Singleton() {}

   public static Singleton getInstance() {
      return instance;
   }
}

How it is thread safe? is it(only) because there is no mutating state in this class?
what happens if I modify it like this
public class Singleton {
    private static final Singleton instance = new Singleton();
    private FancyClass obj1;
    private FancyClass obj2;

    //feel free to imagine all the getters and setters for obj1 and obj2,
    // like getObj1() and so forth

    //tricky method
    public void doSomething() {
      obj1.destroyEnemy();
      obj2.destroyFriend();
    }

    private Singleton() {
       obj1 = null;
       obj2 = null;
    }

    public static Singleton getInstance() {
      return instance;
    }
}

I have no interest in design-patterns discussion, this is the kind of code, I am supposed to maintain. is the above 'singleton' thread safe, assuming that FancyClass is java standard library class.
Comment: Since you are making your constructor private it will never be called. So declaring it null there makes no sense. Anyway instance variables are automatically assigned default values.
Comment: @AniketThakur Yeah, That is super-dumb(initiializing in constructor with null). I was just rewriting an existing class without specifics.
Comment: Note, bunging a `synchronized` in wont make operations that require multiple method calls thread-safe. A `synchronized` "get" method is usually pointless. (ObComment: Mutable statics are a really bad idea.)
Answer: You're right that the first example is safe only because there is no mutable state.
In the second example, the singleton isn't doing anything to make it threadsafe, whether it's safe depends on if FancyClass is threadsafe. Putting synchronized on the doSomething method would make it threadsafe.
Introducing getters and setters for obj1 and obj2 would also have the potential to create problems, those would have to be synchronized on the same lock as the doSomething method, and you would need locking even if FancyClass is threadsafe, because if different threads are changing things then those changes need to be made visible across threads.
Comment: Ok, FancyClass is thread safe according to docs. (part of JDK)
Answer: The first code guarantees that all threads that call getInstance() get a reference to the same instance of Singleton.
For your implementation (second example), the same is true for obj1 and obj2, because they're created while the class itself is created and class creation is thread safe (can't be created twice/"in parallel" within the same classloader).
The doSomething() method is not thread safe. Make it synchronized if you need an atomic operation.
Comment: I assume same would be true with, getters and setters of obj1 and obj2, I need to make them synchronized as well?
Comment: @fedvasu If you only set or get the objects, then synchronization is not necessary. See: http://stackoverflow.com/a/1351271/105224
Answer: The Singleton pattern is not designed to be Thread Safe at all, just to be unique and forbidding creation of additional instances. The only part that is thread safe in you code is the Singleton instantiation private static final Singleton instance = new Singleton(); as it's invoked one time a class loading time.
But effectively, if there's no members in your class modified by a method invked concurently by external systems, your Singleton will be/stay ThreadSafe
Answer: About your code -
Since you are making your constructor private it will never be called. So declaring it null there makes no sense. Anyway instance variables are automatically assigned default values.
First of all the 1st code
   public class Singleton {
   private static final Singleton instance = new Singleton();

   private Singleton() {}

   public static Singleton getInstance() {
      return instance;
   }
}

is called Early initialization unlike lazy initialization in which you create instance only when needed. To make it thread safe you need to do the following
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }

Example is of lazy initialization but the concept remains the same.
Comment: You forgot set it as volatile it should be:  private static volatile Singleton singleInstance = null;
Comment: Why do you need to if statements checking the same thing. I'm assuming that's a mistake?
Comment: @AndrewMartin No it is not a mistake. It is called double locking mechanism. Here is the [Wiki](http://en.wikipedia.org/wiki/Double-checked_locking)
Comment: @AniketThakur: Thanks - never seen that before. Will read up on it.
Comment: @AndresL Yes problems might arise during thread scheduling. So it is good practice to declare it as volatile as well. Thanks for pointing it out.

mutating object as singleton?


Echo colorido em php

Question: Tem como deixar o ECHO em PHP colorido ? Imprimir no HTML, letra por letra colorido ex:
if (strpos($d5, '{"name":"')) {
    echo 'LIVE ->' . $a . '|' . $b . ' | C:' . $c . '';

} else {
    echo "DEAD -> $a|$b ";
}

Tudo que der LIVE e DEAD (imprimido na tela) sair tudo colorido
Answer: Você pode fazer uma função que gera essas letras coloridas.
function geraLetrasColorida($palavra) {

    // Separa as letras
    $letras = str_split($palavra);

    // Percorre todas as letras
    foreach($letras as $letra) {

        // Gera uma cor aleatória baseado no hexadecimal da cor.
        $cor = dechex(mt_rand(0x000000, 0xFFFFFF));

        // Imprimi o html com a letra gerada.
        echo "".$letra."";
    }
}

Dessa forma (a cima), você consegue pegar uma palavra e gerar letras coloridas apenas chamando essa função.
geraLetrasColorida("Não sei, só sei que foi assim!");

Comment: Muito obrigado!
Answer: Usar str_split, explode ou até mesmo iterar string não vai funcionar se acaso estiver usando unicode (UTF-8 por exemplo), como explicado em:

str_split não funciona bem em string contendo UTF-8?
https://pt.stackoverflow.com/a/260398/3635

Para isto você pode usar preg_split com o modificador u, assim:
preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY);

Usei como base esta resposta https://stackoverflow.com/a/25996226/1518921 para gerar as cores, deve ser algo como:
<?php

function mb_text_color($texto)
{
    $letters = preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY);

    foreach ($letters as &$letter) {
        if (trim($letter) === '') continue;

        $cor = dechex(rand(0x000000, 0xFFFFFF));
        $letter = '' . $letter . '';
    }

    return implode('', $letters);
}

echo mb_text_color('foo bár');

Para usar, pode fazer assim:
if (strpos($d5, '{"name":"')) {
    echo mb_text_color('LIVE ->' . $a . '|' . $b . ' | C:' . $c);

} else {
    echo mb_text_color("DEAD -> $a|$b ");
}

Ou assim:
if (strpos($d5, '{"name":"')) {
    echo 'LIVE ->' . mb_text_color($a . '|' . $b . ' | C:' . $c);

} else {
    echo 'DEAD -> ' . mb_text_color("$a|$b ");

Ou variável por variável, como você desejar.

Echo colorido em php


Elementary proof for non-existence of a pointwise convergent subsequence of $\{\sin (nx)\}$

Question: My teacher showed this proof using the dominated convergence theorem or Fourier analysis, but I wonder if there is an elementary proof of this problem. My teacher said it is difficult to solve this in an elementary way, but do you know how?
Comment: Assume that $\{\sin(n_k x)\}_{k\geq 1}$ is pointwise convergent. In order to have pointwise convergence at $x=\frac{\pi}{2}$, all the $n_k$s from some point on have to be even. In order to have pointwise convergence at $x=\frac{\pi}{3}$, all the $n_k$ from some point on have to be multiples of $3$ $\ldots$ This kind of sieve leaves little chances for the arithmetic behaviour of $\{n_k\}_{k\geq 1}$.
Comment: @JackD'Aurizio I don't think that argument works; $sin(n!x)$ converges for $x=\pi/k$ for any positive integer $k$.
Comment: @stewbasic: but it doesn't at $x=\sqrt{2}$, for instance. My idea was to prove first something very strong on the arithmetic behaviour of $\{n_k\}$, then exploit it to prove that pointwise convergence fails somewhere else.
Answer: Here is an elementary proof inspired by this proof.
Fix the subsequence $1\leq n_1<n_2<\ldots$. I will inductively construct sequences $a_1\leq a_2\leq\ldots$ and $b_1\geq b_2\geq\ldots$ such that:

$a_i<b_i$
$\sin(n_k[a_i,b_i])\subseteq(-1)^i[1/2,1]$ for some $n_k\geq i$.

Let $a_1=(-\pi/2)/n_1$ and $b_1=(-\pi/6)/n_1$. Suppose $[a_i,b_i]$ have been constructed. Pick $n_k$ larger than $i$ and larger than $3\pi/(b_i-a_i)$. Let $m=\lfloor n_kb_i/(2\pi)-1/4\rfloor$. Note that
$$
  2\pi m+\pi/2\leq n_kb_i,
$$
$$
  2\pi m-\pi/2\geq n_kb_i-3\pi\geq n_ka_i.
$$
Thus we can take
$$
  a_{i+1}=\left(2\pi m+\pi/6\right)/n_k,\,
  b_{i+1}=\left(2\pi m+\pi/2\right)/n_k
$$
if $i+1$ is even, and
$$
  a_{i+1}=\left(2\pi m-\pi/2\right)/n_k,\,
  b_{i+1}=\left(2\pi m-\pi/6\right)/n_k
$$
if $i+1$ is odd. This concludes the inductive construction.
Now $a_i$ is a bounded monotonic sequence, so it converges to some $a$. For each $i$ we have $a_i\leq a\leq b_i$, so
$$
  \sin(n_ka)\in(-1)^i[1/2,1]
$$
for some $n_k\geq i$. This shows $\sin(n_ka)$ cannot converge as $k\to\infty$.
Comment: Awesome! I really love this proof. It is really visual and essentially needs no calculation. Thank you.
Comment: I think, in the same way, we can show that given a continuous periodic function f(x) which is not constant, there is no point wise convergent subsequence of f(nx).
Comment: It does not seem to me visual. Could you give more intuitive explanation of this, please?
Answer: Here is a proof using measure theory (so unfortunately not elementary).
Fix the subsequence $n_1<n_2<\ldots$ and let $X$ be the set of $x\in\mathbb R$ for which $\sin(n_kx)$ converges. For any $\epsilon\in(0,1)$ let
$$\begin{eqnarray*}
  Y_k^\epsilon&=&\{x\in[0,4\pi]\mid|\sin(n_kx)-\sin(n_{k+1}x)|<2\epsilon^2\},\\
  X_k^\epsilon&=&\bigcap_{l\geq k}Y_k^\epsilon.
\end{eqnarray*}$$
Note that each $Y_k^\epsilon$ is open and therefore measurable, so $X_k^\epsilon$ is also measurable. Moreover
$$
  |\sin(n_kx)-\sin(n_{k+1}x)|=2|\cos(ax)\sin(bx)|
$$
where $a=\frac{n_k+n_{k+1}}2$, $b=\frac{n_k-n_{k+1}}2$. Hence $Y_k^\epsilon\subseteq A_k^\epsilon\cup B_k^\epsilon$ where
$$\begin{eqnarray*}
  A_k^\epsilon&=&\{x\in[0,4\pi]\mid|\cos(ax)|<\epsilon\},\\
  B_k^\epsilon&=&\{x\in[0,4\pi]\mid|\sin(bx)|<\epsilon\}.
\end{eqnarray*}$$
We have
$$\begin{eqnarray*}
  \mu(A_k^\epsilon)&=&\frac1a\mu(\{u\in[0,4a\pi]\mid|\cos(u)|<\epsilon\})\\
    &=&2\mu(\{u\in[0,2\pi]\mid|\cos(u)|<\epsilon\})\\
    &=&2\mu\left((\pi/2-\delta,\pi/2+\delta)\cup(3\pi/2-\delta,3\pi/2+\delta)\right)\\
    &=&8\delta
\end{eqnarray*}$$
where $\delta=\sin^{-1}(\epsilon)$. A similar calculation applies to $B_k^\epsilon$. Hence
$$
  \mu(X_k^\epsilon)\leq\mu(Y_k^\epsilon)\leq16\sin^{-1}(\epsilon).
$$
Note that $X_1^\epsilon\subseteq X_2^\epsilon\subseteq\ldots$, so
$$
  \mu\left(\bigcup_kX_k^\epsilon\right)\leq16\sin^{-1}(\epsilon).
$$
Finally
$$
  X\cap[0,4\pi]\subseteq\bigcup_kX_k^\epsilon.
$$
Since $\epsilon\in(0,1)$ was arbitrary and $X$ is $2\pi$-periodic, $X$ cannot contain any set of positive measure. (I'd like to say that $\mu(X)=0$, but it may not be measurable). In particular $X$ cannot equal $\mathbb R$.

I tried to find a proof which shows that $X$ is countable, but this is not always true. For example, let $n_k=k!$. Let $A$ be the (uncountable) set of sequences with values in $\{0,1\}$, and define $f:A\rightarrow\mathbb R$ by
$$
  f(a)=2\pi\sum_{k=1}^\infty\frac{(-1)^{a_k}}{k!}.
$$
Note that for $k\geq1$ we have
$$
  \left|\sum_{l>k}\frac{(-1)^{a_l}}{l!}\right|\leq
    \frac2{k+1}\sum_{l>k}\frac{1}{l!2^{l-k}}=\frac2{(k+1)!}\leq\frac1{k!}.
$$
This implies $f$ is injective, so $f(A)$ is uncountable. Moreover
$$
  |\sin(n_kf(a))|=\left|\sin\left(2\pi k!\sum_{l>k}\frac{(-1)^{a_l}}{l!}\right)\right|
    \leq\frac{4\pi}{k+1}
$$
so $\sin(n_kf(a))\rightarrow0$ as $k\rightarrow\infty$. Thus $f(A)\subseteq X$.
Comment: Why $Y_k^\epsilon\subseteq A_k^\epsilon\cup B_k^\epsilon$ ?
Comment: If $x\not\in A_k^\epsilon\cup B_k^\epsilon$ then $|\cos(ax)|\geq\epsilon$ and $|\sin(bx)|\geq\epsilon$, so $2|\cos(ax)\sin(bx)|\geq2\epsilon^2$, so $x\not\in Y_k^\epsilon$.


Regression output and relation of 2 regression lines

Question: If I have data with a continuous outcome variable (yvar), age and gender and I run regression as follows (R code):
<code>summary(lm(yvar~age+gender+age*gender, data=mydata))
</code>
How will be the regression output in case of each of following 3 plots between age, gender and yvar:

This question is related to: How to determine signficant difference between 2 curves?
Thanks for your help.
Edit: Assume age is significantly related to yvar. Will gender and age:gender be significantly related in each of three plots? Since gender has not effect in plot A, I think both gender and age:gender will not have a significant P-value in plot A.
Based on comments by @schwebels:
<code>            plot A   plot B       plot C
age         sig      sig          sig
gender      NS       sig or NS    sig
age:gender  NS       sig          NS
</code>
Answer: There is no indication of variance but let's assume the variance is small relative to the effect size
Plot A: The effect of age on yvar looks significantly greater than 0 for both F and M . (F and M start at the same yvar and increase at the same rate as a function of age).
Plot B: The effect of age on yvar may be significantly greater than 0 for both F and M and the slope (the size of the effect) is possibly different between F and M. (F and M start at different yvar and increase at different rates as a function of age)
Plot C: The effect of age on yvar may be significantly greater than 0 for both F and M, the slope is equivalent for F and M and the y-intercept may be significantly different between F and M. (F and M start at a different yvar and increase at the same rate as a function of age)
Comment: Given that age is a significant predictor of yvar, plot A does not show a gender effect and therefore the gender*age interaction is not evaluated. In plot B gender modulates the effect of age on yvar and is significant. The age*gender interaction term is significant. In plot C gender is significant and gender*age is not significant because only the intercept is affected by gender, not the rate of change.
Comment: You have basically described the plots. The regression output gives coefficients and P value for age, gender and age:gender. What will be the P-values (significant or not) for these three parameter for three plots above? That is the main question. Lets assume age is significantly related to yvar.


How can I add rows to grouping in views?

Question: I have a view that lists terms from two different vocabularies (Product Categories, and Traits). The Product Categories vocabulary looks something like this:

Sweet Corn

Type 1
Type 2

Onions

Type 3
Type 4

Popcorn

Type 5
Type 6

Each of these parent categories also have specific traits that are identified in the Traits vocabulary that looks like this:

High Expansion
Augmented
Celebrate

High Expansion is a trait of Popcorn, Augmented is a trait of Sweet Corn, and Celebrate is a trait of Onions. Traits are different from Categories, and must be defined in a separate vocabulary due to other definitions and functionalities on the site. So, I can't just make them children of the above parent terms.
I have a view that is a main landing page for the product categories that displays the icons for all the Categories and Traits, that the user can click to see a filtered view of products within the category clicked. I am grouping the view results by Parent term, but also need to include the Traits in the appropriate groups.
On my landing page view, I need to list the Traits under the appropriate grouping, so my landing page view should look something like:

Sweet Corn

Type 1
Type 2
Augmented

Onions

Type 3
Type 4
Celebrate

Popcorn

Type 5
Type 6
High Expansion

Is there any way to accomplish this type of grouping?
Thank you for your help!
Comment: I'm very confused by your question.  Please identify all of the entities that we're dealing with, and how they relate to each other.  It sounds like you have 2 separate vocabularies: Product Categories and Traits.  It also sound like maybe you have a content type called "Product" -- is that true?  What relationship does each item have to the other?

Furthermore, we need more of an explanation of what you're actually trying to list in Views.
Comment: Sorry for the confusing explanation, I have edited my question to try and clarify. Let me know if this helps. It's a tough one to explain in writing.
Comment: Much better! Thanks for the improved question. It is very clear now.
Comment: That is a different, and better, question.  You say "Each of these parent categories also have specific traits that are identified in the Traits vocabulary" do you mean the Trait term is on the Category term, or is it on a product that is marked with the category parent?
Comment: The trait term is on a product that is marked with a category child.
Comment: @user1697606 I'm not 100% clear on how you're using the words "product" and "category" in your last answer.  In your example is "sweet corn" a taxonomy term in the vocabulary "product category" or is it a node of the type "product"?
Answer: The views Format Settings has your answer.  There is a drop-down for "Grouping field Nr.1" that does exactly this.

As it is, you have one "row" showing for each unique set of values because this is what mysql returns.  By setting this field grouping, Views will match up the values from the selected field and use them as headers for sub sections of your results.
If this is not a good enough match to your issue, please provide details on how it doesn't work and I can update the answer.

Continued:
The view is a tool for making a mysql query and then theming the returned result.  With this in mind, you need to craft a set of data relations and filters to get the appropriate data linkages for the ratios you want in your display.  This means you want the database handing you a field table like:
Category parent | product | category | trait

Sweet Corn | corn product 1  | Type 1  |  Null
Sweet Corn | corn product 2  | Type 2  |  Null
Sweet Corn | generic corn product  |  Null | Augmented
Onions | onion product 1 | Type 3 | Null
Onions | onion product 3 | Null  | Celebrate

Then once you have the dataset you need, you work on the theming side of the views tool.  Use the above mentioned Grouping field setting on the Category Parent.  This will make the sections with the parent titles as indicated in your question, but it might look like

Sweet Corn

corn product 1  | Type 1  |
generic corn product  | | Augmented

Then use the "exclude from display" on the product field, or actually remove it from the fields list.  I have it included here because it is needed to show the data grouping as I understand it in your question.  Finally, configure the "category" field with the link you want it to have and exclude it from display; use the "No Results Behavior" rewrite option on Trait to put in the token for the Category field, something like [field_term_category].  You should be able to find this token in the list of "replacement patterns" available in the Rewrite Results area.

You should now have a list of parent categories showing the linked sub categories and traits where you want them.  The "trait" field will either have the category or the trait in there, as it shows trait when trait is present, and category when not.  Be sure to uncheck the "hide if empty".
Answer: For this to work "properly" (I say properly because you could fudge it visually with CSS and javascript but let's not do that) without custom code you're going to need to do one of 2 things:

Make the "Trait" terms reference the "Category" terms rather than the other way around ...or:
Make the "Trait" field on the "Category" terms be an entityreference field rather than a term reference field.  This is necessary because entityreference gives you views relationships that let you access the referencing entity.

I'll assume you went with option #2 for the purposes of this write-up.  The solution will be quite similar if you went with option #1, but you just won't need to add a relationship in the first view we create,  below.
Once you've done that, create 2 views:

One that can be used with the Views Field View module (could also be done with the EVA module in a similar fashion) to list the items that belong under the top-level categories.
One for listing the top-level categories

View #1:
This one is the more complicated view. This view is going to take in a term ID of one of the parent categories (like the tid of "Sweet Corn") and we want it to list any terms that are either child terms of that term, or are traits of that term.
Install the Views Field View module and the Views Contextual Filters Or module.  This view should also be a list of taxonomy terms and needs to be configured like so:
Relationship:
Add a relationship to the referencing entity via the traits field.
Contextual Filters:

A contextual filter on the parent term ID.
A contextual filter on the term ID (be sure to set this to use the relationship to the referencing entity that we already set up)

Now, we need to make our contextual filters use "or" logic, so if you installed the Views Contextual Filters Or module you will now have an option in your view under Query Settings to turn this on.
View #2:
This should be pretty straightforward. This will also be a view based on taxonomy terms.  You'll probably want to make this use a "page" display and give it a URL.  And you'll want to choose to render the terms using "fields".
Fields:

Term name
Term ID - set this to be excluded from display, we only add it to make it available as a token for our next field
Global: View -- you'll be able to select the appropriate view and display that you configured when you set up view #1, above.  You'll also get to enter arguments to pass to the view, so enter [!tid]/[!tid]

Filters: (just regular filters, not contextual filters)

Vocabulary (so that it only shows terms from the "Category" vocab.
Parent term.  Set this filter to be equal to 0.  This will ensure only top-level terms are displayed.
Comment: This worked perfectly! I'm not sure I understand how it's working, but it works. Thank you for your help!