How to validiate for a solely alphabetic string with spaces in PHP?

Question: I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
Comment: Replace spaces with a number before checking?
Comment: @DanRedux that only works if the string doesn't contain numbers beforehand.
Comment: Why? If it contains numbers beforehand, it'll return false correctly. If it contains numbers after, it'll return false correctly.. The only thing it will do is treat spaces as bad tokens by turning them into bad tokens.
Comment: @DanRedux you misread the question. The OP wants to _accept_ strings that contain spaces; the problem with `ctype_alpha` is that it does not.
Comment: Ohhh. Then change spaces to the letter 'a'? :P
Answer: $is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));

or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);

Comment: Thanks a lot. I like the first one. I am just wondering for learning purposes, how do you know about that first one? Because I cannot even tell by the documentation.
Comment: It's not one function. It uses `str_replace()` to remove spaces and then `ctype_alpha()` to check that the result of that is alphabetical.
Comment: I do understand, though how do you know about it, when the ctype page in the documentation does not point it out (that you can do that), or does it? I can not tell.
Comment: @Carpet you have to think about what you want to accomplish and sometimes you have to accomplish it in steps. You ask yourself, "If `ctype_alpha` doesn't allow spaces, what can I do about that?" The answer is that you can remove the spaces before you pass it to `ctype_alpha` so you go looking for something that will do that. If you look at the **Return Values** section of the manual entry for `str_replace`, you see that it returns a string with the replaced values. So you can pass the return value of `str_replace` to `ctype_alpha`.
Comment: It's worthwhile to browse the PHP manual. The function names are often self-explanatory. There is a list of all the functions for that section in the sidebar of each page and there is a list of related functions in the **See Also** section. Plus, most pages have user-contributed code and help.
Comment: Note that this regular expression will allow an empty string and a string with just spaces. That may or may not be the desired result.
Comment: I can't make single character edits but you have one too many ) in the first example.
Answer: if (preg_match("^/[a-zA-Z ]+$/", $input)) {
    // input matches
}

Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
Comment: Though be aware that `[a-z]` can [match different characters depending on the system's locale settings](http://stackoverflow.com/questions/1930487/will-a-z-ever-match-accented-characters-in-preg-pcre).
Comment: There is a typo in the regex. It should start with `/^` rather than `^/`.
Comment: Note that this regular expression will allow a string with just spaces. That may or may not be the desired result.
Answer: ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Comment: This falls under the category of **If you don't need fancy replacing rules, you should always use `str_replace` instead of `preg_replace`.**
Answer: Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
    if ($spaceAllowed) {
        $valueToValidate = str_replace(' ', '', $valueToValidate);
    }
    if (strlen($valueToValidate) == 0) {
        return true;
    }
    return ctype_alpha($valueToValidate);
}

Answer: I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
  //your code here
}

The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.


A relation between Lebesgue and Riemann integrable functions

Question: Is it true that a bounded function $ f:[a,b]\to \mathbb{R} $ is Lebesgue integrable if and only if there exists a function $f_1:[a,b]\to \mathbb{R}$ that is Riemann integrable and
$$  m^*\lbrace x: (f-f_1)(x)\ne 0\rbrace =0 $$
One side of the above assumption is true and obvious.
Answer: No. Take $f=1_A$, where $A$ is a measurable set with the property that both $A$ and $A^c$ have positive measure intersection with any interval (See for example, Construction of a Borel set with positive but not full measure in each interval). It is not too hard to see that modification on a null set $N$ cannot make such an $1_A$ continuous a.e. (because $A\setminus N$ and $A^c\setminus N$ must accumulate at every point).


Probability of guessing correct pair with 2 dice

Question: We have an office discussion going.
What is the probability of correctly guessing a pair of 6 sided dice? Meaning 3-2 and 2-3 count as the same pair.
Thanks!
Comment: Depends on your guess.  $(2,3)$ is $\frac 2{36}$.  $(1,1)$ is $\frac 1{36}$.  (there are two ways to get $(2,3)$, as you point out, but only one way to get $(1,1)$).
Comment: It depends on how you guess.   What is the probability that you pick, the ordered pair $(x,y)$ for any $1\leq x\leq y\leq 6$.  Do you: write all pairs on pieces of paper and draw from a hat?  Do you roll your own pair of dice?  Do you use your mother's cousin's next-door-neighbour's daughter's favourite pet's birthdate?
Answer: Assuming a pair of fair 6 sided dice the probability of every $6 \cdot 6 =36$ distinct results are equal. When you do not take order into account it depends on your guess. Guessing (1,1),(2,2),...,(6,6) will all have a $\frac{1}{36}$ probability of being correct. Since only one of the 36 outcomes corresponds to the guess. If you guess distinct numbers your probability will be $\frac{2}{36}=\frac{1}{18}$ since for distinct numbers there are two combinations out of 36 outcomes that are considered correct.
Answer: $\dfrac{1}{36}$ if you are picking pairs, like $(2,2)$.
$\dfrac{1}{18}$ if you are picking numbers like $2$ or $3$ without the order of appearance mattering.


How to theme PDF generated by Print module?

