C++, How to create and draw a Binary Tree then traverse it in Pre-Order

Question: How do I create a Binary Tree and draw it using a Pre-Order Traversal strategy?  The root would be the first number going in.
I have a set of numbers: 48 32 51 54 31 24 39.  48 would be the root.  How are the child nodes pushed onto the Binary Tree in a Pre-Order traversal?
Comment: Are you trying to construct a binary tree given a pre-order traversal? Or are you trying to get the pre-order travel on a binary tree? (sorry, the question is not very clear)
Comment: what are the numbers that would result from a PRe-Order Traversal of the binary tree built using the above numberrs
Answer: Imagine the following sub-problem. You have a set of numbers:
N A1...AX B1...BY

You know that N is the root of the corresponding tree. All you need to know is what numbers form the left sub-tree. Obviously the rest of the numbers form the right sub-tree.
If you remember the properties of a binary-search trees, you would know that elements of the left sub-tree have values smaller than the root (while the ones on the right have values bigger).
Therefore, the left sub-tree is the sequence of numbers that are smaller than (or possibly equal to) N. The rest of the numbers are in the right sub-tree.
Recursively solve for
A1...AX

and
B1...BY

For example given:
10 1 5 2 9 3 1 6 4 11 15 12 19 20

You get:

root: 10
left sub-tree: 1 5 2 9 3 1 6 4
right sub-tree: 11 15 12 19 20
Comment: Ok, maybe it's just me but I can't pinpoint this. Ill give you an array of intergers: 47 43 20 24 32 44 35. So the tree would be: 47 left sub-tree: 20 24 32 right sub-tree: 44,43,35?
Comment: No, 44, 43 and 35 are all smaller than 47. This means that 47 is the root, left sub-tree contains all the 6 numbers and the right sub-tree is empty.
Answer: Say you have the following binary tree:
        A
      /    \
    B        C
   / \      / \
  D   E    F   G
     / \
    H   I

A Pre-Order Traversal goes NODE, LEFT, RIGHT.
So Pre-Order of this binary tree would be: A B D E H I C F G
For more details on how to implement this in C++:  https://stackoverflow.com/a/17658699/445131


Hibernate mapping issue

Question: very simple problem here... but I can't work it out.
I have a simple class from my model
public class Catalogazione extends ModelEntity {

private String nome;
private int showBox;

public int getShowBox() {
    return showBox;
}

public void setShowBox(int showBox) {
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}
}

Note that ModelEntity has the an id attribute defined, integer as well.
It's mapped on an oracle table with this mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="alekso.npe.model.Catalogazione" table="Catalogazione" lazy="false">
        <id name="id" column="ID">
        </id>
        <property name="nome" column="Nome" />
        <property name="showBox" column="ShowBox" type="integer"/>

    </class>
</hibernate-mapping>

Very simple.
When I retrieve the object from the DB, the showBox attribute is always 0.
This is the code for retrieving the objects list
public List<Catalogazione> getAll() throws Exception {
    List<Catalogazione> catalogazioni = new ArrayList<Catalogazione>();
    Session session = null;
    try {
        session = SessionFactoryUtil.getInstance().openSession();
        String query = "from Catalogazione as cat";
        catalogazioni = session.createQuery(query).list();
        return catalogazioni;
    } catch (Exception ex) {
        // log error
    } finally {
        session.close();
    }
}

That's it. Every instance of Catalogazioni has showBox=0, even if in db there are several values.
Can anybody tell me why? Moreover the id is equally mapped to an integer field on the db and it works fine... what am I missing?
Answer: Your setter doesn't do anything:
public void setShowBox(int showBox) {
}
^---

Hibernate mapping issue


Changing location of the image using ''

Question: I am using the below command to get the png image into my html page.
print count_out '';

I am also writing out a table to my html page. The problem is this image appears on top and then below is the table.
I need table on top and then image below.
Below is the part were i am printing the table:
print count_out "";
print count_out "";
print count_out "";
print count_out "
";
while (<F>) {
    chomp;
    my @list = split(/,/);
    my $design = $list[0];
    my $bto_date = $list[1];
    my $die_size = $list[2];
    my $technology = $list[3];
    my $transistor_count = $list[4];

print count_out "
";
print count_out "$design	";
print count_out "$bto_date	";
print count_out "$die_size	";
print count_out "$technology	";
print count_out "$transistor_count	";
print count_out "
";

Comment: There is no `` printed, i.e. the table is never closed. This might explain why the position of the image is messed up - although you don't shown where exactly this img related print statement is done in your code.
Answer: You do not close the  tag.
print count_out "
";

is missing at least.
Answer: thanks
adding the below line worked for me
print count_out "
";

also when i open the html ..i see the table but the image does not show up .. i have click the refresh 8-10 times ..then it shows up ..why is that
Comment: depending on your browser, this might just be caching. Try clearing the browser cache and then running the script.
Comment: This is not an answer instead missed out issues.

Changing location of the image using ''


How to bypass or implement IComparable

Question: I get the below error and I can't understand why and how to get past it (or implement icomparable).
I'm trying to get the property Group from the object that has the biggest count of Group using Max().
 public class Program
{
    private static void Main(string[] args) {
        var list = new List<Foo>();

        for (var i = 0; i < 10; i++) {
            list.Add(new Foo());
            if (i == 5) {
                var foo = new Foo() {
                    Group = { "One", "Two", "Three" }
                };
                list.Add(foo);
            }
        }

        var maxGroup = list.Max(x => x.Group); //throws error
    }

}

public class Foo {
    public Guid Id { get; } = new Guid();
    public int Field1 { get; set; }
    public int Field2 { get; set; }
    public int Field3 { get; set; }
    public int Field4 { get; set; }

    public List<string> Group { get; set; } = new List<string>();

}

at least one object must implement icomparable
Comment: How do you intend one `List` to be larger than another?
Answer:
I'm trying to get the property Group from the object that has the longest list

You don't want to do Max for that. Simply order by the length of the list, and take the first one:
Foo res = list.OrderByDescending(x => x.Group.Count).FirstOrDefault();
if (res != null) {
    List<string> longestList = res.Group;
}

Comment: Thank you.. Think I got little confused about all linqing =)

How to bypass or implement IComparable


c# stringbuilder vs Aggreggate?

Question: Is StringBuilder really faster than Aggreggate?

    string c = tmpArr[0].Aggregate(string.Empty, (current, m) => current + (m.Name + " "));

    StringBuilder sb = new StringBuilder();

    foreach (Mobile m in tmpArr[0])
        sb.Append(m.Name + " ");

    sb.ToString();

which of those two is faster? aggregate certainly is cleaner, but is it fast or is it the same as doing

foreach(Mobile m in tmpArr[0])
      c += m.Name + " ";

what I really would like to do is something like string.Join(",",tmpArr[0]), but I don't want it to concat their ToString values, just their Names, how would I do that best?
my problem with not using string.Join is I would actually have to do something like this:

string separator = "";
          StringBuilder sb = new StringBuilder();
    foreach (Mobile m in tmpArr[0])
    {
        separator = ", ";
        sb.Append(separator + m.Name);
    }

