passar variável javascript para uma variável em php

Question: Bom dia pessoal,
estou com uma dúvida:
eu tenho um select que pega o um array do banco, e toda vez que o user muda o select tem um change no javascript que atualizar isso em um input do tipo hidden >
<input id="id_clinic_hidden" hidden name="clinic_id">

a função javascript é essa:
$(document).ready(function () {
    $(document).on("change", "#doc_sel_clinic", function(){
        var id = $(this).val();
        $("#id_clinic_hidden").val(id);
        alert(id);
    });
});

O que quero fazer é pegar essa variável id do javascript para php, pode ser via sessão.
Isso tá dentro do javascript pq preciso mudar o valor quando o usuário mudar o select.
obrigado
Answer: Segue um exemplo:
var myval = 'test';

$.ajax({
  type: 'POST',
  url: 'seuphpfile.php',
  data: {'variable': myval},
});

Recebendo a variavel no PHP (seuphpfile.php)
$minhaVariavel = $_POST['variable'];

Comment: Olá, eu ainda não estou no notebook pra testar, porém isso atualiza a variável toda vez que que acontecer o evento do onchange?
Answer: Para isso você irá precisar trabalhar com ajax, o qual faz requisições http se forma assíncrona;
$.ajax({
   url : 'caminho_do_php_que_ira_recebe_o_input.php',
   dataType : 'html',
   type : 'POST',
   data : {'id' : id},
   beforeSend : function () {
         console.log('Carregando...');
   },
   success : function(retorno){
       console.log(retorno);
   },
   error : function(a,b,c){
       console.log('Erro: '+a[status]+' '+c);
   }
});

Basicamente é chamar em uma função (no momento que quiser enviar) e pronto, no lado do servidor, basta receber da seguinte maneira:
$valor_recebido = $_POST['id'];

