Como carregar um arquivo HTML dentro de uma DIV no zend-framework3

Question: Estou trabalhando em uma ferramenta de email marketing e preciso carregar um template HTML dentro de uma DIV na view. Estou usando o zend-framework3. Eu tentei usar a função .load(), mas está dando erro 500. Alguém pode me ajudar??
Eu estou usando a seguinte função:
<code>$('#carregaTemplate').click(function(){

    var qtdProdutos = $('#qtdProdutos').val();

    $(function(){
        if( qtdProdutos == 1 ) {
            $('#arquivoHtml').load('templates/sem_produtos.html');
        }
        if( qtdProdutos == 2 ) {
            $('#arquivoHtml').load('templates/dois_produtos.html');
        }
        if( qtdProdutos == 3 ) {
            $('#arquivoHtml').load('templates/tres_produtos.html');
        }
        if( qtdProdutos == 4 ) {
            $('#arquivoHtml').load('templates/quatro_produtos.html');
        }
    });
});
</code>
Comment: Erro 500 é no lado do servidor, verifique as rotas, veja no console como está montando o endereço para os templates e tente acessá-los diretamente pela barra de endereços.
Comment: Verifiquei as rotas e tentei acessar diretamente também, o navegador exibe a mensagem de que não pode atender a solicitação. Tentei usar um  obtive o mesmo erro 500. Creio que o zend exige uma outra forma para renderizar arquivos HTML. Estou pesquisando, porém não encontrei nada ainda... @Leandro Angelo
Comment: Não adianta colocar em iFrame, você precisa adicionar uma rota para os arquivos estáticos para que ele a ignore sem tentar achar uma controller e uma action para a requisição
Comment: Dê uma olhada aqui https://blog.eduonix.com/web-programming-tutorials/static-pages-in-zend-framework/
Comment: Obrigado @Leandro Angelo. A partir do blog indicado consegui chegar a resolução do problema. Utilizei o exemplo contido aqui https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Routing/Regex_Route_Type.html
Comment: seria interessante você postar uma resposta explicando como você resolveu. Essa informação pode ser muito útil para outros usuários que venham a esbarrar no mesmo problema
Answer: Após muita pesquisa e a contribuição dos caros amigos aqui do stack, consegui resolver o problema da seguinte maneira:
-criei uma rota do tipo Regex. Esse tipo de rota permite renderizar páginas estáticas. Veja exemplo aqui: https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Routing/Regex_Route_Type.html
-no controlador, criei a seguinte função responsável por renderizar a página:
<code>public function docAction() {
    $pageTemplate = 'email-marketing/template/doc' . $this->params()->fromRoute('page', 'documentation.phtml');

    $filePath = __DIR__ . '/../../view/' . $pageTemplate . '.phtml';
    if (!file_exists($filePath) || !is_readable($filePath)) {
        $this->getResponse()->setStatusCode(404);
        return;
    }

    $viewModel = new ViewModel([
        'page'=>$pageTemplate
    ]);

    $viewModel->setTemplate($pageTemplate);

    return $viewModel;
}
</code>
e por fim, a função que carrega a página dentro de uma DIV, no meu caso, ficou assim:
function carregaTemplate() {
<code>    var qtdProdutos = $('#qtdProdutos').val();

    if( qtdProdutos == 1 ) {
        $('#arquivoHtml').load( "<?= $this->url('doc', ['page' => 'pagina']) ?>", function( response, status, xhr ){
            if( status == "error" ) {
                var msg = "Desculpe, ocorreu um erro: ";
                $('#arquivoHtml').html( msg + xhr.status + " " + xhr.statusText );
            }
        });
    }
    if( qtdProdutos == 2 ) {
        $('#arquivoHtml').load( "<?= $this->url('doc', ['page' => 'dois_produtos']) ?>", function( response, status, xhr ){
            if( status == "error" ) {
                var msg = "Desculpe, ocorreu um erro: ";
                $('#arquivoHtml').html( msg + xhr.status + " " + xhr.statusText );
            }
        });
    }
    if( qtdProdutos == 3 ) {
        $('#arquivoHtml').load( "<?= $this->url('doc', ['page' => 'tres_produtos']) ?>", function( response, status, xhr ){
            if( status == "error" ) {
                var msg = "Desculpe, ocorreu um erro: ";
                $('#arquivoHtml').html( msg + xhr.status + " " + xhr.statusText );
            }
        });
    }
    if( qtdProdutos == 4 ) {
        $('#arquivoHtml').load( "<?= $this->url('doc', ['page' => 'quatro_produtos']) ?>", function( response, status, xhr ){
            if( status == "error" ) {
                var msg = "Desculpe, ocorreu um erro: ";
                $('#arquivoHtml').html( msg + xhr.status + " " + xhr.statusText );
            }
        });
    }

}
</code>


Filtragem de resultados em PostgreSQL a partir de menor valor de apenas uma coluna

Question: É uma questão de lógica e conhecimento dos recursos do PostgreSQL. Tenho o seguinte resultado de uma consulta:

Preciso fazer uma filtragem, agrupando por [hora] de modo que permaneça apenas a [hora_real] mais próxima e, consequentemente, toda a linha correspondente (tenho uma série de outras colunas).
Comecei a tentar solucionar calculando o valor absoluto da diferença em segundos. Entretanto, agrupando por hora e calculando o  valor mínimo da coluna [dif_abs], como garantir que os outros valores da linha correspondente permaneçam? Visto que não posso utilizar um agregador, pois poderia não corresponder em alguns casos.
Comment: Nesse caso, deveria permanecer apenas a linha com dif_abs 45? Coloque o resultado esperado e com mais valores, se possível.
Comment: Murillo, consegui com DISTINCT ON. Vou postar a resposta. Obrigado!
Answer: Consegui com DISTINCT ON.
Em Select first row in each GROUP BY group?
, vi uma solução pra isso.
Posso ordenar por [hora] e [dif_abs] e extrair a primeira linha distinta pelo id (que não está na tabela exemplo que mostrei, mas tenho na minha consulta; ou mesmo podemos criar com row_number() OVER ()). Assim:
SELECT DISTINCT ON (id_hora) id_hora, hora, hora_real, dif_abs FROM qry
ORDER BY id_hora ASC, dif_abs ASC

Dessa forma, terei a primeira linha com id único em que a [hora_real] é mais próxima da [hora].


Lat/Long Distance Comparison

Question: I am having some trouble with figuring out how to do this. What I have is a list of 160K locations on an Access table with lat and long coordinates for each. I am trying to find out how to create a column that compares 1 item on the list to the rest of the items to bring back the closest distance in miles.
I've figured out how to use the haversine formula to make a 1 to 1 comparison but I am lost in  trying to automate the rest.
This is basically what I want to try to produce...

Loc_ID  Loc_Lat     Loc_Long     Min_Miles_Away
1       33.537214   -81.687378   674.48
4       42.16584    -87.845117   11.83
5       41.99558    -87.869057   11.83
6       41.85325    -89.486883   83.75

Explanation to the table...
Location 1 is closest to location 5 (674.48 miles apart)
Location 4 is closest to location 5 (11.83 miles apart)
Location 5 is closest to location 4 (11.83 miles apart)
Location 6 is closest to location 5 (83.75 miles apart)

Any help would be appreciated.
Answer: You can do a cartesian join, i.e. a join without a where. It will join each row with every other row. You can do that by simply writing the SQL into the SQL view of the query.

SELECT *
FROM locations a, locations b

Next you can calculate the distance (I guess you have that code already, so just insert the function) on that table.
Finally you can group by MIN.

SELECT loc_id, loc_lat, loc_long, MIN(calulated_distance) as min_miles_away
FROM myCalculatedQuery

Lat/Long Distance Comparison


/node - 404 or 301?

Question: All the suggestions I've seen for getting rid of that stupid /node page involve programmatically disabling it altogether. Is there a specific reason nobody suggests to 301 it to, say, the home page? It seems to me it'd be smarter to teach web crawlers not to visit the page than send them into a dead end.
Answer: I think it only makes sense to use a 301 if you have already been using /node as a page other than the home page, so it has already been indexed by search engines. If you're building a new site, or if your site has been using /node only as front page, then it has not been indexed and you can safely tell users and search engines that the page does not exist.

/node - 404 or 301?


javascript change image when onmouseover and onmouseout

Question: I am a beginner and I am doing a homework and I have a small problem. My task is when onmouseover is on, image1 should be changed to image2. When onmouseout is on, image2 should be changed to image1
Onmouseover works but onmouseout does not work!
Here is my code:
<!DOCTYPE html>

<meta charset="utf-8">
<title>DOM_4</title>

Why my onmouseout does not work? I know there can be better ways to code, but I must use both onmouseover and onmouseout. There should be only HTML and simple javascript codes. (My teacher said so)
Comment: No problem, just wanted to check because it's an easy mistake to make :)
Comment: Is `bakground.jpg` spelled correctly?
Comment: @ ᔕᖺᘎᕊ  I know that it is incorrect. But I just had a file with name bakground.jpg.
Answer: Your function name changePic22() is incorrect and you have also syntax error document.getElementByID
Replace you code to this one
function changePic1() {
  document.getElementById("myImg").src = "screen.jpg";
}
function changePic2(){
  document.getElementById("myImg").src = "bakground.jpg";
}

Comment: Oh! Thanks I did not see that I have a incorrect function name ! but that syntax error I cannot find.. Which syntax error did I do?
Comment: Aha I found that!! Thanks!! It works perfectly. Thank you!
Answer: Try this one:
JS:
function changePic1() {
document.getElementById("myImg").src = "http://res.cloudinary.com/vishakhanehe/image/upload/v1481149848/mickeywaving_ttphnm.gif";
   }
  function changePic22(){
   document.getElementById("myImg").src = "http://res.cloudinary.com/vishakhanehe/image/upload/v1481149848/obama1_c1buc6.jpg";
   }

HTML:


Creating dummy variables before or after splitting to train/test datasets

Question: I have a data set with a few columns of categorical type. As part of modelling process, I need to convert them into dummy variables. My confusions is whether to do dummy creation before or after splitting the data into train/test data sets.

If I do before splitting, doesn't it mean data leakage ? i.e exposing at least a portion of test data to train data ?
If I do it after splitting, what if some levels in train are not in test & vice versa ? If that level (for eg: country_AU) is a predictor variable in the final model trained on the train data, won't it throw error if it couldn't find that predictor in the test data set ?