Comment: [If you have two horses and you want to know which of the two is the faster then race your horses. Don't write short descriptions of the horses, post them on the Internet, and ask random strangers to guess which is faster!](http://ericlippert.com/2012/12/17/performance-rant/)
Comment: ...you called out your own question for being an exact duplicate?  Why would you post the same question again, especially when the other one was answered?
Comment: Minor point: your final example is incorrect... the `separator = ", ";` should be *after* the Append, otherwise it will set before it's first use, which is not your intention
Comment: It's your code, test it yourself, using your hardware, and your data :)
Comment: string.Join(", ", tmpArr[0].Select(m=> m.Name));
Comment: OR `String.Join(", ",tmpArr[0].Select(m=>m.Name))`
Comment: What happened here? The other one seems to be worded exactly the same, with the same code, however it is two years old. miley, did you copy / paste this old question?
Comment: What is even going on here
Comment: This `sb.Append(m.Name + " ");` is wrong. You are manually composing strings (`m.Name + " "`). Do `sb.Append(m.Name); sb.Append(" ");`
Answer: Is a bad idea to multiple time add chunks to a string, because since string are immutable in .NET you obtain a lot of garbaged string in memory, and probably that dublication is more expensive in term of execution time too. Using StringBuilder, String.Concat(), or String.Join() are definitely the best way when you need to compose strings.
Answer: The cleanest way to do this is to use String.Join, because that's what it is there for:
string.Join(" ", tmpArr[0].Select(x => x.Name));

c# stringbuilder vs Aggreggate?


Trocar versão do Excel em exportação com PHP/Mysql

Question: Galera, tenho um código que exporta minha tabela do banco de dados perfeitamente, mas ele exporta isso no excel 97 (2003), alguém sabe alguma maneira de exportar essa tabela em outra versão do excel e o arquivo em xlsx em vez de xls? OBS: ja tentei trocar a extensao do arquivo para xlsx e dá erro na hora de abrir o arquivo.
Codigo:
<?php
include('conexao.php');
error_reporting(0);

 $tabela = '
';
 $tabela .= '
';
 $tabela .= 'Codigo Prova	';
 $tabela .= 'Nome	';
 $tabela .= 'Supervisor	';
 $tabela .= 'Local	';
 $tabela .= 'Data	';
 $tabela .= 'Questao 1	';
 $tabela .= 'Questao 2	';
 $tabela .= 'Questao 3	';
 $tabela .= 'Questao 4	';
 $tabela .= 'Questao 5	';
 $tabela .= 'Questao 6	';
 $tabela .= 'Questao 7	';
 $tabela .= 'Questao 8	';
 $tabela .= 'Questao 9	';
 $tabela .= 'Questao 10	';
 $tabela .= 'Aprovado ou Reprovado	';
 $tabela .= 'Prova	';
 $tabela .= 'Numero Acertos	';
 $tabela .= 'Numero Erros	';
 $tabela .= '
';

$result                 = "SELECT * FROM provas";
$result_busca           = mysqli_query($conn, $result);
$contar                 = mysqli_num_rows($row_busca);

while($row_busca = mysqli_fetch_array($result_busca)){
    $tabela .= '
';
    $tabela .= ''.$row_busca['cd_prova'].'	';
    $tabela .= ''.$row_busca['nome'].'	';
    $tabela .= ''.$row_busca['supervisor'].'	';
    $tabela .= ''.$row_busca['local'].'	';
    $tabela .= ''.$row_busca['data'].'	';
    $tabela .= ''.$row_busca['questao1'].'	';
    $tabela .= ''.$row_busca['questao2'].'	';
    $tabela .= ''.$row_busca['questao3'].'	';
    $tabela .= ''.$row_busca['questao4'].'	';
    $tabela .= ''.$row_busca['questao5'].'	';
    $tabela .= ''.$row_busca['questao6'].'	';
    $tabela .= ''.$row_busca['questao7'].'	';
    $tabela .= ''.$row_busca['questao8'].'	';
    $tabela .= ''.$row_busca['questao9'].'	';
    $tabela .= ''.$row_busca['questao10'].'	';
    $tabela .= ''.$row_busca['status_aluno'].'	';
    $tabela .= ''.$row_busca['tipo_prova'].'	';
    $tabela .= ''.$row_busca['numero_acertos'].'	';
    $tabela .= ''.$row_busca['numero_erros'].'	';
    $tabela .= '
';
}
$tabela .= '
';

$arquivo = 'prova.xls';

header ('Cache-Control: no-cache, must-revalidate');
header ('Pragma: no-cache');
header('Content-Type: application/x-msexcel');
header ("Content-Disposition: attachment; filename=\"{$arquivo}\"");
echo $tabela;
?>

Comment: Trocar a extensão do arquivo não modifica realmente o seu tipo, se quer alterar o formato do arquivo deve estudar como ele funciona e adaptar seu código com as diferenças em relação ao atual. Você também pode usar alguma biblioteca que facilite esse processo
Comment: Isto não é EXCEL é um HTML que por coincidencia tem um razoavel suporte nos programas de Office como MSExcel, mas não é de fato excel, nem XLS nem XLSX, é apenas HTML, então não tem versão. Não adianta por uma extensão e acreditar que o conteúdo vá mudar, a extensão é só um facilitador para os sistemas operacionais, como outro exemplo não adiantaria renomear um PNG para  JPG não vai tornar a imagem no formato "JPEG" (me refiro ao conteudo)
Answer: Isto não é EXCEL, é um HTML que por coincidência tem um razoável suporte nos programas de Office como MSExcel, mas não é de fato excel, nem XLS e nem XLSX, é apenas HTML, então não tem versão.
Não adianta por uma extensão e acreditar que o conteúdo vá mudar, a extensão é só um facilitador para os sistemas operacionais, como outro exemplo não adiantaria renomear um PNG para JPG não vai tornar a imagem no formato "JPEG" (me refiro ao conteúdo).
Se você estiver usando Composer (somente "se" estiver usando), pode experimentar o composer require phpoffice/phpspreadsheet
Instale na pasta do projeto que JÁ USA composer (se estiver de fato usando) isto:
 composer require phpoffice/phpspreadsheet

Então seu documento deve ficar + ou - assim:
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$sheet->setCellValue('A1', 'Codigo Prova');
$sheet->setCellValue('B1', 'Nome');

...

$i = 1;

while($row_busca = mysqli_fetch_array($result_busca)){
    ++$i; //Incrementa a variavel para ter A2, A3, A4, A5, etc

    $sheet->setCellValue('A' . $i, $row_busca['cd_prova']);
    $sheet->setCellValue('B' . $i, $row_busca['nome']);

    ... Demais células aqui ...
}

$writer = new Xlsx($spreadsheet);

$arquivo = 'prova.xlsx';

header ('Cache-Control: no-cache, must-revalidate');
header ('Pragma: no-cache');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header ("Content-Disposition: attachment; filename=\"{$arquivo}\"");

//Envia para o OUTPUT do PHP e posteriormente resolvido pelo SAPI
$writer->save("php://output");

Não é fácil criar um arquivo XLSX, então fora essa lib até existem outras soluções, mas nem sei se realmente são confiáveis para uso, nem tenho como citar porque não usei outras.

Extra, não use error_reporting(0); incorretamente
Não é que não deva usar error_reporting, o problema é usar achando que serve para apenas sumir com os erros do output, mas isso é um problema, na verdade sentando 0 ele faz bem mais que isso, o ideal seria setar no php.ini da hospesagem display_errors=Off, mas isso já deve estar definido, e se for local é de preferencia que os erros sempre estejam ligados, isso porque você deve sempre corrigir todos antes de enviar pra produção, recomendo que leia:

Por que usar error_reporting com display_errors e display_startup_errors?


Interpretation and application of PCA - positive factor patterns for first component for all variables

Question: I am attempting to reduce the number of variables in a dataset for regression purposes and I suspect that many of the variables are correlated. Hence, I attempt a PCA, which I must admit I'm very new at. The variables in question are a range of indices, all ranging from 0 to 100.
After running PCA, I identify 3 components with eigenvalues greater than 1 (see results attached), with strong patterns for all variables in the first component.
Now I'm unsure how to proceed when it comes to using this information to apply to my regression, notably if factor patterns are strong for all variables in the first component, does that render the two others meaningless? How do I use this information to limit the number of variables in my regression model and avoid collinearity?
Comment: PCA as a way of selecting predictors is a dark art and there are many arguments against, but only rarely do people who think it's a really bad idea write papers explaining why or explain why not to do it in their regression texts. Two more neutral comments: 1. You mention PCA but then talk about factors: people positive on PCA usually dislike FA intensely, and vice versa, so either way be consistent on terminology. Your software may be letting you down here. 2. The first PC or factor being dominant is typically a reflection of variables mostly being size or abundance measures.
Comment: The simplest argument against in my view is that if you have difficulty interpreting the components, quite what you have achieved in your regression won't be easy to interpret either. (And I often have difficulty in interpreting components.) I would focus on identifying important variables either substantively or from their correlations with the outcome variable.
Answer: When applying PCA to reduce the number of variables in a regression model, you would typically use the first few components with large eigenvalues as they explain the majority of the variance in the data. In your case, the first component appears to have strong patterns for all variables, but it's still important to consider the second and third components as they might also contain valuable information.
To avoid collinearity, you could use the first few components as your new independent variables in the regression model instead of the original variables. This is because the components are orthogonal and uncorrelated, which helps to reduce the risk of multicollinearity.
Additionally, you could consider interpreting the factor loadings for each variable to see how much of each variable's variance is explained by each component. This can help you determine which variables are contributing the most to the first component and if there are any outliers that might affect your regression results.
Finally, it's always a good idea to visualize the data and the results of the PCA to gain a better understanding of the relationships between the variables and components.


dplyr mutate replace single column values as ifelse

Question: The purpose:
I have a dataset that contains many loan processing data (dataset: df). I need to change the character string to numeric data in the field "status". The objective is to change string narrative to a numeric value. I wish to use this status as a response variable in lm() method.
Here is what has been done:
df$status <- df$status %>%
  mutate(status = str_replace("Charged On", "100"))
df$status <- df$status %>%
  mutate(status = str_replace("Charged Off", "200"))
df$status <- df$status %>%
  mutate(status = str_replace("Fully Paid", "300"))
df$status <- df$status %>%
  mutate(status = str_replace("Current", "400"))
df$status <- df$status %>%
  mutate(status = str_replace("In Grace Period", "500"))

Answer: I would suggest using case_when here to generate a new numeric column:
df$status <- case_when(
    df$status == "Charged On" ~ 100,
    df$status == "Charged Off" ~ 200,
    df$status == "Fully Paid" ~ 300,
    df$status == "Current" ~ 400,
    df$status == "In Grace Period" ~ 500,
    TRUE ~ -1
)

Answer: If your column "Status" is in a factor format, you can simply change the factor level directly. Here a dummy example mimicking your dataframe:
df <- data.frame(status = rep(c("Charged On","Charged Off","Fully Paid","Current","Grace Period"),10))

        status
1   Charged On
2  Charged Off
3   Fully Paid
4      Current
5 Grace Period
6   Charged On
...        ...

We can check that it is a factor format:
> str(df)
'data.frame':   50 obs. of  1 variable:
 $ status: Factor w/ 5 levels "Charged Off",..: 2 1 4 3 5 2 1 4 3 5 ...

> levels(df$status)
[1] "Charged Off"  "Charged On"   "Current"      "Fully Paid"   "Grace Period"

Now you can change each factor levels by attributing a new corresponding  value based on the order of factor levels. The new value will be replace all along the column and finally convert it in a numeric format:
levels(df$status) <- c(200,100,400,300,500)
df$status <- as.numeric(as.character(df$status))

>   head(df)
  status
1    100
2    200
3    300
4    400
5    500
6    100

If your columns is not a factor format, you can convert it to a factor by doing:
df$status <- as.factor(df$status)

Comment: Indeed, you're totally right. My mistake to have forgot this parameter. I edit my answer accordingly. Thanks for noticing me this mistake.


Arquitetura Limpa e Arquitetura Cebola, são a mesma coisa?

Question: Tenho dúvida se Arquitetura de cebola é a mesma Arquitetura Limpa ?
Porque me parece num primeiro momento que suas estruturas e conceitos são iguais, dai a minha dúvida.
Comment: confesso que em todos os meus anos trabalhando em TI nunca havia ouvido o termo "arquitetura cebola" :D
Answer: A arquitetura limpa é um conjunto de especificações criadas a partir de quatro grandes arquiteturas: "onion architeture", "ports and adapters" (hexagonal), "data, context and interaction" (DCI), "entity-control-boundary" (BCE).
Onion architeture é a arquitetura cebola, que você cita.
De forma mais simples, eu diria que a arquitetura limpa não guia tanto as camadas, não restringe tanto, só exige algumas especificações, como a regra de dependência, que é a regra mais forte da arquitetura limpa. As outras arquiteturas citadas, são mais como uma forma especifica de implementar seu design de projeto.
Por exemplo, a arquitetura de portas e adaptadores tem como caracteristica ter as abstrações de dados e regras de negócios criticas na cerne, os use cases numa camada mais externa, e em uma camada ainda mais externa portas e adaptadores.
Portas: entradas para web, drivers de banco de dados e etc (entrada para Web via http com Express, por exemplo)
Adaptadores: para utilizar os frameworks e drivers nas nossas portas (controller Express, por exemplo, seria utilizado para adaptar nossa entrada para Web plugando em nossa aplicação desacoplada).
A arquitetura limpa em si não vai te definir esse nível de implementação, e sim especificações mais amplas para construir software reutilizável, com manutenção mais simples, regras de negócio bem definidas, e componentes facilmente testáveis.


Como extrair apenas o penúltimo caractere de uma sequencia e depois usar o autopreenchimento no Excel

Question: Tenho uma sequencia numérica separado por espaços, quero apenas extrair os números em vermelho, porém ao usar o autopreenchimento(clicar e arrastar para baixo com o cursor) não funciona! como eu faço para extrair apenas os números em vermelho de todas as células? e usar o autopreenchimento sem problemas, ??
Answer: Solução
Para obter o penúltimo item da célula, utiliza a seguinte função na primeira célula e depois o autopreenchimento.
Fórmula
=ARRUMAR(ESQUERDA(DIREITA(SUBSTITUIR(""&ARRUMAR(A1);" ";REPT(" ";40));80);40))
Em que " " é o separador, que no caso é um espaço. Esta fórmula funciona somente com espaço como separador.
Separador diferente de espaço
Caso o separador seja diferente de espaço, por exemplo um hífen -
Como na tabela a seguir:
+---+----------------------------+---------+
|   |             A              |    B    |
+---+----------------------------+---------+
| 1 | 1-22-333-4444-55555-666666 | 55555   |
| 2 | 1-22-333-4444-55555        | 4444    |
| 3 | 1-22-333-4444              | 333     |
| 4 | 1-22-333                   | 22      |
| 5 | 1-22                       | 1       |
| 6 | 1                          | 1       |
+---+----------------------------+---------+

Uma função personalizada (UDF) pode ser criada no VBA:
Function EXTRAIRPENULTIMO(Txt As String, Separador As String) As String
    On Error GoTo ErrHandler:
    contador = Len(Txt) - Len(Replace(Txt, Separador, ""))
    If contador = 0 Then
        EXTRAIRPENULTIMO = Txt
    Else
        EXTRAIRPENULTIMO = Split(Application.Trim(Mid(Txt, 1)), Separador)(contador - 1)
    End If
    Exit Function
ErrHandler:
    ' error handling code
    EXTRAIRPENULTIMO = CVErr(xlErrNA)
    On Error GoTo 0
End Function

E na coluna B a seguinte fórmula é usada:
=EXTRAIRPENULTIMO(B1;"-")
Comment: Muito bom. Mas seria possível inserir uma outra sequencia de numeração na frente do penúltimo, por exemplo uma numeração que esta antes do "55555" ou depois? no caso ficaria: B1: 55555 4444, ou se tivesse a sequencia "7" na frente da sequencia "666666",  B1: 55555 7777777, ??
Comment: seria o valor antes e o depois do penúltimo? Portanto, uma concatenação do último e antepenúltimo? Sugiro realizar outra pergunta
Comment: Sim. Eu vou fazer outra pergunta
Answer: A fórmula ficou meio grande

No caso específico do penúltimo valor entre espaços fica
=SE(
  NÚM.CARACT(A1) - NÚM.CARACT(SUBSTITUIR(A1; " ";""))<1;
  "";
  SE(
    NÚM.CARACT(A1) - NÚM.CARACT(SUBSTITUIR(A1; " ";""))=1;
    ESQUERDA(A1;LOCALIZAR(" ";A1));
    EXT.TEXTO(
      A1;
      LOCALIZAR("|";SUBSTITUIR(A1;" ";"|";NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1;" ";""))-1))+1;
      LOCALIZAR("|";SUBSTITUIR(A1;" ";"|";NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1;" ";"")))) -
      LOCALIZAR("|";SUBSTITUIR(A1;" ";"|";NÚM.CARACT(A1)-NÚM.CARACT(SUBSTITUIR(A1;" ";""))-1))-1
    )
  )
)

