Apache / Mongrel / Rails Serving Two SSL Certificates?

Question: Is it possible for Apache (2.0) to serve up two SSL certificates when Mongrel and Rails are involved?
Here's the situation... I've got a server with two sites on it: foo.com and bar.com. Both have self-signed SSL certificates (from GoDaddy) and both have their own IP address. Here's the relevant Apache config settings:
<VirtualHost 192.168.100.17:443>
    ServerName secure.foo.com
    DocumentRoot /var/www/client/foo/current
    ProxyPass / http://127.0.0.1:3002/
    ProxyPassReverse / http://127.0.0.1:3002/
    ProxyPreserveHost on
    RequestHeader set X_FORWARDED_PROTO 'https'
    SSLEngine on
    SSLCertificateFile /etc/httpd/conf/ssl.crt/secure.foo.com.crt
    SSLCertificateKeyFile /etc/httpd/conf/ssl.key/secure.foo.com.key
    SSLCertificateChainFile /etc/httpd/conf/ssl.crt/gd_intermediate_bundle.crt
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP
    ErrorLog /var/www/client/foo/current/log/ssl_error_log
    TransferLog /var/www/client/foo/current/log/ssl_access_log
    LogLevel warn
    <Files ~ "\.(cgi|shtml|phtml|php3?)$">
            SSLOptions +StdEnvVars
    </Files>
    <Directory "/var/www/cgi-bin">
            SSLOptions +StdEnvVars
    </Directory>
    RewriteEngine On
    SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
    CustomLog logs/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
<VirtualHost 192.168.100.16:443>
    ServerName secure.bar.com
    DocumentRoot /var/www/sites/bar/secure
    ProxyPass / http://127.0.0.1:3003/
    ProxyPassReverse / http://127.0.0.1:3003/
    ProxyPreserveHost on
    RequestHeader set X_FORWARDED_PROTO 'https'
    SSLEngine on
    SSLCertificateFile /etc/httpd/conf/ssl.crt/secure.bar.com.crt
    SSLCertificateKeyFile /etc/httpd/conf/ssl.key/secure.bar.com.key
    SSLCertificateChainFile /etc/httpd/conf/ssl.crt/gd_intermediate_bundle.crt
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP
    ErrorLog /var/log/httpd/bar.com/ssl_error_log
    TransferLog /var/log/httpd/bar.com/ssl_access_log
    LogLevel warn
    <Files ~ "\.(cgi|shtml|phtml|php3?)$">
            SSLOptions +StdEnvVars
    </Files>
    <Directory "/var/www/cgi-bin">
            SSLOptions +StdEnvVars
    </Directory>
    SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
    CustomLog logs/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>

