Replace em apenas 1 caracter

Question: estou tentando fazer o replace do seguinte exemplo:

"Eu $ tenho $2 muito $$dinheiro$$"

Nesse cenário gostaria de substituir apenas os "$" que não estão duplicados como "$$", ficando a frase a seguir:

"Eu tenho 2 muito $dinheiro$"

já tentei utilizar o str.Replace("$", ""), mas ele substitui todos os "$"
Comment: Tem algumas questões que não estão claras na pergunta: Haverão outros casos de ocorrências múltiplas do `"$"`? O "$$" é uma sequencia de escape? Como seriam feitas as substituições caso a frase fosse `"Eu $ tenho $$2 muito $$$dinheiro$$$$"`? Veja um exemplo simples sem o uso de regex https://ideone.com/KbJ8Ni
Answer: Acredito que para fazer isso tu vai precisar criar uma expressão regular.
<code>using System.Text.RegularExpressions;

string str = "Eu $ tenho $2 muito $$dinheiro$$";
str = Regex.Replace(str, @"\$(?!\$)", "");
</code>
Comment: Expressão regular em C# funciona normalmente como em outras linguagens, estou tentando montar uma a algumas horas, mas até o momento nada eficaz
Comment: Quase lá, agora eu preciso apenas substituir os primeiros "$" da palavra " $$dinheiro$$", para ficar assim "$$dinheiro$$"
Comment: Mas o que ele propôs faz exatamente o que você especificou na pergunta: https://regex101.com/r/JdyTqs/1
Comment: É que eu não tinha visto que tinha que tirar do $$dinheiro$$ também, ai editei a resposta ^^

Replace em apenas 1 caracter


$\int_0^{\infty}x^n e^{-ax}dx$

Question:
How is the following formula proven?

I tried to use the integral $f(x)g'(x) (g(x) = \text{gamma function)}$ but it doesn't work.
This formula is used in Planck function integral and I really need to understand it for my astrophysics class. Any help is appreciated.
Comment: If you know about the gamma function already, then you can immediately just let $t=ax$ and get the result by calculating the effect of the variable substitution
Comment: @FShrike thanks alot i understand completely all this time I just needed a small variable substitution
Comment: Perhaps start with the definition of the Gamma function $\Gamma(n) = \int_0^\infty x^{n-1} e^{-x}\, dx $
Comment: It sounds like you're trying to use integration by parts. Indeed $\int_0^\infty x^{n+1}e^{-ax}\mathrm{d}x=\int_0^\infty fg'\mathrm{d}x$ with $f(x):=x^{n+1},\,g(x):=-\frac1ae^{-ax}$ sets up a useful recursion relation.
Answer: Recall that
$$\Gamma(n)=\int_0^\infty x^{n-1}e^{-x}~\mathrm{d}x.$$
Now let $t=ax$, $\mathrm{d}t=a~\mathrm{d}x$ in your integral, which gives you that
$$\int_0^\infty x^ne^{-ax}~\mathrm{d}x=\int_0^\infty \left(\frac{t}{a}\right)^ne^{-t}\frac{1}{a}~\mathrm{d}t=\frac{1}{a^{n+1}}\int_0^\infty t^ne^{-t}~\mathrm{d}t=\frac{\Gamma(n+1)}{a^{n+1}}.$$

$\int_0^{\infty}x^n e^{-ax}dx$


Password Reset Redirect

Question: I've been trying to redirect the password reset page to my custom login page by creating a small custom module; however it's not resolving properly.
Has anyone done this before with success?  The code that I'm trying to use is:
function m2f_password_reset_form_alter(&$form, &$form_state) {
  if ($form['#action'] == "/user/password"){
    $form['#submit'][] = 'user-pass';
  }
 }
/**
* Redirects user after password reset form is filled
*/
function m2f_password_redirect(&$form, &$form_state){
  $form_state['redirect'] = 'node/20';
}

Answer: There are at least three possible issues that I can see:

You are probably not prefixing the function with the right string.
If the module/theme name is m2f_password, then m2f_password_reset_form_alter() is not recognized at implementation of hook_form_alter().
If you are trying to alter the form that is shown at user/password, you should not check $form['#action']; you should implement hook_form_FORM_ID_alter(), and write a function called m2f_password_form_user_pass_alter(). (I assume the short name of the module/theme is m2f_password; if it is not correct, replace m2f_password with the short name of the module/theme.)
user-pass is not a valid form submission callback name: PHP functions cannot contains hyphens. You are then defining m2f_password_redirect(), and that seems a form submission callback.
The correct code is probably the following one.
$form['#submit'][] = 'm2f_password_redirect';

Answer: The problem is probably here:
$form['#submit'][] = 'user-pass';

The string that you add to the $form['#submit'] array must be a the name of a valid, existing PHP function. It's likely you just need to change that line to:
$form['#submit'][] = 'm2f_password_redirect';

Don't forget that PHP function names can't contain hyphens so user-pass would never be a valid name for a submit handler.
Comment: I understand, and have updated, but it's still not pulling through.  m2f_ is the theme name, correct?  I have the suspicion that there is something small that I'm overlooking.  Thanks for your input/advice!  For reference, I've been trying to follow this page: http://drupal.org/node/1458894

Password Reset Redirect


Por que o servidor web não encontra minha rota?

Question: Fiz o upload de um sistema em Laravel chamado android_api no servidor da hostgator, e configurei no arquivo public.
Até a página principal ele funciona, onde aparece o Laravel 5, porém quando coloco a rota que criei, ele mostra pagina não encontrada.
Publiquei na raiz do meu servidor:
-> raiz
      |_ android_api
      |_ public_html
             |_ android_api (que é a pasta public)
                  |_ index.php

Vocês podem ver aqui como encontra normal o Laravel, mas se coloco a rota que criei /listaService, dá página não encontrada.
Minha rota está assim:
Route::get('/listaService', "GeralController@getServices" );

Localmente funciona.
Vi que tenho que configurar um Virtual Host lá no servidor da Hostgator, mas não achei esse local.
Meu .htaccess está assim:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteBase /android_api

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Comment: O seu ```RewriteRule ^(.*)/$ /$1 [L,R=301]``` não teria que ser ```RewriteRule ^(.*)/$ public/$1 [L,R=301]``` ? Veja se isso te ajuda: http://www.codegeo.com.br/2013/03/utilizando-htaccess-para-hospedar-uma.html
Comment: Só que esse htaccess era do projeto, mas adicionei no htaccess do sevidor essas configurações que você indicou e funcionou. Pode adicionar como resposta. Obrigado
Comment: Show de bola então. Também já tive um problema parecido no passado.
Answer: Atualmente seu RewriteRule está assim:
RewriteRule ^(.*)/$ /$1 [L,R=301]

Como o arquivo index.php mapeado pelo servidor como arquivo padrão de busca e carregamento fica dentro do diretório public, sendo assim basta fazer a seguinte alteração:
RewriteRule ^(.*)/$ public/$1 [L,R=301]

Para mais informações: http://www.codegeo.com.br/2013/03/utilizando-htaccess-para-hospedar-uma.html


How to get current User in Repository of Symfony 3?

Question: I use the symfony 3 and try to get the current user data in Entity Repository file, but when i used $this->get('security.token_storage')->getToken()->getUser();, there is a error message that is can not found the get function
So, how to do it?
PS: if in the form type, how to invoke the user data.
Thanks.
Answer: Repositories shouldnt known the user. If you need user information you should make a method like this:
class YourRepository
{
    public function findSomethingByUser(User $user)
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT t FROM AppBundle:Table t '.
                'WHERE t.user > :user'
        )->setParameter('user', $user->getUsername());

        return $query->getResult();
    }
}

You can use the repository inside a controller:
class MyController
{
    public function someAction()
    {
        $user = $this->get('security.token_storage')
            ->getToken()
            ->getUser();

        $this->get('doctrine')
            ->getManager()
            ->getRepository('AppBundle:EntityName')
            ->findSomethingByUser($user);

        return new Response('foo');
    }
}

Answer: Since Symfony 3.4 you can use the security Utility Class. This allow you to retrieve the actual user.
use Symfony\Component\Security\Core\Security;
...
class YourRepository
{
    private $security;
    public function __construct(ManagerRegistry $registry,  Security $security)
    {
        parent::__construct($registry, Projekt::class);
         $this->security = $security;
    }

    public function findSomethingByUser(User $user)
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT t FROM AppBundle:Table t '.
                'WHERE t.user > :user'
        )->setParameter('user', $this->security->getUser());

        return $query->getResult();
    }

Answer: Entity Repository has not Container. You can find solution how do it (as example here Symfony2: How to access to service from repository), but it is not best practice. Repositories have only one goal - work with data from the database. You can pass the user object as parameter for your method.


How do I prevent prerequisite files from being duplicated in the app deployment folder?

Question: I have a .NET 3.5 SP1 WinForms application.  I have set it up for ClickOnce deployment with the following settings:

Publish to location: \\fileserver\installers\myapp\
Prerequisites: Windows Installer 3.1, .NET Framework 3.5 SP1
Download prerequisites from the following location: \\fileserver\installers\common\
Application is available offline (installs to Add/Remove Programs and Start Menu)

It is likely that our users will not have internet access or 3.5 installed already.  Since they will all be on the company intranet, we've put the necessary installers on a network share location they'll all be able to access.
When testing installation on a machine that lacks .NET 3.5, everything works fine.  It installs the prereqs and the app and it launches no problem.
The problem is that every time I deploy the application (via the Publish button) Visual Studio 2008 insists on copying all of the prerequisite files/folders from my development PC to the network location (installers\myapp).  This causes my 20MB application to be about 200MB in the folder.  This effectively duplicates everything since the ~200MB prereqs are already in the installers\common folder.  As I said, though, it installs fine.  It even installs fine if I delete the prereqs that VS puts in the myapp folder, presumably because the installer is getting them from the common location anyway (as specified in the Prerequisites dialog).
This is perhaps a trivial issue, since nothing goes wrong and it'll work fine, but it is annoying for two reasons:

It slows down deployment since I have to transfer 200+ megs over the wire every time I publish a small change to the application
It wastes space on our file server

I can resolve the second issue by simply deleting the folders every time, but that in itself is an annoying extra step.
Answer: One thing you can do is roll your own prerequisites using the Bootstrapper Manifest Generator. Set the URL to the location where you want to serve up the deployment. Then set the option in VS to "download from vendor location".
It will download the deployment from the URL you set in the BMG, and won't deploy the prerequisites each time you publish the ClickOnce application.
Comment: Did you try it? Although it has not been updated, I find that it still works.


Fourier Sine series uses the orthogonal set $\{\sin(nx)\}^\infty_{n = 1}$ on $0 \le x \le \pi$

Question: I came across the following explanation:

