Successful connect to a closed port with FirewallD

Question: Please help to understand why FirewallD allows me to connect to one port but blocks the second.
There is a Docker container with transmission:
5cf144eed6f2        maksim77/transmission   "/bin/sh -c 'transmis"   14 hours ago        Up 16 minutes       0.0.0.0:9091->9091/tcp, 0.0.0.0:51413->51413/tcp   transmission

Both ports (9091 and 51413) are not listed in FirewallD rules:
root@host:maksim #firewall-cmd --list-all-zones | grep active
public (default, active)
trusted (active)

root@host:maksim #firewall-cmd --list-all --zone trusted
  trusted (active)
  interfaces: docker0
  sources:
  services:
  ports: 4243/tcp
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules:

root@host:maksim #firewall-cmd --list-all --zone public
  public (default, active)
  interfaces: enp9s0
  sources:
  services: dhcpv6-client ftp http ssh
  ports: 41387/tcp 1900/udp 50213/tcp 8200/tcp
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules:

But! The connection is successful for port 9091 but not for port 51413. Port 51413 is available only for 127.0.0.1
Comment: Can yo tell which interface accepts the connection for port 9091? Do you know which interface should've handled 51413?
Comment: netstat shows `tcp6 0 0 :::9091 :::* LISTEN 9807/docker-proxy`
I think 51413 needs to be the same.
Comment: Make sure you did `EXPOSE 51413` and you did _not_ set `bind-address-ipv4` in transmission's [config file](https://trac.transmissionbt.com/wiki/EditConfigFiles).
Comment: Of course i EXPOSE both port. bind-address-ipv4 = "0.0.0.0"
Answer: You don't see these in firewalld because Docker opens the ports itself, outside of firewalld.
To see what Docker is doing, run:
iptables -L DOCKER
iptables -t nat -L DOCKER

Docker will open firewall ports itself for any port your containers EXPOSE, unless you explicitly disable this. It also allows containers which need to communicate with each other to do so, so you should leave this enabled unless you really know what you're doing.
Comment: Thank you! It is now clear why it is not visible in the output ports on the FirewallD.

According to iptables both ports are open but port 51413 is closed from the outside. Whereas at the request of localhost it is available.


foreach in ASP.net with nested runat="server"

Question: For the following code:
<% foreach (Entities.Core.Location loc in locations){ %>

<% }; %>

I would like to display the star rating image for each location object displayed. However, only the first location object's star rating is displayed. For the rest, the image tag becomes
Am I missing anything in the syntax that allows the ability to have controls with runat=server within a foreach on the aspx page? This is with ASP.net 2.0.
I could possibly call a function in the codebehind or a display class to absolute map the URL but I am very curious if there is a solution to this problem.
Just for clarifications, the path to the image could possibly be different for each location object.
Answer: You can't use server controls within an inline loop, because ASP.NET needs to be able to uniquely identify each control to process it. The for... loop prevents this. The easiest and cleanest way is to use a Repeater control and bind your collection to it (in code-behind). Set the URL property in the bind event handler, and maintain a counter variable while binding, to check if you're at the first item or not.
Edit: I've played around with this some more, and found that if you assign an ID attribute, all looped instances get the same ID, but ASP.NET only recognizes the first control found. This would be an extremely dirty way to set properties on the first instance only. Please don't write code like this.
Comment: This is "easier" than simply changing the image tag to not be a server control?  I understand that it may be the accepted way, but it doesn't sound easier.
Comment: Well, depends on the requirements. How would you want to manipulate the control instances (set properties, etc.) if you make them entirely clientside?
Answer: Unless you're using MVC, you might find a Repeater Control more useful in this situation.
If I remember correctly, you can use a source of data (your locations in this instance) and then loop through and set each image.
Answer: I don't know if your code is supposed to work, but this one is ;-)
<asp:Image ImageUrl="~/static/images/stars/star_25_sml.gif" runat="server" class="star_rating" />

Perhaps it's what you are looking for.
EDIT: looking at the code of System.Web.UI.HtmlControls.HtmlImage you can see that the src attribute is removed after the (first) processing. This may be the reason why you can get just the first URI correct with your code.
Answer: I would remove the runat="server" attribute and reference the image using a relative path (or the full path) instead of using the tilde.
EDIT: FWIW, @miies idea fits the ASP.NET paradigm AND is an example of why I'm switching to ASP.NET MVC.


Two sites, same codebase mystery

Question: Ubunutu Server, two Drupal sites. One dev and one live. Both domain names take you to the same code and database, the ones correct for the live site.
Checked apache virtual host files. Both the dev and live sites are pointing to different directories where they should go, one to the live code, and one to dev.
What setting, and where, could make the dev site point to the live one, instead of where apache's virtual host file says it's pointing?
*I should add, this occurred after a server upgrade.
Comment: If it's multilingual, and you've set a language domain, it will redirect. Otherwise you can look in .htaccess for redirects, or check if you've got the redirect module enabled, and that module is redirecting it.
Comment: thank you Jaypan! I have checked the htaccess, but will check now for the redirect module. Your reputation on drupal.org proceeds you, you are famous for answering questions. :)
Comment: I deleted the htaccess file in the dev site directory to see if any of the rewrite rules were even being followed. The site is still up with it deleted, so the server is pointing the dev domain to the live site directory. :( I inherited this site and I'm trying to figure it out. Should the /etc/apach2/apache2.conf file have ServerName [live site domain] at the very top? That seems strange to me. Also should that file have "AllowOverride None" under the ? AllowOverride All is set in the virtual hosts files.
Answer: The answer to this was that the dev site was being redirected to the live site, where the "https" was then crossed out, but the domain name remains, confusingly, the same.

Two sites, same codebase mystery


What's the ideal greylist scheme with multiple MX in different locations?

Question: We currently have two MX servers in the same physical rack, they are sharing the same greylist database, and everything seems to work well. The two MX have different priorities and they are on two different physical servers, so we get redundancy if one of the two fails.
(FYI, the database is on a virtual machine on a redundant hardware cluster: while the db system as a whole is a Single Point of Failure, the hardware it runs on is not, eliminating most of the possible failure modes)
We'd like to introduce a new (or a pair of) MX in a different datacenter, to achieve full redundancy of the incoming mail systems (our DNS servers are already distributed over different DCs), but we can't connect it to the very same MySQL server since that would defeat the redundancy in the first place.
What is the correct way to implement greylisting in such a setup?
Can I just let every location / MX group have its own greylist db, or will that pose any problem or inefficiency? Is there any reason to configure MXes in the same site with the same/different priority or that doesn't matter? (of course different sites will always have different priorities)
EDIT / CLARIFICATION: first replies seems to suggest to setup MySQL replication (either master/slave or two way) or explain how to do that: been there, done that. I can put up a two way MySQL replication between data centers if I need/want to.
My question was focused on if I need to replicate / share the greylist db or if I can do without shared knowledge between the different greylisting MXes, not how to implement shared knowledge.
Comment: ...I'll bite.  If you have a greylist, and it's been created by process FOO for server BAR, why is that greylist not equally as valuable to server PUB when your mail has failed over?  I mean, if you're not concerned with the greylist being up to date for your mailserver, why are you even bothering with it in the first place?  I think that's why so many of us are focusing on replication.
Answer: The worst-case scenario is if your primary data centre goes offline after an initial delivery attempt, the secondary data centre takes over and it has no record of the first delivery attempt.  It will treat the follow up delivery attempt as the initial delivery attempt and will tell the relaying server to try again later.
Since the delay time is often only 5 minutes, this means that the greatest possible delay is about 10 minutes.  Initial delivery at 0 minutes, second delivery to a different mail server at 5 minutes and then the final accepted delivery at 10 minutes.
Given that delay periods other than 5 minutes are possible, the worst case is actually a delay of double of whatever the normal delivery delay is in the case when a data centre fails.
If this is acceptable to you in a data centre failover situation then you won't need to share your greylisting database.  If it isn't, then replication would be the way to go.
Comment: MX priorities: if they are different, then the first MX will get most of the mail, and greylisting will mostly work as if there is only one mail server receiving the mail.  If the priorities are equal, then the retrys will often go to another receiving server, and you will commonly see delays unless the DB is common to the servers. In any case, you can reduce the greylisting delay to 1 minute and still avoid most spam.
Answer: I'm guessing the greylist isn't ludicrously large or active... why not master/slave replication on the MySQL database to the remote datacenter?
Comment: Master/slave replication isn't a good idea in this scenario. It puts a non trivial amount of complexity in the system (not the replication itself, that's easy, but the automatic master/slave switch on the sql servers and the automatic sql server selection on the clients), not to mention the most probable failure is intermittent network between the DCs, leaving you with split brain and resync issues.
Answer: I would suggest you use replication to synchronise your mysql database between both location.
Depending on the structure of your databases there are many possibilities, but a common setting is to configure each cluster to generate independent serial keys and make them replicate each other. For example in my.cnf:
<code>auto-increment-increment = 5
auto-increment-offset = 1  ( and 2, 3, 4 , 5 on your other clusters )
</code>
In case of crash each cluster keeps a log of the not-yet-replicated-transactions locally so that when the other side comes up the transactions are delivered.
Edit:
Ok, you need to synchronise your clusters else you will greylist the same ip address independantly on each of your clusters, which might in practice multiply the greylist time  by the number of clusters you setup.
By the way, why don't you set the same MX priority to all your MX entries?
Comment: Your reply seems to assume that I actually need shared knowledge between the greylisting databases and individual dbs are not a good idea: what's the motivation behind this? It's far easier to setup simple independent MySQL dbs if you don't have any specific reason to do otherwise. I've edited and tried to clarify my question.


Is this 5th root in the set of natural numbers?

Question:
Is $$\sqrt[5]{x(x+1)(x^4 + x^2 + 1)} \in \mathbb{N}$$ for some $x$?

I am not asking for all $x$, but just for some natural number $x$?
I don't believe so, but I may be wrong?
Suppose $x=1$, you get $\sqrt[5]{6}$ which isnt natural.
$x=2$, you get $\sqrt[5]{126}$
$x=3$, you get: $\sqrt[5]{1092}$
I might just try a proof by induction. Suppose for $x \in \mathbb{N}$:
$$\sqrt[5]{x(x+1)(x^4 + x^2 + 1)} \notin \mathbb{N}$$
But I dont see how that would work out...
Comment: You mean for  $x \in \mathbb R$ or $x \in \mathbb N$? If the first case definitely yes.
Comment: Second case natural.
Comment: @Lebes you have to add $x$ natural number in th body of the question and add a tag "elementary number theory"
Comment: What have you tried? What leads you to the belief that no such $x$ exists? If you include that in your question you are more likely to get an answer.
Comment: @ShreevatsaR, I will put this too, but I tried the first few integers.
Answer: Note $(x+1)(x^4+x^2+1)=x^5+x^4+x^3+x^2+x+1$.  But for $x\in\mathbb N, x>0$ we have
$$
x^5 < x^5+x^4+x^3+x^2+x+1 < x^5+5x^4+10x^3+10x^2+5x+1 = (x+1)^5
$$
so that $x^5+x^4+x^3+x^2+x+1$ is not a perfect fifth power, since it it strictly between two consecutive fifth powers.
Next, note that $x$ and $x^5+x^4+x^3+x^2+x+1$ are relatively prime.  If their product is a perfect fifth power, then both of them are perfect fifth powers.
Thus, $x(x+1)(x^4+x^2+1)$ is not a perfect fifth power.