If I go to a page on secure.foo.com that should be secure (e.g. https://secure.foo.com/login), I get a warning that the certificate is for secure.BAR.com. But if I view the certificate it's for secure.FOO.com.
This is only happening in Firefox. No warnings in MSIE.
My theory is that Apache is serving up the correct certificate (for secure.foo.com) but then somehow the certificate for secure.bar.com is also sent. (I'm assuming MSIE doesn't throw an error because it simply ignores the second one.)
I'd like to blame the situation on Mongrel, but Mongrel doesn't "do" SSL. I'd also like to blame it on Rails, but all Rails does is check to see if a page is supposed to be encrypted and if it isn't, just redirect it to a secure connection.
Has anyone seen anything like this before? Any ideas what the problem could be?
UPDATE: Commenting out the following lines in the Apache config takes down the site, of course, but results in a correct SSL "handshake":
ProxyPass / http://127.0.0.1:3002/
ProxyPassReverse / http://127.0.0.1:3002/
ProxyPreserveHost on

Answer: This is embarrassing...
The problem was being caused by a badly formed favicon link on the pages. We were linking to https://foo.com/images/favicon.ico when it should instead be https://secure.foo.com/images/favicon.ico.
As I understand it, the problem wasn't affecting MSIE because MSIE ignores favicon links via SSL.


In VBA for Excel, how do I limit the following code to only run in one single Tab?

Question: I am working with the following Excel VBA script :
Sub Multi_FindReplace()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("Mostly satisfied", "Completely satisfied", "N/A", "Not at all satisfied")
rplcList = Array("Satisfied", "Satisfied", "Satisfied", "Not satisfied")

'Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    'Loop through each worksheet in ActiveWorkbook
      For Each sht In ActiveWorkbook.Worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
      Next sht

  Next x

End Sub

But the issue is that it is operating on all 3 tabs of my worksheet, when I only want it to work on one single tab - called "Refined" .
How do I change the code so that it will only loop on the "Refined " Tab ?
Do I need to remove the line Dim sht As Worksheet and make it to :
Dim sht as "Refined1" ?
Comment: Remove the `For Each` loop and add `set sht = ActiveWorkbook.Sheets("Refined1")`.
Comment: One would think `'Loop through each worksheet in ActiveWorkbook` is clear enough...
Comment: I picked off 'Refined1' from the bottom of the OP. It could be either way, but should match his worksheet name.
Comment: @PeterT - Ok I will try this , thank you !
Comment: @PeterT  - Why is it `"Refined1"` and not just `"Refined"` ?
Answer: Replace:
'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)

    'Loop through each worksheet in ActiveWorkbook
    For Each sht In ActiveWorkbook.Worksheets '<-- This line is looping through worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
        LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
        SearchFormat:=False, ReplaceFormat:=False
    Next sht

Next x

With this:
Set sht = ActiveWorkbook.Sheets("Refined1")

'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)

    sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False

Next x


Não consigo checar se um array é vazio ou null

Question: Preciso exibir uma mensagem sempre que o meu array for vazio ou null, porém não estou conseguindo. Chamo a função JS no PHP, passando um array com json_encode. Funciona perfeitamente, mas não checa se o array for vazio.
arquivo php:

$nGals = $conexao->consultarDados("select gal from portfolio where theme = '{$tem}' group by gal");

    $galArr = array();

    foreach($nGals as $rows){
        array_push($galArr, $rows);
    }

    $countArr = count($galArr);

    $x = 1;
    while($x <= $countArr){

        $parametroGal = array();

        $galeria = $conexao->consultarDados("select * from portfolio where gal = '{$x}' and theme = '{$tem}' limit 4");
        foreach($galeria as $rows){
            array_push($parametroGal, $rows['nome']);
        }

        $jsonGal = json_encode($parametroGal);

        echo "galerias(".$jsonGal.",".$x.");"; //passo o array aqui
        $x++;
    }

A função está em um arquivo JS separado:
function galerias(query,x){

    var imgs = document.querySelector("#gallery");
    var theme = location.search.split("?tem=")[1];

    //verifica se ha imagens na determinada galeria
    //porem o if nao funciona, apenas o else funciona quando o array nao e vazio
    if(!query || query.length == 0 || query == null){
        imgs.innerHTML = "
Ainda não ha galerias nesta seção.
";
    }else{

    imgs.innerHTML += "
";
    imgs.innerHTML += "
";
    imgs.innerHTML += "
Galeria "+x+"
"

    for(var i = 0; i < query.length; i++){
        imgs.innerHTML += '';
    }

    imgs.innerHTML += "
";
    imgs.innerHTML += "
";
    imgs.innerHTML += "

Veja mais

";
    }
    console.log(query.length);
}

Comment: Esse código está assim no PHP? com JS e PHP misturado?
Comment: Também não entendi
Comment: @Sergio Editei a pergunta para ficar mais facil de compreender.
Comment: @anuseranother ok, assim faz mais sentido. E onde está o código do JSONP?
Comment: não é só colocar um `if (!query) return;` no js? ou da erro no json_encode?
Comment: @Sergio não fiz um codigo em json, apenas converti o array em php para json, ja foi o bastante para a situação, funciona perfeitamente, so a verificação que não...
Comment: @MaiconCarraro então cara, não da erro direto mas não funciona do mesmo jeito que está agora.
Comment: @anuseranother ok então precisas de usar o JSON.parse não? o que te dá `console.log(typeof query, typeof x);`?
Comment: @Sergio nas galerias que possuem imagens no array, me retorna "object", "number", nas que possuem o array vazio nao me retorna nada.
Comment: @anuseranother como aparece esta linha `echo "galerias(".$jsonGal.",".$x.");"; //passo o array aqui` no HTML?
Comment: @Sergio aonde possuo galeria: `galerias(["foto1_1.jpg","foto1_2.jpg","foto1_3.jpg","foto1_4.jpg"],1);`, aonde não possuo a linha nem aparece. a tag
Comment: @anuseranother ok, e nessas que dá vazio o que dá `echo $countArr;` no PHP __antes__ do `while`? acho que ele nem está a entrar no `while` no PHP...
Comment: @Sergio não está, como uso apenas para contar o numero de galerias, preciso deixar ele fora para servir de referencia ao contador do while. O echo me retorna 0 e um var_dump me retorna int(0);
Comment: @anuseranother então antes do while devias ter algo como `if ($countArr == 0) echo "galerias([], 0);"; die();` não?
Comment: **Sergio** não, pois há uma `QUERY` no meio do `WHILE`
Comment: @FelipeDouradinho mas esse while nunca é corrido se o `$countArr` dá zero
Comment: Não tem problema **Sergio**, se não é corrido, o `JS` não precisa de alteração...mas se `countArr` ele PODE haver resultado pela `query`
Answer: Como referiste nos comentários $countArr dá zero quando não há galerias -  "O echo me retorna 0 e um var_dump me retorna int(0)". Isso quer dizer que o while nunca é corrido e que
echo "galerias(".$jsonGal.",".$x.");"; //passo o array aqui

nunca é corrido.
Então sugiro que cries uma alternativa no código para esses casos... algo como:
if ($countArr == 0) echo "galerias([], 0);";
else while($x <= $countArr){ // fazer o while

Para fazer o echo de conteudo vazio.
Comment: @Sergio Obrigado Sérgio, foi a resposta mais eficaz e que identificou o meu problema. Agradeço ao Sérgio e a todos.
Comment: Só resolveria a primeira parte do problema. Dentro do `while`, também pode haver a possibilidade de `parametroGal` nunca ser preenchido.
Comment: @FelipeDouradinho como assim "dentro do while"? esse while nunca acontece no caso em que `$countArr` é `0`.
Answer: Provavelmente seu json_encode está retornando [], como você pode ver aqui: https://ideone.com/BO6SsT
Faz uma verificação no javascript:
if (query == '[]')
    imgs.innerHTML = "
Ainda não ha galerias nesta seção.
";

Se estiver utilizando o jQuery existe o jQuery.isEmptyObject

window.onload = function () {

var json = {};

if ($.isEmptyObject(json))
  alert('vazio');

};

Comment: Vou ficar com a resposta do Sergio pois foi a que melhor encaixou para mim, mas agradeço pela ajuda !
Comment: Ainda nada... como se ignorasse o if completamente
Comment: @anuseranother se você colocar um `console.log(query)` aparece o que no console?
Comment: Aparece o meu json aonde o array há valores, aonde não há não aparece nada.
Comment: @anuseranother coloquei uma outra alternativa


Identifying and breaking on exception: 'OpenSSL.SSL.Error' using python's requests module

Question: I'm currently parsing through a list of URLs and in the event that one throws an exception I want to just break and move on to the next one.
However, I keeping getting
OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

Solving this exception is beyond my expertise right now, so I want to just be able to skip it for now and handle that later. My problem, however, is when I write the try catch to do so:
    try:
        r = requests_retry_session(session=s).get(test_link, verify=cafile, allow_redirects=True, timeout=4.0)

    except OpenSSL.SSL.Error:
        print('SSL error, moving to next domain')
        break

I get this:
NameError: name 'OpenSSL' is not defined

I know the easiest way to fix this would be to just do verify=False, however, tthat'svery unsafe and I would rather not open myself up to a possible MITM attack.
What I've tried:
Attempting to follow the documentation of this previous related question:
pip install --upgrade certifi

And finally an extremely sloppy try catch block, that essentially catches NameError: name 'OpenSSL' is not defined and breaks on that as a name error, which is not pythonic at all. I know I can do a very general catch all, however, I don't want to skip all errors.
I'm running python 3.7.3 and requests 2.22.0
Comment: can you tell me which website are you trying to access?
Comment: `NameError: name 'OpenSSL' is not defined` - did you remember about `import OpenSSL`? ;) Also, if you run each request as thread, exception will just kill the thread and you can easily discard killed results.
Comment: @h4z3 running that now, I've been able to parse through a couple domains before I hit the error so I wouldn't image (I think?) that would be the problem.
Comment: @LucasWieloch I'm running it again to get you which domain it is, it takes a second. update: this is the domain  http://www.4mresearch.com/
Answer:
Attempting to follow the documentation of this previous related question

You should have solved this exception handling by following those instructions and having pyopenssl (pip install pyopenssl) installed and its OpenSSL imported at the top of your module.
Comment: I edited my answer, it's about handling the exception, we have no enough data to deal with the actual error.
Answer: Found the correct exception, its super trivial but confusing documentation.
So OpenSSL.SSL.Error would be caught by using requests.exceptions.SSLError, and importing OpenSSL or pyOpenSSL doesn't need to be done (explicitly) in this case.
Comment: Yeah, I don't see a tidy way to handle this.  I get an exception thrown when I call `load_certificate` and I can't catch it with `OpenSSL.SSL.Error`.


Prove that if $X \overset{d}{=} -X$ and $P(X=0)=0$ then $|X|$ and $\operatorname{sgn}(X)$ are independent.

Question: As in question - I need to prove that if $X \overset{d}{=} -X$ and $P(X=0)=0$ then $|X|$ and $\operatorname{sgn}(X)$ are independent. I do not even know where to start. I tried something like that:
$$P(|X|\leq k, \operatorname{sgn}(X) \leq \ell, X <0) = \cdots $$ but it gets me nowhere...
I will appreciate any help.
Answer: $$P(|X| \le t \mid \text{sgn}(X) = 1) = \frac{P(0 < X \le t)}{P(X > 0)} = 2 P(0 < X \le t) = P(|X| \le t) $$
Answer: Writing about an event of the form $\operatorname{sgn}(X) \le \ell$ is rather odd when the only two values that $\operatorname{sgn}(X)$ can have are $+1$ and $-1.$
First note that
$$
\Pr(\operatorname{sgn}(X) = +1) = \overbrace{\Pr(X>0) = \Pr(-X>0)}^{\large\text{since } X \, \overset d = \, -X} = \Pr(X<0) = \Pr(\operatorname{sgn}(X)=-1), \\[10pt]
\text{and therefore } \Pr(\operatorname{sgn}(X)=+1) = 1/2.
$$
Now suppose $A\subseteq (0,\infty).$ Notice that the event $\big[\,|X|\in A\ \&\ \operatorname{sgn}(X)=+1\big]$ is the same as the event $[X\in A].$ Then we have
\begin{align}
\Pr( |X| \in A\ \&\ \operatorname{sgn}(X)=+1) & = \Pr(X\in A) = \Pr(-X\in A) \\[10pt]
& = \Pr(|X|\in A) \cdot \frac 1 2 \\[10pt]
& = \Pr(|X|\in A)\cdot \Pr(\operatorname{sgn}(X)=+1).
\end{align}
Thus the two events are independent. (And similarly with $-1$ instead of $+1.$)


Outputting part of an object

Question: I have the following saved into a variable called fieldErrors.
 Object { url_title="This URL title is being ... titles must be unique."}

How can I output just the text within the " "? (This URL title is being ... titles must be unique.)
Comment: `fieldErrors.url_title`
Answer: Object literal definition looks rather like that (what you've written is wrong):
obj = { url_title: "This URL title is being ... titles must be unique." }
console.log(obj.url_title) <- outputting

Comment: Ah so simple! Thank you.

Outputting part of an object


DropDownList quantidade Itens

Question: Bom dia, estou utilizando dropdownlist no asp.net para carregar alguns dados vindo do banco, porém eu não sei a quantidade que irá ser mostrada, pois depende do preenchimento no banco.
Eu gostaria de mostrar somente uma certa quantidade de itens.
Por exemplo, se possuir 29 registros, quero mostrar somente os 5 primeiros e após isso mostrar barra de rolagem, sempre com 5 registros.
Porém de toda forma que tento não consigo, existe alguma forma de limitar a quantidade de itens do dropdownlist que é preenchido pelo banco de dados?
Dropdownlist:

 <asp:DropDownList ID="cbfuncionario" runat="server" style = "overflow-y: scroll"></asp:DropDownList>

e aqui carrego o dropdownlist:

  public void CarregaFuncionario()
        {
            SqlCommand comando = new SqlCommand();
            comando.Connection = clsdb.AbreBanco();
            comando.CommandType = CommandType.Text;
            comando.CommandText = "select pessoa.id,nome FROM [pessoa] inner join classificacoes on classificacoes.id = pessoa.classificacao_id where estado <> 'Inativo' and estado <> 'Excluido' and classificacoes.tipo = '1' order by pessoa.nome ASC";

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comando;
            DataSet ds = new DataSet();
            da.Fill(ds);

            cbfuncionario.DataSource = ds.Tables[0];
            cbfuncionario.DataTextField = "nome";
            cbfuncionario.DataValueField = "id";
            cbfuncionario.DataBind();

        }
Comment: Tem como colocar o código?
Comment: Alterei a pergunta incluindo o código. Obrigado.
Answer: Usando position:absolute; e this.size, é possivel escolher a quantidade de items(10 no exemplo)
<asp:DropDownList ID="cbfuncionario" onclick="this.size=1;" onMouseOver="this.size=10;" onMouseOut="this.size=1;" runat="server" style = "position:absolute;"></asp:DropDownList>

Creditos
Comment: Também não de Leo, ele fica do tamanho normal, e não abre na quantidade, você vai descendo direto em uma linha só, não expande.
Comment: Leo, na verdade funcionou sim, pois havia um css por trás, e retirei, e funcionou perfeitamente, muito obrigado!
Answer: Creio que isso resolva seu problema, caso queira mostrar mais itens altere a altura do seu item HEIGHT

E seu código HTML fica assim

 <asp:DropDownList ID="cbfuncionario" runat="server" style = "overflow-y: scroll"></asp:DropDownList>

Comment: Tentei dessa forma, porém continua mostrando a quantidade de itens da página, não foi alterado para mostrar somente alguns itens, mudou somente a design do dropdown, mas ao abrir pra mostrar, continua mostrando todos de uma vez.

DropDownList quantidade Itens


Is there a variant of k-means that assumes that most data isn't in a group?

Question: Say I have 100k observations (each observation is a vector of size N), and I have strong prior that there are say 5 distinct groups all with very tight clusters (about 50k observations in total, say 10k per group) and the rest of the data (50k observations) is just noise.
Is there a variant of k-means that would get the 5 desired clusters and ignore most of the noise?
I have thought about doing k-means with a restriction on maximum threshold distance from the centroid but I was wondering if there is a more 'canonical' (using that term very loosely here) way of doing it.
Comment: have you looked at gaussian mixture models, they are a a kind of generalisations of k-means and I could imagine you would set one gaussian to have a fixed large variance ... (or it might fit it automatically)
Answer: This will be difficult if there's a class imbalance, where you have about the same or more non-clustered data than clustered data. If this is the case, normal K-means will suffer from poor choice of initial conditions and most of the time you'll end up with clusters in the non-clustered region. The usual fix for this is to just throw in more clusters in hopes that they will absorb the non-clustered data, but this will be painfully slow. So to make K-means work, you'll need to manually carve out a region of clustered vs non-clustered points. This might not be too bad:
To make this scalable, first try hitting your data with PCA and investigate if there's any obvious separation between clustered/non-clustered in the first few components. You could also try tSNE if your data is highly nonlinear.
Then start manually tagging points as clustered/non-clustered. If you're using tSNE for example, try to manually tag cluster and non-cluster points. Since tSNE preserves distances, try to pick clustered/non-clustered points that are closed to each other (i.e. on the "boundary" of region between clustered/non-clustered points).
If PCA does a good job, you can define non-clustered points by isolating the quadrant they are in, and in effect completely throwing those points out. Otherwise, using the above tagging scheme, you can then train an SVM to find a separating hyperplane. You could also use any reasonable classifier, even small random forests. The nice thing about an SVM is it will give you an obvious separating hyperplane. After that, predict your cluster points, and throw out the predicted non-clusters.
If you really do have solid separation between clustered/non-clustered points, the above scheme should work reasonably well after tagging say, a few hundred points.
Comment: Great! Thanks for the detailed answer. I was hoping for for something a little less ad-hoc but I agree it looks like using PCA as a first pass and tagging from there seems like a reasonable thing to do. Seanv I will also look into Gaussian mixture model. Thanks!
Comment: I was about to ask this same question.  Are there any new algos recently that can do this or is using several models to filter out your data first still the way to go?


Input Type Number Auto Update with comma

Question: I have a question trying to have the input field auto-add a comma on input for readability. E.g 123,456.
.toLocaleString() has been used to resolve the end result, but i need the comma displaying at the time of input also.
Thanks.
  const handleGrossIncomeChange = (event) => {
    const { name, value } = event.target;
    setGrossIncome(value);
    if (resultShower === false){
    setResultShower(!resultShower);
    resultExport = resultShower;
    }
    else {
      return resultShower
    }

  };

Gross Income {""}

            £
            <input
              type="number"
              name="grossIncome"
              id="grossIncome"
              autoComplete="off"
              onChange={handleGrossIncomeChange}
              className="currency-value"
              placeholder="0.00"
            />

<button type="submit" name="resultTester" onClick={handleClick}>click me </button>

Comment: it is not clear what you are trying to achieve here
Answer: You can use Intl.NumberFormat Api like below:

function formatCurrency(event) {

  let value = event.target.value;

  value = value.replace(/[^\d]/g, '');

  value = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value / 100);

  event.target.value = value;
}
<input type="text" id="amount" oninput="formatCurrency(event)">
Answer: Since the input value contains "," (not a number), the input has to be of the text type.
  <input
    type="text"
    onChange={(e) => {
      const value = parseInt(e.currentTarget.value.replaceAll(",", ""));
      if (isNaN(value)) e.currentTarget.value = "0";
      else e.currentTarget.value = value.toLocaleString();
      setGrossIncome(value);
    }}
  />

(Tested in React v18.0, ES5)


Google Drive API - How to get folder id by folder name

Question: I am trying to get folder id by folder name by using google drive api.
Is there anyway i could get Folder id of a folder in drive by passing its name. I am developing this in .net using c#.
I have tried the code provided on the below link
Google DRIVE API V3 - Get a folder id with name
But it was not clearly understood how to execute that.
Any help on this appreciated !
Comment: @MindSwipe Agree, But after that which method to execute that's not clear
Comment: Check out [this](https://developers.google.com/drive/api/v3/search-parameters) from google itself with sample code for .NET
Comment: @MindSwipe Yeah but how to pass the metadata in that case
Comment: Which metadata?
Comment: name and mimetype which we pass in metadata, like shown in the example
Comment: Instead of `request.Q = "mimeType='image/jpeg'` replace it with `request.Q = "mimeType='application/vnd.google-apps.folder'"` and (I'm not sure from here on out) add the name field to the `Fields` Property like so: `request.Fields = "nextPageToken, **name=your-name-here**, files(id, name)";`, you can always use string interpolation ($"") to set your name to whatever
Comment: Yeah.. I have already tried till this point. But it give error as invalid field selection for name field
Answer: @XamDev
Let's say I have a folder "test" on my google drive. I would like to find this folder by giving Google drive API, the name of the folder and restrict the results only to folders. This is how you can do it (It's working in my case):
<code>        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Q = "mimeType = 'application/vnd.google-apps.folder' and name = 'test'";
        listRequest.Fields = "nextPageToken, files(id, name)";

        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
        .Files;
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {   //My TextBlock(WPF)
                ListedFiles.Text = $"{file.Name}, {file.Id} \n";
            }
        }
</code>
The part of the source code comes from: https://developers.google.com/drive/api/v3/quickstart/dotnet and the parameters that you can search for: https://developers.google.com/drive/api/v3/search-parameters


RDweb certificate issue

Question: I have a problem with the following system:

There is a Windows 2012 R2 TS farm with 2 node, a gateway and a broker
It's available externally from login.example.com
There is an AD too, the TS farm servers are member servers, the AD domain is example.local

The problem: I would like to allow users to access this system without any warning or any certificate installation requirements. The computers are non-AD computers and there is no way to make them AD-member.
Things what i tried or thinked around:

I tried to get a free StartSSL certificate to login.example.com but after I installed it, the TS session starting broke because name mismatch.
I tried to make a selfsigned certificate that was issued to tsgw.example.local but the problem was opposite: even if I installed the cert, browsers complained about name mismatch.
As I know, there is no public CA what allow to issue a cert with public common name, but a private altname/additional DNS name.
The forums / SO/SF topics what I discovered are recommends to make a private CA and issue a cert with that (it's able to issue cert to both name) but it's our last plan, because we really don't want to force users to install a CA certificate to use our service (as they're non-AD computers, there is no automatic way to enforce trusting our CA) if there is a way to avoid that.

Is there any solution for this problem? I would like be satisfied if there is a way to enforce RDweb to ignore name mismatch.
Answer: The solution was easier than I expected. You have to navigate in Server Manager to a Remote Desktop management interface, edit deployment properties and change all certificates in "Certificates" tab to the external certificate. In inter-server communication the services do not use an SSL-encrypted connection (just pure RPC), so they can simply ignore the certificate you install. However, in the client-server communication, this certificate will be used, so it's very important to be same in all cases.
Answer: Why can't you buy an SSL cert from an authority?
I was configuring a similar setup recently and I both one from here: https://www.namecheap.com/
It's called PositiveSSL and costs around $6.
After your server is configured with this one you won't get an SSL error.
Comment: And their CA certificate is included in Windows root certificates? We can use onl CAs what already included in that package.

RDweb certificate issue


Show difference between conditional expectations is positive

Question: Suppose we have a continuous random variable $Y$ and a random Bernoulli variable $T$ such that $P(T=1|Y)$ is monotonically increasing in $Y$.
How can we show that $E[Y|T=1]>E[Y|T=0]$?
To me, it makes intuitive sense, but I can't prove it mathematically.
Answer: I've managed to answer the question myself. I'm including the solution here for other people that might have the same question.
I want to show that the quantity below is greater than $0$.
$=E[Y \mid T = 1]-E[Y \mid T = 0]$
$=\int^{\infty}_{-\infty}{yP(Y=y \mid T=1)dy}    -\int^{\infty}_{-\infty}{yP(Y=y \mid T=0)dy}$
Let $p = P(T=1)$ and $f$ be the PDF of $Y$. Then:
$=\int^{\infty}_{-\infty}{y\left(\frac{P(T=1 \mid Y=y)f(y)}{p}-\frac{(1-P(T=1 \mid Y=y))f(y)}{1-p}\right)dy}$
$=\int^{\infty}_{-\infty}{f(y)y\left(\frac{P(T=1 \mid Y=y) - p}{p(1-p)}\right)dy}$
$=\frac{1}{p(1-p)}(\int^{\infty}_{-\infty}{f(y)y P(T=1 \mid Y=y)dy}  -   p\int^{\infty}_{-\infty}{f(y)ydy})$
Let $Z=P(T=1 \mid Y)$. Then:
$=\frac{1}{p(1-p)}(E[YZ]  -   E[Z]E[Y])$
$=\frac{1}{p(1-p)}Cov(Y,Z)$
We know that $Z$ is increasing in $Y$, and the covariance of a random variable and an increasing function of that random variable is always positive (see reference). Therefore:
$=E[Y \mid T = 1]>E[Y \mid T = 0]$


Model selection and estimation for pseudo out-of-sample forecasting

Question: I have quarterly data on inflation from 1990 Quartal 1 to 2016 Quartal 3.
If I want to perform the pseudo out-of-sample forecasting one quarter ahead with an autoregressive function, do I have to estimate the model until 2016 Quartal 2?
When choosing how many lags to include in the AR model (by looking at BIC and AIC) do I have to consider the whole sample or just until 2016:2?
Answer: The whole idea of pseudo out-of-sample forecasting is that each forecast must be constructed without using any information that would not have been available at the time.  This means that you would need to fit your model up to the quarter behind the one you are creating a forecast for.  It also means that you cannot use the whole sample when deciding how many lags to use or in making any other decision about your model.  If you were to use the whole sample to make any decision on your model then this would corrupt the "out-of-sample" nature of the forecast.
Answer: You should estimate the model with sample until 2016:2 and make a forecast for 2016:3.
It is better explained here.
Have you considered to make the pseudo-out-of sample forecasts for longer period? Let's say for all quarters in 2016?
Comment: Thank you for your explanation, I've succeeded in making the one-quarter and three quarters ahead forecasts. However, I have a last question: I would like to make also the 2 quarters ahed forecast, and I begin by estimating the model up until 2015:4 and make a forecast up to 2016:2. Since my forecasting period is 2016:1-2016:3, is the forecasting exercise over or should I estimate the model using observation until 2016:2 and make the forecast fore 2016:3? In this case wouldn't it be just a one period ahead forecast, since i don't have observation for 2016:4?
Comment: I considered it, yes.  Let's say i want to forecasting all the four quarter of 2016, in that case should I use data up until 2015:4? And could I use the lag order determined before when forecasting 2016:3, or should I reengage in model selection considering the sample 1990:1-2015:4?
Comment: Usually it makes sense to use ARMA(p,q) models for forecasting not further than _p_ or _q_ periods forward. So, if you have ARMA(1,1), you should make a forecast for the next period only.
Comment: Then, there is a question: how do you want to use your model? If you want to estimate model everytime when new data are available, then I would reestimate model 3-times and make one-step forward predictions for 2016:1-2016:3.
If you want to use the same model with the same parameters, then you can estimate the model with data until 2015:4 and make predictions for 2016:1-2016:3. However, prediction in time 2016:2 will be based on 2016:1 and I recommend using actual value, not predicted. You can read about this here: http://davegiles.blogspot.sk/2013/11/forecasting-from-regression-model.html


Calling another function using drupal_get_form

Question: How can I call a function using drupal_get_form when a submit button is clicked. My situation is that i have a custom module where there is only a submit button. So when that submit button is clicked I want to call a particular function. How can I achieve it through drupal_get_form.
Answer: $form['#submit'][] = 'myform_form_submit';

You can call your function as above. Or
function myform_form_submit($form, &$form_state) {
  //execute your function here
}

Comment: `myform_form_submit` will work if your form name is `myform_form`


How to alter text filters conditionally based on content type?

Question: How can I get the content type of the current node from within a text filter, so I can use it to conditionally alter how the filter is applied?
Getting the node ID from the arg() function and using it to load a node object does not work because the text filter is run multiple (30+) times and exhausts the available memory.
$node = menu_get_object();
if ( !empty($node) ) {
  dd('Have a node, do something');
}

The same is true with the following method of getting the content type: $node = menu_get_object();
Comment: So basically the question would be: What the most lightweight way to load a node's "type" property from the URL. Right? Cheers
Answer: You could go with the following code inside your filter's callback function:
if(arg(0) == 'node' && arg(1) > 0){
  $result = db_select('node', 'n')
  ->fields('n', array('type'))
  ->condition('nid', arg(1),'=')
  ->execute()
  ->fetchAssoc();
  dsm($result['type']);
}

Good luck!
Answer: check this  replace $user with node  condition node_type = "YOUR_NODE_TYPE_MACHINE_NAME"; // can find this on the node type's "edit" screen in the Drupal admin section.

$result = db_query("SELECT nid FROM node WHERE type = :nodeType ", array(':nodeType'=>$node_type));

$nids = array();

    function hide_formats_permission() {
      return array(
        'show text format dropdown' => array(
          'title' => t('Show text format dropdown'),
          'description' => t('Show the text format dropdowns where more than one text format is available. If a user does not have this permission then the text format dropdown will be displayed in a collapsed fieldset.'),
        ),
      );
    }

    /**
     * Implements hook_element_info_alter().
     *
     * We are using the implementation of better_formats module to intercept the display of input formats and
     * display this with our own function
     *
     */
    function hide_formats_element_info_alter(&$type) {
      // Change text format processing on elements to our version.
      if (isset($type['text_format']['#process'])) {
        foreach ($type['text_format']['#process'] as &$callback) {
          if ($callback === 'filter_process_format') {
          $callback = 'hide_formats_filter_process_format';
          }
        }
      }
    }

    /*
     * Started as a direct copy of filter_process_format from core filter.module
     */
    function hide_formats_filter_process_format($element) {
      global $user;

      // Ensure that children appear as subkeys of this element.
      $element['#tree'] = TRUE;
      $blacklist = array(
        // Make form_builder() regenerate child properties.
        '#parents',
        '#id',
        '#name',
        // Do not copy this #process function to prevent form_builder() from
        // recursing infinitely.
        '#process',
        // Description is handled by theme_text_format_wrapper().
        '#description',
        // Ensure proper ordering of children.
        '#weight',
        // Properties already processed for the parent element.
        '#prefix',
        '#suffix',
        '#attached',
        '#processed',
        '#theme_wrappers',
      );
      // Move this element into sub-element 'value'.
      unset($element['value']);
      foreach (element_properties($element) as $key) {
        if (!in_array($key, $blacklist)) {
          $element['value'][$key] = $element[$key];
        }
      }

      $element['value']['#type'] = $element['#base_type'];
      $element['value'] += element_info($element['#base_type']);

      // Turn original element into a text format wrapper.
      $path = drupal_get_path('module', 'filter');
      $element['#attached']['js'][] = $path . '/filter.js';
      $element['#attached']['css'][] = $path . '/filter.css';

      // Setup child container for the text format widget.
      $element['format'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('filter-wrapper')),
      );

      /*
       * Add custom display.
       */
      if (user_access('show text format dropdown')) {
        $element['format']['#title'] = "Text formats options";  // Title is needed in our theme or you can't expand the fieldset
        $element['format']['#collapsible'] = TRUE;
        $element['format']['#collapsed'] = TRUE;

        // Add custom CSS to fix overlap in fieldsets for seven theme. #17892227
        global $theme;
        if ($theme == 'seven') {
          $custom_css = 'fieldset.filter-wrapper { padding-bottom: 20px;} fieldset.filter-wrapper div.fieldset-wrapper { padding-top: 20px;}';
          drupal_add_css($custom_css, 'inline');
        }
      }

      // Prepare text format guidelines.
      $element['format']['guidelines'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('filter-guidelines')),
        '#weight' => 20,
      );
      // Get a list of formats that the current user has access to.
      $formats = filter_formats($user);
      foreach ($formats as $format) {
        $options[$format->format] = $format->name;
        $element['format']['guidelines'][$format->format] = array(
          '#theme' => 'filter_guidelines',
          '#format' => $format,
        );
      }

      // Use the default format for this user if none was selected.
      if (!isset($element['#format'])) {
        $element['#format'] = filter_default_format($user);
      }

      $element['format']['format'] = array(
        '#type' => 'select',
        '#title' => t('Text format'),
        '#options' => $options,
        '#default_value' => $element['#format'],
        '#access' => count($formats) > 1,
        '#weight' => 10,
        '#attributes' => array('class' => array('filter-list')),
        '#parents' => array_merge($element['#parents'], array('format')),
      );

      $element['format']['help'] = array(
        '#type' => 'container',
        '#theme' => 'filter_tips_more_info',
        '#attributes' => array('class' => array('filter-help')),
        '#weight' => 0,
      );

      $all_formats = filter_formats();
      $format_exists = isset($all_formats[$element['#format']]);
      $user_has_access = isset($formats[$element['#format']]);
      $user_is_admin = user_access('administer filters');

      // If the stored format does not exist, administrators have to assign a new
      // format.
      if (!$format_exists && $user_is_admin) {
        $element['format']['format']['#required'] = TRUE;
        $element['format']['format']['#default_value'] = NULL;
        // Force access to the format selector (it may have been denied above if
        // the user only has access to a single format).
        $element['format']['format']['#access'] = TRUE;
      }
      // Disable this widget, if the fieldset .fieldset-wrapperuser is not allowed to use the stored format,
      // or if the stored format does not exist. The 'administer filters' permission
      // only grants access to the filter administration, not to all formats.
      elseif (!$user_has_access || !$format_exists) {
        // Overload default values into #value to make them unalterable.
        $element['value']['#value'] = $element['value']['#default_value'];
        $element['format']['format']['#value'] = $element['format']['format']['#default_value'];

        // Prepend #pre_render callback to replace field value with user notice
        // prior to rendering.
        $element['value'] += array('#pre_render' => array());
        array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');

        // Cosmetic adjustments.
        if (isset($element['value']['#rows'])) {
          $element['value']['#rows'] = 3;
        }
        $element['value']['#disabled'] = TRUE;
        $element['value']['#resizable'] = FALSE;

        // Hide the text format selector and any other child element (such as text
        // field's summary).
        foreach (element_children($element) as $key) {
          if ($key != 'value') {
            $element[$key]['#access'] = FALSE;
          }
        }
      }

      return $element;
    }