Question: I would like to theme the PDF generated by the Print module. I would like to add header, footer, margins, border to the generated PDF.
The certificate module in Drupal provides theming to the certificate, but my site is almost like a read and get certified site, so I wish not to change print module.
I tried the form alter and other stuffs, but not sure from where the PDF can be changed.
Comment: http://www.blog.yamandi.com/print-module-drupal-generate-pdf
Comment: Have u tried TCPDF?
Comment: If you want to theme pdf as per your site design, then you need to use `wkhtmltopdf` to generate pdf template.
Comment: @Harshal : Yes I am using TCPDF, but still I am not sure where the contents get generated in the PDF. There exits no hook or alter to explain this.
Comment: @JayendraKainthola: I am using TCPDF, that should work. But still I will try the wkhtmltopdf.
Comment: @Gladiator, as per my understanding, TCPDF does not support your custom css.
Comment: @JayendraKainthola: I am partially aware about the lack of CSS support in TCPDF, but it does provides some API type of function to theme. Hence I am sticking to TCPDF.
Comment: YOu should go through this link http://www.tcpdf.org/doc/code/classTCPDF.html
Comment: @Gladiator, Ok. I have not worked with `TCPDF`, so not aware about this.
Answer: You should on your creation of node call a function which will generate a pdf.
Use tcpdf class for it generate pdf and download  tcpdf functions./
Check also the link
 class my_pdf extends TCPDF { //Page header public function Header() { } // Page footer public function Footer() { } }

$pdf = new my_pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, UTF-8', false);

$pdf->setPrintHeader(true);
 $pdf->setPrintFooter(true);
$pdf->SetMargins(25.0, 40, 25.0);
$pdf->SetFooterMargin(1.5);
$pdf->SetAutoPageBreak(TRUE, 50);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('my_document.pdf', 'D');

Comment: @Gladiator have u tried this?
Comment: Not yet will try now and will keep you updated. Thanks for the code.
Comment: check the link for the explanation..
Answer: Print module comes with a print-pdf.tpl.php template as well as a print.tpl.php template (or use the one in your theme).
Since this is all about styling, rather look at editing these and put them in your theme folder.
Answer: Drupal 7 allows to alter how content is rendered with theme_print_pdf_tcpdf_content(). This should be fairly simple: Just place this hook in the template.php file, and add a new function where the PDF file is rendered. Use the following code as reference.
function theme_print_pdf_tcpdf_content(&$vars) {
  return new_function_that_prints_the_content($vars);
}

Answer: It's actually possible using a hook for TCPDF:
/**
 * Implements hook__print_pdf_tcpdf_alter()
 */
function MODULENAME_print_pdf_tcpdf_alter($pdf, $html, $meta) {
  $pdf->setPrintHeader(FALSE);
  $pdf->SetPrintFooter(FALSE);
}


Intel JCC Erratum - what is the effect of prefixes used for mitigation?

Question: Intel recommends using instruction prefixes to mitigate the performance consequences of JCC Erratum.
MSVC if compiled with /QIntel-jcc-erratum follows the recommendation, and inserts prefixed instructions, like this:
3E 3E 3E 3E 3E 3E 3E 3E 3E 48 8B C8   mov rcx,rax ; with redundant 3E prefixes

They say MSVC resorts to NOPs when prefixes are not possible.
Clang has -mbranches-within-32B-boundaries option for this, and it prefers nop, multi-byte if needed (https://godbolt.org/z/399nc5Msq notice xchg ax, ax)
What are the consequences of 3E prefixes, specifically:

Why does Intel recommend this, and not multi-byte NOPs?
What are the consequences for unaffected CPUs?
Reportedly, a program runs faster with /QIntel-jcc-erratum on AMD, what could be possible explanations?
Comment: A NOP is a separate instruction that had to decode and go through the pipeline separately.  [What methods can be used to efficiently extend instruction length on modern x86?](https://stackoverflow.com/q/48046814).  You should always pad instructions with prefixes to achieve desired alignment, not insert NOPs.  Probably Intel considered it worth the effort since this would actually be *inside* inner loops, not just a NOP outside an inner loop.
Comment: IIRC, the GNU toolchain does mitigation in the assembler, so look for an `as` option (that you could get GCC to use with `-Wa,-...`)  GCC doesn't know instruction sizes, it only prints text. That's why it needs GAS to support stuff like `.p2align 4,,10` to align by 16 if that will take fewer than 10 bytes of padding, to implement the alignment heuristics it wants to use.  (Often followed by `.p2align 3` to unconditionally align by 8.)
Comment: But note that some CPUs don't efficiently decode more than 3 prefixes on one instruction, so that might be why *this* strategy for JCC-erratum mitigation isn't on by default.  You'd want to distribute the padding over multiple previous instructions to avoid bottlenecks on Silvermont-family such as Gracemont (e.g. Alder Lake E-cores which have suddenly made that family a lot more mainstream-relevant).  I forget about AMD decode limits.
Comment: Found blog post where they mention size impact as 3% and perf impact as _negligible_: https://devblogs.microsoft.com/cppblog/jcc-erratum-mitigation-in-msvc/
Comment: That blog is saying that *on affected CPUs* (I think only Intel Skylake-family), using the compiler option makes the performance about the same as before the microcode update without the compiler option.  It's not saying anything about its impact on other CPUs, like Silvermont/Goldmont.  (I checked Agner Fog's microarch guide, and AMD Zen has no problem with any number of prefixes on a single instruction, like mainstream Intel since Core2.  AMD Bulldozer-family has a "very large" penalty for decoding instructions with more than 3 prefixes, like 14-15 cycles for 4-7 prefixes.)
Comment: clang prefers NOPs, here `xchg ax,ax` is two byte nop: https://godbolt.org/z/399nc5Msq . Can't find gcc option, apparently it does not exist and gcc does not mitigate this issue.
Comment: They say: _We also measured that the performance impact of /QIntel-jcc-erratum switch on processors that are not affected by the erratum is negligible. However, as codebases vary greatly, we advise developers to evaluate the impact of /QIntel-jcc-erratum in the context of their applications and workloads._  however, the set of not affected processor to test is indeed not specified, and may be very limited, also: _The content of this blog was provided by Gautham Beeraka from Intel Corporation._
Comment: Oh, I missed that part.  I wouldn't be surprised if they only measured on other mainstream Intel CPUs, though, not AMD at all.  (Given that "we" is Intel.)  It's somewhat valid to consider Bulldozer-family obsolete enough to not care much about it, although there are still some APU desktops and laptops around for sure, but they'd certainly show large regressions in loops where the compiler put 4 or more prefixes on one instruction inside a hot inner loop (including existing prefixes like REX or 66h).  Much worse than the 3% for MITE legacy decode on SKL.
Comment: Agner says Goldmont / Goldmont can handle instructions with up to 4 prefixes, so that's a bit more capable than Silvermont.  So perhaps there's been more improvement in Tremont, or at least in Alder Lake E-cores (Gracemont), if they tested those microarchitectures at all.
Comment: @PeterCordes, I've expanded my answer to add another related MSVC option. `/Os` optimizes for smaller code size. Among other things, it suppresses jump table generation, and loop aligning, so it asks for this issue to happen more often. Apparently there are no documented options in MSVC to have finer control, on each size/speed tradeoff. The good part is that removing `/Os` is not expected to be harmful on AMD
Comment: Aligning the tops of loops (by 8 or 16) isn't super closely related to whether the conditional branch at the bottom touches a 32B boundary.  IDK what the distribution of loop sizes is in typical programs.  If you've seen in practice that `/Os` tends to do worse, that's interesting.  (A single indirect jmp is better than a sequence of cmp/jcc for avoiding this, though, and for reducing the necessary front-end throughput in case you do hit it.  And modern CPUs have good indirect branch prediction.)
Comment: I've noticed this for some amount of very small loops, beyond 16b, which are not prevalent, but mostly affected by the issue.
Answer: A NOP is a separate instruction that had to decode and go through the pipeline separately.  It's always better to pad instructions with prefixes to achieve desired alignment, not insert NOPs, as discussed in What methods can be used to efficiently extend instruction length on modern x86? (but only in ways that don't cause major stalls on some CPUs which can't handle large numbers of prefixes).
Perhaps Intel considered it worth the effort for toolchains to do it this way for this case since this would actually be inside inner loops, not just a NOP outside an inner loop.  (And tacking on prefixes to one previous instruction is relatively simple.)

I now have some data point. The result of benchmarking for /QIntel-jcc-erratum on AMD FX 8300 is bad.
The slowdown is by a decimal order of magnitude for a specific benchmark, where the benefit on Intel Skylake for the same benchmark is about 20 percent. This aligns with Peter's comments:

I checked Agner Fog's microarch guide, and AMD Zen has no problem with any number of prefixes on a single instruction, like mainstream Intel since Core2. AMD Bulldozer-family has a "very large" penalty for decoding instructions with more than 3 prefixes, like 14-15 cycles for 4-7 prefixes

It's somewhat valid to consider Bulldozer-family obsolete enough to not care much about it, although there are still some APU desktops and laptops around for sure, but they'd certainly show large regressions in loops where the compiler put 4 or more prefixes on one instruction inside a hot inner loop (including existing prefixes like REX or 66h). Much worse than the 3% for MITE legacy decode on SKL.

Though indeed Bulldozer-family is obsolete-ish, I don't think I can afford this much of an impact. I'm also afraid of other CPUs that may choke with extra prefixes the same way. So the conclusion for me is not to use /QIntel-jcc-erratum for generally-targeted software. Unless it is enabled in specific translation units and dynamic dispatch to there is made, which is too much of the trouble most of the time.

One thing that probably safe to do on MSVC is to stop using /Os flag . It was discovered that /Os flag at least:

Avoids jump tables in favor of conditional jumps
Avoids loop start padding

Try the following example (https://godbolt.org/z/jvezPd9jM):
void loop(int i, char a[], char b[])
{
    char* stop = a + i;
    while (a != stop){
        *b++ = *a++;
    }
}

void jump_table(int i, char a[], char b[])
{
    switch (i)
    {
                            case 7:
            a[6] = b[6];    case 6:
            a[5] = b[5];    case 5:
            a[4] = b[4];    case 4:
            a[3] = b[3];    case 3:
            a[2] = b[2];    case 2:
            a[1] = b[1];    case 1:
            a[0] = b[1];    case 0:  break;
            default: __assume(false);
    }
}

This causes running into JCC perf issue more often (avoiding jump tables produces series of JCC, and avoiding alignment makes small loops less than 16b also sometimes touching the boundary)


Envio de formulário apenas com HTML e/ou JS

Question: Galera eu preciso fazer com que quando o usuário clicar no botão "Enviar" automaticamente ele seja redirecionado para outra página com todos os dados digitados pelo usuário como: e-mail, senha, nome, etc(Utilizando método "get").
Acontece que eu tentei fazer e só conseguir redirecionar para a outra página, estando a mesma vazia.
Segue abaixo meu arquivo HTML:

<form action="dados.html" method="post">

  <input type="text" id="cNome" name="tNome" size="20" maxlength="20" placeholder="       Digite Seu Nome"/>

  <input type="email" id"cEmail" name="tEmail" size="30" maxlength="30" placeholder="       Digite Seu E-mail"/>

                <input type="date" id="cData" name="tData"/>

        Filme:
        <select id="cFilmes">
         <option >Transformers: O Último Cavaleiro</option>
            <option >Planeta dos Macacos: A Guerra</option>
            <option >Velozes e Furiosos 8</option>
            <option >Alien: Paradise Lost</option>
            <option >Carros 3</option>
            <option >Logan</option>
        </select>

  <input type="submit" value="Enviar"/>
  <input type="reset" value="Cancelar"/>

 </form>

Segue abaixo a página de redirecionamento:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dados</title>

Sou iniciante nessa área e já tentei ver diversos tutorial pelo youtube mas a maioria é utilizando HTML junto de PHP, JQUERY, JAVA, linguagens que não tenho o mínimo conhecimento, quero que seja apenas utilizando HTML e JS.Dei uma olhada em outras perguntas e já tem parecido mas quero pedir nessa se tiver uma forma mais simples estarem colocando ela pois como sou iniciante não entendi muito bem com as outras perguntas, porém se não tiver outra forma mais simples explicar o mais detalhado possível, ficarei muito agradecido.
Comment: Você quer trafegar informações de uma pagina a outra usando apenas javascript?
Comment: Utilizando HTML e JS, não sei se é possível com apenas um dos dois.
Comment: Na teoria não é o ideal, mas tem como fazer sim
Comment: Como estou começando agora só vou aprender outras linguagens mais na frente,por favor me mostre esse método.
Answer: Após o redirecionamento, o conteúdo da página antiga é apagado. Você não pode mais acessar nenhum elemento via JavaScript. Por isso seu código não funciona.
Os valores enviados por meio de formulários utilizando os métodos POST, GET... são destinados a parte da aplicação que está rodando no lado servidor, por isso não ficam visíveis(diretamente) em outra página HTML.
Porem, após submeter o formulário(redirecionar), você poderá acessar a URL completa através do JavaScript. E dessa forma, obter os dados "fornecidos" via GET para a sua página estática.
Para fazer isso, você primeiramente deverá alterar o método do formulário para GET. Conforme código abaixo:
...
<form action="dados.html" method="get">
...

Na segunda página, você deverá obter e processar a URL, separando os valores. Na versão em inglês desse site, encontrei uma função implementada para este fim:
function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Então o código da sua segunda página deve ficar assim:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Dados</title>

Só mais uma observação. Essa solução é meio gambiarra, pois o que você quer fazer não é muito usual. Nem consigo imaginar o objetivo. Se é iniciante e está aprendendo a programar. Recomendo dar uma olhada nas linguagens server-side.
Comment: O motivo é simples, estou fazendo curso de informática para internet e o professor passou um trabalho para que o usuário possa escolher lugar da cadeira do cinema, ingresso entre outras coisas, e tive essa ideia para aparecer as informações ao usuário.No entanto essas linguagens server-side, é tipo java, php ?
Comment: A função criada fica apenas solta dentro do script ou precisa ser adicionada em algum lugar como em "onClick" por exemplo? Pois coloquei ela como você falou e continua sem aparacer nada, aparecendo os dados na URL da página.


Headers with media

Question: In PHP, it's recommended to send the header before echoing an image or any type of data or media.
The problem I'm having is, what happens when you need to send another header to change the Content-Type back to text?  A definitive rule is you can't send headers after something has been sent out. Can anyone propose a solution?
Comment: Javascript `location.href`?
Comment: Sorry I meant a PHP solution, but you are right. I could use an href and load texts after it.
Comment: I don't think there is another way in PHP, I suggest javascript way `echo '';`
Comment: Or `echo '';`
Comment: If you want to stick with `header`, use `ob_start`
Answer: Headers aren't as dynamic as you seem to think they are. Setting a non-text header Content-Type header, writing some media, and then sending a text header after it, will not have the result you're thinking it does. Each header can only exist once per HTTP request. Within a single request, you'll have to stick to a Content-Type that properly represents the whole request.
Now, if you don't know which header you want to send until further down in the processing, you can always call ob_start();, then do all of your processing and output and whichever header changes you like (ensuring to pass true as the second parameter to header() to overwrite previous values of that same header), and then call ob_end_flush(); to send all of the output to the browser. However, there shouldn't really be a need to change the Content-Type dynamically, as only one will actually be sent to the user.

Headers with media


Time series Algorithm suggestion

Question: I have a univariate timeseries data which is always cumulative. So the trend is always upwards. I want to build timeseries forecast for future forecast. Currently i have 5 different models running: Auto-Arima, Holtswinter, Holtsmethod, FBprophet and LSTM. I want to replace LSTM with a simple timeseries model. Can you suggest me some? I tried searching and tried XGboost and random forest, but output was giving flat forecast
Comment: How did you choose the 5 models that you are running? What is a "simple" time series model? Is ARIMA simple? To do ARIMA right is not a simple task. Is a parametric model simpler than a nonparametric model? Why not take one method - say ARIMA - and understand it well rather than go through the menu of black-box models.
Comment: Given the information from your question, I think it is impossible to give an answer. It would be helpful to know what type of time series you have and further characteristics like ACF, PACF etc.
Answer: I agree with the comment, Xgboost and random forests are NOT anywhere near my definition of 'simple'. And besides, tree models cannot forecast outside of the known data so the known presence of a trend means trees won't work plug-and-play.
For simple time series I would look at naive methods like the last value or if you have a seasonal pulse of 12 then just repeat the last 12 values. Additionally, you can use the mean or median. Although you may want to test with detrending since these are 'flat' forecasts.
I would say the most 'advanced' simple model in my eyes would be early time series decomposition methods such as the classical method (seasonal_decompose in statsmodels) which is just a centered moving average and average seasonal indices.
These methods will probably produce results that minimize your error a surprising amount of times but may not be 'useful' forecasts.
Answer: As you have a time series which is non-stationary, your most important step will be to stationarise the time series as much as possible. It's difficult to recommend precisely without seeing your data but potentially:

Difference the data to make it non-cumulative.
Subtract mean and divide by standard deviation.

Given a more appropriate time series target (and that your problem is univariate), I think the most simple methods would be any autoregressive-based method (e.g. ARIMA).

Time series Algorithm suggestion


How bad is it to have multiple devices with the same SSH server keys?

Question: I am working on an embedded device that runs FreeBSD and SSH.
As you know, sshd likes to randomly generate a set of server keys when it first boots up.  The problem is that we will be shipping the product with a read-only sd-card filesystem (non-negotiable).
My two options as I see them are:

Ship the same sshd server keys on all devices
Mount a memory file system and generate the server keys on each boot (slow...)

Is it a major security problem to ship the same server keys on all devices?  These items will not be directly on the internet.  There will occasionally be multiple devices owned by the same person and on the same network.
Most of the time the device will not be connected to the internet.
Logging in with SSH is not part of normal operation.  It is mostly for the convenience of the programmers and technicians.  Customers will not be logging in to the device with SSH.
What are the ramifications of using the same server keys on multiple hardware devices?
PS could someone please create an internet-of-things tag?
EDIT: I am talking about installing the same host private keys on all servers (devices).  As far as user public/private keys, there are currently no plans to use key based login - it would be password login.  Again, same password on all servers (devices).
I know that this is probably a bad idea.  I'd like to know why precisely it is a bad idea though so I can understand the tradeoffs.
Comment: Sharing the SSH key means that someone who can access the private key on one device can impersonate all of these devices.
Comment: While this is an interesting question, I don't see anything about it that relates to system administration, and is thus off-topic for Server Fault. You're asking about designing an debugging/diagnostic interface for an embedded device that you are shipping, and not an interface that would be relevant to sysadmins. This question could be migrated to [security.se].
Comment: Using same username / password on all devices is a very bad idea. Those are way easier to brute-force than the private key used for public key authentication. Even if these deviced aren't supposed to be directly connected to the internet, someone will do it anyway. And if "not directly connected" means NAT, they are connected enough...
Comment: If you mean the host keys, then users with more than one of your device may get warnings depending on their ssh client configuration.  the bigger concerns would be around actual ssh authentication keys.  Hopefully you are not installing any private keys and hopefully your public keys are restricted to specific source networks and hopefully your private keys owned by your techs have a strong passphrase on them and hopefully those keys are never checked into a repo by mistake.  IoT's are getting a really bad name because of those things.  Not saying you would, just saying that is a big issue.
Comment: I am talking about installing the same host private key on all servers, if that is what you mean.
Comment: Tero, yes, I do mean NAT, can you elaborate on the risks?
Comment: @200_success  It's a question about managing sshd security on a non-PC unix platform.  That seems relevant to me.  However thank you for pointing out the security stackexchange site, I was unaware that it existed.
Answer: Rather than storing host-specific data such as ssh host keys on the SD card or other read-only media, you can store this in NVRAM, which is what it's for on an embedded system. You'll need to do some custom scripting to store and retrieve the keys at boot time, but the scripts will be exactly the same for every device.
Answer: The impact of shipping the same key pair with all your devices is directly related to the security of the clients connecting to them, as it means that there is no way (from an SSH client) to uniquely identify the device it may be connecting to. Should your key pair be leaked, it could be used for MITM attacks.
On the other hand, regenerating the keys on each boot, will also trigger an alert on the clients.
For reference, from man ssh(1):

ssh automatically maintains and checks a database containing identification for all hosts it has ever been used with.  Host keys are stored in ~/.ssh/known_hosts in the user's home directory.  Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts.  Any new hosts are automatically added to the user's file.  If a host's identification ever changes, ssh warns about this and disables password authentication to prevent server spoofing or man-in-the-middle attacks, which could otherwise be used to circumvent the encryption.  The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed.
Comment: I don't understand why they can't just generate once (on each device, at the first boot) then never generate again (unless they are removed)?
Comment: Perfectly doable. But the OP states he/she wants to: 'Mount a memory file system and generate the server keys on each boot'. So my answer assumes that.
Comment: ah yup I missed that when I read it the first time.
Answer: It sounds like in the first option, the SSH keys would be available on the SD card. So any user could take the card and read them out. So basically your private keys have become (mostly) public.
This will allow man-in-the-middle attacks, like the following:

A user sets up a SSH server with the private keys obtained from your device and gives that IP address to your technician.
Your technician inputs the root password over the SSH connection.
The user now knows the root password that is valid for all your devices.

However, you shouldn't be using root passwords in the first place, use ssh keys for authentication instead. Then the impact of shared server keys is pretty small if you only log on from a LAN.
SSH also provides forward secrecy, so an attacker has to be able to setup a false server to benefit from the keys; passively sniffing the traffic will not allow decrypting it.
Comment: @BenVoigt I think that most unix systems do transmit the password to the server. The shadow file stores only a hash, but you don't want to trust a hash generated by the client - because otherwise anyone would be able to login with a stolen hash, without reversing it. So the server has to know the actual password in order to run bcrypt or similar on it.
Comment: It's funny how our preconceptions can blind us (me).  The SD-Card is inside the unit behind a panel and underneath a circuit board, so it never occurred to me that someone would pull it out.  However, you are correct, it absolutely is accessible to anyone with a screwdriver.  Thanks for the reminder to consider the physical security of the system.
Comment: WRT #2, the root password should not be sent over the SSH connection.  It should be input into the terminal client, and used for the local half of an authentication protocol that proves possession of the secret without transmitting the secret ("knowledge proof").  Even decades-old systems knew to send a hash of the password and not the password itself.  Include a nonce in the challenge/response protocol, and the attacker neither knows the original password nor any token that can be used in its place.
Answer: I read this in horror! I who have done multiple machines in the same cluster with the same ssh host key would never dare do this. Do not under any circumstances allow machines with different sets of administrators to share ssh host keys. That way lies madness and screaming horror when you get posted for your lack of security.
Behold I tell you the truth, he who compromises one device compromises all of them. Once obtained one, expect bad people to jump from one to another at will and the security rolled back as though it were thin paper.
Comment: Could you elaborate on how an attacker would use a stolen server private key to compromise other devices?
Comment: @jpa: For host keys, by intercepting and stealing passwords, etc. Also, this setup seems to propose doing the same thing with user keys.
Answer: Since you mention that the SSH access is not used by the end user/customer you may want to turn off SSH access by default and only enable it temporarily when the device is put into "debug" mode.
You can then either ship all the devices with the same key, assuming that you have protected the "debug" mode so it can't be triggered remotely by someone trying to hack the device.
Or you have a new key generated when the device goes into "debug" mode - so you don't have to waste boot-time generating the keys each time the device is powered up.
Comment: I like this idea.
Answer: Here's a sample attack scenario based on the constraints you have:
If your devices are, say a Raspberry Pi's for example. If I walk up and yank the SD card from one, I can stick the SD card in my own computer, find the sshd key and copy that to everywhere I want. Maybe I grab my own raspberry pi and a USB ethernet card. Now I can stick that in between a target device and wherever they're going and monitor for ssh connections. When I see that the target device is trying to make an ssh connection, I do this:
(target) <---> (my evil sshd <--> decrypted traffic <--> ssh) <---> (real server)
                                       |
                                       V
                                    log file

Oh, what's that? Your password is "I like cats"? Boy, this is an interesting email you sent to your wife. I bet it would be even more interesting if she read this email that you sent to your next door neighbors wife.
The possibilities are endless. And the target would never know, because the sshd key is identical to the one found on the real server. Depending on the physical security of the facilities that are receiving your device, this could be incredibly trivial. Don't do this.
Instead, do what you already propose but fix it. Before you write your image run something like this:
ssh-keygen -f some-new-server
cp some-new-server /path/to/the/mounted/image/sshd/key
cp some-new-server.pub /path/to/the/mounted/image/sshd/key.pub

And now every server has a new key. Because you really, really don't want to be distributing copies of a key. I mean honestly it's at least as bad as snapping a picture of your house keys and uploading them to the Internet with your home address.
Comment: If someone has physical access to your hardware and you fail to encrypt the data at rest then all bets are off.


can't call onNewIntent

Question: My program has MainActivity and myService.
MainActivity is 'singletop', and MainActivity overrides onNewIntent class.
myService is 'foreground' Service.
It pop up a notification.
The notification has Intent(this,MainActivity.class) in pendingIntent to start MainActivity.
My program's flow is
Launch from icon (start) MainActivity (startService) myService (send broadcast) broadcast class(start MainActivity)onNewIntent@MainActivity
When program is Launched like this flow, onNewIntent is called exactly.
But when program is Launched from notification,
onNewIntent never called.
Launch from Notification (start) MainActivity (startService) myService (send broadcast) broadcast class(start MainActivity)onNewIntent@MainActivity
Answer: From the guide at http://developer.android.com/guide/topics/manifest/activity-element.html
Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.
Thus onNewIntent is only called if there is an existing instance of the activity at the top of the stack.

can't call onNewIntent


SQL Most effective way to store every word in a document separately

Question: Here's my situation (or see TLDR at bottom): I'm trying to make a system that will search for user entered words through several documents and return the documents that contain those words. The user(s) will be searching through thousands of documents, each of which will be 10 - 100+ pages long, and stored on a webserver.
The solution I have right now is to store each unique word in a table with an ID (only maybe 120 000 relevant words in the English language), and then in a separate table store the word id, the document it is in, and the number of times it appears in that document.
E.g: Document foo's text is

abc abc def

and document bar's text is

abc def ghi

Documents table will have
id  |  name
1 'foo'
2 'bar'

Words table:
id | word
1 'abc'
2 'def'
3 'ghi'

Word Document table:
word id | doc id | occurrences
1        1        2
1        2        1
2        1        1
2        2        1
3        2        1

As you can see when you have thousands of documents and each has thousands of unique words, the Word Document tables blows up very quickly and takes way too long to search through.
TL;DR My question is this:
How can I store searchable data from large documents in an SQL database, while retaining the ability to use my own search algorithm (I am aware SQL has one built in for .docs and pdfs) based on custom factors (like occurrence, as well as others) without having an outright massive table for all the entries linking each word to a document and its properties in that document?
Sorry for the long read and thanks for any help!
Comment: If full-text search doesn't solve all of your problems, maybe a relational database isn't the solution you're after anyway...
Comment: Have you looked into [Lucene](http://lucene.apache.org/core/)?
Comment: This is a problem better suited for `nosql`  In particular redis
Comment: The content index guys actually store the location of each word in the document (so you can tell if words are nearby each other, find phrases, etc.), not just the number of occurrences.
Comment: i think your structure is correct.  it will be about the indexing
Comment: @Roman Fair warning. You REALLY want to use the pre-built solution. Either SQL Server full-text searching or something like Lucene. You will lose many, many days of your life that you could spend on more productive things if you try to make your own search engine. Realize that Google is very valuable for a reason, it's not something you can duplicate easily.
Comment: As I said, I would like to have full control over the search algorithm, and prioritize certain words over others based on an arbitrary feature set for each word.
Comment: Are you required to use SQL?
Comment: At the moment, NOSQL is not an option (I have considered it, but my situation does not allow for it). I have to use MSSQL or MySQL and ASP.net
Comment: Agree with Randy then.  Set up benchmarks with no indexes and then add index, rerun, etc.  I have a similar issue with a MySQL db and I was surprised which indexes affected performance.
Comment: @Gabe Occurrences was just an example, I might store lots of other features later on as well.
Comment: @JeffDavis From what I can tell, SQL Server uses a very similar solution to my own, however gives me less control over how the search is carried out and how results are organized. As for something like Lucene, I am definitely looking into its implementation. I am well aware of the value and complexity behind Google, and although their degree of result relevancy is remarkable, I have no plans of attempting to duplicating it with my own code.
Comment: hi @Roman has any of these answers been helpful to solve your problem? If not please add what was not successful to your question. When an answer helped you, can you accept it by clicking the hollow green check mark next to it?
Answer: Rather than building your own search engine using SQL Server, have you considered using a C# .net implementation of the lucene search api's? Have a look at https://github.com/apache/lucene.net
Comment: It looks like my best bet is to use Lucene. Thanks.
Answer: Good question. I would piggy back on the existing solution of SQL Server (full text indexing). They have integrated a nice indexing engine which optimises considerably better than your own code probably could do (or the developers at Microsoft are lazy or they just got a dime to build it :-)
Please see SQL server text indexing background. You could query views such as sys.fulltext_index_fragments or use stored procedures.
Ofcourse, piggy backing on an existing solution has some draw backs:

You need to have a license for the solution.
When your needs can no longer be served, you will have to program it all yourself.

But if you allow SQL Server to do the indexing, you could more easily and with less time build your own solution.
Answer: Your question strikes me as being naive. In the first place... you are begging the question. You are giving a flawed solution to your own problem... and then explaining why it can't work. Your question would be much better if you simply described what your objective is... and then got out of the way so that people smarter than you could tell you HOW to accomplish that objective.
Just off hand... the database sounds like a really dumb idea to me. People have been grepping text with command line tools in UNIX-like environments for a long time. Either something already exists that will solve your problem or else a decent perl script will "fake" it for you-- depending on your real world constraints, of course.
Depending on what your problem actually is, I suspect that this could get into some really interesting computer science questions-- indexing, Bayesian filtering, and who knows what else. I suspect, however, that you're making a very basic task more complicated than it needs to be.
TL;DR My answer is this:
** Why wouldn't you just write a script to go through a directory... and then use regexes to count the occurences of the word in each file that is found there?
Comment: That may be a significant problem there, mbeckish. The problem with breaking the documents down into individual words in a database is that it does not allow you to search for phrases or patterns. If speed is an issue, you can always cache your search results so that the most commonly used searches aren't being redone.
Comment: So you're saying there is no need to preprocess tens of thousands of documents to make subsequent searches faster?  The solution is to just do a search through all of the files each time?  Even if the system needs to do lots of searches quickly?
Comment: If you store the correct index data per word, you could also search for phrases, ans others have mentioned above.
Comment: This solution will be deployed on a webserver. My sincerest apologies, I forgot to clarify that in the original post. There will be million of documents simultaneously being accessed by thousands of users. I can't imagine the kind of hard server-side storage I would require to search quickly. And the reason I provided my flawed solution is in an attempt to help people understand the objective in case I wasn't clear enough.


android use html tags in textview programmatically

Question: I have been able to use html tags in the string ie, to set textview from resource like :
<resources>
<string name="somestring">
    Title Italic

    Content
</string>
</resources>

This works fine when the text is in resource and I set it to my textView.
Now, I want to programmatically set a string I get from server at runtime to the textView. Therefore I can't define the string in resource folder.
I tried the following
textView.setText("BoldItalic");

but this doesnt work. Any help would be appreciated.
Comment: Html.fromHtml(); will work
Answer: Use code like:
textview.setText(Html.fromHtml("YOUR HTML STRING"));

Hope it will help you.
Comment: Thx for the answer I cant accept it till the next 6mins it seems
Comment: Ya no problem. you can accept it later also. important thing is that you can now go ahead in your developement.


bit layout of vector after bitcasting in llvm

Question: %0 = bitcast i16 %arg1 to <2 x i8>
%2 = extractelement <2 x i8> %0, i32 1

%arg1 in memory:
 00000000  11111111

|--8bit--||--8bit--|

After bitcasting, %0 is a pointer to vector.
So is %0 also the address of the first element of the vector?
And what is %2 exactly? Is it the second element of vector(11111111) or,
00000000?
Answer: After bitcasting, %0 is a Value of type <2 x i8>. It is not "a pointer". The vector may very well be stored in a register when code generation to machine code happens.
%2 is i8, because extractelement is defined as:
<result> = extractelement <n x <ty>> <val>, i32 <idx>    ; yields <ty>

The vector has two elements, each with of type i8. %2 is a Value that holds the second element in the vector.
Note that how the vector is laid out in memory or registers is target dependent. LLVM IR level doesn't care about that. It sees the vector as an abstract container of two values.
Answer: (Would like to post this despite this question was discussed fairly long time ago, after reading when it's good to reply an old question, since the reply provides another way to verify the answer and references recent document update)
The value of %2 would depend on the endianess and target (the vector 's memory layout depends on the target and endianess as Eli Bendersky mentioned); https://gcc.godbolt.org/z/vfcGhb4EK could be a good way to visualize that.

By reading the language reference, these two are helpful to reason about the above IR (at least to me)

the semantics of bitcast
the memory layout of vector types

Both 1 and 2 were updated from https://reviews.llvm.org/D94964 (credit to the authors and reviewers)
Answer: bitcast <type1> <value> to <type2> converts the value, %arg1 in your case, from type1 to type2 without changing the bits given that the number of bits in the two types are the same.
%0 = bitcast i16 %arg1 to <2 x i8>

This means that %0 is now an array/vector of two 8-bit integers instead of a single 16-bit integer.  Looking over the linked documentation, this appears to only be a value.
extractelement <n x <type>> <value>, i32 <index> extracts the element in the n-length array of typed values as the given type using the 32-bit integer index.
%2 = extractelement <2 x i8> %0, i32 1

This means that %2 is now an 8-bit integer with the value of element 1 (the second/last 8-bit element).  Assuming little endian hardware, I would expect the value of %2 to be 0.
Comment: You have two mistakes here: first, you write that "`%0` is an array/vector" - while it is clearly a vector, not an array. Also, the `extractelement` is a value of type `i8`, not `i32` - the `i32` is the type of the index.
Comment: The vector is logically being treated like an array, which is why I referenced it with the slash. Good catch on the 32-bit versus 8-bit; I definitely misread the documentation on that one.


Division problems

Question: I came across these problems :

1) Find the lowest natural number $k$ that satisfies the condition :
$ 7 \mid A$ , where $A = 194^{19} + 125^{14} + k $
2) Find the different prime numbers $m, n, p$, that satisfy the condition :
$$2mnp - m - n - p - mn - mp - np \le 19$$

For the first one, I'm thinking at Fermat's little theorem..
Some hints would really help me.
Comment: Hint for 1: You might want to use modulo arthimetic and Fermat's Little theorem to work out the remainder when $194^{19}$ and $125^{14}$ are divided by 7. For example, $194^{19} \equiv 5^{19} \equiv 5$ (mod 7)
Comment: @suncup224 thanks, got it. I steel have trouble with the second one.
Comment: For 2: This is not a systematic approach, but seeing how $mnp$ will blow up much faster than $m,n,p,mn,mp,np$, so in order to keep the left hand side small, it seems natural to try the smallest possible primes. So I tried $m=2, n=3, p=5$ and it works. Are you supposed to find all possible solutions, or just one set?
Comment: @suncup224 all possible solutions.
Comment: @suncup224 in the first comment you posted, why $5^{19}≡5 (mod 7)$ ?
Comment: $5^{19} = (5^6)^3 * 5$ and $5^6 \equiv 1$ (mod 7) by Fermat's Little Theorem
Answer: For 2 :
One has
$$\left((2n-1)\left(p-\frac 12\right)-\frac 32\right)m-n-p-np\le 19$$
$$\iff m\le \frac{19+n+p+np}{(2n-1)\left(p-\frac 12\right)-\frac 32}$$
Here, note that $(2n-1)\left(p-\frac 12\right)-\frac 32\gt 0$.
With $2\le m$, one has
$$2\le\frac{19+n+p+np}{(2n-1)\left(p-\frac 12\right)-\frac 32}$$
$$\iff 2\left((2n-1)\left(p-\frac 12\right)-\frac 32\right)\le 19+n+p+np$$
$$\iff (n-1)(p-1)\le 8$$
Can you take it from here?
Comment: Yeah, got it. Thanks!
Answer: Another approach to problem 2) is to let $m=a+2$, $n=b+2$ and $p=c+2$.  The desired inequality becomes
$$2abc+3(ab+bc+ca)+3(a+b+c)\le21$$
so in particular $a+b+c\le7$ with $0\le a,b,c$.  Since these variables are each $2$ less than a prime, the allowed values are $a,b,c\in\{0,1,3,5\}$.  We may as well assume $a\le b\le c$ (and then permute the results to get all solutions).  The $(a,b,c)$ triples that satisfy the displayed inequality are $(0,0,0)$, $(0,0,1)$, $(0,0,3)$, $(0,0,5)$, $(0,1,1)$, $(0,1,3)$, and $(1,1,1)$.
Comment: If I didn't the calculations wrong, I've obtained $2abc+3(ab+bc+ca)+3(a+b+c)≤21$. Nevermind, I understand the principle, so thanks! It's more compact than the other solution described here for this problem (which worked too).
Comment: @scummy, yes, you did the calculation correctly.  I fixed my error.  I'm glad you checked it.  (Fortunately, it didn't affect the resulting solutions -- unless I made another error or two....)
Answer: (194)^19 = -2 (mod 7)
(125)^14 = 1 (mod 7)
194^19 + (125)^14 + K = 0 (mod 7)
-2 + 1 + k = 0 (mod 7)
the minimum natural number for k is 1
k = 1
Comment: I think that you mean $125^{14} = -1 (mod 7)$, right?
Comment: no, 125 = -1 (mod 7)   , (125)^14 = (-1)^14 = 1 (mod 7)
Comment: $125^{14} ≡ 6^{14} (mod 7)$ because 125 = 7 * 17 + 6, and $6^{14} ≡ 6^{7} ≡ 6 (mod 7) $ because of Fermat's little theorem. Correct me if I'm wrong.
Comment: 6^14 = (6^2)^7 = 36 = 1 (mod 7)
Comment: a^p = a (mod p)   put a=6^2   ,  p=7
Comment: you are right, I'm sorrry
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/26543/discussion-between-scummy-and-mahdokht).

Division problems


computation of upper limit and lower limit

Question: the infimum is when $n=1$, infimum is $-1$
the supremum is when $n=2$, supremum $1+\frac{1}{2}=\frac{3}{2}$
I need help to understand this part:
over the set $n \geq m$, the infimum is $\frac{-1}{2k+1}$ where $2m-1=2(2k+1)-1=4k-1$
or $2m+1=4k-1$
when $m \rightarrow ∞, k \rightarrow ∞$, so the infimum is tending to $0$
So the limit inferior is $0$
My problem is I do not know how to put it in notation of limit
over the set $n \geq m$, the supremum is $1+\frac {1}{2k}$ where $2m=4k$ or $2m+2=4k$
when when $m \rightarrow ∞, k \rightarrow ∞$, so the supremum decreases to $1$
So the limit superior is $1$
thanks for your help
Comment: It's really hard to understand your question.
Comment: Can you typeset please?
Comment: It seems the question (unrelated to limits) is to know how to write $-1/(2k+1)$ (first case) and $1+1/(2k)$ (second case) as functions of $m$ if $m=2k$ or $m=2k-1$. Is that so?
Answer: By definition, given any sequence $\{a_m\}_{m\in\mathbb{N}}$ of reals, $$\liminf_{m\to\infty}a_m:=\lim_{m\to\infty}\left(\inf_{n\geq m}a_n\right),$$ and $\limsup_{m\to\infty}a_m$ is similarly defined.
In this particular context (if I'm interpreting your information and question correctly),  given your sequence--which I will label $\{a_m\}_{m\in\mathbb{N}}$--we have $$\limsup_{m\to\infty}a_m=\lim_{m\to\infty}\left(1+\cfrac{1}{2\lceil m/2\rceil}\right)=1,$$ and the limit inferior can be similarly found.
Is that what you were looking for? If not, let me know. It is usually helpful to those who would answer you to give as much of the problem's context as possible. As srijan noted, it's difficult to tell what you are asking.


Previsão de demanda para muitos itens

Question: Boa tarde, pessoal. Gostaria de saber a opinião de vocês, sobre o seguinte:
Eu estou trabalhando em uma empresa e-commerce, que possui mais de 1000 itens a venda, sendo que cada item desse, possui uma série história de vendas diárias, de 2019 até hoje.
O desafio é fazer uma previsão de vendas para cada item, baseado no seu histórico de vendas passadas. Para tal, as dúvidas que eu tenho são as seguintes:
1- qual modelo utilizar?
2- qual software mais indicado para esta previsão? sendo que eu tenho mais de 1000 produtos, e sendo que para cada produto é uma série histórica diferente
3- Eu terei que fazer uma projeção para cada item? não vejo sentido nisso, pois o esforço seria tremendo, e demandaria muito tempo, mas se for este o caso, me digam!!
Obs: os dados estão contidos numa planilha do excel no seguinte formato: cada coluna é um SKU (produto) e cada linha é o número total de vendas daquele respectivo sku, e na respectiva data semanal.
Por favor se alguem que ja trabalhou com previsão de vendas em alguma empresa, me salvem!!! Ficarei grato.
Answer: O processo de análise de séries temporais engloba testes de raiz unitária, sazonalidade, tendência, mas como são muitas séries temporais vou dar uma sugestão que provavelmente não daria em uma situação normal. Recomendo usar modelos univariados de séries temporais, eles usam o histórico da série para prever o comportamento dela mesma, a biblioteca forecast do R tem uma função auto.arima que busca o melhor modelo ARIMA minimizando um critério de informação a sua escolha.
Se você procurar sobre modelos ARIMA no R pode conseguir algumas informações sobre como fazer isso, mas acredito que estudar modelos univariados e a biblioteca forecastsão um bom caminho e que a função auto.arima ajuda a poupar tempo algumas vezes.

Previsão de demanda para muitos itens


SQL Server 2008 : Multiple Queries in One Stored Procedure

Question: I have 2 stored procedures that retrieve data from a table called Places. The procedures are called by C# code one at a time. These are the table columns.
  [ID] int NOT NULL IDENTITY(1, 1),
  [Name] varchar(150) NOT NULL,
  [Latitude] decimal(18, 2) NOT NULL,
  [Longitude] decimal(18, 2) NOT NULL

These are the 2 stored procedures
CREATE procedure dbo.GetPlacesByID
    @ID int
AS
SELECT *
FROM dbo.Places
WHERE  ID = @ID
GO

and
CREATE procedure dbo.GetNearbyPlaces
    @Min_Lat decimal(18, 2),
    @Min_Lng decimal(18, 2),
    @Max_Lat decimal(18, 2),
    @Max_Lng decimal(18, 2)
AS
SELECT *
FROM dbo.Places
WHERE Latitude BETWEEN @Min_Lat AND @Max_Lat
AND   Longitude BETWEEN @Min_Lng AND @Max_Lng
ORDER By ID ASC
GO

The C# application calls GetPlacesByID first. If a row is returned, the app takes the latitude and longitude data and calculates the @max_Lng, @Min_Lng, @Max_Lat and @Max_Long variables by adding or subtracting a constant 0.005. These variables are passed to the GetNearbyPlaces sp which returns nearby places and the app displays the original place plus the nearby places on a Google map.
This works fine but there are two round trips to the database which is not very efficient.
I would like to combine the two procedures into one with something like
create procedure dbo.GetPlaces
  @ID int
select * from  dbo.Places as Row1
where ID=@ID
if Row1 is not null
  Declare @Min_Lat decimal(18, 2),
  Declare @Min_Lng decimal(18, 2),
  Declare @Max_Lat decimal(18, 2),
  Declare @Max_Lng decimal(18, 2)

  Set @Min_Lat=Row1.Latitude - 0.005
  Set @Min_Lng=Row1.Longitude - 0.005
  Set @Max_Lat=Row1.Latitude + 0.005
  Set @Max_Lng=Row1.Longitude + 0.005

 select * from dbo.Places
 where Latitude BETWEEN @Min_Lat AND @Max_Lat
 and   Longitude BETWEEN @Min_Lng AND @Max_Lng
 ....

The procedure would return the original row(Row1) + all the nearby places. I'm looking for suggestions on how to accomplish this. Thanks.
Answer: Give this a try:
CREATE procedure GetNearbyPlaces
  @Id int
AS
BEGIN
  Declare @Min_Lat decimal(18, 3)
  Declare @Min_Lng decimal(18, 3)
  Declare @Max_Lat decimal(18, 3)
  Declare @Max_Lng decimal(18, 3)

  SELECT @Min_Lat=Latitude - 0.005,
    @Min_Lng=Longitude - 0.005,
    @Max_Lat=Latitude + 0.005,
    @Max_Lng=Longitude + 0.005
  FROM Places
  WHERE Id = @Id

  SELECT *
  FROM Places
  WHERE Latitude BETWEEN @Min_Lat AND @Max_Lat
  AND   Longitude BETWEEN @Min_Lng AND @Max_Lng
  ORDER By ID ASC

END
GO

SQL Fiddle Demo

After relooking this over, another issue you could potentially be having is with DECIMAL(18,2) -- I think this needs to be DECIMAL(18,3) since you're offsetting with .005.
Here is a simpler version with a single sql statement:
SELECT P.*
  FROM Places P
    JOIN (
      SELECT Latitude - 0.005 Min_Lat,
        Longitude - 0.005 Min_Lng,
        Latitude + 0.005 Max_Lat,
        Longitude + 0.005 Max_Lng
      FROM Places
      WHERE Id = @Id
      ) P2 ON P.Latitude BETWEEN P2.Min_Lat AND P2.Max_Lat
          AND P.Longitude BETWEEN P2.Min_Lng AND P2.Max_Lng
  ORDER By ID ASC

Updated Fiddle
Comment: Tested 1st example in app. Works like a charm. I tested the 2 example in fiddle but not in the app yet. It works in fiddle so I expect it to work in the app.Thanks **sgeddes**.
Comment: **sgeddes**, I went ahead and changed the Latitude and Longitude table columns to float data types for more decimal points which allows more accuracy. Thanks


$\sum_{n=0}^{\infty} n \left( \frac{2}{3} \right)^n = ?$

Question: $$\sum_{n=0}^{\infty} n \left( \frac{2}{3} \right)^n = ?$$
How to find it? If it lacked n before fraction, I would use formula for the sum of geometric series.
Comment: http://math.stackexchange.com/questions/854566/how-to-solve-infinite-series-sum-n-0-infty-fracn2n1
Answer: Consider the infinite geometric progression for $|x|<1$,
$$
\sum_{n=0}^\infty x^n=\frac1{1-x}.\tag1
$$
Differentiating $(1)$ with respect to $x$ yields
$$
\sum_{n=0}^\infty nx^{n-1}=\frac1{(1-x)^2}.\tag2
$$
Multiplying $(2)$ by $x$ yields
$$
\sum_{n=0}^\infty nx^{n}=\frac{x}{(1-x)^2}.\tag3
$$
Setting $x=\dfrac23$ to $(3)$ yields
$$
\sum_{n=0}^\infty n \left(\frac23\right)^{n}=\frac{\frac23}{\left(1-\frac23\right)^2}=\large\color{blue}{6}.
$$
Comment: (1) is true for $\;|x|<1\;$


Referencing return function?

Question: I'm returning a simple function with two variables,
function checkerValidate(){
$emptyOrNot = "";
$validOrNot = "";

    if(!empty($_POST['domain']))
    {//not empty
        $emptyOrNot = "notEmptyUrl";
        if (filter_var($url, FILTER_VALIDATE_URL) === TRUE) {
            $validOrNot = "validUrl";
        }else{
            $validOrNot = "notValidUrl";
        }
    }else
    {//empty
        $emptyOrNot = "emptyUrl";
    }
    return array($emptyOrNot, $validOrNot);

}

To reference the two variables outside the function I use:
<?php echo checkerValidate()[0]; ?>
<?php echo checkerValidate()[1]; ?>

I tried and upload to the server and it was working, however the I'm using Dreamweaver IDE and it states that checkerValidate()[0] and checkerValidate()[1] are not valid.
Can anyone clarify on this?
Comment: Why would you do that? Valid expression or not... you're calling and executing the whole function each time you want to use any of the values! Wouldn't it be simpler to assign the return value to a variable and then use it as a regular array? Unless you actually need to re-execute it each time, of course.
Comment: @AJPerez thanks, will use your way just to be safe
Answer: That syntax is valid from PHP 5.4. There is a possibility that your IDE is set to syntax check a lower version of PHP which is why it thinks it is wrong.
Your server obviously has a version of PHP greater than or equal to 5.4 so it works just fine (you can check using php -v).

Referencing return function?


How to limit something that pulls me to the right when swimming?

Question: I have a problem to swim straight. When I swim, something pulls me to the right. This happens to me more when I swim breaststroke, and less when I swim crawl.
What could be the reason?
It think I have no scoliosis. Could this be a stronger left leg? I'm left-handed and left-legged.
How could I resolve that problem? What kind of exercises you would recommend?
Comment: Swimming is not a competitive sport?
Comment: The closing of swimming questions is currently being discussed at meta: http://meta.sports.stackexchange.com/questions/641/why-has-a-question-on-swimming-technique-been-closed-as-off-topic
Answer: Swim in the lane next to a wall and have someone walk along and watch to see if there is an obvious discrepancy (strength, length of pull, imbalance, whatever) in your strokes.
Answer: There must be an imbalance in your stroke. The most likely being a difference in your arm strokes, or in the degree that you are rolling side-to-side for each arm in freestyle (crawl). Have a look at the way your arms are pulling. Is your right elbow bent more that the left? Is your right arm pulling back as far as the left? Breaststroke kick is also hard to do symmetrically, most people kick or pull further with one leg than the other.
You can test if it's arms or legs first by swimming with a pool buoy and then kick board to isolate arms and legs and see which is turning you.
Good luck!


expecting high traffic ..no time to change dns

Question: I am expecting high traffic ..no time to change dns. My existing shared godaddy server may fail. i have less than few hours in hand. i have a another dedicated server ...can i transfer traffic /bandwith /load to dedicated server. what are possible solutions.
thanks.
sk
Answer: Reduce bandwidth - You may want to use a free CDN such as CoralCDN or SimpleCDN and temporarily redirect visitors to the CDN domain. That's what people normally do for the slashdot effect.
Reduce CPU load - You could also present a static cache of your site made using httrack or similar tool instead of a full dynamic one.
Spread the load - Varnish can cache some content and if correctly configured, can do a lot more, including load balancing over multiple servers.
Answer: You can change your DNS now and it will have an impact, most definitely. However, if you are storing information server-side (I don't mean session state stuff, I mean taking orders, user input, content whatever...) then this might not be practical.
It takes a full 24 hours for propagation to occur, but if you've got a static-ish site, you can definitely change now and if you are a small to medium site expecting a large traffic spike then the majority of users will be redirected to the new site.
What else you can do depends on your situation. If you are allowing users to login, post to forums, take input etc. then you're going to have a bit of trouble. You can do stuff on the application side, but it's a lot of work, probably not much you can do in a couple of hours.  Again, we need more information here to be specific.
However, if you have relatively static content. Like for example, if you were posted up on slashdot then you can have a look at overriding some of the dynamically generated pages with static pages.

grab the full HTML of the page from your browser
copy and paste it into a file
re-upload it back to your webserver
use mod_rewrite in a .htaccess file to serve that file for any requests to the original URL

You need to be far more specific with what you're running on the site to give any more specific information. In general, you would be recommended running a caching proxy, but that presumably isn't possible on a shared server.
Comment: my site is a small CMS.database is in MS access and just displaying content.No Blog,No forum and no cart.
Comment: DNS might not take 24 hours...  If the TTL on the records are short, changing them will have an immediate effect and a larger one as the records expire from caches.  This is why setting TTLs to 3600 or 7200 or so is a good idea, not weeks-long.
Comment: ISP's will often ignore short TTLs, but from what I have seen in DNS changes, most will update pretty fast (within the hour).  But I would be interested in any stats for for hits over time to the old and new sites after a DNS change for a global high traffic site.
Comment: @Michael GoDaddy's default TTL is a day, I'm making a reasonable assumption this is what the user is talking about when he says "no time to change DNS"

@sunny is anything written to the access database? is it one particular page that you're worried about big loads to or the whole site? Could you dump all of the site out to HTML pages for the time being and remove the access component?
Comment: Most of the traffic is expected on one page like prospectus download.The prospectus page is dynamic. like one have to put country name then accept terms and able to download.

The prospectus is 14mb.I have transferred the downloadble prospectus file to another server for saving bandwidth cosumption.


$G$ is an abelian group, $H \triangleleft G$, show that $G/H$ is abelian.

Question: Prove: if H is a normal subgroup of an abelian group G then G/H is abelian.
Here is what I've tried:
We must show that G/H is abelian. Let a and b be two elements of G/H.
Is this a poor way to start the proof?
Comment: Any subgroup of an *Abelian* group $G$ is normal. But yes, a reasonable way to show that the quotient group is normal is tp start with two elements and show they commute.
Comment: You may want to let the two elements in G/H be aH and bH, where a, b are in G
Answer: $(aH)(bH) = (ab)H = (ba)H = (bH)(aH)$. Done.


Find the angles of an isosceles triangle, given an angle defined the base and a median

Question:
Given an isosceles $\triangle ABC$, where $\overline{AB} \cong \overline{BC}$, let $M$ be the midpoint of $\overline{BC}$. The angle between $\overline{AC}$ and median $\overline{AM}$ is $\alpha$. How can I find the angles of the triangle?
Comment: You need 3 quantities to determine a triangle. We appear to only have 2 ... $AB=BC$ and $\alpha$ ... is there something you are not telling us ?
Comment: @DonaldSplutterwit You need three quantities to determine a triangle. But, I think that the angles could be figured with the two quantities. Did you note that $AM$ is the median?
Comment: That's all I think. The problem is from a contest which took part yesterday
Comment: @frederick99 You are right ... the implicit third piece of info is that the angles of a triangle add upto $180$ ...
Comment: It is implied anyways. To determine a triangle fully, you need another three quantities. :)
Comment: Why don't you validate answers that ... answer your question ?
Comment: @student28: I appreciate the checkmark. However, given that JeanMarie's solution is a vast improvement on mine, I recommend accepting that one instead.
Answer: Inspired by your solution, @Blue, and along the same lines, taking the same notations (with $K$ center of gravity at the intersection of median $AM$ and altitude-median $BN$ with $BN=3KN$), I propose a shorter solution that does not use point $P$. Here it is:
Let $u=AN=NC$. We have, by definition of a tangent:

$\tan \alpha=\dfrac{KN}{u},$
$\tan \beta=\dfrac{u}{BN}=\dfrac{u}{3KN},$

Therefore: $ \ \ \tan \alpha \tan \beta=\dfrac{1}{3} \ \ \ \implies \ \ \ \ \beta=\displaystyle\arctan\left(\dfrac{1}{3 \tan \alpha}\right).$
Remark: I have erased my so complicated previous proof.

Edit by @Blue. This refinement is so good that I had to draw a picture!

$$\tan \alpha \tan\beta = \frac{v}{u}\cdot\frac{u}{3v} = \frac{1}{3}$$

Also, I recommend that OP accept this answer.
Comment: @Blue Thank you very much for your nice figure.
Answer: To avoid fractions, take $\angle B = 2\beta$ and $|\overline{AC}| = 6b$. We may consider the problem solved once we have expressed $\beta$ in terms of $\alpha$.

Let the perpendicular from $B$ meet $\overline{AC}$ and $\overline{AM}$ at at $N$ and $K$, respectively. Take $P$ on $\overline{AC}$ such that $\overline{KP} \parallel \overline{BC}$.
Since $K$, as the intersection of two medians, is the centroid of $\triangle ABC$, we "know" that $|\overline{KM}|:|\overline{AM}| = 1:3$. The parallel $\overline{KP}$ carries this ratio over so that $|\overline{PC}|:|\overline{AC}| = 1:3$. That is, $|\overline{PC}| = 2b$, and we have
$$|\overline{NP}| = 1b \tag{1}$$
Moreover, $$|\overline{AN}| = 3 b \quad \to \quad |\overline{KN}| = 3b \tan\alpha \quad\to\quad |\overline{NP}| = 3 b\tan\alpha \tan \beta \tag{2}$$
Therefore,
$$3b\tan\alpha\tan\beta = 1b\quad\to\quad\tan\alpha\tan\beta = \frac{1}{3} \quad\to\quad \beta = \operatorname{atan}\left(\frac{1}{3}\cot\alpha\right)\tag{3}$$
$\square$
Comment: @JeanMarie: I'm just trying to deflect attention from the embarrassment of focussing on the trisection of the wrong median. ;)  But seriously, yours is clearly the better solution, and deserves to be "accepted" over mine. (I'm happy enough to take some credit for "inspiring" it!)
Comment: Materializing quantity $3b\tan\alpha\tan\beta$ is a good idea. Besides, I have much appreciated your elegance in recommending my solution.
Comment: As you are interested by classical geometry, have you noticed my recent question about inversion transform (https://math.stackexchange.com/q/2626356) ?
Comment: @JeanMarie: I've seen the question, but I can't think of anything to contribute ... yet.


`watch jobs` doesn't work in linux

Question: I want to use watch jobs to see an updated showing of all the jobs I have running, but when I try to do it, all I get is the headline of watch and a blank screen. But using the script
while (1)
  sleep 10;
  clear;
  jobs;
end

does work, where is the problem?
Answer: Job control is managed by the shell and jobs is a shell builtin function.  If you use the command which jobs you will see there is no binary called jobs anywhere in your $PATH.
watch is doing a system call every two seconds so shell functions aren't available to it.
You could also try watch 'ps awwwux | grep yourusername'.  But its not quite the same as jobs.
Comment: ps awwwux | grep  shows too much stuff for me (I use google chrome which has plenty of threads), so I prefer using `pgrep -fl ` here
Answer: Job is not a system command its a shell command - when you start watch he executes a subshell which has its own job managment and of course no jobs. Try watch ps.

`watch jobs` doesn't work in linux


format_date() not working

Question: I've got a field in a content type called "field_program_date" of type "Date". I'm using Drupal's format_date() function to format the date in the content template like this:
$program_date = format_date($node->field_program_date[$node->language][0]['value'], 'custom', 'F j, Y');
print $program_date;

Something is wrong because nothing gets printed out at all.
Answer: Since the date is not coming out as a timestamp, you can to use strtotime. Something like:
$date = strtotime($node->field_program_date[$node->language][0]['value']);
$program_date = format_date($date, 'custom', 'F j, Y');
print $program_date;

Comment: Yep! That did it! For correctness, and if anyone is cutting and pasting this, it looks like there's a missing semicolon at the end of the first line.
Answer: Have you tried printing out the value of $node->field_program_date[$node->language][0]['value']? format_date takes a unix timestamp as it's first param. So if the variable isn't in a format like "1429026611," then you'll need to convert it to a timestamp first.
Comment: That's got to be it! It prints out like this: `2015-04-10 00:00:00`. How do I convert it into a timestamp?
Comment: Use php's strtotime function. For readability, you might want to set a var as the unix timstamp, and just send the var in the format_date function call.

format_date() not working


How to find a list of structured records in a router log with Python

Question: We receive daily some dumps from our routers. This has been configured by the vendor of the routers. Now I would like to find the real records in these logs and put them in tables.
Here is a sample of such a dump file.
PZMO120#
PZMO120# show interface description

                                              IF      IF      IF                                                                                IPV6
                      AF                      ADMIN   OPER    TRACKER                                                                               ADMIN
VPN    INTERFACE      TYPE  IP ADDRESS        STATUS  STATUS  STATUS   DESC                                                                         STATUS
------------------------------------------------------------------------------------------------------------------------------------------------------------
0      ge0/0          ipv4  xx.yy.zz.r/pp     Up      Up      Up       ORCH=NETWORK - To INTERNET                                                   Up
0      ge0/1          ipv4  -                 Up      Up      NA       ORCH=NETWORK - TLOC Extension - B2B between Primary vEdge & Secondary vEdge  Up
0      ge0/2          ipv4  -                 Down    Down    NA       None                                                                         Up
65530  ge0/3          ipv4  -                 Up      Up      NA       ORCH=NETWORK - CUSTOMER LAN - Service VPN physical interface                 Up

PZMO120#
PZMO120#
PZMO120# show  vrrp

                                                                                PRIMARY                             TRACK   PREFIX
                GROUP                                            REAL      VRRP     OMP    ADVERTISEMENT  DOWN                                PREFIX  LIST
VPN  IF NAME    ID     VIRTUAL IP   VIRTUAL MAC        PRIORITY  PRIORITY  STATE    STATE  TIMER          TIMER    LAST STATE CHANGE TIME     LIST    STATE
--------------------------------------------------------------------------------------------------------------------------------------------------------------
1    ge0/3.510  10     zz.zz.zz.x   00:00:??:00:01:0a  150       150       primary  up     1              3        2022-12-06T19:32:06+00:00  -       -
2    ge0/3.511  11     yy.yy.yy.r   00:00:??:00:01:0b  150       150       primary  up     1              3        2022-12-06T19:32:06+00:00  -       -

PZMO120#
PZMO120# show  run vpn 1

I'm not a Python expert, but would like to create a system that recognized a predefined header, and knows that x lines further some real data is coming until the first blank line.
Comment: What have you tried to program? Is this a csv or txt file? Could you share a example of your code and input file, please.
Comment: Until now nothing yet, I would have started with a classic find while looping the records in the txt file. But that is a classic programmers approach. From what I've seen in some other cases is that puthon has quite a lot of specials in it that work mucht faster then just looping and comparing. That's why I asked the question with a 'KickOff hint'.
Answer: Finaly got something working, might not be the super code but might others give a head-start, to be refined.
def find_vrrp_table(routername, filecontent):
    result = ""
    regex_to_find = "(?s)(?<=VPN  IF NAME    ID     VIRTUAL IP  VIRTUAL MAC        PRIORITY  PRIORITY  STATE    STATE  TIMER          TIMER    LAST STATE CHANGE TIME     LIST    STATE)(.*?)(?=" + routername + ")"
    regex_result = re.search(regex_to_find, filecontent)
    if regex_result:
        result = regex_result.group()
    return result

and
def convert_interfaces_string_into_df(routername, interfaces_string):
    # Make a List with only records
    interfaces_list = interfaces_string.replace('\r','').split('\n')
    interfaces_list.pop(0)
    interfaces_list.pop(0)
    interfaces_list = list(filter(None, interfaces_list))
    # Convert Records into Pandas DataFrame
    colspecs = 0, 7, 22, 28, 46, 54, 62, 71, 148, 152
    df = pd.DataFrame([[row[i:k] for i, k in zip(colspecs[:-1], colspecs[1:])] for row in interfaces_list])
    df.columns = ['VPN', 'INTERFACE', 'AF_TYPE', 'IP_ADDRESS', 'ADMIN_STATUS', 'OPER_STATUS', 'TRACKER_STATUS', 'DESC', 'IPV6_ADMIN_STATUS']
    df['ROUTERNAME'] = routername
    df['LOG_DATE'] = dt.datetime.today().strftime("%m/%d/%Y")
    return spark.createDataFrame(df)


Paypal PHP API - UNAUTHORIZED_AGREEMENT_REQUEST

Question: I am setting up a Payment agreement using Paypal Rest API.
In sandbox mode, this works fine, I can create the Plan and set up the agreement for the plan.
however when going live, I get the following error:
<code>UNAUTHORIZED_AGREEMENT_REQUEST
You don't have permission to create such agreement.
</code>
I have Enhanced Recurring Payments enabled on my account. So , I thought that would be all that was required.
The steps I am taking are:
<code> $plan = new Plan();
 ....
$output = $plan->create($apiContext);
$planID = $output->getId();
</code>
Then create the agreement based on the PlanId
<code>$agreement = new Agreement();
....
 $plan->setId($planID);
 $agreement->setPlan($plan);
 .....
 $createagreement = $agreement->create($apiContext);
</code>
The $agreement->create is the call that is failing.
Is there something I am meant to enable either on the site or on the developer app settings in order to get this to work, or am I missing something else?
Comment: Can you provide the debug id received in the PayPal response ?
Comment: Did you solve your problem ?
Comment: @VarunNaharia While it worked in sand box mode, It doesnt work in all regions on the live site. Pay Pal told me this, while it wasn't clearly stated that this was the case, it was the issue for me. You may want to check with Pay Pal to find out if its available in your region.
Comment: @CharlieSmith I asked you this to if my answer helped you to solve your problem ?
Answer: Ask the paypal MTS executive via mail they will help you within Hours here is the link
Paypal MTS
Believe me they are very helpful


WPF - Error after using Int32.Parse

Question: After using Int32.Parse in ComboBoxNotEmptyValidationRule class I get an error:
Input string was not in a correct format.

When I add to XAML:
<local:ComboBoxNotEmptyValidationRule x:Name="Number" ValidatesOnTargetUpdated="True"/>

Program is Running normaly and this walidation work properly. In design window I haven't any content, only FormatException: Input string was not in a correct format. message. Everything is allright when I comment this line in XAML.
class ComboBoxNotEmptyValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            int str = -1;
              str = Int32.Parse(value as string);
            if (str > 0)
            {
                if (str > 0)
                    return ValidationResult.ValidResult;
            }
            return new ValidationResult(false, "please fill required field");
        }
    }