E uma generalização disso seria
=SE(
  NÚM.CARACT($A1) - NÚM.CARACT(SUBSTITUIR($A1; " ";""))<C$7;
  "";
  SE(
    NÚM.CARACT($A1) - NÚM.CARACT(SUBSTITUIR($A1; " ";""))=C$7;
    ESQUERDA($A1;LOCALIZAR(" ";$A1));
    EXT.TEXTO(
      $A1;
      LOCALIZAR("|";SUBSTITUIR($A1;" ";"|";NÚM.CARACT($A1)-NÚM.CARACT(SUBSTITUIR($A1;" ";""))-C$7))+1;
      LOCALIZAR("|";SUBSTITUIR($A1;" ";"|";NÚM.CARACT($A1)-NÚM.CARACT(SUBSTITUIR($A1;" ";""))-C$7+1)) -
      LOCALIZAR("|";SUBSTITUIR($A1;" ";"|";NÚM.CARACT($A1)-NÚM.CARACT(SUBSTITUIR($A1;" ";""))-C$7))-1
    )
  )
)


Generate mixed/multipart HTTP request in Java

Question: I would like to POST (in Java) a multipart/mixed request, where one part is of type 'application/json' and the other of type 'application/pdf'. Does anyone know of a library which will allow me to do this easily? Surprisingly I haven't been able to find one.
I'll generate the JSON, but I need to be able to set the content type of that part to 'application/json'.
Many thanks,
Daniel
Answer: Easy, use the Apache Http-client library (this code used version 4.1 and the jars httpclient, httpcore and httpmime), here's a sample:
<code>package com.officedrop.uploader;

import java.io.File;
import java.net.URL;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class SampleUploader {

    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();
        String basePath = "http://localhost/";

        URL url = new URL( basePath );

        HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );

        HttpPost httpost = new HttpPost( String.format( "%s%s", basePath, "ze/api/documents.xml"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file_1", new FileBody( new File( "path-to-file.pdf" ) , "file.pdf", "application/pdf", null));
        entity.addPart("uploaded_data_1", new FileBody( new File( "path-to-file.json" ) , "file.json", "application/json", null));

        httpost.setEntity(entity);

        HttpResponse response = httpclient.execute( targetHost, httpost);

    }

}
</code>
Comment: Hi Maurício, thanks for the suggestion. However the request is generated with a 'multipart/form-data' content-type instead of 'multipart/mixed'. I haven't found a way to change that, do you know how?
Comment: Why do you need it to be mixed? Any specific reason? Any HTTP server/framework will be able to decode these files correctly.
Comment: The documentation for the service I'm calling requires mixed, but it appears now that the documentation is in error. :) Thanks again!


What is the significance of the 20 yard line?

Question: I can think of two instances where this comes into play. One is if the kick-off falls behind the receiving goal line, and the runner chooses to "down" the ball in the endzone rather than run it out. This allows the receiving team to start at 20 yard line "for sure" instead of taking their chances with a running play.
The second is if the offensive team's ball carrier is tackled in his own end zone for a "safety," this team has to make a free kick from its 20 yard line (instead of from the 40 yard line).
How and why was the 20 yard line chosen for these purposes? And why was the "20" yard line changed to the 25 yard line for both touchbacks and safeties in college football in 2012?
Answer: Also add to this an offensive player fumbling into the endzone and recovered or out of bounds, an interception in the end zone kneeled, and a couple of blocked kick rules (and I fear I am missing things).
As far as I know, the touchback was an original (or very very old rule).  I have a pretty good idea of the history of most rules and the 20 yard line for touchbacks or change of possession rules has not been changed or altered for quite possibly the past 100 years.
What is the significance?  It is just the "average" spot that worked out as a good starting spot.  If an offense started out at the 10 yard line then a penalty and a sack results in a defensive advantage (hardly ever has a team started out on their 20 or greater and got a safety).  If an offense started on the 30 they would need just 30 more yards and most NFL kickers would be in range.
The significance of the 20 yard line is that it was such a well picked spot on the field that the original rule makers were exactly right.  If the 20 spot had problems rule changes would happen.  Only in 2012 did college change touchbacks to the 25.  And that had nothing to do with creating a fairer/better governed game.  It was just so that they could convince college coaches to have their guys take a knee so that the 22 guys on the field, probably never seeing the pros didn't get hurt.
Comment: You're slightly overstating the range of NFL kickers (57 yard FG is not commonly makeable...) but generally this looks right to me.
Comment: @Joe - maybe... by range I mean for half the teams coaches would think about it.  Obviously 57 yards is probably no better than a 50/50.
Answer: Another significance of the 20 is that when an offense advances the ball to within 20 yards of scoring a Touchdown, they are considered in the "red zone" for statistical purposes.
As the Coach said in his answer, the 20 was an average spot a return man could get to if he ran out a kick off out of his end zone. Additionally, the touch back rule is important because it forces kickers to strategical kick the ball rather than always kicking it beyond the end zone for a automatic touch back.
As for college, I'd like to expand on that answer. With the prevalence of new concussion research and repetitive head trauma, it was determined that kick offs have the highest likelihood of high impact concussion inducing plays. By awarding 5 extra yards to the touch back rule, the receiving team is encouraged to take a touch back so as to prevent as many high impact head blows as possible.
Comment: OK, the 25 yard line touchback gives college players "better than expectation" in order to avoid injuries to young bodies. Makes sense.
Comment: Sadly in the NFL this probably wouldn't make much difference - nowadays I suspect the median drive after kickoff starts behind the 20, as players catch the ball eight yards deep and still take it out (since, if they're just taking touchbacks, why does the team need to pay them and keep a roster spot for them, I guess?)
Comment: @Joe Many return men handle punts as well.  Most also fill the spot of 3/4th string WR, or 2/3rd string RB.  Some even are 1st string WR (Brown-Steelers) or a starting CB on defense.


How to resolve circular reference between dataframe columns in pandas?

Question: I have a multiindex dataframe with indexes Date and Symbol. The dataframe has around 10 million rows. The dataframe has a column Entry_signal with True or False values, another column Initial_stop with number values, and another column Low with number values as well. Based on the content of these three columns I want to calculate another three columns: Stop_level, Position, Exit_signal. These should be calculated based on the following logic:
data['Entry_signal'] = # True or False
data['Initial_stop'] = # numbers
data['Low'] = # numbers

data['Stop_level'] = np.where(data['Position'] == True,
                              np.maximum(data['Stop_level'].shift(1),
                                         data['Initial_stop']),
                              data['Initial_stop'])

data['Exit_signal'] = np.where(data['Low'] < data.groupby('Symbol')['Stop_level'].shift(1),
                               True,
                               False)

data['Position'] = np.where(data['Exit_signal'] == True,
                            False,
                            np.where(data['Entry_signal'] == True,
                                     True,
                                     data.groupby('Symbol')['Position'].shift(1)))

data['Position'] = data.groupby('Symbol')['Position'].ffill()

Now Stop_level raises error because it needs a Position. If I put Position at the beginning, it raises error because it needs Exit_signal. If I put Exit_signal at the beginning, it raises error because it needs Stop_level. And so on. How can I make this logic work?
Answer: Write it out on a scrap of paper:

Stop_level is a function of: Position, Stop_level,
Initial_stop.
Exit_signal is a function of: Low, Symbol, Stop_level.
Position is a function of: Exit_signal, Entry_signal,
Symbol, Position.

The current order does not work because Stop_level requires Position. Putting Position first doesn't work since it requires Exit_signal. Putting Exit_signal first doesn't work as it requires Stop_level. This exhausts all your options.
Therefore, you need to define logic which can actually be implemented.
Comment: You are right. Actually I want `Stop_level` to be the rolling max of `Initial_stop` (starting at the first `True` `Position` value) in case `Position` is `True`.  Otherwise, `Stop_level` should equal `Initial_stop`. I try to rephrase the question.


$|A|\ge |B|$ iff there is a surjection $g:A\to B$

Question: After define the equality of the cardinality of two sets, I defined the following ordering in the class of the all sets: let $A,B$ be sets, we define $|A|\le|B|$ if there is a injection $f:A\to B$.
Now, I'm trying to prove that $|A|\ge |B|$ iff there is a surjection $g:A\to B$ using the definitions I made.
I know this is true intuitively, but I couldn't prove it formally using my definitions, I need help.
Another question is this construction is standard in set theory?
Thanks in advance
Answer: Let $g : A \to B$ be a surjection, then there exists a right inverse:
Surjection iff right inverse
and this right inverse map, has a left inverse, namely $g$ itself, and so is injective since:
Injectiion iff left inverse
Call it $g^{\leftarrow}$,  then $g^{\leftarrow} : B \to g^{\leftarrow}(B) \subset A$ is a bijection.  Thus you have a bijection of $B$ onto a subset of $A$.  What does that mean?
Now, if $|A| \geq |B|$, in particular $|B| \leq |A|$ and you have an injection $f: B \to A$.  And using the above-reffered to articles, there's a left inverse of $f$, $g$ which is surjective.  You do the rest.  QED
Comment: You're welcome!!!!!!!