Meu arquivo js não está carregando

Question: Estudando Ajax com JQuery, no livro do Mauricio Samy Silva não está funcionando comigo. Fiz um arquivo js fora e agora eu não consigo carregá-lo. O que fiz acho não está errado. Debuguei o browser com F12 e não vejo nenhum erro de js. Coloquei vários alerts e não disparou nenhum. Abaixo me js e na sequencia meu html. Usei o próprio template do VS2013.
function iniciaAjax() {

    var objAjax = false;
    if (window.XMLHttpRequest) {

        objAjax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){

        try
        {
            objAjax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                objAjax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (ex)
            {
                objAjax = false;
            }
        }
    }
}

function requisitar(arquivo){

    var requisicaoAjax = iniciaAjax();
    if (requisicaoAjax) {
        alert(1);

        requisicaoAjax.onreadystateshange = function () {
            alert(2);
            mostraResposta(requisicaoAjax);
            alert(3);
            requisicaoAjax.open("GET", arquivo, true);
            requisicaoAjax.send(null);
            alert(4);
        }
    }
}

function mostraResposta(requisicaoAjax) {
alert(11);

    if (requisicaoAjax.readyState == 4) {
alert(21);
        if (requisicaoAjax.status == 200 || requisicaoAjax.status == 304) {

            alert("Problema com o servidor");

        }
        else
        {
            alert("Problema com o servidor");
        }
    }
}

Eveja como está meu Html. O arquivo acima(js) coloquei dentro de um arquivo chamado libAjax, conforme está no meu html.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Teste_Javascript._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

ASP.NET

ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.

Learn more »

    Resultado aqui

Getting started

                ASP.NET Web Forms lets you build dynamic websites using a familiar drag-and-drop, event-driven model.
            A design surface and hundreds of controls and components let you rapidly build sophisticated, powerful UI-driven sites with data access.

                Learn more »

Get more libraries

                NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

                Learn more »

Web Hosting

                You can easily find a web hosting company that offers the right mix of features and price for your applications.

                Learn more »

</asp:Content>

Comment: Atualizei a resposta com outros erros que encontrei :)
Answer: Acho que identifiquei seu problema, você não está retornando o objAjax na função de iniciaAjax(), faça:
function iniciaAjax() {

    var objAjax = false;
    if (window.XMLHttpRequest) {

        objAjax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){

        try
        {
            objAjax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                objAjax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (ex)
            {
                objAjax = false;
            }
        }
    }
    return objAjax; /* aqui */
}

Descobri 2 erros na sua função requisitar, estava escrito onreadystateshange ao invés de onreadystatechange e a chamada da requisição tava dentro da função.
function requisitar(arquivo){

    var requisicaoAjax = iniciaAjax();
    if (requisicaoAjax) {
        alert(1);

        requisicaoAjax.onreadystatechange = function () {
            alert(3);
            mostraResposta(requisicaoAjax);
            alert(4);
        }
        // isso fica fora do onreadystatechange
        requisicaoAjax.open("GET", arquivo, true);
        requisicaoAjax.send();
        alert(2);
    }
}

Comment: Não. O primeiro alert foi disparado, mas os demais não, ou seja, ele validou a função com True e depois acho que ele sai do escopo. Com F12 não vejo nenhum erro.
Comment: @pnet Atualizei a resposta com outros 2 erros que encontrei na sua função.
Comment: Não entra nesse bloco: requisicaoAjax.onreadystateshange = function () {
            alert(2);
            mostraResposta(requisicaoAjax);
            alert(3);

        }
Comment: @pnet Como eu te disse você está escrevendo `shange` ao invés de `change`, dessa forma ele nunca vai chamar.
Comment: Cara, nem me atentei a isso. Resolvido. Vou marcar sua resposta.
Comment: @pnet Bom estudo! :)
Answer: Importe o javascript dessa maneira:

Comment: Onde está o diretório Scripts na árvore de diretórios da sua aplicação? Na raiz?
Comment: sim, essa seria o meu caminho. Projetos/Teste_Javascript/ScriptsAjax<libAjax.js
Comment: Essa linha está correta para chamar a função js? Resultado aqui

Meu arquivo js não está carregando


Can't view Application property page - E_FAIL / Method Not Implemented

Question: In the Solution Explorer in Visual Studio 2012, I right click on my wp8 project and go Properties, and the Application tab shows:
An error occurred trying to load the page.
Error HRESULT E_FAIL has been returned from a call to a COM component.

or
An error occurred trying to load the page.
The method or operation is not implemented.

Would anyone know how to go about debugging this?
I cannot repro this problem with a fresh project, but haven't been able to nail out where it is failing in my project...
Maybe related to AssemblyInfo.cs? Source file 'Properties\AssemblyInfo.cs' could not be found
BTW it builds and deploys to my device just fine...

Thanks
Comment: Perhaps you ought to show us a screenshot of the file structure (expanded) for your project then. If you deleted the AssemblyInfo or any of the manifest files, that's sure to cock things up.
Comment: BTW it compiles and deploys fine to the device...
Comment: For some reason now the error is different... anyways, uploaded a png. Thanks!
Answer: So after an exhaustive round of brute force elimination, I was able to narrow this down to my use of .java files. Yes it is weird, but it has worked. I have been including .java files in my project and setting their properties to Compile as c#. There were merge reasons for doing so, and I had of course modified the java code slightly to compile, but somehow Visual Studio's property pages spaz out when a .java file is included this way, even though the project compiles just fine. So I wrote a little tool to copy all the .java files to .java.cs and include them that way and everything is fine now!
Answer: I found this issue in all of my projects and reasoned it might have had to do with a recent Windows update.  I updated VS 2017 to 15.9.15 and that resolved it for me.


JAVA - Somar dígitos de um número X em um intervalo de A e B

Question: Preciso calcular a soma dos dígitos de um X número em um intervalo de A e B;
Por exemplo, se X = 3, A = 10 e B = 30, então a reposta é 3, pois existem três números
no intervalo de [10, 30] cuja soma dos dígitos é igual a três: 12, 21 e 30.
Restrições: (1 ≤ X ≤ 36), (1 ≤ A ≤ 10 000), (1 ≤ B ≤ 10 000)e (A ≤ B)
Seu programa deve produzir uma única linha, contendo um único inteiro, quantos
números no intervalo dado têm a soma de dígitos indicada.
O código que elaborei foi este ↓
<code>    Scanner in = new Scanner(System.in);

    int x, a, b;

    System.out.format("Informe o valor de 'X' de 1 até 36: ");
    x = in.nextInt();

    if (x >= 1 && x <= 36) {
        System.out.format("Informe o valor de 'A' de 1 até 10000: ");
        a = in.nextInt();

        if (a >= 1 && a <= 10000) {
            System.out.format("Informe o valor de 'B' de 1 até 10000: ");
            b = in.nextInt();

            if (b >= 1 && b <= 10000) {

                int soma = 0;
                for (int i = a; i <= b; i++){

                    soma = i % 10; // imprime o resto de 10, 11, 12...

                }
            }
        }
    }
}
}
</code>
Encontrei o resto dos números no intervalo de 10 a 30, porém eu não consigo achar o quociente desses números para somar eles.
<code>    soma = i % 10;
    i = soma / 10;
</code>
E não obtive o quociente dos números para depois somar e verificar qual é igual a X.
Não consigo entender aonde estou errando para achar uma solução.
Answer: Não entendi bem o que tu fez com relação a soma, mas pelo o que eu entendi, tu poderia fazer desse modo:
<code>import java.util.LinkedList;
import java.util.Scanner;

public class teste {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int x;
    int intervalStart; // numero que indica começo do intervalo
    int intervalEnd; // numero que indica final do intervalo

    System.out.print("Informe o valor de 'X' de 1 até 36: ");
    x = in.nextInt();

    if (x >= 1 && x <= 36) {
        System.out.print("Informe o 1º de valor de intervalo de 1 até 10000: ");
        intervalStart = in.nextInt();

        if (intervalStart >= 1 && intervalStart <= 10000) {
            System.out.print("Informe o 2º valor de intervalo de 1 até 10000: ");
            intervalEnd = in.nextInt();

            if (intervalEnd >= 1 && intervalEnd <= 10000) {

                for (int currentNumber = intervalStart; currentNumber <= intervalEnd; currentNumber++) { // percorre toda a lista do intervalo
                    int aux = currentNumber; // criando um auxiliar
                    int digitSum = 0; // soma dos dígitos
                    while(aux > 0){
                        digitSum += aux % 10; // somando digitos
                        aux /= 10; // pegando o proximo digito
                    }
                    if(digitSum == x) // verifica se a soma é igual ao que foi escolhido no começo
                        selectedNumberAmount++; // se for, ela soma na quantidade de números filtrados
                }
            }
        }
    }
    System.out.println(selectedNumberAmount); // mostra a quantidade
    in.close(); // fechando o scanner
}
</code>
}


Is correct to repeat an answer if the question has already one?

Question: I noticed some questions being answered more than oncewith the same info (in my opinion) just for the delicious points.
It means: Someone ask a question and user 1 answer with a correct answer. User 2 see the question already answered and adds the same answer, with the same approach to resolve it, with almost the same solution plus some minor changes.
Is this a good practice in SE? Should this be accepted or is there any way to proceed in this case? In my opinion it does not add anything to the community but misunderstandings to the original question since there are a lot of similar (really similar) answers.
Answer: I guess the approach on these questions depends on when the answers were written.
It happens very often that 2 people start answering the same question at almost the same time, but they post the answer a few seconds or minutes apart.
In this case, if the second poster does not delete on his own the answer there is nothing you can do. Both answers are equally valid.
But if you see a duplicate answer days or months after the original answer, my opinion is that you should flag it.
Answer: I'm on my phone so I will make this short: yes, duplicate answers with minor changes are highly encouraged, in fact in the beta period we are graded at having an answer to question ratio of at least 2:1!
In the case where an answer is never accepted a lone answer may seem dubious; but multiple approaches or duplication of the answer will instill confidence in future visitors.
Comment: Interesting point of view. Multiple answers with the same code/approach in it seems like unnecessary for me. If someone has something else to say which does not differ much from the original answer it might be added as a comment to the original answer or if it is minor, as an edit too.
Answer: Multiple answers are OK as for me. See for example:
How to consolidate/summarise/combine color and other attributes in the layered navigation
I've offered the solution based on our layered navigation modifications experience. The user haven't accepted it.
Then again the same answer. No reaction.
The same answer for the third time - finally accepted!
Answer: I had this occasion many times. Fortunately or unfortunately, you referenced a question in which I have answered just after you. Yes indeed, my answer is just a continuation of yours and shows the same content. But be honest, I can say that, I didn't copy you. In fact, I didn't see your answer before I am posting mine.
When I answer a question, I will always try to give my answer in detail. I always think about future visitors and try to give an answer in a way they can benefit too. In the above case, you can see that, I have provided almost everything that needed for a helper class. So any one who go through that quesiton atleast understand what are the files that are dealing with a helper class.
This way, I think my answer gave an addition to your answer. It helped to complete your answer. Do you think I need to delete my answer ?
Most of the time I have colllision with @Marius. He is superfast. No one can beat him while answer. When I post my answer, he may get a tick for his answer. :). After I see his answer, if I feel that my answer is not required any more, then I deleted such answers. If my answer added a single point more to his answer, then normally I will request him to mention my answer on his answer.
So what I feel right in this context is,
1) Delete second post if it has the same exact content of the first answer
2) If the other answer possess atleast one additional point that is not in other answers, then it should not be deleted.
3) If you believe your answer is an add-on to the question and answer for that question get already accepted, then it would be good to request to the answered guy to mention your answer in his post or add that point to his answer itself.