Comment: Can you show more code?  We don't know what `ComboBoxNotEmptyValidationRule` is, etc.
Comment: @Jeff-Meadows I add this class.
Comment: Are you sure value is of type string? What is the content of value?
Answer: You could use int32.TryParse
class ComboBoxNotEmptyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        int str;
        if (Int32.TryParse(value as string, out str))
        {
            if (str > 0)
                return ValidationResult.ValidResult;
        }
        return new ValidationResult(false, "please fill required field");
    }
}

Alternatively, you could catch FormatException and return your false validation result.
class ComboBoxNotEmptyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        int str = -1;
        try
        {
            str = Int32.Parse(value as string);
            if (str > 0)
            {
                if (str > 0)
                    return ValidationResult.ValidResult;
            }
            return new ValidationResult(false, "please fill required field");
        }
        catch (FormatException)
        {
            return new ValidationResult(false, "please fill required field");
        }
    }
}

WPF - Error after using Int32.Parse


Como contar funcionários menores de idade?

Question: Utilizo o código abaixo para exibir o número de funcionários ativos:
{{ $relatorio->Empresa->Funcionario->where('id_status', 1)->count() }}

Como faço para contar somente os funcionários que tenham menos de 18 anos?
na tabela de funcionários tenho a data de nascimento no formato date "2000-09-23"
Answer: A maioria dos bancos de dados, a cláusulas where aceita mais de um parametro. Cassi tenha sido você quem fez esta classe de select, certifique-se de que ela  aceite mais parâmetros.  Esse segundo paramatro seria:
SELECT *
FROM table
WHERE id_status = 1 and colunaDataNascimento::date < '".dates("Y-m-d",strtotime ("-18 years"))."' -- deve estar em ISO-8601 format, YYYY-MM-DD