Supremum and infimum of $\{ \frac{n}{n+1}-a | a \in A\}$ where A is a bounded set.

Question: This is a pretty standard question, but I am having trouble to complete the final step.

I am asked to find the
  supremum and infimum of $B=\{ \frac{n}{n+1}-a | a \in A, n \in \mathbb N\}$ where A is a bounded set, and $\mathbb N$ includes $0$.

A first guess would be to find a good upper bound. Notice that:
$a \geq \inf(A) \implies -a \leq \inf(A) $ and that $ 0\leq\frac{n}{n+1}< 1$
so we get that:
$$ \frac{n}{n+1}-a \leq 1-\inf(A).$$
 and hence we have found an upper bound for $B$, which could be a candidate for the supremum. Similarly we can derive that:
$$ \frac{n}{n+1}-a \geq 0-\sup(A).$$
This is a candidate for the infimum of $B$.

Now how would I prove that:
$$ \sup(B)=1-\inf(A) $$
$$ \inf(B)=-\sup(A) $$

Standard approaches:
1)$ \forall \epsilon>0$ there must exist an element $x \in X$ such that $x>\sup(X) - \epsilon$
2) Bounded and increasing, therefore the sequence converges to supremum. (Monotone convergence theorem)
3) There is no smaller upper bound, we force a contradiction
I do not see how this would work as we have an $n$ AND a set $A$
Comment: The correct definition of $B$ is most probably $B:=\left\{ \frac{n}{n+1}-a\mid a\in A,n\in\mathbb{N}\right\} $.
Answer: For example, take the case where we want to show $\sup B= 1 - \inf A$. We have already shown that $1-\inf A$ is an upper bound, so $1 - \inf A \geq \sup B$.
For the other way, pick $\epsilon > 0$. We want to show that there is some $n$ and some $a \in A$ with $\frac{n}{n+1} - a < 1 - \inf A- \epsilon$.
This is simple : note that we can find $N$ so that $1-\frac{N}{N+1} < \frac\epsilon 2$(take any $N > \frac 2 \epsilon$), and then we can find $a \in A$ such that $a - \inf A < \frac{\epsilon}{2}$ (by the definition of infimum).
Add these up and rearrange to get $\frac{N}{N+1}- a> 1 - \inf A - \epsilon$.
In other words, if $A$ AND $n$ are involved, then split the given $\epsilon$ into smaller $\epsilon$-numerator fractions, obtain separate equations for $A$ and $n$ and then combine them.
I leave you to figure out how the second one can be done. Remember, obtain separate equations for $A$ and $n$ and then combine them.

This is the sort of situation where generality helps.

Result : For any two subsets $X$ and $Y$ of the real line, define $X+Y = \{x + y : x \in X, y \in Y\}$. If $X,Y$ are bounded, then so is $X+Y$. Furthermore, we also have the following formulas : $\inf X + \inf Y = \inf(X+Y)$, and $\sup(X+Y) = \sup X + \sup Y$.

Proof : I will do it for the supremum, you figure out the infimum : it is exactly the same.
For any $z \in X+Y$, we know $z = x+y$ for some $x\in X,y \in Y$. Therefore $z \leq \sup X + \sup Y$. It follows that $\sup X + \sup Y$ is an upper bound for $X+Y$, so $\sup X+Y \leq \sup X + \sup Y$.
For the other way, fix $\epsilon > 0$. Let $ x',y' $ be such that $\sup X - x' < \frac \epsilon 2$ and $\sup Y - y' < \frac \epsilon 2$. Add and conclude that $(\sup X + \sup Y) - (x'+y') < \epsilon$. Therefore, $\sup X+Y = \sup X + \sup Y$ .

Result : If $A$ is bounded, then $-A$ is bounded, with $\sup (-A) = - \inf (A)$  and $\inf (-A) = -\sup A$.

Prove this yourself.
Now, just note for your question that $B = S + (-A)$, where $A$ is some bounded set and $S = \{\frac{n}{n+1} : n \in \mathbb N\} \cup \{0\}$. Can you use the general result to find the infimum and supremum of $B$?
Comment: You are welcome! On the three techniques you mentioned at the end of your question, at least in the starting you will see mostly the first being used : that is, proceeding by definition.In the case of taking the supremum of a sequence, the second condition may be used , and the third is essentially a contradiction of the first, seen more occasionally though.
Comment: Aston.As usual, a pleasure to read.
Comment: Great answer connecting the general and the specific and showing me various ways to do something :)
Comment: Thanks for empowering me :)
Comment: @PeterSzilas Thank you for the compliment!
Answer: If $B$ is defined as in your question then $\inf B=\frac{n}{n+1}-\sup A$ and $\sup B=\frac{n}{n+1}-\inf A$.
Most probably this is about a set $B$ defined as: $$B:=\left\{ \frac{n}{n+1}-a\mid a\in A,n\in\mathbb{N}\right\} $$
Indeed from $a\geq\inf A$ we can conclude that $1-\inf A$ is an upper bound of $B$ on base of $$\frac{n}{n+1}-a\leq\frac{n}{n+1}-\inf A\leq1-\inf A$$
Now if $1-\inf A$ is not the least upper bound of $B$ then  there must be a smaller upper bound. So if $c$ denotes this smaller upper bound of $B$ then we must have $$\frac{n}{n+1}-a\leq c<1-\inf A$$for every $a\in A$ and every $n\in\mathbb N$.
Now be aware that we can take $n\in\mathbb N$ such that $\frac{n}{n+1}$ is very very close to $1$ and that we can take $a\in A$ very very close to $\inf A$.
In fact: as close as we want.
Let $\epsilon>0$ such that $1-\inf A-\epsilon>c$
We can take some $n\in \mathbb N$ such that $\frac{n}{n+1}>1-\frac12\epsilon$ and $a\in A$ such that $a<\inf A+\frac12\epsilon$ leading to:$$\frac{n}{n+1}-a>1-\inf A-\epsilon>c$$
This however contradicts that $c$ is an upper bound of $B$ and allows us to conclude that $1-\inf A$ is the least upper bound of $B$.
In mathematical language:$$\sup B=1-\inf A$$
Similarly it can be proved that:$$\inf B=1-\sup A$$


Mule- Access spring property placeholder inside groovy component

Question: Is there a way I can access spring property placheolder directly inside groovy script file used in a mule Flow
Would something like this work? . Assuming that 'ftp.server.url' is a property in application.properties loaded by spring
<context:property-placeholder location="classpath:application.properties" />

Ex Groovy script:
def ftpClient =new FTPClient().with {
    connect ${ftp.server.url}
}

Answer: If your script is embedded in the Mule XML config, this should work:
def ftpClient =new FTPClient().with {
    connect "${ftp.server.url}"
}

Comment: Thanks David. That worked like a charm. Is there a way I can access the properties if the groovy script is in external file.Just curious
Comment: I don't know... have you tried the above with an external file?


Sharepoint Fresh install how to set up site - getting _layouts/error.aspx

Question: We have a fresh install of a Sharepoint site. The administration panel is all set up, but we need to set up a base Team site. I tried to create a site collection and use the Teamsite as our base but I keep getting the /_layouts/error.aspx.  How do you do a fresh site? There are tutorials all around on how to set up a team site once a site is already set up, but not one from a fresh install.  How do we set up a new site?  Kind of frustrated.
We just get this error: An unexpected error has occurred. and it redirects to the /_layouts/error.aspx.
Any ideas? Thanks.
ADDITIONAL INFO:
The site we are trying to get to is actually a different site from our administration area than our public facing site.
Answer: I am assuming that you have already created an Application? If not you have to do that first THEN you create a site UNDER that application. So for example, under Application Management, you create a new Application (Use claims based auth for best results), set the Port number (defaults to 80) and when that's done, it will prompt you if you want to create a site.

DON'T MAKE THE MISTAKE OF USING A TEAM SITE as the top level site if you are using Server (not foundation); a top level Team Site can only create Team Sites underneath it (i.e. No publishing).

If you do have an Application setup (so you know, an Application is the same as setting up a blank IIS site with a matching SharePoint DB), then it's something else. Setting up a site is usually not a problem under an application but it might be that you may have a permissions error; unfortunately cause of 99% of SP problems.
The only way to track this down is using the System Application Event Log and the SharePoint Log. Start with event log and see if any errors are there. If not open the SharePoint log (by default, c:\Program Files\Common Files\Microsoft\Web Server Extensions\14\Logs). SharePoint creates a new log every 30 min (again by default) - sort the folder by date and open the latest. Search for the first part of the correlation number (xxxxx-) without the dash - when you find the first occurence of it, scroll left in the editor to where the message is then start scrolling down. You can also simply try searching for "Error" or "Failure". The log can be hard to read so you can use the ULSViewer (download from here: http://archive.msdn.microsoft.com/ULSViewer).
In many cases, this may be that the Application pool account does not have the right permissions to access the database.
If this doesn't help (or you can't figure it out), you can TEMPORARILY modify the web.config file - find 'customerrors="Off"' and change it to On (case sensitive!); you may need to do an IISReset (open a command window or Start > Run enter CMD then click OK) then enter IISreset; this stops and restarts the IIS. This turns off the error handling from SharePoint and will display the full error - TURN THIS BACK to Off when done!
If you are on a production system, do this after hours!!
That said, if you do see any errors and can't figure it out, repost here.
Best Regards,
David Sterling - CEO/CSA/Executive Consultant
firstname.lastname@example.com – +1 704-202-2282 – Skype: davidmsterling
Blog: http://davidmsterling.blogspot.com
Corp Site: http://www.sterling-consulting.com
Featured on: http://www.sharepoint-blog.com
Comment: we will check all these solutions out. I was not the initial person to install Sharepoint.  It looks like the person who did, did set up a web application on Port 80 but I don't know if they chose a site template or not.  I am not sure about the App Pool but we will check that out. I looked at the permissions in Sharepoint and it looks like that App has Full Control set.  We will check other the other solutions out.  If we don't find anything, we will comment back. Thanks for the info.
Comment: Quick question, what permissions should the Port 80 app have? We assume Full Control.
Right now we have Local Service set with Full Control under User Policy. Would there be any other service or user policy permissions under the Port 80 application that would need to be added?
Comment: Full control is not required - Local Service is the WRONG account, you must setup a separate domain account to use as the Application Service account and it must have user access to the SharePoint databases. Local Service will not work!


Does Holder's inequality require finite measure space?