Recording multitrack in FL studio with multiple USB-connected microphones

Question: I have two mics which I connect to my PC via XLR to USB cables, but when I record in FL studio it only record the default mic. I have read that for multi track recording an Audio interface is needed, is this true?
Answer: Yes .An Audio interface is preferred due to possible compression limitation on your PC Sound card .
Roland created many such as CD-2U-Digital-Recording-Interface.Capturing audio is a sepreate matter to recording Midi
Comment: FL studios being a software can not overcome compression limitations which may exist in a PC sound card .In suggest contacting the PC maker or the maker of the sound card.
Answer: A driver such as ASIO4ALL will let you connect several audio devices to be used at the same time.  Depending on what drivers your USB microphones use, this may work.  (I used to use this software to connect my Realtek sound card and Virtual Audio Cable into FL studio at the same time.)
There is a menu that looks like this

Image Source
which is accessible from inside FL studio, once ASIO4ALL is installed.  You can select all devices which you want to use.  If two USB microphones show up here, then great!  You can use both of them.
This is not really recommended, since you will likely run into sync issues when the two microphones are separate audio devices.  You will not be able to make proper true stereo recordings, but you may be able to record two different sources (e.g. a singer and a guitarist) at the same time, as long as there is not much bleed between the two mics.


Rolar a pagina verticalmente esperar e rolar de novo

Question: Tenho uma pagina em PHP que lê um XML com uma RSS, eu gostaria de saber se há como eu rolar a pagina até aparecer a segunda RSS e depois continuar até a próxima RSS assim sucessivamente.
Veja a página: http://rss.dbcam.com.br/principais
Ao rolar vê-se outras RSS a baixo.
Outra opção seria uma forma de eu carregar a primeira RSS, depois apagar ela e aparecer a segunda e assim sucessivamente.
Comment: Olá David, esse HTML do link que mostras-te está cheio de erros. Tens controlo sobre esse HTML? és tu que o crias ou é de um site externo?
Comment: sim, sou eu que tenho controle. Ele está com algumas falhas pois eu apenas estou utilizando este para exemplo.
Answer: Tens problemas no HTML que tens de corrigir.
lembra-te que IDs têm de ser unicas. Assim em vêz de

        <img id="foto"

deves usar classes e mudar para:

        <img class="foto"

No teu HTML há outro problema que é algumas divs não estarem fechadas. As divs class="corpo" estão a ficar dentro de si próprias.
Em relação à tua pergunta do scroll podes fazer assim, usando classes:
var $noticias = $('.corpo');
var qtd = $noticias.length;
var i = 0;
setInterval(function () {
if ((i++) == qtd) i = 0;
    $('html, body').animate({
        scrollTop: $noticias.eq(i).position().top
    }, 800); // <--- velocidade do scroll

}, 2000);  // <--- tempo de espera entre cada imagem

jsFiddle: http://jsfiddle.net/0ufjvuyx/


Does using multiline in logstash filter print out the data?

Question: I am trying to use multiline to combine a number of of lines in a logfile with the same starting symbol. In my case the starting symbol is #S#. it would look something like this:
#S# dsifj sdfojosf sfjosdfoisdjf
#S# dsfj sdojifoig dfpkgokdfgk 89s7fsjlk sdf
#S# lsdffm dg;;dfgl djfg 930`e`fsd
...
...
...

Note: The random character is just use to imitate the content of the actual log.
The following is what is wrote for the multiline startment:
multiline {
   type => "table_init"
   pattern => "#S#"
   negate => true
   what => "next"
}

I am assuming what I wrote does combine them as one line, but I am wondering if this prints out the line or do I need to use gork to parse the whole entire line before it prints. Any thoughts and inputs will be helpful. Thank you.
Answer: If you are trying to match up all lines that DO match "#S#", then you should have negate set to false. You use negate when you want to get all lines that DO NOT match a certain pattern.
As for your actual question, multiline takes all the relevant lines and puts them into the "message" field, including newline characters (\n, and I assume \r if you are running Windows as well though I have never checked). You can then grok this entire message to get the data you want.
So if you set up your output like so:
output { stdout { codec => rubydebug } }

You should find that the outputted message will read something like:
"message" = "#S# dsifj sdfojosf sfjosdfoisdjf \n#S# dsfj sdojifoig dfpkgokdfgk 89s7fsjlk sdf\n#S# lsdffm dg;;dfgl djfg 930`e`fsd

if you set up your multiline filter correctly.
Hope this helps!


In linear regression, are the noise terms independent of the coefficient estimators?

Question: In the Wikipedia article on the bias-variance tradeoff, the independence of the estimator $\hat f(x)$ and the noise term $\epsilon$ is used in a crucial way in the proof of the decomposition of the mean square error. No justification for this independence is given, and I can't seem to figure it out. For example, if $f(t)=\beta_0t + \beta_1$, $Y_i=f(x_i) + \epsilon_i$ ($i=1,\ldots,n$), and $\hat f(x)=\hat\beta_0 + \hat\beta_1 x$ as in simple linear regression, are the $\epsilon_i$ independent of $\hat\beta_0$ and $\hat\beta_1$?
Comment: Did you mean the noise terms or the residual terms?
Answer: $\hat f(x)$ and $\epsilon$ should not be independent --- only asymptotically so as the cardinality of the data set approaches infinity. Reference [7] in that Wikipedia article is a correct derivation. It, specifically Equation (8), uses the premise that $\mathbf E[\epsilon|x]=0$. The derivation in the article cited from reference [6] is wrong.
Comment: I've poured over https://web.archive.org/web/20140821063842/http://ttic.uchicago.edu/~gregory/courses/wis-ml2012/lectures/biasVarDecom.pdf and https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff#Derivation
and I think that a non-asymptotic independence claim holds if you set things up right. I'm posting an explanation in an answer below. Does it make sense?
Answer: I've poured over the argument in the link Hans kindly provided and I think I (finally) understand what's going on.  I'd like to give a version of the argument in the simpler case where the $x$-values fixed quantities so that I can avoid conditional expectations. [Corrections/confirmation/feedback greatly appreciated!]
tl;dr The claim in the Wikipedia article that $\epsilon$ and $\hat f$ are independent is true when $\hat f$ is computed using training data, $(x_1,y_1),\ldots,(x_n,y_n)$, and $\epsilon=\epsilon_0$ is the noise term associated to an independent test measurement, $(x_0,y_0)$.
More formally, let $f(\theta, x)$ be a real-valued function, where $\theta\in\mathbb R^n$ and $x\in\mathbb R$.
Fix quantities $x_1,\ldots,x_n\in\mathbb R$. Let $\epsilon_1,\ldots,\epsilon_n$ be pairwise independent random variables with $E[\epsilon_i]=0$ and consider random variables
$$Y_i = f(\theta, x_i) + \epsilon_i.$$
Let $\hat\theta(Y_1,\ldots,Y_n)$ be an estimator of $\theta$.
For $x\in\mathbb R$, view $f(\hat\theta(Y_1,\ldots,Y_n), x)$ as an estimator of $f(\theta, x)$.
Let $x_0\in\mathbb R$, let $\epsilon_0$ be a random variable, independent of $\epsilon_1,\ldots,\epsilon_n$, with $E[\epsilon_0]=0$, and suppose
$$
Y_0 = f(\theta,x_0) + \epsilon_0.
$$
We want to determine the expected error in $f(\hat\theta(Y_1,\ldots,Y_n), x_0)$ as an estimate of the "new measurement" $Y_0$:

Theorem
$$E\left[\big(Y_0 - f(\hat\theta(Y_1,\ldots,Y_n), x_0)\big)^2\right] = E[\epsilon_0^2] + E\left[\big(f(\theta,x_0)-f(\hat\theta, x_0)\big)^2\right]$$
Proof
Write $\hat\theta$ for $\hat\theta(Y_1,\ldots,Y_n)$.
Doing some algebra and using the identity $Y_0=f(\theta,x_0)+\epsilon_0$, we get
$$
\begin{aligned}
E\left[\big(Y_0 - f(\hat\theta, x_0)\big)^2\right]
&= E\left[\big(Y_0 - f(\theta, x_0) + f(\theta, x_0) - f(\hat\theta, x_0)\big)^2\right]\\
&= E\left[\big(Y_0 - f(\theta, x_0)\big)^2\right] + E\left[\big(f(\theta, x_0) - f(\hat\theta, x_0)\big)^2\right]\\
&\qquad+ 2E\left[\big(Y_0 - f(\theta, x_0)\big)\big(f(\theta, x_0) - f(\hat\theta, x_0)\big)\right]\\
&= E\left[\epsilon_i^2\right] + E\left[\big(f(\theta, x_0) - f(\hat\theta, x_0)\big)^2\right]\\
&\qquad+ 2E\left[\epsilon_0\big(f(\theta, x_0) - f(\hat\theta, x_0)\big)\right].
\end{aligned}
$$
Since the random variable
$f(\theta, x_0) - f(\hat\theta, x_0)$
depends only on $\epsilon_1,\ldots,\epsilon_n$ (through $\hat\theta(Y_1,\ldots,Y_n)$) and $\epsilon_0$ is independent of $\epsilon_1,\ldots,\epsilon_n$,
it follows that $\epsilon_0$ and
$f(\theta, x_0) - f(\hat\theta, x_0)$ are independent.
Therefore,
$$
E\left[\epsilon_0\big(f(\theta, x_0) - f(\hat\theta, x_0)\big)\right]=
E[\epsilon_0]E\left[f(\theta, x_0) - f(\hat\theta, x_0)\right] = 0,
$$
since $E[\epsilon_0]=0$, by hypothesis.
The result follows.

The term
$$
\mathop{\text{MSE}}\big(f(\hat\theta, x_0), f(\theta,x_0)\big)
=E\left[\big(f(\theta,x_0)-f(\hat\theta, x_0)\big)^2\right]
$$
decomposes, further, as
$$
\left(E\big[f(\hat\theta, x_0)\big] - f(\theta, x_0)\right)^2 + \mathop{\text{Var}}\, f(\hat\theta, x_0),
$$
giving the bias-variance decomposition. (See below.)
Note, also, that we haven't assumed that the $\epsilon_i$ have equal variances.