Answer: If the problem is just calling the same function over and over, you could use the following code.
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['node'] = &drupal_static(__FUNCTION__);
  }
  $node = &$drupal_static_fast['node'];
  if (empty($node)) {
    // The function was not called earlier.
    $node = menu_get_object();
    // …
  }

Generally speaking, an input filter should never try to understand in which context it is being called, if not from the given parameters. In fact, an input filter could be called:

In a page listing different nodes, which is what happens for the front page, for example
For each of the comments for a node, which could be show in the same page together the node itself
In every context a module calls check_markup()


Could it be that the drupal database doesn't work anymore after using jquery .load()

Question:
After using jquery .load() in drupal 7, the database doesn't seem to work

module

I want to use the database in the page "page" and echo the result back.
page
 $query = db_select('course_function', 'f');
  $query
      ->fields('f', array('id'))
      ->condition('f.chapter_id', $id, '=')
  ;
  $result = $query->execute();
  print_r($result);
  foreach ($result as $res) {
    $id = $res->id;
  }
echo $id;

But it does not work - do I need to use the PHP manner?
Answer: Most likely that drupal database API is not available in your page.php file because corresponding files are not included in it. What I usually do if I want to do stuff like this, is declaring a menu item:
function MYMODULE_menu(){
    $items['path/page'] = array(
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'title' => 'AJAX: Page callback'
    );
    return $items;
}