Caso queria receber algum retorno após o envio com o return do PHP, basta receber e trabalhar com essa variável chamada retorno (caso achar melhor nomeie como preferir).
Comment: boa, para que serve esse dataType?
Comment: `dataType` é formado de resposta do servidor, eu particularmente só uso `html` ou `json`, mas não é um campo obrigatório.
Answer: fiz dessa forma no javascript como vcs recomendaram:
$(document).ready(function() {
  $(document).on("change", "#doc_sel_clinic", function(){
    var id = $(this).val();
    $("#id_clinic_hidden").val(id);

    $.ajax({
      type: 'POST',
      url: base_url + 'Doctor/config_schedule',
      data: {'id_selected': id},
    });

    console.log(id);
  });

e tentei buscar a no php>
<?php $minhaVariavel = $_POST['id_selected']; ?>

Porém não tive sucesso, retorna erro:

Message: Undefined index: id_selected

Comment: você tem que testar para ver se ela existe exemplo:` `
Comment: sim, o isset não resolve meu problema, pq eu queria que fosse atualizada no evento do onchange como mostrei. A página ela mostra os dados conforme o que for escolhido nesse select, aí toda vez que o user escolher um select ele tem que atualizado. não tô conseguindo fazer isso.
Comment: eu não sei se estou passando o path de url do ajax corretamente, pq aqui usamos url amigavél e codeigniter, não sei se é isso.


Book on matrix computation

Question: I'm taking a machine learning course and it involves a lot of matrix computation like compute the derivatives of a matrix with respect to a vector term. In my linear algebra course these material is not covered and I browsed some book in the school library but didn't find something relevant to my problem.
So can you recommend me a book which covers these matrix computations?
Thanks!
Comment: Related: http://math.stackexchange.com/questions/135008/a-book-for-self-study-of-matrix-decompositions
Answer: I suggest Matrix computation by Golub and van Loan.
Comment: This needs about +10
Answer: I recommend two books

Matrix Algebra from a statistician's perspective by David Harville. (chapter 15 covers derivatives of matrices with respect to matrices.)
Matrix Differential Calculus with Applications in Statistics and Econometrics by Jan Magnus and Heinz Neudecker. (a huge portion of the book is about that particular question of differentiation.)

These two books are also excellent because they come with two additional monographs with a lot of solved problems (check for instance Matrix Algebra (Econometric Exercises, Vol. 1) by Karim Abadir and Jan Magnus which has a lot of solved problems on matrix differentiation). Also they have the additional advantage that they are directly relevant to machine learning.
Answer: I find the Matrix Cookbook handy. It's not a textbook, rather, to quote the introduction:
These pages are a collection of facts (identities, approximations,
inequalities, relations, ...) about matrices and matters relating to them.
It is collected in this form for the convenience of anyone who wants a quick
desktop reference
Comment: This seems good because it has a whole chapter on derivatives.  "This section is covering differentiation of a number of expressions with respect to a matrix X."
Answer: Bishop's excellent machine learning textbook, Pattern Recognition and Machine Learning, has an appendix on "Properties of Matrices".  One section in this appendix (p. 697) is about Matrix Derivatives, and discusses formulas like this:
\begin{equation}
\frac{\partial}{\partial A} \text{Tr}(AB) = B^T
\end{equation}
and
\begin{equation}
\frac{\partial}{\partial A} \ln | A | = \left(A^{-1} \right)^T,
\end{equation}
for example.
Peter Lax has a great book called Linear Algebra and its Applications.  Chapter 9 is entitled "Calculus of Vector- and Matrix-Valued Functions".

Book on matrix computation


How to sort array numbers using Array.Sort

Question: I've got a fair idea on how it works, I've seen other examples on how to use it just can't figure out how to apply it to my code.
using System;

namespace ArrayRandomNumbers
{
    class RandomNumbers
    {
        public static void Main()
        {
            int[] num = new int[1000];
            Random rnd = new Random();

            for (int i = 0; i < 1000; i++)
            {
                num[i] = rnd.Next(1000);

                Console.WriteLine(num[i]);
                Array.Sort(num); //Doesn't do anything here
                //Console.WriteLine(num[i] = rnd.Next(1000));
            }
            Console.ReadLine();
        }
    }
}

Comment: Does nothing at all happen? Are you outputting the values after you sort them, or using breakpoints to look at the array?
Comment: You can not expect sorted array while it is being constructed!! see answer given by @ekad
Comment: The way I was trying to do it was sort it before it's printed, don't know why I got a negative for that?
Comment: @Carl Blance In that case You should use a printing for loop after the first for loop, see my answer below.
Comment: Carl Blance` I have tried something a bit different using an anonymous method looping across the array which I have called .ToList() this way I could do the `foreach` even quicker against the collection and the sorting is done last and done very quickly, also if you are not familiar with `Random numbers` read up if you are wanting number to be sorted from 1 to 1000 then there is no need for a sort you could just perform a simple loop
Comment: `Carl Blance` I fixed the problem I will edit my answer and you will see what it is that you were wanting to see
Answer: Array.Sort(num); actually does the sorting for each iteration, but it's inefficient because you only need to sort the array once instead of 1000 times. You need to put Array.Sort(num); outside of the for loop and create another for loop to print the sorted array.
int[] num = new int[1000];
Random rnd = new Random();

for (int i = 0; i < 1000; i++)
{
    num[i] = rnd.Next(1000);

    Console.WriteLine(num[i]);
    //Console.WriteLine(num[i] = rnd.Next(1000));
}

Console.WriteLine("Press Enter to sort the array");
Console.ReadLine();

// sort the array
Array.Sort(num);

// print the sorted array
for (int i = 0; i < 1000; i++)
{
    Console.WriteLine(num[i]);
}

Console.ReadLine();

Comment: I think this is right. If you are sorting after every iteration, you are changing the array. There's no guarantee that the x values you already put in will stay in the first x places in the array (here they definitely won't, because they are 0s and what you are putting in is >=0).
Comment: It does work but after it's sorted, sorted value start's at the 700's and end at (998 always) but thank you @ekad. I'll continue to work on it.
Comment: @CarlBlance well the numbers are random, so they could be any integer between 0 and 1000.
Answer: if you want to do this all in one like your original code you could do the following as well
using System;
namespace ArrayRandomNumbers
{
    class RandomNumbers
    {
        public static void Main()
        {
            int[] num = new int[1000];
            Random rnd = new Random();
            var randList = new List<int>();
            var distinctList = new List<int>();
            for (int i = 0; i < 1000; i++)
            {
                num[i] = rnd.Next(1000);
                randList.Add(num[i]);
                Console.WriteLine(randList[i]);
            }
            distinctList = randList.Distinct().ToList();
            distinctList.Sort();
            Console.ReadLine();

            distinctList.ForEach(delegate(int s)
            {
                Console.WriteLine(s.ToString());
            });
            Console.ReadLine();
        }
    }
}

Yields the following output reading left to right, a short snippet based on the random numbers generated when I ran this if you write these numbers to a file you will see that the distinctList will have the sorted values as you have expected I am showing the unsorted results use the code and you can see for yourself in the debugger when you inspect at the last Console.ReadLine();
774
452
566
682
814
702
585
371
469
694
241
168
235
763
35
548
158
212
106
297
921
65
280
419
682
42
116
52
212
523
467
777
195
999
316
836
735
742
6
332
647
645
245
622
674
925
692
141
643
84
85
806
663
476
971
709
171
146
999
772
585
532
159
946
227
464
972
235
447
199
813
416
206
773
650
275
819
657
745
757
350
974
409
128
437
661
113
719
28
606
664
588
742
234
747
114
485
299
395
209
953
457
694
443
270
668
599
890
826
695
889
514
401
242
421
610
123
31
508
565
350
253
206
840
535
224
673
971
26
535
789
520
262
535
803
892
280
965
857
769
61
223
892
332
717
149
187
500
812
136
990
454
790
829
858
700
250
854
908
46
995
628
864
291
906
369
251
865
438
529
330
158
173
739
504
127
360
874
122
385
37
173
158
889
544
334
730
433
677
103
641
425
57
810
773
432
358
600
426
348
898
321
61
283
806
832
280
50
324
731
339
376
731
522
9
821
469
974
746
571
638
818
188
334
887
904
100
362
965
71
768
760
448
774
487
715
112
875
83
712
54
679
108
945
764
265
694
534
801
952
963
384
854
854
709
79
133
726
395
901
731
917
84
252
962
579
928
956
35
294
709
594
891
34
517
958
709
242
570
622
209
566
561
13
108
384
905
593
65
407
581
385
479
181
980
136
595
855
983*
Comment: Is that caused by the way I've written it? I'm trying to do it like 1 , 5 , 44, 77 675, 789, 976. Not start from a high number such as 600* or 700 then + 1 till 998
Comment: you need to understand random numbers depending how someone runs it their numbers will be different..
Answer: just for hint to @Carl
Code:
class Program
    {
        static void Main(string[] args)
        {
        var num = new int[1000];
        var rnd = new Random();

        Console.WriteLine("Before Sorting...");
        for (var i = 0; i < 1000; i++)
        {
            num[i] = rnd.Next(1000);

            Console.WriteLine(num[i]);
             //Doesn't do anything here
            //Console.WriteLine(num[i] = rnd.Next(1000));
        }
        Console.WriteLine("After Sorting...");
        Array.Sort(num);

        for (var i = 0; i < 1000; i++)
        {

            Console.WriteLine(num[i]);
            //Doesn't do anything here
            //Console.WriteLine(num[i] = rnd.Next(1000));
        }

        Console.ReadLine();
    }
}

Process is:
1) make an array, Print it while making (optionally you can sort it too, but it will be inefficient, i  guess.)
2) sort the array.
3) Print out Sorted array.
What you are doing:
1) Make and array.
2) Populate each element with random number.
3) Printing that random number.
4) sorting the array so far made.
hence the Disaster, you are seeing.
Answer: Use below Code :
int[] intArray = new int[] {1, 9, 6, 7, 5, 9};

// Sort array in ascending order
Array.Sort(intArray);
Console.WriteLine("Ascending: ");
foreach(int value in intArray)
{
  Console.Write(value + " ");
}

// Reverse array
Array.Reverse(intArray);
Console.WriteLine("\n\nDescending: ");
foreach(int value in intArray)
{
   Console.Write(value + " ");
}

Output:
Ascending:
1 2 3 4 5 7 9

Descending:
9 7 5 4 3 2 1


Google Cloud Datalow:Getting a below error at runtime

Question: I am writing data into nested array BQ table(array name inside the table is -merchant_array)using my dataflow template.
Sometime its running fine and loading the data but sometime its giving me that error at run time.
<code>java.lang.RuntimeException: org.apache.beam.sdk.util.UserCodeException: com.fasterxml.jackson.databind.JsonMappingException: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) (through reference chain: com.google.api.services.bigquery.model.TableRow["null"])
</code>
"message" : "Error while reading data, error message: JSON parsing error in row starting at position 223615: Only optional fields can be set to NULL. Field: merchant_array; Value: NULL",

Anyone has any idea why I am getting this error.
Thanks in advance.
Comment: I suppose this is json serialization error.
Comment: Due to this "NULL" value? But why getting null.
Comment: Looks like your input data contains records that aren't valid according to the schema you have set.  Where is your data coming from, and what is the schema you are using?
Comment: Data is coming from one table.The schema is correct but when the loop is iterating on source iterable data that time it is putting null for some tablerow.  sourceValuesIterable.parallelStream().forEach(tblRow ->
  {
   }
Answer: here I got the issue that was causing error so I am posting my own question's answer,it might be helpful for anyone.
So the error was like-
Only optional fields can be set to NULL. Field: merchant_array; Value: NULL",
And here merchant_array is defined as an array that contains record (repetitive) data.
As per google doc the the array can not be-
ARRAYs cannot be NULL.
NULL ARRAY elements cannot persist to a table.
At the same time I was using arraylist in my code, that allows null values. So before making a record type data in code or setting the data in arraylist, just remove the NULL  tablerows if exist.
hope this will helpful.


On the associated graded ring , corresponding to an $\mathfrak m$-primary ideal , of the $\mathfrak m$-adic completion

Question: Let $(R, \mathfrak m)$ be a Noetherian local ring. Let $\hat R$ be the $\mathfrak m$-adic completion of $R$. $J$ be an ideal of $R$ with $\sqrt J=\mathfrak m$. Let $\hat J =J\hat R$ be the $\mathfrak m$-adic completion of $J$ regarded as an ideal of $\hat R$. I know that $\hat {J^n}={\hat J}^n, \forall n\ge 1$. My question is, are the following true:
(1) the completion map $R \to \hat R$ induces an isomorphism $R/J^n \to \hat R/\hat J^n, \forall n\ge 1$ ?
(2) the completion map $R \to \hat R$ induces an isomorphism $J^n/J^{n+1} \to \hat J^n/\hat J^{n+1}, \forall n\ge 0$ ?
[Note that question  (2) just amounts to asking whether the associated graded rings $\oplus_{n\ge 0} J^n/J^{n+1}$ and $\oplus_{n\ge 0} \hat J^n/\hat J^{n+1}$ are canonically isomorphic or not ]
Answer: Note that any module of finite length is complete.  In particular, $R/J^n \cong \widehat{R/J^n}$ and $J/J^{n+1} \cong \widehat{J/J^{n+1}}$. But completion is exact, so $\widehat{R/J^n} \cong \hat{R}/\hat{J}^n$ and $\widehat{J/J^{n+1}} \cong \hat{J}/\hat{J^{n+1}}$.


SQL syntax exception

Question: I am beginner to MYSQL and want to find out why i am getting a sql syntax exception for the below query:
select a.file_id
   from FILE_XFER_TRACKING_DETAIL a,  FILE_XFER_TRACKING_HEADER b
where  b.transaction_id = a.transaction_id
and  b.interface_id =?
and  a.file_name =?
and  a.status = 'InProcess'
and   a.update_time > sysdate- 0.003472222222222222
and a.file_id <> ?
and b.direction = ?

In mysql workbench, in the editor i see the syntax error at and b.interface_id=? . I am a beginner and not sure how to fix it,
Comment: replace `?` for actual values
Comment: Can you give the exact syntax errors?
Answer: You must put an actual value where the ? is. For example and b.interface_id = 100
And so on for the rest of them.
Comment: It would be nice if people left a reason for a down-vote... It's not all the issues in the query, but it does address one of them.
Answer: Also, the reference to the bareword sysdate is valid syntax for Oracle, but it's invalid for MySQL.
In MySQL, to return the current datetime, you'd want to reference the function SYSDATE(), or the function NOW().
Subtracting a numeric value from a DATE expression is valid in Oracle; but it's not valid in MySQL.
The particular numeric value specified in your query (0.003472222222222222) would be interpreted by Oracle as the fractional part of day, essentially equivalent to 5 minutes. ( = 1/24/60 * 5 )
In MySQL, to do the equivalent, you'd want something like:
NOW() + INTERVAL -5 MINUTE

Also, ditch the old-school comma syntax for the join operation, and use the JOIN keyword instead, and relocate the join predicates from the WHERE clause to an ON clause. (The comma join operator is still valid syntax, it's just very outdated and the improved syntax has been available for a long time.)
  FROM FILE_XFER_TRACKING_DETAIL a
  JOIN FILE_XFER_TRACKING_HEADER b
    ON b.transaction_id = a.transaction_id
 WHERE ...

Answer: You've copied this from some code where the SQL was meant to be a a prepared statement.
The question marks ? need to be replaced with values for comparison in you where clause.
 where  b.transaction_id = a.transaction_id
    and  b.interface_id = '<your value here>'
    and  a.file_name = '<your value here>'
    and  a.status = '<your value here>'
    and   a.update_time > sysdate- 0.003472222222222222
    and a.file_id <> '<your value here>'
    and b.direction = ''<your value here>'

Comment: That possibility totally escaped me; I'm just so used to qualifying _EVERY_ column reference with a table alias, I forget that you can actually reference columns _WITHOUT_ qualifying them. That, and I'd never consider naming a column "sysdate".  If `sysdate` _is_ in fact a column name, and the datatype of the column is something other than DATE, DATETIME or TIMESTAMP, then what I said in my previous comment doesn't apply. (The OP query just looks an awful lot like old-school Oracle syntax.)
Comment: **`sysdate - 0.03472`** is valid Oracle syntax, but it's invalid in MySQL. In MySQL, we'd replace that with something like: **`NOW() + INTERVAL -5 MINUTE`**
Comment: ah, I thought it was a unique column name

SQL syntax exception


which CSS query method is the best to use:container query.element query or media query?

Question: I like to know which kind of queries  I have to use because  this is my first website I am developing and I am working with foundation grid system.
I see at this moment you have containers queries  which is more targeted to an element .  also I see you have  element queries and media queries.
to have modern responsive website which one I have to use and why?
container query,element query or media query?
what is your advise to me?
thanks
johan
Answer: The concept of Container Queries is rather new and enables adjusting Elements to the Container, Not Viewport. Container queries would grant you more control over styling in contrast to Media queries but Media queries are largely supported. To use container queries you will need to add extensions. It depends upon how much control does your site require on the responsiveness of its elements.
Do you want to control each and every element of your site individually?
Use container queries.
Otherwise go for traditional media queries.
Read here for a more extensive discussion on this.


How can I prepare the input layer for recurrent neural network if there are many categorical variables?

Question: I am building a recurrent neural network (RNN). The feature set contains many categorical variables. Some of them are like users and items. In this case, if I use one-hot encoding and concatenate these vectors into a big one, the resulting vector will be super sparse. Is it fine to do this? I am not sure if this is normal for RNN.
Is there any other way to handle this case?
Comment: Entity embedding is a method that seems promising here.

Cheng Guo and Felix Berkhahn "Entity Embeddings of Categorical Variables"
https://arxiv.org/pdf/1604.06737.pdf
Comment: crossposted on quora: https://www.quora.com/unanswered/How-should-I-handle-many-categorical-variables-at-the-input-layer-of-recurrent-neural-network
Comment: Should I remove either?
Comment: That's fine, just for people to check out the link first before they answer
Comment: Are these categorical features "metadata" or is it something like text, engagement indicators, etc.? Also is this a classification or regression problem?
Answer: The "default" way of dealing with categorical variables for neural networks is to use embeddings. The most popular usage is word embeddings, where words are represented by vector representation (learned or pre-trained). The advantages of such approach is that it has smaller dimensionality then if you used one-hot encodings and they usually form meaningful representations of words, i.e. similar words have similar representations in the embedding space. Same idea can be applied to any other categorical variables, Sycorax gave one reference of paper by Guo and Berkhahn, but you can check also other references and this Medium post. Embeddings were used for categorical variables in Kaggle competitions, but you can also find many examples of recommender systems using such representations, for example this recent post on Google Cloud blog.
Answer: This is not my area of expertise, but my understanding is that it's a lot harder to learn on a sparse representation.  You won't have many training examples for each input, so most of the neurons will be training on just a few examples.
The canonical example for RNNs would be NLP, and I think it's fairly standard to transform the input text from something sparse (e.g., a one-hot encoding of word IDs), to a dense vector embedding (e.g., word2vec).  This page is pretty good:
https://www.tensorflow.org/versions/r0.8/tutorials/word2vec/index.html
In your case it's hard to say what exactly would be best without knowing more about your data.  But maybe you could find some sort of vector embedding that would work for your data.  Then you could capture some of its essential properties and train your RNN effectively.


How do I use iptables to do port forwarding from one to another port on the same host?

Question: How do I use iptables to forward all requests to a port (say 1443) to another port on the same host (say 443)?
This should also be done for requests from another computer.
Comment: I see, this approach also requires root access. But certainly if some application is not safe; it's better to run it as normal user than as root. Normally applications run as root and then privileges are dropped to user privileges when it 'daemonizes'.
Comment: why do you need this if I may ask?
Comment: @HrvojeŠpoljar Some applications that can't guarantee they will be started by UID 0 start on a high-number port by default, and it is up to you to reconfigure or NAT/Proxy if you want to use on a lower port. For example, Tomcat Java application container runs on ports 8080 and 8443 by default. If I recall correctly, BT Diamond's IPControl DNS engine runs on a high-numbered port and expects either IPTABLES-based NAT or a forwarding/caching BIND on port 53 to get to it.
Answer: You need rule which will update 'nat' tables PREROUTING chain like this :

iptables -t nat -A PREROUTING -p tcp --dport 1443 -j REDIRECT --to-port 443


VMWare and storage virtualization solution

Question: I'd like to use the capabilities of two Dell EqualLogic SAN and a VMWare vSphere 6 installation to implement a storage virtualization solution.
Basically I'd like to put virtual SAN layer above my two physical SANs so that it can provide the same services as a usual SAN, this is for say, LUNs, iSCSI endpoint and more, NFS, CIFS shares, etc...
The idea is that whatever happens to the physical layer, I can replace the defective device in a transparent manner or attach new devices to the virtual layer so that more space is available.
On its end, the storage virtualization layer should make sure to replicate data for redundancy and use the capabilities of the physical devices for replication, snapshots and other.
It seems that VMWare's Virtual Volumes is what I'm looking for but I don't seem to be able to create a Virtual Volume/VMDK (a.k.a LUN) and allow a physical host to connect it via iSCSI.
Do you know any solution that could accomplish the requirements listed above? A bonus point would be to be able to use the resources from the VMWare infrastructure.
Comment: You want to know what software to buy to do this?
Answer: Very odd question - seemingly you don't know vSphere terribly well. It already allows for much of what you want - you can attach a range of storage to your hosts and move VMs between them as needed already - though you can't use CIFS. VMWare won't in itself manage and data replication but you can use it's built in Replication service to replicate whole VMs to help with DR. And while VVOLs may help you they're not THAT much different from what we have now with regular storage management, certainly it still requires your storage to manage any storage-to-storage replication. Also only more recently storage arrays support VVOLs.
As for your Equalogics, you need OS 8 on their and you need to implement the VSM as a VASA provider - it doesn't 'just happen'.
I think you need to research this a lot more and come back to use with clearer requirements.
Comment: You did not get at all what I tried to explain here. I know that vSphere can provide all of this. I just don't want to have to manage all my storage individually, I'm looking for a [distributed file system](https://en.wikipedia.org/wiki/Clustered_file_system#Distributed_file_systems) like interface **between** vSphere and all my storage appliances so that I can move one or another part with little impact. Connecting everything to vSphere does not really help here.
Comment: I do understand, I just don't think you understand the current marketplace for Storage - either way you're looking for product recommendations, something we don't do on this site - as we make very clear in the text you've ignored when you sign up here - ask VMWare directly.


If $\mathcal T$ and $\mathcal S$ are two topologies, can we defined $\mathcal T\cup \mathcal S$ and $\mathcal T\cap \mathcal S$ on $X$?

Question: Let $X$ a topology space, and $\mathcal T$ and $\mathcal S$ two topology on $X$. I would define $\mathcal T\cap \mathcal S$ the thinest topology included in $\mathcal T$ and $\mathcal S$ and $\mathcal T\cup\mathcal S$ being the coarser topology that contain $\mathcal T$ and $\mathcal S$.
Obviously, each topology is contains in the discrete topology, and all topology contain the coarser topology, but is there any way to construct $\mathcal T\cup \mathcal S$ and $\mathcal T\cap \mathcal S$.
For $\mathcal T\cup \mathcal S$, I would do set
$$\left\lbrace\bigcup_{i\in \mathcal I}U_i\cap V_i\mid U_i\in \mathcal T,V_j\in \mathcal S\right\rbrace.$$
This look to be a topology, no ? And for $\mathcal T\cap \mathcal S$, I have no idea... but may be it's not possible ?
Comment: Notice $T \cap S$ is a topology while $T \cup S$ will not be in general, the most natural way to define $T \cup S$ as a topology would be to say that $T \cup S$ is the smallest topology that contains $T \cup S$ (and then change $T \cup S$ to something else to prevent ambiguity, such as $T \vee S$ say).
Comment: $\mathcal T\cap \mathcal S$ is just the set theory intersection. But $\mathcal T\cup \mathcal S$ is not the set theoretic union, but yes, you can find a smallest topology that contains the two.
Comment: You essentially get that the ordered set of topologies is a lattice.  It can be seen as a complete lattice, I believe. Not sure if it is a distributive lattice.
Comment: @WillM.: Can we construct it rigorously ? (not only say that it's the smallest topology that contain $T\cup S$).
Comment: I don't know what "construct rigorously" can possibly mean and how "is the smallest topology that contains $T \cup S$ is not rigorous? Maybe you did not realise, but the intersection of topologies is a topology (regardless of how many topologies you intersect, but at least one). Thus, the smallest topology that contains $T \cup S$ _signifies_ the intersection of all topologies containing $T \cup S.$
Answer: For $\mathcal T \cap \mathcal S$ you can use the set-theoretic intersection. i.e.
$\mathcal T \cap \mathcal S =\{U: U\in \mathcal T \text{and} \ U\in \mathcal S \}$. Then clearly you can see this is the largest topology which lies inside both topologies.
$\mathcal T \cup \mathcal S$ set $\mathcal B=\{U: U\in \mathcal T \text{or} \ U\in \mathcal S \}$. Then $\mathcal B$ is a subbase for the smallest topology which contains both topologies, and this gives the topology you describe.
Note that both facts generalise to arbitary sups and infs.
Answer: Writing $\mathcal{T} \cup \mathcal{S}$ is misleading imo, since a topology is by definition a subset of the powerset, so the union of two such sets is already defined.
Regarding the intersection of two (in fact arbitrary intersections of) topologies (by which I mean the intersection of the subsets of the powerset) note that all the axioms are satisfied, since they are satisfied in all topologies involved.
The coarsest topology containing given two topologies may be defined as the intersection of all topologies containing $\mathcal{T}$ and $\mathcal{S}$. Indeed, one can show that this is explicitly given by your definition.


How work BigPipe cache around block views?

Question: I have 2 blocks with swiper.js around.
This 2 blocks are from the views module.
I need to print them in the theme like i want so, i load them into the preprocess_page.
$block1 = \Drupal\block\Entity\Block::load('views_block__test_1');
$variables['block1'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block1);

And the second :
$block2 = \Drupal\block\Entity\Block::load('views_block__test_2');
$variables['block2'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block2);

They have exactly the same configuration in views and block config.
But for block 1 swipper work, not for the block2 every time i load the page.
If i look at the source i got this for the second block :

For the block 1 i got the HTML render.
I don't know why the second block is cached by big-pipe and not the first block.
But my js on the ready state work every time on the first block, and depend if i clear the cache but it's not everytime, work on the second block the first time i load the page.
The callback (in the bigpipe attributes) call something at the bottom of the page after the js include.
That why my second block doesn't work ? it's not clear.
What's happen ?
Comment: Does the 2nd block have an exposed filter or some sort of form/pulling in uncacheable content? Bigpipe will step in for anything deemed as uncacheable e.g. has a form. You should move your JS into a drupal behavior and that code should be triggered upon bigpipe loading in the content
Comment: nop no exposed filter, i ll try to move the js in the drupal behavior
Comment: @Leigh Mason thank put the code inside the drupal.behavior solve the problem.
Answer:
I don't know why the second block is cached by big-pipe and not the
  first block.

This depends on the auto placeholder conditions defined in services.yml and the cache metadata of the block:
auto_placeholder_conditions:
  # Max-age at or below which caching is not considered worthwhile.
  #
  # Disable by setting to -1.
  #
  # @default 0
  max-age: 0
  # Cache contexts with a high cardinality.
  #
  # Disable by setting to [].
  #
  # @default ['session', 'user']
  contexts: ['session', 'user']
  # Tags with a high invalidation frequency.
  #
  # Disable by setting to [].
  #
  # @default []
  tags: []

As mentioned in the comments, when the module BigPipe is enabled you need to use Drupal.behaviors for your javascript, see:
https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


how do I use my web reference in MVC?

Question: greeting folks, I need to reference an external service in my MVC app.
I'm using this service to validate an authentication token that one of our clients has requested we use.
I'm porting an older project to MVC.
I added a web reference.
The config was generated like so:
<code><system.serviceModel>
<bindings>
    <basicHttpBinding>
        <binding name="ExternalServicesSoap" closeTimeout="00:01:00"
            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy="true">
            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
            <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                    realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<client>
    <endpoint address="http://myapps.test.com/ExternalServices/ExternalServices.asmx"
        binding="basicHttpBinding" bindingConfiguration="ExternalServicesSoap"
        contract="AssertionService.ExternalServicesSoap" name="ExternalServicesSoap" />
</client>
</code>

In the older ASP.NET world, I could do the following on the specific service I am referencing, using the Assertion object defined in the external service reference.
<code>        var service = new ExternalServices();
        Assertion assertion = service.Validate(Id);
        if(assertion.Valid){}
</code>
This doesn't seem to be the exact case in the MVC project.
I seem to be working with WCF.
I'm not sure if I'm approaching this properly in the MVC world.
All I have to work with is an ExternalServiesSoap interface or an ExternalServicesSoapChannel interface.
None of which return an Assertion object like in the ASP.Net world.
They both have the Validate method but return a ValidateAssertionResponse.
The response object doesn't have any useful properties; just a response body.
The Assertion class is still accessible but it doesn't seem to be returned by any of the interface methods.
Can anyone help me with how to properly use one of these interfaces?
thanks
Answer: Rather than adding a Service Reference, add a Web Reference.  Right click on your project, select "Add Service Reference...".  In the Add Service Reference dialog, click "Advanced", then click "Add Web Reference".  This will generate a proxy that is appropriate for use with ASMX based services.

how do I use my web reference in MVC?


Erro no comando CRUD ATUALIZAR - java.sql.SQLException: No value specified for parameter 8

Question: Estou montando um sistema Java com ligação ao banco MySQL, mas parei em um certo ponto pois não consigo localizar o erro. O meu método atualizar acontece um erro no JUnit, mas não consigo descobrir qual é.
Segue partes do código:
package com.sistemacliente.DAO;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.sistemacliente.domain.Balada;
import com.sistemacliente.domain.Cliente;
import com.sistemacliente.factory.ConexaoFactory;

public class ClienteDAO {

    public void salvar(Cliente c) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO cliente");
        sql.append("(nome,sobrenome,telefone,email,data,valor,baladas_codigo)");
        sql.append("VALUES (?,?,?,?,?,?,?)");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());
        comando.setString(1, c.getNome());
        comando.setString(2, c.getSobrenome());
        comando.setInt(3, c.getTelefone());
        comando.setString(4, c.getEmail());
        comando.setDate(5, c.getData());
        comando.setDouble(6, c.getValor());
        comando.setInt(7, c.getBalada().getCodigo());

        comando.executeUpdate();

    }

    public ArrayList<Cliente> listar() throws SQLException {

        StringBuilder sql = new StringBuilder();
        sql.append(
                "SELECT c.codigo, c.nome, c.sobrenome, c.telefone, c.email, c.data, c.valor, b.codigo, b.descricao ");
        sql.append("FROM cliente c   ");
        sql.append("INNER JOIN balada b ON b.codigo = c.baladas_codigo");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());

        ResultSet resultado = comando.executeQuery();

        ArrayList<Cliente> lista = new ArrayList<Cliente>();

        while (resultado.next()) {
            Balada b = new Balada();
            b.setCodigo(resultado.getInt("b.codigo"));
            b.setDescricao(resultado.getString("b.descricao"));

            Cliente c = new Cliente();
            c.setCodigo(resultado.getInt("c.codigo"));
            c.setNome(resultado.getString("c.nome"));
            c.setSobrenome(resultado.getString("c.sobrenome"));
            c.setTelefone(resultado.getInt("c.telefone"));
            c.setEmail(resultado.getString("c.email"));
            c.setData(resultado.getDate("c.data"));
            c.setValor(resultado.getDouble("c.valor"));
            c.setBalada(b);

            lista.add(c);
        }
        return lista;

    }

    public void excluir(Cliente c) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM cliente ");
        sql.append("WHERE codigo = ?");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());
        comando.setInt(1, c.getCodigo());
        comando.executeUpdate();

    }

    public void atualizar(Cliente c) throws SQLException {

        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE cliente");
        sql.append("SET codigo = ? , nome = ? , sobrenome = ? , telefone = ? ,"
                + " email = ? ,  data = ? , valor = ? , baladas_codigo = ? ");
        sql.append("WHERE codigo =  ? ");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());

        comando.setString(1, c.getNome());
        comando.setString(2, c.getSobrenome());
        comando.setInt(3, c.getTelefone());
        comando.setString(4, c.getEmail());
        comando.setDate(5, c.getData());
        comando.setDouble(6, c.getValor());
        comando.setInt(7, c.getCodigo());

        comando.executeUpdate();

    }
}

E aqui esta a parte do JUnit:
    @Test
    public void atualizar() throws SQLException {

        Cliente c = new Cliente();
        c.setCodigo(7);
        c.setNome("Koppa");
        c.setSobrenome("Troppa");
        c.setTelefone(11111);
        c.setEmail("firstname.lastname@example.com");
        c.setData(new Date(2016/07/10));
        c.setValor(5.00);

        Balada b = new Balada();
        b.setCodigo(14);
        c.setBalada(b);

        ClienteDAO dao = new ClienteDAO();
        dao.atualizar(c);

    }
}

Eis o erro gerado:

java.sql.SQLException: No value specified for parameter 8

Screenshot do erro:
Answer:
Não há porque usar o StringBuilder para construir uma String cada vez que cada método é chamado, sendo que sempre a mesma String será construída. Usar uma String fixa já pré-fabricada é bem melhor e mais simples.
Observe que se alguma exceção for lançada, o ResultSet, o PreparedStatement e/ou o Connection não são fechados em lugar nenhum, e portanto são mantidos abertos, o que pode ocasionar vários problemas. Mesmo se você chamar os métodos close() explicitamente, deverá tomar o cuidado de garantir que eles sejam chamados mesmo se a execução for abortada com uma exceção (e daí o uso do finally deve ser lembrado). Entretanto, é para esse tipo de situação que a sintaxe try-with-resources foi concebida no Java 7.
Definir o tipo como sendo ArrayList<AlgumaCoisa> não é considerado uma boa prática de programação quando List<AlgumaCoisa> for suficiente. A principal razão é que usando ArrayList<AlgumaCoisa> (exceto no construtor) significa que você está codificando para uma implementação, enquanto que com List<AlgumaCoisa> você está codificando para uma interface. As boas práticas de desenvolvimento de software orientado a objetos dizem que o ideal é codificar-se para uma interface e não para uma implementação.
Use a sintaxe do diamante que o Java 7 introduziu para ter que evitar de repetir os tipos genéricos nos construtores.
Este código aqui:
StringBuilder sql = new StringBuilder();
sql.append("UPDATE cliente");
sql.append("SET codigo = ? , nome = ? , sobrenome = ? , telefone = ? ,"
        + " email = ? ,  data = ? , valor = ? , baladas_codigo = ? ");
sql.append("WHERE codigo =  ? ");

Produz a seguinte String:
UPDATE clienteSET codigo = ? , nome = ? , sobrenome = ? , telefone = ? , email = ? ,  data = ? , valor = ? , baladas_codigo = ? WHERE codigo =  ?

Esta String tem dois problemas. O primeiro problema é que ao usar o StringBuilder, você não se atentou aos espaços e acabou produzindo um clienteSET tudo junto, o que obviamente dá um erro de sinatxe no SQL.
O segundo problema é que não faz sentido você colocar o código do cliente duas vezes, vez que o código do cliente informado no WHERE (o cliente a ser alterado) é o mesmo informado no SET. Você não está tentando alterar o código do cliente aqui, e só faz sentido colocar no SET aquilo que você quer alterar. Assim sendo o primeiro codigo = ? não deveria estar lá.
O código da sua atualização não define todos os campos que deveriam ser definidos. Faltou preencher o campo do código da balada e também faltou o primeiro código do cliente (mas de acordo com o item 5 acima, este não deveria estar na SQL mesmo).

Eis como fica o seu código com estes problemas todos arrumados:
package com.sistemacliente.DAO;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.sistemacliente.domain.Balada;
import com.sistemacliente.domain.Cliente;
import com.sistemacliente.factory.ConexaoFactory;

public class ClienteDAO {

    private static final String SQL_SALVAR = "INSERT INTO cliente (nome, sobrenome, telefone, email, data, valor, baladas_codigo) VALUES (?, ?, ?, ?, ?, ?, ?)";

    public void salvar(Cliente c) throws SQLException {
        try (
            Connection conexao = ConexaoFactory.conectar();
            PreparedStatement comando = conexao.prepareStatement(SQL_SALVAR);
        ) {
            comando.setString(1, c.getNome());
            comando.setString(2, c.getSobrenome());
            comando.setInt(3, c.getTelefone());
            comando.setString(4, c.getEmail());
            comando.setDate(5, c.getData());
            comando.setDouble(6, c.getValor());
            comando.setInt(7, c.getBalada().getCodigo());
            comando.executeUpdate();
        }
    }

    private static final String SQL_LISTAR = "SELECT c.codigo, c.nome, c.sobrenome, c.telefone, c.email, c.data, c.valor, b.codigo, b.descricao FROM cliente c INNER JOIN balada b ON b.codigo = c.baladas_codigo";

    public List<Cliente> listar() throws SQLException {
        List<Cliente> lista = new ArrayList<>();

        try (
            Connection conexao = ConexaoFactory.conectar();
            PreparedStatement comando = conexao.prepareStatement(SQL_LISTAR);
            ResultSet resultado = comando.executeQuery();
        ) {
            while (resultado.next()) {
                Balada b = new Balada();
                b.setCodigo(resultado.getInt("b.codigo"));
                b.setDescricao(resultado.getString("b.descricao"));

                Cliente c = new Cliente();
                c.setCodigo(resultado.getInt("c.codigo"));
                c.setNome(resultado.getString("c.nome"));
                c.setSobrenome(resultado.getString("c.sobrenome"));
                c.setTelefone(resultado.getInt("c.telefone"));
                c.setEmail(resultado.getString("c.email"));
                c.setData(resultado.getDate("c.data"));
                c.setValor(resultado.getDouble("c.valor"));
                c.setBalada(b);

                lista.add(c);
            }
        }
        return lista;
    }

    private static final String SQL_EXCLUIR = "DELETE FROM cliente WHERE codigo = ?";

    public void excluir(Cliente c) throws SQLException {
        try (
            Connection conexao = ConexaoFactory.conectar();
            PreparedStatement comando = conexao.prepareStatement(SQL_EXCLUIR);
        ) {
            comando.setInt(1, c.getCodigo());
            comando.executeUpdate();
        }
    }

    private static final String SQL_ATUALIZAR = "UPDATE cliente SET nome = ?, sobrenome = ?, telefone = ?, email = ?, data = ?, valor = ?, baladas_codigo = ? WHERE codigo = ?";

    public void atualizar(Cliente c) throws SQLException {
        try (
            Connection conexao = ConexaoFactory.conectar();
            PreparedStatement comando = conexao.prepareStatement(SQL_ATUALIZAR);
        ) {
            comando.setString(1, c.getNome());
            comando.setString(2, c.getSobrenome());
            comando.setInt(3, c.getTelefone());
            comando.setString(4, c.getEmail());
            comando.setDate(5, c.getData());
            comando.setDouble(6, c.getValor());
            comando.setInt(7, c.getBalada().getCodigo());
            comando.setInt(8, c.getCodigo());
            comando.executeUpdate();
        }
    }
}

Answer: Bom, faz tempo que não programo em java, mas acredito que seu erro esta aqui:
    StringBuilder sql = new StringBuilder();
    sql.append("UPDATE cliente");
    sql.append("SET codigo = ? , nome = ? , sobrenome = ? , telefone = ? ,"
            + " email = ? ,  data = ? , valor = ? , baladas_codigo = ? ");
    sql.append("WHERE codigo =  ? ");

Primeiro ponto, que não é recomendado atualizar o código quando ele for a chave primaria e principalmente quando ele esta na condição WHERE. E repare que voce passou 9 vezes o ?, então ele vai esperar que você passe 9 valores posteriormente o que no caso voce não fez. Você colocou apenas 7, faltando o baladas_codigo:
    comando.setString(1, c.getNome());
    comando.setString(2, c.getSobrenome());
    comando.setInt(3, c.getTelefone());
    comando.setString(4, c.getEmail());
    comando.setDate(5, c.getData());
    comando.setDouble(6, c.getValor());
    comando.setInt(7, c.getCodigo());

O correto seria algo proximo disso:
 public void atualizar(Cliente c) throws SQLException {

    StringBuilder sql = new StringBuilder();
    sql.append("UPDATE cliente");
    sql.append("SET nome = ? , sobrenome = ? , telefone = ? ,"
            + " email = ? ,  data = ? , valor = ? , baladas_codigo = ? ");
    sql.append("WHERE codigo =  ? ");

    Connection conexao = ConexaoFactory.conectar();

    PreparedStatement comando = conexao.prepareStatement(sql.toString());

    comando.setString(1, c.getNome());
    comando.setString(2, c.getSobrenome());
    comando.setInt(3, c.getTelefone());
    comando.setString(4, c.getEmail());
    comando.setDate(5, c.getData());
    comando.setDouble(6, c.getValor());
    comando.setDouble(7, c.getBaladas_codigo());// Aqui é só um exemplo, poi pelo que vi, esta em outra tabela, ou você retira do SQL ou passa de alguma forma

    comando.setInt(8, c.getCodigo());

    comando.executeUpdate();

}

Acredito que seja o erro que esta acontecendo. Qualquer coisa comenta aqui, se não consegui explicar bem!
Comment: Sem contar que é desnecessário criar um StringBuilder para construir a query e depois converter para String. Mais fácil fazer uma query direto em string
Comment: Então...  Ficaria até mais simples e legível


python cant find packages on ec2 instance

Question: I am trying to run a python-script on an aws ec2-instance using jenkins.
I get the following error:
<code>[ProdTest] $ /bin/sh -xe /tmp/jenkins14047325752732522807.sh
+ python3 prod.py
Traceback (most recent call last):
  File "prod.py", line 2, in <module>
    import base
  File "/home/jenkins-slave-strat/workspace/ProdTest/base.py", line 3, in <module>
    import boto3
ModuleNotFoundError: No module named 'boto3'
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>
on the ec2 instance:
<code>$ python3 --version
Python 3.7.9

$ pip3 install boto3 --user
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Requirement already satisfied: boto3 in /usr/local/lib/python3.7/site-packages (1.16.25)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/site-packages (from boto3) (0.10.0)
Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/site-packages (from boto3) (0.3.3)
Requirement already satisfied: botocore<1.20.0,>=1.19.25 in /usr/local/lib/python3.7/site-packages (from boto3) (1.19.25)
Requirement already satisfied: urllib3<1.27,>=1.25.4; python_version != "3.4" in /usr/local/lib/python3.7/site-packages (from botocore<1.20.0,>=1.19.25->boto3) (1.26.2)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.7/site-packages (from botocore<1.20.0,>=1.19.25->boto3) (2.8.1)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.20.0,>=1.19.25->boto3) (1.15.0)
</code>
How do i get python to access the packages in /usr/local/lib/python3.7/site-packages ?
Thanks to everyone taking the time!
Answer: Before I give a short answer, a few cautions:

I don't know what version of Linux (I assume) the EC2 instance is running.
As a result, it's unclear if Python 2 is installed, but since you used pip3 and not just pip, it seems like it might be.

You could try altering your $PATH variable, but it's generally considered a good practice to use virtual environments for Python. I'm personally a fan of Conda, but you can find guides for Pipenv as well. My advice is; install Conda via Miniconda, then do the following:
<code>$ conda create --name myAppEnv python=your.python.version
$ conda activate myAppEnv
$ conda install [your libraries]
</code>
Comment: weirdly, the site-package is included in the PATH. I even got some seemingly contradicting statements when installing packages (in this example numpy):
WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/usr/local/bin' which is not on PATH.
However, when checking the path it gives:
$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/ec2-user/.local/bin:/home/ec2-user/bin

Anyways, your solution works and looks like better practice than anything i ve been doing at this point :D thanks!
Comment: Yeah. If you're not a data science person you may want to look into Pipenv, but basically any Python developer, even on a single purpose VM, should use virtual environments. It's just a quirk of how the language has fragmented.


How to pass arguments in ruby on rails

Question: I have an issue with the code below, it takes no argument, and i am suppose to create a method to return the answer. I don't know how to get the value passed.
And please what is the name of this concept, so i can read it up.
describe "reverser" do
it "reverses the string returned by the default block" do
  result = reverser do
    "hello"
  end
  result.should == "olleh"
end
end

def reverser(sent)
words = sent.split(" ")
  i = 0
  while i < words.length
   words[i] = words[i].reverse
   i += 1
  end
  words.join(" ")
end

Answer: def reverser
  yield.reverse
end

Here is the code in question:
result = reverser do
  "hello"
end

That is equivalent to:
result = reverser() do
  "hello"
end

Breaking that down:
    method call -+      +- 'do' marks the start of the block
                 |      |
                 V      V
    result = reverser() do
      "hello"
    end
     ^
     |
     +--- end of the block

A block is like a method, and it's as if the block is passed as an invisible argument to the reverse() method.  Inside reverse(), you can call the block using yield:
def reverser
  return_value_of_block = yield
  return_value_of_block.reverse
end

Writing yield, or yield(), is like writing unamed_block_method(). In other words, yield is the name ruby gives to the block-method.
And if the block is supposed to take arguments, then the block will look like this:
result = do_stuff do |x|
  x * 2
end

And do_stuff() will look like this:
def do_stuff
  return_value_of_block = yield(4)  #call block with the argument 4
end

And please what is the name of this concept, so i can read it up.

Search for ruby blocks.
Comment: Explicitly return is not necessary here.
Answer: Your reverser takes a block which you call to get it return value:
def reverser(&block)
  string = block.call
  string.reverse
end

Note: You do not need the string variable. I just use it for readability reasons. You can also just write block.call.reverse.
Comment: Thanks. I also saw the "yield" implementation
Comment: Block.call is two times slower than yield. Please be aware of that.
Comment: As I wrote: I aimed for readability and tried to make my solution easy to understand. Performance was not my priority.

How to pass arguments in ruby on rails


Views relationship outputting duplicate nodes?

Question: I have a view of Planet content types. These Planets have a node reference field for Trade Routes to reference other Planets. I'm attempting to output both the current Planet's x/y coordinates, as well as the x/y coordinates of the Planets it references in it's Trade Routes field.
Setting up the fields with each Planet outputting its own x/y and the x/y fields again but using the Trade Route relationship this time results in each Planet being returned as a row once per Trade Route it is storing, instead of returning an array of x/y like I would expect.
What am I doing wrong here?
Comment: I had something similar, try changing your relationships to "required". it fixed my problem. give it a shot
Answer: Maybe You can try to use the Query Parameter and check the "Distinct" option to have distinct result :
Answer: I've tried every recomendation I've found and nothing seems to do the trick perfecly. The most precise result I can get is filtering the views results before rendering the view, like this:
<code>function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}
</code>
Put that snippet in your template.php and replace YOURTHEMENAME and YOURVIEWNAME with your values, you should have no duplicates. HOWEVER, I'm finding that this creates pages with less rows than expected, for example, if you want 10 results per page and your view has 8 duplicates in the first page, the first page would have just 2 rows. So, take my code as a partial result and only if you don't care having less results per page or if you are displaying all results at once.
Answer: you can use an "attachment" to show the related content. This article describes it well.
Or you could use the table format and group by the first field. That will put the first field above the table and just show the values of the 2nd field in the table.


Rewrite *all* non-file requests to index.php with htaccess

Question: I'm basically trying to have everything that's not a file (.css, .js, .jpg, etc...) rewrite to index.php to create sym-links. The code I have in my .htaccess file works for my root directory and for a single subdirectory So. "localhost/" and "localhost/help" both work, but "localhost/help/article-27" does not work. The .htaccess seems to rewrite everything when I try to use that second sub-directory, including JS and CSS files. Does anyone know why that is? Here's my code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [L]
</IfModule>

Comment: You shouldn't have any need for the `RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]` line in there.
Comment: Does `help/` also have a .htaccess?
Answer: As darren mentioned as per the comments it's not required to have $1 !!.(gif|jpe?g|png)$ [NC]
This will work for all the levels and CSS files whether symlink / direct links.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [L]
</IfModule>


Text Rotator Infinito

Question: Estou com o seguinte código:

var words = ['Buy it',
    'Use it',
    'Break it',
    'Jam it',
    'Unlock it',
    'Save it'],
     current_length = 0,
     current_direction = 1,
     current_word = 0,
     character_delay = 50,
     word_delay = 500,
     $title = $('h1');

    function advanced_text() {
      if(current_direction == -1) {
        $title.addClass('highlighted');
        setTimeout(function() {
          $title.removeClass('highlighted');
          current_length = 0;
          current_direction = 1;
          current_word++;
          setTimeout(advanced_text,0);
        },word_delay/2);
        return;
      }
      current_length += current_direction;
      var timeout_delay = 0;
      set_text($title, words[current_word], current_length);
      if(current_length >= words[current_word].length) {
        current_length = words[current_word].length;
        current_direction = -1; //Now we're deleting
        if(current_word >= words.length -1) {
          //stop! we're done
          return;
        }
        //set long timout
        timeout_delay = word_delay;
      }
      timeout_delay = timeout_delay ? timeout_delay : (current_direction > 0 ? character_delay-10+Math.random()*20 : character_delay/4);
      setTimeout(advanced_text, timeout_delay);
    }

    advanced_text();

    function set_text($element, word, length) {
      $element.text(word.substring(0,length));
    }
h1 {
      border-right: 1px solid;
      display:inline-block;
      padding-right:4px;
      animation: 1s infinite blink;
    }

    *.highlighted {
      background:#338fff;
      color:#fff;
      display:inline-block;
    }

    @keyframes blink {
      0% {
        border-color: rgba(0,0,0,0);
      }
      49.99% {
        border-color: rgba(0,0,0,0);
      }
      50% {
        border-color: rgba(0,0,0,255);
      }
      99.5% {
        border-color: rgba(0,0,0,255);
      }
    }

Minha dúvida é como deixar a parte do js com loop infinito. Depois de o código ler todo o js, ele simplesmente para na última tag do array. Como fazer ele ficar em loop e ficar repetindo os valores do array?
Comment: Tem alguns plugins prontos pra isso. https://www.sitepoint.com/jquery-infinite-scrolling-demos/
Answer: neste ponto, no lugar de interromper o fluxo, reinicie o valor de current_word
if(current_word >= words.length -1) {
  //stop! we're done
  return;
}

então teremos isto.:
if(current_word >= words.length -1) {
  current_word = 0;
}

var words = ['Buy it',
    'Use it',
    'Break it',
    'Jam it',
    'Unlock it',
    'Save it'],
     current_length = 0,
     current_direction = 1,
     current_word = 0,
     character_delay = 50,
     word_delay = 500,
     $title = $('h1');

    function advanced_text() {
      if(current_direction == -1) {
        $title.addClass('highlighted');
        setTimeout(function() {
          $title.removeClass('highlighted');
          current_length = 0;
          current_direction = 1;
          current_word++;
          setTimeout(advanced_text,0);
        },word_delay/2);
        return;
      }
      current_length += current_direction;
      var timeout_delay = 0;
      set_text($title, words[current_word], current_length);
      if(current_length >= words[current_word].length) {
        current_length = words[current_word].length;
        current_direction = -1; //Now we're deleting
        if(current_word >= words.length -1) {
          current_word = 0;
        }
        //set long timout
        timeout_delay = word_delay;
      }
      timeout_delay = timeout_delay ? timeout_delay : (current_direction > 0 ? character_delay-10+Math.random()*20 : character_delay/4);
      setTimeout(advanced_text, timeout_delay);
    }

    advanced_text();

    function set_text($element, word, length) {
      $element.text(word.substring(0,length));
    }
h1 {
      border-right: 1px solid;
      display:inline-block;
      padding-right:4px;
      animation: 1s infinite blink;
    }

    *.highlighted {
      background:#338fff;
      color:#fff;
      display:inline-block;
    }

    @keyframes blink {
      0% {
        border-color: rgba(0,0,0,0);
      }
      49.99% {
        border-color: rgba(0,0,0,0);
      }
      50% {
        border-color: rgba(0,0,0,255);
      }
      99.5% {
        border-color: rgba(0,0,0,255);
      }
    }

Text Rotator Infinito


do we need to lock this queue?

Question: If there is only one thread to add to queue and only one thread to retrieve from the queue, it is not necessary to lock the queue for those access actions, I think.
Usually the retrieve will be in a loop. If it missed one item, it will get it in next try. only concern is getting a partially data. if it is value type queue and the value is bigger than one basic memory unit, it may happen. but if it is a reference type, it should be ok.
am i right?
Answer: Assuming you are talking about Queue<T>.
As long as the thread which is writing and the thread which is reading are the same thread then no a lock is not needed.  If they are different threads then yes indeed a lock is needed.  The documentation explicitly states that a lock is needed if there are readers and writers on different threads

http://msdn.microsoft.com/en-us/library/7977ey2c.aspx
Comment: If you're using .NET 4 you can use ConcurrentQueue and let that class deal with the synchronisation issues. http://msdn.microsoft.com/en-us/library/dd267265.aspx
Comment: @Paolo, `ConcurrentQueue` only makes it's own internal data integrity automatic.  It, and any other mutable concurrent structure, must be handled with great care.  They don't remove race conditions by any means.
Answer: I believe a Queue keeps information in an array; if the number of items in the queue would exceed the size of the array, the array will be replaced with a bigger one.  The Queue contains no mechanisms to avoid disrupting queue operations which are in process when such reallocation occurs.
It is certainly possible to construct lock-free queue implementations which will work fine with a concurrent reader and writer.  If one uses a linked-list data structure, it is also possible to support multiple concurrent writers without using locks (use Interlocked.CompareExchange to update the queue).  A linked-list queue which requires allocating a new object for every insertion will often not be as efficient as an array-based one, but multi-writer queues can be handy.

do we need to lock this queue?


Converter Blob em String no angularJs

Question: Olá, estou com um código em angularJS porém só funciona quando estou no debug do browser.
    $scope.upload=function(){
        var newFiles = [];
        $scope.carregando = true;
        angular.forEach($scope.files, function (item) {
            if(item.upload){
                item.idFicha = vm.ficha.id;
                var reader  = new FileReader();
                reader.readAsDataURL(item._file);

                //TODO Quero recuperar a substring do result.
                item.arquivo = reader.result.substr(reader.result.indexOf(',') + 1);

                newFiles.push(item);
                item.upload = false;
            }
        });
        service.uploadDocumento(newFiles);
        $scope.carregando = false;
    };

Bem, quando tiro o breakpoint para executar a função a variável item.arquivo fica nula, mas se eu colocar o breakpoint e inspecionar a variável é está com valor e a função funcionar perfeitamente.
O que pode estar acontecendo e o que devo fazer para dar fim nesse problema?
Answer: Acontece que a API FileReader carrega os dados de forma assíncrona, isso quer dizer que o código continuará sendo processado, mesmo que uma determinada função ainda não esteja completa, ou seja, o código não espera uma determinada linhar "terminar seu trabalho".
Quando temos uma função assíncrona, nós também temos alguns eventos disponíveis. No caso do FileReader, os eventos são:

abort: Será chamado quando o procedimento for abortado;
error: Será chamado quando houver algum erro;
load: Será chamado quando o arquivo for carregado;
loadstart: Será chamado no início do carregamento do arquivo;
loadend: Será chamado no final do carregamento do arquivo;
progress: Será chamado durante o carregamento do arquivo.

No seu caso, você terá que adicionar toda a regra do seu código na função load, por exemplo:

const input = document.querySelector("input");

input.addEventListener("change", () => {
  for (let file of input.files) {

    let reader = new FileReader();
    reader.addEventListener("load", result => {
      console.log( `Teste #2: ${reader.result}` )
    })
    reader.readAsDataURL(file);
    console.log( `Teste #1: ${reader.result}` )
  }

});
<input type="file" multiple />

