htaccess remove uma barra (/) da url ao utilizar WWW no prestashop

Question: Tenho uma instalação prestashop versão 1.7.6 com multiloja ativado.
A princípio, o prestashop configurou o htaccess já. Cada loja é acessada da seguinte forma:

https://meudominio.com/loja-a
https://meudominio.com/loja-b

acontece que, ao tentar utilizar www (www.meudominio.com/loja-x), o htaccess deveria redirecionar para https correto?
no domínio principal ele consegue fazer isso:
de:
- www.meudominio.com
para:
- https://meudominio.com
agora, quando tento acessar uma loja com www, o htaccess remove a barra da URL. o resultado é esse:
de:
- www.meudominio.com/loja-x
para:
- https://meudominio.comloja-x
Alguém ja enfrentou algum problema parecido?
Tem alguma dica de como resolver?
Eu não sei mexer no htacces, ja tentei algumas coisas mas sem sucesso.
segue o trecho do htacces que eu acredito que está fazendo essas alterações:
.htaccess
//-------------------------------------------------------------
RewriteCond %{HTTP_HOST} ^meudominio.com$
RewriteRule . - [E=REWRITEBASE:/]
RewriteRule ^api(?:/(.*))?$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]
RewriteCond %{HTTP_HOST} ^meudominio.com$
RewriteRule ^demo$ /demo/ [L,R]
RewriteCond %{HTTP_HOST} ^meudominio.com$
RewriteRule ^demo/(.*) /$1 [L]
//-------------------------------------------------------------
o meu htaccess tem vários trechos iguais a esse, porém é um para cada loja que tenho registrada.. o próprio prestashop que criou essas configurações.
No caso acima, é uma regra para a loja chamada "demo"
Apenas substitui meu domínio real por "meudominio"
Comment: Já tentou:
`RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^meudominio.com$`, [veja aqui](https://htaccessbook.com/htaccess-redirect-https-www/)
...
Comment: Sim, eu havia verificado esse artigo anteriormente. Mas não consegui resolver, eu também verifiquei sobre configurações de DNS achando que pudesse ser o problema. Depois de várias tentativas eu acredito que realmente seja algo no htaccess
Answer: Experimenta assim:
<code>//-------------------------------------------------------------

RewriteCond %{HTTP_HOST} ^(www\.)?meudominio\.com$

RewriteRule . - [E=REWRITEBASE:/]

RewriteRule ^api(?:/(.*))?$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]

RewriteCond %{HTTP_HOST} ^(www\.)?meudominio\.com$

RewriteRule ^demo$ /demo/ [L,R]

RewriteCond %{HTTP_HOST} ^(www\.)?meudominio\.com$

RewriteRule ^demo/(.*) /$1 [L]

//-------------------------------------------------------------
</code>
Comment: Ivan, eu tentei utilizar o código acimas mas o problema continuou o mesmo.
Reiniciei o apache e limpei o cache do prestashop.
Será que o problema está em outro trecho do htaccess?
Tem um trecho que está no início do arquivo que parece algumas regras mais gerais..
segue o trecho:

SetEnv HTTP_MOD_REWRITE On

RewriteEngine on

#Domain: meudominio.com
RewriteCond %{HTTP_HOST} ^meudominio.com$
RewriteRule . - [E=REWRITEBASE:/]
RewriteRule ^api(?:/(.*))?$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]
Comment: Acho estranho você dizer que o .htaccess remover a barra, porque, pela lógica, o .htaccess possui uma regra de reescrita, mas na verdade ele só é um interpretador de como deve receber o valor e, ele não remove barras, ele apenas redireciona para a maneira da reescrita que foi definida na regra. Entenda que ele não cria nada, ela se baseia na entrada que vem, e envia a saída que vc mascara.
Comment: Você está me dizendo quando quando vc acessa um endereço com www na frente, ele está removendo a barra, eu não consigo entender, como vc está acessando esse endereço, é um link na sua página? Ou quando bate no link normal, ele está reescrevendo para esse sem barra?
Comment: eu digito no navegador "www.meudominio.com/loja-x", ai eu recebo uma resposta 301 que é de redirecionamento não é? só que eu sou redirecionado para o endereço "https://meudominio.comloja-x" e ai então da um erro, pois esse endereço não existe. se eu adicionar a barra nesse endereço final ai funciona. eu pensei que era o htaccess que "formatava" a url nova para a qual eu seria redirecionado.. mas se não for ele que está me redirecionando para essa url errada, então não sei onde procurar, vou olhar novamente as configs no dns


How to select the level of confidence when using confidence intervals?

Question: Saw the expression of "95% confidence interval is commonly used" in a lot of literature. I want to understand more about why 95% (or 99%) is a good level to use. Or is there a general methodology to determine what a good level to use is?
Commonly see the need for bootstrap confidence intervals from data with unknown (non-Gaussian) distributions. For various kinds of metrics (e.g. median, rank, specially customized measure). Is 95% a good starting point for all sorts of metrics? For some use cases, a more stringent 99.9999% confidence interval is agreed by the field. In other instances, people use a more relaxed level. I hope to get an understanding of the general theory or methodology to determine when to use what level.
Comment: Having fought this battle at work a few times, I will add that if you're basing your confidence level on the sample size, you're misusing frequentist inference.
Comment: It's like that song from *Fiddler on the Roof*: Tradition!
Comment: The confidence threshold you elect to use has *nothing* to do with sample size.  A small sample size might be problematic because of low *power.*  Any "general methdology," to the extent it exists at all, must consider the entire decision risk curve: namely, confidence together with power.
Answer: Richard McElreath puts it nicely in Chapter 3 of Statistical Rethinking, second edition:

Rethinking: Why 95%? ... This customary interval
also reflects the customary threshold for statistical significance,
which is 5% or p < 0.05. It is not easy to defend the choice of 95%
(5%), outside of pleas to convention. Ronald Fisher is sometimes
blamed for this choice, but his widely cited 1925 invocation of it was
not enthusiastic:
"The [number of standard deviations] for which $P=0.05$, or 1 in 20,
is 1.96 or nearly 2; it is convenient to take this point as a limit in
judging whether a deviation is to be considered significant or not."
Most people don't think of convenience as a serious criterion. Later
in his career, Fisher actively advised against always using the same
threshold for significance.
So what are you supposed to do then? ... For example, why not present
67%, 89%, and 97% intervals, along with the median? Why these values?
No reason. They are prime numbers, which makes them easy to remember.
Answer: There is no de-constextualised confidence level that is "better" than others.  The point of a confidence interval procedure is that it should be valid for any chosen confidence level from 0% to 100%, and the interval gives an inference at whatever confidence level is desired.  In most contexts we want to use a confidence level that is high enough that the parameter of interest will usually fall within the interval.  Conventionally that has led people to use confidence levels of 90% or higher.  The conventional use of confidence levels 90%, 95%, 98%, 99%, etc., it based solely on an appeal to using "simple" numbers that are easy for users to understand.
Where a particular choice of a confidence level for a confidence interval (or significance level in a hypothesis test) becomes good or bad is when we have an actual decision problem with a decision to make, and there are negative consequences for an incorrect decision.  In such cases we form a confidence level (or hypothesis test) by considering the relative size of the negative consequences that accrue to wrong decisions of different kinds.  As a general principle, if the consequences of having the parameter fall outside the interval are relatively bad then we would use a higher confidence level; if the consequence of having the parameter fall outside the interval are relatively minor then we would use a lower confidence level.
In order to avoid bias in the procedure, one thing that is important here is that the choice of confidence level (or significance level) should not depend on the content of the data.  The confidence level should be formed by reference to exogenous factors relating to the relative consequences of inferential errors (in the contextual case) or based on conventional values that might later be useful (in the non-contextual case).  The sample size should not affect the choice of confidence level, but it does affect the power of the inference, and attention should be paid to the latter to give a holistic understanding of the inference.


Data validation based on cell value

Question: I am adding a data validation list based on a cell value. If value in cell B29 = "text1" then add data validation in cell D29. If the cell B29 has a different value then a formula has to be added to cell D29 and the data validation has to be removed.
Here is an example of the macro:
If Range("B29").Value = "Text1" Then
Range("D29").Value = ""
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=INDIRECT(B29)"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
ElseIf Range("B29").Value = "Value1" Then
 Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
 Range("D29").Validation.Delete
ElseIf Range("B29").Value = "Value2" Then
 Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
 Range("D29").Validation.Delete
ElseIf Range("B29").Value = "Value3" Then
 Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
 Range("D29").Validation.Delete
 End If
End Sub

Cell B29 is also a data validation cell which has 4 values. If the value is text1 then cell D29 has to change into a data validation list but I have to run the macro manually to do this. When D29 is a data validation list and I change the value in cell B29 I have to run the macro again (manually) to change it back to the formula.
Comment: Please explain how is your macro not working
Comment: Cell B29 is also a data validation cell which has 4 values. If the value is text1 then cell D29 has to change into a data validation list but I have to run the macro manually to do this. When D29 is a data validation list and I change the value in cell B29 I have to run the macro again (manually) to change it back to the formula.
Answer: You could capture the Worksheet_change event to re-run the macro when D29 changes.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("B29")) Is Nothing Then
        Call myMacroToChangeValidationOfD29
    End If
End Sub

BTW, why With Selection.Validation not With Range("D29").Validation ??
Comment: I indeed changed it to With Range("D29").Validation and used StrComp which  Lajos Arpad posted and it works like it should but I still need to run the macro manually. Am I doing something wrong?
Comment: @Miksel not wrong, but you have a requirement which is to change the validation of `D29` whenever `B29` changes. The `Worksheet_Change` event is made for this. You need to add this handler to automate the running of the macro, add it (as in my answer) in the code of worksheet that contains your `B29` cell, and change the `call` to the correct name of your macro, the macro that you show in the OP.
Comment: I get an error message: runtime error 438. Object doesn't support this property or method.
Comment: Yeah I made a mistake in the syntax of `Intersect`. Please reconsider the edited code.
Answer: I would use StrComp to compare strings, example:
If StrComp(Range("B29").Value, "text1") = 0 Then
    'Something
End If

You want to check B29 against "text1", however, you are checking it against "Text1". You might have a problem of case sensitivity. Your else cases are similar, you could simplify them to a single else, like this:
If StrComp(Range("B29").Value, "text1") = 0 Then
Range("D29").Value = ""
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=INDIRECT(B29)"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
Else
 Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
 Range("D29").Validation.Delete