the code above adds a new page to drupal menu system and makes it available as: http://www.yoursite.com/path/page
and then in your function
function your_function_name() {
    $query = db_select('course_function', 'f');
    $query->fields('f', array('id'))
          ->condition('f.chapter_id', $id, '=');
    $result = $query->execute();
    print_r($result);
    foreach ($result as $res) {
        $id = $res->id;
    }
    echo $id;
    //You need to have exit in such callback functions to prevent drupal theme
    //functions from taking over the page processing
    exit;
}

Then in your javascript you can approach this page just like this:

Comment: Thank you verry much,
if I had more points, I would give it +1


High availability in SQL Server

Question: How can I implement High Availability in SQL Server 2005/2008 Standard.
Some people Recommended me to use third party tools such as double take.
What do you think.
Comment: I voted for Jason's answer below, and jl gives some good background. Can you describe more fully what you're doing now and what you'd like it to look like when it's all done?
Comment: Thanks, well we have two SQL servers machines and we want to add mirroring and high availability to them. and a web server who we like to connect it to the SQL servers through connection pooling technique.
in the bottom of line we have a site and we want it to have access to sql servers. if one falls down the other keeps working.
Thank you very much
Answer: SQL Server 2005 Standard edition supports 2 node clustering out of the box, as well as synchronous database mirroring.  You can also use third party tools to do this.
Answer: Jason is correct.  Keep in mind that the cluster shares a quorum drive.  A clear definition of "High Availablity" is necessary since the clustering is for the front end server on not the (presumably) external storage.
Double-take might be satisfactory for a disaster recovery scenario where the intent is to fail-over an entire database server to a separate physical site.  If memory serves me, you will have to map your current server to the secondary server so that Double-take knows where to place the files it copies.   A secondary server laid out exactly like your primary server makes this easier.  I believe there can also be some latency issues depending on the distance between the primary and secondary servers.  That being said Double-take will help you set up a test of the product to see how it performs.
Comment: Thanks for your answer it was very useful even the one from jason, a vote up from me.

High availability in SQL Server


Photo edit extensibility for UWP?

Question: In Silverlight it was once possible to register an app for the edit-dialog in the photo hub (https://msdn.microsoft.com/en-us/library/windows/apps/hh202966(v=vs.105).aspx).
Is there an UWP-equivalent now? Or is there any other way, my app can be started from within the photos hub?
Comment: I think [this](https://channel9.msdn.com/Series/A-Developers-Guide-to-Windows-10/11) is what you're after. Skip to **5:33**.
Comment: No, unfortunately not. I am looking for a way, that users can start my app from within the built-in photos app, not the other way round.
Answer: This functionality is not currently available in the Universal Platform. You can use the Windows Feedback tool ("Developer" section) or UserVoice to request that it be made available.
Comment: As suggested, I posted the idea to the UserVoice: https://wpdev.uservoice.com/forums/110705-universal-windows-platform/suggestions/9831597-allow-launching-a-specific-app-for-a-photo-from-wi

Photo edit extensibility for UWP?


I need to render just the submenu

Question: I need to print the current nodes submenu somewhere on the page. Inside my page.twig.html file I have this markup:

  {{menu_children}}

Inside my mytheme_preprocess_page() function I have this which rendering all the submenus.
function mytheme_preprocess_page(&$vars) {
  if ($vars['node']->id()) {
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $subtree = $menu_tree->build($element->subtree);
        $output = drupal_render($subtree);
        array_push($subtrees, $output);
      }
    }
    //dpm($subtrees);
  }

}

I was looking into using manipulators, but that wasn't working. How can I render JUST the current nodes submenu using this function? Again, what I have now is rendering all the submenus and I need just the current one.
Comment: @kenorb yup, you are correct. I answered my own question and you can see I did not use it.
Comment: You shouldn't use `drupal_render` inside the preprocess function. TWIG can render the subtree itself, like so `{( $subtree }}`.
Comment: @eyal good to know, but still, it is rendering all sub menus when I just need the current pages sub menu
Comment: I'm not familiar with the menu tree functionality. But when I encounter such problems then I open the relevant classes and start reading the code to understand how they work.
Comment: Btw. You should use `\Drupal::service('renderer')->renderRoot()` instead of `drupal_render()`.
Answer: I managed to grab just the child submenu of the current page. Each subtree has a getRouteParameters() fn that contains the node ID that it links to. I simply test if that route param node id == the current pages node id.
function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']) && is_numeric($vars['node']->id())) {
    $nid = $vars['node']->id();
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $routeId = $element->link->getRouteParameters()['node'];
        if ($routeId == $nid) {
          $vars['menu_children'] = $menu_tree->build($element->subtree);
        }
      }
    }
  }
}

I need to render just the submenu


Encontrar elemento html no css

Question: Eu preciso encontrar um elemento especifico do que está no meu código em html só que no css, exemplificando:
Da pra fazer tipo:
meuElemento [type=input]{
    color: #FFFFFF;
}

Só que a duvida está em como eu encontro um elemento como id="textoUm" do meu html por ID, não da pra simplesmente pegar e fazer  [id=textoUm].
Como eu consigo fazer isso? Já procurei diversos sites da internet e não consegui.
Answer: Usando o attr do css ficaria assim: (repare na construção do attr [id="textoUm"])

[id="textoUm"] {
 border: 2px solid red;
}

input {
 border: 2px solid black;
}
<input type="text" id="textoUm" value="com ID">
<input type="text" value="sem id">

OBS: Mas se vc vai colocar o css usando o ID não tem por que usar o attr[] crie direto a classe #textoUm {seu css}
Quando vc coloca o estilo no ID tem que que começar o nome por #textoUm {} e quando cria um estilo para por na classe tem que começar o nome por .textoUm {}
Link da documentação da Mozilla sobre o css attr https://developer.mozilla.org/pt-BR/docs/Web/CSS/attr está em PT e vai te ajudar vale a leitura
Comment: Pow, valeu ai pela ajuda era isso mesmo que eu queria.
Comment: Valeu, era isso mesmo, mas acho que eu não estava acertando a sintaxe, tipo eu estava tentando colocar em um `p` ai estava assim `p [id=textoUm]{` não da pra fazer esse tipo de seleção?
Comment: Da sim! Mas o certo seria assim  `p[id="textoUm"]` com o P sem espaço do [ e com o valor do ID entre aspas id="textoUm"
Comment: @Groot dmr tmj!
Answer: Quando você quer utilizar com id ou class é mais simples
Exemplo com id:
#textoUm{
    color: #FFFFFF;
}