Question: I read that when the domain of functions is compact, we have the following:
$$
C[a,b] \subseteq L^{\infty}[a,b] \subseteq L^2[a,b] \subseteq L^1[a,b]
$$
and which uses Holder's inequality for the proof..
However, if it is a sequence space, I think we have:
$$
l^1[a,b] \subseteq l^2[a,b] \subseteq l^{\infty}[a,b] ?
$$
for example, the sequence $(1/1,1/2,1/3,1/4,...)$ is in $l^{\infty}$ but not in $l^1$...
But a sequence is a function from $\mathbb{N} \rightarrow \mathbb{R}$ right? In that case, why doesn't Holder inequality apply to sequence spaces $l^{1},l^{2},...l^{\infty}$ s.t. we have a reverse order from those spaces in $L^p$ for $p \geq 1$?  Does this mean that Holder's inequality require finite measure spaces?
Answer: Holder's inequlaity: $|\int fg d\mu| \leq (\int |f|^{p} d\mu)^{1/p}(\int |g|^{q} d\mu)^{1/q}$ ($\frac 1 p +\frac 1 q=1$) is valid for any measure space. However if we take $g =1$ when  the measure is an infinite measure the  inequality becomes useless since $1$ is not in any $L^{p}$. That is why we cannot prove any inclusion between $L^{P}$ spaces for a general measure.
Comment: @LinkL By $l^{p}[a,b]$ do you men the space of functions $f:[a,b] \to \mathbb R$ with $\sum_{t \in [a,b]} |f(t)|^{p} <\infty$. If so then YES,your inclusions are correct.
Comment: thanks, just to add, does $ l^1[a,b] \subseteq l^2[a,b] \subseteq l^{\infty}[a,b]$ hold for infinite sequence spaces?


FFmpeg decode raw buffer with avcodec_decode_video2

Question: I am receiving a h264 stream where I at least know the size of one frame. The stream is coming in right as I can store it in a file and playback with vlc. Playing back a file is no problem for me as I include the libavformat. But libavformat gives me back an AVPacket which I can directly give to avcodec_decode_video2. In this case I got a bytestream. How can I give the raw h264 stream to the avcodec_decode_video2? How can I wrap my data into a AVPacket. VLC does not need to guess any data.
Answer: It is more or less easy to decode a stream. This code is working perfect for me:
<code>class ffmpegstreamdestination
{
public:
    ffmpegstreamdestination(AVCodecID decoder):
    {
        m_pCodec= avcodec_find_decoder(decoder);
        m_pCodecCtx = avcodec_alloc_context3(m_pCodec);
        avcodec_open2(m_pCodecCtx,m_pCodec,0);
        m_pFrame=avcodec_alloc_frame();
    }

    ~ffmpegstreamdestination()
    {
        av_free(m_pFrame);
        avcodec_close(m_pCodecCtx);
    }

    void decodeStreamData(unsigned char * pData, size_t sz)
    {
        AVPacket        packet;
        av_init_packet(&packet);

        packet.data=pData;
        packet.size=(int)sz;
        int framefinished=0;
        int nres=avcodec_decode_video2(m_pCodecCtx,m_pFrame,&framefinished,&packet);

        if(framefinished)
        {
                   // do the yuv magic and call a consumer
        }

        return;
    }

protected:
    AVCodecContext  *m_pCodecCtx;
    AVCodec         *m_pCodec;
    AVFrame         *m_pFrame;
};
</code>
the call decodeStreamData expect the data as frames. You have to search your stream for the NAL (more or less a header magic number) which is in h264 case 0x00000001 .Its the beginning of a frame. Filling the AVPacket is not as problematic as I thought. If you do not have the information, you can left the attributes in it as the are init by av_init_packet. There are only problems if you have a different framerate for example.
As always, if you see a bug or think something would work otherwise better, a short message would be welcome.
Comment: hi, how can i parse `0x00000001`, because this start codes repeats before `SPS` and `PPS`?
Comment: @nmxprime it is better to start a new question about that. As far as I know, you can simply iterate through pData like: for(size_t i=0;i<sz-4;i++) if((pData[i]==0x00)&&(pData[i+1]==0x00)&&(pData[i+2]==0x00)&&(pData[i+3]==0x01)) {/* i is the start here */} but be carefull, you need special buffer boundary check code
Comment: i tried like this, but i may be iterating wrongly, so not succeeded ! Let me try!!Actually, Typically the file contains data for 100 frames,which means 100's of`(sps,pps and data)`. The same start code is used for sps,pps and data. BTW, what boundary checking you're telling of?
Comment: @nmxprime our question is going to far to response it in the comment section. Open a new question with your code. Add a comment here to your question and I + 1 million coders will look into your problem :-)
Comment: I have raw data from RTSP stream. Getting this error "[h264 @ 001436e0] no frame!", "nres" value is always less than 0. Any hing whats wrong with my code?
Comment: @Tariq Post a new question with an example code. Your problem may be the streamdata itself, not the decoding.
Comment: avcodec_decode_video2 is deprecated, use avcodec_send_packet instead.
Source: Documentation in https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/avcodec.h


On integer solutions to $a^3+b^3+c^3+d^3=3$

Question: I was challenged to prove that there are infinitely many solutions to the equation$$a^3+b^3+c^3+d^3=3\ \ \text{ with }(a,b,c,d)\in\mathbb Z^4$$
That was easy: elementary algebra is enough to prove that $\forall z\in \mathbb Z$ then $$(a,b,c,d)=(1+6z^3,\,1-6z^3,\,-6z^2,\,1)$$ is a solution. Call these solutions and their permutations trivial.
Define a nonsum as a value of $k\in\mathbb Z$ for which there is no solution with $a+b=k$.
What about proving (or disproving/perfecting) the following conjectures?