Any advice is appreciated. Thanks in advance.
Answer: You gotta do it before splitting the data into train and test. There is no data leakage when u do preprocessing. The leakage will happen only when u expose the test data to your model, which has nothing do with the preprocessing phase.
Comment: This is true as long as in your preprocessing nothing is learned from the data itself.  Making dummies is not data dependent, it is just an application of a fixed transformation.  But standardizing, for example, is a preprocessing step that must be handled delicately, since it involves learning the mean and variance of the features in the data.
Comment: It is always tricky to do data pre-processing like missing value imputation, outlier treatment without looking at the complete data. If we really want a pure untouched data set for validation (as we expect to face such data sets in the real world post production), we should separate out a test data set at the very beginning itself. If we do some transformation together & then split, we can't really call them 100% untouched (at least as per my belief).


Difference Equation, verify expression is solution to the equation

Question: I am reading a book on Probability, and do not know how to solve this example question.
Consider the following difference equation and initial condition(s). In each case, verify that the expression given for a(subscript(n))
(i) is a solution of the equation
(ii) satisfies the initial condition(s).
<code> a(subscript(n)) = 16(1/2)^n satisfies 2a(subscript(n)) = a(subscript(n−1)),
 a(subscript(0)) = 16.
</code>
Answer: All you need to do here is substitute in $$16(1/2)^n ~~~~ \textrm{and} ~~~~ 16(1/2)^{n-1}$$ for $a_n$ and $a_{n-1}$, respectively, in the difference equation.  You should see that the given choice of $a_n$ follows the rule provided (this is part (i)).  Then check that, by plugging in $n = 0$, you indeed find $a_0 = 16$ (this is part (ii)).
Some students find the idea of verifying a solution like this is unintuitive; you start with both the question and the answer - what are you expected to do?  It might help to see that another choice of function does $not$ satisfy the equation.  Suppose you were told to do the same thing with $$ a_n = 16 + n$$ or $$ a_n = 7(1/2)^n.$$ These are examples of functions that don't solve the equation and initial condition.


While loop with buffered reader readline only loops once and goes into infinite loop

Question: Am new to java and i have a program that's supposed to read through a file using a bufferred read and do some stuffs with the result. The program is that it only reads the first and line and goes into an infinite loop. I have tried different files but am getting the same result.
private void readingFile(){
    DataType type;
    String line;
    Log log = new Log(writeFile);
    try(BufferedReader reader = Files.newBufferedReader(Paths.get(readFile))){
        while ((line = reader.readLine()) != null){
            if (line.charAt(0) == '#' || line.charAt(0) == '/') {
                continue;
            }
            String[] lineArray = line.split(" - ", 2);
            String one = lineArray[0];
            String two = lineArray[1];
            type = new DataType(one, two);
            queue.put(type);
            log.readMessage(one, two);
        }
    }
    catch (Exception ex){
        System.out.println(ex.getClass().getSimpleName() + "-" +
                ex.getMessage());
    }
}

Comment: How did you find out it's an infinite loop and not a blocking call to ``readLine()``? Debug your program please.
Comment: some print statements and console output demonstrating that the while loop is infinite would help... I don't see any problem with your while loop.
Comment: Commented out the  line, queue.put(type) and it works fine now only problem is i cant add entries to the queue. Thanks
Answer: What does the statement:
log.readMessage(one, two);

do? Does it return in a finite amount of time?
Try and run your program again while removing the following lines:
String[] lineArray = line.split(" - ", 2);
String one = lineArray[0];
String two = lineArray[1];
type = new DataType(one, two);
queue.put(type);
log.readMessage(one, two);

Comment: Its supposed to console the two strings, i believe queue.put was blocking hence the reason why the program kept looping. Thanks


If I'm grade X, how close to X-standard pieces should I be able to sight read?

Question: When you take a grade exam you have pieces you have to prepare, and you are also expected to sight-read... but the sight-read pieces for each grade will be easier than the pieces you prepare.
I wondered how big the difference is i.e if I take a grade 5 piano exam, are the grade 5 sight-reading pieces similar in difficulty to prepared pieces in a grade 3 exam, or maybe grade 4 or grade 2?
In my case I'm new to piano so I don't really have a grip on how much harder sight reading is, or how much time someone would put into practicing a prepared piece to get to the right standard, but I assume the difference is substantial... but can someone quantify it in terms of numbers of grades?
I'm primarily thinking ABRSM but answers for similar grade 1-8 based systems used in the UK are welcome too.
Comment: ABRSM sight reading example books are readily available in U.K. They will give you a far better clue than any answers here. The difficulty related to performance pieces is somewhat subjective - some are easier to tackle initially, but harder to perform for the exam, and vice versa. It's probably too much of a generalisation to say sight reading at grade III is the same level as a set piece at I, but a call to ABRSM on the phone would give you some indication.
Comment: From my own experience, if anyone cares, I have to work hard to be able to play a Grade 1 piece - but typically can sight-read each hand, since for me the ability to play two things at once is the biggest difficulty.
Answer: It isn't really that useful to think of the sightreading tests for a graded music exam in comparison to the performance pieces for graded music exams. This is because:

the sightreading tests are much shorter, more like exercises than actual pieces.
the sightreading tests are designed simply to test your ability to read notation and perform it at sight; they don't demonstrate the level of study that learning a piece does.
sightreading tests incrementally introduce the necessary elements of notation through the grades, whereas the performance pieces also incrementally introduce techniques (although this inevitably happens to a certain extent with sightreading tests too, it is certainly of less importance).

Although a Grade 8 sightreading test may, for example, seem on the surface to have a similar difficulty to read and play as, say, a Grade 4 or 5 piece, this similarity is reasonably superficial. The demands of learning a whole Grade 4/5 piece and sightreading a 10-bar Grade 8 sightreading test are completely different, even if a short passage from each seems to use the same complexity of notation and require a similar level of performance technique.
As @Tim points out, the best thing to do is try some of the example sightreading tests, which are available for all grades for each instrument.
This link takes you to an Amazon page listing piano example sightreading test books for each grade, as well as "Joining the Dots" books, which are really useful for improving general sightreading skills. You used to be able to get example sightreading tests for all the grades in one booklet, but I don't know if ABRSM still produce these (anyone?!)
Comment: Without wishing to seem obvious, I guess the answer would be "as well as possible"! In the end, sight-reading is difficult when first learning an instrument. For this reason examiners will be fairly lenient when marking sight-reading tests, and are looking to give marks for what you *can* do, rather than take marks away for what you get wrong. (Anecdotally I have heard that a certain number of marks are awarded just for attempting the sight-reading.) And this is also why the sight-reading tests are much easier than the level of the performance pieces...
Comment: ...however, to get full marks, you would need to perform the sight-reading test convincingly, with the correct rhythms and notes, and observing performance directions such as dynamics. This makes sense: it gives scope for candidates who are able to sight-read well to display their skill with a convincing performance.
Comment: If you haven't done so, I strongly recommend you look at some example sight-reading tests - you will see that compared to the performance pieces they are far less difficult, which should put your mind at rest somewhat!
Answer: I've been told that you should be able to sight read pieces 2 grades below your standard.
Eg. If you're Grade 5 standard, you should be able to sight read grade 3 standard pieces.


Animation to shrink view to top left corner

Question: I would like to shrink my UIView to the top left corner. I am currently using a scale transform to achieve this, but the view is shrunk to the center. I have tried to change the layer's anchorpoint, but this results in the entire view changing position on screen . How should a transform be set up to achieve a shrink to the top left corner? Thank you
Answer: Something like:
<code>[UIView beginAnimations:nil context:nil];
// setAnimationDuration
// set transform scaling
myView.center = CGPointMake (0, 0);
[UIView commitAnimations];
</code>
If you are transforming it to something like 50% of the screen you can change the center point to where it should be.  For example, if it's a 320x480 view, you'll be scaling it to 160x240...so the center point will need to be 160/2 (80) and 240/2 (120)...
Comment: A better way to do that would be to just set the frame to `CGPointZero`, avoiding the need for the transform.


Is $\dfrac{0}{0}$ indeterminate with respect to limit only or in general?

Question: Is $\dfrac{0}{0}$ indeterminate with respect to limit only like $\lim_{x\to 0}\dfrac{\sin x}{x}$ or it is indeterminate in general like $\log_1 1$?
I asked this because I encountered indeterminates only in limits, we don't talk about in other areas.
Like $\log_1 1$ can be any real number.
Comment: It is meaningless.
Comment: It is undefined. That is all.
Comment: if its meaningless, why do we give importance to it in limits?
Comment: Normally the term "indeterminate form" is used _only_ to refer to certain limit properties and not to anything else.  So you need to explain exactly what you mean by "indeterminate in general" for your question to have any meaning.
Comment: We don't.  ${}{}{}$
Comment: so you mean to say its not indeterminate, it is undefined?
Answer: You should probably be more explicit in phrasing your Question.
Certainly "$\frac{0}{0}$" is shorthand for the indeterminacy of limits in the first sense, but whether the expressions of a more general form are indeterminate will depend on defining them in a limiting sense or otherwise.
I don't see any real objection to saying that $1^0 = 1$, but then again $1$ to any power can be $1$.  In that respect we would rather say that $log_1 1$ is not a well-defined operation (rather than call it indeterminate).  In an application where a well-defined value is indicated, one would have to backtrack to discover where critical information has been lost or forgotten.
The point of calling something "indeterminate" is that further information is needed to arrive at a value.  Thus it is not enough information to determine a value to know the numerator goes to a limit of zero and the denominator goes to a limit of zero.  The limit of such ratios might not exist, or it might exist but be any value at all, without further information.


WPF FlowDocument space size is inconsistent

Question: I'm using a FlowDocumentScrollViewer to print out log outputs to my application window, and am getting some rather weird spacing issues. Most of the spaces are correctly sized, but I'll consistently get way too large of spaces in some areas. Here's an example:
Correctly spaced: "d Copying E:\Projects"
What is displayed: "d      Copying      E:\Projects"
I had to use multiple spaces to reflect the spacing issue above, but I guarantee that it is indeed just displaying one space, incorrectly sized. This is easily verifiable by copying the text from my FlowDocumentScrollViewer into a text editor like notepad++. Here's the printing code for my simplest FlowDocumentScrollViewer:
LogBox.Document = new FlowDocument();
LogBox.Document.Background = LogBox.Background;
LogBox.Document.Foreground = LogBox.Foreground;
LogBox.Document.Blocks.Add(logParagraph = new Paragraph());
logParagraph.Margin = new Thickness(0); //Tested making Margin 0, didn't help
logParagraph.FontFamily = font;
logParagraph.FontSize = defaultFontSize;

...

public void PrintLog(String s)
{
    logParagraph.Inlines.Add(s);
}

I've never seen anything like this, and searching for it on google is very difficult since everyone that uses "spacing" as a keyword really means line height... any help is appreciated.
Answer: Have you tried...
LogBox.TextAlignment = TextAlignment.Left;