Exemplo com class:
.textoUm{
    color: #FFFFFF;
}

Ou se quiser algo como, um input com a class 'textUm' por exemplo, você pode fazer assim:
input.textoUm{
    color: #FFFFFF;
}

Ou com algum id:
input#textoUm{
    color: #FFFFFF;
}

Um pequeno exemplo:

.texto{
  color: #f00;
}
#texto{
  color: #00f;
}
input.texto{
  color: #0f0;
}
input#texto{
  color: #ff0;
}
<input type="text" value="teste" class="texto" />
<input type="text" value="teste" id="texto" />

teste

teste

Comment: Nosso amigo hugocsl, postou uma resposta da forma que você deseja
Comment: Vlw a consideração jovem!
Comment: Sim, mas não tem como fazer do jeito que eu coloquei la?

Encontrar elemento html no css


Find a sequence of consecutive rows with the same value in a PySpark dataframe

Question: I have a dataframe ordered by date. Each row contains a "flag" column (values are 1 or 0). I want to find the sequences of 3 (or more) consecutive rows with the "flag" value equal to 1. The objective is to reset the "flag" value to 0 if it is not part of a 3 or more consecutive elements sequence with the :flag" being 1.
This is an example of the data:

date
flag

01-01-2022
1

02-01-2022
1

03-01-2022
1

04-01-2022
1

05-01-2022
0

06-01-2022
0

07-01-2022
1

08-01-2022
1

09-01-2022
0

10-01-2022
1

We have to keep value 1 only for the first 4 rows, as they constitute a sequence of four rows (more than 3) with a 1 in the flag. The desired output should be:

date
flag

01-01-2022
1

02-01-2022
1

03-01-2022
1

04-01-2022
1

05-01-2022
0

06-01-2022
0

07-01-2022
0

08-01-2022
0

09-01-2022
0

10-01-2022
0

I thought that maybe it makes sense to use the lag function based on the previous element but not sure about how efficient it is in PySpark.
Comment: does this dataframe have any groups, like an ID or name?
Comment: the one I'll work with yes, it has a name field that we should use to consider only consecutive appearances only for that group
Answer: You will need to use several window functions. Counting flags in 3 different windows: -2:0, -1:1, 0:-2. If the sum of at least one from these is 3, then you have 3 consecutive 1's.
In the following script I assumed tat your dates are stored in the string data type, so I have used a column expression date to read true dates from strings. If your dates are not in string format, you should not use that line.
Input:
from pyspark.sql import functions as F, Window as W
df = spark.createDataFrame(
    [('01-01-2022', 1),
     ('02-01-2022', 1),
     ('03-01-2022', 1),
     ('04-01-2022', 1),
     ('05-01-2022', 0),
     ('06-01-2022', 0),
     ('07-01-2022', 1),
     ('08-01-2022', 1),
     ('09-01-2022', 0),
     ('10-01-2022', 1)],
    ['date', 'flag'])

Script:
date = F.to_date('date', 'dd-MM-yyyy')
cond1 = F.sum('flag').over(W.orderBy(date).rowsBetween(-2, 0)) == 3
cond2 = F.sum('flag').over(W.orderBy(date).rowsBetween(-1, 1)) == 3
cond3 = F.sum('flag').over(W.orderBy(date).rowsBetween(0, 2)) == 3
df = df.withColumn('flag', (cond1 | cond2 | cond3).cast('long'))

df.show()
# +----------+----+
# |      date|flag|
# +----------+----+
# |01-01-2022|   1|
# |02-01-2022|   1|
# |03-01-2022|   1|
# |04-01-2022|   1|
# |05-01-2022|   0|
# |06-01-2022|   0|
# |07-01-2022|   0|
# |08-01-2022|   0|
# |09-01-2022|   0|
# |10-01-2022|   0|
# +----------+----+

Comment: This worked! In order to generalize it for any number of elements in a row I did:

`conds_list = [F.sum('flag').over(Window.orderBy('date').rowsBetween(-N +1 + i, i)) == N for i in range(0, N)]

cond = reduce(lambda x, y: x | y, conds_list)

df = df.withColumn('flag', cond.cast('long'))
`
Comment: That's a clever approach :) I was thinking about `reduce`, but didn't want to complicate the simple answer. It's cool that you did it yourself.


On a decreasing sequence of compact subsets of a Hausdorff topological space

Question: I have the following exercise to solve:

Exercise. Let $ (E,\tau) $ be a Hausdorff topological space and
    $ (K_{n})_{n \in \mathbb{N}} $ a decreasing sequence of non-empty
    $ \tau $-compact subsets of $ E $. Prove that
    $ \displaystyle K \stackrel{\text{df}}{=} \bigcap_{n \in \mathbb{N}} K_{n} $ is
    $ \tau $-compact.
Suppose that there exists a $ \tau $-open subset $ U $ of $ E $ such that
    $ K \subset U $. Then prove that there exists an $ n_{0} \in \mathbb{N} $ such
    that $ K_{n} \subseteq U $ for all $ n \in \mathbb{N}_{\geq n_{0}} $.

To prove that $ K $ is $ \tau $-compact, I mentioned that as the $ K_{n} $'s are $ \tau $-compact, they are $ \tau $-closed, so $ K $ is a $ \tau $-closed subset of $ E $ contained within a $ \tau $-compact subset of $ E $. Therefore, $ K $ is $ \tau $-compact.

However, I don't know how to solve the second question or how to see that $ K \neq \varnothing $. Could someone please suggest another method to prove that $ K $ is $ \tau $-compact?
Thank you!
Comment: Is "separated" another word for Hausdorff?
Answer: This post was re-written because the OP apparently had trouble understanding the original version. The argument should be crystal clear now.

Proof that $ K $ is a compact subset of $ E $.
$ K $ is an intersection of closed subsets of $ E $ (in a Hausdorff space, compact subsets are closed), so $ K $ itself is a closed subset by the axioms of a topology. Then as $ K \subseteq K_{1} $ and $ K_{1} $ is a compact subset, it follows that $ K $ is a compact subset as well (a closed subset of a compact subset is compact). $ \quad \clubsuit $

Lemma. $ K $ is non-empty.
Proof
Assume for the sake of contradiction that $ \displaystyle K = \bigcap_{n = 1}^{\infty} K_{n} = \varnothing $. Then by de Morgan's Laws, we have
\begin{align}
    K_{1}
& = K_{1} \setminus \varnothing \\
& = K_{1} \bigg\backslash \bigcap_{n = 1}^{\infty} K_{n} \\
& = \bigcup_{n = 1}^{\infty} (K_{1} \setminus K_{n}).
\end{align}
Let $ n \in \mathbb{N} $. Observe that $ K_{1} \setminus K_{n} = K_{1} \cap (E \setminus K_{n}) $, which shows that $ K_{1} \setminus K_{n} $ is the intersection of $ K_{1} $ with an open subset of $ E $. By definition, $ K_{1} \setminus K_{n} $ is thus a $ K_{1} $-open subset of $ K_{1} $.
Hence, $ \mathcal{O} \stackrel{\text{df}}{=} \{ K_{1} \setminus K_{n} \}_{n = 1}^{\infty} $ is a $ K_{1} $-open cover of $ K_{1} $, and as $ K_{1} $ is a compact topological space, we can find natural numbers $ n_{1},\ldots,n_{k} $ such that $ \mathcal{O}' \stackrel{\text{df}}{=} \{ K_{1} \setminus K_{n_{i}} \}_{i = 1}^{k} $ is a finite $ K_{1} $-open subcover of $ K_{1} $. Without any loss of generality, we may assume that $ n_{1} < \ldots < n_{k} $, which yields
\begin{align}
             K_{1}