If polynomials $A$, $B$, $C$, $D$ with integer coefficients are such that $\forall z\in \mathbb Z,\ (A(z),B(z),C(z),D(z))$ is a solution, and one such solution is non-trivial, then all the polynomials are constant.
There are nevertheless infinitely many non-trivial solutions.
Any $k\equiv0\pmod3$ is a nonsum.
$k=7$ is a nonsum.
There are infinitely many nonsums with $k\not\equiv0\pmod3$
If $k$ is a nonsum, then $-k$ is a nonsum.
If $k$ is not a nonsum (that is, if there exists a solution with $a+b=k$), then there are infinitely many solutions with $a+b=k$.
Comment: For references on the sum of cubes see also [here](http://mathworld.wolfram.com/CubicNumber.html).
Answer: Conjecture 2 is true.
Given an initial solution to
$$a^3+b^3+c^3+d^3=N$$
one can generate infinitely more using a Pell equation. Start with the general identity,
$$t^3+x^3+y^3+z^3 = (a^3+b^3+c^3+d^3)\big(p^2+wq^2\big)^3$$
where,
$$\begin{aligned}
t &= a p^2 - (c^2-d^2) p q + b w q^2 \\
x &= b p^2 + (c^2-d^2) p q + a w q^2\\
y &= c p^2 + (a^2 - b^2) p q + d w q^2\\
z &= d p^2 - (a^2 - b^2) p q + c w q^2\\
w &= (a+b)(c+d)
\end{aligned}$$
with $(a,b,c,d)$ suitably permuted so that $w$ is negative, then $p,q$ chosen to solve the Pell equation,
$$p^2+wq^2 = 1$$
Since from your parameterization,
$$(a,b,c,d)=(1+6z^3,\,1-6z^3,\,-6z^2,\,1)$$
we get a negative value for $w$,
$$w=(a+b)(c+d) = -2(6z^2-1)$$
necessary for the Pell equation, this shows we can derive infinitely many non-trivial solutions from the "trivial" one. Perhaps you can use this on some of your other conjectures.
Comment: Incidentally, for the special case $a^3+b^3+c^3+d^3 = 0$, then $p,q$ become free parameters, yielding infinitely many quadratic parameterizations to the _taxicab problem_.
Answer: Conjecture 3 is true.
Note first that for any integer $n$, $n^3 \equiv -1,0$, or $1\pmod 9$. Hence any solution of $a^3+b^3+c^3+d^3=3$ must contain three cubes congruent to $1\pmod 9$ and one cube congruent to $0\pmod9$.
Now suppose $a+b = k\equiv0\pmod3$. We have:
$$a^3+b^3=(a+b)^3-3ab(a+b)$$
where:
$$(a+b)^3\equiv0\pmod{3^3}\quad \text{and}\ \textit{a fortiori}\quad \equiv0\pmod9$$
$$3ab(a+b)\equiv0\pmod9$$
Hence $a^3+b^3\equiv0\pmod9$ which is inconsistent with the condition stated above, since it implies either both $a^3$ and $b^3$ congruent to $0\pmod9$ or one of them congruent to $-1$ and the other to $1\pmod9$.
Similar but not identical reasoning shows that conjecture 4 is true, and more generally any $k\equiv0\pmod7$ is a nonsum.
For any integer $n$, $n^3 \equiv -1,0$, or $1\pmod 7$. Hence any solution of $a^3+b^3+c^3+d^3=3$ must contain either (Case 1) three cubes congruent to $1\pmod 7$ and one cube congruent to $0\pmod7$ or (Case 2) four cubes congruent to $-1\pmod7$
Now suppose $a+b = k\equiv0\pmod7$. We have:
$$a^3+b^3=(a+b)(a^2-ab+b^2)\equiv0\pmod7$$
But this is inconsistent with both Case 1 and Case 2 above, since it implies either both $a^3$ and $b^3$ congruent to $0\pmod7$ or one of them congruent to $-1$ and the other to $1\pmod7$.
Answer: Equation given above is shown below;
$a^3+b^3+c^3+d^3=3$
In the solution given by Tito Piezas for $z=1$ we have $(a,b,c,d)=(7,-5,-6,1)$
and $(p,q,w)=(19,6,-10)$ which in turn gives $(t,x,y,z)=(337,-335,210,-215)$
Thus one of the many new solutions is,
$(t^3+x^3+y^3+z^3) = (a^3+b^3+c^3+d^3)(p^2+wq^2)^3=3$


How to get traffic sources of my visitors?

Question: What is the best way to get information about traffic sources of visitors on my web application? I want to store that information in database after every created an account by user.
I know that is possibility to get that information from google analytics cookies (utm*). But some browser extensions like adblock are blocking these cookies.
Comment: `information about visitors`  Could you elaborate?  Do you mean demographic profile?
Comment: Just only traffic sources
Answer: If by traffic source you mean: were where the user before landing into your web site, you could capture the document.referrer value.
Answer: you may get visitor IP-Address for unique visitor.
Which technology you are used?
If you are used PHP Technology.Here is the code for find IP
<code>echo SERVER['REMOTE_ADDR'];
</code>
Answer: main point is which types of traffic you want? means organic, social or referral traffics.
there are many ways to get traffics:
 - if your site is new, best option is paid marketing like PPC, PR etc.
 - your site is old then guest posting with high DA is best option. apart from social media traffics is also good option. now a days you can also get targeted social media traffics with Facebook paid marketing.
here are some of google links which you will get good tips

http://neilpatel.com/2016/03/22/how-to-increase-website-traffic-without-seo/
http://www.thecrazythinkers.com/11-killer-tips-increase-traffic-website-blog/

if you will get specific need, i will guide you with exact answer.


Filtrando eventos para Triggers

Question: Estou com um contra tempo que estou quebrando a cabeça mais não consigo resolver. Tenho uma tabela no qual gostaria que sempre que fosse inserido, alterado ou deletado um dado, disparasse uma trigger e adiciona-se o dado em uma tabela chamada log. Meu trigger está assim:
string sql = "CREATE TRIGGER Historico_Contacts ON Contacts " +
                    "FOR INSERT, DELETE, UPDATE AS " +
                    "BEGIN " +
                    "INSERT INTO Logs (Id, DataModificacao, Acao) SELECT Id, DataModificacao = GETDATE(), Acao = 'INSERT' from INSERTED " +
                    "INSERT INTO Logs (Id, DataModificacao, Acao) SELECT Id, DataModificacao = GETDATE(), Acao = 'DELETE' from DELETED " +
                    //"SELECT Id, DataModificacao = GETDATE(), Acao = 'INSERT' from inserted " +
                    //"SELECT Id, DataModificacao = GETDATE(), Acao = 'DELETE' from deleted " +
                    //"SELECT Id, DataModificacao = GETDATE(), Acao = 'UPDATE' from deleted " +
                    "END;";

Como podem ver, já tentei vários métodos. O principal problema que estou tendo é que quando faço alteração no dado, ele continua registrado como se fosse inserido o dado. Sei que estou esquecendo alguma coisa, mais não sei o que.
Obs.: Esse código da trigger é executado em uma aplicação C#.
Answer: Triggers são gerenciadas pelo próprio banco de dados, são diferentes de procedures que você consegue executar via código.
Tente da seguinte maneira:
1 - Criar a trigger dentro do seu banco de dados
CREATE TRIGGER TGR_HISTORICO_CONTATO ON CONTATOS
FOR INSERT
AS
BEGIN

    INSERT INTO LOGS SELECT ID, GETDATE(), 'Novo contato inserido' FROM INSERTED

END

2 - Execute o insert via código, que a sua trigger está esperando para ser executada
INSERT INTO CONTATO ( COL ....

dentro de seu banco de dados
Comment: Beleza amigo. Então só para eu ver se entendi direito, vou ter criar um gatilho separado para cada evento (INSERT, DELETE UPDATE)?
Comment: @MarcosHenrique não, você poder criar exatamente como você criou no seu código acima ( com as outras operações ), porém você só precisa ter em mente que as trigger precisam ser criadas dentro do banco de dados, e o que fica no seu código são apenas as operações de DML ( insert, update, select e delete )

Filtrando eventos para Triggers


Use nohup to run a long process in docker at a remote server

Question: I used to run a long training process on a remote server with GPU capabilities. Now my work schedule changes, so I can't have my computer connected to a network all the time till I finish the process. I found that nohup is the solution for me. But I don't know how to keep invoke the process correctly related my situation.

I use ssh to connect to the remote server.
I have to use docker to access to GPU.
Then I start the process in the docker.

If I start the process with nohup in docker, I can't really leave docker, right. So, do I use nohup at each step?
Edit:
I need the terminal output of the process at step 3, because I need that information to carry out the rest of the work. Consider, step 3 is training a neural network. So, the training log tells me the accuracy of different models at different iterations. I use that information to do the testing.
Comment: The Docker container should _be_ the process – there shouldn't be a "start the process in Docker" step – and you can use `docker run -d` to launch the container in the background.
Comment: So, I have to include the start-the-process in my docker file, so that I could get ridof it. But I do need the output of the process run inside docker. That output tells me which model I should use for testing.
Comment: It will be in the `docker logs` of the container, until you `docker rm` it.
Comment: You might get along better with `tmux` or `screen`.
Answer: Following @David Maze's suggestion, I did this (a slightly different approach as I was not familiar with docker a whole lot)

Logged in to the remote server.
Configured the docker script to have remote workdir.

...
WORKDIR /workspace
...

After building the docker container, run docker with mount option to mount the local project to docker workdir.  When running docker, I used nohup. Since I don't need interactive mode I ignored the -it flag.

nohup docker run --gpus all -v $(pwd)/path-to-project-root:/workspace/ docker-image:tag bash -c "command1; command2" > project.out 2>&1 &

To test this, I logged out from the server and see the content of project.out later. It contained the expected output.
Comment: Just FYI, a lot of people write `cmd > logfile 2>&1` to redirect `stdout` to a logfile, then redirect `stderr` to `stdout`, but there is a convenient and more readable shortcut : `cmd &> logfile`


Connecting to remote Active Directory using C# .Net

Question: I want to connect to a ActiveDirectory using c#.
I need to be able to connect to an DC which I can only resolve using an IP Address (which I have).
The next step is to find a computer in the DC address leases to resolve the IP address of a computername entered by a user.
Can someone give me a heads up?
I should be using
<code>DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://DC-IpAddress");
directoryEntry.Path = "LDAP://(What should I enter here for "Address Leases"?);
</code>
then I need a returned value which gives me the IP-Address of target Computer.
Hope you folks can help me out a bit.
FYI: The DHCP Server is installed on the target DC. just in case ;)
Comment: This sure sounds a lot like you're confusing LDAP with DNS.
Comment: I could be mistakes, yes. Lets say I need the DNS-record from the DC and then find my value..
Comment: If you just want to resolve a name, `Dns.GetHostEntry()` will give you the IP Addresses associated with a DNS name.
Comment: The problem is that its not "just resolve à name", I need to resolve it through à remote DC. So I am unable to use my local dns server. The target computer is connected to à different DC than I am on. Although I do have à connection with the DC I need the pc-adress from
Answer: in this  link VB project which is contains in the  forth section a method that  Listing all computers in the Active Directory .. may it helpful for you
http://www.codeproject.com/Articles/19689/Working-with-Active-Directory-in-VB-NET
Comment: Thx but this does not get me further then getting an OU or domain relationship.
Comment: if your main problem in the connection to specific DC remotely you need to an authenticated connection as the follow
Comment: var d = Domain.GetDomain(new DirectoryContext(
            DirectoryContextType.Domain,
            domainStr,
            Username,
            Password));
Comment: you may need to check out this link .
http://stackoverflow.com/questions/5374773/cant-connect-to-ad-without-specifically-connecting-to-a-dc
Comment: and here http://stackoverflow.com/questions/4015407/determine-current-domain-controller-programmatically  you will read related problem and it is answer


Error in flask in python with YouTube API and Replit googleapiclient.errors.UnknownApiNameOrVersion: name: youtube version: v3

Question: I have a python/html file that uses the YouTube api to run a few simple searches. It runs completely fine when I have it on a local server but whenever I upload it to Replit, I get the following error whenever I press the "reccomend" button.
This is the code python code:
<code>from flask import Flask, jsonify, request, render_template
from googleapiclient.discovery import build

app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/recommend', methods=['GET'])
def recommend():
  # Get the YouTube link from the query parameter
  youtube_link = request.args.get('link')

  # Parse the video ID from the link
  video_id = youtube_link.split('v=')[-1]

  # Initialize the YouTube API client
  youtube = build('youtube',
                  'v3',
                  developerKey='AIzaSy...')

  # Get the details of the video
  video_response = youtube.videos().list(part='snippet', id=video_id).execute()

  # Extract the video title and channel ID
  video_title = video_response['items'][0]['snippet']['title']
  channel_id = video_response['items'][0]['snippet']['channelId']

  # Get the details of the channel
  channel_response = youtube.channels().list(part='snippet,statistics',
                                             id=channel_id).execute()

  # Extract the channel title and subscriber count
  channel_title = channel_response['items'][0]['snippet']['title']
  subscriber_count = channel_response['items'][0]['statistics'][
    'subscriberCount']

  # Get the related videos for the video
  related_response = youtube.search().list(
    part='id,snippet', type='video', relatedToVideoId=video_id).execute()

  # Filter the related videos to only include videos from channels with less than 1000 subscribers
  recommendations = []
  for item in related_response['items']:
    channel_id = item['snippet']['channelId']
    video_id = item['id']['videoId']

    channel_response = youtube.channels().list(part='statistics',
                                               id=channel_id).execute()

    subscriber_count = int(
      channel_response['items'][0]['statistics']['subscriberCount'])
    if subscriber_count < 1000:
      recommendations.append({
        'id': video_id,
        'title': item['snippet']['title']
      })

  return jsonify(recommendations)

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=5000, debug=True)
</code>
and this is the error i'm getting:
<code> File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2548, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2528, in wsgi_app
    response = self.handle_exception(e)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/SmallChannelReccomender/main.py", line 21, in recommend
    youtube = build('youtube',
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/discovery.py", line 287, in build
    content = _retrieve_discovery_doc(
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/discovery.py", line 404, in _retrieve_discovery_doc
    raise UnknownApiNameOrVersion(
googleapiclient.errors.UnknownApiNameOrVersion: name: youtube  version: v3
</code>
Have changing API key, tried changing the API version but none of this seems to be making a difference. I even ran it through ChatGPT but this just told me the API version was wrong which I know is not the case. I have the package installed for the APi as well.
Answer: I have no idea why this works but adding static_discover=False to the build works for me, I had the exact same issue.
googleapiclient.discovery.build('youtube', 'v3', developerKey=API_KEY, static_discovery=False)


Repeating background in iOS when set to no-repeat

Question: I have an issue on a website I did a few years ago. It repeats the background on iOS.
The URL is writersadvice.co.uk

I don't have an iPhone myself and can't iOS simulator to work on my macbook but if anyone has any ideas, would be great as I have searched and not found any clues so far.
Thanks
Comment: Do you want to keep your site as it is? There are better techniques than having a 994x10000 background image, my iPhone refuses to even download the image, let alone show it twice. Other than that, I think you should check your code a few times over and fix double styles like `.cssbox { width: 980px !important; width: 965px; .. }`
Comment: I did the site a long time ago, before the dawn of smartphones.. that repeated style you quote there was an IE hack.
Yes there may well be better ways to have an extending vertical background like that.. the file size is still fairly small as it is mostly whitespace. I don't have a lot of time spare to redo the site, so would rather keep it close to how it is now. Ideally, yes it would be redone with proper responsive design.
Answer: I just copied your site and on a iPad and it did load the double background, opened through Safari on the PC to see if it happened as well but no luck there. A wild guess was it being the retina vs normal screen, which it happened to be.
A quick fix would be to add the following to your CSS, below all the other background calls:
<code>@media screen and (-webkit-min-device-pixel-ratio:2){
  .cssbox, .cssbox_body, .cssbox_head, .cssbox_head h2 {
      background-size: 1988px 20000px;
  }
}
</code>
But it ain't pretty, I'd really spend a few minutes re-writing some when possible ;)


MKMapView ignores annotations after unload&load (memory warning)

Question: please help me with this obstacle. I have a MKMapView with about 200 annotations. When I tap one of them, a detail view is pushed into UINavigationController so the MKMapView gets hidden. During browsing the presented detail view, I get memory warning and the hidden view is unloaded. After I close the presented detail view, the view with MKMapView is loaded again, but no annotation is visible (except User Location blue bubble) and focus is reset to the default one. [mapView: viewForAnnotation:] doesn't get called.
Even if I remove all annotations in viewDidUnload and insert fresh ones in viewDidLoad, the MKMapView doesn't display them anyway, even though [mapView: viewForAnnotation:] gets called for every single one.
Any idea how to make it behave and keep the same visible map rectangle after unload & load? Thank you very much.
EDIT - RESOLVED! The problem was that in the initWithNibName, I was getting
map = (MKMapView*)[self.view viewWithTag:TAG_MAP];
and from that moment on, I worked just with the 'map' variable. But after the reload, the variable apparently pointed to an invalid object. So I moved the command above to the viewDidLoad and now it works a treat. Thanks Craig to pointing me to the good direction!
Answer: Perhaps you're getting separated from the MKMapView or its delegate during the reload. You could look at fixing the memory warning, or change your map initialization code to be sure the same stuff is called during viewdidload as the initial load. Might be worth checking on viewDidLoad though, I think I heard it gets treated differently in iOS 6.
Comment: You were right, I was getting separated from the MKMapView (or more precisely, I had worked with the original one while a new one was displayed; I don't understand where the new one came from because initWithNibName is not called during unload & load but anyway, it works now :-) thanks!
Comment: That seems like a strange way to get a connection to a subview. Normally you'd add an outlet and use InterfaceBuilder to make a connection from the MKMapView you dragged on to the main view and that outlet. Are you using tags for a good reason?


Apagar conteúdo incluindo pastas

Question: Estou tentando apagar o conteúdo de uma pasta mas estou com o seguinte problema:

Usando o comando del ele apaga só arquivos e as pastas ficam (tem que apagar as pastas também).
Usando o comando rd ele apaga além do conteúdo todo, apaga a pasta raiz também.

Como posso fazer isso ?
Comment: Tente `rd /s /q`
Comment: @acklay tentei mas ele apaga a raiz também.
Comment: Se você colocar assim: `rd /s /q C:\path\to\directory\* ` não vai?!
Comment: @acklay não dá, acontece até uma mensagem de erro falando que está incorreto o label se colocar o * .
Comment: Veja minha resposta, testei aqui e funcionou. Pode usar tb o `Erase`.
Comment: Dê uma olhada aqui pra vê se ajudar: https://ss64.com/nt/del.html
Comment: Muito Bom! Deleta as sub-pastas e arquivos, mas mantem a RAIZ.
Answer: Se você quiser manter o diretório raiz por algum motivo e deseja realmente esvaziá-lo, então você pode fazer o seguinte:
del /q caminho_destino\*
for /d %x in (caminho_destino\*) do @rd /s /q "%x"

O primeiro comando remove todos os arquivos do diretório e, em seguida, o segundo remove recursivamente todos os diretórios aninhados, e mantém o diretório de nível raiz como está (exceto pelo seu conteúdo que foi apagado). Vale ressaltar que caminho_destino é o caminho do diretório que deseja esvaziar.
Observe que dentro de um arquivo .bat você precisa dobrar o % no loop for:
del /q caminho_destino\*
for /d %%x in (caminho_destino\*) do @rd /s /q "%%x"

Comment: Show, muito obrigado.
Comment: Disponha, fico feliz que tenha resolvido.
Comment: Muito bom, acabei tendo a mesma ideia só que só vi sua postagem depois de editada minha resposta. Acontece. :-)
Answer:
Editada, Script:
  A primeira versão não exclui as subpastas, entao tente o script abaixo:

del /q "C:\Teste\*.*"
FOR /D %%p IN ("C:\Teste\*.*") DO rmdir "%%p" /s /q

mkdir teste
cd \teste
mkdir files
cd files
echo $null >> file.txt
cd \
del /S teste\*.*

Comment: Tentei, ele apaga só os arquivos, a pasta continua.
Comment: A pasta raiz? vc queria deleta-la tb?
Comment: Seu script não funciona, observe... Mas não quero apagar a raiz, só o conteúdo dela.
Comment: Ok, verifique q nao funcionou mesmo, vou editar para uma nova versao
Comment: Não testei pq estou no linux, mas assim que liberar uma mq windows aqui vou testar.

Apagar conteúdo incluindo pastas


Finding a Field in an parsed HTML content

Question: I was trying to get the table from https://www.innovatoretfs.com/etf/default.aspx?ticker=kjul
I just want the top-right table
I wrote the  code in python and was able to get till the parsed HTML content and got the contents.
import requests
from bs4 import BeautifulSoup
url = "https://www.innovatoretfs.com/etf/default.aspx?ticker=kjul"
r = requests.get(url, headers = headers)
soup = BeautifulSoup(r.content, "html.parser")
table_it=soup.find_all(class_="al_fund")
value_it=soup.find_all(class_="ar_fund")
print(table_it)
print(value_it)

But I am not able to get the final values in a table coz of the HTML formal. can some one please help?
Answer: Another approach would be to grab all the values for given divs and then zip them all together.
Here's how:
import requests
from bs4 import BeautifulSoup

def extractor(s: BeautifulSoup, tag: str, cls: str) -> list:
    return [i.getText() for i in s.find_all(tag, class_=cls)]

url = "https://www.innovatoretfs.com/etf/default.aspx?ticker=kjul"
soup = BeautifulSoup(requests.get(url).content, "html.parser")

row_names = extractor(soup, "div", "al_fund")
row_values = extractor(soup, "div", "ar_fund")

for k, v in list(zip(row_names, row_values))[:6]:
    print(f"{k}\t{v}")

Output:
Ticker  KJUL
Listing Date    7/1/2020
Number of Holdings  7
Expense Ratio   0.79%
Intraday NAV    KJUL.IV
Exchange    Cboe BZX

Answer: Quick and easy way to get the desired content is like the following:
import requests
from bs4 import BeautifulSoup

link = 'https://www.innovatoretfs.com/etf/default.aspx?ticker=kjul'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    r = s.get(link)
    soup = BeautifulSoup(r.text,"lxml")
    for item in soup.select(".noshadecol")[:6]:
        title = item.select_one(".al_fund").text
        value = item.select_one(".ar_fund").text
        print(title,value)

Output:
Ticker KJUL
Listing Date 7/1/2020
Number of Holdings 7
Expense Ratio 0.79%
Intraday NAV KJUL.IV
Exchange Cboe BZX

Answer: with respect to the structure of HTML you did right to extract al_fund and ar_fund. You just need to add this code to print the table :
for i in range(6):
    print(f'{table_it[i].text} : {value_it[i].text}')

Ticker : KJUL
Listing Date : 7/1/2020
Number of Holdings : 7
Expense Ratio : 0.79%
Intraday NAV : KJUL.IV
Exchange : Cboe BZX


Problema com ponto em passagem de parametro post no slim framework

Question: Meu webService utiliza o slim framework e funciona corretamente usando essa requisição:
http://localhost:8000/wsrf/cadastrarFarmaciasPlantao/TESTEA/38410101/38410202/38410303/35172062/Rua X/email@emailcom/site/2015-10-15/IMAGEM01JPG

mas se eu adicionar um ponto no e-mail ou na extensão da imagem deixa de funcionar
http://localhost:8000/wsrf/cadastrarFarmaciasPlantao/TESTEA/38410101/38410202/38410303/35172062/Rua email@example.com/site/2015-10-15/IMAGEM01.JPG

Alguém sabe a causa?
Cabeçalho php da requisição:
$app->post("/cadastrarFarmaciasPlantao/:nome/:telefone/:telefone2/:telefone3/:cep/:endereco/:email/:site/:data/:imagem",
        function ($nome,$telefone,$telefone2,$telefone3,$cep,$endereco,$email,$site,$data,$imagem)

Comment: O `@` é um simbolo reservado em url, ele serve para passar user:pass no url. Provavelmente o ponto faz ativar essa funcionalidade. Deves usar `%40` e depois descodificar o url quando fôres usar. http://php.net/manual/en/function.urlencode.php
Answer: Obrigado pela resposta, mas meu problema era com o . com o @ não tive problemas
Resolvi meu problema opitando por passar o parâmetro pelo header ao invés da url.
Comment: Gente estou tento problemas com pontos no slim 4, mas acho que deve ser um bug, uma solução temporária é usar $request->getQueryParams() usando => exemplo?params=value


Hide default text for android switch Button

Question: In my Android application I have used a Switch Button. Is there anyway to hide text of switch button? For API level 21 there is an option to hide (android:showText), but I need to run it on lower level devices.
Here is my xml file:
<Switch
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:background="@drawable/offbuttonbg"
        android:textAppearance="@style/SwitchTextAppearance"
        android:thumb="@drawable/switchselector" />

Comment: set empty string on textOff, textOn...,maybe...the simplest solution....
Comment: I agree, see an example answer below.
Comment: Yes i got it, very silly question, anyway thanks for your quick response
Answer: For lower version, to hide the text use
 <Switch
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="7dp"
            android:textOff=""
            android:textOn=""
            android:background="@drawable/offbuttonbg"
            android:textAppearance="@style/SwitchTextAppearance"
            android:thumb="@drawable/switchselector" />

Comment: what is the problem with my answer?
Answer: You have two options one via code another via XML.
Via Code:
yourSwitch.setTextOff("textWhenOff") //Sets the text when the component is not in checked state.

yourSwitch.setTextOn("textWhenOn") //Sets the text when the component is not in checked state.

XML
<Switch
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:textOff="The text for the component when it's not checked."
        android:textOn="The text for the component when it's checked."
        android:background="@drawable/offbuttonbg"
        android:textAppearance="@style/SwitchTextAppearance"
        android:thumb="@drawable/switchselector" />

Always refer to the Switch Documentation if you need more info.
Comment: user wants to hide the text
Comment: I agree that is why the solution of setting a textOff and textOn will work for this case, also looking at yours you are suggesting the same, just that only for XML, I gave both forms in code and XML,

No reason to down vote here.


Write the following statements in if then form? Are my answers correct?

Question: (a) It is necessary that x is irrational for 1/x to be irrational.
my answer: If 1/x is irrational then it is necessary that x is irrational.
(b) I get an A in my English class only if I get an A on the final.
my answer: If I get an A in my English class then I got an A on the final
Answer: You don't need "necessary" in the if-then form. The first can just be "if $1/x$ is irrational then $x$ is irrational".
The second one is right (except perhaps for the change in tense).
Comment: So you think the second would should maybe be "If I got an A on the final then I get an A in my English class."?
Comment: @gnollwarden With the original sentence as written, both verbs should stay present tense. Of course writing English this way is a bit weird; more likely we would say "If I get an A on the final then I will get an A in the class" or something like this.


Flutter Error: The body might complete normally, causing 'null' to be returned

Question: I'm returning fetch data from MQTT broker and set the data in a variable. I got this issue, may I know why?
void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: true,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: sensor01(),
    );
  }
}