Added in response to Hans's comment:
Theorem
$$
E\left[\big(f(\theta,x_0)-f(\hat\theta, x_0)\big)^2\right]
=
\left(E\big[f(\hat\theta, x_0)\big] - f(\theta, x_0)\right)^2 + \mathop{\text{Var}}\, f(\hat\theta, x_0),
$$
Proof
The idea is to let $E[f(\hat{\theta},x_0)]$ mediate between $f(\hat{\theta},x_0)$ itself and $f(\theta,x_0)$
$$
\begin{aligned}
E\left[\big(f(\theta,x_0)-f(\hat\theta, x_0)\big)^2\right]
&= E\left[\big(\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}-\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}\big)^2\right]\\
&= E\left[\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}^2\right]\\
&\qquad + E\left[\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}^2\right]\\
&\qquad - 2E\left[\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}\right]\\
&=: A + B - 2C
\end{aligned}
$$
Since $\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}^2$ is just a number, it's its own expected value:
$$
A = E\left[\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}^2\right]
=\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}^2 =
\mathop{\text{Bias}}(f(\hat{\theta},x_0), f(\theta,x_0))^2.
$$
By definition,
$$
B = E\left[\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}^2\right]
= \mathop{\text{Var}}f(\hat{\theta},x_0).
$$
Since $f(\theta,x_0) - E[f(\hat{\theta},x_0)]$ is just a number and $f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]$ has expected value $0$,
$$
\begin{aligned}
C &= E\left[\left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}\right]\\
&= \left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}E\left[\left\{f(\hat\theta, x_0) - E[f(\hat{\theta},x_0)]\right\}\right]\\
&= \left\{f(\theta,x_0) - E[f(\hat{\theta},x_0)]\right\}\cdot 0\\
&= 0.
\end{aligned}
$$
Comment: I like your setup. However, can you carry out the decomposition of the last two terms that you skipped over?
Comment: @Hans I've edited my post, adding the details of the decomposition at the bottom.
Answer: When doing ordinary linear regression then $\hat f(x)$ is the vector projection of $f(x)$ onto the column space of the model matrix.
If $f(x)$ is distributed as a multivariate normal distribution with equal variance and no correlation then the components $\hat f(x)$ and the residual $\epsilon$ in this projection will be independent.
But this is certainly not always the case when the variance is not equal and/or when there is correlation and/or when the error distribution is not Gaussian.
Example
To make the plotting easier we use the simplest of all models (estimating the mean) and only two data points, but you can extend this to more dimensions (in which case it becomes a projection onto a hyperplane instead of a projection onto a line).
We test use the model below for fitting.
$$f(x_i) = \beta_0+\epsilon_i$$
We generate a hundred data sets with the 'true' model: $\beta_0 = 5$, $\epsilon_1 \sim N(0,0.25)$, and $\epsilon_2 \sim N(0,4)$. Below you see this plotted.
In the first graph you see the pairs of points $\lbrace x_1,x_2 \rbrace$ projected onto the line $x_1=x_2$ (depicted by the gray dotted lines). The projected point correponds to the sample mean $\bar{x}$.
In the second graph you see the plot of the estimator model $\hat{f}(x) = \lbrace \bar{x}, \bar{x} \rbrace$ versus the residual of the first coordinate $\epsilon_1 = x_1-\bar{x}$.
It is obvious that the two are not independent.

The image below is for independent normal distributed variables with equal variance. $\epsilon_i \sim N(0,2)$

Now the residual term and fitted term are independent.
Answer: No, they're not independent: In multiple linear regression the OLS coefficient estimator can be written as:
$$\begin{equation} \begin{aligned}
\hat{\boldsymbol{\beta}}
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} (\mathbf{x}^\text{T} \mathbf{y}) \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} (\mathbf{x} \boldsymbol{\beta} + \boldsymbol{\varepsilon}) \\[6pt]
&= \boldsymbol{\beta} + (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \boldsymbol{\varepsilon}. \\[6pt]
\end{aligned} \end{equation}$$
In regression problems we analyse the behaviour of the quantities conditional on the explanatory variables (i.e., conditional on the design matrix $\mathbf{x}$).  The covariance between the coefficient estimators and errors is:
$$\begin{equation} \begin{aligned}
\mathbb{Cov} ( \hat{\boldsymbol{\beta}}, \boldsymbol{\varepsilon} |\mathbf{x})
&= \mathbb{Cov} \Big( (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \boldsymbol{\varepsilon}, \boldsymbol{\varepsilon} \Big| \mathbf{x} \Big) \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbb{Cov} ( \boldsymbol{\varepsilon}, \boldsymbol{\varepsilon} | \mathbf{x} ) \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbb{V} ( \boldsymbol{\varepsilon} | \mathbf{x} ) \\[6pt]
&= \sigma^2 (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \boldsymbol{I} \\[6pt]
&= \sigma^2 (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T}. \\[6pt]
\end{aligned} \end{equation}$$
In general, this covariance matrix is a non-zero matrix, and so the coefficient estimators are correlated with the error terms (conditional on the design matrix).

Special case (simple linear regression): In the special case where we have a simple linear regression with an intercept term and a single explanatory variable we have design matrix:
$$\mathbf{x}
= \begin{bmatrix}
1 & x_1 \\[6pt]
1 & x_2 \\[6pt]
\vdots & \vdots \\[6pt]
1 & x_n \\[6pt]
\end{bmatrix},$$
which gives:
$$\begin{equation} \begin{aligned}
(\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T}
&= \begin{bmatrix}
n & & \sum x_i \\[6pt]
\sum x_i & & \sum x_i^2 \\[6pt]
\end{bmatrix}^{-1}
\begin{bmatrix}
1 & 1 & \cdots & 1 \\[6pt]
x_1 & x_2 & \cdots & x_n \\[6pt]
\end{bmatrix} \\[6pt]
&= \frac{1}{n \sum x_i^2 - (\sum x_i)^2} \begin{bmatrix}
\sum x_i^2 & & -\sum x_i \\[6pt]
-\sum x_i & & n \\[6pt]
\end{bmatrix}
\begin{bmatrix}
1 & 1 & \cdots & 1 \\[6pt]
x_1 & x_2 & \cdots & x_n \\[6pt]
\end{bmatrix} \\[6pt]
&= \frac{1}{n \sum x_i^2 - (\sum x_i)^2} \begin{bmatrix}
\sum x_i(x_i-x_1) & \cdots & \sum x_i(x_i-x_n) \\[6pt]
-\sum (x_i-x_1) & \cdots & -\sum (x_i-x_n) \\[6pt]
\end{bmatrix}. \\[6pt]
\end{aligned} \end{equation}$$
Hence, we have:
$$\begin{equation} \begin{aligned}
\mathbb{Cov}(\hat{\beta}_0, \varepsilon_k)
&= \sigma^2 \cdot \frac{\sum x_i(x_i-x_k)}{n \sum x_i^2 - (\sum x_i)^2}, \\[10pt]
\mathbb{Cov}(\hat{\beta}_1, \varepsilon_k)
&= - \sigma^2 \cdot \frac{\sum (x_i-x_k)}{n \sum x_i^2 - (\sum x_i)^2}. \\[10pt]
\end{aligned} \end{equation}$$
We can also obtain the correlation, which is perhaps a bit more useful.  To do this we note that:
$$\mathbb{V}(\varepsilon_k) = \sigma^2 \quad \quad \quad
\mathbb{V}(\hat{\beta}_0) = \frac{\sigma^2 \sum x_i^2}{n \sum x_i^2 - (\sum x_i)^2} \quad \quad \quad
\mathbb{V}(\hat{\beta}_1) = \frac{\sigma^2 n}{n \sum x_i^2 - (\sum x_i)^2}.$$
Hence, we have correlation:
$$\begin{equation} \begin{aligned}
\mathbb{Corr}(\hat{\beta}_0, \varepsilon_k)
&= \frac{\sum x_i(x_i-x_k)}{\sqrt{(\sum x_i^2)(n \sum x_i^2 - (\sum x_i)^2)}}, \\[10pt]
\mathbb{Corr}(\hat{\beta}_1, \varepsilon_k)
&= - \frac{\sum (x_i-x_k)}{\sqrt{n(n \sum x_i^2 - (\sum x_i)^2)}}. \\[10pt]
\end{aligned} \end{equation}$$


.NET 7.0 - OData 8.0 versioning not show in swagger

Question: I added OData to my project and tested some scenarios. I got stuck on adding versioning to OData, but I eventually added it without any major issues. Now, I can call the endpoint with the version without any problems, but it's not showing up in Swagger.
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntityType<Order>();
modelBuilder.EntitySet<Customer>("Customers");

builder.Services.AddControllers().AddOData(
options => options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null).AddRouteComponents(
    "api/v{version:apiVersion}/",
    modelBuilder.GetEdmModel()));

builder.Services.AddApiVersioning(opt =>
{
    opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0);
    opt.AssumeDefaultVersionWhenUnspecified = true;
    opt.ReportApiVersions = true;
    opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
                                                    new HeaderApiVersionReader("x-api-version"),
                                                    new MediaTypeApiVersionReader("x-api-version"));
});

builder.Services.AddVersionedApiExplorer(setup =>
{
    setup.GroupNameFormat = "'v'VVV";
    setup.SubstituteApiVersionInUrl = true;
});

Controller
namespace Aimtec.DataIntegrator.WebApi.Controllers.v1
{
    [ApiVersion("1.0")]
    public class CustomersController : ODataController
    {
        private static Random random = new Random();
        private static List<Customer> customers = new List<Customer>(
            Enumerable.Range(1, 3).Select(idx => new Customer
            {
                Id = idx,
                Name = $"Customer {idx}",
                Orders = new List<Order>(
                    Enumerable.Range(1, 2).Select(dx => new Order
                    {
                        Id = (idx - 1) * 2 + dx,
                        Amount = random.Next(1, 9) * 10
                    }))
            }));

        [EnableQuery]
        public ActionResult Get()
        {
            return Ok(customers);
        }
    }
}

OData routing debug

Swagger

Also, do you happen to have a good guide on how to add versioning for OData in general?
Answer: This is Swagger's problem with controller matching. The easiest way is to add the [ApiController] attribute to the controller:
[ApiVersion("1.0")]
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ODataController
{
}

It is worth noting that attribute routing is required after adding this attribute, which can be added to the controller or action.
About adding versioning for OData, you can check Sam Xu's article: API versioning extension with ASP.NET Core OData 8.
Comment: Aaa perfect im blind. Thank you very much


Help understand beta reduction example

Question: I am currently reading a text book on distributed computing systems that includes a short introduction to $\lambda$-calculus. There is an example of evaluating the sequence $(((if \space \space  true) \space \space 4) \space \space 5)$ which is written below.

$\space\space(((\lambda b.\lambda t.\lambda e.((b \space t) \space e) \space \lambda x.\lambda y.x) \space 4) \space 5) $
$\space\space((\lambda t.\lambda e ((\lambda x.\lambda y.x \space \space t) \space e) \space 4) \space 5) $
$\space\space(\lambda e ((\lambda x.\lambda y.x \space \space 4) \space \space e) \space \space 5) $
$\space\space((\lambda x.\lambda y.x \space \space 4) \space \space 5) $
$\space\space(\lambda y.4 \space \space 5) $
$\space\space 4$