Como eu citei, o FileReader não espera o arquivo ser carregado para poder continuar o processamento restante do código, porém quando adicionamos um breakpoint, nós forçarmos essa "pausa". Isso é o tempo necessário para que o FileReader possa ler o arquivo e já armazenar na propriedade result.

Converter Blob em String no angularJs


How to calculate the limit of a sequence having a factorial $ \lim_{n\to \infty}\frac{\ln \left ( n \right )}{\left ( n! \right )^{\frac{1}{n}}} $

Question: The limit of

$$ \lim_{n\to \infty}\frac{\ln \left ( n \right )}{\left ( n! \right )^{\frac{1}{n}}} $$

Since the sequence is positive , can we find a sequence bigger having as a limit 0 ?
Comment: Use Stirling approximation.
Answer: Use Stirling's Formula,
\begin{align}
n!\sim \sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\end{align}
then it follows
\begin{align}
\lim_{n\rightarrow \infty} \frac{e \ln n}{(2\pi n)^{1/2n} n} =0.
\end{align}
Answer: Assume first $n$ is even. Then there are exactly $n/2$ integers among $1,2,\dots , n$ that are $>n/2.$ Thus $n!> (n/2)^{n/2},$ giving $(n!)^{1/n}> (n/2)^{1/2}.$ So
$$\tag 1 \frac{\ln n}{(n!)^{1/n}}< \frac{\ln n}{(n/2)^{1/2}}.$$
Since $(\ln n)/n^{1/2} \to 0,$ the limit of $(1)$ is $0$ as $n\to \infty$ through even values.
The case of odd $n$ is basically the same.
Answer: Yes, you can.  First, take the log of the factorial:
$$\ln(n!)=\ln(1\times2\times\dots\times n)=\sum_{k=1}^n\ln(k)$$
Which is derived from log rules.  Then note that
$$\sum_{k=1}^n\ln(k)>\int_1^n\ln(x)\ dx=n\ln(n)-n+1>n\ln(n)-n$$
Thus,
$$\log(n!)>n\ln(n)-n$$
$$n!>\left(\frac ne\right)^n$$
$$(n!)^{1/n}>\frac ne$$
Which reduces your limit to the following:
$$0<\frac{\ln(n)}{(n!)^{1/n}}<e\frac{\ln(n)}{n}$$
which can be proven to go to zero in one application of L'Hospital's rule.