class sensor01 extends StatefulWidget {
  const sensor01({Key? key}) : super(key: key);

  @override
  State<sensor01> createState() => _sensor01();
}

class _sensor01 extends State<sensor01> {
// connection succeeded
  void onConnected() {
    print('Connected');
  }

// unconnected
  void onDisconnected() {
    print('Disconnected');
  }

// subscribe to topic succeeded
  void onSubscribed(String topic) {
    print('Subscribed topic: $topic');
  }

// subscribe to topic failed
  void onSubscribeFail(String topic) {
    print('Failed to subscribe $topic');
  }

// unsubscribe succeeded
  void onUnsubscribed(String topic) {
    print('Unsubscribed topic: $topic');
  }

// PING response received
  void pong() {
    print('Ping response client callback invoked');
  }

  var data;

  Future<MqttServerClient> connect() async {
    MqttServerClient client = MqttServerClient.withPort(host, id, port);
    client.logging(on: false);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    // client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;
    client.autoReconnect = false;

    final connMessage = MqttConnectMessage()
        .authenticateAs(username, password)
        .withClientIdentifier(id)
        .startClean()
        // .withWillRetain()
        .withWillQos(MqttQos.atLeastOnce);
    client.connectionMessage = connMessage;

    try {
      await client.connect();
      // client.unsubscribe('topic/');

      client.subscribe(topic1, MqttQos.atLeastOnce);
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }

    client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload as MqttPublishMessage;
      final payload =
          MqttPublishPayload.bytesToStringAsString(message.payload.message);
      print('Received message:$payload from topic: ${c[0].topic}>');
      Map<String, dynamic> userMap = jsonDecode(payload);
      var user = dataList.fromJson(userMap);

      setState(() {
        if (user.sensorid == 'sensor01') {
          data = user.sensorid;
        }
      });
    });

    @override
    void initState() {
      super.initState();
      connect();
    }

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          appBar: AppBar(
            title: Text("MQTT"),
          ),
          body: FutureBuilder(
            future: connect(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasError) {
                return Center(
                  child: Text("Error: ${snapshot.error}"),
                );
              }

              // if succeed to connect
              if (snapshot.connectionState == ConnectionState.done) {
                return ListView(
                  children: [
                    Card(
                        child: ListTile(
                      title: Text(data),
                    ))
                  ],
                  padding: EdgeInsets.all(10),
                );
              }
              return Center(child: CircularProgressIndicator());
            },
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