The Fourier Sine series uses the orthogonal set $\{\sin(nx)\}^\infty_{n = 1}$ on $0 \le x \le \pi$.
Here, the norm squared is
$$|| \sin(nx) ||^2 = \int_0^\pi \sin^2(nx) \ dx \\ = \frac{1}{2} \int_0^\pi (1 - \cos(2nx)) \ dx \\ = \frac{1}{2} \left[ x - \frac{\sin(2nx)}{2n} \right]^\pi_0 \\ = \frac{\pi}{2}$$

What does it mean to say that the Fourier Sine series uses the orthogonal set $\{\sin(nx)\}^\infty_{n = 1}$ on $0 \le x \le \pi$? And how did they get and why is the norm squared $|| \sin(nx) ||^2 = \int_0^\pi \sin^2(nx) \ dx$?
I would appreciate it if people could please take the time to clarify this.
Answer: The $\mathscr{L}^2$ norm on $[0,\pi]$ is
$$ \Vert f \Vert_{\mathscr{L}^2} = \left(\int_0^\pi |f(x)|^2 \,dx\right)^{1/2}. $$
It is induced by the $\mathscr{L}^2$ inner product
$$ \langle f,g \rangle_{\mathscr{L}^2} := \int_0^\pi f(x)\overline{g(x)} \,dx. $$
One usually works in $\mathscr{L}^2$ when dealing with Fourier series because $\mathscr{L}^2$ is a Hilbert space, so it makes sense to speak about orthogonality and similar things.
The set $\{\sin(nx)\}_{n=1}^\infty$ is orthogonal because
$$ \langle \sin(nx),\sin(mx) \rangle_{\mathscr{L}^2} = \int_0^\pi \sin(nx)\sin(mx) = 0 $$
whenever $n \not= m$.
Now you can see directly from the above that
$$ \Vert \sin(nx) \Vert_{\mathscr{L}^2}^2 = \int_0^\pi \sin^2(nx) \,dx = \frac{\pi}{2}. $$
Note that this shows that the set $\left\{\sqrt{\frac{2}{\pi}}\sin(nx)\right\}_{n=1}^\infty$ is orthonormal.
Comment: Yes, I will update that! I always thought that they were synonyms, but I guess that inner product is a more general concept, so it's better to call it the inner product.
Comment: Be careful. Your stated norm is only a semi-norm. You have to take the quotient of all functions constant zero almost everywhere. In fact, if you do so, $\{\cos(nx),\sin(mx)\}_{n \geq 0, m>0}$ is even a Hilbert basis of $L^2[0,\pi]$. That's why the Fourier series works.
Comment: Of course, I always feel that it is understood that we are talking about the quotient spaces when $\mathscr{L}^p$ spaces are in question.
Comment: Yeah, I forget that all the time to mention aswell. :D
Comment: Thanks for the response. :) When you say $\mathscr{L}^2$ scalar product, you're referring to the inner product, right?


JavaScript: Invalid left-hand side in assignment?

Question: I am a beginner and I want to make color game as a project. The html contains six grids but the javascript is showing the error?
var colors = [
 "rgb (255, 0, 0)",
 "rgb (255, 255, 0)",
 "rgb (255, 0, 255)",
 "rgb (0, 255, 255)",
 "rgb (0, 255, 0)",
 "rgb (0, 0, 255)",
]

var squares = document.querySelectorAll(".square");

for (var i = 0; i < squares.length; i++){
 squares[i].style.background-color = colors[i];
}

Comment: `style.background-color` is invalid syntax for accessing a property name with dashes in it
Comment: This question is not duplicated completely as there is error in `colors` array where the style will not apply as there is white space in `rgb (255, 0, 0)` after `rgb` which it shouldn't.
Answer: It is throwing an error because style.background-color has a dash in it and it is not valid . You can use background instead
for (var i = 0; i < squares.length; i++){
 squares[i].style.background  = colors[i];
}

or backgroundColor as follows,
 squares[i].style.backgroundColor = colors[i];

Comment: or `backgroundColor` if needing to modify the color only
Comment: @PatrickEvans yeah
Answer: There are two issues in your code:

There should not be any white space in rgb (255, 0, 0). The color value should be rgb(255, 0, 0) where there is no space after rgb
Second issue is the background-color which should be backgroundColor.

var colors = [
 "rgb(255, 0, 0)",
 "rgb(255, 255, 0)",
 "rgb(255, 0, 255)",
 "rgb(0, 255, 255)",
 "rgb(0, 255, 0)",
 "rgb(0, 0, 255)",
]

var squares = document.querySelectorAll(".square");

for (var i = 0; i < squares.length; i++){
 squares[i].style.backgroundColor = colors[i];
}

Color 1

Color 2

Color 3

Color 4

Color 5

Color 6

Comment: Thank you! I wanted to vote but can not because I am a noob.


What are my choices for transforming data that are not normally distributed?

Question: I have two sets of data comparing two variables: x and y. I'd like to transform and compare both sets either in r or matlab.
Scatter plot

Neither are normal and come from (by the looks of it) different distributions)
QQPLOT of data 1

QQPLOT of data 2

I would like to transform both data sets to compare them on a level playing field but I know they are not normally distributed, though I don't know from what distribution they come. What are my choices?
Comment: What is the end goal here? i.e. How exactly do you plan to compare them?
Comment: Data 1 are experimental. Data two come from a model which had to estimate some parameters. My end goal is to show that after some sort of transformation they are statistically significantly similar (ie that somehow they are a scaled version of each other, or some such). I will use the Kuskall-Wallis test here after the transformation. But what are my best choices to make such a transformation?
Answer: 1) Why transform at all?  If you use a nonparametric test, normality is not assumed.
2) "Statistically significantly similar" is tricky; usually statistical significance applies to a difference (although there are also equivalence tests).
3) I am not sure what your first plot does... what are the two axes?
4) Are your QQPLOTs plots against a normal distribution? It looks like data 1 is truncated
EDIT in response to comments:
You do seem to want some kind of regression here. I would first look at a scatterplot of the two variables. Then I'd try an ordinary least square regression for starters, and look at the residuals. If there are problems with normality and homoscedasticity, you might need to do something else.
By the way, I still am not sure what that first plot is.
Comment: Let me put it into perspective: the experimental data are the bacteria colonies (y) on nurses' hands after time (x) 1)The reason for transformation was because the data1 are experimental but data2 are predicted. Although the mechanics of accruing germs is known, the quantity on surfaces they touched is not. So surely I need a transformation to make them comparable?
Comment: QQPLOTS were against normal distributions. And data 1 is truncated because detectability of germs has an upper limit.
Comment: Why would the fact that one is actual data and the other is predicted mean that you need a transformation?  It might mean that what you want regression, rather than Kruskal Wallis. That is, the DV would be actual germs and the IV predicted germs
Comment: Ah interesting, I see that using regression wouldn't need any transformation. Are we talking general linear modelling or something else would you say? Also what do you think about that truncated data?
Comment: Just try out some GLM first, as @PeterFlom has suggested.


Problema com retorno de POST utilizando Synapse

Question: Estou realizando uma requisição POST no Delphi XE7 utilizando o Synapse (Synalist). Peguei apenas a parte onde faço o método POST e realizo minhas tentativas de conversão do resultado.
Acima disso eu declaro propriedades como userAgent, headers e cookies.
O método UTF8FileTo88591 eu peguei deste link: UTF8FileTo88591
var
  http: THTTPSend;
  stl : TstringList;
  ss  : TStringStream;
begin
  if http.HTTPMethod('POST', edtUrMenu.text) then
  begin
    HTTP.Document.position := 0;
    HTTP.Document.saveToFile('d:\a\a3.txt');

    UTF8FileTo88591('d:\a\a3.txt'); // tentativa 1

    stl.defaultEncoding := TEncoding.UTF8; // tentativa 2
    stl.loadFromStream(http.document);
    stl.saveToFile('D:\a\LoadFromStream.txt');

    // tentativa 3
    try
      ss := TStringStream.Create('', TEncoding.UTF8);
      HTTP.Document.position := 0;
      ss.CopyFrom(HTTP.Document, 0);
      ss.SaveToFile('d:\a\a4.txt');
      showmessage(ss.datastring);
    except
    end;
    ss.free;
  end;
end;