& =          \bigcup_{i = 1}^{k} (K_{1} \setminus K_{n_{i}}) \\
& =          K_{1} \bigg\backslash \bigcap_{i = 1}^{k} K_{n_{i}} \qquad
             (\text{By de Morgan's Laws again.}) \\
& =          K_{1} \setminus K_{n_{k}} \qquad
             (\text{As $ K_{n_{k}} \subseteq \ldots \subseteq K_{n_{1}} $.}) \\
& \subsetneq K_{1}. \qquad
(\text{As $ K_{n_{k}} \subseteq K_{1} $ and $ K_{n_{k}} \neq \varnothing $ by hypothesis.})
\end{align}
We thus have the contradiction $ K_{1} \subsetneq K_{1} $, and so our assumption that $ K $ is empty is truly rubbish. Therefore, $ K $ is non-empty. $ \quad \spadesuit $

Theorem. If $ K \subseteq U $ for some open subset $ U $ of $ E $, then there exists an $ n_{0} \in \mathbb{N} $ such that $ K_{n} \subseteq U $ for all $ n \in \mathbb{N}_{\geq n_{0}} $.
Proof
Suppose that $ K \subseteq U $ for some open subset $ U $ of $ E $. Then
\begin{align}
    \varnothing
& = K \setminus U \\
& = \left( \bigcap_{n = 1}^{\infty} K_{n} \right) \bigg\backslash U \\
& = \bigcap_{n = 1}^{\infty} (K_{n} \setminus U).
\end{align}
Let $ n \in \mathbb{N} $. Observe that $ K_{n} \setminus U = K_{n} \cap (E \setminus U) $, which implies that $ K_{n} $ is an intersection of two closed subsets of $ E $. Hence, $ K_{n} \setminus U $ is a closed subset, and as it is at the same time contained inside the compact subset $ K_{n} $, it is a compact subset as well.
We now see that $ (K_{n} \setminus U)_{n = 1}^{\infty} $ is a decreasing sequence of compact subsets of $ E $ whose intersection is empty. The lemma above tells us that if all members of this sequence were non-empty, then their intersection would be non-empty as well. However, this is not the case! Hence, some member of the sequence must be empty, i.e., $ K_{n_{0}} \setminus U = \varnothing $ for some $ n_{0} \in \mathbb{N} $, or equivalently, $ K_{n_{0}} \subseteq U $. Then as
$$
          \ldots
\subseteq K_{n_{0} + 3}
\subseteq K_{n_{0} + 2}
\subseteq K_{n_{0} + 1}
\subseteq K_{n_{0}}
\subseteq U,
$$
we conclude that $ K_{n} \subseteq U $ for all $ n \in \mathbb{N}_{\geq n_{0}} $. $ \quad \blacksquare $
Comment: i know this i need an other method and a hint or a solution for the seconde question and why $K\neq\emptyset$
Comment: I see. I had a hard time separating what was being asked from what were your attempts at the problem.
Comment: @Vrouvrou: I have added more details concerning the second question.
Comment: I don't understand why
$\bigcap_{i = 1}^{k} K_{n_{i}}
=  K_{n_{k}}$ we have that $n_1<n_k$ so $K_{n_k}\subset K_{n_1}$ and if $K_{n_k}=K_1$ we proved nothing...
Comment: I forgot to add the condition that $ n_{1} < n_{2} < \ldots < n_{k} $, which can easily be arranged. You will then obtain
$$
\bigcap_{i = 1}^{k} K_{n_{i}} = K_{n_{k}}.
$$
If $ K_{n_{k}} = K_{1} $, then it does not damage my argument because I am aiming for a contradiction with $ K_{1} $, which is non-empty, on the extreme left and something strictly smaller than $ K_{1} $ on the extreme right. If $ K_{n_{k}} = K_{1} $, then even better because I now get $ K_{1} = \varnothing $, which is still a contradiction.
Comment: The contradiction is with the $K_1=K_1\setminus K_{n_k}\subset K_1$ and $K_1\neq \emptyset$ right ?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/21359/discussion-between-vrouvrou-and-berrick-fillmore).
Comment: if there exists $n_0\in \mathbb{N}$ such that $K_{n_0}\subset U$ why $\forall n\geq n_0, K_{n}\subset U$ ? please
Comment: @Vrouvrou Think about it.  The $K_{n}$'s are nested, which means $K_{1} \supseteq K_{2} \supseteq K_{3} \supseteq ...$.  Now, if $U \supseteq K_{n_{0}}$, then since for all $n \geq n_{0}$, $K_{n_{0}} \supseteq K_{n}$, it follows that if $U \supseteq K_{n_{0}}$, $U \supseteq K_{n}$ for all $n \geq n_{0}$.
Comment: @Vrouvrou: Yes, you're right. We have $ K_{1} \neq \varnothing $ on the extreme left, and we have $ K_{1} \setminus K_{n_{k}} $, which is *strictly smaller than* $ K_{1} $, on the extreme right. Why $ K_{1} \setminus K_{n_{k}} $ should be strictly smaller than $ K_{1} $ is because $ K_{n_{k}} $ is a non-empty subset of $ K_{1} $, by your assumption that $ (K_{n})_{n \in \mathbb{N}} $ is a decreasing sequence of non-empty sets. The contradiction we have here is therefore that of a set being equal to a strict subset of itself.
Comment: @Vrouvrou: Regarding your second point, simply observe that
$$
          \ldots
\subseteq K_{n_{0} + 2}
\subseteq K_{n_{0} + 1}
\subseteq K_{n_{0}}
\subseteq U.
$$
When we have $ A \subseteq B \subseteq C $, shouldn't $ A \subseteq C $? This is basic set theory. :)
Comment: why $K_1\setminus K_n$ is open ?
Comment: @BerrickFillmore $K_1\setminus K_n$ is open in $K_1$ or in $E$ ?
Comment: @Vrouvrou: $ K_{1} \setminus K_{n} $ is $ K_{1} $-open (i.e., open in $ K_{1} $ with respect to the subspace topology on $ K_{1} $ inherited from $ E $), not $ E $-open. Observe that
$$
  K_{1} \setminus K_{n}
= K_{1} \cap
  \underbrace{(E \setminus K_{n})}_{\text{$ E $-open subset}},
$$
so $ K_{1} \setminus K_{n} $ is $ K_{1} $-open. However, $ K_{1} $, being a compact subset of $ E $, is a compact topological space in its own right, so as $ (K_{1} \setminus K_{n})_{n \in \mathbb{N}} $ is a $ K_{1} $-open cover of $ K_{1} $, we can extract a finite $ K_{1} $-open sub-cover.
Comment: @BerrickFillmore thank you
Comment: @BerrickFillmore for the question "Suppose that there exist an open set $U\subset E$ such that $K\subset U$. prove that there exist $n_0\in \mathbb{N}$ such that $\forall n\geq n_0, K_n\subset U$ " i found a proof in a book it says: By contradiction suppose that for all $n_0\in \mathbb{N}$ there exists $n\geq n_0$ and $K_n\not\subset U$ then for all $n\in \N$ there exists an element$x_n\in K_n$ and $x_n\in C_E U$ closed
Comment: because $(K_n)$ is decreasing then $(x_n)\subset K_0$ witch is compact then $(x_n)$ has a limit point in $\overline{\cap K_n}=\cap K_n\subset \Omega$ but $(x_n)$ is in $C_e \Omega$ contradiction .
Comment: i dont understand the relation between the fact that $(x_n)\subset K_0$ and the fact that it's limit point must be in $\overline{\cap K_n}$ ? thank you
Comment: I'm confused because you're using non-standard terminology and I don't know what $ \Omega $ is, but here's what I think about this other argument.

Let $ x $ be a limit point of $ (x_{n})_{n \in \mathbb{N}} $. By definition, $ x $ is the limit of a subsequence $ (x_{n_{k}})_{k \in \mathbb{N}} $ of $ (x_{n})_{n \in \mathbb{N}} $. Now, for each $ N \in \mathbb{N} $, as all members of this subsequence, **after some sufficiently large index**, must lie in $ K_{N} $, we see that $ x $ is the limit of some subsequence of $ (x_{n})_{n \in \mathbb{N}} $ whose members all lie in $ K_{N} $.
Comment: Then as $ K_{N} $ is a closed subset of $ E $, we automatically have $ x \in K_{N} $. However, this is true for all $ N \in \mathbb{N} $, so $ \displaystyle x \in \bigcap_{n = 1}^{\infty} K_{n} = K \subseteq U $.

On the other hand, $ x_{n} \in K_{0} \setminus U $ for all $ n \in \mathbb{N} $, and as $ K_{0} \setminus U $ is also a closed subset of $ E $, we must have $ x \in K_{0} \setminus U $. Therefore, we obtain $ x \in U $ **and** $ x \notin U $, which is a contradiction.


Isolated points of set

Question: For a set $S \in \mathbb{R}^n$, define $S^{\bullet} = \{x \in S: \text{x is not limit point of S}\}$ (i.e. $S^{\bullet}$ is the set of all isolated points of $S$). Prove or disprove the following:
(a) For every $A \in \mathbb{R}^n$, $\bar {A^{0}} = \bar {A}$
(b) For every $A \in \mathbb{R}^n$, $(A^{\bullet})^{\bullet} = A^{\bullet}$
(c) Define sequence of subsets $A_k \in \mathbb{R}^n$ such that for each $k \in \mathbb{N}$, $A_k \setminus A_k' =\emptyset$. Then, $B = \bigcap_{k=1}^{\infty} A_k$ satisfies $B\setminus B' = \emptyset$
I can't think of any counterexample nor can't prove any of them. Any help is appreciated :) !
Comment: I've replaced `S^.` with `S^\bullet` as the full-stop was barely visible
Comment: Please note $A\subset \mathbb{R}^n$ or $A\in P(\mathbb{R}^n)$ but not $A\in \mathbb{R}^n$
Answer: (a) False. Simply find a non-empty set with no inner points. This should be doable.
(b) True. You should prove that if $B\subset A$ and $x\in B$, $x$ is a limit point in $B$ implies it is a limit point of $A$. This means that if $x\in A^\bullet$ is a limit point in $A^\bullet$, it would be a limit point of $A$, and thus it cannot lie in $A^\bullet$ as we removed all limit points, contradiction. Thus $A^\bullet$ has no limit points, and gives the desired identity.
(c) True. Take any point $x\in B$. Then $x\in A_i$ for all $i$, and this implies $x\in A_i'$ for all $i$. Then $x\in B'$, and so we see $B\subset B'$, i.e. $B\setminus B'=\emptyset$.
Comment: the reason x∈A′i  for all i. Then x∈B′,?
Comment: I am assuming you define $B'=\bigcap_{k=1}^\infty  A_k'$, no? Then this is by definition.

Isolated points of set


Testing constructor initialization list

Question: I am working on a test which checks if all class attributes are initialized in a constructor.
My current solution works for non pointer attributes:
void CSplitVectorTest::TestConstructorInitialization()
{
    const size_t memorySize = sizeof(CSplitVector);
    char* pBuffer1 = (char*) malloc(memorySize);
    char* pBuffer2 = (char*) malloc(memorySize);
    memset(pBuffer1,'?',memorySize);
    memset(pBuffer2,'-',memorySize);
    new(pBuffer1) CSplitVector;
    new(pBuffer2) CSplitVector;
    const bool bObjectsAreEqual = memcmp(pBuffer1,pBuffer2,memorySize)==0;
    if (!TEST(bObjectsAreEqual))
    {
        COMMENT("Constructor initialization list not complete!");
    }
    free(pBuffer1);
    free(pBuffer2);
}

Do you have an idea how could it be improved to test if pointers are initialized?
Comment: Your approach wouldn't work. The compiler may insert padding between the data members.
Comment: @Lol4t0: bytes not occupied by any data member would remain `?` in the 1st buffer and `-` in the 2nd
Comment: What do you mean it does not work for pointers?
Comment: @Marek Ah yes of course. Augmented my answer below (last paragraph).
Comment: For pointers, whenever I can I use smart pointers, otherwise I have the safe pointer of the controlled_vars: http://snapwebsites.org/project/controlled-vars and I use it for all basic data types too (int, char, etc.) This way everything will be initialized no matter what. Especially, if you marked the variables as "need init" then you HAVE to have an initializer in your class. So there is no way you'd miss that.
Comment: @Andrey: Do you think #pragma pack(1) should resolve this issue for test purpose only?
Answer: Your test checks whether every byte of the object has been written over by the constructor. As a straight memory check it looks OK, although if the class contains other objects which don't necessarily initialise themselves fully, you may be in trouble.
That said, my main question would be: Is it really an effective test? For example, is it critical that every attribute in the CSplitVector class is initialised by the initialisation list? Do you perhaps have some which may not need to be initialised at this point? Also, how about checking whether the attributes are set to values that you'd expect?
Answer: Instead of comparing byte by byte, you probably should use the right padding or word size, and test if any byte of each word got initialized. That way you will probably get around compiler using padding and constructor leaving uninitialized bytes between padded shorter-than-word fields.
To test the real padding size, shooting from the hip, following code should do it pretty reliably:
struct PaddingTest {
  volatile char c; // volatile probably not needed, but will not hurt either
  volatile int i;

  static int getCharPadding() {
    PaddingTest *t = new PaddingTest;
    int diff = (int)(&(t->i)) - (int)&((t->c));
    delete t;
    return diff;
  }
}