Use the division algorithm to prove that 3|(n³ + 2n) for all n ∈ ℕ

Question: I can do it by induction, thanks to the wonderful people of this website, but I'm not sure how to do it by the Division algorithm. Can anyone help me? I think I can show how 3 divides 2n, but I'm not sure how to show that 3 divides n³.
Comment: "I think I can show how 3 divides 2n, but I'm not sure how to show that 3 divides n³" Actually none of these is true, for example 3 does not divide 2n = 2 when n = 1.
Comment: What about considering $n^3$ and $2n$ together and then show that whenever $n$ is odd or even, $n^3 + 2n$ is a multiple of $3$?
Answer: Note that $$n^3+2n=3n^2+n(n-1)(n-2),$$ hence it would suffice to show that $$3\mid 3n^2\qquad\text{and}\qquad 3\mid n(n-1)(n-2),$$ to deduce that indeed, $$3\mid n^3+2n.$$ Can you proceed?
Comment: A little bit. Could you explain it a little for me?
Comment: Sure, which part and which problem? Please be specific.
Comment: What about the 3 dividing n(n-1)(n-2)? How does 3 divide that?
Comment: This is the product of 3 consecutive integers hence at least one of them is $______$.
Comment: Hence at least one of them is divisible by 3.
Comment: Indeed, and your proof is now complete.
Answer: $$n^3+2n=n^3-n+3n=\underbrace{(n-1)n(n+1)}_{\text{product of three consecutive integers}}+3n$$
See The product of n consecutive integers is divisible by n factorial
Answer: This is less elegant and less fun than Did's answer, but you could try using the Division Algorithm. The Division Algorithm says that you can find integers $q$ and $r$ such that $n=3q+r$ and $r$ is $0$, $1$, or $2$. So there are three cases: (i) $n=3q+0$, (ii) $n=3q+1$, and (iii) $n=3q+2$. In each case you can show that $n^3+2n$ is divisible by $3$.
For instance, here's how you can do case (iii): if $n=3q+2$ then
$$n^3+2n=n(n^2+2)=n([3q+2]^2+2)=n(9q^2+12q+6),$$
and so
$$\frac{n^3+2n}3=n(3q^2+4q+2)$$
is an integer, showing that $n^3+2n$ is divisible by $3$.
Comment: +1. A complete answer should probably include this basic always-working approach.
Answer: Actually :
if n=3*k, then 3 divides n*(n^2 +2)
if n= 3*k +1  --> n^3 +2n = 1 + 2*1 = 0 mod(3)
if n= 3*k +2  --> n^3 +2*n = 8+ 4 = 0 mod(3)
So 3 always divides n^3 +2*n, for every n positive integer