Paramiko not returning stdout

Question: I'm using Paramiko to make a few SSH commands from a python program. The commands I am using are:
stdin, stdout, stderr = client.exec_command('ls')
print stdout
client.close()

however I'm getting the same output - it looks like a different data-type. Any ideas anybody? It's definitely not a list of files!
<paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x801d6750L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>

Thanks!
Answer: Whoops - figured it out straight after. I forgot to do readlines() on stdout.
So, before the print statement I should have:
stdout = stdout.readlines()

Paramiko not returning stdout


Find the exponent 2 in the decomposition of $A$ into prime factors

Question: Let's put $A=100!$
Find the highest power  of 2 in A after the decomposition of A of prime numbers
I tried this :
$$
A=1\times2\times3\times4\times\ldots\times99\times100\\
=(2\times4\times6\ldots\times100)\times(1\times3\times5\times \ldots\times99)\\
=2(1+2+3+...+50)((2+1)(4+1)(6+1)...(98+1))
$$
Comment: If you are asking for the highest power of 2 in 100!,it can be got as sum of all [100/2^n] where n varies from 1 to 6 and [n] is the greatest integer function
Comment: The last passage is nonsense to me. Why does the product become a sum?
Comment: Possible duplicate of [Highest power of a prime $p$ dividing $N!$](http://math.stackexchange.com/questions/141196/highest-power-of-a-prime-p-dividing-n).  While the Question above contains a fairly erroneous attempt to answer, I don't think that makes it worthwhile to keep open, given the numerous similar problems on the site since early days.
Comment: @Ant: Makes sense, although it was such a charming use that I thought about just adjoining the usual term as a footnote.
Comment: @BrianTung As I don't speak French, it was not charming, just confusing :-)
Answer: Sum up $trunc(\frac{100}{2^k})$ , $1\le k\le 6$. You get $$50+25+12+6+3+1=97$$
Note that $2^7>100$
Comment: Peter's answer is correct. The result presented in his answer is an application of Legendre's formula (see: https://en.wikipedia.org/wiki/Legendre's_formula).
Comment: @Xaver: Yeah, I was answering the wrong question (despite my comment that suggested the exact reverse!).
Answer: Another approach: This is the same basic approach as in Peter's answer, but gets at the value in a different way.  Let $m = $ the number of $1$'s in the binary expansion of $n$.  Then the answer is $n-m$.  Since the binary expansion of $100$ is $1100100$, the answer is $100-3 = 97$.
This can be seen as follows: As per Peter's answer, we are calculating $P_2$, the exponent of $2$, as
$$
P_2 = \sum_{k=1}^\infty \text{trunc} \left(\frac{n}{2^k}\right)
$$
Peter has it as $k = 1$ to $6$, but since the truncations after $k = 6$ add nothing, this doesn't change the final result, and will make the explanation clearer (I hope).  On the other hand, we can also write
$$
n = \sum_{k=1}^\infty \frac{n}{2^k}
  = \frac{n}{2} + \frac{n}{4} + \frac{n}{8} + \cdots
$$
If we write $n$ out in binary, we find that the difference $n-P_2$ is accounted for exactly by the $1$'s in that binary expansion: As we successively halve $n$, we have an excess whenever a $1$ is encountered in the ones digit.  At that point, halving produces an excess of $1/2$.  In the next halving, it produces an additional excess of $1/4$, then $1/8$, etc.  As a result, as $k$ runs from $1$ to $\infty$, each $1$ produces an excess of $1/2+1/4+1/8+\cdots = 1$.  The total excess is therefore $m$, and since $n-P_2 = m$, it follows that $P_2 = n-m$.
Just for good measure, the exponent of $2$ in prime factorization of $(100!)!$ is $100! - 207$, since there are $207$ $1$'s in the binary expansion of $100!$ (which has $525$ digits in all, the last $97$ of which are $0$, as you would expect).
Comment: @Peter: Just a calculating trick.  I've added an explanation, not quite a proof, but it could be turned into one.
Comment: Never heard of this method. +1 It would be nice if you would prove that it works.
Answer: Your formula in the last row is incorrect, but if you fix it, it should put you on the right path.
$$100! = (2 \times 4 \times 6 \cdots \times 100) \times (\text{an odd number}) = 2^{50} \times 50! \times (\text{an odd number}),$$
so this gives you an exponent of $50$, plus whatever the exponent of $2$ in $50!$. You should be able to recognize a recurrence here: this is why the answer is $50 + 25 + \cdots$ as in Peter's answer.


Merge a flv with mp3 without replacing flv audio stream using FFMPEG

Question: I would like to merge a flv with mp3 without touching / removing flv audio stream using ffmpeg in php. I tried many commands and none helps. Here is the command I am using now.
/usr/bin/ffmpeg -i "4bpCRRV82x.flv"-i "Someday.mp3" -vcodec libx264  -shortest "output.mp4"

But it replaces flv audio with the mp3 inputting.
Any help and suggestions will be highly appreciable. Thanks.
Comment: Why dont you extract first the video's audio, merge your track with, and then use that command to put back the audio?
Comment: @ITomas Will it slow down the entire process ?
Comment: Well, currently ffmpeg seems to support exactly what you are looking for, see http://www.ffmpeg.org/ffmpeg-filters.html#amerge
Comment: Please include the complete `ffmpeg` console output. You should provide more information before an accurate answer can be provided. How do you want to "merge"? I'm assuming both inputs are stereo. Do you want the output to be stereo or 4 channels? Do you want the output to contain one audio stream or two separate audio streams?
Comment: @LordNeckbeard : Sorry for the short note. I want to get output as one audio stream with original video.
Answer: Assuming both inputs contain stereo audio you can use the amerge audio filter to merge both stereo streams into a single four channel stream, then use the pan audio filter to combine the appropriate channels into a single stereo stream:
ffmpeg -i video.flv -i audio.mp3 -filter_complex \
"[0:a][1:a]amerge,pan=stereo:c0<c0+c2:c1<c1+c3[a]" \
-map 0:v -map "[a]" -c:v copy -c:a aac -strict experimental -shortest out.mp4

The video can be stream copied (depending on the input video format) as shown in the example if you do not need to re-encode it, but if you must re-encode then see the FFmpeg and x264 Encoding Guide.
The example uses the native FFmpeg AAC encoder which requires -strict experimental (or the alias -strict -2). See the FFmpeg and AAC Encoding Guide for information on other encoders.
The option -shortest will finish encoding when the shortest input stream ends.
See Manipulating audio channels with ffmpeg for more examples.
Make sure you're using a recent version of ffmpeg. See the FFmpeg Download page for builds for Windows, OS X, and Linux.
Comment: Thank you for the detailed answered, but I am getting error "Error while opening encoder for output stream #0:1 - maybe incorrect parameters such as bit_rate, rate, width or height" when using your code. Please check this for detailed output : http://sharetext.org/vni5
Answer: As of the ffmpeg documentation you may use the amerge filter
http://www.ffmpeg.org/ffmpeg-filters.html#amerge
ffmpeg -i input.mkv -filter_complex "[0:1][0:2][0:3][0:4][0:5][0:6] amerge=inputs=6" -c:a pcm_s16le output.mkv

Answer: FLV does not support multiple audio streams. Technically is is possible in the binary format by incrementing the stream id. However the FLV documentation says the stream id should always be 0. so even if you did create this file, most players would not play it.


MySQL Join with condition of previous join

Question: Select t3.* from table1 t1
left join table2 t2  on t1.id_traslado=t2.id_traslado
inner join table3 t3 on IFNULL(t2.id_traslado,t3.id_traslado=t1.id_traslado,t3.id_pasajero=t2.id_pasajero)

I have a query similar to this, but obviously it's not woking, is there any way to join the third table with differents columns, depending if the second table contains any results?
EDIT:
The columns of the tables are like that:
t3===> id_reserva  id_prestacion  id_traslado(NULL)  id_pasajero(NULL)
t2(NULL) ===>id_traslado  id_pasajero
t1===>id_traslado
if t2 is not null, the relation between t3 and t1 with id_traslado doen't exits and it's replaced with t2 and t3 relation with id_pasajero
Comment: is there any relation between t1 and t3?
Comment: Yes, t2 relations with t3 with columnaux2 ... and t1 relations with t3 columnaux1
Answer: use this way of join hope no need to check tabl2 data exist or not
Select * from table1 t1
inner join table3 t3  on t1.columnaux1=t3.columnaux1
left join  table2 t2 on t3.columnaux2=t2.columnaux2

Comment: No.. i already think of that... the problem is that if the relation with table2 and table1 exists "inner join table3 t3  on t1.columnaux1=t3.columnaux1" this is null..
Comment: can you please share your sample data of 3 table and sample output it would help to give answer
Comment: i have updated the question, any ideas now?
Answer: Try this:
inner join table3 t3 on t3.columnaux1= COALESCE(t2.columnaux2, t1.columnaux1)


plot df on map - two plots instead of one

Question: enter image description hereenter image description hereI want to plot data from a df in a map. However, I don't manage to print out the values in the plot, but I get two plots - one with an empty map and one with the values without map.
What am I doing wrong?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cf

#ax1=plt.axes(projection=ccrs.Mercator())
#fig, ax=plt.subplots(figsize=(8,6))
ax1.add_feature(cf.BORDERS);
ax1.add_feature(cf.RIVERS);
ax1.set_extent([7.4, 8.8, 47.5, 49.1])
ax1.set_title('Niederschlag', fontsize=13);
ax.grid(b=True, alpha=0.5)

df.plot(x="longitude", y="latitude", kind="scatter",
c='RR',colormap="YlOrRd")

plt.show()

Thanks in advance
Comment: kindly attach your data sample as well also make your question a little more clear to understand
Comment: secondly it would be best to use geo pandas for some thing like this as mentioned in answer below
Answer: pandas.DataFrame.plot creates a new plot by default, this is why you are getting two plots: first you crate one with ax1=plt.axes(projection=ccrs.Mercator()), then pandas creates another one.
To fix this you can use the ax argument on pandas.DataFrame.plot:
df.plot(x="longitude", y="latitude", kind="scatter", c='RR',colormap="YlOrRd", ax=ax1)

Edit
There is also a problem with the projection. You are setting the projection as Mercator which uses a different coordinates system from the standard one. When you set the bounds you are not specifying the projection and it being converted automatically. Your points though are in a different projection and no automatic conversion is performed.
To fix this I suggest using a different projection to start with (e.g.: PlateCarree). If this is not possible then you would need to convert the coordinates yourself.
This code produces a map with points:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cf

df = pd.DataFrame(
    {
        "longitude": [7.99, 8.42, 7.78],
        "latitude": [48.98, 48.74, 47.59],
        "RR": [5, 15, 25],
    }
)

ax1=plt.axes(projection=ccrs.PlateCarree())
ax1.add_feature(cf.BORDERS)
ax1.add_feature(cf.RIVERS)
ax1.set_extent([7.4, 8.8, 47.5, 49.1], crs=ccrs.PlateCarree())
ax1.set_title('Niederschlag', fontsize=13);
ax1.grid(b=True, alpha=0.5)

df.plot(x="longitude", y="latitude", kind="scatter", c="RR", colormap="YlOrRd", ax=ax1)

Comment: Thanks Matteo! Now i have the legend in the wanted plot, but still not the values... :(
Comment: I am not sure what data you have in your dataframe, are you sure the points are inside the bounds? Also maybe check https://stackoverflow.com/questions/43470238/cartopy-set-extent-extending-requested-boundary
Comment: Yes they are in the domain; see: https://i.stack.imgur.com/GqTEH.png
Comment: I think the problem is with your projection... I will add it to my answer!
Answer: try this : plt.scatter(x=df['Longitude'], y=df['Latitude'])
or try using geo pandas like so
    import pandas as pd
    from shapely.geometry import Point
    import geopandas as gpd
    from geopandas import GeoDataFrame

    df = pd.read_csv("Long_Lats.csv", delimiter=',', skiprows=0, low_memory=False)

    geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])]
    gdf = GeoDataFrame(df, geometry=geometry)

    #this is a simple map that goes with geopandas
    world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
    gdf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='red', markersize=15);