The author has used $\beta$-reduction on each line and I can follow up until the second to last reduction. Could someone explain how we get from line 4 to line 6?
Comment: This was down-voted within 30 seconds of posting - if I can improve the question please let me know!
Comment: In the first line there is a typo because $(((λb.λt.λe((b t) e) λx.λt.λx) 4) 5)$ is not a $\lambda$-term. In particular, what does $\lambda x ) 4$ mean?
Comment: @Taroccoesbrocco - You're quite right, I made two typos. It should now be correct.
Answer: When going from line 4 to line 5, we substitute $x=4$ into $\lambda y. x$, because the inner argument is bound to the $\lambda x$.  The 5 is then passed to the result and bound to the $\lambda y$, so that we substitute $y=5$ into $\lambda y. 4$.  Since $y$ does not appear free in $4$, this does not alter the expression, so we end up with $4$.
Answer: In line 4. there is a $\beta$-redex $(\lambda x \lambda y. x \ 4)$, where $\lambda x \lambda y. x$ is applied to $4$.
This means that $(\lambda x \lambda y. x \ 4)$ rewrites$-$via a $\beta$-step$-$to $(\lambda y. x)\{4 / x\} $ (which is $(\lambda y. x)$ where the free occurrence of $x$ is replaced by $4$), i.e. $ \lambda y. 4$.
Since the $\beta$-redex $(\lambda x \lambda y. x \ 4)$ is inside a context (i.e. it is a sub-term of a bigger term), then from line 4., if we put the sub-term $(\lambda x \lambda y. x \ 4)$ into its context, we have:
\begin{align}
 ((\lambda x \lambda y. x \ 4) \ 5) &\to_\beta (\lambda y. x \ 5)\{4 / x\} = (\lambda y. 4 \ 5)
\\ &\to_\beta 4\  \{5/y\} = 5
\end{align}
where, again, $(\lambda y. 4 \ 5) $ is a $\beta$-redex and then rewrites$-$via a $\beta$-step$-$to $4\  \{5/y\}$ (which is $4$ where the free occurrences of $y$ are replaced by $5$), i.e. $4$ because there are not free occurrences of $y$ in $4$.

Help understand beta reduction example


How can I dynamically alter the files in the /Content directory in ASP.NET MVC?

Question: When I serve a javascript file to a user from the /Content Directory I want to replace a string token in that file with a value, so that when the user requests a given file, it has all the customizations they expect.
I think that means I need to somehow proxy requests to the /Content directory, perform the dynamic insertion, and give the file to the user.

I'm interested in performing this insertion as a stream or as a in -memory file.  I'd prefer to use a stream just because it's probably more efficient memory wise.

How do I get ASP.NET to proxy this directory?
I've attempted

Using routes to point to a controller
WCF to proxy a URL

But they all seem "ugly" to me and I'd like to make this insertion/replacement as transparent as possible int he project.
Is there a cleaner way?
Answer: The easiest way is to create an action on a controller.
public class JavascriptController : Controller
{
    public ActionResult Load(string file)
    {
        var content = System.IO.File.ReadAllText(Server.MapPath(string.Format("~/Content/{0}", file)));

        //make replacements io content here

        return this.Content(content, "application/javascript");
    }
}

You can then access the javascript like this (assuming you have the default routing):
http://localhost:53287/Javascript/Load?file=file.js

where file.js is the name of the file you are requesting.
Don't worry about the url, you can customise this by creating another route if necessary
Comment: Thank you.  What if I also want to proxy requests to a vendors (Telerik) dynamic javascript files?  Doesn't that operate at a lower level?
Comment: You can change the line which reads all the text from a file to request the file contents over http.. that is quite a simple solution, but more overhead (each request, would actually be processed twice)
Answer: Here is alternative answer to the answer I posted above, taking into account your comment regarding dynamic javascript.
Firstly, I don't know of a way to do this specifically using either mvc or wcf.. the only way I know how to do this is with a lower-level HttpModule
Take a look at the following code:
public class JavascriptReplacementModule : IHttpModule
{
    public class ResponseFilter : MemoryStream
    {
        private Stream outputStream = null;

        public ResponseFilter(Stream output)
        {
            outputStream = output;
        }

        public override void Flush()
        {
            base.Flush();
            this.Seek(0, SeekOrigin.Begin);
            var sr = new StreamReader(this);

            string contentInBuffer = sr.ReadToEnd();

            //Do replacements here

            outputStream.Write(UTF8Encoding.UTF8.GetBytes(contentInBuffer), 0, UTF8Encoding.UTF8.GetByteCount(contentInBuffer));

            outputStream.Flush();
        }

        protected override void Dispose(bool disposing)
        {
            outputStream.Dispose();
            base.Dispose(disposing);
        }
    }

    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
    }

    void context_PostRequestHandlerExecute(object sender, EventArgs e)
    {

        var context = (HttpApplication)sender;
        if (context.Request.Url.AbsolutePath.StartsWith("/Content") && context.Request.Url.AbsolutePath.EndsWith(".js"))
        {
            HttpContext.Current.Response.Filter = new ResponseFilter(HttpContext.Current.Response.Filter);
        }
    }
}

And register the module like this (make sure you put the full type in the type attribute):
<system.webServer>
  <modules>
    <add name="JavascriptReplacementModule" type="JavascriptReplacementModule"/>
  </modules>
</system.webServer>

This allows you to modify the output stream before it gets to the client
Comment: Thanks!  In case you're wondering I'm using this for a security solution relating to CORS and AJAX POSTs:  http://security.stackexchange.com/q/17036/396   I'd be curious to hear your thoughts about it if you had something come to mind :)


Owl carousel (Canvas) autoplay working but speed not changing at all

Question: I have owl carousel working within a Canvas template environment but the javascript connected to it doesn't seem to be functioning properly. The documentation refers to 'autoplay', and altering this number to change the delay between transitions.
Altering the number has no effect whatsoever. Can anyone assist? This is driving me mad. I know there are later versions of owl carousel out there that have slightly different documentation. I know some may say try 'autoPlay' with uppercase, but that stops it from working completely.
Current code is:
<code>jQuery(document).ready(function($) {

                    var ocClients = $("#oc-clients");

                    ocClients.owlCarousel({
                        margin: 0,
                        // loop: true,
                        // nav: false,
                        autoplay: 1000,
                        // speed: 600,
                        // paginationspeed: 1000,
                        // dots: false,
                        autoplayHoverPause: true,
                        responsive:{
                            0:{ items:3 },
                            600:{ items:4 },
                            1000:{ items:5 },
                            1200:{ items:6 },
                            1400:{ items:6 }
                        }
                    });

                });
</code>
Please help!
Thanks
Comment: Docs of owl carousel 1 says autoPlay : integer would turn the delay to 5 seconds. If that's not working, please create a demo or provide some more code.
Comment: Yes, using autoPlay breaks it as I believe this version of owl carousel that Canvas provide, is an older version so only autoplay (in lowercase works). The site can be seen at blueprint.campaigncircle.co.uk and the logos are at the very base if this helps? It's the carousel at the very base of the index page.
Answer: Use this:
autoplay: true,
autoplayTimeout: 1000,
Comment: Please add more details to the answer.


Dynamic named parameters in Groovy?

Question: I found it really cool that in Groovy SQL it is possible to do this:
def resultList = Domain.executeQuery('select * from languages where name = :name', [name: 'Groovy'])

I am trying to get the HQL "in" keyword to work with a dynamic list used as the argument, not a fixed list.
I also know that you can use the "?" operator for your SQL parameters instead of using named parameters. However according to this question:
Doing an "IN" query with Hibernate
The "in" keyword only supports named and positional parameters, not the "?" parameter. The problem is, when I try to do something like this:
def paramMap = [:]
paramMap.put("name", "groovy")

   def resultList = Domain.executeQuery('select * from languages where name = :name', paramMap)