Form navigation showing unsorted records in MS Access

Question: I have a form in MS Access that have 153 records. The "ID Number" field is primary key and its format is auto numbers.
When I navigate this form to "First Record" it showing "ID Number" 68 instead of "1".
On "next record" it showing "ID Number" 97 instead of "2". On next record it showing "ID Number" 75 instead of "3" and so on.
I have not use any custom macro to navigate records. But I don't know why my form showing unsorted records.
Answer: Rather than relying on the order in which the records appear in a table/query being the order in which they are presented by a form, it is more reliable to specify a sort order either as part of the SQL for the Record Source, or within the Order By property found within the Form Data properties, with Order By On Load set to Yes.
Answer: My issue has been resolved by doing the following steps

Open the form in design view
In property sheet removed the Record Source
Save and close the form
Open the form again in Design view
Re-enter the Record Source.
Comment: That is pure luck only. Do implement the method described by Lee.


How to get last 2 digits of year from Javascript date

Question: I have string in the following format "30.11.2019". I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19".
The following code doesn't work
var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear();

Comment: simple modulo 100 operation
Answer: new Date() does not work with a single string argument in that format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Easiest way is to call it with 3 arguments (year, month, day).
Do note that month is the month index (0 based), so November (11th month) is actually 10th in the format that Date expects.
  new Date(2019, 10, 30).getFullYear() % 100;
  // returns 19;