O problema é que o resultado está com codificação ao qual não consegui converter. Uma parte do resultado (gerado através do HTTP.Document.saveToFile('d:\a\a3.txt')) ou pastebin com o resultado completo
‹      í½`I–%&/mÊ{JõJ×àt¡€`$Ø@ìÁˆÍæ'ìiG#)«*ÊeVe]f@Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ãäñïúôË"7¿ÏËÓtÞ.ÊôåWOžŸ¤mß½ûÝ{'wï>}ó4ý½¿ýæ‹çéîx'}Sg˦h‹j™•wïž¾ø(ýhÞ¶«Gwï^]]¯î«úâî›WwßÖ.^Ö_·[ïÍñ¬}tô'Ô9¾Lß-ÊeóYÒîÇÀG)µ<ϳYZÌ>ûhÚ–;;¿ÿ·éÏÝŽ·E[æôý-ÑMÞ¦/ò«iµ¤7îÊwy›¥è`;ÿEëâò³~ïí¯Ž·OªÅ*k‹I™"Rû6_¶Ÿ}tvúÙéb]fm~vúð£ônäå"l:Ïémê®"Ôì«Ëj{Š¯ø²X¾Mçu~þÙGãñÝŸnîN›ænu™×Ó¬iïþô/ZçõõöºÓÇ¥u^~öQÓ^—y3Ïóö£´½^åŸ}ÔæïZ¼X,§åz–7w¿È—ëߟpÉÚ¯Jqk³  þk(DÞfZ«ÖÿËL>ŧô\feY]½È/ˆÒ—

Comment: Se esta utilizando o XE7 porque não utilizar a `Indy` para essa requisição?
Comment: Eu tentei com o Indy, mas tive outros problemas e acredito que tenha sido por causa dos cookies ou o fato de que precisava deixar a conexão ativa a qualquer custo (keep-alive). Eu consegui resolver o problema da pergunta, o conteúdo que estava recebendo era um GZIP, usei uma lib pra descomprimir o resultado.
Answer: Consegui identificar o problema e resolver a situação. O conteúdo que recebo é um gzip, identifiquei isso pois no header eu só recebia um resultado caso colocasse o seguinte header, sem o header ou caso aceitasse outro tipo de encoding eu não recebo o conteúdo (301 http code):
http.headers.add('Accept-Encoding: gzip, deflate, br');

Portanto fui atrás e encontrei a seguinte biblioteca: GZip ao qual usei a função unzipStream e então consegui ter o dado descomprimido.
ss := TStringStream.create;
b := unzipStream(http.document,ss);
ss.saveToFile('D:\a\a4.txt');


Como utilizar traduções em Qt diretamente com QApplication::tr()

Question: Em uma aplicação desenvolvida em Qt eu tenho uma classe não visual (isto é, que não é herdada de um QWidget) mas que manipula strings de texto que devem ser apresentadas ao usuário. Para utilizar o mecanismo de tradução do Qt, eu defini todas as strings utilizando a função QApplication::tr().
As strings são corretamente exibidas na ferramenta Linguist, sob o contexto de QApplication (como esperado - veja imagem abaixo). Porém, quando via código eu altero o Locale da aplicação, apenas as strings sob o contexto de MainWindow são alteradas.

O código que eu utilizo para trocar o idioma é o seguinte:
void MainWindow::setLocale(QString sLocale)
{
    QTranslator *pTranslator = m_mpTranslators[sLocale];
    if(pTranslator)
    {
        for(map<QString, QTranslator*>::iterator it = m_mpTranslators.begin(); it != m_mpTranslators.end(); ++it)
        {
            qApp->removeTranslator(it->second);
            QApplication::removeTranslator(it->second); // Essa linha não existia antes!
        }
        qApp->installTranslator(pTranslator);
        QApplication::installTranslator(pTranslator);  // Essa linha também não!

        if(sLocale == "pt_BR")
            m_pLocaleButton->menuAction()->setIcon(QIcon(":/resources/icons/pt_BR"));
        else
            m_pLocaleButton->menuAction()->setIcon(QIcon(":/resources/icons/en_UK"));

        ui->retranslateUi(this);
        updateUI();
    }
}

Creio que é importante notar que a alteração dos textos na interface gráfica é imediata (via chamadas de ui->retranslateUi(this) e updateUI()), mas que as chamadas da classe não visual ocorrem posteriormente a troca do locale, então o texto deveria ser traduzido corretamente.
No código acima, eu também cheguei a incluir as linhas marcadas com comentários, mas isso não fez com que a tradução acompanhasse o locale definido.
Alguém tem alguma ideia de onde eu possa estar me equivocando?
Edição:
A versão do Qt é a 5.1.0 (32 bit), e estou executando no Windows 7 (64 bit). Os tradutores são criados no construtor da classe MainWindow, da seguinte forma:
// Setup the translation system
QTranslator *pPortuguese = new QTranslator(this);
QString sPortuguese = QCoreApplication::applicationFilePath().replace(".exe", "_pt_BR.qm");
if(pPortuguese->load(sPortuguese))
    m_mpTranslators.insert(map<QString, QTranslator*>::value_type(QString("pt_BR"), pPortuguese));
else
    qWarning() << "Portuguese translation file not found";

QTranslator *pEnglish = new QTranslator(this);
QString sEnglish = QCoreApplication::applicationFilePath().replace(".exe", "_en_UK.qm");
if(pEnglish->load(sEnglish))
    m_mpTranslators.insert(map<QString, QTranslator*>::value_type(QString("en_UK"), pEnglish));
else
    qWarning() << "English translation file not found";

O atributo m_mpTranslators é um mapa simples que relaciona a string do locale com o tradutor: std::map<QString, QTranslator*> m_mpTranslators;
Comment: Que versão do QT você usa, e de onde vem o _Translator_? Eu vejo `mpTranslators`, mas aonde e como essa variável recebe o _Translator_?
Comment: Desculpe @bigown. Já corrigi. :)
Comment: @MarcosZolnowski, eu editei a pergunta pra incluir as informações que você solicitou. Como eu disse, as traduções funcionam corretamente para a interface gráfica. Não funcionam apenas para os textos extraídos via chamada QApplication::tr().
Comment: Downvote por não escrever Qt seria pior @bigown :)
Answer: O problema realmente decorreu de uma falha (erro meu, sorry!) na atualização dos arquivos de tradução (*.qm) no diretório de destino do build. No arquivo .pro não haviam instruções para a cópia automatizada das traduções para os diretórios de destino, e por isso os testes utilizavam uma versão anterior das traduções (que eu havia manualmente copiado, provavelmente). Isso resultou na incorreta exibição dos textos independentemente do contexto utilizado.
Para solucionar o problema definitivamente, eu alterei o arquivo .pro para incluir nas configurações de release e debug a cópia automatizada dos arquivos para os diretórios corretos:
. . .

copyfiles.commands += @echo Copying translation files... &

# Configurações para Windows
win32{

    . . .

    # Troca '/' por '\' nos diretórios de origem e destino
    SOURCE_WIN = $${PWD}
    SOURCE_WIN ~= s,/,\\,g
    TARGET_WIN = $${OUT_PWD}
    TARGET_WIN ~= s,/,\\,g

    debug_and_release {
        CONFIG -= debug_and_release
        CONFIG += debug_and_release
    }

    # Configurações de debug
    CONFIG(debug, debug|release) {
        CONFIG -= debug release
        CONFIG += debug

        . . .

        copyfiles.commands += @call copy $${SOURCE_WIN}\\*.qm $${TARGET_WIN}\\debug\\
    }

    # Configurações de release
    CONFIG(release, debug|release) {
        CONFIG -= debug release
        CONFIG += release

        . . .

        copyfiles.commands += @call copy $${SOURCE_WIN}\\*.qm $${TARGET_WIN}\\release\\
    }

}

# Inclui os comandos de cópia das traduções na execução do QMake
QMAKE_EXTRA_TARGETS += copyfiles
POST_TARGETDEPS += copyfiles

. . .

Comment: Eu não esperava por isso, mas o único indicador é a data de modificação do arquivo, porque não se pode simplesmente abrir o arquivo no editor de texto.
Comment: Por favor, marque a resposta para o seu problema (embora tenha sido você mesmo que postou). Isso permitirá que todos saibam que seu problema foi resolvido sem precisar ler o tópico.
Comment: @RenatoUtsch: Obrigado pela dica. Já fiz como sugerido.
Answer: Eu uso uma versão mais antiga, mas pelo que entendi, a chamada do TR na sua classe está errada.
A documentação fala que se sua classe não é sub-classe de QObject, use TR de QCoreApplication:

If the quoted text is not in a member function of a QObject subclass,
  use either the tr() function of an appropriate class, or the
  QCoreApplication::translate() function directly

A questão é: de que jeito você chama ela?
Abaixo o exemplo da documentação:
 qApp->translate("LoginWidget", "Password:"),
             logwid);

Acho interessante que este exemplo acima deve usar uma instancia de QApplication, e ele usa translate em vez de TR.
Comment: Acabei de fazer um teste. Estava até bastante esperançoso porque a sua resposta faz bastante sentido. Troquei todas as chamadas de QApplication::tr() para qApp->translate() com um contexto diferente (ficou assim, por exemplo: qApp->translate("EmotionData", "Aperture of Left Eye"), com o contexto "EmotionData"). Retraduzi algumas frases pra teste (cheguei até a apagar os arquivos .qm e recompilar tudo), e infelizmente não funcionou.
Comment: Pode dizer se chamando `qApp->translate("EmotionData", "Aperture of Left Eye")` logo depois `UpdateUI()` funciona? Pode ser que você tenha que cadastrar manualmente os termos, ou ele quer outro contexto. Mas sabendo se funciona logo após a chamada, já ajuda bastante a entender o problema.
Comment: Fiz o teste com QString s = qApp->translate("EmotionData", "Aperture of Left Eye"); qDebug() << "s = " << s; logo depois da chamada de UpdateUI(). O resultado é sempre em inglês (o que está no código), independentemente do locale.
Comment: Aliás, o que você quis dizer com "cadastrar manualmente os termos"? :)
Comment: Manualmente seria editar manualmente os arquivos *.TS (que não recomendo), melhor usar a técnica do `QT_TR_NOOP()`. Pois é, deveria ter vindo o texto certo nesse teste, você regerou todos os *.qm?
Comment: Sim, regerei. :( Eu conferi os arquivos .ts e até abri os arquivos .qm gerados pra ver se o conteúdo em pt_br estava lá (e eles aparentemente estão corretos. Mas não acho mesmo que o problema esteja na geração desses arquivos.
Comment: Existe esse contexto "EmotionData"? nos arquivos *.TS? Porque decidi fazer testes de todo tipo, com `TR`, `translate`, direto na MainWindow.ui, e rodando o `lupdate` todas funcionaram.
Comment: Sim, existe. O meu processo é bem padrão: depois de alterar o código (adicionando novas strings, por exemplo), eu exeucuto o lupdate. Vou lá na ferramenta Linguist do Qt e traduzo o que tem de novo. Então, executo o lrelease pra gerar os arquivos .qm. Dai vou no QtCreator e recompilo tudo (pra garantir, rodo qmake de novo antes de fazer o rebuild).
Comment: Também fiz testes usando as mais diversas formas de tradução. O código sempre compila bem, não dá erro de execução, só que não traduz! :)
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11917/discussion-between-marcos-zolnowski-and-luiz-vieira)
Comment: Só pra constar aqui, o problema foi devido a uma falha minha na atualização dos arquivos .qm nos diretórios de destino. Eu adicionei uma resposta com o que eu fiz pra corrigir de vez. Por favor, desculpem pela bobagem. :) De todas as formas, +1 pela ajuda! Obrigado!


Adding custom methods to Laravel 5 scheduler

Question: I'm wondering what the best way to add things like weekends to the available schedule constraints:
Illuminate\Console\Scheduling\Event.php
public function weekdays()
{
    return $this->spliceIntoPosition(5, '1-5');
}

and its logical opposite:
public function weekends()
{
        return $this->days(array( '0','6'));
}

Where would I include these things so that they're not overwritten with a framework update?
Answer: First of all, if all you are missing is the weekends() method, you can achieve that by calling days(6,7) on your event.
If you need to add some more logic to the scheduler, please go on reading.
I had a look at the code and while Laravel doesn't offer a way to extend the Scheduler, and specifically its scheduled Events, with additional methoods, it's still possible to apply additional constraints from your Kernel::schedule().
Depending on your needs, there are 2 ways to do it.

If you want to set some custom CRON expression for an event, you can simply use its cron() method:
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        //scheduled code
    })->cron('0 1 2 * * *')->daily();
}

If you need to apply some CRON constraints using existing methods, but need to modify it later the way weekdays() does using spliceIntoPosition, you can access it by calling getExpression(), modify it, and then set using cron().
protected function schedule(Schedule $schedule)
{
    $event = $schedule->call(function () {
        //scheduled code
    });

    $scheduledAt = $event->getExpression(); //get cron expression

    ...; //modify the $scheduledAt expression

    $event->cron($scheduledAt); // set the new schedule for that even
}

If you want to reuse the logic for multiple events, you can add helper functions in your Kernel.php, e.g.:
    protected function specialSchedule(\Illuminate\Console\Scheduling\Event $event) {
      $scheduledAt = $event->getExpression();

      ...; // modify $scheduledAt expression

      $event->cron($scheduledAt);

      return $event;
    }

Then you can reuse that logic when defining the schedule:
    protected function schedule(Schedule $schedule)
    {
        $this->specialSchedule($schedule->call(function () {
            //scheduled code
        }));
    }

UPDATE:
There is one more way to do that - a bit more complex, as it requires you to provide your own Schedule and Event classes, but also more flexible.
First, implement your own Event class and add there the new methods:
    class CustomEvent extends \Illuminate\Console\Scheduling\CallbackEvent {
      public function weekends() {
        return $this->days(6,7);
      }
    }

Then your own Schedule class, so that it creates CustomEvent objects:
    class CustomSchedule extends \Illuminate\Console\Scheduling\Schedule
    {
      public function call($callback, array $parameters = [])
      {
        $this->events[] = $event = new CustomEvent($callback, $parameters);

         return $event;
      }

      public function exec($command, array $parameters = [])
      {
        if (count($parameters)) {
          $command .= ' '.$this->compileParameters($parameters);
        }

        $this->events[] = $event = new Event($command);

        return $event;
      }
   }

Lastly, in your Kernel.php you need too make sure your new schedule class is used for scheduling:
    protected function defineConsoleSchedule()
    {
      $this->app->instance(
        'Illuminate\Console\Scheduling\Schedule', $schedule = new Schedule
      );

      $this->schedule($schedule);
    }

Comment: Yeah, I'm well aware of the built in cron method, I was just wondering where I'd make a ->weekends() method, or specifically for my use: ->holiday(), which would of course be many days that are not always static in a numerical sense, ie. Thanksgiving, or not always on a set day (Dec. 25th). I was hoping to find a way to just call them like the normal ->weekdays() command.
Answer: Folowing @jedrzej.kurylo's answer, i did this on laravel 5.8:
php artisan make:model CustomCallbackEvent
php artisan make:model CustomEvent
php artisan make:model CustomSchedule
In CustomCallbackEvent:
use Illuminate\Console\Scheduling\CallbackEvent;
use Illuminate\Console\Scheduling\EventMutex;

class CustomCallbackEvent extends CallbackEvent
{
    public function __construct(EventMutex $mutex, $callback, array $parameters = [])
    {
        parent::__construct($mutex, $callback, $parameters);
    }
}

In CustomSchedule:
use Illuminate\Console\Scheduling\Schedule;

class CustomSchedule extends Schedule
{
    public function call($callback, array $parameters = [])
    {
        $this->events[] = $event = new CustomCallbackEvent(
            $this->eventMutex,
            $callback,
            $parameters
        );

        return $event;
    }

    public function exec($command, array $parameters = [])
    {
        if (count($parameters)) {
            $command .= ' '.$this->compileParameters($parameters);
        }

        $this->events[] = $event = new CustomEvent($this->eventMutex, $command, $this->timezone);

        return $event;
    }
}

In CustomEvent:
use Illuminate\Console\Scheduling\Event;

class CustomEvent extends Event
{
    public function myFunction()
    {
        //your logic here
    }
}

In Kernel.php:
protected function defineConsoleSchedule()
    {
      $this->app->instance(
        'Illuminate\Console\Scheduling\Schedule', $schedule = new CustomSchedule
      );

      $this->schedule($schedule);
    }

Answer: The Illuminate\Console\Scheduling\Event class uses the Macroable trait. It means that you can dynamically add methods to the class without inheriting it.
First of all you have to register it in the boot method:
use Illuminate\Console\Scheduling\Event;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Event::macro(
            'weekends',
            function () {
                /** @var Event $this */
                return $this->days([0, 6]);
            }
        );
    }
}

Then you can use it as any other method:
$schedule->command('do-work')->weekends();

For more details about macros see https://asklagbox.com/blog/laravel-macros


What are the possible return codes of bpf_filter(), in FreeBSD kernel? What does each return codes mean?

Question: What are the possible return codes of bpf_filter(), in FreeBSD kernel?
What does each return codes mean?
The man page (link) is not clear on this issue.
The bpf_filter() function executes   the filter program starting at pc on
     the packet pkt. The wirelen argument is the length of the  original
     packet and buflen is the amount of data present.  The buflen value of 0
     is special; it indicates that the pkt is actually a pointer to an mbuf
     chain (struct mbuf *).
Return Values
The bpf_filter() function returns -1 (cast to an unsigned integer)  if there is no filter.  Otherwise, it returns the result of the filter program.
I am getting 65535 when there is a Match and 0 when there is no match. Not sure what is the meaning for the return value 65535.
Can someone please explain the return code of bpf_filter() in detailed?
Answer: The return value of bpf_filter() is the result of the filter program. The result being number of bytes of the packet being filtered to be copied to the buffer for the task (the filter return instruction value).
The value will be 0 if the packet does not match the filter.
If the packet matches the filter it will be the snapshot length (snaplen) that was defined in the pcap_open_ call.
The default value is 65535 bytes as the maximum size of a TCP packet is 64K (65535 bytes).
Answer: The function bpf_filter() takes a pointer to a struct containing the BPF instructions as an argument (pc on the man page) and runs these on the packets to filter them.

The bpf_filter() function returns -1 (cast to an unsigned integer) if
  there is no filter.

We can check in the source code that when pc, the structure that should contain the BPF instructions, is null, then bpf_filter() immediately returns -1, cast to a u_int:
if (pc == 0)
    /*
     * No filter means accept all.
     */
    return (u_int)-1;

[Edited] Internally, for a signed integer, -1 would be stored as "the maximal value for a integer, minus one". With 32 bits, since the return value here is cast to an unsigned integer, that would be 2^32 - 1.
Since the return value here is cast to an unsigned integer, this is the value you obtain: 65535 equals to 2**16 - 1, so -1 cast to a unsigned 16 bit-long integer (a u_int). So I would tend to believe that when you see this 65535 value, you do not actually provide any BPF program to the function? Would that be consistant with you observations?
Now when there is a match:

Otherwise, it returns the result of the filter program.

The result value of bpf_filter() is the result retreived from the BPF program. So when you get a 0 return value, it means that:

Either your BPF program completed and returned 0.
Or possibly (even though this does not seem documented in the man page), an error was encountered while running the BPF program. Here is an example, also from the source:
case BPF_ALU|BPF_DIV|BPF_X:
    if (X == 0)
        return 0;
    A /= X;
    continue;

"In the case of an arithmetic division, if the denominator X is null, then make bpf_filter() return 0, else divide register A by register X and carry on to the next instruction".
[Edited] (see comments) As you found out, the same applies for the 65535 value: it is the value you made your BPF program return.
Comment: Thanks for your explanation.

u_int bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)

you could see from above that the return value is of type " u_int" so its 32bit unsigned integer. when you cast -1 to unsigned 32 bit integer, then it is: 4294967295.

More over I have put few traces around "if(pc == 0)" block, where "-1" is returned. And from those traces I could see that it is not going to this "if" block at all.

I guess it should return the packet length in success case, but it is returning 65535 everytime when the match is hit.(my pkt len is 78)
Comment: Hmm I do not see why it would print the packet length anyway, it should be BPF return value. Since you can debug the function, then could you tell which "return" statement in `bpf_filter()` is actually used? Maybe that could help. Also, would that be possible to provide the BPF program you are using?
Comment: I found the issue, bpf_filter() is returning 65535 because I had specified 65535 for pcap open, as below:
pcap_open_dead(DLT_EN10MB, 65535);

Now, bpf_filter() returning 1, after replacing 65535 with 1.

Qeole, Thanks for your answer. It helped me in getting more clarity..
Comment: @KrishnamRajuraju: Great! That makes sense indeed. Happy to know I could help :-).


What's the purpose of making a "below slot" high round draft pick?

Question: This question applies to Major League Baseball, where teams have an "allowance" on which they can spend for players in various slots.
In the first round, the Pittsburgh Pirates surprised many people, when the selected high school short stop, Cole Tucker, with the 24th overall pick when at least some would say that Michael Chavis (26th overall) was better at that spot.
As I (and others) suspected, Tucker was signed for $1.8 million, $125,000 less than the slot "allowance." Most of this difference was used to sign pitcher Mitch Keller with an above slot bonus in the second round.
Why would a team "skimp" on the first round in order to use the money in the second round? Aren't most of the impact players in the first round, meaning that you get the "biggest bang for the buck" there? And if the Pirates wanted Keller so badly, why not just draft him in the first round (Tucker was a relative unknown who might have lasted into the second round)?
Answer: It is hard to speak for a team, know what their strategy is going into a draft.
In my opinion the Pirates didn't like certain players in the spot they were picking as much as other teams/scouts may have projected there.  For one reason or another they decided that they could save money by drafting another player and paying him below his slotted value.  Saving this money may allow them to save money for later rounds, as well as sign undrafted free agents.
Here is a story about the Minnesota Twins landing a undrafted player with a lot of potential.
No matter where you are picked in the draft, it is tough to make it to the MLB club. Story
Answer: Drafting has changed dramatically with the new collective bargaining agreement. There are really great reasons to pick under slot players early in the draft.
First, a bit on how the draft slotting system works. Each draft position in the first ten rounds has a dollar value assigned. The first pick in the draft is worth a certain dollar amount, the last pick in the tenth round is worth significantly less money.
The dollar values for the picks a team controls are summed together to form a teams "bonus pool". They can use this money to sign all of the players they draft. If you exceed this pool you must pay penalties. The first 10% is just monetary penalties, if you spend more than 10% you start forfeiting future draft picks (which also means less bonus pool money in the following years). There is a great primer here on draft slots and the penalties.
Any player a team drafts after the tenth round may be signed for up to $100k without counting against their bonus pool. However, any amount they spend over 100k does count against their pool from the first 10 rounds.
Here's the thing. The first four or so draft slots are huge, significantly larger than the other draft slots. So if a team drafts a player in one of those slots who they know will sign for less money, they get to save a ton of money to be able to draft high risk players in the later rounds and offer them larger bonuses than other teams would be able to.
This is important for several reasons:

First, if a player is a highschool graduate, a large bonus may lure them away from their college commitment (or if they are a junior, it may entice them to leave school early).
It allows you to draft hard to sign players in the first ten rounds, earlier than other teams. There is an emerging strategy to draft hard to sign players after the start of the 10th round, so that you get the free 100k, and so that if you fail to sign the player, the money for the slot is not lost (As it would be if you drafted them in rounds 1-9).

Basically, if you draft under slot early, it allows you to get more better talent by drafting guys over slot late.
Brett Taylor, who covers the Cubs on his blog Bleacher Nation, has written several articles on the Cubs' use of this draft strategy. Here's his article about the Cubs' top pick in 2014, a significantly underslot signing that allowed the Cubs to have one of the years best drafts.
To address the specific case you mention. It's probably two things. First the talent falls of pretty hard after about the first ten picks every year. So most likely they had a few guys at that level who they liked, and everything else being equal, you take the guy you can sign for less money (so you can sign another good player later).
The other factor is that the draft can be a real crapshoot. Sure you want to get the sure thing superstars, but there might only be 5 of those in a given draft. So you stock up on highish level guys. There might not be a lot of seperation between three or four guys one of whom might sign below slot. You pick the guy who will sign low.


Generic function ensuring the type of a given value matches the type defined a Record for the given key

Question: Please let me know if this is a duplicate, but I can't find an answer to this. Maybe because I'm missing the right words to search for as you can see in the title :/
Is it possible to define a generic function in TypeScript that receives two arguments (a key and a value) and verifies that the type of the given value matches the type defined in a Record type depending on the given key? This may sound confusing. Let me give you a simple example:
import { setAttribute } from './attribute_helper'

type Human = {
  name: (name: string) => void
  age: (age: number) => void
}

function setName(name: string): void {
  // ...
}

setAttribute<Human>('name', setName) // valid
setAttribute<Human>('age', setName) // invalid

// should work with a different Record type:
setAttribute<Cat>('food', giveFood)

Here's how this would work if one specific Record type can be used in the definition of the function:
type Human = {
  name: (name: string) => void
}

function setAttribute<T extends keyof Human>(key: T, value: Human[T]): void {
}

function setName(name: string): void {
  // ...
}

setAttribute('name', setName)

But in my case, setAttribute is imported from a different file and needs to work with different Record types it doesn't know about at definition time. It needs to be typed when it is called.
Here's a sketch which unfortunately is not valid TypeScript, but it may help to illustrate the problem:
// attribute_helper.ts
export function setAttribute<T>(key: keyof T as V, value: V): void {
}

Comment: I think [this approach](https://tsplay.dev/w11ZKw) is the closest you can get; your function wants to be generic in both `T` and `K extends keyof T`, and you want the compiler to infer `K` while you manually specify `T`.  But TS doesn't have such partial type parameter inference.  See https://stackoverflow.com/a/60378737/2887218 for more information.  If you have control over `setAttribute` I'd probably prefer the curried version to the dummied version.  Let me know if you want me to write up an answer.
Comment: Note that there is [a `Record utility type`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype) in global scope so a type named `Record` is not advisable.  I'd suggest some other name, especially in SO example code (where people searching for `Record` are looking for something else)
Comment: Nice! I actually tried currying but could not get it right. Thank you so much. Please write up an answer and I'll gladly accept it.
Comment: Good advice. I'll change the example. The code is just a simplified version of what I tried to achieve. I'm not actually calling types Record :) Was just trying to make clear it's a Record type.
Answer: Conceptually, what you want is a function like
function setAttribute<T, K extends keyof T>(key: K, value: T[K]): void { }

which is generic both in the type of the record ou'd call it like
setAttribute<MyRecord>('name', setName); // want it to be okay, but error!

Unfortunately, this is not valid TypeScript.  You can't manually specify some generic parameters (like putting MyRecord in for T in this case) and have the compiler infer the rest of them (like inferring "name" for K in this case).  That would require partial type parameter inference as requested in microsoft/TypeScript#26242.  Right now it's not possible.
It might be tempting to try to use generic parameter defaults to get this behavior, like
function setAttribute<T, K extends keyof T = keyof T>(key: K, value: T[K]): void { }

but while this does let setAttribute<MyRecord>('name', setName) compile, it does not work the way you want; the K type parameter will not be inferred from key; instead it will simply use the default, which is keyof T in this case, which is not what you want.  You want K to be "name" so that the compiler could accept setName but reject setAge for the second parameter.
So right now this is not possible.  A single generic function requires callers to either manually specify all its type parameters, or let the compiler infer all its type parameters.

The workarounds I know of are either to pass in a dummy parameter of type T so that the compiler can infer both T and K:
function setAttributeDummy<T, K extends keyof T>(dummyT: T, key: K, value: T[K]): void { }

const dummyRecord: MyRecord = null!;
setAttributeDummy(dummyRecord, 'name', setName) // valid
setAttributeDummy(dummyRecord, 'age', setName) // invalid

Or to make a curried function that lets you manually specify T and returns another function that infers K:
function setAttributeCurry<T>(): <K extends keyof T>(k: K, v: T[K]) => void {
    return (k, v) => {
        /* your impl here */
    }
}

setAttributeCurry<MyRecord>()('name', setName); // valid
setAttributeCurry<MyRecord>()('age', setName); // invalid

This works, but is awkward looking and repetitive.  If you're going to use a curried function you might as well use it just once for any particular value of T, like this:
const setMyRecordAttribute = setAttributeCurry<MyRecord>();

setMyRecordAttribute('name', setName); // valid
setMyRecordAttribute('age', setName); // invalid

And then again for any other value like
const setSomeOtherAttribute = setAttributeCurry<{ a: string, b: number }>();
setSomeOtherAttribute('b', 123); // okay
setSomeOtherAttribute('a', 123); // error

Playground link to code
Comment: Thank you so much for taking the time to respond quickly and for writing up this excellent answer!


copy folders from one team project to another

Question: i have one TFS server, with 4 team projects in it. i want to copy folders of of one team project into another team project.
here's the tree -

TFS(Server)
 |___ A1(Team project1)
 |___ A2(Team project2)
         |______________(Folder1)
         |______________(Folder2)
         |______________(Folder3)
         |______________(Folder4)
 |___ A3(Team project3)
 |___ A4(Team project4)

I want to copy folders in A2(TeamProject2)-->(Folder2) only to A1(Team Project1)
How do i do this?
Answer: I think source control explorer has a copy option on the right click menu.  This question might get a better response on StackOverflow though.


Escrever uma linha em arquivo texto sem usar instrução de repetição, é possível?

Question: Preciso escrever um arquivo texto a partir de um DataSet em C#, sendo assim ficara algo como:
string[] lines = {"First line", "Second line", "Third Line"}
using(StreamWriter outputFile = new StreamWriter(docPath)){
   foreach(string line in lines){
       outputFile.WriteLine(line);
   }
}

Até aí tudo bem, porém, eu possuo várias colunas em um DataSet e preciso colocá-las em apenas uma linha delimitando por ponto e vírgula. Teria como fazer isso sem concatenar strings?
Vi alguns códigos onde o pessoal coloca "Append()" para concatenar com o delimitador, porém acredito que tenha uma forma de escrever a linha passando apenas o DataSet e um delimitador, alguma biblioteca, qualquer coisa que faça isso de forma mais simplificada, que deixe o código mais limpo e flexível a diferentes layouts.
Se não for possível fazer isso com arquivos texto (*.txt), seria possível fazer com CSV?
Comment: è e não é, depende da definição, ou do que quer, mas precisa saber porque precisa ser assim, o que tem de errado em fazer desta forma? Isso nada tem a ver com arquivos ou seu tipo.
Comment: Precisa porque eu quero algo simples, limpo.
Comment: Já ficou claro que não precisa. Mais simples e limpo do que isso? Acho difícil. Pode perder performance?
Comment: Quanto a performance não sei, até porque não testei de outras formas sem ser com o Loop. Só que eu vejo assim cara, sou eu que estou programando, então no mínimo quem precisa saber se eu necessito ou não sou eu mesmo kkkk. A pergunta vai ficar em aberto porque eu acredito que tenha algo parecido com o que eu quero, obrigado pela sua atenção.
Answer: Bom, uma alternativa se você quer "evitar loopings" visíveis no seu código é utilizar o string.Join(String, String[]). Porém por de baixo dos panos ele fará mais operações do que as já existentes no seu trecho de código.
O que ele fará é um loop em seu string[], adicionando uma string de separação entre os elementos (o que no seu caso é uma quebra de linha) e concatenar tudo em uma única string.
string[] lines = { "First line", "Second line", "Third Line" };

using (StreamWriter outputFile = new StreamWriter(docPath))
{
    string text = string.Join("\r\n", lines);
    outputFile.Write(text);
}

Comment: @L.Gustavo Seria interessante você postar a sua solução como resposta então.
Comment: Agradeço a ajuda, acabei por utilizar o Loop mesmo, consegui fazer de uma forma simples ocupando apenas 4 linhas onde o arquivo é estruturado de acordo com um layout, ficou muito bom.


Understanding uber startup screen reporter code

Question: I am React Native engineer trying to understand/learn objective c.
I was going through Uber Startup screen reporter code, and have some difficulties understanding the code
Here is the code sample they have shared
Can someone explain me the flow of code?
What I have been doing (not sure if it is correct).
In AppDelegate.h, Added notification relay
@property (nonatomic, strong) UBApplicationStartupReasonReporterNotificationRelay *notificationRelay;

In AppDelegate.mm
I have added these delegate they shared..
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self.notificationRelay updateApplicationStateNotification:[NSNotification notificationWithName:UIApplicationDidBecomeActiveNotification object:nil]];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [self.notificationRelay updateApplicationStateNotification:[NSNotification notificationWithName:UIApplicationWillResignActiveNotification object:nil]];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [self.notificationRelay updateApplicationStateNotification:[NSNotification notificationWithName:UIApplicationWillTerminateNotification object:nil]];
}

then I created a new Cocoa Touch class and add this code there (inside shared instance), something like this.
- (instancetype)init
{
    if (self = [super init]) {

      // Determine whether the app crashed on a prior launch
      BOOL crashedOnPriorLaunch = false;

      // Initialize a storage mechanism implementing UBApplicationStartupReasonReporterPriorRunInfoProtocol
      id<UBApplicationStartupReasonReporterPriorRunInfoProtocol> runInfo = ...

      // Initialize the notification relay
      id<UBApplicationStartupReasonReporterNotificationRelayProtocol> = [[UBApplicationStartupReasonReporterNotificationRelay alloc] init]

      // Initialize the startup reason reporter
      UBApplicationStartupReasonReporter *startupReasonReporter = [[UBApplicationStartupReasonReporter alloc] initWithPreviousRunDidCrash:crashedOnPriorLaunch
              previousRunInfo:runInfo
              notificationRelay: notificationRelay
              debugging:[UBBuildType isDebugBuild]];

      // Profit
      UBStartupReason startupReason = startupReasonReporter.startupReason;

    }
    return self;
}

[Question:]
I am not sure how is the value of UBStartupReason startupReason = startupReasonReporter.startupReason;  going to update? For example we have applicationDidBecomeActive and applicationWillResignActive which are two separate event.
Comment: The point is you are supposed to do something with the `startupReason` variable once it has a value. In your case you don't do anything with it.  The value it has was set during the startup process or as a result of one of the notifications being posted in the app delegate methods. . You need to structure your code so that you re run the "profit" code when you need to know the most recent startup reason
Answer: If you see the code in github link that is provided, the startupReasonReporter.startupReason is updated based on the previousRunInfo data whenever startupReasonReporter is instantiated with initWithPreviousRunDidCrash with the previousRunInfo (or runInfo in your case) when the app is run the next time.
You have to use below public method to get the runInfo instance which is
/**
 *  Returns the prior run information stored to disk at the given directory URL.
 *  @param directoryURL The directory to use to to store the startup reason data.
 *  @return the previous startup reason data if it was present on disk, or empty startup reason object.
 */
+ (nonnull instancetype)priorRunAtDirectoryURL:(nullable NSURL *)directoryURL;

The way you are initializing runInfo seems to be incorrect.
You have to do something like below:
id<UBApplicationStartupReasonReporterPriorRunInfoProtocol> runInfo = [[UBApplicationStartupReasonReporterPriorRunInfo] alloc] priorRunAtDirectoryURL:<yourDirectoryURL>];

These delegates applicationDidBecomeActive, applicationWillResignActive and applicationWillTerminate whenever called will just update the runInfo for the current run which will be store in a file in directory that you have provided in <yourDirectoryURL> in above call and the data will be retrieved from this file into startupReasonReporter.startupReason when the app is run next time.
Every time when you run the app the previous run data will be retrieved and startupReasonReporter.startupReason is set based on the data available in previousRunInfo
Comment: If this clarifies your question. Please accept the answer


Can I use UIBezier to draw an oval progress bar

Question: How to draw oval with start and end angle in swift?
Just like the method that I use init(arcCenter:radius:startAngle:endAngle:clockwise:)
to draw a circle with a gap.
I tried to use init(ovalln:) and the relation of the bezier Curve and ellipse to draw an oval with a gap.
However, it only came out with a perfect oval eventually.
How can I draw an oval with a gap like the image below? thanks!
Answer: May or may not work for you, one approach is to draw an arc leaving a gap and then scaling the path on the y-axis.
Arcs begin with Zero-degrees (or radians) at the 3 o'clock position. Since your gap is at the top, we can make things easier by "translating" degrees by -90, so we can think in terms of Zero-degrees being at 12 o'clock... that is, if we want to start at 20-degrees (with Zero at the top) and end at 340-degrees, our starting angle for the arc will be (20 - 90) and the ending arc will be (340 - 90).
So, we begin by making a circle with a bezier path - startAngle == 0, endAngle == 360:

Next, we'll adjust the start and end angles to give us a 40-degree "gap" at the top:

Then we can scale transform that path to look like this:

and, how it will look without the "inner" lines:

Then, we overlay another bezier path, using the same arc radius, startAngle and scaling, but we'll set the endAngle as a percentage of the full arc.
In the case of a 40-degree gap, the full arc will be (360 - 40).
Now, we get this as a "progress bar":

Here's a complete example:
class EllipseProgressView: UIView {

    public var gapAngle: CGFloat = 40 {
        didSet {
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    public var progress: CGFloat = 0.0 {
        didSet {
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    public var baseColor: UIColor = .lightGray {
        didSet {
            ellipseBaseLayer.strokeColor = baseColor.cgColor
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    public var progressColor: UIColor = .red {
        didSet {
            ellipseProgressLayer.strokeColor = progressColor.cgColor
            setNeedsLayout()
            layoutIfNeeded()
        }
    }

    private let ellipseBaseLayer = CAShapeLayer()
    private let ellipseProgressLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    private func commonInit() -> Void {
        backgroundColor = .black

        layer.addSublayer(ellipseBaseLayer)
        layer.addSublayer(ellipseProgressLayer)

        ellipseBaseLayer.lineWidth = 3.0
        ellipseBaseLayer.fillColor = UIColor.clear.cgColor
        ellipseBaseLayer.strokeColor = baseColor.cgColor
        ellipseBaseLayer.lineCap = .round

        ellipseProgressLayer.lineWidth = 5.0
        ellipseProgressLayer.fillColor = UIColor.clear.cgColor
        ellipseProgressLayer.strokeColor = progressColor.cgColor
        ellipseProgressLayer.lineCap = .round
    }

    override func layoutSubviews() {
        var startAngle: CGFloat = 0
        var endAngle: CGFloat = 0
        var startRadians: CGFloat = 0
        var endRadians: CGFloat = 0
        var pth: UIBezierPath!

        startAngle = gapAngle * 0.5
        endAngle = 360 - gapAngle * 0.5

        // totalAngle is (360-degrees minus the gapAngle)
        let totalAngle: CGFloat = 360 - gapAngle

        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = bounds.width * 0.5

        let yScale: CGFloat = bounds.height / bounds.width

        let origHeight = radius * 2.0
        let ovalHeight = origHeight * yScale

        let y = (origHeight - ovalHeight) * 0.5

        // degrees start with Zero at 3 o'clock, so
        //  translate them to start at 12 o'clock
        startRadians = (startAngle - 90).degreesToRadians
        endRadians = (endAngle - 90).degreesToRadians

        // new bezier path
        pth = UIBezierPath()

        // arc with "gap" at the top
        pth.addArc(withCenter: center, radius: radius, startAngle: startRadians, endAngle: endRadians, clockwise: true)

        // translate on the y-axis
        pth.apply(CGAffineTransform(translationX: 0.0, y: y))
        // scale the y-axis
        pth.apply(CGAffineTransform(scaleX: 1.0, y: yScale))

        ellipseBaseLayer.path = pth.cgPath

        // new endAngle is startAngle plus the percentage of the total angle
        endAngle = startAngle + totalAngle * progress

        // degrees start with Zero at 3 o'clock, so
        //  translate them to start at 12 o'clock
        startRadians = (startAngle - 90).degreesToRadians
        endRadians = (endAngle - 90).degreesToRadians

        // new bezier path
        pth = UIBezierPath()

        pth.addArc(withCenter: center, radius: radius, startAngle: startRadians, endAngle: endRadians, clockwise: true)

        // translate on the y-axis
        pth.apply(CGAffineTransform(translationX: 0.0, y: y))
        // scale the y-axis
        pth.apply(CGAffineTransform(scaleX: 1.0, y: yScale))

        ellipseProgressLayer.path = pth.cgPath

    }

}

And an example view controller to try it out -- each tap will increase the "progress" by 5% until we reach 100%, and then we start over at Zero:
class EllipseVC: UIViewController {

    var progress: CGFloat = 0.0

    let ellipseProgressView = EllipseProgressView()

    let percentLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black

        ellipseProgressView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(ellipseProgressView)

        // respect safe area
        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([
            // constrain 300-pts wide
            ellipseProgressView.widthAnchor.constraint(equalToConstant: 300.0),
            // height is 1 / 3rd of width
            ellipseProgressView.heightAnchor.constraint(equalTo: ellipseProgressView.widthAnchor, multiplier: 1.0 / 3.0),
            // center in view safe area
            ellipseProgressView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            ellipseProgressView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
        ])

        // base line color is lightGray
        // progress line color is red
        // we can change those, if desired
        //  for example:
        //ellipseProgressView.baseColor = .green
        //ellipseProgressView.progressColor = .yellow

        // "gap" angle default is 40-degrees
        // we can change that, if desired
        //  for example:
        //ellipseProgressView.gapAngle = 40

        // add a label to show the current progress
        percentLabel.translatesAutoresizingMaskIntoConstraints = false
        percentLabel.textColor = .white
        view.addSubview(percentLabel)
        NSLayoutConstraint.activate([
            percentLabel.topAnchor.constraint(equalTo: ellipseProgressView.bottomAnchor, constant: 8.0),
            percentLabel.centerXAnchor.constraint(equalTo: ellipseProgressView.centerXAnchor),
        ])

        updatePercentLabel()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // increment progress by 5% on each tap
        //  reset to Zero when we get past 100%
        progress += 5
        if progress.rounded() > 100.0 {
            progress = 0.0
        }
        ellipseProgressView.progress = (progress / 100.0)
        updatePercentLabel()
    }

    func updatePercentLabel() -> Void {
        percentLabel.text = String(format: "%0.2f %%", progress)
    }
}

Please note: this is Example Code Only!!!


Rewriting FTC to look like Stoke's Thm

Question: The Fundamental Theorem of Calculus states
$\int_{a}^{b} f' \ = f(b)-f(a)$
If I define $\frac{df}{dx}:=f'$ and $\int_{a}^{b} f \, dx \ := \int_{a}^{b} f \ $, then I can rewrite above as
$\int_{a}^{b} \frac{df}{dx} \, dx\ = f(b)-f(a)$
Note that I have not defined or assigned any meaning to the terms $df$ or $dx$ individually. If I ignore this important fact and I make the non-rigourous step of simply crossing out the $dx$s, the left hand side becomes
$\int_{a}^{b} df \ $
which looks like the left hand side of the generalized Stokes's theorem, which we know reduces in this case to exactly FTC. So my question is, is there any mathematical meaning to what I did by crossing out the $dx$s? If so, is crossing out the $dx$s "correct" in the context of that meaning? And what actually does the $df$ that I am left with mean?
I am especially curious because it seems that the correct interpretation, especially in the context of the expression looking like Stokes's theorem, is that $df$ is the differential of $f$ (which if I understand correctly is its derivative, although please note I have not learned differential forms). However, we already defined the derivative of $f$ to be $\frac{df}{dx}$, not $df$.
Comment: It's not quite clear what kind of answer you are expecting. On one hand you say this loooks like Stokes' theorem, on the other hand you say you don't know differential forms. The FTC is indeed a special case of Stokes' theorem, but in order to understand this, I'm afraid you probably need differential forms.
Comment: You're integrating the differential 1-form $df=f'dx$. Stokes's theorem applied to this case is the FTC.
Comment: Welcome to MSE! <> (i) The differential $df$ (a "1-form") is not the derivative $f'$ (a "function"), because (as you note) the differential contains a "$dx$". (ii) The name _differential calculus_ refers to formal computational procedures for working with "infinitesimal" expressions such as $df$ and $dx$. (iii) These entities ($dx$ etc.) have precise mathematical definitions, and the formal manipulations have precise, provable interpretations, but one can _do calculus_ without knowing either, see for example Sylvanus Thompson's _Calculus Made Easy_.
Answer: $\newcommand{\bd}{\partial}$The Calculus on Manifolds interpretation of the fundamental theorem of calculus is:
Let $n = 0$. If $a$ and $b$ are real numbers with $a < b$, the closed interval $M = [a, b]$ is an $(n+1)$-manifold with boundary, whose boundary $\bd M = \{b\} - \{a\}$ is the $n$-manifold comprising two points, the left endpoint $a$ with negative orientation and the right endpoint $b$ with positive orientation.
"Integrating" a $0$-form (smooth function) over an oriented $0$-manifold means evaluation multiplied by the sign induced by the orientation.
If $f$ is a smooth $n$-form, i.e., a smooth, real-valued function on $M$ (er, I mean $[a, b]$), then
\begin{align*}
  \int_{a}^{b} f'(x)\, dx
  &= \int_{[a, b]} df \\
  &= \int_{M} df \\
  &= \int_{\bd M} f \\
  &= \int_{\{b\} - \{a\}} f \\
  &= \int_{\{b\}} f - \int_{\{a\}} f \\
  &= f(b) - f(a).
\end{align*}
This is not a good way to explain the FTC to a calculus student, but it's a fine private realization to have when you study differential forms and integration on manifolds.

Rewriting FTC to look like Stoke's Thm


Add pagination to the results in custom module after split the row to many sub rows

Question: I try to build new module (Drupal 7), in some page I show the results to the user as a table like the following:
<?php
    $header = 'bla bla bla'; //header come here
    $query = db_select('myTable', 't')
        ->fields('t', array('field_1', 'start_date', 'end_date', 'due_date'))
        ->extend('TableSort')
        ->extend('PagerDefault');

    $result = $query
        ->limit(10)
        ->orderBy('t.startdate')
        ->execute();

    foreach ($result as $row) {
        $rows[] = array('data' => (array) $row);
    }

    $form['tablesort_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('Sorry, there is no results to show'),
    );
?>

and this of course works perfectly (each page has 10 rows), but for some reasons I have to split each row to multi sub row according to the start date and end date like the followin
foreach ($result as $row) {
    $timeInLoop = $row->start_date;
    while($timeInLoop < $row->end_date){
        //split the row to multi row (one week for each row)
        $timeInLoop = strtotime(date("Y-m-d", $timeInLoop) . " +1 week");
        $row->due_date = date("Y-m-d", $timeInLoop);
        $rows[] = array('data' => (array) $row);
    }
}

and here is my problem:
if some row has 10 weeks and other row has 2 weeks the total rows in the page will be more than 10 rows
how can I make them 10 rows in each page ???
thank you for your help
Answer: I find the solution here
$limit = 10;
$rows = pager_array_splice($rows, $limit);
$form['tablesort_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Sorry, there is no results to show'),
);

function pager_array_splice($data, $limit = 10, $element = 0) {
    global $pager_page_array, $pager_total, $pager_total_items;
    $page = isset($_GET['page']) ? $_GET['page'] : '';
    // Convert comma-separated $page to an array, used by other functions.
    $pager_page_array = explode(',', $page);
    // We calculate the total of pages as ceil(items / limit).
    $pager_total_items[$element] = count($data);
    $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
    $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
    return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}


Odoo auto-fill fields when created from other form

Question: Any idea how I can fill in some fields on the product page when I quick create this from a Sales Order. These fields are based on the Sales Order (name and customer). Do I need to pass them with context?
Thanks
Comment: Could you explain in detail what you want and what you have done so far.
Answer: Yes, it can be done with context. In your sale.order.line XML views, you have a Many2one field named product_id (it points to product.product model).
You have to specify the default value you want for each product.product field, extracting the value for the fields of the current view (sale.order.line):
<xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_field_1': field_1, 'default_field_2': field_2}</attribute>
</xpath>

Where default_field_1 and default_field_2 are fields of the product.product model, and field_1 and field_2 are fields of sale.order.line model.
Example:
<xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_name': name}</attribute>
</xpath>

In the above case, when you create a new product (clicking on the create option of the dropdown of the Many2one field product_id) from sale.order.line tree or form view, the product.product form would be opened with the name field automatically filled in with the name of the current sale order line.


Encrypt function for CryptoJs decrypt function

Question: I have next code that was copied from the right answer here:
public static String decrypt(String cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] saltData = Arrays.copyOfRange(cipherData, 8, 16);

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, saltData, secret.getBytes(StandardCharsets.UTF_8), md5);
        SecretKeySpec key = new SecretKeySpec(keyAndIV[0], "AES");
        IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);

        byte[] encrypted = Arrays.copyOfRange(cipherData, 16, cipherData.length);
        Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decryptedData = aesCBC.doFinal(encrypted);
        String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);

        return decryptedText;
    }

How can I write encrypt function for this in Java? I tried something like this, but it doesn't work:
public static String encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, getNextSalt(), secret.getBytes(StandardCharsets.UTF_8), md5);
        SecretKeySpec skeySpec = new SecretKeySpec(keyAndIV[0], "AES");
        IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(plainText.getBytes());

        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static byte[] getNextSalt() {
        byte[] salt = new byte[8];
        RANDOM.nextBytes(salt);
        return salt;
    }

Comment: `encrypt` must return the data in OpenSSL format, i.e. the first 8 bytes are the ASCII encoding of `Salted__`, then comes the 8 bytes salt and then the actual ciphertext, the whole stuff is Base64 encoded after its concatenation. The salt is generated randomly. As far as I can see, your `encrypt`-method lacks the conversion to this OpenSSL format. By the way, the OpenSSL format is insecure and not a standard, [here](https://security.stackexchange.com/a/29139).
Comment: Can you write your answer with code, please? I'll give you the right answer. Thank you.
Answer: The encrypt-method must return the data in OpenSSL format, which consists of the ASCII encoding of Salted__, followed by the 8 bytes randomly generated salt and the actual ciphertext, whereby the data are Base64 encoded after their concatenation.
Note, however, that the key derivation function used for the OpenSSL format is insecure and is not a standard, here. A possible extension of the encrypt method could be:
public static String encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

    byte[] salt =  getNextSalt();
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, salt, secret.getBytes(StandardCharsets.UTF_8), md5);
    SecretKeySpec skeySpec = new SecretKeySpec(keyAndIV[0], "AES");
    IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(plainText.getBytes());

    byte[] prefix = "Salted__".getBytes(StandardCharsets.US_ASCII);
    byte[] prefixSaltEncrypted = new byte[prefix.length + salt.length + encrypted.length];
    System.arraycopy(prefix, 0, prefixSaltEncrypted, 0, prefix.length);
    System.arraycopy(salt, 0, prefixSaltEncrypted, prefix.length, salt.length);
    System.arraycopy(encrypted, 0, prefixSaltEncrypted, prefix.length + salt.length, encrypted.length);

    return Base64.getEncoder().encodeToString(prefixSaltEncrypted);
}


Android in app billing using external payment processor

Question: If I have web and android app that share same data and user can sync between them, but I deicide to charge for "premium" features which can include storing pictures and other stuff which take space on the servers outside android, can I charge for those features (on subscription bases) on the web and unlock them automatically in android while subscription is running without getting banned from the play store?
Also can I also use some other mobile payment processor, for example paypal to charge for that subscription directly from android app if it will unlock the features on both web and android app?
This is what I have found relevant in the developer content policies :

In-app purchases: Developers offering virtual goods or currencies
  within a game downloaded from Google Play must use Google Play's
  in-app billing service as the method of payment. Developers offering
  additional content, services or functionality within another category
  of app downloaded from Google Play must use Google Play's in-app
  billing service as the method of payment, except: where payment is
  primarily for physical goods or services (e.g., buying movie tickets,
  or buying a publication where the price also includes a hard copy
  subscription); or where payment is for digital content or goods that
  may be consumed outside of the app itself (e.g., buying songs that can
  be played on other music players). Developers must not mislead users
  about the apps they are selling nor about any in-app services, goods,
  content or functionality they are selling. If your product description
  on Google Play refers to in-app features to which a specific or
  additional charge applies, your description must clearly notify users
  that payment is required to access those features.
Answer: In simple word if your app is the only thing you got, you must go through google payment service but if you are selling your service through multiple environments(desktop/ios/windows mobile) and Android is one of it you are ok.
Example; CBS app, where once you pay you can watch shows in desktop, Android or in iOS platform and they use third payment processors.
But, if you are selling your app through a third party payment service, it is not ok. For example, you developed a Chess game app which can be downloaded free from Play store. But after the download user have to pay and you are collecting payment using third party payment service like Paypal. This same goes for any other app features or digital contents.
In one of the place i worked where my company was selling app to end user. We have the same app for Android, Desktop and Windows mobile. When a user is paying for Android app they will not got Desktop version for free or Windows Mobile version. There were separate license agreements for each app and user have to pay for each license separately. I remember on that instance our company lawyer suggested we should distribute our app outside Play store.
But finally i will recommend you to consult a legal expert who understand digital content policies. Better safe then sorry.
Comment: in your comment `I remember on that instance our company lawyer suggested we should distribute our app outside Play store.` it means that if we distribute our app outside Play Store, are we free of the 30% fee for subscriptions, for example?


Como verificar o retorno de uma função

Question: Galera montei uma função que executa a classe phpmailer e envia um e-mail. Porém não sei como verificar o retorno dela e saber se o e-mail foi enviado. Bom segue a função:
    function envia_email($destinatario) {

        // Aqui fica todos os dados da função

        // Envia o e-mail
        $email->Send();
    }

O que envia o e-mail e esse comando $email->Send();.
E eu chamo a função assim:
envia_email($destinatario);

Bom, como eu faço para saber se deu true ou false?
Answer: É preciso analisar a biblioteca que esta utilizando, dê uma olhada na documentação dela e veja o retorno de send().
Porém, caso esteja utilizando PHPMailer que é de costume geral utilizar você pode observar aqui:

Creates message and assigns Mailer. If the message is not sent successfully then it returns false. Use the ErrorInfo variable to view description of the error. Returns true on success, false on failure.

Este método ele retorna true ou false para o envio. Sendo assim, você pode utilizar este retorno.
function envia_email($destinatario) {

    // Aqui fica todos os dados da função

    // Envia o e-mail
    return $email->Send(); // true or false
}

$retorno = envia_email($destinatario);

if($retorno === false){
   throw new Exception('Email não foi enviado.');
}

Simples.
Comment: ok, funcionou 100% muito obrigado
Answer: Ela retorna True ou False:
if(!$Email->Send()) {
   echo A mensagem não foi enviada.";
   echo Mensagem de erro: " . $Email->ErrorInfo;
} else {
    echo "Mensagem enviada!";
}

Mais detalhes do funcionamento da classe aqui:
http://www.devmedia.com.br/enviando-e-mail-com-o-phpmailer/9642
Comment: eu sei, mas o que eu quero e verificar com a função, ou seja que o `$Email->Send()` retome false ou true na função entendeu.
Answer: Eu uso esse código, funciona bem e relata os erros.
if(!$email->Send()) :
$mensagemRetorno = 'Erro ao enviar formulário: '. print($email->ErrorInfo);
else :
echo"";
endif;

Comment: eu sei, mas o que eu quero e verificar com a função, ou seja que o `$Email->Send()` retome false ou true na função entendeu.

Como verificar o retorno de uma função


Combinations question - why is my approach wrong?

Question: I'm learning Permutations and Combinations and while trying to solve this simple question, I stuck on the solution:-
From a group of 7 men and 6 women, five persons are to be selected to form a committee so that at least 3 men are there on the committee. In how many ways can it be done?
The solution was to consider all three possibilities one by one- 3 men and 2 women, 4 men and 1 women, all 5 men. Calculate the combinations for each case and add them.
But I was trying it from a different approach- Firstly select 3 men from 7 (gives 35 combinations) and multiply it with the combinations of selecting 2 more committee members from 10 remaining members. So my answer came out to be 35 x 45 = 1575. But the answer is 756 which is not even a multiple of 35. So is my approach wrong? Why so?
Answer: If you first select 3 men and then fill up with two arbitrary people, then you count each combination with exactly three men once, but others are counted repeatedly. For example, you count all-male committees 10 times, once for each way to choose the three first men in retrospect from the final five men.
Smaller numbers example: Given John, Jack and Jill, form a committee of two people with the constraint that the committee must have at least one man. Actually, there are three such committees possible (because the constraint is no constraint at all).
But your method would give four: First select John as male, then select either Jack or Jill as second. Or first select Jack as male, then select John or Jill as second. The committee "Jack and John" is counted twice by you.
Comment: I don't understand your first paragraph, but your second paragraph, with the simpler example, was very helpful. Thanks.
Answer: You're counting every committee with $4$ men $\binom43=4$ times: if the men are A, B, C, and D, and the woman is F, you're counting it once with A, B, and C as the first $3$ and D and F as the extra $2$, once with A, B, and D as the first $3$ and C and F as the extra $2$, once with A, C, and D as the first $3$ and B and F as the extra $2$, and once with B, C, and D as the first $3$ and A and F as the extra $2$.
Similarly, you're counting every committee with $5$ men $\binom53=10$ times: if the men are A, B, C, D, and E, you're counting the committee once with A, B, and C as the first $3$ and D and E as the extra $2$, and so one for every possible $3$-$2$ split of the five men.
Only the committees of $3$ men and $2$ women are counted correctly, exactly once each.
Since some committees are counted once, some four times, and some ten times, you don't even get an answer that's related to the correct one in some very simple way, as you would if, for example, you counted every committee twice. From the correct answer you know that there are $525$ committees with $3$ men, $210$ with $4$ men, and $21$ with $5$ men, and sure enough,
$$525+4\cdot210+10\cdot21=1575\;,$$
your answer.
Answer: You interpretation seems to right unlike your calculation
as
$$\binom 73\cdot\binom 62+\binom 74\cdot\binom 61+\binom 75\cdot\binom 60=35\cdot15+35\cdot6+21\cdot1=756$$
Comment: This was the actual solution given in the book. I tried it differently and wanted to know why was I wrong? There was a difference in approach to the solution. Thanks btw :-)


Accessing form's resources (resx file) from code

Question: If I have a form Frm1.cs that is using some icons, images or other resources, these resources get stored in the form's resx file (Frm1.resx).
My simple question is how do I access these resources from code?
As a workaround I can store these resources in the Project resource file and they will be available via Properties.Resources.resourcename.
However, similar syntax does not work for the resources stored in the form's resource file.
While searching for a solution I have come across several references to  ResourceManager class but was not able to find a way to use that to access the form's resources...
Comment: Did you see the answer here: http://stackoverflow.com/questions/19465405/access-the-value-from-resource-file-programmatically
Answer: The way to access local form resources is through an instance of ResourceManager.
Suppose you got two PictureBox in a Form called Frm1:
var resources = new ResourceManager(typeof(Frm1));
var image = (Bitmap)resources.GetObject("pictureBox1.Image");

pictureBox2.Image = image;

Hope this could help you...
Answer: If you use visual studio designer to add resources, you get a class Resources with static properties to access them.
To access:
this.pictureBox1.Image = Properties.Resources.MyResourceImage;

Answer: Building on Harold Coppoolse's answer, Visual Studio (speaking from 2022 Community) has some nice automation when it comes to accessing any given Form's resources.
Edit Resource file
With every Form created in Visual Studio, there should be an associated .resx generated along with it (if an item with a Text property is inserted, for example.) When you open the .resx file in the Designer tool, there's an Access Modifier: option. Change it to the most restrictive permission possible in your language (there should be no reason to use Public), and this will generate a FormName.Designer.code extension file underneath the .resx file.
What's happening in the background?
In the background, Visual Studio is using ResGen.exe to generate the strongly-typed resource class to accompany the .resx file. What this does is create a class in the namespace specified by the Custom Tool Namespace .resx file property, with:

A parameterless constructor, which can be used to instantiate the strongly typed resource class.

A static (C#) or Shared (Visual Basic) and read-only ResourceManager property, which returns the ResourceManager instance that manages the strongly typed resource.

A static Culture property, which allows you to set the culture used for resource retrieval. By default, its value is null, which means that the current UI culture is used.

One static (C#) or Shared (Visual Basic) and read-only property for each resource in the .resources file. The name of the property is the name of the resource.-

This means that, in code, you simply use *Namespace*.*FormClassName*.*ResourceName* to access any resource you need. No extra code is required on your part.


Can't decode utf-8 string in python on os x terminal.app

Question: I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:
>>> wtf = u'\xe4\xf6\xfc'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> wtf = u'\xe4\xf6\xfc'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

Anyone know what I'm doing wrong?
Comment: [This](http://stackoverflow.com/questions/368805/python-unicodedecodeerror-am-i-misunderstanding-encode/370199#370199) answer in a related question about encoding/decoding might be of help.
Answer: I think there is encode/decode confusion all over the place. You start with an unicode object:
u'\xe4\xf6\xfc'

This is an unicode object, the three characters are the unicode codepoints for "äöü". If you want to turn them into Utf-8, you have to encode them:
>>> u'\xe4\xf6\xfc'.encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

The resulting six characters are the Utf-8 representation of "äöü".
If you call decode(...), you try to interpret the characters as some encoding that still needs to be converted to unicode. Since it already is Unicode, this doesn't work. Your first call tries a Ascii to Unicode conversion, the second call a Utf-8 to Unicode conversion. Since u'\xe4\xf6\xfc' is neither valid Ascii nor valid Utf-8 these conversion attempts fail.
Further confusion might come from the fact that '\xe4\xf6\xfc' is also the Latin1/ISO-8859-1 encoding of "äöü". If you write a normal python string (without the leading "u" that marks it as unicode), you can convert it to an unicode object with decode('latin1'):
>>> '\xe4\xf6\xfc'.decode('latin1')
u'\xe4\xf6\xfc'

Comment: aha. This finally makes sense.
Answer: I think you have encoding and decoding backwards. You encode Unicode into a byte stream, and decode the byte stream into Unicode.
Python 2.6.1 (r261:67515, Dec  6 2008, 16:42:21)
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> wtf = u'\xe4\xf6\xfc'
>>> wtf
u'\xe4\xf6\xfc'
>>> print wtf
äöü
>>> wtf.encode('UTF-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
>>> print '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8')
äöü

Comment: Um. UTF-8 is an already encoded byte stream, so, while not backwards, you got it sideways at least :) Perhaps you meant Unicode instead of UTF-8. I'll edit your post and let you decide.
Answer: >>> wtf = '\xe4\xf6\xfc'
>>> wtf
'\xe4\xf6\xfc'
>>> print wtf
���
>>> print wtf.decode("latin-1")
äöü
>>> wtf_unicode = unicode(wtf.decode("latin-1"))
>>> wtf_unicode
u'\xe4\xf6\xfc'
>>> print wtf_unicode
äöü

Answer: The Unicode strings section of the introductory tutorial explains it well :

To convert a Unicode string into an 8-bit string using a specific encoding, Unicode objects provide an encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.
>>> u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

Comment: aren't you decoding characters then in your last line?
Comment: Yep, I've removed my fatigued-wrongness, the unicode strings section explains it better than I can..


$location.search().name and base href breaks application URL - Need Guidance

Question: I have a angular app and my URL seems http://localhost:8080/personal?name=xyz and i'm using $location.search().name to get xyz in js.
My code as follows..
app.js
app.config(function ($locationProvider) {
$locationProvider.html5Mode({enabled:true});
});

app.controller('myController', function($location) {
var name = $location.search().name;
alert(name); // xyz

index.html
<base href="/" />

the functionality is working well but it breaks my URL to localhost:8080, how to set my base href to get localhost:8080/personal
Comment: Please provide a [mcve]
Comment: https://docs.angularjs.org/guide/$location
Comment: i have tried  and  but nothing seems working. How to get URL like localhost:8080/home
Answer: I got the solution as desired by changing my $location.path from my controllers and templateUrl's on routeProvider


find all complex numbers $z$ such that $\mid 2z/(z^2+1) \mid < 1$

Question: I need to find all complex numbers $z$ such that $\mid 2z/(z^2+1) \mid < 1$. If $z$ were real, it would be easy, but now that $z$ being complex numbers makes things so twisted...I cannot find a way to approach. Could anyone please help me?
Comment: Compare https://math.stackexchange.com/q/2149074/42969 – the same inequality just with opposite sign.
Answer: If you substitute $z=x+iy$ into this inequality then square both sides you should get
$$x^4+y^4+2x^2y^2-2x^2-6y^2+1\gt0$$
$$(x^2+(y-1)^2-2)(x^2+(y+1)^2-2)\gt0$$
So we need
$$z\in\{x+iy:x^2+(y-1)^2-2\gt0\land x^2+(y+1)^2-2\gt0\}\cup\{x+iy:x^2+(y-1)^2-2\lt0\land x^2+(y+1)^2-2\lt0\}$$


PHP Warning: PHP Startup: Unable to load dynamic library 'php_fileinfo.dll'

Question: Good morning,
I'm struggerling to understand the below error. I believe it was caused when i migrated a cPanel account from one WHM to another.
I'm currently running Laravel but my log files are repeatedly growing with the same error.
<code>[02-Jun-2020 10:46:47 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'php_fileinfo.dll' (tried: /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
</code>
Has anyone experienced this before? or no of how i can resolve it...
Regards
Ross
Comment: Does this answer your question? [How to enable php\_fileinfo extension in PHP?](https://stackoverflow.com/questions/28981576/how-to-enable-php-fileinfo-extension-in-php)
Answer: You may be missing a library. See this related question:
How to enable php_fileinfo extension in PHP?

If you have cpanel just go to

Select PHP Version

and search for the extension

fileinfo

check it and you're good to go.
Comment: Hello thanks for getting back to me.

I have it enabled already via WHM for PHP version 7.3. I believe what is happening here is it's being referenced elsewhere...
Comment: Hey no probs :). Have you enabled it for both the `cli` and `fpm`?