I got this one error. The error shows at the Fure function above the override widget. What should I add in order for the code able to run even the returned data is null?
The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<MqttServerClient>', is a potentially non-nullable type.

How to solve the error??
Answer: In your function connect() you have the return type of MqttServerClient:
Future<MqttServerClient> connect() async {}

but you aren't returning anything.
your function returns nothing -  it's void.
So, change:
Future<MqttServerClient> connect() async {}

To:
Future<void> connect() async {}

Comment: @MendeIG I get it, thank youu! Do you perhaps know if Flutter can subscribe to 3 different topics of MQTT broker at the same time? and then display data from all topics at the same time too
Comment: @syaf_ I've never dealt with MQTT, that's a _completely_ separate question. Please consider marking this answer [as accepted](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) and consider asking your question on as a separate question on StackOverflow.
Comment: Okay noted! didn't meant to trouble you, I'm sorry if you felt like so. Thank you once again! You're a big help for me
Comment: @syaf_ No problem, glad I could help! (I didn't mean to speak in harsh tone)
Comment: @MendeIG It's okay, have a nice day!


awaited promise not waiting for resolve() before contuining

Question: I'm making a pretty simple game within node.js. within my TCP client I have a async function that returns a promise, the promise resolves when the socket receives the information and then closes. My problem is: when I await the function, the program moves on before it resolves example below:
async GetPlayers(player) {
    return new Promise(resolve =>{
        var net = require('net');
        const client  = new net.Socket();

        client.connect({
          port:this.port,
          host:this.IpAdress
        });

        client.on('error',function(error){
            console.log('Error : ' + error);
          });

        client.on('connect',function(){
        client.write("sendPlayersToMePls: "+ JSON.stringify(player)+"\n");
          var address = client.address();
          var port = address.port;
          var family = address.family;
          var ipaddr = address.address;

        });
        client.on('data',function(data){
            //
            var data2 = data.toString();
            if(data2.startsWith("hereAreYourPlayers: ")){
            if(Config.Verbose)console.log("data = "+data2);
            var players2 = data2.slice(20);
            var obj = JSON.parse(players2);
            that.FileSystem.allPlayers = obj.players;
            that.FileSystem.TickCount= parseInt(obj.turnCount);
            resolve(obj);
            client.end();
        }

    });
}

//to call it i am using the following
async UpdateMapStatuses(player){

        this.SetCurrentMap();
        const players = await GetPlayers(player);
        return new Promise(resolve => {
        //the program starts exectuing this before "players" has been defined
        //code that uses "players"
        }

}

Comment: @JaromandaX that makes sense, but it doesn't make sense to return that promise. it would make more sense to await that execution and return the result. But as you point out - we have no idea what the intent is.
Comment: the `UpdateMapStatuses()` function already returns a promise - why are your returning a promise of a promise?
Comment: what does `console.log("data = "+data2)` output? assuming it ouputs anything
Comment: Here's a thought ... the code looks wrong ... shouldn't it be `async function GetPlayers(player) {` and `async function UpdateMapStatuses(player){` - as written, this code won't even parse will it?
Comment: Thank you for your comments, you helped me diagnose the problem, I did resolve the inefficient code that you were talking about. thanks for the help
Answer: Try converting your client.on callbacks to arrow functions and see if that helps. For example:
async GetPlayers(player) {
    return new Promise((resolve) =>{
        var net = require('net');
        const client  = new net.Socket();

        client.connect({
          port:this.port,
          host:this.IpAdress
        });

        client.on('error', (error) => {
            console.log('Error : ' + error);
          });

        client.on('connect', () => {
          client.write("sendPlayersToMePls: "+ JSON.stringify(player)+"\n");
          var address = client.address();
          var port = address.port;
          var family = address.family;
          var ipaddr = address.address;

        });
        client.on('data', (data) => {
            //
            var data2 = data.toString();
            if(data2.startsWith("hereAreYourPlayers: ")){
            if(Config.Verbose)console.log("data = "+data2);
            var players2 = data2.slice(20);
            var obj = JSON.parse(players2);
            that.FileSystem.allPlayers = obj.players;
            that.FileSystem.TickCount= parseInt(obj.turnCount);
            resolve(obj);
            client.end();
        }

Comment: Hey, just wanted to clarify, changing the functions to arrow functions did fix this problem, but there was another place in the code that had the same problem that i forgot to change, thus producing the same error, and i didn't notice where it had fired from had changed. Thank you for your help, I have marked your answer as accepted.
Comment: @AuthoredEntropy - Changing these particular functions to arrow functions does not look to me like it would make any difference.  There is no use of `this` in these arrow functions, therefore they would perform the same one way or the other.  Perhaps that was the case in the other function the OP mentions that is not shown in the question or the answer.  As it stands, this answer is very misleading because changing these functions to arrow functions does not fix anything.


Regular expression for strings with length not a multiple of 10

Question: Let $P = \{z^n \mid \text{$n$ is not divisible by $10$} \}$.
Give a regular expression for this language and then a generalized regular expression that is shorter than the regular expression.
Comment: Usually, we put conditions on $n$ inside the braces, such as $$\{z^n: n\text{ not divisible by }10\}$$
Answer: HINT: Every integer $n\ge 0$ can be written uniquely in the form $n=10q+r$, where $q$ and $r$ are non-negative integers, and $r<10$. If $n\ge 0$, the word $z^n$ is therefore $z^{10q+r}=z^{10q}z^r=(z^{10})^qz^r$.
Answer: If the goal is to get a short expression, one may propose $(z^{10})^*z(1 + z + z^2)(1 + z^3 + z^6)$, which looks slightly shorter than the solution $(z^{10})^*(z + z^2 + z^3 + z^4 + z^5 + z^6 + z^7 + z^8 + z^9)$ suggested by Brian M. Scott. If extended regular expressions are allowed, then simply write $P$ as the complement of $(z^{10})^*$.


Get the user ID for a newly created user account

Question: I'm trying to import user data from a JSON file. So far I've managed to import user entities with some fields. The next step would be to retrieve the user ID.
The code I wrote is the following one.
$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach ($users_array as $user) {
  if(!empty($user["roles"])) {
    $values = array(
      'name' => $user["name"],
      'pass' => '',
      'status' => $user["status"],
      'mail' => $user["e_mail"],
      'field_first_name' => $user["first_name"],
      'field_last_name' => $user["last_name"],
      'field_nationality' => $user["nationality"],
      'field_introduction' => $user["introduction"],
      'field_about_me' => $user["about_me"],
      'field_current_job' => $user["current_job"],
      'field_website' => $user["website"],
    );

    $storage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $storage->create($values);
    if ($userEntity->save() == 1) {
      echo "User " . $userEntity->id . " saved!\n\n";
    }
    else {
      echo "User " . $userEntity->id . " updated!\n\n";
    }
  }
}

However, when I try to print the user ID, I get no data.
I've just started to use Drupal API, so I'm not very familiar with it. Is there something I'm doing wrong?
Answer: You don't have access to an id property. You need to use the id() method instead, e.g. $userEntity->id(). See the documentation for User.
For example:
echo "User " . $userEntity->id() . " saved!\n\n";

Comment: This is correct. I would add it applies to any entity whose class implements [`EntityInterface`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityInterface.php/interface/EntityInterface/8.8.x).


Updating Visual FoxPro from SQL Server

Question: I'm trying to update some simple Visual FoxPro tables with SQL Server. I've created a linked server with the following:
sp_addlinkedserver @server = 'UTIL',
@srvproduct = 'VFP',
@provider = 'VFPOLEDB',
@datasrc = 'L:\M2MDATA\Util\util.dbc'
GO

And the following works:
select * from UTIL...utcomp

However, I cannot use the following statement:
update util...utcomp
set fmaddress = '123 Elvis Dr.'
where fcsqldb = 'M2MDATA01'

I receive the error:

OLE DB provider "VFPOLEDB" for linked server "util" returned message Multiple-step OLE DB operation generated errors. Check each
  OLE DB status value, if available. No work was done.".
  Msg 7333, Level 16, State 2, Line 2
  Cannot fetch a row using a bookmark from OLE DB provider "VFPOLEDB" for linked server "util".

I have the latest version (9.0) installed so I should have the latest provider. Am I doing something wrong? Is it not possible to update VFP from SQL?
Answer: There are some examples on the Fox Wiki that might help. Specifically the last one which shows how to access VFP data through OLEDB without using a linked server.
Comment: Great stuff, particularly note the change in provider string for SQL 2008, AllowInProcess setting and also check permissions on the folder as they will require the *user* account to have permissions as opposed to the sqlserver identity.

Updating Visual FoxPro from SQL Server


I am new to Python and getting this error while creating new Python 2 notebook. The Error is "Permission denied: Untitled.ipynb".

Question: I am learning python and Installed Anaconda and Trying to generate new python 2 notebook using jupyter notebook. I am using windows OS.
Answer: check If your "Untitled.ipynb" is open or in use somewhere in system.If yes close it.