I get an error saying that I have not specified the parameter name. So it is acting as if I have not actually specified the parameter "name". I have read the Groovy documentation on named parameters here:
http://groovy.codehaus.org/api/groovy/sql/Sql.html
But all of the examples using named parameters use a predefined parameter list. I have searched and have not found an example of using a dynamic parameter list map. How can I pass a dynamic map of parameters into Groovy named SQL query? If that is not possible, how can I use the "in" keyword with a dynamic list?
To be clear, I am constructing a dynamic SQL query and I would like to be able to add parameters to a map or list as I go along. I was previously using the "?" operator until I had to use the "in" clause, which does not work with "?".
Comment: this syntax should work as you have put it down.  are you sure, you have not e.g. changed the name into e.g. ``:names`` and forgot about the key in the map?  and on a side note: you should rely on the (GORM|http://grails.org/doc/latest/guide/GORM.html) docs instead of groovy sql ones.
Answer: Why not try find all with closures?
def paramMap = [:]
paramMap.put("name", "groovy")
def resultList = Domain.findAll {
    paramMap.containsValue(name)
}

Here's the docs, hopefully it helps! http://grails.org/doc/latest/ref/Domain%20Classes/findAll.html

Dynamic named parameters in Groovy?


define, that the user came from specific page? (in PHP)

Question: Is there the way in PHP to define, that the user came from specific page? without "post" requests.
I have a "add post" page. when user submit a post, on the next page he can submit some more information. But when user click "back" in browser he returns to blank "add post" form, and what I need is that the user can modify previously submitted info, but only if he presses back from this second page.
$_SERVER['HTTP_REFERER'] - doesn't seem to work.
Maybe I can set some data in $_SESSION on second page and celar it on every other page except the first.. but its seems like not very smart.
Comment: @Grom S, why don't you make an edit button that returns to the previous page but and has all the form fields filled out? You could check for a specific session value when entering that page to determine if it's an edit or a new submission.
Comment: why should a session not be very smart? Your scenarion is what it's implemented for..
Comment: @Nick yes, i can do it. but what if user prefer "back" button in browser. or maybe the design is not very user friendly. after all i can't be shure that user do not click back button..
Comment: @Grom S, if the design isn't very user friendly I think you need to make it user friendly rather. If your edit button stands out enough, the user may try to use that first.
Comment: @freddy K because i need to clear it in every page. as i understand. what if somewhan creates new pages later?
Comment: @Nick what if i'm not designer) and i don't get money for it)
Comment: @Grom S, tell the designer you're not a designer and you can still tell his design sucks? Seriously though, you could try using an iframe in the final page so the back button won't work, or you could just deal with the user going backwards.
Answer: PHP $_SESSION is a great, easy fix for storing temporary data (especially if you can't use $_POST).  You only need to clear the SESSION value once, not on every page.
I'm not 100% clear on what you're asking, but try looking at some other values in $_SERVER; they may have what you need.
Comment: I don't remember another solution. Still, if you think that the same user can open several tabs in different pages of your site, you'll understand that the mechanism is not possible to be 100% accurate. Instead of using 2 page, why not only 1 page but with hidden 'divs' for each step?
Comment: how can i clear the $_SESSION once? what if user comes from another page, this value still be there. where should i clear it?
Comment: The SESSION is the same for all pages.  Clear it immediately after it's used.

As for multiple tabs, I think hidden divs would still suffer the same problem.  More specific code is needed for a more exact answer. =D
Comment: @AlfaTeK yes. 'hidden divs' way is better. but what if such structure is already done. and it requires a lot of work to combine it to one page..
Comment: for example after i submit first page. on second i set my session. then go to third page (still don't use session yet), and then again to first. and i fill my post form with data, beacause session are steel set. and i need to do it only when i go from second page to first.
Comment: How do you know when he goes back to the first page that he wants to create a new post?  Wherever you determine that, also clear the SESSION.


Hatcher, p.35, $\mathbb{R^{n}} - \{x\}$ is homeomorphic to $S^{n-1} \times \mathbb{R}$

Question: Could some help me understand how $\mathbb{R^{n}} - \{x\}$ is homeomorphic to $S^{n-1} \times \mathbb{R}$.
Also, if the one point set is replaced by any finite set, how does the argument work.
This is in Hatcher's book, example 1.15, p.35, where he states this as a fact. I could not find an explanation either before or in the example.
Thank you.
Comment: Just a guess. Have you tried to use stereographic projection?
Comment: I know that $S^{n-1} - \{x\}$ is homeomorphic (indeed diffeomorphic) to $R^{n-1}$. My ultimate aim is to show that the fundamental group is trivial for $n \ge 3$.
Comment: I note that in the 2019 printing this fact has moved to p36 as part of the proof of corollary 1.16.
Answer: First of all, $y \mapsto y - x$ is a homeomorphism from $\mathbb{R}^n\setminus\{x\}$ to $\mathbb{R}^n\setminus\{0\}$.
Note that $\mathbb{R}^n\setminus\{0\}$ is homeomorphic to $S^{n-1}\times(0, \infty)$ via the map $y \mapsto \left(\frac{y}{\|y\|}, \|y\|\right)$.
As $(0, \infty)$ is homeomorphic to $\mathbb{R}$ via the homeomorphism $z \mapsto \ln z$, we see that $\mathbb{R}^n\setminus\{x\}$ is homeomorphic to $S^{n-1}\times\mathbb{R}$ with an explicit homeomorphism given by $$f(y) = \left(\frac{y-x}{\|y - x\|}, \ln\|y - x\|\right).$$
Answer: It is helpful to break the argument down into two steps.  First, show that $\mathbb{R}$ is homeomorphic to $\mathbb{R}_{>0}$, the latter denoting the positive real numbers.
Then show that $\mathbb{R}^n \setminus \{x\}$ is homeomorphic to $S^{n-1} \times \mathbb{R}_{> 0}$.  For notational convenience, I will assume that $x = (0,0,\dots,0)$, as it is straightforward to modify the argument for any $x$ (or simply show that $\mathbb{R}^n \setminus \{x\}$ is homeomorphic to $\mathbb{R}^n \setminus \{(0,0,\dots,0)\}$).
The main idea is to think of $S^{n-1}$ as the unit sphere in $\mathbb{R}^n$ and the $\mathbb{R}_{>0}$ as a scaling factor.  So I claim that the map
$$ f : S^{n-1} \times \mathbb{R}_{> 0} \rightarrow \mathbb{R}^n \setminus \{(0,0,\dots,0)\} $$
given by $f(\vec{x}, c) = c \vec{x}$ is a continuous map, with a continuous inverse.  The details are left to you.
Answer: Even without reading his book, you should probably know how to do this intuitively. Assume without loss of generality, that $x=0$, and then $\mathbb R^n-\{0\}$ admits a foliation into concentric spheres. The radius is of course non-essential in differential geometry, you can always find a way to map homeomorphically the set to $S^{n-1}\times\mathbb R^+$. But again $\mathbb R^+$ is homeomorphic to $\mathbb R$, so you have your result.
For finite set, you should not expect to have the same result. But that part I returned to my teacher ;P, so I can't say more.
Comment: Upvote for giving the concentric sphere mental image as motivation.


Unable to record script in Jmeter 2.10 using HTTP Script Recorder

Question: I have tried all the information you have metioned. But it wont work. Still unable to record the script. I need to work only on IE alone.

Steps I have followed are

Lanched Jemeter;
Cretae Thread Group;
HTTP Request Defaults;
updated server name/IP and port no;
Added Recording Controller;
Under Workbench created HTTP(s) Test Script Recorder;
Updated URL patterns .*.html;
Added View Result Tree.
Clicked on Start and install Roor CA certificate;
Launched my application and moved on some modules;
Finally I have did not see any script that has been recorded

.
Answer: I had experienced similar problems.
Try resetting your browser.(I tried this with firefox).
Answer: Agreed with Johan B.
Set your proxy settings in the Browser you are using and everything should would as expected.
If not just let us know!
Oh and make sure you are also using the correct port number when you set your proxy settings in the browser...I've forgotten to this more times than I'd like to admit :)
Best of Luck
Phil
Answer: Seems you forgot to set your browser proxy settings to localhost


Rule for when content is published?

Question: I have the scheduler module installed, and i am using rules to notify users when new content is published.
The scheduler module is working perfect, i enter a future date and time for the content to be published. The content is published on the exact date and time.
Rules cannot action on this because there is no event coming with rules that allows me to perform some action when content is published, only when content is saved.
So my question is, how can i rules perform an action when content is published in a future date?
thanks in advance
Answer: I believe you are looking for something like this module

Rules: when Triggers won't do, use the event-condition-action paradigm of Rules. More complicated to set up than Trigger, but very powerful. Revisioning adds its own events and conditions to Rules, for example "content is about to be published" and "content has pending revisions".

and

Revisioning is integrated with Rules, adding a number of revision-specific conditions and events.

Rule for when content is published?


How to allow systemd daemon run DBus service

Question: I created PyQt5 program and a daemon using python. They should communicate via dbus - the program sends dbus-send --session --dest="org.example.dirswatcher" --type="method_call" --print-reply "/" "org.example.dirswatcher.update_dirs_to_watch" and accordingly the update_dirs_to_watch method from the daemon is executed. While I'm testing, everything works fine, but when I create a daemon from the dirswatcherd.py file and try to execute my PyQt5 app, it says Error org.freedesktop.DBus.Error.ServiceUnknown: The name org.example.dirswatcher was not provided by any .service files.
Yes, I did all of systemctl stuff and the daemon has 'activating' status (sometimes when I was changing .service or .conf files the status was green but still no DBus service was provided)
What I also did is:

put .conf file in /etc/dbus-1/system.d/org.example.dirswatcher.conf,

<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
  <policy context="default">
    <allow own="org.example.dirswatcher"/>
    <allow send_destination="org.example.dirswatcher"/>
    <allow receive_sender="org.example.dirswatcher"/>
  </policy>
</busconfig>

put .service file in /etc/systemd/system/dirswatcher.service.

[Unit]
Description=Dirs watcher
After=network.target

[Service]
User=omen
ExecStart=/usr/bin/python3 /home/user/file-manager/daemon/dirswatcherd.py
Restart=always

[Install]
WantedBy=multi-user.target

ALSO. dirswatcherd.py:
class Service(QDBusAbstractAdaptor, QObject):
    Q_CLASSINFO('D-Bus Interface', 'org.exmaple.dirswatcher')

    def __init__(self, parent):
        super().__init__(parent)
        QDBusConnection.sessionBus().registerObject("/", parent)

        if not QDBusConnection.sessionBus().registerService("org.exmaple.dirswatcher"):
            print(QDBusConnection.sessionBus().lastError().message())
...

Comment: I'm voting to close this question because as the systemd tag states: systemd questions should be for *programming questions* using systemd or its libraries. Questions about *configuring the daemon* (including writing unit files) are better directed to [Unix & Linux Stack Exchange](https://unix.stackexchange.com). Please delete this.
Comment: Arguably, writing the integration configs _is_ part of "programming" a D-Bus service, given that OP is writing their own D-Bus service and not just configuring something from apt-get (like the 100 other posts out there...)
Answer: Your error message is kind of guiding you in the wrong direction. It implies two things – it says that 1) there's no service with such name currently running and that 2) D-Bus tried to start it "on demand" but didn't know how.
Although the second part is easy to fix (by creating a second, different kind of .service file), in your case that's not actually related to the problem you're solving – it's not a mandatory part of D-Bus; it's just an "on-demand start" mechanism, but that's not what you're doing. Your systemd config and even the service name imply that you want it to be permanently running, so you don't actually need to have D-Bus start it again. (And, besides that, the name "dirswatcherd" kind of implies that it should be a permanently running service, and therefore on-demand activation wouldn't really be suitable for it anyway.)
You should instead focus on the first part: the fact that there's no such service currently running, even though you tried to start it via systemd. You said that you only ever saw status "activating", which means that your service keeps crashing. If you see a service "activating" but it never goes to "active", the first thing you should do is check the systemd logs via journalctl -b -u dirswatcher to see what's happening.
Most likely, what's happening is that your program is trying to connect to the session bus, but you're running it as a system service (and for some reason, adding .conf files for the system bus, even though that's not the same thing).
The key point is that system services have no access to the session bus. Not even if you set 'User=omen'. (Yes, they can be made to have access to one specific user's session bus, but the point is that you should not do that, even if it's possible.) In the same way, they don't have access to your GUI – that's also part of the "session".
(That's probably the reason you only ever saw "activating" and never "active" – the service kept failing to start because it had no bus access, and your 'Restart=always' just masked the problem.)

Generally, user-level services (e.g. stuff that runs under the invoker's user account, and especially stuff that interacts with X11/Wayland GUIs) should be on the session bus.
In that case, using a 'system' .service unit is wrong – it should go in the 'user' directory – and placing configuration in /etc/dbus-1/system.d/ is useless (both because the session bus instance doesn't look there, and because the session bus instance has no name restrictions to begin with).

On the other hand, system-level services (e.g. stuff that runs as root or as a dedicated daemon account) should be on the system bus.

So if this is a "user level" program, what you should do is:

Remove the /etc/dbus-1/system.d/org.example.dirswatcher.conf configuration file. As the directory name implies, that's for the system bus only. (Session bus has no bus-name restrictions by default, so such configuration is not necessary.)

Convert the system .service unit to a user .service unit – move it to /etc/systemd/user (or even to ~/.config/systemd/user/); remove the User= parameter; change multi-user.target to default.target.

Use systemctl --user ... to control the service.

Also, fix the typo in org.exmaple – as it currently is, your configuration defines one bus name but the service claims another.

Optionally, if you actually want D-Bus to be able to start the service "on demand", you would need to create a dbus-daemon .service file (different from systemd .service files) that associates the bus name with a particular executable and/or systemd service.
For system services, this would go in /usr/[local/]share/system-services/; for user-level services the subdirectory is just services/ (and it may be located in your ~/.local/share). For example:
~/.local/share/dbus-1/services/org.example.dirswatcher.service
[D-BUS Service]
Name=org.example.dirswatcher
# For direct (non-systemd) start; required but may be /bin/false to require systemd
Exec=/home/user/file-manager/daemon/dirswatcherd.py
# For indirect (systemd) start; optional
SystemdService=dirswatcherd.service
Comment: Thank you so much for such a response! It actually closed some "gaps" in my considerations, but the mistake in my case was that I didn't specify `Group=omen`.
Also, I got rid of the XML file altogether, because the application registers the new DBus service itself.
But I still left the file in the directory `/etc/systemd/system`, which is probably not quite right so for correctness of the whole situation, should I redo it according to your instructions?
Comment: The XML file is not to register the D-Bus service – it's to grant a user _permissions_ for registering the D-Bus service. (Session bus has no such permission checks since it's inherently limited to a single user anyway.) And yes, I would still say that it's very much not right to mix system-level services and QDBusConnection.sessionBus(), whether it's technically doable or not.


Why some other value than zero is coming in first row?

Question: I'm trying to make an MxN zero matrix using an array in C++. But some values aren't coming zero. Please help me resolve this problem.
#include <iostream>
using namespace std;
int main()
{
int m,n;
cin>>m>>n;
int i,j,s[m][n]={0};
for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        cout<<s[i][j]<<" ";
    }
    cout<<endl;
}
}

input: 4 4
output:
0 11097 1757549776 11097
0 0 0 0
0 0 0 0
0 0 0 0

expected ouput:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Comment: `s[m][n] = {0}` is not even valid C++.    Try using a `std::vector>std::vector >` instead.    For example,  `std::vector > s(m, std::vector(n))` will give you the behaviour you expect.
Answer: This code is not valid in standard C++ because it does not allow dynamic array creation without new like this.
For example, here is VC++ output: https://rextester.com/VFVL26633
ource_file.cpp(9): note: failure was caused by non-constant arguments or reference to a non-constant symbol
source_file.cpp(9): note: see usage of 'm'
source_file.cpp(14): warning C4552: '<<': operator has no effect; expected operator with side-effect
source_file.cpp(18): error C2036: 'int [m][n]': unknown size

If you make n, m const it will work correctly.
Use std::vector or new/delete.
Comment: Several compilers support VLAs as a non-standard extension.
Comment: @Peter: True, but that means you can't count on them implementing the _same_ non-standard extension. For instance, this exact problem (zero initialization) might be inconsistent across compilers.
Comment: @MSalters - No argument on that.  Context of my previous comment was the original posting of this answer, which used more tentative language than it does now.  (It appears the answer was edited to its current form about an hour before your comment).
Answer: I'm not sure, but probably it's because the size of the matrix is dynamic and the compiler can't generate initializer in compile-time.
Answer: s[m][n]={0} initialization is only valid when you know the size of the matrix in compiling time, you need use memset or a loop to initialize this matrix. using memset is very easy : memset(s,0,m*m*sizeof(int))
Comment: The question is tagged C++, not C. VLA's don't exist in C++, and you'd use `std::fill`.
Answer: Assigning size of static matrix/array in the form of variable is prohibited. You have to give the size at compile time or use dynamic arrays.
#include <iostream>
using namespace std;
int main()
{
    int i, j, s[4][4] = { 0 };
    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 4; j++)
        {
            cout << s[i][j] << " ";
        }
        cout << endl;
    }
}