and / or
logParagraph.TextAlignment = TextAlignment.Left;

owo? Because as I can see, in some cases the Block is getting an auto alignments to justify / stretch the text in the line~ Don't know why but seems to happen ;o
Comment: Wow. I can't believe this actually fixed the issues. Auto-formatting for the lose!
Answer: You could try adding a Run object in the PrintLog method, and modifying its properties like CharacterSpacing, and maybe try other ones as well. Sorry I don't have access to Visual Studio at the moment so I can't actually try it.
public void PrintLog(String s)
{
     var run = new Run();
     // modify run properties here
    logParagraph.Inlines.Add(run);
}

You can view the MS documentation here: Run Class


jQuery var to equal the value of the input box that it is focused on

Question: I am building a dynamic small lenght converter that contains 3 input[text]s. Like so
<input type='text' class='bx' id='cm'> Centimeter

<input type='text' class='bx' id='m'> Meter

<input type='text' class='bx' id='km'> Kilometer

The effect is the following: if you click on "Meter" the value becomes '' and if you type a value the "Centimeter" and "Kilometer" value will be equal to a value(...).
Example
The jquery is like so:
$(function() {

var selected = ????;

// do i need something here to empty the input it is focused on?

$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);

})

I want the var selected to be equal to the value of the text input it is focused on.
How can i do this?
The calculation in examples are informative.
Answer: You can use jQuery focus to get selected input field.
 $(function() {
         $("input.bx").focus({
          var selected  =parseInt(this.value, 10);
              this.value = ''; //this line will remove text from selected input.
              $("#cm").val(selected * 545);
              $("#km").val(selected * 545);
             $("#m").val(selected * 453);
         });
    })

Answer: var selected = $(this).val();

//  // The code you have written will only work fro the first time your page loads. If you want it to work on every click of it you need to handle the focus event of the input..
 $('#cm , #km , #m').on('focus', function() {
        var selected = parseInt($(this).val() , 10) ; // Will convert to a Int

        $("#cm").val(selected * 545);
        $("#km").val(selected * 545);
        $("#m").val(selected * 453);

    });

But I think a blur event makes more sense here instead of a focus event..
FIDDLE
Which will point to the value of the selected input
Comment: thanks this is helpful but in your example the input values dont chance as in the example that i have given
Comment: I have used blur event in the example.. So as soon as you type in something and the input loses focus you can see the change
Answer: You have to implement a listener that listens for the focus event.
check this out:
http://api.jquery.com/focus/
$('.bx').focus(function() {
    var id = $(this).attr("id");
    if (id === "cm") {
        alert('Handler for .focus() called cm');
    }
    else if (id === "m") {
        alert('Handler for .focus() called m');
    }
    else if (id === "km") {
        alert('Handler for .focus() called km');
    }
});

Answer: You need an event handler, in this case for the focus event:
$(function() {
     $(".bx").focus(function(e) {
         var selectedval = this.value,
             selectedtype = this.id;
         …
     });
});


How to delete irrevelant sentence from Richtextbox?

Question: I use GPS data and NMEA sentences.Even I only want to see and save the sentences which begins with "$GNGGA" and "$GNTVG" in my richtextbox, there are other sentences(lines) begining with different codes($GNGLL, $GLGSV, $GPGSV etc). What should I do to only get "$GNGGA" and "$GNTVG" sentences to Richtextbox?
Here is my code;
       string[] gParca;
    string gKG, gDB, gUydular, gYukseklik, gEnlem, gBoylam, gYataySapma, gKilitlenme, gVelocity, gSaat;

       private void GPSVelocity(string NMEA2)
    {
        gParca = NMEA2.Split(new char[] { ',' });
       switch(gParca[0])
       {
           case "$GNVTG":
               gVelocity = gParca[7];
               break;
       }
      private void GPSDataBilgisi(string NMEA)
    {
        gParca=NMEA.Split(new char[] { ',' });
        switch (gParca[0])
        {
            //Global Positioning System Fix data
            case "$GNGGA":
                gParca[2] = gParca[2].Replace('.', ',');
                gParca[4] = gParca[4].Replace('.', ',');
       }
      }
      private void serialPortGPS_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
       GPSDataBilgisi(serialPortGPS.ReadLine());
       GPSVelocity(serialPortGPS.ReadLine());
    }

    private void GPSVel(string NMEA2)
    {
       if(checkBoxSave.Checked)
       {
           richTextBoxGPSData.AppendText(NMEA2);

      }

    }

    private void GPSData(string NMEA)
    {
        if(checkBoxSave.Checked)
        {
            richTextBoxGPSData.AppendText(NMEA);
        }
    }

Comment: For my answer, can I assume `serialPortGPS` works like a `TextReader` object with its `ReadLine()` function? I would expect the data to come out of the event args but your code seems to think otherwise...
Comment: Yes, you can assume serialPortGPS as a TextReader .
Answer:
Disclaimer
  As per OP's reply to my question, I am assuming serialPortGPS.ReadLine() works exactly like TextReader.ReadLine().

Since you want to filter the input you are getting, add a filter to the function that retrieves the data.
private void serialPortGPS_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   for(int i = 0; i < 2; i++)
   {
       string line = serialPortGPS.ReadLine();

       if(line.StartsWith("$GNGGA"))
           GPSDataBilgisi(line);

       if(line.StartsWith("$GNVTG"))
           GPSVelocity(line);
   }
}

If the line starts with anything else (e.g. "HELLOIAMALINE"), neither if-check will pass and the code will not do anything with the line, it just moves on to the next one.
You can remove the switch statements in your code, they are no longer needed (of course keep the logic that is inside them!)
There are some caveats here, because I think your code and intention is a bit vague. If you can clarify any of these, I can update my answer.

Going by your question, I assume you do not want to call ReadLine() exactly twice (once for each method). I infer that you want to read every line individually (because that's how TextReader usually works), check if it starts with a "good" value, and then execute the function that needs it.

My original example specifically reads 2 rows and parses them. If you are instead trying to read all lines from the gps update, change the code as follows:
 private void serialPortGPS_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   string line;
   while((line = serialPortGPS.ReadLine()) != null)
   {
       if(line.StartsWith("$GNGGA"))
           GPSDataBilgisi(line);

       if(line.StartsWith("$GNVTG"))
           GPSVelocity(line);
   }
}

Part of me wonders if reading directly from serialPortGPS is the correct approach. This is pure speculation, but I would expect your SerialDataReceivedEventArgs e to contain a property with the newly received data. It's not impossible that what you are currently doing is correct, but it is more unusual than using the event args that you receive from the update event.
You could use LINQ to immediately filter out the rows that you need (instead of having to manually iterate over them). However, Textreader implements a pattern where it only processes one line at a time (similar to yield return). If you use LINQ, you're going to end up processing all lines at the same time when you want to filter them. If you need to process line by line (e.g. because the data you're processing has a huge memory footprint), then you should avoid LINQ

If you want an example of LINQ:
List<string> theLinesThatIWant =
    allTheLines.Where(line => line.StartsWith("$GNGGA")).ToList()

But like I said, only use this if you are able and willing to have all the data in memory at the same time.


Problema com rotas Asp.net MVC

Question: Tenho uma aplicação na qual eu coloquei como um novo site e funcionou direitinho, mas ao colocar essa aplicação dentro de outra, da um erro na rota.
Preciso que ao fazer login, direcione para "http://localhost:porta/Documentos/PainelAdm" e ele está direcionando para "http://localhost:porta/PainelAdm".
Trecho onde retorna para a view "PainelAdm":
<code>[HttpPost]
        public ActionResult LogOn(FormCollection f, string returnUrl)
        {
            Conta user = new Conta();
            ContaModels atrrConta = new ContaModels();
            atrrConta = user.RetornaUser(f["login"]);
            if (user.AutenticaUser(atrrConta, f["senha"]))
            {
                //Rotina para autenticar usuario
                if (returnUrl == "" || returnUrl == null)
                {
                    returnUrl = "/CalendarioAlertaSMS";
                }

                System.Web.Security.FormsAuthentication.SetAuthCookie(atrrConta.Ide_Perfil.ToString(), false);

                Session["PERFIL"] = atrrConta.Ide_Perfil;
                Session["NOME"] = atrrConta.Nome;

                if (Session["PERFIL"].ToString() == "ADMIN")
                {
                     returnUrl = "/PainelAdm";
                }

                return Redirect(returnUrl);
            }
            else
            {
                ViewBag.Message = "Login ou senha inválidos.";
                return View();
            }
        }
</code>
Comment: Defina "colocar aplicação dentro de outra". O que seria isso?
Comment: Você fez alguma modificação no RouteConfig.cs ? Ou está usando o padrão?
Comment: Se possível, edite a questão adicionando o código do seu RouteConfig.cs, imagino que você esteja fazendo algo errado nele.
Comment: @CiganoMorrisonMendez, Cara aquele meu problema eu consegui resolver, agora o problema é, tipo, tenho um site em asp classico que através de um botão irá chamar uma outra aplicação em asp.net mvc. E eu coloquei essa aplicação em mvc dentro do site que está em asp classico. Preciso que ele abra através desse site em asp classico.
Comment: @Intruso, não, não fiz nenhuma alteração, só tem um trecho onde eu estou verificando o perfil de usuário, que se ele tiver o perfil de administrador ele retorna uma Home diferente de usuários que não tem esse perfil, e é nesse ponto que eu estou passando essa que eu mencionei na pergunta.
Comment: @AndreeH Isso é muito tosco. Eu colocaria cada site em um subdomínio diferente. As rotas em MVC não são diretórios, e naturalmente o IIS se perde na hora de resolver os nomes.
Comment: @CiganoMorrisonMendez Beleza, tenho isso feito, mas como consigo fazer com que o botão do site asp classico chame essa aplicação mvc ?
Comment: @AndreeH Faça uma requisição *hard*, sem caminhos relativos. Não deixa de ser outro site em outro lugar.
Comment: @CiganoMorrisonMendez, pode me dar um exemplo de como faço isso ?
Comment: Ué, um link para http://meusite:porta/
Comment: @CiganoMorrisonMendez Puts, já tentei isso e não foi. :S
Comment: @CiganoMorrisonMendez também não funciona, cara, só preciso que redirecione assim "http://lmeu_site:porta/Documentos/PainelAdm". Como posso definir uma rota para isso que funcione no iis ?
Comment: Subdomínios diferentes quer dizer diretórios virtuais diferentes. Você não entendeu esta parte?
Comment: @CiganoMorrisonMendez, não entendi.
Answer: Uma aplicação MVC quando colocada dentro de outra, não funciona mesmo, para que funcione converta a pasta da aplicação interna em um um aplicativo.
Comment: cara, eu fiz isso, eu tenho uma aplicação independente que funciona perfeitamente, mas ao colocar ela para ser chamada dentro de um site em asp classico não está funcionando. O problema é com a rota.