If you can't do it this way and you simply must work around the string format mentioned, then you can just do
const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);

Answer: I'm not entirely sure if you want only short representation of the year or whole date, BUT with short representation of the year on it - if so, then I would suggest using toLocaleDateString method:
new Date(2019, 10, 30).toLocaleDateString('pl', {day: 'numeric', month: 'numeric', year: '2-digit'})

It will return you:
"30.11.19"

or if you want to get the short year date only:
new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})

it will return you:
"19"

Comment: +1 for using .toLocaleDateString()
this is what it was built for.
Answer: You can get last two digits with the following code:
var strDate = new Date(); // By default Date empty constructor give you Date.now
var shortYear = strDate.getFullYear();
// Add this line
var twoDigitYear = shortYear.toString().substr(-2);

Answer: Since the string you're using isn't in a format recognized by Date.parse() (more on that here), you need to manually create that Date object.
For example:

const strDate = '30.11.2019';
let [d,m,y] = strDate.split(/\D/);
const date = new Date(y, --m, d);

console.log(date.getFullYear())

You can then use Date.getFullYear() to get the year and extract the last two digits, as you need.
Comment: @ndrewl the second argument to Date() is an integer value representing the month, beginning with 0 for January to 11 for December. Since the numeric representation of the month in the original string begins with 1 for January, we need to reduce it by `1` before we pass it to Date(). Does that answer your question?
Comment: @RobG that is so much more elegant! Updating the answer accordingly :)
Comment: Why do you need --m in `new Date(y, --m, d)`?
Comment: Yes, thanks! I'm currently learning JavaScript, and it seemed a bit unnatural to me that days start at 1, but months at 0. If someone else is interested, here is the reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Answer: var strDate = "30.11.2019";
var lastdigit = strDate.slice(-2);