Answer: When you declare array s its dimensions should be known in the compile time.
As you did not initialize explicitly m and n, they are both initialized with some random values and used for s array declaration.
So your s array could have any random dimensions (maybe zero) and after entering m and n from cin you might be just printing some uninitialized memory cells.
Comment: You may want to recheck the code. The values of `m` and `n` are read from standard input. Regardless, even if that wasn't the case, they wouldn't be "initialized with random values" (unspecified behavior), they'd be **uninitialized** (Undefined Behavior).
Comment: The `m` and `n` are read from the standard input indeed, but for the array declaration at the compile time they don't have those values from the standard input yet. Right, the variables are uninitialized so at the array declaration time they could have any values.
Comment: this is a VLA (variable length) array. The doc says that initialization of VLA is not supported, so the array elements are not padded with 0 like it would be done for a constant size array
Answer: Use an empty bracket {} to initialize the array. This will initialize all elements of the array to null by default.


Windows AD CA Code Signing Cert Request for Wrong User

Question: I am having an odd problem with a Code Signing certificate request from my Windows 10 workstation.  We have a Windows Server 2012R2 CA setup with the Code Signing template and everything works fine if I do the request from another machine.  But, if I do the request through MMC->Certificates->Current User->Request New Certificate I get the error:
<code>The EMail name in unavailable and cannot be added to the Subject or Subject Alternate name. 0x80094812 (-2146875374 CERTSRV_E_SUBJECT_EMAIL_REQUIRED)
</code>
If I look at the failed request on the server I see the same error but the requester name is incorrect.  Instead of my user name (DOMAIN\User) I see my admin user name (DOMAIN\UserAdmin).  This obviously fails as my admin user does not have an AD email address.
I cannot for the life of me figure out where the request is getting my admin name from?  If I look at my workstations event log I see the following error:
<code>- System
  - Provider
   [ Name]  Microsoft-Windows-CertificateServicesClient-CertEnroll
   [ Guid]  {54164045-7C50-4905-963F-E5BC1EEF0CCA}
   [ EventSourceName]  CertEnroll
  - EventID 13
   [ Qualifiers]  49754
   Version 0
   Level 2
   Task 0
   Opcode 0
   Keywords 0x80000000000000
  - TimeCreated
   [ SystemTime]  2021-01-19T13:27:15.5372014Z
   EventRecordID 118908
   Correlation
  - Execution
   [ ProcessID]  0
   [ ThreadID]  0
   Channel Application
   Computer workstation.domain.com
  - Security
   [ UserID]  S-1-5-21-507921405-651377827-682003330-2622
- EventData
  Context DOMAIN\user
  TemplateName CodeSigningCertificate
  CA CertServ.domain.com\Domain-Issuing-CA
  RequestId 12919
  ErrorCode The EMail name is unavailable and cannot be added to the Subject or Subject Alternate name. 0x80094812 (-2146875374 CERTSRV_E_SUBJECT_EMAIL_REQUIRED)
</code>
So it looks like it is making the request with my standard user but the server gets the request with my admin user.
Any ideas?
Answer: If you see different requester name, then it may indicate that either, you logged in with wrong account or application (MMC.exe or certmgr.msc) has hardcoded credentials to run in elevated mode with admin user credentials. This is configured through Compatibility tab in executable/shortcut properties.
Comment: Thanks for the ideas but this doesn't seem to be it.  I have checked Task Manager and MMC.exe is running as DOMAIN\User.  You also can't change the compatibility settings for Windows executables and I'm not using a shortcut to launch MMC.exe.
Comment: there must be something between you and CA that changes impersonated context and often it is due to saved creds in runas or somewhere else.
Comment: Thanks.  I'm playing around with this to see where it might be coming from.  I'll get back to you.


Hold an Angular 2+ app from loading until APP_INITIALIZER finishes running?

Question: I've found how to call a service before the root component loads. But I can't find a way to keep the whole app waiting until the service successfully finishes its job. In other words, how to make it a synchronous call. The service is loading essential setting through AJAX, and I have to hold the application from starting until the call finishes.
Adding *ngIf to the router-outlet doesn't work, it causes an error.
Blocking routes with CanActivate will stop the views from loading, but I then have to define a loader screen and call the appropriate route from code when the promise is fulfilled. It's not very elegant.
Is there a way to tell Angular to STFU until a certain value is true?
Comment: Show the code that makes the call and where it currently is.
Comment: This is the function which runs during bootstrap: https://pastebin.com/NvtTKa5M
Comment: Use promises: https://docs.angularjs.org/api/ng/service/$q. eg: return from your loadsettings function by resolving the promise once your service finishes doing stuff.
Comment: Thanks, but this is AngularJS, the old one, not Angular.
Answer: Not sure how you are using the APP_INITIALIZER, but I assume you have setup a factory function for the provider. If you make sure that function returns the promise of your API call made by your service the application initialization will be blocked until the promise is resolved.
E.g. create a file called app.initializer.ts
import { FactoryProvider, APP_INITIALIZER } from '@angular/core';
import { MyDataService } from './core/my-data.service';

export function initialAppSetup(provider: MyDataService) {

 // MyDataService's getInitialData must return a promise
 return () => provider.getInitialData()
}

export const ApplicationSetupProvider: FactoryProvider = {
 provide: APP_INITIALIZER,
 useFactory: initialAppSetup,
 deps: [MyDataService],
 multi: true
}

In your app.module.ts import the ApplicationSetupProvider
import { ApplicationSetupProvider } from './app.initializer';

and add it to the providers array
providers: [ AuthorizationSetupProvider ],


Add additional button to login form

Question: Drupal 7

I am trying to add a new button or link to my log in form. The button would simply link to another page outside of the drupal framework. I am looking at the form_alter hook but I am not sure if I completely understand how to implement my update.
do I have to update the template.php page?
The form is the login form on the front page. Any help would be great.
I am pretty sure I need something like the following :
<?php
$form['preview'] = array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#weight' => 19,
);
?>

But I need to add the link. request.php to the button so when clicked it will go to request.php. Also I am not sure where to add this code and how to direct it to my log in form.
Answer: You cannot alter a form from a theme's template.php file. You need to create a custom module for that. In this module, you can alter the login form in an implementation of the hook_form_alter() or hook_form_FORM_ID_alter() hooks.
Without some JavaScript, you will not be able to submit the form to a separated URL. What you can do, in your module, is to provide an dedicated validation or submit handler for you button. In this handler, you can redirect to your external URL using drupal_goto().
Something like:
MODULE_form_user_login_alter(&$form, &$form_state) {
  $form['foo'] = array(
    '#type' => 'button',
    '#value' => t('Foo'),
    '#submit' => array('MODULE_user_login_foo_submit'),
    '#limit_validation_errors' => array(),
  );
}

MODULE_user_login_foo_submit($form, &$form_state) {
  drupal_goto('/path/to/request.php', array('external' => TRUE));
}

Comment: I was afraid of that. Do you know of any clear resource on accomplishing this? There is a lot of great documentation on drupal.org but not much in the way of implementation. Thanks +1
Comment: Thats great but when I click the form tells me I need to enter something into the name and password fields (even though they are not getting used)  I tried adding:   $form['user_login_block']['pass'] = array(
    '#required' => FALSE
  );

  $form['user_login_block']['name'] = array(
    '#required' => FALSE
  );
Comment: Add '#limit_validation_errors' => array() to the button.
Comment: Thanks for your help. This worked perfectly. I am going to have to spend some more time with hooks!

Add additional button to login form


Longitudinal Impact of Intervention on Continuous Outcome Variable

Question: I am working on a research project to determine the impact of several different interventions on a dependent variable.  Over the last couple days, I have been reading about possible ways to approach the problem, but I haven't found anything that exactly fits how I have conceptualized the problem (though perhaps I'm thinking about it in the wrong way).
The easiest way to explain the question is with an example.  Suppose I want to determine the longitudinal effectiveness of two new procedures intended to lower blood pressure.  I want to know not only whether they're effective, but also which is most effective and if other factors impact the outcome (e.g. covariates like age).  Considering the following:

Each patient undergoes only one intervention.
I have 5-10 blood pressure measurements for each patient pre- and post-intervention at uneven time periods.
Since blood pressure fluctuates naturally based on a variety of environmental factors (which I can't control for), I would like to take all of my measurements into consideration rather than using a simple point estimate (e.g. mean, median, etc.).

So far, I have investigated these options, but none of them seem to take into account everything I would like to:
1. Mixed-design ANOVA:
  In this case, I would use the intervention (and potentially, some other elements like patient sex, age, etc.) as the between-subjects factors and time as the within-subjects factor.  The issue here is that I would not be able to take all of my measurements into account, I would have to use 1-2 point estimates at different time periods.
2. Interrupted Time Series:
  In this method, the measurements from each individual could be view as a time series.  I could use interrupted time series analysis to test if there is a change at or close to the time of intervention.  The problem is that this can only be used on a single time series (or possibly one time series from each intervention group), so it would be an incomplete picture of the data.
3. Multiple Analyses:
  I could perform multiple analyses to answer the different portions of my question.  In this method, I could potentially use a t-test or non-parametric test (e.g. Wilcoxon) to determine separately if there is a difference pre- and post-intervention for each treatment.  I could then use ANCOVA on the post-treatment data (with the pre-treatment mean/median of each sample as a covariate) to determine which of the two treatments was most successful.  However, both of these would fail to take into account the variation within each of the subjects.
Note:
Previous literature on this subject has just used point estimates (e.g. median of 3 measurements) for pre-intervention and difference at pre-determined time points (e.g. 1 day, 1 week, 4 weeks, etc.) post-intervention
Is there some other type of analysis/model/test that I haven't found that could answer these questions?  Am I thinking about the problem in the wrong way?  Perhaps it is okay to use the point estimates and I am just overly worried about the natural fluctuation in the measurement?
Update - here's an example of the kind of data I am dealing with:
<code>╔═══════════╦════════════╦══════════════╦═══════════╦══════════╗
║  Subject  ║ Treatment  ║ Measurement  ║   Date    ║ Pre/Post ║
╠═══════════╬════════════╬══════════════╬═══════════╬══════════╣
║ Patient 1 ║ A          ║           12 ║ 1/1/2018  ║ Pre      ║
║ Patient 1 ║ A          ║           16 ║ 1/23/2018 ║ Pre      ║
║ Patient 1 ║ A          ║           13 ║ 2/4/2018  ║ Pre      ║
║ Patient 1 ║ A          ║           14 ║ 2/7/2018  ║ Pre      ║
║ Patient 1 ║ A          ║           12 ║ 2/21/2018 ║ Post     ║
║ Patient 1 ║ A          ║           10 ║ 3/5/2018  ║ Post     ║
║ Patient 1 ║ A          ║            8 ║ 3/12/2018 ║ Post     ║
║ Patient 1 ║ A          ║            9 ║ 4/15/2018 ║ Post     ║
║ Patient 1 ║ A          ║            7 ║ 5/12/2018 ║ Post     ║
║ Patient 2 ║ B          ║           21 ║ 1/1/2018  ║ Pre      ║
║ Patient 2 ║ B          ║           22 ║ 1/23/2018 ║ Pre      ║
║ Patient 2 ║ B          ║           19 ║ 2/4/2018  ║ Pre      ║
║ Patient 2 ║ B          ║           17 ║ 2/7/2018  ║ Pre      ║
║ Patient 2 ║ B          ║           24 ║ 2/21/2018 ║ Pre      ║
║ Patient 2 ║ B          ║           21 ║ 3/5/2018  ║ Pre      ║
║ Patient 2 ║ B          ║           10 ║ 3/12/2018 ║ Post     ║
║ Patient 2 ║ B          ║           15 ║ 4/15/2018 ║ Post     ║
║ Patient 2 ║ B          ║           13 ║ 5/12/2018 ║ Post     ║
╚═══════════╩════════════╩══════════════╩═══════════╩══════════╝
</code>
Answer: I don't agree with your reflection about Interrupted Time Series as there may be multiple time point of Intervention and multiple ( waiting to be discovered) time points of intervention via Intervention Detection schemes here https://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html
Comment: Do you mind elaborating on where you disagree?  ITS would definitely allow me to find the intervention point(s) as you say in your answer.  My issue with it is that I haven't found a way to include the data from all of my samples into the ITS analysis.  Is there a way to do this?  Thanks!
Comment: It would help me if you actually posted all of your data so I can more fully understand your issue. By the way I am in the Philadelphia area also.
Comment: "I have 5-10 blood pressure measurements for each patient pre- and post-intervention at uneven time periods." .... This being so vitiates standard time series analysis which requires equally spaced observations.
Comment: I updated with an example of the data.  Obviously, this is not real data, but it approximates the kind of thing that I am dealing with.  Also, I am aware that time series requires equally spaced observations, which is precisely why I mentioned that my observations are not evenly spaced.  Sorry for not making that more clear in my question.


Error facing while installing scrapy for python using PIP

Question: I have python Python 3.6.3. Tried to install scrapy using below pip command.
pip install Scrapy

I got error say to install Microsoft Visual 14. I have installed it. Then I got below error in my command prompt.
Due to limitation, I have given last few lines of error messages. I have already went though few posts in here. But those solutions is not worked for me.
copying src\twisted\internet\test\fake_CAs\thing2.pem -> build\lib.win-amd64-3.6\twisted\internet\test\fake_CAs
copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.6\twisted\mail\test
copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-amd64-3.6\twisted\python\test
copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-3.6\twisted\words\im
copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.6\twisted\words\xish
running build_ext
building 'twisted.test.raiser' extension
creating build\temp.win-amd64-3.6
creating build\temp.win-amd64-3.6\Release
creating build\temp.win-amd64-3.6\Release\src
creating build\temp.win-amd64-3.6\Release\src\twisted
creating build\temp.win-amd64-3.6\Release\src\twisted\test
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DWIN32=1 -Ic:\python36\include -Ic:\python36\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" /Tcsrc/twisted/test/raiser.c /Fobuild\temp.win-amd64-3.6\Release\src/twisted/test/raiser.obj
raiser.c
c:\python36\include\pyconfig.h(222): fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

----------------------------------------

Command "c:\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\KAVIG~1.LAP\\AppData\\Local\\Temp\\pip-build-u9d1gd5n\\Twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\KAVIG~1.LAP\AppData\Local\Temp\pip-mhpbb97y-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\KAVIG~1.LAP\AppData\Local\Temp\pip-build-u9d1gd5n\Twisted\
Comment: Possible duplicate of [Running Cython in Windows x64 - fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory](https://stackoverflow.com/questions/23691564/running-cython-in-windows-x64-fatal-error-c1083-cannot-open-include-file-ba)
Comment: Most of the time when I face an error I don't understand I copy the last two lines of the error and past it in google search box. It works 90% of the time and its much easier then asking the question on SO.
Comment: it seems it needs `C/C++` compiler to compile it. There is ["Unofficial Windows Binaries for Python Extension Packages"](https://www.lfd.uci.edu/~gohlke/pythonlibs/). Probably `Scrapy` is on the list.
Answer: I have installed .Net framework and reinstalled Microsoft Viscal C++ 14v. This solved my issue.


Calculating the Covariance matrix for the mean of variables

Question: Assume that we have 3 3D points to make this questions simpler.
$$
pt_1 = \begin{bmatrix} x_1 & y_1 & z_1 \end{bmatrix} \\
pt_2 = \begin{bmatrix} x_2 & y_2 & z_2 \end{bmatrix} \\
pt_3 = \begin{bmatrix} x_3 & y_3 & z_3 \end{bmatrix}
$$
and we also have the variance-covariance matrix for each point
$$
c_1 =
\begin{bmatrix}
s_{x_1} & s_{x_1y_1} & s_{x_1z_1} \\
s_{x_1y_1} & s_{y_1} & s_{y_1z_1} \\
s_{x_1z_1} & s_{y_1z_1} & s_{z_1}
\end{bmatrix},
c_2 =
\begin{bmatrix}
s_{x_2} & s_{x_2y_2} & s_{x_2z_2} \\
s_{x_2y_2} & s_{y_2} & s_{y_2z_2} \\
s_{x_2z_2} & s_{y_2z_2} & s_{z_2}
\end{bmatrix}
c_3 =
\begin{bmatrix}
s_{x_3} & s_{x_3y_3} & s_{x_3z_3} \\
s_{x_3y_3} & s_{y_3} & s_{y_3z_3} \\
s_{x_3z_3} & s_{y_3z_3} & s_{z_3}
\end{bmatrix}
$$
I can easily calculate the average 3d point comprised of the 3 points above.
How would I calculate the variance-covariance matrix of the calculated average point ?
Comment: Hint: covariance is a linear operation.
Comment: I read that the variance parts are pretty much the quadrature over 3, in this case. So there is no difference for the correlations then I guess.
Comment: Just to clarify my previous comment: assuming that all between-point covariances are zero, you have simply $c=(c_1+c_2+c_3)/9$. There is no need to go through any computations at all.
Answer: Let $\overline{pt}=\frac{pt_1+pt_2+pt_3}{3}$. Then the covariance matrix of $\overline{pt}$ should be:
$C_\overline{pt} = \left[\matrix{Cov(\bar{x},\bar{x}) & Cov(\bar{x},\bar{y}) & Cov(\bar{x},\bar{z}) \\
                    Cov(\bar{x},\bar{y}) & Cov(\bar{y},\bar{y}) & Cov(\bar{y},\bar{z})\\
                    Cov(\bar{x},\bar{z}) & Cov(\bar{y},\bar{z}) & Cov(\bar{z},\bar{z})\\}\right]$
Note that $Cov(A,A)=Var(A)$ for any random variable $A$.  This will simplify all of the elements on the diagonal.
In addition, consider $Cov(\bar{x},\bar{y})$.
$\begin{eqnarray*}
Cov(\bar{x},\bar{y}) &=& Cov\left(\frac{x_1+x_2+x_3}{3},\frac{y_1+y_2+y_3}{3}\right) \\
&=& \frac{1}{3}\times\frac{1}{3}\times Cov\left(x_1+x_2+x_3,y_1+y_2+y_3\right) \\
&=& \frac{1}{9}\left[Cov(x_1,y_1)+Cov(x_2,y_1)+Cov(x_3,y_1)+Cov(x_1,y_2)+Cov(x_2,y_2)+Cov(x_3,y_2)+Cov(x_1,y_3)+Cov(x_2,y_3)+Cov(x_3,y_3)\right] \\
&=& \frac{1}{9}\left[s_{x_1y_1}+s_{x_2y_1}+s_{x_3y_1}+s_{x_1y_2}+s_{x_2y_2}+s_{x_3y_2}+s_{x_1y_3}+s_{x_2y_3}+s_{x_3y_3}\right] \\
&=& \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{x_iy_j}
\end{eqnarray*}$
This, of course, generalizes to $Cov(\bar{y},\bar{z})$ and $Cov(\bar{x},\bar{z})$.
Combining the above results, the covariance matrix $C_\overline{pt}$ simplifies to the following:
$C_\overline{pt}=\left[\matrix{s_\bar{x} & \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{x_iy_j} & \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{x_iz_j} \\
                    \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{x_iy_j} & s_\bar{y} & \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{y_iz_j}\\
                    \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{x_iz_j} & \frac{1}{9}\sum_{i=1}^3\sum_{j=1}^3s_{y_iz_j} & s_\bar{z}\\}\right]$
Comment: I guess this is the full blown out formula when there is also correlation between the 3 points themselves.
In my case this
$$
\frac{1}{9}\left[s_{x_1y_1}+s_{x_2y_1}+s_{x_3y_1}+s_{x_1y_2}+s_{x_2y_2}+s_{x_3y_2}+s_{x_1y_3}+s_{x_2y_3}+s_{x_3y_3}\right]
$$
will be simplified to
$$
\frac{1}{9}\left[s_{x_1y_1}+s_{x_2y_2}+s_{x_3y_3}\right]
$$
Comment: If you can assume independence between $pt_1$, $pt_2$, and $pt_3$, then yes.
Comment: And just confirming that indeed the diagonal terms are
$$
\frac{\sqrt{(s_{x1}^2+s_{x2}^2+s_{x3}^2)}}{3}
$$
Comment: Assuming $pt_1$, $pt_2$, and $pt_3$ are independent of one another, $Var(\overline{x})=Var(\frac{x_1+x_2+x_3}{3}=\frac{1}{9}\left[Var(x_1)+Var(x_2)+Var(x_3)\right]=\frac{1}{9}\left[s_{x_1}+s_{x_2}+s_{x_3}\right]$.  If they are not independent of one another, then there will be additional covariance terms on the back end. ($2s_{x_1x_2}$,$2s_{x_1x_3}$,$2s_{x_2x_3}$)