Edit: You still need the two objects, but you no longer compare them to each others, you just compare each initialized data to the memset value, and if either object has any change, it means the word got touched (also on the other one, it's just chance that it got initialized to same value you memset).
Answer: I found a solution for mentioned problems, tested it with initialized/not initialized pointers and with different length types.
In test header I added #pragma pack(1) (I am working on gcc)
#pragma pack(1)
#include <CSplitVector>

Test got a little bit complicated:
void CSplitVectorTest::TestConstructorInitialization()
{
    const size_t memorySize = sizeof(CSplitVector);
    char* pBuffer = (char*) malloc(memorySize);
    memset(pBuffer,'?',memorySize);
    CSplitVector* pSplitVector = new(pBuffer) CSplitVector;

    // find pointers for all '?'
    QList<char*> aFound;
    char* pFoundChar = (char*) memchr(pBuffer,'?',memorySize);
    while (pFoundChar)
    {
        aFound.append(pFoundChar);
        char* pStartFrom = pFoundChar+1;
        pFoundChar = (char*) memchr(pStartFrom,'?',memorySize-(int)(pStartFrom-pBuffer));
    }
    // if there are any '?'....
    if (aFound.count())
    {
        // allocate the same area with '-'...
        pSplitVector->~CSplitVector();
        memset(pBuffer,'-',memorySize);
        pSplitVector = new(pBuffer) CSplitVector;
        // and check if places found before contain '-'
        while (aFound.count())
        {
            pFoundChar = aFound.takeFirst();
            if (*pFoundChar=='-')
            {
                // if yes then class has uninitialized attribute
                TEST_FAILED("Constructor initialization list not complete!");
                pSplitVector->~CSplitVector();
                free(pBuffer);
                return;
            }
        }
    }
    // if no then all attributes are initialized
    pSplitVector->~CSplitVector();
    free(pBuffer);
    TEST(true);
}

Feel free to point any flaws in this solution.

Testing constructor initialization list


debian: creating user with password with one command

Question: I need to create a user with password in a shell script, but passwd wants me to enter the password twice. Is there a way to create a user with password in one command?
Comment: check this: http://stackoverflow.com/questions/714915/using-the-passwd-command-from-within-a-shell-script
Answer: You can use this command.
echo -e "password\password\n\n\n\n\n\n\n\n"|adduser username
Please replace the 'password' with the desired password and 'username' with the username you need to create.
Regards,
Ajo
Answer: If you want to create a user in a shell script, you should use useradd -p which takes the encrypted form of the password. That way, you don't have have the password in cleartext.
Note that on debian, users are normally added with adduser, which has various bits of policy configured in /etc/adduser.conf. useradd is the "raw" command, so you need to take care to get group membership and homedir permissiones as you expect them.


Contact of a player with the net

Question: The FIVB rules state that:
(11.3.1)
Contact with the net by a player is not a fault, unless it interferes with the play.
(11.4.4)
A player interferes with the opponent's play by (amongst others):

touching the top band of the net or the top 80 cm of the antenna during his/her action of playing the ball, or
taking support from the net simultaneously with playing the ball, or
creating an advantage over the opponent by touching the net, or
making actions which hinder an opponent's legitimate attempt to
play the ball.

The only criterion that is clear to me here is the one about touching the top band of the net. What exactly does it mean to interefere with the play or to get an advantage over the opponent?
Suppose the following sample situations:

An attacker hits the ball and then, while landing back on the court, touches the middle part of the net (not the top band) with his body or with his hand.
Same as before, but this time a blocker touches the net while landing back on the court.

It seems to me that in all these cases the player would get an advantage in comparison to situations in which they would not touch the net at all, because then they would have to play more carefully and less aggressively, resulting in a less effective hit.
What are the rules that one should follow to distinguish valid and invalid net contacts?
Answer: Update: The below answer was valid at the time it was posted, however, the rules changed dramatically, and now any contact with the net by a player between the antennae, during the action of playing the ball, is a fault. (With explicit inclusion of the take-off and landing in the action of playing the ball.) Therefore, per the current rules, both sample situations are now faults.

These are perfect examples of cases where touching the net is not a fault. The current net-touch rules are constructed so that almost no inadvertent net touches are faults.
Simplifying it a bit, touching the net is a fault only when

while playing the ball, you touch the top band (or the top part of the antenna), or
you touch the net intentionally to gain an unfair advantage (like: pulling the net down to help your attacker, forcing the ball flying into the net on the other side of the court to rebound directly to the ground, etc.).

The FIVB Rules of the Game Volleyball Casebook, 2014 edition lists several examples (examples 3.13–3.22; pages 11–12), where it is made clear that:

Slightly touching the body of the net is not a fault.
When an attacker touches the band while faking an attack while the ball is on the other side of the court, it is not a fault (as this was not "during action of playing the ball").
The same is true for blocking: When a blocker touches the band while trying to block a fake attack while the ball is on the other side of the court, it is not a fault. (But touching the band while trying to block the attacking player is a fault, no matter whether the blocker touched the ball or not.)

Also, I especially recommend watching teaching videos for referees available as a part of the FIVB Multimedia Teaching Material for Referees: First, click Net Rule Move in the left menu and watch the video. Then, navigate to rule 11 in the contents menu and click Jump to the videos to see a list of applicable video examples.
Answer: Mormegil's answer was completely correct at the time it was posted; however, the FIVB Congress of November 2014 amended the rule such that any contact with the net is a fault (which is actually a reversion to the earlier rules).
This rule is likely to be applied to any competitions starting in 2015, although I believe national federations have a small amount of leeway in this.

Contact of a player with the net


Fiz esse código e tá rodando, mas a parte do else não funciona. Quando digito uma entrada invalida dá erro no meu código invés de mostrar a mensagem

Question: print("BEM VINDO!")
print("*" * 40)
player_1 = input("Player 1: Qual o seu Nome? ")
player_2 = input("Player 2: Qual o seu Nome? ")
entradasValidas = ('Pedra','Papel', 'Tesoura', 'Lagarto', 'Esponja')
print('''Considerando as seguintes escolhas como válidas:
[0] Pedra
[1] Papel
[2] Tesoura
[3] Lagarto
[4] Esponja''')
player_1 = int(input("Player 1: Qual sua Escolha? "))
player_2 = int(input("Player 2: Qual sua Escolha? "))
print("*" * 40)
print("Player_1 Escolheu: {}".format(entradasValidas[player_1]))
print("Player_2 Escolheu: {}".format(entradasValidas[player_2]))
print("*" * 40)
if player_1 == 0: # jogador 1 jogou Pedra
    if player_2 == 0:
      print("Temos um Empate!")
    elif player_2 == 1 or player_2 == 4:
      print("O Jogador 2 Venceu!")
    elif player_2 == 2 or player_2 == 3:
      print("O Jogador 1 Venceu!")
    else:
      print("Ops! Essa jodada está inválida. Tente novamente!")

if player_1 == 1: # jogador 1 jogou Papel
    if player_2 == 0 or player_2 == 4:
      print("O Jogador 1 Venceu!")
    elif player_2 == 1:
      print("Temos um Empate!")
    elif player_2 == 2 or player_2 == 3:
      print("O Jogador 2 Venceu!")
    else:
      print("Ops! Essa jodada está inválida. Tente novamente!")

if player_1 == 2: # jogador 1 jogou Tesoura
    if player_2 == 0:
      print("O Jogador 2 Venceu!")
    elif player_2 == 1 or player_2 == 3 or player_2 == 4:
      print("O Jogador 1 Venceu!")
    elif player_2 == 2:
      print("Temos um Empate!")
    else:
      print("Ops! Essa jodada está inválida. Tente novamente!")

if player_1 == 3: # jogador 1 jogou Lagarto
    if player_2 == 0 or player_2 == 2:
      print("O Jogador 2 Venceu!")
    elif player_2 == 1 or player_2 == 4:
      print("O jogador 1 Venceu!")
    elif player_2 == 3:
      print("Temos um Empate!")
    else:
      print("Ops! Essa jodada está inválida. Tente novamente!")

if player_1 == 4: # jogador 1 jogou Esponja
    if player_2 == 0 or player_2 == 2:
      print("O Jogador 1 Venceu!")
    elif player_2 == 1 or player_2 == 3:
      print("O Jogador 2 Venceu!")
    elif player_2 == 4:
      print("Temos um Empate!")
    else:
      print("Ops! Essa jodada está inválida. Tente novamente!")

print("")
print("*" * 40)

Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a melhor por causa disso. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça a sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045) ([versão curta](https://pt.meta.stackoverflow.com/q/8089/101)). Lei a [Como debugar programas pequenos](https://pt.meta.stackoverflow.com/q/7785/137387) e faça o nosso [tour].
Answer: Eu fiz um jokenpo há um tempo atras, veja se te ajuda
from random import randint
import time
itens=('\u270A', '\u270B', '\u270C\uFE0F')
computador = randint(0, 2)
print(' \U0001f3b2 \U0001f3ae'*5)
jogador = int(input('''   Escolha sua jogada:
   [ 0 ] \u270A
   [ 1 ] \u270B
   [ 2 ] \u270C\uFE0F\n   Sua escolha: '''))
 print('-='*15)
 print('LOADING', end='')
 time.sleep(1)
 print(' .', end='')
 time.sleep(1)
 print(' .', end='')
 time.sleep(1)
 print(' .')
 print('Já escolhi, VAMOS?')
 time.sleep(1.5)
 print('JO')
 time.sleep(1.2)
 print('KEN')
 time.sleep(1.5)
 print('POOO')
 print(itens[computador])
 time.sleep(1)
 if computador == 0:
   if jogador == 0:
     print('EMPATE!')
   elif jogador == 1:
       print('JOGADOR VENCEU!')
   else:
       print('COMPUTADOR VENCEU!')
 if computador == 1:
   if jogador == 0:
     print('COMPUTADOR VENCEU!')
   elif jogador == 1:
       print('EMPATE!')
   else:
       print('JOGADOR VENCEU!')
 if computador == 2:
   if jogador == 0:
     print('JOGADOR VENCEU!')
   elif jogador == 1:
     print('COMPUTADOR VENCEU!')
   else:
     print('EMPATE!')

Comment: Obrigada, me ajudou bastante *-*
Consegui implementar algumas coisas no meu código pra ficar mais legal com isso
Answer: Creio que a condição está sem sentido, não há um laço de repetição, depois do tente novamente de qualquer forma o programa encerra.
Coloquei um while True e um tratamento para exceção try except no início, assim só cai nas condições após a entrada de dados correta por parte do usuário.
print("BEM VINDO!")
print("*" * 40)
jog_1 = input("Player 1: Qual o seu Nome? ")
jog_2 = input("Player 2: Qual o seu Nome? ")
entradasValidas = ['Pedra', 'Papel', 'Tesoura', 'Lagarto', 'Esponja']
print('''Considerando as seguintes escolhas como válidas:
[0] Pedra
[1] Papel
[2] Tesoura
[3] Lagarto
[4] Esponja''')
while True:
    try:
        player_1 = int(input("{}: Qual sua Escolha? ".format(jog_1)))
        player_2 = int(input("{}: Qual sua Escolha? ".format(jog_2)))
        if player_1 != 0 and player_1 != 1 and player_1 != 2 and player_1 != 3 and player_1 != 4:
            print('Jogada Inválida {}'.format(jog_1))
        elif player_2 != 0 and player_2 != 1 and player_2 != 2 and player_2 != 3 and player_2 != 4:
            print('Jogada Inválida {}'.format(jog_2))
        else:
            break
    except ValueError:
        print('Jogada Inválida')
        continue
print("*" * 40)
print("Player_1 Escolheu: {}".format(entradasValidas[player_1]))
print("Player_2 Escolheu: {}".format(entradasValidas[player_2]))
print("*" * 40)
if player_1 == 0:  # jogador 1 jogou Pedra
    if player_2 == 0:
        print("Temos um Empate!")
    elif player_2 == 1 or player_2 == 4:
        print("O Jogador 2 Venceu!")
    elif player_2 == 2 or player_2 == 3:
        print("O Jogador 1 Venceu!")

if player_1 == 1:  # jogador 1 jogou Papel
    if player_2 == 0 or player_2 == 4:
        print("O Jogador 1 Venceu!")
    elif player_2 == 1:
        print("Temos um Empate!")
    elif player_2 == 2 or player_2 == 3:
        print("O Jogador 2 Venceu!")

if player_1 == 2:  # jogador 1 jogou Tesoura
    if player_2 == 0:
        print("O Jogador 2 Venceu!")
    elif player_2 == 1 or player_2 == 3 or player_2 == 4:
        print("O Jogador 1 Venceu!")
    elif player_2 == 2:
        print("Temos um Empate!")

if player_1 == 3:  # jogador 1 jogou Lagarto
    if player_2 == 0 or player_2 == 2:
        print("O Jogador 2 Venceu!")
    elif player_2 == 1 or player_2 == 4:
        print("O jogador 1 Venceu!")
    elif player_2 == 3:
        print("Temos um Empate!")

if player_1 == 4:  # jogador 1 jogou Esponja
    if player_2 == 0 or player_2 == 2:
        print("O Jogador 1 Venceu!")
    elif player_2 == 1 or player_2 == 3:
        print("O Jogador 2 Venceu!")
    elif player_2 == 4:
        print("Temos um Empate!")

print("")
print("*" * 40)

Comment: Muito Obrigada! Eu tava achando que precisava colocar um loop mesmo, mas não estava conseguindo implementar. Me ajudou muito! Consegui até criar outro loop para jogar novamente kkk


Anybody have experience with using Nexenta?

Question: I'm evaluating the Nexenta platform to hopefully one day replace our legacy file servers.  I would primarily use it as a CIFS server in an Active Directory environment.

Anyone out there have any experience using it?  Good?  Bad?
Which hardware vendor did you go with?  Why?  Did you build your own (Supermicro) or go prebuilt?
Comment: Did you even end up going with a Nexenta based solution for your CIFS sharing?
Comment: Not yet, I am still testing it out.  So far, I have CIFS working in AD, but still trying to get a feel for ACLs.
Comment: I can't add comments directly since I don't have enough 'karma' yet. @3dinfluence: Not that I am aware of. AD users get unix attributes via ACL's and idmapping. I'm presently running 3.0 but started with 2.2. CIFS/AD works for SOME users just fine, but I've helped multitudes of people diagnose and work around kerberos bugs that interweave with CIFS. It's not fun nor very stable. Though I guess technically it's not even Nexenta's fault since they are OSOL bugs but since I'm a paying user I think they should at least consider fixing the bugs themselves and uploading the code to the OpenSolaris O
Answer: I can't comment on Nexenta's AD/CIFS implementation as I've just started using that feature, but we have been using it as our primary storage for just over a year now, with an appliance here in the office and one in the datacenter. I assume you're talking about the NexentaStor appliance platform, and not the Nexenta distribution.
1 -  It has been great to use, though we are primarily using it for NFS.  Depending on the system configuration, it is very fast and reliable.  In our (crappy) office, we have had quite a few power outages, and it never skips a step.  We use it with both OracleVM (Xen) and VMware esx, it has been great for both.  The only caveat, at least with NFS, is to be sure to have dns setup and fully populated with all your servers.
2 - I would recommend going through a vendor, having both built our own (in the office) and purchased from a reseller (PogoLinux appliance in the datacenter).  Everything works fine on the one we spec'ed out ourselves, but performance could be better, and we forgot a couple things up front.  We didn't spec out OOBM on our home-built one, so that has bit us a couple times and necessitated a couple late night drives to the office.  We also chose a storage controller (sata JBOD) that I've since heard is very slow compared to other stuff out there.
Our experience with PogoLinux has been great, the solution we created them has been top-notch performance wise, and their support is a great addition to normal nexenta support as they have a lot of hands on experience with the hardware, software, and storage implementations in general.  Price-wise, it was very close to building it ourselves, so the extra 2% or so we spent with PogoLinux has been well worth it.
Comment: +1 Pogo Linux is indeed a fantastic vendor to work with, particularly for Nexenta storage servers.
Answer: Sadly there is a massive stack of Kerberos and AD bugs in opensolaris (and nexenta) that are plaguing MS AD users. I've been cataloging mine since Dec 09. I wouldn't count on using CIFS reliably with AD at this point.
Comment: Can you install Samba and use it for CIFS and Windbind for AD auth?  I know it's possible to do that on OpenSolaris....but I don't have any experience with Nexenta.  I'm not sure that will solve any of the Kerberos issues though as I know that Sun/Solaris has it's own implementation of it.  Which from a client point of view is supposed to be compatible with Kerberos MIT.
Comment: That is a major bummer, because that's pretty much all I wanted to use it for.  Have you tried Nexenta 3.0?  In my environment, I would have to use nested groups (AD users in local groups).  I've been told by Nexenta support that this would work.  Another concern I have is the AD users don't have unix attributes.  I'm assuming Nexenta will derive it's own?
Answer: I was quite impressed with how well nexanta fulfilled it's primary purpose, pulling in data from other systems and snapshotting it.
I have gotten extremely high dedup/compress rate, 3.67x with .5T of data.
Any linux/bsd system will lag behind on zfs fixes compared to a opensolaris version.
I for one without knowing much about the cifs in opensolaris would trust it as a samba server.
Answer: Of course one way to get around this is to use a separate device for the L2ARC.  As for stability and production readiness - http://www.informationweek.com/news/software/open_source/showArticle.jhtml?articleID=227600191&subSection=Hosted+Software - ultimately will be 1PB - mission critical stuff.
Both Illumos and OpenIndiana will provide a solid base for the future of OpenSolaris I think. It maybe that they merge at some point to pool their resources.
I know Nexenta are hiring CIFS chaps from Redmond to work on getting that side of things tip-top though it works well already. Personal experience here.
Answer: I tried it in a VM and it seemed ok, however do be aware that as Oracle (Sun) have now (essentially) killed OpenSolaris this may spell the end for Nexenta.
An alternate ZFS serving platform would be FreeBSD.
Comment: @LapTop006: There was no such statements by Oracle about OpenSolaris. Only that some Solaris new features might not be included in the OpenSolaris source code which was already the case anyway. As of Solaris no more being a freeware, this has nothing to do with OpenSolaris and even less with Nexenta which is an independent project.
Comment: "as Oracle (Sun) have now (essentially) killed OpenSolaris" - uhm, how did they kill OpenSolaris?
Comment: opensolaris has not changed. Beyond that Nexenta is an entire distro using the opensolaris kernel and gnu tools.
Comment: I admit there's no clear statements either way, but they've done a licence change for Solaris, and also announced that OpenSolaris will no longer recieve new features as a test bed, which will likely cause OpenSolaris to stagnate.
Comment: Got a link?  The only thing I've seen is that Solaris itself is no longer free to use and you must license it for commercial use after a trial period.  Also the creator of ZFS just joined the Nexenta Advisory Board.  I wouldn't be too concerned about the future of OpenSolaris or Nexenta.
Comment: I've found some stories that seem to speculate this but I'm having a hard time finding any official stance on OpenSolaris from Oracle.
Answer: This is old but I don't think it has been adequately answered. The CIFS integration with ZFS is terrible. I know of no one using it in a production environment, it is just broken. ACLs get horribly mangled and it is impossible to keep them managed.
Samba, OTOH, is fine - or at least, far more mature.
I'm not pumping my own blog (I get about one visitor per month and don't care), but I already went into some more detail about it:
http://jimcollier.blogspot.com/2010/03/2kc820q3.html
Answer: You might want to consider the 3+ years bug with ZFS ARC that still persists before jumping in too deep with ZFS...
http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6522017
(This one is nasty as it will also go out-of-bounds from the VM limits of a hypervisor!)
Comment: @user48838 - cross posting the same response to every ZFS-related question, regardless of its appropriateness to the question helps nobody. Can I ask you to only post appropriate responses to questions please as your efforts in the last day have generated a number of moderator attention alerts.
Comment: See my comment over here: http://serverfault.com/questions/144639/best-filesystem-choices-for-nfs-storing-vmware-disk-images/163972#163972
Comment: See my response at http://serverfault.com/questions/162693/my-opensolaris-server-hangs-when-writing-large-files-after-upgrading-zpool/163955#163955
Comment: The collective "moderator zombie" response is bewildering, especially when reviewing the following - http://serverfault.com/about with the "operative" references to "site for system administrators and IT professionals..."
Comment: I have been ignored repeatedly to sensible requests for careful (re)reading of the postings in their full context - yes it is repeatish, but they are relevant responses to the original posted questions: "Is ZFS ready for production consideration?" The negative noise (in the guise of "moderatorism") totally and effectively side-steps the valid warning of the production significance (along with the possibly career inhibiting implications) of this bug...
Comment: This sends the strong message that for the sake of "moderator window dressing" you folks are willing to sit by as the users are not informed of this bug when they are asking if there are issues to consider (the collective negative efforts have probably effectively minimized this information too, so give yourselves a "pat on the back" if that is something you can be/are proud of).


Getting 405 error, Node Js - Method not found

Question: I am trying to run a server in node js, its actually a GraphQL server. I am just calling the method from the client side from React JS
client-side running in localhost:3000, and server-side in localhost:4000
Client-side code
var dice = 3;
var sides = 6;
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", "http://localhost:4000/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
    debugger;
  console.log('data returned:', xhr.response);
}
var query = `query RollDice($dice: Int!, $sides: Int) {
  rollDice(numDice: $dice, numSides: $sides)
}`;
xhr.send(JSON.stringify({
  query: query,
  variables: { dice: dice, sides: sides },
}));