Comment: While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value.
Answer: do not need split string, I think.
using moment
yarn add moment
const moment = require( 'moment' );

const simpleYear = moment( "30.11.2019", "DD.MM.YYYY" ).format( "YY" );
console.log( "simpleYear = " + simpleYear );


Making a tabbed cef sharp browser rename tab page

Question: i have been creating a cefsharp browser in C#. i have made it so you can have multiple tabs and it loads the pages correctly. however, i cannot seem to find how i can rename the tab to the name of the page.
this is the code in the load event for form1.cs:
                    Cef.Initialize();
        toolTip1.SetToolTip(button1, "Settings");
        TabPage tab = new TabPage();
        Tab newtab = new Tab();
        newtab.Show();
        newtab.TopLevel = false;
        newtab.Dock = DockStyle.Fill;
        tab.Controls.Add(newtab);
        tabControl1.TabPages.Add(tab);

i have tried:
                    private void myBrowser_isLoading(object sender)
    {
        myBrowser.Parent.Parent.Text = myBrowser.Title;
    }

but that doesn't work.
then this is the code for tab.cs:
                    public Tab()
    {
        InitializeComponent();
        // Start the browser after initialize global component
        InitializeChromium();

    }
    public CefSharp.WinForms.ChromiumWebBrowser myBrowser;
    public bool nav = new bool();
    public void InitializeChromium()
    {

         myBrowser = new CefSharp.WinForms.ChromiumWebBrowser("http://www.google.com");
        this.Controls.Add(myBrowser);
        myBrowser.Dock = DockStyle.Fill;

        myBrowser.Parent = panel2;
    if (nav == true)
        {
            myBrowser.Load(textBox1.Text);
            nav = false;
        }

    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Cef.Shutdown();

    }