Problema com rotas Asp.net MVC


Remove update elements from User-Defined Table Type?

Question: On a User-Defined Table Type, @TT dbo.IntType readonly,,
IntType is batch of int, as Primary-Key
CREATE TYPE [dbo].[IntType] AS TABLE(
    [T] [int] NOT NULL,
    PRIMARY KEY CLUSTERED

I would like to do an UPDATE based on all key(int) in IntType, and INSERT new rows for the key(int) not exist in the database (an upsert). How?

I wonder if there is an easy way to remove the "UPDATED" key(int)? Then I can insert the rest.
(or if you have a super one-line upsert for SQL Server)
Answer: Use the MERGE statement.
http://technet.microsoft.com/en-us/library/bb510625.aspx
Let me see if I can put something together.
EDIT: Example
MERGE INTO [TargetTable] AS T
USING (SELECT l.T AS 'id' FROM @list l ) AS S
ON (T.[id] = S.[id])
WHEN MATCHED THEN
    UPDATE SET
        T.updated = 1
WHEN NOT MATCHED THEN
    INSERT VALUES ([insert value into each column of target table]);

EDIT 2: The parameter @list is the list that is passed in that you populated with the ids
Comment: It is really nice but this only works on 2008 and up. Since you are using 2010 I figured you would be fine.
Comment: I wasn't quite too sure what that was either. I figured it was a new release after 2008 R2 but figured I don't always keep up with the latest versions.
Comment: holy cow, that was easy, I cannot wait to try it
Comment: It works like a charm, fast and reliable. Worked both on my local `SQL Server 2008 R2` and `SQL Azure`. For the SQL 2010 thing, my fault, M$ has too many products, messed up my mind.


Need a list of terms from a vocabulary machine name

Question: How can I get the terms of a vocabulary using vocabulary machine name.
I have used the following code, although it works for me but I am looking for efficient methods.
$vocabulary = taxonomy_vocabulary_machine_name_load('school_courses');
$terms = taxonomy_get_tree($vocabulary->vid);
$courses = array();
foreach($terms as $term) {
    $courses[$term->tid] = $term->name;
}

Answer: What you are doing is pretty much the same as Drupal core is doing for the term reference field, so doubt you can improve the code much.
/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

Answer: Using EntityFieldQuery, you can add
->entityCondition('bundle', 'my_machine_name') to get terms by vocabulary name:
Example:
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'taxonomy_term')
                ->entityCondition('bundle', 'my_machine_name')
                ->execute();

Answer: I use EntityFieldQuery:
// Get vid from machine_name
$my_vocabulary = taxonomy_vocabulary_machine_name_load('my_machine_name');
$my_vid = $my_vocabulary->vid;

// Build and execute the query
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $my_vid)
$result = $query->execute();

// Process the result
var_dump($result);

Output:
array(1) {
  ["taxonomy_term"]=>
  array(8) {
    [12]=>
    object(stdClass)#145 (1) {
      ["tid"]=>
      string(2) "12"
    }
    [14]=>
    object(stdClass)#149 (1) {
      ["tid"]=>
      string(2) "14"
    }
    /* etc... */
  }
}

http://api.drupal.org/api/drupal/includes!entity.inc/class/EntityFieldQuery/7


How can we cut a 3D Cube using 3D Cube?

Question: Cutting a 1D Line:
We can cut a 1D line via 0D point.
if we want to cut a 1D line via a 1D line.
we have to move 1 dimension up that is in 2D

(Image for 1D Line cut by 0D pt.)
(Image for 1D Line cut by 1D line)
Cutting a 2d Plane:
We can cut a 2D plane via 1D Line.
if we want to cut a 2D plane by a 2D plane
we have to move 1 dimension up that is in 2D

(Image for 2D plane cut by 1D line)
(Image for 2D plane cut by 2D plane)
Cutting of a 3D Cube:
We can cut a 3D Cube by a 2D Plane
So the question arises that
Can we cut a 3D cube by a 3D cube?
And if yes then how ?
For it we may require 1 more dimension (4th dimension).

(Image for 3D Cube cut by 2D Plane)
So how can we do that!
In all the cases sizes doesn't matter:
Size of a Line doesn't matter that if we cut a Line by another Line.
And Size of a Plane doesn't matter that if we cut a Plane by another Plane.
Is it same for Cubes?
Does Cubes size also doesn't matter. Can we cut a Cube by another Cube(Like a Plane cuts a Cube) and that another Cube's size can by 10x, 100x, 1000x etc ?
I think understanding how a 3D Cube is cut by a 3D cube help me to understand (or say visualize) what 4th Dimension is?
Answer: The short answer to your question, in your terms, is that the 3D cube cut by a 3D cube will be a be a 2D thing in the fourth dimension.
Your deeper question

I think understanding how a 3D Cube is cut by a 3D cube help me to
  understand (or say visualize) what 4th Dimension is?

is a hard one. Mathematicians study the geometry of $n$ dimensions by using algebra. When $n$ is $1$, $2$ and $3$ you have the number line, the plane with points $(x,y)$ and 3D space with points $(x,y,z)$. There you can match algebraic arguments with pictures. For four dimensions, work with points $(x,y,z,w)$ - but there and in higher dimensions all you have is the algebra.
The algebraic answer to your "cutting" question is that in general, if you have  subspaces (what you call "cubes") of dimensions $k$ and $l$ living in $n$ dimensional space they will cut each other in a subspace of dimension $k+l-n$. That pretty much covers all your examples.
But visualizing this is not something humans are naturally equipped to do. My thesis advisor, Andy Gleason, once told me he would give a lot for one good look at the fourth dimension.
Comment: [off topic] interesting comment by Prof Gleason.  along a similar vein, I've always wanted one good look at an analytic $f: \mathbb{C} \rightarrow \mathbb{C}$.  I can see 3D plots of $Re(f), Im(f), |f|, \angle f$ vs the complex plane, but (at least for me) they dont really give good insights into what makes $f$ analytic...
Answer: @EthanBolker already gave a great general answer.  This answer gives one way to visualize a 3D cube cutting a 3D cube in 4D.  I wouldnt say this way is generally useful, but it might be useful in the case of cubes.
Imagine the 4th dimension as "time" $t$.  The first cube is $\{(x,y,z,0): -1 \le x, y, z, \le 1\}$.  So this cube "doesnt exist" except at one moment $t=0$, and at that moment it exists as a regular 3D cube $[-1,1]^3$ in the $(x,y,z)$-space.
The second cube is $\{(x,y,0,t): -1 \le x, y, t \le 1\}$.  First you have to convince yourself that this is a 3D cube in 4D.  :)  Then if you go along the time dimension, the cube "doesnt exist" except in the time range $t \in [-1, 1]$, and at any moment during that time, it exists as a regular 2D square $[-1,1]^2$ on the $(x,y)$-plane (where $z=0$).
The intersection of the two is $\{(x,y,0,0): -1 \le x, y \le 1\}$ which is a 2D square that "exists" only for one moment $t=0$, but at that moment the 1st cube also "exists" and this square bisects the 1st cube.  (This square also bisects the 2nd cube.)
Like I said, making a dimension special (calling it time) may not be a generally helpful method, but perhaps it helps in this case?

How can we cut a 3D Cube using 3D Cube?


function argument not matching with function call

Question: I have this function:
std::string reverse_words(const std::string& in)
{
    std::stringstream ss(in);
    std::string item, result;
    while (std::getline(ss, item, ' ')) {
        the_stack.push(item);
    }
    for (int i = 0; i < the_stack.size(); i++)
    {
        result += " " + the_stack.top();
        the_stack.pop();
    }
    return result;
}

However, when I try to call it here:
int main(int argc, char** argv) {
    reverse* s = new reverse();
    std::string in = "fdgdfgbjfd gdf gjhfd";
    std::string reverse_words = s.reverse_words(&in);
    cout << reverse_words;
    return 0;
}

I get an error on std::string reverse_words = s.reverse_words(&in); (request for member 'reverse_words' in 's', which is of pointer type 'reverse*' (maybe you meant to use '->' ?)). I am unable to understand where I am going wrong in this.
Comment: As a point of clarification, shouldn't the function call std::string reverse_words(const std::string& in) be std::string reverse::reverse_words(const std::string& in) since in main its being used as a method of the class reverse?
Answer: Your function
std::string reverse_words(const std::string& in)

takes a const reference, but you pass an address. Remove the & when passing the argument
std::string reverse_words = s.reverse_words(&in);
                             ^change to->   ^ remove this

Next, s is a pointer, so you have to call the member function via the -> operator, like
s->reverse_words(in);

Side note: even if internally references are usually implemented as pointers, you should not use pointer syntax when passing an argument by reference. In other words, the & address-of operator should never be present when passing by reference.
Comment: @DemCodeLines, *maybe you meant to use '->'* Pointers and dots don't mix. The compiler could barely be any more helpful there.
Comment: @DemCodeLines I suggest you start small, and understand how C++ works. You are missing `std::cout` since probably you are not `using namespace std;`, or forgot to `#include `
Comment: Thank you for your response. I tried taking the `&` out and I continue to get the same error on that line.
Comment: It made the error go away, but now it threw an error on the `cout` line, saying that `'cout' is not a member of 'std'`
Comment: It seems I had taken out `` for some reason when debugging an earlier problem with stacks. Oh well, thanks!


How can one access the lowest ranges of one's bass voice?