and In the server-side, I am using the below code
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    rollDice(numDice: Int!, numSides: Int): [Int]
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  rollDice: function ({numDice, numSides}) {
    var output = [];
    for (var i = 0; i < numDice; i++) {
      output.push(1 + (numSides *3));
    }
    return output;
  }
};

var app = express();
//CORS middleware
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

The error I am getting is
XMLHttpRequest cannot load http://localhost:4000/graphql. Response for preflight has invalid HTTP status code 405
Is there anything I am missing ...
Thanks.
Answer: You need to handle pre-flight requests (OPTIONS) in your CORS code by correctly responding to OPTIONS request:
function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware

    if (req.method === "OPTIONS") {
        return res.status(200).end();
    }

    return next();
}


Laurent expansion

Question: I have $\dfrac{z}{(z-1)(z+1)}$ and wish to find the Laurent expansion about $z = 1$. I have simplified this down to $\dfrac{z}{z^2 - 1}$ but I'm unsure of where to go from here. A hint has been given that I can use a substitution but I don't know what to use.
Any help at all is greatly appreciated.
Comment: Rewrite the expression in terms of $w=z-1$ may help. Partial fraction is useful too.
Comment: Ah, that's done it. Thanks!
Answer: Here how you advance
$$= \dfrac{z}{(z-1)(z+1)} = \dfrac{(z+1)-1}{(z-1)(z+1)}= \frac{1}{z-1}- \dfrac{1}{(z-1)(z+1)} $$
$$=\frac{1}{z-1}- \dfrac{1}{(z-1)(2+(z-1))}   $$
$$=\frac{1}{z-1}-\dfrac{1}{2(z-1)\left(1+\frac{(z-1)}{2}\right)}   $$
$$=\frac{1}{z-1}-\dfrac{1}{2(z-1)}\sum_{k=0}^{\infty} (-1)^k\frac{(z-1)^k}{2^k}=\dots. $$

Laurent expansion