again, i am using c# with the latest build of cef sharp(or atleast the one installed from the nuget package manager).
Comment: i forgot to mention i am using a windows forms project (you can probably already tell).
Comment: also it is parent.parent.text because the browser's parent is a panel.
Comment: The `CefSharp` source contains a `WinForms` example that's tabbed, check it out for a reference. Subscribe to the `TitleChanged` event for notifications when the title changed.
Comment: @amaitland hey, thanks for your help, but i have been looking all through the cef sharp source and couldnt find where the TitleChanged event was. if you could go more indepth or even take the time to answer the question, that would be great :)
Comment: I don't have a clue what's going on with your code. Just search the solution for the keyword.
Comment: @amaitland i have already done that, thanks for the help.
Comment: really though, i really need an answer
Comment: The best I have time for is pointers. The `CefSharp` source contains a working tabbed browser, what more do you need?
Comment: @amaitland i have already looked all through the cef sharp winforms source, i found nothing to help (although i did find stuff to help for other things), im not saying you have to answer, i just need an answer from anyone who knows the answer.
Answer: In your tab function in form1.cs, you need to add a title changed function like this
browser.TitleChanged += OnBrowserTitleChanged;

you also need to specify what browser is and set dockstyle to fill like this
ChromiumWebBrowser browser = new ChromiumWebBrowser("google.com");
tab.Controls.Add(browser);
browser.Dock = DockStyle.Fill;

now for the OnBrowserTitleChanged, you will need an EventArg which will tell the tab to have the document title in this format
this.InvokeOnUiThreadIfRequired(() => browserTabControl.SelectedTab.Text = args.Title);

this will add the document title to the tabcontrol browserTabControl is the name of the tabcontrol you will have to change browserTabControl to whatever name you have for the tabcontrol. Also the code you have does not belong with cef initialize. you need to create an addNewTab method with all the functions that will be processed when you want to add a new tab. Also, you cannot use a panel if you want to have tabs. you need a tabcontrol
Comment: First of all, im not using a panel to do it. i made the panel its parent, then the panel is the child of the tab control. i also have an addnewtab method. also, i have already found out about the cef.initialize thing and fixed it.
Comment: also, it gives me an error under this.InvokeOnUiThreadIfRequired(()  saying... wait first i need to say something that just MIGHT change things. i have it in a form  called "tab" every time you create a tab, it does this:                                                                                TabPage tab = new TabPage();
            Tab newtab = new Tab();
            newtab.Show();
            newtab.TopLevel = false;
            newtab.Dock = DockStyle.Fill;
            tab.Controls.Add(newtab);
            tabControl1.TabPages.Add(tab);
Comment: @JamDoggie anyway, it says its not referenced in the class. that might be stupid of me.
Comment: If you use a tabcontrol, you dont need to use a panel reread the code i provided you should have no problem understanding it and you also need to look at the documents on github to complete the addNewTab method. If you still have problems with this, you should try to do something else
Comment: i used a panel to minipulate the browser control easy without having to do it in code. i have since figured this out, i will mark the answer you gave as correct because the error was on my part. thanks.