Question: Sometimes in specific conditions such as some early mornings, the day after having strained my voice, or having a mild cold, I can reach unusually low vocal ranges. Looking around, there is very little information about how (if at all), one can access this potential under normal conditions through training or preparation as there seems to be very few resources online on singing that specifically target bass singers.
So, how can I access these extra low ranges when I actually need them?
The following is more specific to myself to provide a concrete example of what I mean:
I am 25 years old and have been a bass singer ever since my early teenage years, and since about 16 years of age would be considered a "Basso Profondo" according to the wikipedia definition. On most days, I produce a strong C2 without issue, and I commonly have access to a range down to A2 (albeit most often without any considerable volume). In the situations described above, I produce strong, clear notes in the region of A2, and have sometimes even reached as far as a clear Eb1 (the day after a choir practice weekend where my voice felt really strained the night before). Often during long sessions of practice, I feel strained and are unable to access my normal range of down to C2, but once the strain passes is when I usually have the deepest voice.
Comment: I'm a rubbish singer, but I'd love to know if it is possible for me to reproduce the voice I have when I've got a cold :) As would Phoebe Buffay  I seem to recall :)
Comment: I've heard about fry tones - maybe this is what they are?
Comment: I guess most often notes sung around those lower ranges have some element of vocal fry to them, but this isn't what I'm after or what I've experienced in those particular situations.
Answer: You can sing lower when you have a cold for the same reason that your speaking voice often lowers when you're sick - your vocal folds are swollen or inflamed, thicker, and vibrate at a lower frequency. The same is true of being able to reach lower pitches in the morning except for it's caused by mucous or simply from the folds being in a very relaxed (and hence thicker) state.
I suspect that lower range following prior intense usage of your voice also is a result of swollen folds.
Unfortunately, there are physiological lower limits at which your vocal folds can vibrate based on your anatomy - it's not possible to indefinitely extend low range through training. Since these low notes are only existent when your folds are either very relaxed or swollen, they are probably not pitches that you can consistently rely on being part of your usable range. That being said, a competent voice teach would be able to help you access what you can in your lowest register consistently and easily.
(Note I'm talking only about the typical modal register used in singing and not vocal fry which is a different mode of vocal fold function.)
Answer: I was taught to relax my vocal cords as much as possible. This way, I was able to reach 1-2 semitones lower toward the more guttural tones than I was when straining to reach lower. Exercises where you extend the range by singing up-and-down c d e d c and then moving down chromatically to b c# d# c# b etc. could also help you. Repeatedly singing one of the three lowest tones you can reach can build stability over time together with control of air flow by isolating your breathing to the diaphragm.
Answer: While I agree a voice teacher is a good idea, telling someone they can't learn to song on their own is bs. Most people who sing learn w/o a vocal instructor, and some learn to sing extremely well on their own. Telling someone they cannot learn to sing on their own is extremely classist. Not everyone is fortunate enough to afford a vocal teacher, and your are essentially telling them to give up. Poor people are allowed to sing too.
To the OP, get a vocal instructor IF YOU CAN AFFORD ONE. If you cannot, use whatever resources available to improve your singing, including YouTube tips or audio recording apps to listen back to yourself. I find it far easier to extend your range up than down. As previously posted, thickness of vocal finds makes a difference, but this can be somewhat emulated with mucus. Most singers avoid things that create excess mucus like milk, because it makes it more difficult to sing high notes (or sing in general) but if you are determined to sing below what your vocal folds normally allow maybe this wouldn't hurt. Personally, I have trouble going below an E2 under normal circumstances, but consuming dairy can get me down as far as an audible B1, with a fairly strong D2.
Sometimes we have to break conventional wisdom to do what others tell us we can't.
Answer: You need to take voice lessons from a teacher.
Like I have said many times on this site, you cannot improve anything about your singing voice from reading about singing technique. You need to hire a voice teacher and take lessons. Improving anything about your singing requires frequent feedback from a teacher who is listening to your voice and teaching you how to make minute corrections and improvements over time, interactively, and teaching you how to practice and extend your range, improve your tone, and make your voice stronger.
Trying to develop your own singing technique all by yourself is counterproductive. You will unconsciously develop bad habits, and in the absence of a professional teacher to point out these bad habits and correct them, you will reinforce these bad habits and train yourself to sing in ways that are not optimal, or even counterproductive.
You need to work with another human being who is a trained professional voice teacher. You will make significant progress if you do this. Sitting alone reading books or posts on the Internet about vocal technique will not help at all.
Comment: While I tend to agree with your points, I have had a couple of different teachers in the subject. All of them knew very well how to help me unlock my soloist potential in the tenor ranges, but when asked dodged questions about the lower bass ranges or simply telling me they didn't know. I got the impression from them that a tenor voice is the result of much practice while a bass "just happens".


drupal 7 user registration custom url returning a blank page

Question: I dont think my url is working. I am trying to use page/medical then use the page callback to redirect to medical_reg_form_user_register_form_alter. Instead of displaying the form I get a blank page.
function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'medical_reg_form_user_register_form_alter',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}

function medical_reg_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'medical_register';
  $form['actions']['submit']['#value'] = t('Nextdfd');
}

Answer: You can't call a hook in hook_menu(). You can either create an alias for the user registration page or replace your menu item with:
function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}

Comment: This is correct: Using a hook also as page callback is fount of troubles. The least it can happen is that the arguments the function gets as page callback are not the same it would get as hook implementation. In this case, as page callback, the function would not get any argument, while the hook is expecting 3 parameters.


Como adicionar o Google Analytics ao meu aplicativo Android?

Question: Quero usar o Google Analytics para coletar mais informações sobre o uso de meus aplicativos, como adicionar o Google Analytics ao meu aplicativo Android?
Answer: Configuração do projeto
Atualize o arquivo AndroidManifest.xml do seu projeto para incluir as permissões INTERNET e ACCESS_NETWORK_STATE:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.analytics">

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

  <application android:name="AnalyticsApplication">
    ...
  </application>
</manifest>

O plug-in do Google Services para Gradle analisa informações de
  configuração do arquivo google-services.json.

Para adicionar o plug-in ao seu projeto, atualize seus arquivos build.gradle de nível projeto e build.gradle no nível do aplicativo da seguinte forma:

Adicione a dependência ao arquivo build.gradle no nível do projeto:
classpath 'com.google.gms:google-services:1.5.0-beta2'

Adicione o plug-in ao arquivo build.gradle no nível do aplicativo:
apply plugin: 'com.google.gms.google-services'

Agora, você precisa adicionar uma dependência ao Google Play Services. Dentro do arquivo build.gradle do seu aplicativo, adicione:
compile 'com.google.android.gms:play-services-analytics:8.4.0'

Acessar um arquivo de configuração

O arquivo de configuração fornece informações específicas de serviço
  para seu aplicativo. Para acessá-lo, você precisa selecionar um
  projeto existente para seu aplicativo ou criar um novo. Você também
  precisa fornecer um nome de pacote para seu aplicativo.

Observação: você precisa ter uma conta do Google Analytics e uma
  propriedade registrada para acessar o arquivo de configuração.

Clique no link abaixo para acessar um arquivo de configuração a ser adicionado ao seu projeto.
ACESSAR UM ARQUIVO DE CONFIGURAÇÃO
Adicionar o arquivo de configuração ao seu projeto
Copie o arquivo google-services.json que você acabou de receber no diretório app/ ou mobile/ do seu projeto do Android Studio.
/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}
AnalyticsApplication.java

Activity ou Fragment

Abra a atividade que você deseja acompanhar.

Você também pode acompanhar um Fragment, mas ele precisa representar
  corretamente a exibição de tela.

Inclua no método onCreate da Activity ou do Fragment que deseja acompanhar para acessar a instância do Tracker compartilhado:
// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();

Inclua o código abaixo no método apropriado, como onResume para uma Activity ou onPageSelected para um ViewPager com a finalidade de registrar quando a tela muda.
Log.i(TAG, "Setting screen name: " + name);
mTracker.setScreenName("Image~" + name);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());

Adicione o código de acompanhamento a cada Activity ou Fragment que representa uma tela. Defina um nome dentro de cada Activity ou Fragment se você quiser diferenciar exibições de tela para seu aplicativo no Google Analytics. Todas as atividades gravadas no rastreador compartilhado enviam o nome de tela mais recente até que ele seja substituído ou apagado (definido como null).
Envio de um evento
Para enviar um evento, defina os valores dos campos de tela no rastreador e envie o hit. O exemplo a seguir usa o HitBuilders.EventBuilder para enviar um Event:
mTracker.send(new HitBuilders.EventBuilder()
    .setCategory("Action")
    .setAction("Share")
    .build());

Código Completo:
MainActivity.java:
/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import java.util.Locale;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

/**
 * Activity which displays numerous background images that may be viewed. These background images
 * are shown via {@link ImageFragment}.
 */
public class MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";

  private static final ImageInfo[] IMAGE_INFOS = {
      new ImageInfo(R.drawable.favorite, R.string.pattern1_title),
      new ImageInfo(R.drawable.flash, R.string.pattern2_title),
      new ImageInfo(R.drawable.face, R.string.pattern3_title),
      new ImageInfo(R.drawable.whitebalance, R.string.pattern4_title),
  };

  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each image.
   * This uses a {@link FragmentPagerAdapter}, which keeps every loaded fragment in memory.
   */
  @SuppressWarnings("FieldCanBeLocal")
  private ImagePagerAdapter mImagePagerAdapter;

  /**
   * The {@link ViewPager} that will host the patterns.
   */
  private ViewPager mViewPager;

  /**
   * The {@link Tracker} used to record screen views.
   */
  private Tracker mTracker;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // [START shared_tracker]
    // Obtain the shared Tracker instance.
    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();
    // [END shared_tracker]

    // Create the adapter that will return a fragment for each image.
    mImagePagerAdapter = new ImagePagerAdapter(getSupportFragmentManager(), IMAGE_INFOS);

    // Set up the ViewPager with the pattern adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mImagePagerAdapter);

    // When the visible image changes, send a screen view hit.
    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
      @Override
      public void onPageSelected(int position) {
        sendScreenImageName();
      }
    });

    // Send initial screen screen view hit.
    sendScreenImageName();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
      case R.id.menu_share:
        // [START custom_event]
        mTracker.send(new HitBuilders.EventBuilder()
            .setCategory("Action")
            .setAction("Share")
            .build());
        // [END custom_event]

        String name = getCurrentImageTitle();
        String text = "I'd love you to hear about " + name;

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, text);
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
        break;
    }
    return false;
  }

  /**
   * Return the title of the currently displayed image.
   * @return title of image
   */
  private String getCurrentImageTitle() {
    int position = mViewPager.getCurrentItem();
    ImageInfo info = IMAGE_INFOS[position];
    return getString(info.title);
  }

  /**
   * Record a screen view hit for the visible {@link ImageFragment} displayed
   * inside {@link FragmentPagerAdapter}.
   */
  private void sendScreenImageName() {
    String name = getCurrentImageTitle();

    // [START screen_view_hit]
    Log.i(TAG, "Setting screen name: " + name);
    mTracker.setScreenName("Image~" + name);
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    // [END screen_view_hit]
  }

  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
   * one of the sections/tabs/pages.
   */
  public class ImagePagerAdapter extends FragmentPagerAdapter {

    private final ImageInfo[] infos;

    public ImagePagerAdapter(FragmentManager fm, ImageInfo[] infos) {
      super(fm);
      this.infos = infos;
    }

    @Override
    public Fragment getItem(int position) {
      ImageInfo info = infos[position];
      return ImageFragment.newInstance(info.image);
    }

    @Override
    public int getCount() {
      return infos.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      if (position < 0 || position >= infos.length) {
        return null;
      }
      Locale l = Locale.getDefault();
      ImageInfo info = infos[position];
      return getString(info.title).toUpperCase(l);
    }
  }
}