Comment: I'm sorry but I think my experience isn't sufficient to convert this to my problem
Comment: could you share your data so i can run that scenario?
Comment: I don't see an option to share the file; it's like this                                        Station; latitude; longitude; RR                                                                        Durbach; 48.7; 8.2;40.3
Comment: i've added pictures in the original question


Erro no render do Android Studio 2.0

Question: Toda vez que eu abro um arquivo de layout não aparece a preview e aparece um erro no log de eventos. Não é um layout específico, são todos layouts.
Tem um pergunta igual na versão em inglês, mas já possui um ano e está sem resposta.
Erro:
<code>com/xxxx/xxxx/activity/R$mipmap
java.lang.ClassFormatError: com/xxxx/xxxx/activity/R$mipmap
at java.lang.Class.getDeclaredClasses0(Native Method)
at java.lang.Class.getDeclaredClasses(Class.java:1867)
at org.jetbrains.android.uipreview.ViewLoader.parseClass(ViewLoader.java:562)
at org.jetbrains.android.uipreview.ViewLoader.loadAndParseRClass(ViewLoader.java:546)
at org.jetbrains.android.uipreview.ViewLoader.loadAndParseRClassSilently(ViewLoader.java:502)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadAndParseRClass(LayoutlibCallbackImpl.java:663)
at com.android.tools.idea.rendering.RenderTask.<init>(RenderTask.java:153)
at com.android.tools.idea.rendering.RenderService.createTask(RenderService.java:198)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:649)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:80)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:594)
at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:589)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:337)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:327)
at com.intellij.util.ui.update.MergingUpdateQueue$3.run(MergingUpdateQueue.java:271)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:286)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:244)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:234)
at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:352)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>
Update:
Troquei a versão do android no preview de design como dito neste post, não resolveu.
Update 2:
Procurei atualizações pro Android Studio, reinstalei o mesmo e instalei todos os pacotes pelo SDK Manager novamente, também não resolveu.
Answer: Após horas tentando, criei um novo projeto no Android Studio pra copiar os arquivos do projeto para um novo projeto (minha última esperança). Criado o projeto o render voltou a funcionar normalmente. Provavelmente é algum bug do Android Studio, onde já reportei o mesmo.

Erro no render do Android Studio 2.0