End Sub

Data validation based on cell value


Painfully slow local development

Question: I know some may suggest that this question needs to be asked on StackOverFlow, but I do not believe this is not a Dev issue and probably an IT/Security thing. I will post this question on Superuser as well.
I am the newest developer in a company and I work remotely. I have received a top notch fast development laptop which is the same as everyone else.
This Laptop is connected to a USB-C to Lan adapter, then to a network switch, then to my router (all with Lan connection).
I use a VPN to connect to databases and whatnot. Among all developers, My environment has the slowest (by like 10~20X) performance. So every time I make a code change and recompile my code I have to wait 12~15min for things to load!
I have profiled my code and have noticed that SQL queries take painfully long time to execute.
A query that takes 70~90s to run on my machine through SSMS, takes less than 2s on other developers machines. (One of the developers lives in the same town as me and uses the same internet provider)
Some of the C# operations that take less than a ms to run on other laptops, take like 70ms~150ms on my machine.
Another developer and me pinged the same database server and we had comparable statistics, (delay, both zero packet loss, etc., similar internet speed after connecting to VPN) but still my queries took much longer to execute! The query is also a simple
<code> Select top(10000) ID from someTable</code>

I have disabled my Antivirus (again same thing on everyone's PC) and
no luck!
I have connected the laptop (via USB-C -> LAN hub) to my router (eliminating the switch), still no luck.
I have modified my hosts file to point localhost to 127.0.0.1 to make sure these calls are not going outside and still no luck.
I have pointed my Dev to other databases and no luck! everything still super slow.
I have disconnected my Lan and used WIFI to connect to my router, still no luck!
I have asked IT and they don't have a clue! I have done a whole bunch of other tests but I really doubt if it is something local!
during run time I have given 'Realtime' priority to all Visual Studio/IIS/SSMS processes and still no luck.

What are the other things that I can ask our It to check and what are the other local settings/stuff that I can check?
Whatever it is, to me it seems that it knows what packets are going where and what their content is and can scan/delay them selectively!
I am going to disable Windows Firewall and see but I really doubt that it is the culprit.
Comment: I seriously doubt this is a question that can be treated sensibly in a Q&A forum. There's no way you can provide sufficient technical detail here for someone to even begin to speculate about possible causes for what you report. This is something that has to be pursued hands-on.
Answer: Tilman is right.  We will most likely never figure this one out.  Too many variables all along the way.
Plug your computer directly into the cable modem. Bypass your router.  See if that helps.  Your router settings could cause latency.
Is your ISP bandwidth sufficient enough?  Run Speed tests. (again, directly from the modem)
The company's firewall could also be causing the issue.  The IT department should be willing to investigate a little bit.  At least enough to say hey, this isn't our problem.  Being an IT Manager I've seen it go both ways.
Is the sluggish performance just related to your development software?  Does the machine run well otherwise?
It's possible that you could have something misconfigured in your dev environment.  Something stupid like using an external address vs. a local address somewhere.  So that being connected to a vpn, you are sending that request to the vpn site, which then goes out to the internet only to come back in to the same vpn site and then back to your machine instead of going to the vpn site and back to your machine.
Is your dev file on a separate drive?  A lot of times, on more powerful laptops with second hdds, the second drive is a crappy one so the read/write latency on it is terrible.

Painfully slow local development


Problema com switch case dentro de for loop

Question: Preciso de ajuda com meu código com switch case dentro de for loop.
Sou iniciante em programação e não entendi o porque de o loop não ser executado como desejado. O desejado seria executar os printfs antes do switch e, posteriormente, o switch em si. Assim que a opção dentro do switch fosse escolhida e tudo dentro dela fosse executado, o loop começaria novamente. Por algum motivo, ele recomeça mas os printfs antes do switch aparecem mais de uma vez (uma vez sendo o desejado).
Se alguém puder me dizer o que eu fiz de errado e o que eu posso fazer para consertar eu agradeceria.
#include <stdio.h>

int main(void) {
  char opcao;//opcao=a vista ou parcelado
  float trans, soma;//transações, soma=soma das trans
  int numt;//número de trasações

  trans = 0;
  soma = 0;

    for(numt=0;numt<15;numt++)/* Este loop é feito duas vezes seguidas sem chance de interação após a primeira entrada de dados, por algum motivo */
    {
      printf("\nEscolha umas das duas opções:");
      printf("\nv = transações à vista");
      printf("\np = transações a prazo");
      printf("\nDigite a sua escolha: ");
      scanf("%c", &opcao);

      switch(opcao)
      {
        case'v':
        printf("\nDigite uma transação: ");
        scanf("%f", &trans);
        soma = soma + trans;
        break;

        case'p':
        printf("");
        printf("\nDigite uma transação: ");
        break;

        default:
        printf("\nERRO! A opção deve ser 'v' ou 'p'. Reinicie o programa.");
      }

    }

    printf("\nO valor das compras à vista é: %.2f", soma);
    printf("\nO valor total das compras");

  return 0;
}

Answer: O problema está na seguinte linha:
scanf("%c", &opcao);

O que acontece é que quando digitamos algum caractere no terminal, na prática é enviado para o buffer do teclado (stdin), dois caracteres:

O próprio caractere inserido.
O caractere \n, gerado ao pressionar a tecla Enter.

Como você está lendo apenas um caractere, o \n ainda está no buffer do teclado, sendo lido na segunda iteração do laço, pulando a segunda leitura do scanf() e caindo no default do seu switch-case, que imprime o erro.
Logo, ao terminar a leitura de qualquer dado do teclado, usando o scanf() ou comandos similares, o ideal é sempre limpar o buffer do teclado para retirar os "restos de dados" de dentro dele. Para isso, você pode colocar a função abaixo acima da sua função main():
void flush_buffer(){
    int c;
    while((c = getchar()) != '\n' && c != EOF)
    /* Descarta os demais caracteres do buffer */ ;
}

E chamá-la dentro da função main(), após cada scanf(), da forma abaixo:
  scanf("%c", &opcao);
  flush_buffer();

Comment: https://stackoverflow.com/a/2979217
Comment: https://pt.stackoverflow.com/a/325635/101


Resizing image in Python

Question: I'm using the code from this question to convert some raw images into png.
import matplotlib.pyplot as plt
import numpy as np

# Parameters.
input_filename = "JPCLN001.IMG"
shape = (2048, 2048) # matrix size
dtype = np.dtype('>u2') # big-endian unsigned integer (16bit)
output_filename = "JPCLN001.PNG"

# Reading.
fid = open(input_filename, 'rb')
data = np.fromfile(fid, dtype)
image = data.reshape(shape)

# Display.
plt.imshow(image, cmap = "gray")
plt.savefig(output_filename)
plt.show()

The thing is, I'm expecting a png size of 2048x2048 but all I'm getting is images under 500x500. Any advice on how to fix this?
Answer: If you just want to save the array as a .png without plotting it, you can use matplotlib.image.imsave:
import numpy as np
from matplotlib import pyplot as plt

# some random data
img = np.random.randint(256, size=(2048, 2048))

# creates a 2048 x 2048 .png image
plt.imsave('img.png', img, cmap='gray')

Resizing image in Python


InvalidArgumentException: Field field_message_header is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField()

Question: At a total loss as to what is the cause of this error. The field was added to a Message Notify template entity. It is basically used as a token in emails sent using that module. The only place in my custom code that i use this field is to set its value from a value collected in a modal form. When submitting the modal; this error occurs.
The crazy part of this is that i have removed the field from the entity (so no longer exists in visible config in the site). I have also commented out the 1 line of code that refers to this field. After a db search the only tables to reference this field are config_snapshot and config_import. There were entries there for the field which i removed and the only records which remain are for the bundles which used to hold this field. Can't find any reference to what these tables are for but guessing they are only records of past import and not actively used.
To add to the crazy, this all works fine on my local dev copy of the site.
I have run cron and cr numerous times.
Any hints?
Comment: You might find hints in the call stack of a full error message. getTranslatedFields() is a protected method which is called by the public get() method, which has as only argument the field name. Which function is on 3rd position of the call stack and where it is getting the argument from?
Comment: Had tried to get call stack to print but wouldn't show for that error (shows in logs for other errors). Anyway, my client restored the db (old) from the production server and we ran cim to get latest config - and this solved the issue. After a year of doing numerous cim on various projects i was comfortable thinking that this was the definitive defn of the site's config - but possibly it isn't. :(
Answer: I restored an old db (from the live site) and reran drush cim to get the config which should have been in the staging site (which was showing this error) - and this solved our problem. Very odd that i couldn't find a reference to this field in the db or in code and odd that cim didnt fix it until i ran it on an older db.


Longest Path in a grid

Question: Given a grid G.
Each cell can contain numbers [0 - 9] inclusive or an upper case alphabetical letter (say Z);
we can start with the upper left corner.
Then if the cell number we are on is a, we can allowed to move exactly a cells up, down left or right. Until we reach an alphabetical letter then we stop.
Given these rules, we want to find the maximum path from the start till we get out of the grid.
If the path is infinite, print "-1";
Comment: this is a typical dynamic programming problem. its straightforward. in this current state your question is more likely to get closed unless you are more forthcoming in your efforts...
Comment: @SrikarAppal Care to give a pointer? I have no idea how to solve this.
Comment: What about "0"? Is that one cell away, or the same as a letter?
Answer: Ok, to solve using dynamic programming the problem needs to have these essential properties -

Optimal substructure - optimal sol. to smaller problems leads to optimal sol. to larger problems.
Overlapping subproblems - we can store answers and reuse them (this is what gives dynamic programming efficiency, otherwise complexity would be exponential).

That was some theory, coming back the maze problem. Since you want the MAXIMUM path from the start to end. This is a NP-Hard problem & no polynomial solution exists. A General maximum path problem in a graph with positive weights is as simple as Travelling Salesmen problem where we visit all nodes before reaching destination as longest path includes all vertices.
So the approach you take is this (also mentioned in wiki link) -

Consider your maze as a graph. Perform a DFS on it which will result in a DFS-tree.
Use the sequence of root-to-leaf paths of the depth-first search tree, in the order in which they were traversed by the search, to construct a path decomposition of the graph, with pathwidth d. i.e. Traverse this DFS tree and one path would be there from root-to-leaf which starts from a and ends at z.
Apply dynamic programming to this path decomposition to find a longest path.
Answer: The grid forms a directed graph, with possible cycles. For each cell in the grid, you will have an edge stretching to the cell n steps away in each direction. The letter-nodes will not have any outgoing edges.
Using this graph, G, try to find a topological ordering. If there are any cycles, no such ordering is possible, and the longest path will be infinite. Use DP to compute the longest path ending in each node. The full algorithm can be read on Longest Path Problem.
void Main()
{
    string text = @"
        75XXX83XXXXX9X06218X
        XX93X7XX4X87XXX611X6
        4XXXX7X5XXXXX3XXX74X
        X5XXX2XXXX5162X7XX97
        X72X1XXXXXXXX2XXX2XX
        9X617X8XX7XXXX1931XX
        X6X14X43XXXXXXXX0166
        7XXX3XXX10XXX30315XX
        X410XXX2XX91X6XX77XX
        X42XXX7XXXXX59X2XXX5
    ";
    int pathLength = FindLongestPathInGrid(text);
    Console.WriteLine(pathLength);
}

int FindLongestPathInGrid(string text)
{
    int pathLength = -1;

    var grid = StringToGrid(text);
    var nodes = GridToNodes(grid);
    var ordering = TopologicalSort(nodes);

    if (ordering != null)
    {
        var longestPath = FindLongestPath(ordering);
        pathLength = longestPath.Count;
    }

    return pathLength;
}

char[,] StringToGrid(string text)
{
    var lines = text.Split('\n')
        .Select(l => l.Trim())
        .Where(l => !string.IsNullOrEmpty(l))
        .ToList();

    var height = lines.Count;
    var width = lines.Max(l => l.Length);

    var grid = new char[height,width];
    for (int y = 0; y < height; y++)
    {
        var line = lines[y];
        for (int x = 0; x < line.Length; x++)
        {
            grid[y, x] = line[x];
        }
    }
    return grid;
}

class Node
{
    public int Index { get; private set; }
    public int Order { get; set; }
    public List<Node> Outgoing { get; private set; }
    public List<Node> Incoming { get; private set; }

    public Node(int index)
    {
        Index = index;
        Order = index;
        Outgoing = new List<Node>();
        Incoming = new List<Node>();
    }

    public void AddOutgoing(Node other)
    {
        Outgoing.Add(other);
        other.Incoming.Add(this);
    }
}

IList<Node> GridToNodes(char[,] grid)
{
    int height = grid.GetLength(0);
    int width = grid.GetLength(1);

    // Create the nodes
    var nodes = new List<Node>();
    for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
    {
        nodes.Add(new Node(y*width + x));
    }

    // Connect them
    for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
    {
        var node = nodes[x+y*width];
        if ('0' <= grid[y,x] && grid[y,x] <= '9')
        {
            int n = grid[y,x] - '0' + 1; // '0'..'9' -> 1..10
            if (x-n >= 0) node.AddOutgoing(nodes[x-n+y*width]);
            if (x+n < width) node.AddOutgoing(nodes[x+n+y*width]);
            if (y-n >= 0) node.AddOutgoing(nodes[x+(y-n)*width]);
            if (y+n < height) node.AddOutgoing(nodes[x+(y+n)*width]);
        }
    }

    return nodes;
}

IList<Node> TopologicalSort(IList<Node> Nodes)
{
    // Compute the in-degree of each node
    var incomingCount = Nodes.Select(n => n.Incoming.Count).ToList();

    int nodeCount = Nodes.Count;

    List<Node> result = new List<Node>();
    while (nodeCount > 0)
    {
        // Find the index of any node with in-degree 0
        var node = Nodes
            .Where((n,i) => incomingCount[i] == 0)
            .FirstOrDefault();

        // None found. No ordering possible.
        if (node == null) return null;

        nodeCount--;

        // Add it to the output
        node.Order = result.Count;
        result.Add(node);

        // Remove it from further consideration
        incomingCount[node.Index] = -1;

        // Decrement the in-degree of any connected nodes.
        foreach (var neighbor in node.Outgoing)
        {
            incomingCount[neighbor.Index]--;
        }
    }

    return result;
}

IList<Node> FindLongestPath(IList<Node> nodeOrdering)
{
    int count = nodeOrdering.Count;
    Node[] cameFrom = new Node[count];
    int[] longestPath = new int[count];

    foreach (var node in nodeOrdering)
    {
        if (node.Incoming.Count > 0)
        {
            Node best = node.Incoming.MaxBy(n => longestPath[n.Order]);
            cameFrom[node.Order] = best;
            longestPath[node.Order] = longestPath[best.Order] + 1;
        }
    }

    var maxLength = longestPath.Max();

    var last = nodeOrdering.MaxBy(n => longestPath[n.Order]);
    return ReconstructPath(cameFrom, last);
}

IList<Node> ReconstructPath(Node[] cameFrom, Node last)
{
    var result = new List<Node>();
    while (last != null)
    {
        result.Add(last);
        last = cameFrom[last.Order];
    }

    result.Reverse();
    return result;
}

public static class Extensions
{
    public static TItem MaxBy<TItem,TKey>(this IEnumerable<TItem> items, Func<TItem,TKey> keySelector)
    {
        var currentBestItem = default(TItem);
        var currentBestKey = default(TKey);
        var comparator = Comparer<TKey>.Default;
        bool hasBest = false;
        foreach (var item in items)
        {
            var key = keySelector(item);
            if (!hasBest || comparator.Compare(key, currentBestKey) > 0)
            {
                currentBestKey = key;
                currentBestItem = item;
                hasBest = true;
            }
        }
        return currentBestItem;
    }
}

Example:
75XXX83XXXXX9X06218X
XX93X7XX4X87XXX611X6
4XXXX7X5XXXXX3XXX74X
X5XXX2XXXX5162X7XX97
X72X1XXXXXXXX2XXX2XX
9X617X8XX7XXXX1931XX
X6X14X43XXXXXXXX0166
7XXX3XXX10XXX30315XX
X410XXX2XX91X6XX77XX
X42XXX7XXXXX59X2XXX5

has a max path-length of 11, and a total of 4 such paths. Here is one:
....................
...3....4......6.1..
....................
...X................ <-- end
....................
...1................
................0... <-- start
.............30.15..
....................
....................

Longest Path in a grid


What does it mean for something to have good frequentist properties?

Question: I've often heard this phrase, but have never entirely understood what it means. The phrase "good frequentist properties" has ~2750 hits on google at present, 536 on scholar.google.com, and 4 on stats.stackexchange.com.
The closest thing I found to a clear definition comes from the final slide in this Stanford University presentation, which states

[T]he meaning of reporting 95% confidence intervals is that you "trap"
  the true parameter in 95% of the claims that you make, even across
  different estimation problems. This is the defining characteristic of
  estimation procedures with good frequentist properties: they hold up
  to scrutiny when repeatedly used.

Reflecting a bit on this, I assume that the phrase "good frequentist properties" implies some assessment of a Bayesian method, and in particular a Bayesian method of interval construction. I understand that Bayesian intervals are meant to contain the true value of the parameter with probability $p$. Frequentist intervals are meant to be constructed such that such that if the if the process of interval construction was repeated many times about $p*100\%$ of the intervals would contain the true value of the parameter. Bayesian intervals don't in general make any promises about what % of the intervals will cover the true value of the parameter. However, some Bayesian methods also happen to have the property that if repeated many times they cover the true value about $p*100\%$ of the time. When they have that property, we say they have "good frequentist properties".
Is that right? I figure that there must be more to it than that, since the phrase refers to good frequentist properties, rather than having a good frequentist property.
Comment: @MichaelChernick: can you provide a precise reference about Jeffreys seeking frequentist properties for Bayes estimators? I have never heard of this story. And I also doubt Jeffreys was at all worried about using improper priors, they are all over [Theory of Probability](http://amzn.to/2h56hss).
Comment: I really like the way you thought out this question.  In the early days Sir Harold Jeffreys  tried to construct Bayesian posterior distributions that behaved like likelihood functions and hence had good frequentist properties.  So it amounts to constructing a "uniform" prior distribution.  The idea is that using such a prior means the prior is neutral and does not influence the inference.  So this applies to more than just making credible intervals look like confidence intervals.  But Jeffreys ran into some trouble because there were cases where the "uniform" prior was not proper.
Comment: Improper means that the prior density does not integrate to 1.  It seems that Jeffreys believed that the Bayesian method needed to be justified by agreeing with the frequentist method.  Bayesians eventually rejected this notion because the value of the approach they claim is that there is prior information that influences the inference and so they prefer to use proper "informative" priors.
Comment: @Xi'an as a matter of fact, for the Beta-Binomial model it's the Haldane prior (which is improper) the one which leads to the frequentist estimate, not the Jeffreys prior (which is proper, in this case). I also have never heard that Jeffreys was looking for good frequentist properties: I thought he was looking for objective priors, and by objective he meant invariant under reparametrization.
Comment: I **LOVE** this question!
Answer: A tricky thing about good frequentist properties is that they are properties of a procedure rather than properties of a particular result or inference. A good frequentist procedure yields correct inferences on the specified proportion of cases in the long run, but a good Bayesian procedure is often the one that yields correct inferences in the individual case in question.
For example, consider a Bayesian procedure that is "good" in a general sense because it supplies a posterior probability distribution or credible interval that correctly represents combination of the evidence (likelihood function) with the prior probability distribution. If the prior contains accurate information (say, rather than empty opinion or some form of uninformative prior), that posterior or interval might result in better inference than a frequentist result from the same data. Better in the sense of leading to more accurate inference about this particular case or a narrower estimation interval because the procedure utilises a customised prior containing accurate information. In the long run the coverage percentage of the intervals and the correctness of inferences is influenced by the quality of each prior. Such a procedure will not have "good frequentist properties" because it is dependent on the quality of the prior and the prior is not appropriately customised in the long run accounting.
Notice that the procedure does not specify how the prior is to be obtained and so the long run accounting of performance would, presumably, assume any-old prior rather than a custom-designed prior for each case.
A Bayesian procedure can have good frequentist properties. For example, in many cases a Bayesian procedure with a recipe-provided uninformative prior will have fairly good to excellent frequentist properties. Those good properties would be an accident rather than design feature, and would be a straightforward consequence of such a procedure yielding similar intervals to the frequentist procedures.
Thus a Bayesian procedure can have superior inferential properties in an individual experiment while having poor frequentist properties in the long run. Equivalently, frequentist procedures with good long run frequentist properties often have poor performance in the case of individual experiments.
Comment: I don't follow. Except for Empirical Bayes, in all Bayesian procedures I saw the prior is chosen **independently** of data. Thus, when applying such a procedure to multiple data sets coming from the same data generating process (this is the frequentist framework) the Bayesian will use the same likelihood function ( the data generating process is the same) **and** the same prior (the prior is independent of data in most Bayes procedures). Of course since the data change each time, the **value** of the likelihood changes, but its form is the same. Now, if each individual  [1/2]
Comment: [2/2] estimate is more accurate, how can the whole procedure be less accurate? This is only possible if the Bayesian estimate is not always more accurate. However,  since the prior is not customised to observed data, I'm not sure what makes it more or less accurate for each single case and/or "on average".
Comment: @DeltaV I think that you are dealing with the wrong reference set. Frequentist properties of a procedure relate to long run performance of the procedure applied in all new cases, not just to repeats of the particular experiment. That's why confidence interval procedures for binomial proportions have to work for all values of the parameter, not just for the value relevant to any particular instance where the procedure is used.
That type of 'long run' means that the customised prior that is appropriate to the case in question will be inappropriate for the long run.
Comment: you are right that a frequentist confidence procedure must have the nominal coverage for all values of the unknown parameter. This was clearly specified by Newman & Pearson, and it's often overlooked today. However, when you choose the prior, you don't know which is the "true" value of the parameter. You only have your sample, and the prior should be independent of the sample. Thus I still don't see clearly how you could customize the prior based on the sample. Can you make a practical example?
Comment: @DeltaIV If I know that the current parameter of interest has been estimated in the previous study then I can shape an informative prior based on that estimate. That prior will be appropriate for this current analysis, but there is not an equivalent appropriate informative prior available for the notional set of applications of the method in the long run. Thus the analysis can have much better properties in the isolated real case than  it would appear to have in the frequentist long run.
Comment: ok, I see your point. +1
Answer: I would answer that your analysis is correct.
To provide a few more insights, I would mention matching priors.
Matching priors are typically priors designed to build Bayesian models with a frequentist property. In particular, they are defined so that the obtained hpd intervals satisfy the frequentist coverage of confidence interval (so 95% of the 95% hpd contain the true values on the long run).
Notice that, in 1d, there are analytical solutions: the Jeffreys priors are matching priors. In higher dimension, this is not necessary the case (to my knownledge, there is no result proving that this is never the case).
In practice, this matching principle is sometimes also applied to tune the value of some parameters of a model: ground truth data are used to optimize these parameters in the sense that their values maximise the frequentist coverage of the resulting credible intervals for the parameter of interest. From my own experimence, this may be a very subtle task.
Answer: If there is any contribution that I can make, let me add a clarification first, and then answer your question directly. There are a lot of confusion about the topic (frequestist properties of bayesian procedure), and even disagreement among specialists. The first misconception is "Bayesian intervals are meant to contain the true value of the parameter with probability $p$." If you are pure Bayesian (one that does not adopt any frequentist notion to evaluate the Bayesian procedure), there is no such thing as "true parameter". The main quantities of interested that are fixed parameters in the frequentist world are random variables in the Bayesian world . As a Bayesian, you do not recover the true value of the parameters, but the distribution of the "parameters", or their moments.
Now, to answer your question: no, it does not imply any assessement of the Bayesian method. Skiping the nuances and focusing in estimation procedure to keep it simple: the frequentism in statistics is that idea of estimating an unknown fixed quantity, or testing a hypothesis,  and evaluating such procedure against a hypothetical repetition of it. You can adopt many criteria to evaluate a procedure. What makes it a frequentist criterium is that one cares about what happen if one adopts the same procedure over and over again. If you do so, you care about the frequentist properties. In other words: "what are the frequentist properties?" means "what happens if we repeat the procedure over and over?" Now, what makes such frequentist properties good is another layer of criteria. The most common frequentist properties that are considered good properties are consistency (in an estimation, if you keep sampling the estimator will converge to the fixed value you are estimating), efficiency (if you keep sampling, the variance of the estimator will go to zero, so you will be more and more accurate), coverage probability (in many repetitions of the procedure, a 95% confidence interval will contain the true value 95% of the time). The first two are called large sample properties, the third is the Neyman-genuinely frequentist property in the sense that it does not need to use asymptotic results necessarily. So, in sum, in the frequentist framework, there is a true and unknown value. You estimate it and you are always (except in a rare lucky accident) wrong in the estimation, but you are trying to save yourself by requiring that at least under a  hypothetically indefinitely repetition of your estimation, you would be less and less wrong or you know you would be right a certain amount of times. I won't discuss if it makes sense or not, or the additional assumptions required to justify it, given it was not your questions. Conceptually, that is what frequentist properties refer to, and which good means in general in such context.
I will close by pointing you this paper, so that you judge by yourself  if it makes sense and what it means a Bayesian procedure to have good frequentist properties (you will find more references there):

Little, R., & others, (2011). Calibrated bayes, for statistics in general, and missing data in particular. Statistical Science, 26(2),162–174.


Inverse Laplace of $p_1\cdot p_2/[(x+p_1)(x+p_2)]$

Question: I can't find the inverse Laplace of :
$$\frac{p_1p_2}{(x+p_1)(x+p_2)}$$
I remove first $p_1,p_2$ and try to $$\mathscr{L}^{-1}\frac{1}{(x+p_1)(x+p_2)}$$
$$\frac{1}{(x+p_1)(x+p_2)}= \frac{A}{(x+p_1)} + \frac{B}{(x+p_2)}$$
$$1 = A(x+p_2) + B(x+p_1)$$
With $x = 0$
$$1 = Ap_2 + Bp_1$$
Then with $x = 1$ and $x = -1$, I get:
$$1 = A + B \\ A = 1-B \\ 1 = (1-B)p_2 + Bp_1\\
1 = p_2 -Bp_2 + Bp_1
\\ B = \frac{1-p_2}{p_1-p_2} \\
A =  1- \frac{1-p_2}{p_1-p_2} = \frac{p_1-1}{p_1-p_2}$$
Which would mean that $$\frac{p_1-1}{p_1-p_2} * \frac{p_1p_2}{x+p_1} + \frac{1-p_2}{p_1-p_2}\frac{p_1p_2}{x+p_2}$$
So I see that we should have $e^{-p_1x}$ and $e^{-p_2x}$ at some point but I don't know what to do with the factors  $\frac{p_1-1}{p_1-p_2}$ and  $\frac{1-p_2}{p_1-p_2}$. What is wrong and why?
Edit: I am adding a picture of the reply.
Comment: Your A and B are wrong actually. Choose $x=-p_1$ and $x = -p_2$ to find A and B. Then $e^{-p_1 t}$ is the inverse transform of $\frac{1}{x+p_1}$.
Comment: Since $x$ is your variable the terms in $p_1$ and $p_2$ are just multipliers. The inverse will have terms of the form $e^{-p_1 t}$ with variable $t$ not $x$
Comment: Sorry I don't understand how do you come to that result?
Answer: $$\frac{p_1 p_2}{(p_1+x) (p_2+x)}=\frac{A}{p_1+x}+\frac{B}{p_2+x}=\frac{Ap_2+Ax+Bp_1+Bx}{(p_1+x) (p_2+x)}$$
Therefore it must be
$$\frac{(Ap_2+Bp_1)+(A+B)x}{(p_1+x) (p_2+x)}=\frac{(p_1 p_2)+0\cdot x}{(p_1+x) (p_2+x)}$$
this means
$$
\begin{cases}
Ap_2+Bp_1=p_1p_2\\
A+B=0\\
\end{cases}
$$
$$
\begin{cases}
Ap_2-Ap_1=p_1p_2\to A(p_2-p_1)=p_1p_2\\
B=-A\\
\end{cases}
$$
$$
\begin{cases}
A=\frac{p_1p_2}{p_2-p_1}\\
B=-\frac{p_1p_2}{p_2-p_1}\\
\end{cases}
$$
therefore
$$\frac{p_1 p_2}{(p_1+x) (p_2+x)}=\frac{p_1p_2}{p_2-p_1}\left(\frac{1}{p_1+x}-\frac{1}{p_2+x}\right)$$
Inverse Laplace transform is
$$\frac{p_1p_2}{p_2-p_1} \left(e^{-p_1 t}-e^{-p_2 t}\right)$$
Comment: @Dovendyr I added a few lines. Hope it is clearer
Comment: Hi again, I see now that $A + B =0$ but why $2−1 = 12$ on line 4 of your explanation?
Comment: Dear @Raffaele, thank you for your precisions! I get it now, very clear!
Comment: The reply seems to be =
1 + p2/(p1-p2) * e^(-p1x)  - p1/(p1-p2) * e^(-p2x)

Why is that?
Comment: @Dovendyr You can keep out the constant $\frac{p_1p_2}{p_2-p_1}$. Then look on the tables. Inverse of $\frac{1}{p_1+x}$ is $e^{-p_1t}$ and inverse of $\frac{1}{p_2+x}$ is $e^{-p_2t}$.
Comment: @Dovendyr the answer in your book says that?
Comment: Yes, I will edit my question with a picture of the answer.
Where is the 1 coming from?
Comment: @Dovendyr I don't know. It is wrong. Taking Laplace transform of the answer I get $$\frac{\text{p1} \text{p2}}{s (\text{p1}+s) (\text{p2}+s)}$$ which is not what we started from. They made a mistake. You know, I use *Mathematica* to compute this stuff and I am quite sure that my result is correct.
Comment: No, indeed. I added a picture now!
Comment: Hmm the denominators are different, did they do some algebraic transformation there that I do not see?
Comment: Dear @Raffaele, you were right! And the error is on me, the exercise was not about a Laplace transform (even if it was a big part of it) but about a step response, which consist in multipliying 2 functions, one of them being 1/s. So what you found 3 comments above is absolutely correct. Thank you again for helping me.


What chord is Dm7 with a Bb?

Question: If I have a Dm7 chord played on the 5th fret of a guitar as a barre chord and move my pinky to play the Bb note next to the A on the 4th string I have the notes
D Bb C F A
so basically a Dm7 with an added Bb. Can someone please tell me the name of this chord? Does it change to a Bb chord of some kind?
EDIT: The chord in question will move as a ii chord in C major to F major and work as a pivot chord.
Comment: As @LaurencePayne's answer indicates, the chord name depends on its context. Very helpful if you would update your question to reflect what comes before and after, or at least how you're intended this chord to operate.
Answer: If you respell the chord in triads with the Bb at the root, you'll see it's a Bbmaj9 as you suspected.
Comment: So, Bbmaj9/D... 1st inversion.
Answer: It's a good idea to try to find a basic triad amongst any group of notes in a chord. Here, the three are B♭, D and F. O.k. F A C could also have been in the frame, but let's continue with not only 1,3,5, but 7 and 9 as well.Basic triad makes B♭ major. Adding the A makes it B♭maj7, and then the C makes it B♭maj9.
Putting it all together, it's called B♭maj9/D, as the lowest note is D. That makes it 1st inversion of said chord.
Upon more thought - D F and A are also making a D minor triad. So this could be the basis for an extended chord. That leaves C and B♭. Adding C into the mix makes it Dm7. Leaving just B♭.Not particularly fitting, as it's ♭6 of D minor. but put into the mix, with the D bass, it becomes Dm7♭13. That leaves out the 9th and 11th of the chord, which often happens with 13th chords.
Comment: Wouldn't it have to be in the higher octave to be a b13 or does it not mater? Im my voicing it is the second note after the bass note? I always thought it would have to be higher up.
Comment: As long as it's not next to the A, where it would sound dissonant, it's o.k. We must  have a little leeway, otherwise we'd end up with even more complex names.
Answer: You could certainly parse those notes as B♭maj9/D.    It may or may not be useful to do so, in context of what comes before and after.  Where does that B♭ note lead to?  Does D still feel like the root of the chord?    A Dm chord with both 5 and +5 might not make much harmonic sense, but it could make melodic sense.
Dm, (your chord), F is lovely if you root the progression D, C, F.   Then it would be harmonically useful to call it C-something   (but practically probably more useful to label it B♭major7/C).
Comment: I wanted to modulate from C major to F major via the ii chord Dm in C major without making too much of an obvious shift like using a secondary dominant or pivot chord. The progression would go from Dm in C major to this Bbmaj9 chord to F major but in the hope that F major is the new key center. I like the sound of this chord because it has the note that differentiates C major and F major (Bb)
Comment: Yes.  I've expanded my answer.
Answer: Since you're in the key of C, the presence of Bb in the chord prevents its ("formal") interpretation as a ii chord -- which is to say, as a chord in the key of C. It would be C9sus4: the dominant chord in F. Alternatively, it could be looked at as a Bb9 chord, also in F. The interpretation would depend on how the chord sounds in context.
Either way, the chord represents a direct modulation. To be considered a pivot chord it must be common to both keys.

What chord is Dm7 with a Bb?


Define a linear operator which has as Kernel the line $y=-x$ and as image the line $y=$x

Question: So the question asks basically to determine a linear operator $F: \mathcal{R}^2 \rightarrow \mathcal{R}^2$ which has as Kernel the line $y=-x$ and as image the line $y=x$.
Here is what i tried: i supposed i could write the operator in the form $F(x,y)=(ax+by,cx+dy)$. Thus
$Ker(F)$={$(x,y) \in \mathcal{R}^2 : (ax+by,cx+dy)=(0,0)$}
and i defined a=b=1 and c=d=0, so that i would have
$Ker(F)$={$(x,y) \in \mathcal{R}^2 : (x+y)=(0,0)$}
and the solution is x=-y if i'm not wrong. But for the image with these same guesses i got
$Im(F)$={$(x+y,0) : (x,y) \in \mathcal{R}^2$}
={$(x+y)(1,0) : (x,y) \in \mathcal{R}^2$}
But idk if i can conclude that the image is y=x. I don't have arguments to support it or i'm just wrong in my trial. Any help would be great, thank you
Comment: Your map is $F(x,y)=(x+y,0)$?   But then the image is the $x-$axis (note that the $y-$coordinate is always $0$).
Comment: Hint: if the image is $y=x$ then you need $ax+by=cx+dy$.
Answer: Let $f: \mathbb{R}^{2} \to \mathbb{R}^{2}$ such that if $(x,y) \in \mathbb{R}^{2}$ so $\ker(f)=\text{ span}\{(-1,1)\}$ and $\text{im}(f)=\text{ span}\{(1,1)\}$.
Then we need a linear transformation such that
$$f(-1,1)=(0,0)$$ and $$f(0,1)=(1,1)$$
Note that a basis for $\mathbb{R}^{2}$ is $\beta_{\mathbb{R}^{2}}=\{(-1,1),(0,1)\}$.
Also by rank-nullity theorem:$$\dim(\text{im}(f))+\dim(\ker(f))=1+1=\dim(\mathbb{R}^{2})=2$$
Now, let $$(x,y)=\alpha_{1}(-1,1)+\alpha_{2}(0,1) \quad \implies \alpha_{1}=-x, \quad \wedge \quad \alpha_{2}=x+y$$
so $$f(x,y)=-xf(-1,1)+(x+y)f(0,1) \quad \implies \quad f(x,y)=(x+y,x+y)$$
Finally, you can see that $\ker(f)=\text{ span}\{(-1,1)\}$ and $\text{im}(f)=\text{ span}\{(1,1)\}$.
Answer: Let's figure out the matrix for $T$.
First, the column space of $T$ is a one-dimensional space spanned by
$$v = \begin{bmatrix} 1 \\ -1 \end{bmatrix}.$$ So the columns of $T$ must be scalar multiples of $v$:
$$ T = \left[\begin{array}{c|c} c_1v & c_2v \end{array}\right].$$
(Here $c_1$ and $c_2$ are scalars that cannot both be zero.)
Second, the nullspace of $T$ is spanned by $$w = \begin{bmatrix}1 \\ 1\end{bmatrix}.$$
Multiplying, we have
$$ Tw = \left[\begin{array}{c|c} c_1v & c_2v \end{array}\right]\begin{bmatrix} 1 \\ 1\end{bmatrix} = c_1w + c_2w = \begin{bmatrix} 0 \\ 0\end{bmatrix}$$
which implies that $c_1 = -c_2$.
Putting these together, the linear transformation given by
$$
T = \left[\begin{array}{c|c} cv & -cv \end{array}\right] = c\begin{bmatrix}1 & -1 \\ -1 & 1 \end{bmatrix}
$$
for any nonzero $c$ satisfies the requirements.


Como ler o seguinte código em python?

Question: Encontrei um código em Python, mas não estou conseguindo entender como ele funciona.
from itertools import permutations

n = 8
cols = range(n)
contador = 0

for vec in permutations(cols):
    if n == len(set(vec[i]+i for i in cols)) == len(set(vec[i]-i for i in cols)):
        print ( vec )

Até o for eu entendi, mas na parte do if me perdi.
Answer: A primeira parte do if:
len(                           ) #1
    set(                       ) #2
        vec[i]+i for i in cols   #3

A linha 3 cria um iterador que retorna o valor da posição i no vec mais o valor da posição i em cols.
A linha 2 converte a linha 3 em um set, onde não há valores repetidos.
A linha 1 pega o comprimento.
A segunda parte segue a mesma lógica, apenas mudando de soma para subtração, e no fim compara os dois.
vec[i]+i for i in cols
Esta linha funciona como uma compreensão de lista, com a diferença que quando não se usa chaves ([]) ele cria um iterador.
Um exemplo simples de criar uma lista com compreensão é:
lista = [x for x in range(10)]

Que substitui:
lista = []
for x in range(10):
    lista.append(x)

No caso do código da dúvida ele está passando duas listas já existentes para criar uma terceira, o código for alternativo seria:
lista = []
for i in cols:
    lista.append(vec[i]+i)
lista = set(lista)
lista = len(lista)

Comment: Eu nunca tinha visto essa forma (vec[i]+i for i in cols) de se fazer um for. Ainda está meio obscuro como devo interpretar isso, mesmo com a sua explicação.
Poderia ser mais detalhista? Obrigado
Comment: ola, editei minha resposta, espero que faça sentido

Como ler o seguinte código em python?


Endomorphism ring of a vector space

Question: I have proof of this but not getting please help me.
If $End_{K}(V)$ is a simple ring then $V$ is finite dimensional vector space.
proof:- Let us assume that $V$ be not a finite dimensional vector space over field $K$.
Define
$I=\{f \in End_{K}(V)\mid\dim_{K}f(V)<\infty\}$
$0 \in I$ and $1\notin I$
$(0)\subseteq I \neq End_{K}(V)$
Now to show that I is both sided ideal we get contradiction.
i am not getting it from my text book
Answer: Only the basic verification stands between you and the answer:
If the image of $f$ and $g$ are finite dimensional, show that the images of $-f$ and $f+g$ are finite dimensional also.
For any $h\in End_K(V)$, give a reason why $fh$ has finite dimensional image.
Finally, why should the image of $hf$ be finite dimensional?
Comment: How we can prove if $V$ is finite dimensional then $End(V)$ is simple ring ?
Comment: @user197636 You can show it's isomorphic to the full ring of square matrices $M_n(F)$ for some $n$, and then it's simple [for this reason.](http://math.stackexchange.com/q/654451/29335)
Comment: 's thanks alot now i will try this.

Endomorphism ring of a vector space


How to pass an instance variable from a class to another in odoo

Question: from odoo import api, models, fields, tools
from odoo.tools.misc import formatLang
class SaleOrder(models.Model):
_inherit = 'sale.order'
commission = fields.Float(compute='_compute_commission')
@api.depends('user_id.commission')
def _compute_commission(self):
    for order in self:
        order.commission = order.user_id.commission

class AccountTaxGroup(models.Model):
_inherit = 'account.tax'
def _prepare_tax_totals(self, base_lines, currency, tax_lines=None):
    res = super()._prepare_tax_totals(base_lines, currency, tax_lines=tax_lines)
    commission_amount = 1900  # Calculate the commission amount here
    res['amount_untaxed'] -= commission_amount
    res['amount_total'] -= commission_amount
    res['formatted_amount_total'] = formatLang(self.env, res['amount_total'], currency_obj=currency)
    print(self.user_id.commission)
    return res

I want to access value of "commission" declared on "class SaleOrder" inside the "class AccountTaxGroup".
How to do it?
Answer: for that, you need to open a field of order_id so that odoo can know from which record of 'sale.order' you want to take the value of the commission.
class AccountTaxGroup(models.Model):
    _inherit = 'account.tax'

    order_id = fields.Many2one('sale.order', string='Sale Order')

    def _prepare_tax_totals(self, base_lines, currency, tax_lines=None):
        res = super()._prepare_tax_totals(base_lines, currency, tax_lines=tax_lines)
        commission_amount = 1900  # Calculate the commission amount here
        res['amount_untaxed'] -= commission_amount
        res['amount_total'] -= commission_amount
        res['formatted_amount_total'] = formatLang(self.env,
        res['amount_total'], currency_obj=currency)
        print(self.user_id.commission)
        sale_order_commission = self.order_id.commission
        print('########', sale_order_commission)
        return res

Comment: Thank You. I solved it in another way. Thank you for reply.


Prevent Apache2 from executing CGI in Static Directory

Question: I am running an Apache 2 web server running on Ubuntu 20.04 LTS. I have a Python CGI handler enabled for the /var/www/html directory, which is the DocumentRoot. I am wondering how to exclude a certain directory from running CGI for Python files.
Here in my CGI config:
<Directory "/var/www/html">
    Options +ExecCGI
    AddHandler cgi-script .py
        <IfModule mod_rewrite.c>
                RewriteEngine On
                RewriteCond %{REQUEST_FILENAME} !-d
                RewriteCond %{REQUEST_FILENAME}\.py -f
                RewriteRule ^(.*)$ $1.py
        </IfModule>
</Directory>

<Directory "/var/www/html/static/cdn">
        DirectoryIndex disabled
        Options +Indexes -ExecCGI
        AllowOverride None
        Require all granted
</Directory>

In the /static/cdn directory, I want .py files to be served just like any other static file, instead of being executed as CGI. Here is a tree of the cdn directory:
.
├── checkForUpdates.exe
├── checkForUpdates.py
└── findLogErrors
    ├── botCriteria.json
    ├── cleanup.json
    ├── findLogErrors.exe
    └── version.json

1 directory, 6 files

I am able to see the indexes of the directory in the web browser, as desired. I am able to view or download any file from this directory except checkForUpdates.py. The server is not trying to execute it as CGI, it's giving a 403. The permissions on checkForUpdates.py are the same as the other files:
nbroyles@webserver:/var/www/html/static/cdn$ ls -altr
total 15548
-rwxrwxr-x 1 www-data web 15901526 Nov 17 11:37 checkForUpdates.exe
drwxrwxr-x 7 www-data web     4096 Nov 19 11:13 ..
drwxrwxr-x 2 www-data web     4096 Dec 23 09:41 findLogErrors
drwxrwxr-x 3 www-data web     4096 Dec 23 09:49 .
-rwxrwxr-x 1 www-data web     2072 Dec 23 09:49 checkForUpdates.py

How can I view the .py file just like any of the .json or .exe files? I'm sure there's something simple I'm missing in my config. Any help is greatly appreciated!
Answer: You need to add SetHandler default-handler in <Directory "/var/www/html/static/cdn">
Comment: That works to display the Python file, but now the indexes are not showing.
Comment: Then chage it to `SetHandler default-handler .py`
Comment: `apachectl configtest` shows `SetHandler takes one argument, a handler name that overrides any other configured handler`, but I changed it to `AddHandler` and it's all good. Thank you!


100% packets dropped on first RX queue on 3/5 raid6 iSCSI NAS devices using intel igb (resolved)

Question: Edit : The issue is resolved. The Queues in question have been used for Flow Control Packets. Why the igb driver propagated FC packets up to have them dropped (and counted) is another question. But the solution is, that there is nothing dropped in a way that data got lost.
Thank you very much, syneticon-dj, your pointer to dropwatchwas gold!
=== original question for further reference ===
we have the following situation:
System:
The server in question is a dell poweredge with 4 quad-core xenon cpus, 128GB ECC RAM and is running debian linux. The kernel is 3.2.26.
The interfaces in question are special iSCSI cards with four interfaces each using Intel 82576 Gigabit Ethernet Controller.
Background: On one of our servers a lot NAS (Thecus N5200 and Thecus XXX) are connected using iSCSI on dedicated 1GB/s interfaces. We have 5 cards with 4 ports each. The NAS filers are connected directly, no switch in between.
Two weeks ago we managed to clear four NAS filers and used them to build a raid6 using mdadm on them. Using LVM this allows us to dynamically create, shrink and/or grow storage for our various projects instead of searching all our NAS filers for free space every now and so often.
However, we got a lot of overruns on pretty much every interface and a lot packets got dropped. Investigations showed, that the default settings for the networking stack(s) had to be increased. I used sysctl to tweak all settings until no more overruns occurred.
Unfortunately the interfaces that are used for the NAS raid still drop a lot of packets, but only RX.
After searching (here, google, metager, intel, anywhere, everywhere) we found information about the intel igb drivers to have some problems and that some work has to be done.
Thus I downloaded the latest version (igb-4.2.16), compiled the module with LRO and separate queues support, and installed the new module.
All 20 (!) interfaces using this driver now have 8 RxTx queues (unpaired) and have LRO enabled. The concrete options line is:
options igb InterruptThrottleRate=1 RSS=0 QueuePairs=0 LRO=1

irqbalancer is nicely distributing the queues of all interfaces and everything works splendid.
So why am I writing? We have the following odd situation and simply can not explain it:
Three of the five interfaces for the NAS raid (We have added one spare NAS, and the raid should be grown once mdadm has finished its current reshape) show a massive amount (millions!) of packet drops.
Investigations with ethtool now show, thanks to the new multiple-queue-enabled drivers, that each interfaces uses one queue massively, this will be the reshape we guess.
But three use another queue with millions of incomming packets, which all get dropped. At least showed investigations utilizing 'watch', that the packet numbers on these queues correlate with the dropped packages.
We changed the MTU on the NAS and interfaces from 9000 down to 1500, but the packet drop rate increased and the mdadm performance went down. Thus it does not look like an MTU problem. Further the network stack has insane amounts of memory to its disposal, this shouldn't be a problem either. backlogs are large enough (huge in fact) and we are completely at sea.
Have example output here:
~ # for nr in 2 3 4 5 9 ; do eth="eth1${nr}" ; echo " ==== $eth ==== " ; ethtool -S $eth | \
> grep rx_queue_._packet | grep -v " 0" ; ifconfig $eth | grep RX | grep dropped ; \
> echo "--------------" ; done
==== eth12 ====
    rx_queue_0_packets: 114398096
    rx_queue_2_packets: 189529879
          RX packets:303928333 errors:0 dropped:114398375 overruns:0 frame:0
--------------
==== eth13 ====
    rx_queue_0_packets: 103341085
    rx_queue_1_packets: 163657597
    rx_queue_5_packets: 52
          RX packets:266998983 errors:0 dropped:103341256 overruns:0 frame:0
--------------
==== eth14 ====
    rx_queue_0_packets: 106369905
    rx_queue_4_packets: 164375748
          RX packets:270745915 errors:0 dropped:106369904 overruns:0 frame:0
--------------
==== eth15 ====
    rx_queue_0_packets: 161710572
    rx_queue_1_packets: 10
    rx_queue_2_packets: 10
    rx_queue_3_packets: 23
    rx_queue_4_packets: 10
    rx_queue_5_packets: 9
    rx_queue_6_packets: 81
    rx_queue_7_packets: 15
          RX packets:161710730 errors:0 dropped:4504 overruns:0 frame:0
--------------
==== eth19 ====
    rx_queue_0_packets: 1
    rx_queue_4_packets: 3687
    rx_queue_7_packets: 32
          RX packets:3720 errors:0 dropped:0 overruns:0 frame:0
--------------

The new spare drive is attached to eth15.
As you can see, there are no overruns and no errors. And the adapters report, that they did not drop a single packet. Thus it is the kernel throwing data away. But why?
edit: I forgot to mention that eth12 to eth15 are all located on the same card. eth19 on another.
Does anybody have ever witnessed such strange behaviour, and was there a solution to remedy the situation?
And even if not, does anybody know a method with which we could at least find out which process occupies the dropping queues?
Thank you very much in advance!
Comment: This is a terrible setup. But an interesting technical question.
Comment: What exactly is terrible? I have found plenty of howtos and tutorial on setting up NAS RAID using iSCSI. At least it does not seem to be this uncommon, does it?
Comment: This is definitely an uncommon setup. You'd be better served by building/buying an appropriately-sized storage unit with the right types of disks/interconnects and capacity.
Comment: @Yamakuzure what's uncommon is your use of numerous interfaces and direct connections instead of (redundant) switches. Also, using "dumb" storage devices to provide storage space via iSCSI to build an md array is surely technically possible, but typically an approach involving an "intelligent" storage providing resilience and sufficient space under a unified management interface would be preferred. I see how you are trying to create a low-cost SAN, but you likely are maneuvering yourself into more trouble than you can imagine.
Comment: @ewwhite: Unfortunately an "appropriately-sized storage unit" that can replace 23 5.2TB NAS does not exist imho. However, we have those filers now and simply want to consolidate them.
Comment: @syneticon-dj We have already discussed the change to redundant switches. The question is, whether the performance impact is acceptable when lowering the amount of 1GB lines drastically. Could you please explain what you mean with "dumb storage devices"? All filers are set up using RAID5, which has helped us already when a hard drive failed. Currently the set up allows us to keep on working even if one hard drive on each NAS fails and it would even keep working when two NAS fail completely. (The rebuild/reshape time is rather unholy of course.)
Comment: from what I know about the N5200, it runs a low-end old Celeron CPU and reaches sustained transfer rates of about 20 MB/s max(for reading) - you likely would not miss all that much in performance, even when running 5 of them on a single GB link. But I actually meant to advise you on running switches with 10 GB interfaces. Also, 23x5,2TB sounds like a lot at first, but if you look at 60-bay 4U JBODs like http://www.dataonstorage.com/dataon-products/6g-sas-jbod/dns-1660-4u-60-bay-6g-35inch-sassata-jbod.html, you quickly realize that this could be easily accomplished in much less rack space.
Comment: @syneticon-dj That storage looks nice, thank you for the hint!
Comment: About The N5200 performance: It can do over 50MB/s writing with concurrent ~90MB/s reading in "Overlapped I/O". [firstname.lastname@example.com](http://www.hardwaresecrets.com/article/Thecus-N5200-NAS-Review/606) - at least in lab conditions. However, it is a lot faster than 20 MB/s from my own experience. (I just rsync'd a 1.8GB file from one of the filers somewhere else, and while both the server and the NAS are anything but idle rsync reported an average of 43MB/sec. So I guess you assumption of 20MB/s are a bit low.)
Answer: You have enough interfaces to build a workgroup switch with. As this configuration is not employed as often and thus not tested as thoroughly, expect oddities coming from that alone.
Also, as your setup is quite complex, you should try isolating the issue by simplifying it. This is what I would do:

rule out the simple cases, e.g. by checking the link stats by issuing /sbin/ethtool -S <interface> to see if the drops are a link-related problem
as the NICs are making use of interrupt coalescing, increase the ring buffer and see if it helps matters
use dropwatch to get a better idea if any other buffers could be increased
disable multiqueue networking again - with 20 active interfaces there hardly will be a situation where multiple queues per interface would gain any performance and from your description it might be a queuing-related problem
reduce the number of interfaces and see if the problem persists
if nothing else helps, post a question to the Kernel netdev mailing list
Comment: Thanks. I wasn't aware of `dropwatch.`
Comment: To 1: We have observed the link stat by using `watch`on ethtool. Everything is stable. 2: `watch -g` did not show anything suspicious. But I'll keep that in mind and will try what happens after enlarging the ring buffer. 3: I'll give `dropwatch`a try, thank you very much for that idea! 4: Well, we had the drop rates with single-queues, too. 5: Well, almost all interfaces are currently used (and needed!) only two are spare. 6: I bet your ideas 2 and 3 will bring me towards finding a solution. (I dodn't know `dropwatch`either!) If not I'll try that. Thank you very much!
Comment: The issue is solved! The dropped packets are simply rx_flow_control_xon and xoff packets. Three of the filers simply aren't fast enough. And that is the reason why the "drop rate" went up when we lowered MTU down to 1500. Flow control works as intended. Why the driver let's the FC packets move up so they get dropped (and counted) is a riddle for me, but at least there is nothing bad happening. ("dropwatch" was what gave the final clue)
Comment: @Yamakuzure glad it could be resolved. The only thing that puzzles me is that Ethernet does not have a notion of XON and XOFF for flow control - it just uses PAUSE frames which are destined for a multicast address. It might be though that the internal Kernel structures mimic XON/XOFF behavior for compatibility with other transmission protocols. As the PAUSE frames are addressed to a valid multicast destination, it does not seem wrong to see them counted. As the destination address is not owned by the interface, it does not seem wrong to see them dropped, although I can see how it is confusing.
Comment: @Yamakuzure BTW: I *told* you the N5200 were dog-slow ;)


Google Maps V2 showing blank screen on 4.4 with google logo showing in bottom left

Question: I'm going absolutely crazy here, I've been through so many posts, and nothing seems to be working. My device is definitely connection to play service as I've checked that, and my key is showing my application when I look under my api credentials. For some unknown reason to me, I can't seem to get it to display the map, just the blank screen, and I've spent a good 3 hours on it with no luck. Any help as to why I can't get the map to show would be hugely appreciated! I've even tried regenerating the keys with no luck.
AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.*****.****" >

<permission
    android:name="com.*****.****.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.*****.****.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="********-***********"/>

</application>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<fragment
    android:id="@+id/mapView"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java
package com.zoome.natalie.zoo;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

public class MainActivity extends Activity {

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleMap googleMap;
// tag used on log messages.
static final String TAG = "HelloGooglePlayServices";

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

@Override
protected void onResume() {
    //auto-generated method stub
    super.onResume();

    // You need to do the Play Services APK check here too.
    checkPlayServices();

}

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.i(TAG, "Device not supported.");
            finish();
        }
        return false;
    }
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void createMap() {
    try {
        if (null == googleMap) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.mapView)).getMap();

            /**
             * If the map is still null after attempted initialisation,
             * show an error to the user
             */
            if (null == googleMap) {
                Toast.makeText(getApplicationContext(),
                        "Error creating map", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (NullPointerException exception) {
        Log.e("mapApp", exception.toString());
    }
}
}

And in case it's useful the build.gradle module
apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.zoome.natalie.zoo"
    minSdkVersion 15
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'

compile 'com.google.android.gms:play-services-maps:6.5.87'
}

The debugging key is what I am most unsure of, but I think it's right, any help of what to try or where I've made a mistake would be so greatly appreciated. Thanks.
Comment: API was generated from Google Dev Console...
Comment: Is your api key value a reference from a strings.xml file ?I mean in your manifest  where you have   is it hardcoded ?
Comment: Yes, what I ask is if you have that value in a strings.xml file or you just typed it to the manifest? If it's in an strings.xml file did you check if you added the value for both debug and release version of you app ?
Comment: It seems you need to use `Google Maps V2` api, and use it to your app. Just try to following [this](https://www.youtube.com/watch?v=8ADb5bNOFHE) step by step, it will help you.
Comment: @bjiang there was one step in that i missed out originally so got hopeful it'd fix it but still the same issue. Thanks though, that videos really helped me understand it better! :)
Comment: some issue as blank screen?Thats wired. what network u use? Have u tried create a new project and try the video out?
Comment: Fixed it! It seems I had conflicting things to display it but it wasn't picking up that they were conflicting.
Answer: Assuming you have SDK stuff installed (which I believe you do based on the fact that you get to the gray screen with the Google Logo) the first thing you'll want to do is create a debug and release keystore. The full documentation is here:
https://developers.google.com/maps/documentation/android/start
Here's the quick and dirty for a Mac / Linux user. In the terminal type the following:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

You should then see your SHA1 hash to be used for debug builds. Copy and paste that somewhere.
I'm not sure if you're at a point where you're trying to compile this app for a release yet, but let's go through the motions now and save you the headache down the road. In Android Studio click Build -> Generate Signed APK.
This will take you through a little walk-through process where you select the Module you want to compile and then select the key that you want to use for the module. At this point you want to click Create New
This will let you decide where you want to save your release key, make you set a password and there are a few other options you can set at that time.
Now get the SHA1 hash for your release key that by using the same keytool command as above but replacing the path to the file you just created and the password arguments for whatever you just used as your password.
Now go to
https://console.developers.google.com/project
Select your project and go to the Credentials link on the left. If you don't have one yet, make yourself a Public API Access Key for Android. If you do have one, click the Edit Allowed Android Applications button. Paste both of the SHA1 keys that you took note of earlier here and then put ';your.package.name' after each line. Now, copy an paste the API KEY somewhere.
Go back to Android Studio and find the google_maps_api.xml file in both your debug and release folders. The paths should be:
package/app/src/debug/res/values/google_maps_api.xml
package/app/src/release/res/values/google_maps_api.xml
Open each of those up and paste in a strink like this:
<string name="google_maps_key" templateMergeStrategy="preserve">API KEY</string>

Finally, go in your AndroidManifest and make it say this:
<meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key" />

Grab a beer and celebrate
Comment: Not having any luck :( Putting the string into the release maps api throws an error, and the same with the google_maps_key string
Comment: What is the error you're seeing? Can you paste the stack trace in your original post?
Comment: What was it that you had to change?
Comment: Originally I had it linking to google play twice, which appeared to be stopping it for some reason, so removed one of the lines of code declaring it and it worked.
Answer: If you see a blank screen (or with grids) on the view area of the map, Possibility is, You are using the API key for Version 1 and putting it inside your manifest. Please have a look at your developers console and look for Google Maps V2 key!!
Answer: If you see a blank screen without any grid, with a google logo on your bottom left hand-side, most probably the API key that you created is not the
appropriate one, You should not create a simple API key but one which registers your application for Google Maps Android API in Google Developers Console.The proper link drives you to the "Enable an API page", here the link
https://console.developers.google.com/flows/enableapiapiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&reusekey=true
both your manifest and layout look good to me, the MainActivity has nothing unusual....
Answer: Please create the api key properly; the link below provides the required details:
https://developers.google.com/maps/documentation/android-api/signup
Please make sure that you have enabled internet on your phone before running the app.


exchange accounts on outlook 2010 freeze randomly due to high latency

Question: One of our clients is running a windows SBS server 2011, with users in both a TS environment and local lan computer access.
This is a small environment with approximately 35 users.
The symptoms we are experiencing are as such:
individual users will experience outlook not responding for approximately 5-10 minutes at a time, at roughly the same time every day, as well as random times.
This happens to both TS and local users.
There isn't usually overlap between users, ie, different users will experience the issue at different times, whilst others continue to work without incident.
What we have observed:

Store.exe on the Server running exchange has constantly high disk access. varying between 5-10MB/s read access, with between 1-5MB/s write access (according to resource monitor). This remains constant regardless of people experiencing lockout. This activity dissapears at night time when no one is accessing the system.
During the users lockout of outlook, Exmon will report very high  avg server latency for the specific user in question, (60 seconds latency is average during this time, normally sitting between 0 and 500 msec). Other unaffected users do not have high latency
during lockout, the users in question will have a high session count

Additional notes:

Event log doesn't appear to report anything related
There is nothing scheduled on the exchange server during the times people experience the lockout
all windows updates and service packs have been applied to both servers and to office.
when locked out, you cannot even open the mail control panel item for the exchange settings page for the specific user

Server Spec:

dual cpu xeon email@example.com
24GB Memory
SAS 15K (seagate Cheetah) - 300gb pair in raid 1

We are at a loss as to what is causing the issue at this stage.
Any suggestions or direction would be greatly appreciated.
Comment: Your units are wrong and it makes a difference. Is it Mb or MB? mb isn't a unit of measure that is used in our field. What is the hardware config of the exchange server? Specifically disk layout and rotational speed?
Comment: Apologies, fixed that up and added specs
(it's MB/s)
Answer:
It's not TCP connection exhaustion.
Use Perfmon to log and check your key server metrics.  I'd start with disk, as I'm fairly confident the issue is that you have a very long disk queue length.
Check your hardware, both to make sure it hasn't gone bad and so you can get an idea of what performance you should be capable of.

The last time I saw this happen (5-10 minute, sporadic freezes for certain users), the issue was bad blocks on one of the server's disks.
The time before last that I saw this it was massive disk queue due to users opening >10 GB .pst files over a network share.
Having a disk configuration that does not support the level of IOPS your users are throwing at the server can also cause this type of behavior in use-cases similar to yours.
Answer: Looks like the issue was caused by their antivirus.
There is a configuration in the MSExchangeIS service that enables background virus scanning.
With this enabled the antivirus was re-scanning the entire 120gb mail database 3 times a day.
Every time the virus definitions were updated it would trigger a new scan.
In doing so it was locking mailboxes as it scanned through.
If anyone else has an issue like this, check the following registry key
HKLM\system\currentcontrolset\services\MSExchangeIS\VirusScan\BackgroundScanning
set this to 0
Comment: Which AV was this?
Comment: AVG internet security business edition


Generating short, random and unique string on Appengine

Question: I want to generate string ids which have following properties:

short, up to 5-6 apha + numbers
random
unique, desired, but not so important as first too

Currently I am thinking about:

allocate unique id with https://developers.google.com/appengine/docs/python/datastore/functions#allocate_ids
hash it with some secret key, md5(id + secret)
take first 5 symbols

Is there a better way? I thought also about using datacenter_id + instance_id + request_id , but I have no idea if it will be better.
Comment: Is an UUID toooo long for you? :) [LINK](http://docs.python.org/2/library/uuid.html)
Comment: I currently use UUID, but want to add short URLs for guys who are using app from smartphones.
Answer: Why not just generate a random string using random.choise?
<code>for _ in xrange(5):
  yield random.choice(digits + alpha)
</code>
This has a space of 36^5 keys
Comment: I thought that hash of unique number will be more unique. I still think so, but I know nothing about cryptography.
Comment: You might also want to look at using Base32 for your alphabet, it works very nicely for URLs, filenames etc. A Base32 encoded integer will give you a string 1 - 7 characters long if you don't care about fixed length.


How to have nginx serve only the home page of site?

Question: I am running a server with nginx on port 80 and Apache on 8080. I want the home page of my site to be served with nginx, and every other request passed through to Apache. I found this great article and understand the nginx proxy_pass directive, but I can't figure out the right regex to tell nginx to only serve the home page of my site. Since users will come to the site by just visiting http://mysite.com (without /index.htm), I don't know what "location" value I should use.
Here's an example config file that demonstrates how to have all pages sent to Apache (like I want) except the /css folder, and image files. As you can see nginx uses a simple regex to specify what should be served by nginx. What regex would I use to specify only the home page should be served by nginx? Or should I be using try_files somehow?
server {
      root /usr/local/www/mydomain.com;
      server_name mydomain.com www.mydomain.com;

      # next line says anything that matches this regex should be sent to Apache
      location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            # Apache is listening on port 8080
            proxy_pass http://127.0.0.1:8080;
      }

      # Example 1 - Specify a folder and its contents
      # To serve everything under /css from nginx only
      location /css { }

      # Example 2 - Specify a RegEx pattern such as file extensions
      # to serve only image files directly from Nginx
      location ~* ^.+\.(jpg|jpeg|gif|png)$
      {
            # this will match any file of the above extensions
      }
}

Comment: Is this a contrived example or something? It doesn't seem likely that you only want to serve the home page from nginx. The usual configuration is to serve any static files, and pass everything else upstream. What are you really trying to do?
Comment: Honest, this is a real thing. The URL is going to be blasted on TV screens across America and gets a huge traffic spike, but everyone is looking for something that will be right on the home page. The rest of the site needs to be available and running, but while the TV program is on, I have a special lean home page with the thing that 99% of folks are looking for.... so they'll see what they want (on the one single nginx-served home page) and leave, and the other 1% off folks can click off from there and use the rest of the site (served by Apache through nginx reverse proxy).
Comment: Hmm, so you make the home page a static file for the duration. Takes five seconds, and doesn't require any bizarre configurations.
Comment: But the problem is a jillion people come to the site and even with the special lean (static) home page, Apache gets buried quickly. That's why I want nginx to serve it.
Answer: OK, so what you really need to be doing is:

Serve all static files from nginx, and only pass upstream to Apache any other requests.
When necessary for performance reasons, make the homepage a static file such as index.html in the document root. Thus, nginx will serve it directly. Delete it to return to the previous behavior.

Your configuration should look something like this:
server {
      root /usr/local/www/mydomain.com;
      server_name mydomain.com www.mydomain.com;

      index index.html;

      location @upstream {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            # Apache is listening on port 8080
            proxy_pass http://127.0.0.1:8080;
      }

      location / {
            try_files $uri $uri/ @upstream;
      }
}

Later you should look at doing caching within your web app; if it writes generated HTML files to the disk, you could then have nginx serve those files directly out of its cache.
Comment: http://codex.wordpress.org/Nginx
Comment: This seems like it should work, but my site is powered by Wordpress and it's just failing left and right-- nginx won't let me access any subdirectories, and PHP code from a WP plugin is being shown mixed in the HTML code (which obviously screws up the page). I'm guessing all this is because WP routes pages strangely, or something along those lines.
Comment: In that case, why are you using Apache at all?
Comment: Because Wordpress likes Apache and its .htaccess file... and the caching plugin I'm using does a lot to the .htaccess file as well. And I'm inheriting the whole project and not looking to rework it all :-) Good news is, I found a solution: I moved Apache up to port 8080 and kept nginx on port 80. Nginx never really serves any Apache pages; once someone clicks on the home page, I add :8080 to the URL and they're handled by Apache. Works perfectly for my needs.
Comment: Thanks for the link-- I hadn't seen that before. In browsing that page, I think it definitely shows how much Apache wants to work with .htaccess, and what a pain in the ass it is to get Wordpress (and whatever plug-ins you're using) going with nginx. That's a lot of by-hand customization. I kinda like my dual-port trick ;-) ...in all seriousness, it does the job for the two hours that the URL is broadcast on the air. The rest of the time I just run the site as a normal Apache setup since the traffic isn't spiking. Thanks for all your help and good information.
Comment: Setting it up once, means you don't have to worry about the server whenever you run a new TV campaign. It's just always ready to handle whatever you throw at it.
Comment: Agreed. For my particular case, this is the last time that it will be necessary to deal with this, as the entire site is transitioning to a new platform (which I'm not a part of) that will easily handle the traffic spikes. Thus my need to post this question and find a solution that would work without me needing to spend time rejiggering the entire server structure. Nginx fit the bill perfectly.


Scroll bar not showing the full content in right side in HTML doc

Question: I plan to create a horizontal scroll bar. One div element wraps all contents.The problem is when user scrolls, it is not fully scrolled until end of the right. So I am not able to see the content at end. I need a help to fix it.
CSS
.fr {
    width: 100%;
    align-items: center;
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
    overflow-x: auto;
    background: pink;
    padding: 20px;
}

.c1 {
    position: relative;
    flex: 0 0 auto;
    width: 300px;
    height: 400px;
    box-shadow: 0 0 18px 0 rgba(0, 0, 0, 0.3), 0 0 9px 0 rgba(0, 0, 0, 0.19);
    padding: 20px;
    margin-right: 20px;
}

HTML

...

....

.....

...

....

.....

...

....

.....

Answer: The problem lies in your overflow-x: auto on .fr. This restricts how far across the scrollbar can go. Removing this solves the width problem, but will still have the background only go to the edge of the container. You likely want to move this to the parent element, in this case body.

body {
  background: pink;
}

.fr {
  width: 100%;
  align-items: center;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: row;
  padding: 20px;
}

.c1 {
  position: relative;
  flex: 0 0 auto;
  width: 300px;
  height: 400px;
  box-shadow: 0 0 18px 0 rgba(0, 0, 0, 0.3), 0 0 9px 0 rgba(0, 0, 0, 0.19);
  padding: 20px;
  margin-right: 20px;
}

...

....

.....

...

....

.....

...

....

.....

Answer: Add this to remove scrollbar. Or can you explain more clearly what is your problem.
.fr{
     box-sizing: border-box;
}


What kind of maths/stats questions allowed?

Question: One of the mods has asked and answered a question (edit: also this question) involving stochastic calculus. I'm not quite sure how this relates to economics or finance other than the exercise being from a mathematical finance book.
Sure the Girsanov Theorem is important in mathematical finance, but I don't think its only use is in mathematical finance. It seems to me that such question should have been instead asked in Quant SE, Maths SE or CV / Stats SE
So is it on-topic? Why/Why not? To what extent must a question involve economics or finance to be on-topic here? Are all Brownian-motion related questions on-topic here even if the question is about the mathematical details?

From Physics SE (jamals):

Questions devoid of any physics content (or reference to physics), which focus entirely on mathematical details should be migrated to the mathematics SE. If the question is regarding a mathematical method applied to a physics problem, then it is appropriate for the physics SE.
Answer: This is a difficult question—which is why the physicists have wrestled with it so much. I would tend to be inclusive because it would be better to have overlap between two SE sites than to have gaps where good questions can't find an appropriate home.
I think an important factor should be whether economists are likely to give an answer with some additional nuance that will help the reader with the application of the technique to economics.
For example, suppose someone was interested in Langrangian methods for optimisation. For sure, the people at math.SE could answer such questions. But it is likely that economists have a better ideas how such methods fit into the typical curriculum or what the typical application is likely to look like. This might mean that economists get more useful answers to their constrained optimisation questions here.

Whatever is decided, the community should try to converge on an agreed set of guidelines because the worst thing would be to arbitrarily allow some questions and refuse others.
Answer: I agree with Ubiquitous that it is better to have overlap between SE sites than gaps. A further point in favour of inclusiveness is that the rates of unanswered questions of these types, as of just now, is lower on this site than on Mathematics or Cross Validated SE:
Unanswered Q's tagged Mathematical Economics on Economics SE:  18% (21 / 118)
Unanswered Q's tagged Economics on Mathematics SE:  31% (187 / 602)
Unanswered Q's tagged Econometrics on Economics SE:  28% (47 / 166)
Unanswered Q's tagged Econometrics on Cross Validated SE:  37% (306 / 825)
Having said that, where a question of this type does not receive an answer (or any answer appears to be low-quality) and noting that cross-posting is generally discouraged, it would I suggest sometimes be appropriate to migrate the question to a site where there would be another chance for an answer.
Answer:
If the question is regarding a mathematical method applied to a
  physics problem, then it is appropriate for the physics SE.

In many cases, each discipline has its own idiosyncratic way of using/applying the same mathematical method, and so also of teaching/explaining/interpreting it. Then, even if the question is about a pure "technical" issue around a mathematical method, it has been asked here because the asker tries to apply this method in an Economics problem.
And in economics.se, it stands a better chance of receiving an answer from someone knowledgeable about how the method is applied in the Economics field, which I believe would result in a more helpful answer.