AnalyticsApplication.java
/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}


LoginStatus control in asp.net

Question: Any one help me out, how to work with LoginStatus control in asp.net...
the statu before login should be 'userlogin'
after logged in ,it automatically changes to 'userlogout'
any suggestions??
Comment: It's a valid behavior of this control - show user's current login status. What's the problem with that?
Comment: do you want to change the "text" that is displayed?
Answer: How about this
<asp:LoginView ID="ctlRightNavbar" runat="server">
   <AnonymousTemplate>
       userlogin
   </AnonymousTemplate>
   <LoggedInTemplate>
      userlogout
   </LoggedInTemplate>
</asp:LoginView>

This will make a more custom view for you if you do not wish to use LoginStatus. You can read more about the above code sample here.

LoginStatus control in asp.net


Parsing PGN string starts with number

Question: Hello everyone I am new to python and try to learn about parsing the string from PGN.
'[ECO "B08"]',
 '',
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0',
 '',
 '[Event "Telechess ol1 7778"]',

The result that I want is just to put the move part into a list
1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4,9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+ 16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1

The approach that I take is by reading the PGN and split by '\n'. The output contains a list as the first block of code.
I want to detect by every list that started with a number (one digit or two-digit before the dot '.') should append into a new list.
rough code should be like
listmove = []
for i in pgn:
if i.startswith(1digitnumber or twodigitnumber before dot):
listmove.append[i]

Is it possible? Guidance will help a lot and will be appreciated.
Comment: Incase you just want to parse the pgn then the [python-chess](https://python-chess.readthedocs.io/en/latest/) module is worth checking out but if you are doing this to practice python string formatting and stuff then the answer provided by others are certainly some of the best approaches.
Answer: Yes it's possible using regular expressions. The regex you need is ^\d+\. Demo
Explanation:

^: Start of line / start of string
\d+: One or more digit characters
\.: One period

In python, you'd do:
import re

lines = ['[ECO "B08"]',
 '',
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0',
 '',
 '[Event "Telechess ol1 7778"]']

regex = r"^\d+\."

movelines = []

for line in lines:
    if re.search(regex, line):
        # This line starts with digits and a period
        movelines.append(line)

print(movelines)

prints:
[
 '1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Nf3 Bg7 5.Be2 Nbd7 6.O-O O-O 7.e5 dxe5 8.dxe5 Ng4',
 '9.e6 Nde5 10.Qxd8 Rxd8 11.Nxe5 Nxe5 12.Nb5 c6 13.Nc7 Rb8 14.f4 Ng4 15.Bxg4 Bd4+',
 '16.Kh1 Bb6 17.f5 Bxc7 18.fxg6 fxg6 19.Bh6 Be5 20.Rad1 Rxd1 21.Rxd1 Bd6 22.Rf1  1-0'
]

You could also remove the ^ from your regex and use re.split() to get the different moves. You can use the fact that re.match() searches from the beginning of the line, so use that instead of re.search():
split_regex = r"\d+\."

all_moves = []

for line in lines:
    if re.match(split_regex, line):
        moves = re.split(split_regex, line)
        all_moves.extend(moves)

print(all_moves)

This prints
[
'', 'e4 d6 ', 'd4 Nf6 ', 'Nc3 g6 ', 'Nf3 Bg7 ', 'Be2 Nbd7 ', 'O-O O-O ', 'e5 dxe5 ', 'dxe5 Ng4',
'', 'e6 Nde5 ', 'Qxd8 Rxd8 ', 'Nxe5 Nxe5 ', 'Nb5 c6 ', 'Nc7 Rb8 ', 'f4 Ng4 ', 'Bxg4 Bd4+',
'', 'Kh1 Bb6 ', 'f5 Bxc7 ', 'fxg6 fxg6 ', 'Bh6 Be5 ', 'Rad1 Rxd1 ', 'Rxd1 Bd6 ', 'Rf1  1-0'
]

Notice the extra empty strings at the start of each line. This happens because of the way re.split() works, so you can simply ignore the first entry in each line with all_moves.extend(moves[1:]) to give
[
  'e4 d6 ', 'd4 Nf6 ', 'Nc3 g6 ', 'Nf3 Bg7 ', 'Be2 Nbd7 ', 'O-O O-O ', 'e5 dxe5 ', 'dxe5 Ng4',
  'e6 Nde5 ', 'Qxd8 Rxd8 ', 'Nxe5 Nxe5 ', 'Nb5 c6 ', 'Nc7 Rb8 ', 'f4 Ng4 ', 'Bxg4 Bd4+',
  'Kh1 Bb6 ', 'f5 Bxc7 ', 'fxg6 fxg6 ', 'Bh6 Be5 ', 'Rad1 Rxd1 ', 'Rxd1 Bd6 ', 'Rf1  1-0'
]

The win marker 1-0 is included in this because it's not separated by a move number, but it should be fairly trivial to remove that because it can only be one of three possibilities:

1-0 (White wins),
0-1 (Black wins)
1/2-1/2 (draw)
Comment: thank you so much, I have an enlightenment now. Really curious on the first part with match, I did as you wrote but by assigning ```moveline=" "``` as empty string. I have all the move parts. But now I want to apply to a bigger file. The idea of win marker as a split just popped up in my head. how to achieve that by the way ? I tried the same with regex2 ```r"^\d+\-\d+"``` and do re.split(regex2, moveline). I ended up with empty string
Comment: @Trojan666 Not sure I understand your question. The `^` makes the regex look for whatever comes next _at the start of the line / string_, but the win marker isn't at the start of the line.
Comment: Also, `\d+-\d+` wouldn't work all the time because it would have false positives e.g. `3-1`, or false negatives e.g. `1/2-1/2`. It's better to use `r"\b(?:0|1(?:/2)?)\-(?:0|1(?:/2)?)\b"` (see demo [here](https://regex101.com/r/9eA4om/1))
Comment: no wonder why it is not working because we have draw as well. here what i mean ```move = ""
for line in chess:
    if re.match(regex, line):
        # This line starts with digits and a period
        move = move+line

print(move)``` Now I have ```move``` contains all string of move and score. Now i want to split by score then, ```regex2 = r"\b(?:0|1(?:/2)?)\-(?:0|1(?:/2)?)\b"

move_new=[]

for line in move:
    if re.match(regex2, line):
        moves = re.split(regex2, line)
        move_new.extend(moves)

print(move_new)```

it return empty list
Comment: `for line in move` iterates over _each character in the string_ `move`, so `regex2` will never match `line`. The score is usually in the end after a space, isn't it? It's probably easier to remove everything after the last space. To do this, you'd [find the last occurrence of a space](https://stackoverflow.com/questions/9572490/find-index-of-last-occurrence-of-a-substring-in-a-string) and then [slice `move` up to the last index you just found](https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/) @Trojan666
Comment: This will be applied in bigger data, so there will be multiple moves. Let say I save the object move like above. How about iterate and put everything that starts with '1.' until it finds another '1.' put the first string until the last occurrence into a list? Sorry, it is a little bit overwhelming.
Comment: I think you should give it a shot and ask a new question with more details and examples. It's hard to understand what you need to do through a comment. Once you've posted the question, feel free to shoot me the link and I can try to answer it. @Trojan666
Comment: I made it with the guidance of yours. I found one difficulty to separate the move from black and white. I will post it in a new question tho.
Comment: What's the difficulty? Simply splitting by space should do that, no?
Answer: The shortest intelligible line you might be interested in should be at least 4 characters (move number, move notation). So you can freely check those first characters for initial validity even up to moves of index 100 or more.
At some stage you might come across lines that start with a Black move, but they still start with a number I believe. ('15. ... Bd4+')
Since an earlier version caused a little confusion, this one splits out the first character test from those subsequent more explicitly:
def good_moves_start(pgnline):
    if len(pgnline) < 4:
        return False
    if pgnline[0] not in '123456789': # first char test
        return False
    for ch in pgnline[1:4]:
        if ch == '.':
            return True               # dot completes move #
        elif not ch.isdecimal():
            return False              # disqual characater
    return False                      # no dot in first 4 chars

This only identifies candidate move data of course; there is plenty more validation possible as the moves are read in. It would be interesting to consider how to allow for puzzle boards and chess variants - pieces, board, moves, # of players.
Comment: @PranavHosangadi not quite; I didn't want to allow leading zero for first test, and subsequently '.' is permitted.

Parsing PGN string starts with number


Passar parâmetros usando o client do guzzle

Question: Preciso consumir uma api, a passagem dos parâmetros são feitos dessa forma:

https://api.typeform.com/v1/form/[typeform_UID]?key=[your_API_key]

Estou utilizando o guzzle para fazer a requisição.
Estou instanciando o client com a base url dessa form:
$client = new Client(['base_url' => 'https://api.typeform.com/v1']);

Eu queria passar os parâmetros "/form", "[typeform_UID]?key=[your_API_key]", utilizando o $client->get(). Se eu utilizo o get(query=>[]) do guzzle ele não forma a url da forma que eu gostaria.
Alguém sabe alguma maneira de fazer isso, utilizando o Client com base_url?
Comment: Qual versão do Guzzle você instalou?
Answer: A forma de definir o parâmetro padrão no Guzzle é usando query.
Veja:
$client = new GuzzleHttp\Client([
    'base_uri' => 'http://example.com/',
    'query'   => ['foo' => 'bar']
]);

Se você precisar usar outros parâmetros na url combinado com os parâmetros padrões que você quer definir, sugiro usar o método Client::getConfig('query'), combinando com os novos valores desejado, dessa forma:
$client->get('foobar', [
    'query' => $client->getConfig('query') + ['bar' => 'foo']
]);

Outra coisa que você precisa tomar cuidado é que o Guzzle tem umas regrinhas específicas para a "montagem" do path da sua base_url.
Se você colocar o base_url com a / no final, você não pode fazer uma requisição para uri colocando / no início. E se não colocar a / no final do base_url, aí já é o inverso, você precisa colocar a barra, sempre que fizer as requisições:
Exemplo A:
$cli = new GuzzleHttp\Client(['base_url' => 'http://meusite.com/api/v1/']);
$cli->get('usuarios/list');

Exemplo B:
$cli = new GuzzleHttp\Client(['base_url' => 'http://meusite.com/api/v1']);
$cli->get('/usuarios/list');


Number of try for $p$ and $q$ to find $m$(Brute-force a RSA key)

Question: To find $m$ there is a method called Brute-force that calculates all possible combination and apply them to find the only one true answer.
This is an example:
Prime number (Bitsize: 512) (*): p
============================================================= dec ====
13059313724319126815698328933761111023445599295666419531591666294317326706135802771868772964777544791631665594397048785390359533210057462940524389248589953
Prime number (Bitsize: 512) (*): q
============================================================= dec ====
11292070857539789665049405958629835091255215659291199773104193934768436659737674012016529740997052319915770253093741328930874356021224885805564002892313913
Modulus (Bitsize: 1024): n=p*q
============================================================= hex ====
d1ffe2398f9c81edb18b3a94a59939e54c751961c27c6e377d55b1c6477a6b88d7404d9f2dcad2928b6058d1f63339cb63ab9e48c0882ca55a044719ab304edd30811ad743aefaeb5d1576685e58808635d8837c7bc097343cddb21f88d72c3b7cc4a6b45a5f0e5214844a1ef88decec9c0780b513772e64d0cadad3161571b9
looking for a mathematical formula to estimate the number of entire test values.
Comment: @R1w By the [Fundamental Theorem of Arithmetic](https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic), the will be precisely 1 way to factor a number as the product of primes.
Comment: If I understand your question correctly, you are asking, given a product of two primes $m$, how many ways are there to factor it as $m=pq$ where $p,q$ are primes?
Comment: Please make clear what you are asking.  In RSA we choose two large primes, $p,q$ and multiply them to get $m$.  There is then exactly one way to factor $m$.  Are you suspecting there may be more?  Or are you asking about more general $m$ of this size.  An $m$ that has more prime factors will have more factorizations.
Comment: Finally it is clear you want the number of numbers to try for $p$, not the number of factorizations.
Comment: Perhaps other people on this site are more savvy in the technical field from which you are asking (which appears to be cryptography) are able to understand what it is you are asking for, but I could not tell, even after re-reading your question a couple of times...
Answer: In a brute force trial you are simply taking $m$, guessing $p$ and dividing to see if it comes out even.  If you know nothing about how $p$ and $q$ are chosen, you need to try all the primes up to $\sqrt m$, which is about $\frac 12\cdot \frac {\sqrt m}{\log m}$.  Traditionally we force $p$ and $q$ to be just about the same size, so you can reduce this a bit but not much, say $10\%$
If $m$ has $1024$ bits it is about $2^{1024} \approx 1.8\cdot 10^{308}$.  There are about $2^{512} \approx 1.3\cdot 10^{154}$ choices for $p$.  If you had an oracle to tell you which of these are prime, it is about $1$ in $355$ of them, so that would cut the number to try to about $3.8 \cdot 10^{151}$.  You are not going to get this done any time soon.


Find $\vec{r}$ which satisfies given conditions

Question: Let $\vec{a},\vec{b},\vec{c}$ are three non-coplanar vectors and $\vec{r}$ be any vector in space such that $$\vec{r}.\vec{a}=1$$ $$\vec{r}.\vec{b}=2$$ $$\vec{r}.\vec{c}=3$$
and $$[\vec{a}\hspace{0.2cm} \vec{b}\hspace{0.2cm} \vec{c}]=1$$
Then find $\vec{r}$.
Problem is that using conventional method, too many variables are introduced. How should I proceed?
Comment: What vector space are you working in?  $\mathbb{R}^3$?  What does the notation $[\overrightarrow{a}\overrightarrow{b}\overrightarrow{c}]$ mean?  The triple scalar product $\overrightarrow{a}\cdot (\overrightarrow{b}\times \overrightarrow{c})$?
Comment: @JMoravitz Yes to both your questions.
Answer: $$  \vec{b} \times \vec{c} + 2 \, \vec{c} \times \vec{a} + 3 \,  \vec{a} \times \vec{b} $$
It should be pretty easy to check that this satisfies the requested conditions.
Comment: Why did this receive a down vote??  +1
Comment: Could you give just a bit of explanation?


How to get numbers from a string and add them?

Question: I want to find a number from a string and return the value.
If a string contains more than one number then it should add all the numbers in string and return the total.
For Ex: "20 min was spent on team huddle meeting and 90 minutes were spend on training" So the return value should be 110 (90+20)
Comment: look into using RegEx
Comment: What have you tried? Have you googled - this is not an uncommon question?
Comment: @PalashGangal the answers and/or examples are only meant to assist you overcome your difficulties, and not to function as a black box that you can use 'as is' because you dont understand how it works. if your understanding in coding is not sufficient to understand the solutions you found online, then first i recommend you learn some more coding.
Comment: are the numbers always in the same position? Same number of characters? One way or another, worksheet text functions can do this. (ie., FIND,MID, LEN, etc)
Comment: Yes I googled it, but not able to identify which code will work for me. Because I do not understand their solution. @ SJR
Comment: @Banana I don't know how to use regex. It would  be great if you can help
Comment: @ashleedawg No numbers are not always at the same position.
Answer: Try regex.
Option Explicit

Function sumNums(str As String) As Long
    Dim n As Long
    Static rgx As Object, cmat As Object

    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If

    With rgx
        .Global = True
        .MultiLine = True
        .Pattern = "[0-9]{1,7}"
        If .test(str) Then
            Set cmat = .Execute(str)
            For n = 0 To cmat.Count - 1
                sumNums = sumNums + cmat.Item(n)
            Next n
        End If
    End With
End Function

Comment: Using a static object is a great idea *(+1)*
Answer: Give this a try:
Public Function NumEx(s As String) As Double
    Dim L As Long, i As Long, s2 As String
    Dim CH As String

    L = Len(s)
    NumEx = 0
    If L = 0 Then Exit Function
    s2 = ""

    For i = 1 To L
        CH = Mid(s, i, 1)
        If CH Like "[0-9]" Or CH = "." Then
            s2 = s2 & CH
        Else
            s2 = s2 & " "
        End If
    Next i

    s2 = Application.WorksheetFunction.Trim(s2)
    arry = Split(s2, " ")

    For Each a In arry
        NumEx = NumEx + a
    Next a
End Function

NOTE:

the input string is converted into an array of numbers
the array is then summed

EDIT#1:
A VBA UDF can be use in two ways:

in a cell (see the picture above)
from a Sub or from another UDF

Here is an example of the second way:
Comment: Can you please tell me how to run a function program in VBA, I am working in normal module, and if I paste this program it asks me to name the macro, and it creates a new sub and end sub.
Comment: @PalashGangal  See my **EDIT#1**
Comment: Thanks a lot, now I am able to run the code. But its returning value in msg box and not as you have shown in your excel screenshot. And which line in your code is deciding that it has to pick string from which column,
Comment: It worked. Thanks a lot for your help. Wish I could code like this.
Comment: can this take the string from different sheet in same workbook? because its giving #value if I try to use it by giving reference to cell in different sheet.
Comment: @PalashGangal  We are almost there!  The first picture shows how to use the function in a worksheet cell *(like you would use Vlookup)*.  The second picture shows how to use the function from a sub.
Comment: @PalashGangalTo use a cell in a different worksheet try **=numex('new data'!C3)** or something like it


How to fix ADFS asking for Windows credentials after login?

Question: We are having issues with an ADFS environment (providing authentication for a Dynamics CRM 2011 IFD installation), symptoms are as follows:

We navigate to https://crm.domain.com:444
We see the ADFS authentication form
We enter valid credentials
We are redirected to the authentication URL
Instead of being redirected to the site, a Windows auth popup shows up, requesting credentials, stating "The server https://auth.domain.com requires a username and password" [auth.domain.com is the ADFS server]
Any credentials we input in the popup leads to some waiting, and the popup shows up again
If we navigate away and go back to https://crm.domain.com:444 we are not asked again to authenticate but the popup shows up immediately (so it seems ADFS authentication has indeed worked).

We already tried to reboot all servers:

DC first
DB second
ADFS/CRM last

Customer's IT person is at a loss too (he's new to ADFS, and we are devs not IT people ourselves so out knowledge is hit and miss). Is there any known solution ?
I'll add more info/specs as needed (I'm not sure what's relevant).
Answer: I suspect the authentication settings on the virtual directories have been messed about with.
Ensure /adfs virtual directory is set to anonymous only
Ensure /adfs/ls is set to anonymous and Windows Integrated Auth both only.
Comment: I forgot to follow up on this: authentication settings were indeed off, after fixing them like you suggested everything went back up. Further investigation revealed that a third party was working on some kind of unrelated web app, and was oblivious about the ADFS having stopped working ...


Why is the tune of Twinkle Twinkle Little Star used everywhere?

Question: We've all heard the lullaby Twinkle Twinkle Little Star. It's madly famous. Today I noticed that the melody used in the piece is actually used in The Alphabet Song. ABCDEFGHIJKLMNOPQRSTUVWXYZ or whatever it's called. If you listen to Baa Baa Black Sheep you are also able to notice that the tune is quite close to Twinkle Twinkle Little Star.
Why is this one melody used in so many different lullabies?
Comment: Not to mention its presence in "Carnival of the Animals: Fossils"
Answer: The melody is from a French song, Ah! vous dirai-je, maman
The first known publishing of the melody dates from 1761, who knows how much further back it goes.
Mozart wrote some variations based on it, which probably helped popularise it a lot greatly

Nursery rhymes, sport chants, folk songs, political rally songs etc. often use existing melodies that are already well remembered, and just change the words, this happens with a lot of melodies.
This particular melody? Musically, it's simple, memorable, and easy for children and adults to sing and play because of its short range (6 notes, less than an octave).  It's rhythmically repetitive and pretty much as simple as you can get: 1 2 3 4 5 6 7 (8) x6 which makes it very easy to put words to, and very easy to remember.  Also more subjectively, it's a lovely little melody, it's not surprising it's stuck around.
The question as to why twinkle twinkle is such a memorable and well loved melody is  despite its simplicity is difficult to answer without either being too technical or too hand-wavy, but suffice to say that it packs a lot of content into it short and sweet package.  It's conversational, it sort of raises a question and answers it.  It has a sort of tension and release, with the middle section being reassuringly answered by the same melodic phrase that came at the beginning.  The harmonic structure is perfectly resolved: I'd be hard pressed to think of a more "complete" sounding short melody.
I think it's just one of those melodies like "oh when the saints" "amazing grace" "O tannenbaum/Oh Christmas Tree/The red flag etc." - which knows exactly what it is, doesn't have any unnecessary frills: every note is pretty much there for a purpose, and it makes them pretty timeless.  "Amazing Grace" and "Oh when the saints" function very differently harmonically to "Twinkle Twinkle", but the point I just made applies to them both.  But if it was easy to exactly quantify what makes these melodies so timeless, then we'd all be writing them.  There's an element of tradition of course, but there's more to it than that.  I'm sure people have written long books about it.
Comment: By the way, if anyone wants to rip off whichever parts of this answer they agree with and elaborate further on parts where I could have been clearer, I certainly wouldn't mind!
Answer: Some of this is certainly a feedback loop: it's popular to use this melody because it's popular to use this melody.  Once you start using a melody for multiple songs, it becomes more likely that that melody will be used for the next song!
That melody has a few great features:

Its range is only 6 notes, which means nearly everybody can sing it.  Even with mixed voices, one can typically find a root pitch for which everyone can sing 6 notes.
It has a jump from the tonic to the fifth.  That's a rather common interval for much of Western music, so there may be some value in teaching it to kids early.
Its middle part ends on the supertonic, almost forcing the song to move forward towards resolution.
It's chock full of chord progressions from IV to V to I, which are a major fundamental basis for western music.

That being said, if you want to know what song is used for too many famous songs...
Comment: All excellent points.  I would add that the reason that I V and IV are a fundamental basis for western music is because they sound so agreeable to us (not vice versa), that is to say we gravitate towards them naturally.  There's a bunch of stuff about frequency ratios and the harmonic series we could go into, but it's probably better to just summarise it that the harmony in this song sticks in the territory of  our "Basic" musical intuitions.  Basic in the sense of "fundamental", rather than "boring" I mean.
Comment: (not trying to imply that you implied the opposite here, just thought it might be a valuable little footnote to a good answer)
Comment: @Some_Guy Yeah.  There's some interesting psychology involved because the harmonics of what sounds good are not universal to all humans, but are rather universal within a culture.  It's quite the fascinating topic to explore!
Comment: I would love to discuss this in chat because I am very interested in this topic, and have to disagree with you quite strongly.  I'm not saying that culture is irrelevant, just that there are also universals to all humans  :)
Comment: @Some_Guy http://chat.stackexchange.com/rooms/51199/discussion-on-chord-progressions (in case you didn't see my ping from within the chatroom)


Probability that given weight is on the heavier side of a balance

Question: Assume we have 6 balls weighting 101, 102, 103, 104, 105 and 106 in kg. If we randomly pick 3 balls and place them on one side of the scale and the other 3 left are placed on the other side of the scale. What is the probability that the ball weighting 106 kg is on the heavier side?
Comment: There are ${6 \choose 3}=10$ configurations, and we are aided by knowing if the 104 or 105 are with 106 then that side will always be heavier. It should now be easy to count.
Answer: Let $X,Y$ be the other two balls on the same side as the $106kg$ ball,
The event "106kg is on the heavier side"($E$) can be expressed as the following:
$$E \iff X+Y+106 \geq \left \lceil \frac{621}{2} \right\rceil = 311 \implies X+ Y \geq 311 - 106 = 205 \implies $$
$$P(E) = P(X + Y \geq 205)$$
If we set aside 106 then $X,Y$ are chosen from the remaining 5 balls, so there are ${5 \choose 2} = 10$ total possibilities. Of these, the ones that result in $205$ or higher are:
$(101,104),(101,105), (102,103), (102,104), (102,105), (103,104),(103,105),(104,105)$
So 8 possibilities out of 10, so $80\%$ probability that the side that htas 106 kg ball is the heavier side..
Comment: @fool_of_a_took you can solve in similar way for 106 being by itself and 106 being with one other, up through 4 others, these will be conditional probabilities: P(E|106 is part of a group of size i). You then add them up by multiplying P(106 is part of a group size i) with each conditional probability. For example, 106kg by itself will never be on the heaver side, similarly for being with only 1 other (given how all the weights are more or less 100 + y. On the flip size, if its in a group of 4 or 5 others it will always be on the heavier side, so really its just N=3 that matters.
Comment: Concretely -- P(E|N=i) = 0 if i is 1,2 and P(E|N=j) = 1 for j = 4,5 ,s so you just add up the probability it will be in a group of 4,5 + 0.8*probability being in group of 3
Comment: Thanks for your answer. What about the case where it is not guaranteed that there are 3 weights on each side(Assume at least one weight on each side)?
Answer: The problem is same as considering the weights $1,2,3,4,5,6$ instead.
There are $\dfrac{6!}{3!3!2!}=10$ ways to divide $6$ distinct objects into two groups of threes. One way, quick enough, is to list out the ten pairs of triples and see for how many cases $6$ belongs to the group with larger sum.
A yet shorter way is to consider the sum $1+2+3+4+5+6=21$. $6$ belongs to heavier side, when sum of three weights including $6$ is more than $21/2=10.5$. Unfavorable cases are only two : $(6,1,2)$ and $(6,1,3)$.
Number of favorable events is $10-2=8$ and required probability is $8/10$.


How to differentiate $ f(x) = (\csc \pi x)^{-4/5}$

Question: How can I  differentiate $ f(x) = (\csc \pi x)^{-4/5}$?
My problem is that there is a $\pi$ in the question and it's a constant so how is it supposed to be differentiated in the first place?
Would appreciate any help on this.
Answer: We can take a simple example first so as to ease your confusion around $\pi$ being in the expression we want to differentiate.
Take $\sin(3x)$. I'm sure you'll agree with me that the derivative of this with respect to $x$ is $3 \cos(3x)$. We can arrive at this using the chain rule, where after differentiating $\sin(x)$ we multiply by the derivative of $3x$ which is, of course, just $3$. Now replace the constant $3$ with $\pi$. There is no difference in technique—the derivative is $\pi \cos(\pi x)$.
Let's tackle your real question. First note that $\frac{d}{dx} [\csc(x)] = -\cot(x)\csc(x)$.
We'll apply the chain rule as we did above, repeatedly.
$$f(x) = (\csc(\pi x))^{\frac{-4}{5}}$$
$$f'(x) = \color{red}{ \frac{d}{dx} [(\csc(\pi x)^{\frac{-4}{5}})]}$$
$$ = \frac{-4}{5} \csc(\pi x)^{\frac{-9}{5}} \cdot \color{red}{ \frac{d}{dx} [\csc(\pi x)]}$$
$$= \frac{-4}{5} \csc(\pi x)^{\frac{-9}{5}} \cdot -\cot(\pi x)\cot(\pi x) \cdot \color{red}{ \frac{d}{dx} [\pi x]}$$
$$= \frac{-4}{5} \csc(\pi x)^{\frac{-9}{5}} \cdot -\cot(\pi x)\cot(\pi x) \cdot \pi$$
which rearranges to give
$$f'(x) = \frac{4}{5} \pi \csc(\pi x)^{\frac{-9}{5}} \csc(\pi x) \cot(\pi x)$$
There is no problem with $\pi$ being within the $\csc$ function here; we can treat it like any other constant.
Answer: It may help if you think of the function $f$ defined by $f(x) = (\csc \pi x)^{-4/5}$ as the composition of three separate function:
$$
f(x)=(\csc \pi x)^{-4/5} = g(h(j(x))
$$
where
$$
g(x) = x^{-4/5} \\
h(x) = \csc x\\
j(x) = \pi x
$$
By the chain rule,
$$
\frac{d}{dx} f(g(x) = f'(g(x)\cdot g'(x).
$$
Hence, we have
\begin{align}
\frac{d}{dx} (\csc \pi x)^{-4/5} &= \frac{d}{dx} g(h(j(x))\\
&=g'\left(h(j(x)\right)\cdot \frac{d}{dx}\left(h(j(x))\right) \\
&= g'(h(j(x))\cdot h'(j(x)) \cdot j'(x)
\end{align}
or
\begin{align}
\frac{d}{dx} (\csc \pi x)^{-4/5} &=
\frac{-4}{5} \left(\csc \pi x\right)^{-9/5}\cdot \frac{d}{dx}\left( \csc \pi x\right) \\
&= \frac{4}{5} \left(\csc \pi x\right)^{-9/5}\cdot \csc \pi x\cot \pi x \cdot \frac{d}{dx} (\pi x) \\
&= \frac{4\pi}{5} \left(\csc \pi x\right)^{-9/5}\cdot  \csc \pi x\cot \pi x
\end{align}
Comment: You dropped a negative in your second to last step. Check d/dx ( csc pi x )
Answer: $\csc'(x)=-\csc x \cot x$.  Now use the chain rule:   $\dfrac{4\pi}5(\csc \pi x)^{-\dfrac 95}\csc \pi x\cot \pi x$.
Answer: You can use that the derivative is linear with respect to multiplication by a constant, that is;
$$\frac{d}{dx}\alpha f(x)=\alpha\frac{d}{dx}f(x)$$
For any constant $\alpha$ and differentiable function $f(x)$.
Using the chain rule and this linearity, you then have;
\begin{align*}
\frac{d}{dx}cosec(\pi x)=-cosec(\pi x)cot(\pi x)\frac{d}{dx}(\pi x)=-\pi cosec(\pi)\cot(x)
\end{align*}
Then you can use the chain rule again to find the derivative you're after.


CKEditor tabber shows tabs to the right on the screen when logged in as admin

Question: I have reported this question with the CKEditor tabber issues, but I thought I ask this question here too, in case I am missing something obviuos... I have installed the CKEditor tabber module and after creating some tabs and tab content, the tabs is pushed out to the right in the screen. Like this:

I noticed that when I log out the tabs appear above the content as expected. I have narrowed it down to the permission "Use admin toolbar". When the admin toolbar is shown, the CKEditor tabs is showed as on the image. When the admin toolbar is not shown, the CKEditor tabs shows as they should above the tab content.
I have spent hours trying to find how the toolbar affects the CSS in this way, but I can't figure out what to do...
Anyone?
UPDATE: I noticed that the "left" attribute is 100% too large in this section that is in charge of the first tab's positioning and width:

In the js file semantic-tabs.js this code is in charge of the above:
$(this).css({
  'width': (100 / numTabs) + '%',
  'left': (100 / numTabs * tabIndex) + '%'
});

So, if I add "-100" after tabIndex above the tabs are positioned correctly when logged in with the admin toolbar visible. If logged out the tabs are pushed to the left in this case. So the JS decides to add 100% to the "left" value when the toolbar is visible. Also I can see that for half a second the tabs are positioned correctly before being pushed out, every time I refresh the page. I am going crazy here...
Comment: On what page/s does this happen? Is it for a particular content type? All content type? For a specific role? All roles?
Comment: All content types and all roles that have permission to see the admin toolbar. If I disable the toolbar permission the tabs shows correctly.
Comment: Odd. When you look at the HTML source code, do you see an extra   or a missing  somewhere before/after the tabs? It seems like something is pushing the divs out of whack...
Comment: Yes, it really is... No I cannot see any stray DIV's. See my update above.
Answer: In case anyone else has the same problem I will answer my own question. I found the answer to my problem in this issue for the same module: https://www.drupal.org/node/2774763
The problem was not exactly the same to begin with, but the solution was the same. The variable tabIndex needed to be placed within the function, not outside as a global. Problem solved.