How to use entity_reference programatically

Question: i'm building a module with an Company entity, this entity should be linked to other 2 entities and i think that the type "entity_reference" should be useful for this pourpose, but i dont see how configure this, and only found tutorials to make this by UI, some know how should use or known some link where is weel explained?
There is my actual code, "producto" and "tipo" should be "entity_reference"
<code>public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('Identificador de la empresa.'))
            ->setReadOnly(TRUE);

        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('Identificador único de la empresa.'))
            ->setReadOnly(TRUE);

        $fields['razon_social'] = BaseFieldDefinition::create('string')
            ->setLabel(t("Nombre de la empresa"))
            ->setDescription(t('Nombre de la empresa.'))
            ->setSettings(array(
                'max_length' => 255,
                'text_processing' => 0,
            ))
            ->setRequired(TRUE);

        $fields['logo'] = BaseFieldDefinition::create('uri')
            ->setLabel(t('Logo'))
            ->setDescription(t('Logo de la empresa.'))
            ->addPropertyConstraints('value', ['Image' => []])
            ->setRequired(TRUE);

        $fields['resumen'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['url'] = BaseFieldDefinition::create('string')
            ->setLabel(t("URL"))
            ->setDescription(t('Sitio web de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 255,
                'text_processing' => 0,
            ))
            ->addPropertyConstraints('value', ['Url' => []]);

        $fields['quienes_somos'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Quienes Somos'))
            ->setDescription(t('Texto del Quienes Somos.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['mision'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Misión'))
            ->setDescription(t('Misión de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['vision'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Visión'))
            ->setDescription(t('Visión de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['tipo'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['producto'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 255,
                'text_processing' => 1,
            ));

        return $fields;
    }
}
</code>
Answer: To add entity_reference try something like, the following example to reference to user:
Adapted it to your use case.
<code>$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of Entity entity.'))
      ->setRevisionable(TRUE)
     // Set your target type here change user by your target.
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);
</code>
Comment: you are welcome, i'm glad that help, yeah of course you can just change the `target_type` to your target_type, it will works.
Comment: Is just the example that i need! :D I love you hehehehe, is possible with the same code link others entities created by me by the same way? Thanks in advance.


Where do I include custom JS and CSS files in Laravel 9?

Question: I'm manually downloading these CSS and JS files from: https://github.com/1j01/os-gui
I'm not sure where in my Laravel 9 app I should place the CSS and JS files.
What's the proper way to do it? Should I just download and place the files in the public directory? But shouldn't I be utilizing Laravel 9's Mix to compile the JS CSS files, and if so how can I go about doing that?
This is the list of files I want to use:
css/layout.css
css/windows-98.css
css/windows-default.css
js/$Window.js
js/MenuBar.js
js/parse-theme.js
js/demo.js
js/jquery-3.3.1.js // i'll probably use v3.6.0 (or whatever is the latest version)

Comment: I usually place them inside of the public folder i create a assets directory that contains the js and css files but you can also place them inside of resources/assets directory as well. I believe laravel comes built in with those directories.
Answer: If you want those files to be optimized and controlled and also want that every request does not download a bunch of css and js files, you should use laravel mix which is installed by default
You should put those files inside /resources folder and compile them into a single file, adittionally you could purge with the mix purge plugin so your assets will be purged/optimized.
This is really simple in your webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
    .css('resources/css/app.css', 'public/css', [
        // and in your app.css you can @import every css you need to load
    ]);

Comment: When I placed the files inside of ```resources/js/os-gui``` and ```resources/css/os-gui``` and I ran ```npm run dev```, the two files ```app.js``` and ```app.css``` were the only ones compiled ```608 KiB``` and ```1 bytes``` respectively (obviously the file sizes are too low, which hints to the fact that the ```os-gui``` js and CSS files weren't compiled). Is there something I'm doing wrong?
Comment: From mix example usage you have to tell mix what to compile.
`/* src/app.css */

@import 'layout.css';
@import 'windows-98.css';
@import 'windows-default.css';

body {
    color: red;
}` https://github.com/laravel-mix/laravel-mix/tree/master/docs


How do I display my Android device's screen on my mac?

Question: I would like to display my Android device's screen on my mac for a presentation. I don't care if I have to use a USB cable or wifi. What is the best way to do this?
Comment: check this thread http://android.stackexchange.com/questions/34933/android-remote-screen-display-control
Comment: FWIW, the `screenrecord` in Android 5.0 will send raw H.264 over an ADB connection.  See http://stackoverflow.com/questions/27394916/android-native-opengl-openmax-screen-capture/27475298#27475298
Answer: Update
Starting from Android Studio 2022.2.1 Device mirroring is under "Tools" menu in "Preferences" or "Settings" (For mac users).
How to show the screen of a physical device inside Android Studio?
Old Answer
Droid@Screen might work for you.  I've never used it on a Mac but it's just a jar so it should work.


Find all triples of positive integers (x, y, z)

Question:
I've no idea how to attempt such a question. I tried eliminating z from the equations to get a quadratic equation in terms of x, so I could use the fact that the discriminant would be a perfect square. Please help
Comment: Please do not post unsearchable images of text or equations.  Instead, typeset using *MathJax*.
Answer: You have the $2$ equations
$$x^2 + y - z = 100 \tag{1}\label{eq1A}$$
$$x + y^2 - z = 124 \tag{2}\label{eq2A}$$
Next, \eqref{eq2A} minus \eqref{eq1A} gives
$$\begin{equation}\begin{aligned}
x - x^2 + y^2 - y & = 24 \\
-4x^2 + 4x + 4y^2 - 4y & = 96 \\
-(4x^2 - 4x + 1) + (4y^2 - 4y + 1) & = 96 \\
(2y - 1)^2 - (2x - 1)^2 & = 96 \\
(2y - 2x)(2y + 2x - 2) & = 96 \\
(y - x)(y + x - 1) & = 24
\end{aligned}\end{equation}\tag{3}\label{eq3A}$$
Also, as Neat Math's comment states, it would have been simpler & easier to use $x - y + y^2 - x^2 = -(y - x) + (y - x)(y + x) = (y - x)(y + x - 1)$.
With $x$ and $y$ being positive integers means $y + x - 1 \gt 0$, so $y - x \gt 0$. Next, note the parity of $y - x$ and $y + x - 1$ are different, i.e., one is even and the other odd. The only odd & even set of divisors of $24$ are $(1, 24)$ and $(3, 8)$. Since $y + x - 1 \gt y - x$, this means we have first the possibility of
$$y - x = 1 \tag{4}\label{eq4A}$$
$$y + x - 1 = 24 \implies y + x = 25 \tag{5}\label{eq5A}$$
Adding \eqref{eq4A} and \eqref{eq5A} gives $2y = 26 \implies y = 13$, so $x = 12$, with \eqref{eq1A} and \eqref{eq2A} giving $z = 57$. The second possibility gives
$$y - x = 3 \tag{6}\label{eq6A}$$
$$y + x - 1 = 8 \implies y + x = 9 \tag{7}\label{eq7A}$$
Adding \eqref{eq4A} and \eqref{eq5A} gives $2y = 12 \implies y = 6$, so $x = 3$, with \eqref{eq1A} and \eqref{eq2A} giving $z = -85$. However, since this is not a positive integer, it's not allowed.
Thus, the only triple of positive integers solution is $(x, y, z) = (12, 13, 57)$.
Comment: Completing the square is unnecessary.

$$ x - x^2 + y^2 - y  = 24 = (y+x)(y-x)-(y-x)=(y-x)(y+x-1).$$
Comment: @NeatMath Thanks for the feedback. I'm not sure why I didn't notice that myself. I've added your alternative to the answer.
Answer: $$(x,y,z) = (-3,6,z)\quad {\rm or}\quad (12,13,z)$$
for any integer value of $z$.
So there are an infinite number of solutions.
Comment: Problem asks for positive integer solutions.


Debugging Scheme in Emacs

Question: I am shifting from DrScheme to Emacs to edit my PLT Scheme files. Can you teach me how to use steppers or debuggers in Emacs?
Thanks.
Answer: Tracing functions can be helpful for debugging.
<code>(trace function-name)
</code>
It will print arguments and return value.
To turn off tracing use:
<code>(untrace)
</code>
Comment: It's one of the best features for debugging. In Plt Scheme, make sure you (require (lib "trace.ss")) before.
Answer: Would something as simple as scheme-mode suffice or do you need something more along the lines of QuackMode? I highly-suggest you read around the Emacs Wiki article on Scheme as it describes a fair number of options regarding Scheme and Emacs. To be quite honest, a debugger and stepper wouldn't necessarily be found in Emacs even though they were present in DrScheme which is a specific environment. Perhaps looking for a Scheme debugger you like should be done before you figure out how to hook it into Emacs.
All this being said, I'm pretty sure that MIT-Scheme has what you want because you can run a Scheme process from Emacs. Also, there's EdWin.
Answer: You cannot do that with DrScheme's stepper and/or debugger, since they are currently integrated into DrScheme's GUI.  It probably won't be too hard to make the connection, but nobody bothered with this work so far.
Comment: Sir, how do you debug your scheme files in emacs? I really love my emacs but I dont think I can live without a good debugging option.
Comment: Well, there are many options for that.  In fact, for the PL class, the lack of DrScheme's debugger and stepper will not be a problems since they will not be relevant tools even inside DrScheme.  The good way to work is just the same as what HtDP teaches: write good contracts, write tests, and make sure that your code passes the tests.  If you do all of that, you will find that debugging is something you need much more rarely, and in cases where you need it, simple printouts will do just fine.
Answer: you can try to setup slime for some scheme implementation. Look to my article about Emacs + Scheme
Answer: This isn't the answer you're looking for, but I've found the best way to debug is to insert "printf"s throughout the code.  Pretty Neanderthal, but ...

Debugging Scheme in Emacs


Trying to understand relative homology group

Question: I'm reading about relative homology group but I'm having hard time in understanding this concept.
So I was trying to find $H_1(D^n,S^{n-1})$, but I'm unable to solve this problem. Can someone give some idea for $n=1$ (Then I'll try to generalize it)?
Added By using long exact sequence as suggested in comment I get $H_n(D_n,S^{n-1})$ is isomorphic to $H_{n-1}(S^{n-1})$.How to proceed further?
Comment: You can use the long exact sequence of the pair, see e.g. https://en.wikipedia.org/wiki/Relative_homology#Properties
Comment: A possible approach: You should start with the definition of the relative chain complex. Then go on with the long exact sequence of homology.
Comment: @QuangHoang but that does not work for $n=1$,I think?
Comment: OP, maybe you want to try to clarify what is exactly that you don't understand?
Comment: @SilviaGhinassi I think I understand the definition of Relative homology group but still I'm not getting a way to compute it.Can you tell about my particularexample which I'm trying?
Comment: @Pedro but this does not work for $n=1$,right?
Answer: The long exact sequence of the pair (plus the fact $H_1(D^1) = 0$) gives us the exactness of
$0 \to H_1(D^1, S^0) \to H_0(S^0) \to H_0(D^1) \to H_0(D^1, S^0) \to 0$
Hence $H_1(D^1, S^0)$ is just the kernel of the map $H_0(S^0) \to H_0(D^1)$. Recall that (assuming integer coefficients) $H_0(S^0) \cong \mathbb{Z} \oplus \mathbb{Z}$ and $H_0(D^1) \cong \mathbb{Z}$. The application $H_0(S^0) \to H_0(D^1)$ is induced by the inclusion $S^0 \hookrightarrow D^1$. Hence in terms of generators it is the application $\mathbb{Z} \oplus \mathbb{Z} \to \mathbb{Z}$ given by $(x, y) \mapsto x + y$. Hence its kernel is $\cong \mathbb{Z}$, and thus we have established $H_1(D^1, S^0) \cong \mathbb{Z}$.
Comment: (+1),Can you please add for general  $n$ too?Thank you!
Comment: The ideas are the same... what are you having trouble with?
Comment: By using long exact sequence I got $H_n(D^n,S^{n-1})$ is isomorphic to  $H_{n-1}(S^{n-1})$ then how to proceed?Do we need to use some induction argument?
Comment: You can use, for example, the Mayer-Vietoris sequence to show $H_{n-1}(S^{n - 1}) \cong \mathbb{Z}$. This is a well-known calculation which you can find in any algebraic topology textbook
Comment: Or the fact that, since $(D^n, S^{n - 1})$ is a good pair, $H_n(D^n, S^{n - 1}) \cong \widetilde{H}_n(D^n / S^{n-1}) \cong \widetilde{H}_n(S^n)$ and so inductively calculate this.


Determine the $n$th string among those of a given length in alphabetical order starting at a given string and using a given character set?

Question: When building strings using a particular character set (the set can change), such as in a brute-force password cracking, how would I determine which string occurs in the $n$th position when the strings are ordered alphabetically for each length, starting at a given string? (Conversely, what is the position of a given string among those of the same  length, starting at a given string of that length?)
For example, if the character set is $ABCDEFG$, then among the strings of length 2, starting at $AA$, string $AC$ is in position 3 and string $AE$ is in position 5:
$$\begin{matrix}
\text{position:}&1&2&3&4&5&6&7\\
\text{string:}&AA&AB&AC&AD&AE&AF&AG
\end{matrix}
$$
I am programming in Delphi and want to use a function that returns the string:
function CharArrayPosToStr(ca: TCharArray; len, pos: Integer): String;
The purpose is to break the job into working sets of given lengths, so I need to be able to quickly determine something like:  Set 1 starts at $AAAA$ and ends at $AAQA$ and set 2 begins at $AAQB$, etc.
Answer: The shortlex ordered list of all words on the seven-letter alphabet $ABCDEFG$ is
$$A,B, C, D, E, F, G, AA, AB, ..., GF, GG, AAA, ..., GGG, ...$$
If we replace the letters $A,B,C,D,E,F,G$ with the nonzero digits $1,2,3,4,5,6,7$, then
this becomes the list of positive integers written in bijective base-7 notation (in numerical order):
$$1, 2, 3, 4, 5, 6, 7, 11, 12, ..., 76, 77, 111, ..., 777, ...$$
More generally, in the shortlex ordering of all the words on the digit-set $\{1, 2, ..., k\} (k \ge 1)$, the $m$th word is $a_n a_{n−1} ... a_1 a_0$, where
$$\begin{align}
a_0 & =  m   - q_0 k ,   & & q_0  =  f\left(\frac m   k \right)  \\
a_1 & =  q_0 - q_1 k ,   & & q_1  =  f\left(\frac {q_0} k \right) \\
a_2 & =  q_1 - q_2 k ,   & & q_2  =  f\left(\frac {q_1} k \right) \\
    & \vdots             & &     \vdots  \\
a_n & =  q_{n-1} - 0 k , & & q_n  =  f\left(\frac {q_{n-1}} k \right)  = 0
\end{align}
$$
and
$$f(x) = \lceil x \rceil - 1.$$
So, to find the $m$th word in the shortlex ordering of words on an alphabet of $k$ letters, just use the preceding algorithm to find the bijective base-$k$ numeral for $m$ (and convert back to letters using the reverse substitution).
Also, note that the list-position $m$ of a given word is obtained simply by making the digit-substitution and then reading the result (say $a_n a_{n−1} ... a_1 a_0$) as a bijective base-$k$ numeral:
$$
m = (a_n a_{n−1} ... a_1 a_0)_{\text{bijective base-}k} = a_n\ k^n + a_{n-1}\ k^{n-1} +  ... + a_1\ k^1 + a_0\ k^0.$$
NB:
If you're interested in the positions of certain words relative to that of others (i.e. in a particular list segment), just find the relative position by the appropriate subtractions.
Answer: I realize this is an old thread, but the problem seemed familiar, and I recognized I've had a solution for years. In VBA, you can do it like this:
Function ShortlexPos(sInp As String, sSym As String) As Long
  If Len(sInp) Then ShortlexPos = InStr(sSym, Right(sInp, 1)) _
     + Len(sSym) * ShortlexPos(Left(sInp, Len(sInp) - 1), sSym)
End Function

For example, columns in Excel are named
A, B, ..., Y, Z, AA, AB, ..., AX, AY, AZ, BA, ... XFD
The position of the last column is given by
ShortlexPos("XFD", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")

... which (correctly) returns 16384.
The complementary function returns the sequence at a given position:
Function ShortLexStr(iNum As Long, sSym As String) As String
  If iNum > 0 Then ShortlexStr = ShortlexStr((iNum - 1) \ Len(sSym), sSym) & _
   Mid(sSym, ((iNum - 1) Mod Len(sSym)) + 1, 1)
End Function

For example,
ShortLexStr(16384, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")

returns XFD


Module update manually multiple versions at once

Question: Actually my website use module views 7.x-3.5 version. The last version is 7.x-3.11, so i need update. My question is if I can upgrade (replace folders and code) directly to version 7.x-3.11 and run mysite\update.php or I need apply each new version separately running update.php for each, e.g. views 7.x-3.6, views 7.x-3.7...
Answer: You can replace it with the latest version and run update.php. Drupal modules keep track of what version data schema it's on; update.php will apply the needed DB updates since 7.x-3.5.


RegExp não pega o valor do input

Question: Preciso extrair o valor de uma tag html
<input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">

Estou usando uma Expressão Regular para retornar o valor do input
   $pattern = '~<input type=hidden id=X-Tmx-session-id name=X-Tmx-session-id value=(.*?) \/>~';
   preg_match($pattern, $get, $xArray);
   var_dump($xArray);

só que a minha expressão retorna apenas um array vazio: array(0) { }
Preciso pegar apenas o value do input

2530317385
Comment: @LucasCasterlamar o teu ultimo edit deformou a pergunta. Restaurei a pergunta. Se quiseres podes apagar a pergunta ou pedir ajuda a um dos moderadores para apagar. Se tiveres duvidas comenta aqui ou no meta (http://meta.pt.stackoverflow.com/) que nós ajudamos.
Comment: @Sergio eu não entendi o porque ele copiou o código da resposta e colocou na pergunta, acho que ele não entendeu como funciona o Stackoverflow. Rollback to Revision 3. Lucas somos uma comunidade de perguntas e respostas, se o código da resposta não funcionou você pode comentar falando o problema na propria resposta.
Comment: Você apenas retornoar o `value` desse input? `$_GET/$_POST` não resolve isso?
Comment: A Variável $get ela recebe o html que vem do cuRL
Answer: O teu RegEx é diferente do teu html-input, só comparar:
 <input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
~<input type=hidden id=X-Tmx-session-id name=X-Tmx-session-id value=(.*?) \/>~

Falta as aspas, a posição solicitada pelo RegEx é diferente.
Se você está recebendo um html por curl, porque não usa o DOM para pegar os elementos? Por exemplo:
$get = '<!DOCTYPE html>

    <title></title>

<input value="test1">
<input value="test2">
<input value="test3">

';

$doc = new DOMDocument();
@$doc->loadHTML($get); //O @ previne mostrar erro de HTML

$allInputs = $doc->getElementsByTagName('input');
foreach ($allInputs as $input) {
    echo $input->getAttribute('value'), '
';
}

Ou com XPath (acaso necessite de seletores mais avançados):
<?php
$get = '<!DOCTYPE html>

    <title></title>

    <input value="2530317381" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317382" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317383" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">
    <input value="2530317384" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">

';

$doc = new DOMDocument();
@$doc->loadHTML($get);

$xpath = new DOMXpath($doc);
$doc = NULL;

$allInputs = $xpath->query('*/input[@id=\'X-Tmx-session-id\']');

foreach ($allInputs as $input) {
    echo $input->getAttribute('value'), '
';
}

Exemplo online: https://ideone.com/i9ZCsg
Comment: Os dois exemplo me retorno erro $allInputs = $dom->getElementsByTagName('input');

$allInputs = $xpath->query('*/input[@value]');
Comment: @LucasCasterlamar que erro?
Comment: COm Xpath ele não me retorna nada na tela.
Comment: e no primeiro
Fatal error: Call to a member function getElementsByTagName() on a non-object in /

nessa linha $allInputs = $dom->getElementsByTagName('input');
Comment: @LucasCasterlamar corrigido os dois códigos e adicionado exemplo com XPath :)
Comment: Vou edita minha pergunta com o código que usei e seguindo o seu exemplo
Comment: @LucasCasterlamar a minha resposta resolveu o teu problema? Se sim marque a resposta como correta, se não comente o que falhou. Se não entendeu como o StackOverflow funciona, faça um tour (você ganha uma medalha só por fazer isto rs): http://pt.stackoverflow.com/tour
Answer: Eu também recomendo a utilização da biblioteca DOM contudo prefiro utilizar esta.
Agora caso queira ratomar a tentativa por ER, tente:
Exemplo
$id = 'X-Tmx-session-id';

$pattern = "~(?=<input.*id=['\"]*{$id}['\"]*.*)<input.*value=['\"]*([^'\"]*)['\"]*.*~";

$get = '<input value="2530317385" name="X-Tmx-session-id" id="X-Tmx-session-id" type="hidden">';

preg_match($pattern, $get, $xArray);

echo "
";
var_dump($xArray[1]);

RegExp não pega o valor do input


Placing a server in the DMZ vs opening firewall ports

Question: When should you place a server in a DMZ vs opening ports on the firewall and keeping it within the network? I'm referring to active directory servers, IIS servers, and mostly things on a windows based setup.
Some issues I've noticed with placing in the DMZ is that it's no longer on the domain, it doesn't have nameserver access to our internal servers, and a few other things that make it strange to work with.
Answer: A server placed in a DMZ can't open connection to your network because there is a firewall in the middle (by the very definition of DMZ), so your network will be protected from it, should it ever be compromised by an attacker: in this scenario, the compromised server could not be used as a starting point to launch new attacks against the rest of your network. This is instead not the case if the server is placed inside your network, and you open firewall ports to allow external users to access it using the services it provides. The same succesful external attack (f.e. against a web site) would lead to very different consequences if your server is in a well-guarded DMZ or inside your LAN.
That said, placing a server in a DMZ is really only useful if you can actually filter the traffic between it and your internal network; if it requires domain controller access for authentication, database access for back-end data and mail access for sending out messages (like an Exchange CAS), and you need to open all of those ports between it and internal servers in order for it to actually do anything useful, then there really isn't much of a point in placing it in a DMZ. Domain member servers are the worst offenders here: domain access requires so many open ports between a computer and its domain controllers that it could as well be placed in the same network as them; and a compromised domain member computer is a big security pain, because it can access lots of things in the domain.
Rule of thumb for Windows servers: if it needs to be a domain member, then placing it in a DMZ is A) a pain to get it to work correctly and B) almost useless; keep them in your LAN, but be sure to keep them fully patched, running a good antivirus and protected by a well locked down external firewall. The best approach here is using a reverse proxy, an inbound mail relay, or anything else that can act as an application gateway, and avoid exposing them directly to the Internet.
Answer: A good rule of thumb is to consider the damage that could potentially be done if the server were to be compromised via the service that you've opened.  You'll want to consider two factors for each device: the risk level ("How likely is this to get compromised?" - this measure should go way up as soon as a service is internet-exposed) and the sensitivity level ("How much of a loss would it be if this system were compromised?  Is there important/confidential data?").
For high risk systems, you should endeavor to keep their sensitivity as low as possible.  This is the reason that you build a DMZ.
The idea of a DMZ is to isolate the high-risk systems, so that an attacker needs to penetrate an additional layer of security (another firewall) to access your highly sensitive systems.  You'll likely need some connections between the DMZ and the internal network, but try to push data outward to the DMZ instead of allowing connections inbound to the internal network.
Answer: If the server get compromised when you open ports to the internal network, potentially the attacker will have access or much easier way to perform attacks toward internal systems. In today's world, most of the system that you're planning on deploying in DMZ can be tweaked and configured to perform some type of Internal/DMZ network distinguish. As a matter of fact, the only way the traffic should flow is from your INTERNAL network to DMZ, essentially, the internal servers opening connections towards servers in DMZ.


How can I set apache to listen 43 port

Question: I am trying set up my own whois server, that user can request by command
whois -h mywhois.server domain.com

I inserted in apache.conf Listen 43 and created vhost like this
<VirtualHost *:43>
    ServerName whois.test.dev
    DocumentRoot /var/www/whois.test.dev
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

But when I request via terminal it returns bad request, with other ports i  t works normal (e.g. 8080)
What is the problem with that
Answer: It's wrong configuration for WHOIS because Whois it's service like an apache or nginx.
By default whois using 43 port for sending answers for whois-requests and you can't assign 43 for the web server virtual host (actually you can but it won't be works).
Answer: Whois doesn't use the http protocol for answering questions... A webserver wouldn't know what to do with the traffic coming from a whois query.
There are web-based whois lookups.... but they just work as a gateway to a backend lookup to a real whois query.
If you want to run a whois service, you need to install a whois implementation like for example rwhois, see for example: WHOIS server daemon

How can I set apache to listen 43 port


Closed form expression for $\sum_{n=0}^\infty H(x - n y) z^n$ involving Heaviside functions

Question: For $x>0$, $y>0$ and $0 < z < 1$ consider the sum
$$
\sum_{n=0}^\infty H(x - n y) z^n\ ,
$$
where $H$ is the Heaviside step function. Is there a way to write down a closed form expression for this?
Answer: This is the sum of a finite geometric progression: $$\sum_{n:x\geq yn,n\geq0}{z^n}=\sum_{n=0}^{\left\lfloor\frac{x}{y}\right\rfloor}{z^n}=\frac{z^{\left\lfloor\frac{x}{y}\right\rfloor+1}-1}{z-1}$$


Drupal cron will unserialize array and add extra characters

Question: I am working in an application using Drupal. Thru the UI I upload a text file that is then parse and each line store in the DB as a serialized array. So far so good until there.
I have setup a module using queue and the hook_cron that will check each of the serialize arrays from the DB and make a node out of it.
I was getting some odd errors like the cron was not able to parse the serialized array and I noticed something odd the array keys were been serialize with extra characters (invisible characters).
While looking in the DB imports I notice that something like the word "comunique" that when serialize should be like:
s:9:"comunique"

instead it was showing like:
s:12:"comunique"

also a print_r show me the following:
[comunique ] => Array (...)

I even test changing the word and there are always 3 characters extra. I tested locally in my computer and it is all good.
What am I missing? is this a server config issue or a code issue?
Comment: Hello. Title of your question looks like a series of tags. Could you please make it human readable? :)
Comment: Can you post your code? Somewhere 3 characters are being added.
Answer: Thank you for your input. I open the PHP file with Notepad++ and there was the hidden tilde character. I remove it an everything started to work again like a charm.
For people having a similar issue, I will recommend opening the file in a different text editor.


Powershell New-SMBShare not running as expected in script

Question: I am working to move some files from one physical drive to another in large group of Windows 2012 servers. The drive letters and sizes are all the same on these servers. Basically we have a share on each server and I want to move that data and share over to another drive that has more free space. I'm trying to develop a script to accomplish the following:

Shrink an existing partition
Create and format new partition using the new free space
Copy files from an existing share/drive to newly created partition
Remove the share from existing drive(the actual drive is being shared)
Recreate share on new drive
Assign new drive the drive letter that was assigned to the old one.
Log any failures

This is the code I have put together. As the title states, I can't get the New-SMBShare to run correctly in this script. I'm not getting an errors but the drive is not shared when the script completes. I am attempting to execute the script from within the Powershell ISE and if I run the same command on it's own, the share is created as expected. What would cause the command to fail when run within the script.
I'm also occasionally getting the following: Format-Volume : Cannot perform the requested operation when the drive is read only
I get this every once in a while when I run this so I'm not sure why it happens intermittently. It almost seems like sometimes the previous command hasn't completed before the formatting command is run.
Finally I'm also not really sure the best way to accomplish logging any errors or even a success message. I've considered using Robocopy instead of Copy-Item for this reason but if anyone knows a good way to accomplish this with Copy-Item, I'd like to here it.
 #Stopping service to prevent "Format Disk" dialog box from appearing on screen
 Stop-Service ShellHWDetection
 #Create New 90GB Partition from W Drive
 Resize-Partition -DriveLetter W -Size (1772GB)
 Get-Disk | where size -GT 1.5TB | New-Partition -UseMaximumSize -DriveLetter K
 Get-Partition -DriveLetter K | Format-Volume -FileSystem NTFS  -NewFileSystemLabel "PC_Images" -Confirm:$false
 #Restart ShellHWDetection service
 start-service ShellHWDetection
 #Copy files from "I drive" PC_Images share to new partition
 Copy-Item -Path I:\* -Destination K:\ -Recurse -erroraction silentlycontinue
 #Remove existing PC_Images share and recreate on new partition
 Get-SMBShare -Name PC_Images | Remove-SMBShare -Confirm:$False
 New-SMBShare -Name PC_Images -Path K:\ -ChangeAccess Everyone
 #Change drive letter on new share to I
 Set-Partition -DriveLetter I -NewDriveLetter X
 Set-Partition -DriveLetter K -NewDriveLetter I

Any help would be appreciated
Answer: I figured out the issue on my primary question. My script changes the drive letter AFTER I created the share which removes the share. If I change the drive letter before creating the share it works as desired. I'm still unsure why I am periodically getting the read only error though.
Answer: I ran into a similar issue with the read only nonsense and resolved it with something like the following (you can pipe New-Partition directly to Format-Volume and omit Get-Partition):
New-Partition … | ForEach-Object { Start-Sleep -s 3; $_ | Format-Volume … }

Comment: Thanks for sharing. The Start-Sleep is a clever way to handle that.


Operator's norm

Question: Let $T$ be a linear densely defined operator on a Hilbert space $H$ and $L$ be a selfadjoint operator with discrete spectrum and $T^{-1}$ is bounded
such that $$\|Tf\| \leq M \|Lf\|^{a}\|f\|^{1-a}, \quad\forall~f \in \mathcal{D}(L),$$ where $0< a<1$ and $M$ is positive constant. In this case, this implication is it always true?
$$\|L^{-1}Tf\|\leq M \|f\|^{a}\|L^{-1}f\|^{1-a}$$
and $L^{-1}T$ is it bounded?
Comment: please the tite of this question must be changed "norm operators"
Comment: By the way, $\alpha<1$ or $\alpha\in(0,1)$? Also, does the first inequality hold for a given $\alpha$ or for all $\alpha<1$?
Comment: I have changed $T^-1$ to $T^{-1}$. I suppose that's what you meant.
Answer: In order for the implication: If
$$
\|Tf\|\le M \|L^\alpha f\|, \quad \text{for all}\,\, f\in {\mathcal D}(L^\alpha),
$$
then
$$
\|L^{-\alpha}T\| \le M,
$$
to hold, you need that $L^{-\alpha}$ is bounded, or ${\mathcal D}(L^\alpha)\cap {\mathcal D}(L^{-\alpha})$ dense in $H$.
In the second question the correspond inequality would be
$$
\|L^{-\alpha}T\| \le M_1+M_2\|L^{-\alpha}\|.
$$
Comment: With the above hypotheses, can I say that $L$ is invertible and have bounded inverse?
Comment: No you can't. Take $L$ defined on an orthonormal basis $\{e_n\}$ of $H$ as follows $L^{a}e_n=n^{a}e_n$, if $n$ odd and $L^{a}e_n=n^{-a}e_n$, if $n$ even, and $Te_n=n^{-a}e_n$, if $n$ even and $Te_n=e_n$ if $n$ odd. Then the original assumption holds for $M=1$, and $\|L^{-a}T\|=\infty$.
Comment: http://www.google.tn/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCkQFjAA&url=http%3A%2F%2Fdeepblue.lib.umich.edu%2Fbitstream%2Fhandle%2F2027.42%2F24433%2F0000706.pdf%3Fsequence%3D1&ei=IHK4UpqMG4us7Qaf_oD4Dg&usg=AFQjCNFi7DB30styr9Ro9jDKShN58esb3w&bvm=bv.58187178,d.d2k&cad=rja
Comment: See inequalities 2 and 12
Comment: @salma I think it is better to provide direct link in the form http://deepblue.lib.umich.edu/bitstream/handle/2027.42/24433/0000706.pdf?sequence=1 than a link encoded as a part of Google link. (If DOI is available, it would be even better.) If your question comes from reading that paper, it should be mentioned in the original post.

Operator's norm


Correspondence between $C^k$-vector fields and $C^k$-Diffeomorphisms

Question: Let $(M,g)$ be a Riemannian manifold; suppose for simplicity that $M$ is of Cartan-Hadamard type.
On page 4 of these notes the author states that there is a (local) correspondence between diffeomorphisms $Diff^k(M)$ and to the space of $C^k$ vector fields on $\mathbb{R}^d$ (ie: $C^k(M,M)$) given by the identification
$$
X(p) = \exp_p^{-1}(g(p))
,
$$
where $\exp_p$ is the Riemannian exponential map on $M$.
I'm having a bit of difficulty interpreting this expression in the case where $M=\mathbb{R}^d$....
Does it mean that given any $X:\mathbb{R}^d\rightarrow\mathbb{R}^d$ with $C^k$-components, the map
$$
f^X(x)\triangleq X(x)+x,
$$
is a diffeomorphism from $\mathbb{R}^d$?  This interpretation seems wrong since $X(x)=x^2-x$ would clearly break the surjective requirement in $d=1$ case.  So what does $\exp$ mean in that case?
Intuition:
I imagine that the correspondence should somehow be given by derivatives?
Answer: I suggest you disregard this part of the notes, what's written is partly wrong or/and sloppy.
There are several places which discuss groups of diffeomorphisms as infinite-dimensional analogues of Lie groups, for instance:
Adams, Malcolm; Ratiu, Tudor; Schmid, Rudolf, The Lie group structure of diffeomorphism groups and invertible Fourier integral operators, with applications, Infinite dimensional groups with applications, Publ., Math. Sci. Res. Inst. 4, 1-69 (1985). ZBL0617.58004.
Keep in mind though, that many things you expect by analogy with the Lie groups theory do not apply. One standard mistake is to expect that every diffeomorphism close to the identity to belong to a flow generated by a vector field. This fails even for compact manifolds.
See
Palis, J., Vector fields generate few diffeomorphisms, Bull. Am. Math. Soc. 80, 503-505 (1974). ZBL0296.57008.
Comment: Ah, so the "exponential map" is from the space of vector fields to $Diff(M)$ isn't (locally) surjective then?  Interesting.
Comment: @New_Topologist_On_The_Block: Exactly! In particular, the claim made by Mann in her notes that the space of vector fields can be identified with the tangent space to $Diff(M)$ should be taken with a grain of salt.
Comment: I've been thinking is the exp map "consistent on finite-dimensional Lie subgroups": in the sense that if $H\trianglelefteq Diff(M)$ then does $exp|_H$ coincide with the exponential map on $H$ (ie does is functorially restrict to a Lie exponential map)?


Haskell: Non-exhaustive patterns in function (simple functions)

Question: I am confused as to why the 1st and 3rd versions of this functions give this error whereas the second definition works fine.
-- head and tail
third :: [a] -> a
third [a] = head (tail (tail[a]))

-- Pattern matching
third2 :: [a] -> a
third2 (_:_:x:_) = x

-- List indexing
third3 :: [a] -> a
third3 [a] = [a]!!2

Thanks in advance
Comment: ghc 7.4.1 with `-Wall` complains about all three functions.  What compiler do you use?
Answer: That is odd that the second one does not complain about non-exhaustive
patterns, since third2 will not match lists of length zero, one, or two.
The third and third3 functions complain because [a] is not a variable,
it is a pattern. [a] desugars to (a:[]), so you could have written them as
third (a:[]) = head (tail (a:[]))

third3 (a:[]) = (a:[]) !! 2

Neither of which will work, as those are single element lists.
I suspect what you want is
third a = head (tail a)

third3 a = a !! 2

Answer: You need to understand the syntax better.
Basically, there are 2 sub-syntaxes:

syntax for types
syntax for expressions and patterns

In the type syntax, [a] means list of elements of type a
In the expression/pattern syntax, [a] means the singleton list, that contains the value a. This is equivalent to (a:[])  (a prepended to the empty list).
Hence your first function, for example, checks if it gets a singleton list. Then it takes the head of the tail of the tail of a singleton list, which will fail.
The message you're getting is because there are shapes of lists you didn't cover: namely, the empty list and lists with more than 1 element.
And, of course, you should be getting a warning for third2, is it only covers lists with 3 or more elements. I am sure you're overlooking something.
Comment: The question appears to be about why doesn't the second function raise such error, not what this error means.
Comment: I do not believe it doesn't.


Populate data as individual days of the months as columns

Question: I have created a query that gives me a sum of sales for each department for the day.
What I want is to generate this data for the whole month using one master query.
This is the result I expect to see:
Department No  Department Name  1-April  2-April  3-April
1               Infants          100      112      96
2               Kids             120      132      123
Total Total                      220      144      219

Currently, I can generate this for one day only, and I have to keep changing the date value to get the data for the next day.
As stated earlier, I want to run a this for the whole month in one master query.
Comment: To improve the quality of your Question, please show us the code you have been using as well as the fields of your table(s), with sample data.  Also, please show us the code that you have developed so far.  Finally, if you can include a script to create and populate those tables, then that will enable us to readily reproduce your situation.
Comment: Add sample table data, and your current code/query.
Comment: This is the code I use to generate daily sales
SELECT Department Name,
Department No,
sum(Total Sales)*-1 as Net_Amount
FROM     Item Master
where Date = '2017-04-01'
GROUP BY Department Name, Department No
Answer: Thanks for all the answers
I managed to write a query based on the Pivot Function.
Answer: Please try the following...
SELECT CONCAT( 'SELECT department.id AS `Department No`,
                       department.departmentName AS `Department Name`',
               GROUP_CONCAT( ', SUM( date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.sales ) AS `',
                             DATE_FORMAT( salesDate, '%e-%M' ),
                             '`',
                             SEPARATOR '' ),
               ' FROM department',
               GROUP_CONCAT( ' LEFT JOIN departmentSales AS date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             ' ON department.id = date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.department_id AND date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.salesDate = `',
                             DATE_FORMAT( salesDate, '%Y-%M-%d' ),
                             '`',
                             SEPARATOR '' ),
               ' GROUP BY department.id
                ORDER BY department.id
                UNION
                SELECT `Totals`,
                       ` `,
               GROUP_CONCAT( ', SUM( date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.sales )',
                             SEPARATOR '' ),
               ' FROM department',
               GROUP_CONCAT( ' LEFT JOIN departmentSales AS date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             ' ON department.id = date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.department_id AND date_',
                             DATE_FORMAT( salesDate, '%d_%M' ),
                             '.salesDate = `',
                             DATE_FORMAT( salesDate, '%Y-%M-%d' ),
                             '`',
                             SEPARATOR '' ),
               ' ) INTO @salesQuery
FROM ( SELECT DISTINCT salesDate
       FROM departmentSales
       WHERE salesDate BETWEEN FROM_DAYS( TO_DAYS( targetDate ) -
                                          DAYOFMONTH( targetDate ) +
                                          1
                                        )
                           AND LAST_DAY( targetDate )
     ) AS salesDateFinder;

PREPARE salesTotals FROM @salesQuery;
EXECUTE salesTotals;

This attempt is based on code found at mysql select dynamic row values as column names, another column as value.  I am concerned about the group_concat_max_len variable being a problem.  If it is then I'll step up my research into the CASE method eggyal mentioned.  If it is not a problem, then I'll take things a bit easier.
Most of the lines here actually form just one SQL statement.  It takes the list of salesDate values constructed by the subquery near the end, which are then used to help construct a rather long string containing the SQL statement to be run against the database.
The string is formed from a list of substrings specified as the arguments to the function CONCAT(), which you can read about at https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat.
The string starts by specifying that the fields id and departmentName from the table department should be the first selected for each record, followed by the SUM() of each date's sales for that department.  Each date field is given a name like date_09_March and in the output a heading like 9-March.
The repeated segments of the string are achieved by using the GROUP_CONCAT function, which you can read about at https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat.
After the fields are specified the string specifies that the values should come from a temporary table formed from department LEFT JOINed with an instance of the departmentSales table for each date, with each instance being given an alias like date_09_March and joined on its department_id field to the id field of department.
Once it is formed, the temporary table's records are grouped by department.id so that the totals for each department may be calculated.  The output is then sorted by department.id.
The statement used to produce this sorted output and its column headings is then joined to another (somewhat simpler) statement used to generate the totals row.  The string containing the SQL statement formed by the concatenation of each substring is then assigned to the variable @salesQuery, prepared and executed.
If you have any questions or comments, then please feel free to post a Comment accordingly.
Further Reading
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html (for information on the DATE functions used)
Comment: Explanation added.  Also, code revised to include a `WHERE` clause that limits the dates chosen to just those for the month of the date referred to here as `targetDate`.  `targetDate` can be any date within the month.
Answer: You can control the range of dates with something like this:
select (...) where v_date >= 1-April and v_date <= 30-April

(consider v_date the name of the column and 1-April in date format)
Comment: That wouldnt get what I want Rui
Comment: That pseudocode would only get the specified fields for records that fall within the specified period.  `Sequel3` is asking for the date values to become fields themselves, with the sum of Sales for that date and that department filling the fields so created.
Comment: Alright, thanks for the explanation.
Guess I got it wrong.
Comment: Hi Toonice, I am getting errors with your code.To simplify this,can you declare what texts are variables?(like for instance I get an error on 'DATE_FORMAT' - 'DATE_FORMAT' is not a recognized built-in function name.) So I can change the values only for the text that needs to be changed(DepartmentID,Department.Departmentname is what I should change)


Do I have to reduce the GOP size for zero-latency streaming?

Question: I am piping frames into FFmpeg at quite a slow rate (1 per second) and I want to stream them out with very low latency.
There are not only sources (for example here and here) that don't mention that I need to set the GOP size (keyint) to a small value, but there are even sources (like here and here) that explicitly say that I don't have to set the GOP size to a small value.
However, so far the only way I found to reduce the really long start delay is to actually reduce the GOP size to 1.
Anyway, here's my current command line:
ffmpeg -f image2pipe
       -probesize 32
       -i -
       -c:v libx264
       -preset veryfast
       -crf 23
       -vsync 2
       -movflags "frag_keyframe+empty_moov"
       -profile baseline
       -x264-params "intra-refresh=1"
       -tune zerolatency
       -f mp4
       -

(I also tried adding :bframes=0:force-ctr:no-mbtree:sync-lookahead=0:sliced-threads:rc-lookahead=0 to -x264-params (what -tune zerolatency is supposed to do) because some of those values didn't appear in the debug output, but as expected it had no effect.)
As you can see here, we are already 182 frames (= 3 minutes wall clock) into the stream, but it still hasn't emitted anything (size was 1kB from the start).

frame=  182 fps=1.0 q=20.0 size=       1kB time=00:00:07.24 bitrate=   0.8kbits/s speed=0.0402x

This actually talks about the time-to-first-picture, but it makes it seem like it's not a big deal. ;) It is for me, so maybe I have to make the first GOP 1 frame long and then I can switch to longer GOPs? Can FFmpeg do that?
Answer: Adding -force_key_frames expr:eq(n,1) will force a KF on the 2nd frame.
Since your rate is 1 fps, I would suggest an expr of lt(n,5). Also, the default keyint is 250 and min-keyint is 40. So if you want to leave and rejoin the stream, it may take very long to restart. Consider reducing keyint.
Comment: It's HTTP and FFmpeg is started when a client connects, so there's no rejoining.


What is $\Bbb Q_p(p^{1/p^\infty})$?

Question: What is $\Bbb Q_p(p^{1/p^\infty})$ ? I am mainly looking for a reference - i.e. which topic of number theory does this fall into?
I know what $\Bbb Q_p$ is but i don't understand the notation $p^{1/p^\infty}$ means.
Context: I am trying to understand this post.
Comment: $\bigcup_n \Bbb{Q}_p(p^{1/p^n})$
Comment: It is the field obtained by adjoining all $p$-power roots of $p$, a totally wildly ramified extension of $\mathbb{Q}_p$.
Comment: (and then completing $p$-adically).
Comment: I guess its usefulness comes from that $T_K=\bigcup_{p\ \nmid\ n} K(\zeta_n,p^{1/n})$ is the largest tamely ramified extension of $K$, with $F=\mathbb{Q}_p(p^{1/p^{\infty}})$ then $T_F$ is dense in $\Bbb{C}_p$ (really ?) thus $Gal(T_F/F) = Gal( \overline{\Bbb{Q}}_p/F)$
Comment: I learn from other people that $T_F$ is not dense in $\mathbb{C}_p$, and sketch the proof as follows. Take $\alpha \in \overline{\mathbb{Q}}_p \smallsetminus T_F$ defined by the equation $\alpha^p+\alpha + \frac{1}{p}=0$. By the Krasner's lemma,
$$|\alpha-\beta| \geqslant \operatorname*{min}_{\substack{\sigma \in \operatorname{Gal}\left(T_F(\alpha)/T_F\right)\\ \sigma \neq Id}} |\alpha-\sigma(\alpha)|$$
for any $\beta \in T_F$, thus $\alpha$ can not be approximated by any sequences in $T_F$.
Comment: When the Krasner's lemma is applied, the base field is any NA local field containing $\beta$ (rather than $T_F$), to satisfy the condition of completeness.
Answer: The definition would be $\mathbb{Q}_p(p^{1/p^{\infty}}) = \bigcup \mathbb{Q}_p(p^{1/p^{n}})$, which means you adjoin all $p$-power roots of $p$. This arises in the study of (wildly) ramified extensions if you want to read about it and it is very natural to study ramification in number theory.
Comment: Is there any recommended text/notes/papers about this?
Comment: You can read about ramification theory in *Corps Locaux* of Serre, translated as *Local Fields*.

What is $\Bbb Q_p(p^{1/p^\infty})$?


Changing all body elements' color to target value

Question: how to change all body elements' color with a single click in javascript. like;
a.url{
color:#000;
}
div.sample{
color:#000;
}
table td.sample{
color:#000;
}

can i change all color properties of elements to #CCCCCC for example?
I think i have to clear my question. I don't want to change all elements color to target value, i want to change lets say; all blue colors to black. just blue colors, not all of them.
Comment: *All* elements on the page, or just those elements you've identified in your question?
Comment: all elements with same color properties.
Answer: you can use:
html:
<button id="changeColor">Change Color</button>

and javascript:
$('#changeColor').on('click', function(){
    $('*').css('color', '#CCCCCC');
}

Answer: With jQuery:
$element.click(function() {
  $('body *').css('color', '#ccc !important');
});

Answer: See this answer for how to add a stylesheet rule: How do you add CSS with Javascript?
Add the rule
* {
  color: #CCC !important;
}

or possibly:
body * {
  color: #CCC !important;
}


Using XPath Following to get element from XML

Question: I have an XML like the following

    Popular Neighborhoods

            Quartier Latin Hotels

    Popular Paris Categories

            Paris Cheap Hotels

I want to get all links under "Popular Paris Categories". I used something like this //li//a/@href/following::span[text()='Popular Singapore Categories'], but it gave no results. Any idea how to get the correct result? Here is the snippet of the python code that I wrote.
t_url = 'https://www.tripadvisor.com/Tourism-g187147-Paris_Ile_de_France-Vacations.html'
page = requests.get(t_url, timeout=30)
tree = html.fromstring(page.content)

links = tree.xpath('//li[span="Popular Paris Categories"]//a/@href')
print links

Comment: Yes, `span` and `ul` are at the same level, and it doesn't matter. See the demo (or try it in any XPath tester you like) : http://xpatheval.apphb.com/3849byFx2
Comment: `//li[span='Popular Paris Categories']/ul/li/a/@href`
Comment: it did not work because "span" and "ul" are at the same level of the xpath.
Comment: I am using python to evaluate the xpath. I have included the python code that I wrote.
Comment: Make sure you post HTML that you actually get from `page.content`, not the one you see in browser...
Comment: The full page.content is too long. But the section that I post here is there.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126399/discussion-between-agus-sanjaya-and-har07).
Answer: This is one possible way :
//li[normalize-space(span)="Popular Paris Categories"]//a/@href

Notice how normalize-space() is used to remove trailing space from the span content. This is the reason why the XPath I suggested initially in the comment didn't work for your actual HTML.
Comment: Yes you are correct. There is a new line after "Popular Paris Categories". Thank you very much for your help.
Answer: Something like this perhaps
//span[text()='Popular Paris Categories']/following-sibling::ul//a/@href

Comment: @AgusSanjaya it should work (see demo at http://xpatheval.apphb.com/8524GG-JA). What environent are you running this in ? (*what xpath engine etc*)


The rule that Chord I, IV, and V are majors - does that extend to 7th chords?

Question: So for example, in the key of G# major.
D# is the V chord
In major key the V chord should be a major, so does that mean if I am doing a seventh chord, it should be D#maj ? This would be: D#, G, A#, D.
But 'D' is not a note in the key of G# major.
So does the whole concept of Chord I, IV, V being major chords in a major key only extend to triad chords? does the seventh note not ascribe to the rules of being a major or minor (according to 1 4 5/ 7 /2 3 6), and rather the seventh note is whichever note fits into the key (so in this case it would be D#, G, A#, C#, a D#7 chord)?
Comment: Whereby the triad of D# is: D#, F##, A#
Answer: Interesting question. Firstly, let's consider only using the notes that are diatonic - those actually from the major scale and key. Don't know why you chose G♯ - it's a more complicated scale than its enharmonic of A♭, and with loads of sharps, will complicate the issue.
So, I'll keep it simple in key C. Notes are CDEFGAB. Making 'seventh' chords involves starting with a basic triad, and adding the next note one third above the highest. So, C maj. =CEG. Adding a B note makes it CEGB. C major seventh. Playing the IV uses FACE - another M7 - F major seventh. The V chord, GBD has F added, making G dominant seventh. Those three are the mainstay used in a lot of pieces - they keep happily within the key (which is NOT a rule!!) The next most used will be C7, comprising CEGB♭, which sort of belongs to another key - F. And often it's used in key C in order to get to the chord F.
I wish you hadn't used G♯ as the key. True, there's no D note, only because we don't use two different notes with the same letter name in scales.  This question could have been answered using that key, but I can't be responsible for the suicide rate of any subsequent readers! So please, forget that key!!
The base problem is that there are many different types of seventh chords. There's major seventh, with major triad and a M7 note on top. There's dominant seventh, with a major triad and m7 on top. There's minor seventh, with a minor triad and m7 on top. There's diminished seventh, with a minor third, diminished fifth and a dim 7 note on top. There's also more, but it's already gone past what you asked about.
Comment: Hi, thank you so much for this detailed explanation! To be honest I'm only just starting to learn music theory, I chose G# at random! I didn't realise it was such a complex issue but I should have guessed considering its music theory...
Comment: You could do a *lot* worse than reading some of the questions (and answers) on this site. And when there's something you don't understand, pose another question. Just avoid key G#!
Comment: Music theory isn't as complicated as it's made out to be. For this sort of question, you might do well to start by memorizing the Circle of Fifths: it's literally a circle with 12 positions (like a clock) that represent the 12 (15) most common keys (it is technically 15, but 3 of them are aurally equivalent to each other: Db/C#, Gb/F#, Cb/B). C is at the top, and moving to the right a position moves you up a perfect fifth (G), moving left a position moves you down a perfect fifth (F), and so on. Most music theory gets easy when thought about relative to the Circle of Fifths.
Answer: I7= major 3rd, perfect 5th, major 7th
IV7= major 3rd, perfect 5th, major 7th
V7= major 3rd, perfect 5th, minor 7th
this is not a rule, this is the law derived of the diatonic scale and this doesn't change whether we are in C or in Eb, or in C# or in D#
P.S.:
As the tetrad of D  (Dmaj7) is D, F#, A, C# - if D = I or IV - so the tetrad of D# (D#maj7)  is D#, Fx  A#, Cx.  (x = ## -> double sharp!)
Or when D7 = V7 (D, F#, A, C) -> D#7 = D#, Fx, A#, C#)
As Tim says it is not quite obvious why you choose D# major and not Gx major! (so the dominant V7 of CX  would be Gx, Bx, Dx, Fx (theoretically  you can add as many sharps as you want without confusing beginners - just ignore the sharps when reading!)
Btw: The last section was just joking ;)
Comment: When I see '7' after a letter or Roman numeral, I think 'dominant seventh'. So writing I7 along with V7 could be confusing, since one is shown as major seventh, the other as dominant seventh.
Comment: How would you then write the C maj7 in RN? and what is IV7 if not F maj7
Comment: I use that little triangle for maj 7. With a letter or a Roman numeral.
Comment: Yes, now I remember: in a blues I use to read I7 and IV7 as minor seventh.
Answer: You appear to be cataloguing the chords that can be made from the notes of a scale - the diatonic chords  in a certain key.
It's not a 'rule', just a list of what chords can be built from the notes C. D, E, F, G, A, B (if we're in C major) or G♯, A♯, B♯, C♯, D♯, E♯, Fx  (if you insist on taking G♯ major as an example!)
Yes, if you restrict your choice to diatonic notes, the 7th chord built on I will be a major triad with a major 7th.  The one built on II will be a minor triad with a minor 7th.  etc.
We could list some 9th, 11th and 13th chords as well.  The 13th chord on IV in C major would be F, A, C, E, G, B, D.  (But remember, we DON'T call that F13.)
But so what?  It's just a list of the permutations  and combinations of the notes in a scale.  Definitely not a list of PERMITTED chords when a song's in a certain key.
Answer: When you ask about key and used symbols like I, IV, V, I assume you are asking about functional, common practice harmony (basically the style of Handel and Mozart.) Sometimes the harmonic system is called the major/minor system.
In major and minor keys the dominant chord is a major triad or a dominant seventh chord.
Other seventh chords are used. Probably the other two to get acquainted with are the ii6/5 minor seventh in major (iiø6/5 half diminished in minor) and the full diminished seventh chord built on the leading tone viio7 in major or minor. Seventh chords are usually in the second half or advanced section of harmony textbooks. I suggest learning those common seventh chords first - by identifying them in real scores - before taking the deep textbook dive.
About your example: G# major.
In G# major the dominant seventh chord would be: D# Fx A# C#. The x is a double sharp. Those accidental spellings are awkward, because the more typical thing is to call that key Ab major with a dominant of Eb G Bb Db.
Enharmonic equivalence digression: G# and Ab major are called enharmonically equivalent meaning the pitches are the same but the letters and sharps and flats differ. consider just the starting tones. G# and Ab are the same key on the piano (key meaning the keyboard key.) G# and Ab are enharmonically equal, but one or the other will be used depending on the harmonic context. In the case of key signatures, you usually go with the one that uses the fewest sharps and flats. G# major uses 6 sharps and one F double sharp. Ab major uses only four flats so Ab is the one used. You can call G# major a theoretical key signature meaning you can writing it, but it's very impractical!
If you are just getting started with studying theory and harmony, learn your key signatures. It will take some time, but in the end things will be a lot easier to understand when you know the keys and how to "spell" chords correctly.
Answer: Whether a chord is major or minor depends on its 3rd - so your plain V triad is major because it contains that major 3rd, right? You can stack another note on top to get a 7th chord, but it won't change that major tonality.
What might be confusing is that maj7 is referring to the fact you have a major 7th in there, not whether the chord itself is major (in fact you can have a minmaj7 chord!). So the V being a major chord doesn't require a major 7th, and as you've noticed, it usually has a minor 7th instead!
When you're building chords like this you're basically stacking thirds, and in practice that means you're starting on a scale degree, skipping a note and taking the next one. So all the notes in your chord are within the key, and for the V you get a major chord, and when you add another third to get a 7th chord, you end up with that minor 7th.
That's also what gives it its function, the major 3rd and minor 7th in there are a tritone apart, so there's dissonance that wants to pull back to the I chord and resolve (they both shift away from each other, so the 3rd and 7th of the V become the root and 3rd of the I respectively)
Comment: The last paragraph sounds a little confusing!
Comment: This is how I would have answered the question, but the last paragraph may be more advanced than a newbie might be able to understand without further study, however I'm all for promoting further study.
Comment: @skinnypeacock yeah that's why I added it at the end, kind of as a little taster for the more advanced stuff, but also because it's the reason you *don't* want a maj7 chord there - it needs that major 3rd and minor 7th to really do its thing. I hope it didn't make it too confusing because I was going for the simple answer!


WSUS difference between Windows 10 and Windows 10 GDR-DU Products

Question: In the Choose Products screen of WSUS configuration, there is an option for both Windows 10 GDR-DU and Windows 10:

What is the difference between the two? I can't find any Microsoft documentation that explains the difference between the products.
Answer: GDR-DU mean General Distribution Release (Dynamic Update)
Sadly from TechNet no resource seem wrote for that. From the information I have it's file kept for upgrading from a build to another, to prevent a fresh system re-install (like build 1511 to 1607). (not for normal updating).
A description for GDR-DU from a Microsoft source there, official (but on an archived mailing list). (https://marc.info/?l=patchmanagement&m=147085158401556&w=2)

GDRDU just means that when you install Windows 10
    1607, it will automatically download and inject the
    update as part of the upgrade process, as long as
    dynamic update is enabled (which is the default).
    It's a mechanism to get fixes in place without
    refreshing the entire OS image.

See there for a quick info, not official, but still point to the same answer than the Microsoft's source: http://www.urtech.ca/2016/12/solved-what-do-the-windows-10-product-names-mean-in-wsus/

Windows 10 GDR-DU: GDR = General Distribution Release, DU=Dynamic
  Update. These updates are only used by the current GDR build of
  Windows 10 when it is trying to perform a Dynamic Update (see item 5
  above).
Item 5: Windows 10 Dynamic Update: This includes only updates to the
  setup process that occurs when one build of Windows 10 is trying to
  update to a new build of Windows 10 (i.e. 1511 to 1607).

A more generic description for GDR-DU.

By default, all components on Windows systems start on the GDR branch
  following each major release. When you install updates from Windows
  Update for a GDR component, it gets upgraded with the GDR version.
When you install a specific Hotfix, the files and components in the
  Hotfix package are migrated to the LDR branch. At this point, that
  particular component is marked as a LDR component. If you install a
  newer Update over this component, the Windows servicing technology
  will automatically install the appropriate latest version from the LDR
  branch for you. This is possible because each Update package ships
  with both the GDR and LDR versions of the component.
Once a component is marked as a LDR component, the only way to move
  back to the GDR branch is to uninstall all Hotfixes for that
  component, or move to the next available service pack.

Quoted text from https://blogs.msdn.microsoft.com/ntdebugging/2008/10/21/windows-hotfixes-and-updates-how-do-they-work/
The question after is, why you can select GDR-DU alone without the Dynamic Update too.


What is the smallest prime of the form $2n^n+91$?

Question: I wondered what the smallest prime of the form $2n^n+k$ is for some odd $k$. For
$k<91$, there are small primes, but for $k=91$ , the smallest prime (if it exists)
must be very large.

What is the smallest prime of the form $2n^n+91$ ?

It is clear that $\gcd(91,n)=1$ must hold. $2n^n+91$ is composite for every
natural number $n$ below $1000$.
$$2\times 15^{15}+91 = 42846499\times 20440124659$$
shows that the smallest prime factor can be large.
Comment: No primes up to $n=1200$. Watch this space...
Comment: Did you also check the range $0\le n \le 1000$ ?
Comment: Yes.${}{}{}{}{}{}$
Comment: No primes up to $n=1500$...
Comment: I experience a [deja-vu](http://math.stackexchange.com/questions/597234)... There must be a glitch in the Matrix !
Comment: As most commoners would say, "Since there are no primes to $n=1500$, then $2n^n+91$ must therefore always generate composites for all integers $n \geq 1$"
Comment: There are two cases: $n=3k$, and $n=6k-1$. Otherwise, $2n^n+91$ cannot be prime, since all primes greater than $3$ are of the form $6m\pm1$.
Answer: $$2 \times 1949^{1949} + 91$$
is probably prime! (Running a rigorous primality test on it would take almost a whole day $-$ see here, for instance $-$ so I'm not going to do that.) $2n^n+91$ is composite for all lower values of $n$.
Comment: How did you conclude that it is 'probably prime'? But it does look suspiciously prime...
Comment: @Trogdor there are plenty of test that show a number is composite, if they fail it is "probably prime." See http://en.wikipedia.org/wiki/Probable_prime
Comment: I like "suspiciously prime". All we have to do is decide on a meaning for it.
Comment: You're the one who made me ***recant*** my skeptical statements about proving a large number prime. Same person asking, too. They deleted my revised answer, which is a shame.  http://math.stackexchange.com/questions/402357/is-184720132-really-a-prime
Comment: @WillJagy: Philistines.


Como enviar dados de um filtro em php com vários campos de busca

Question: Estou criando uma página de filtro, mas essa página irá ter muitos campos para o usuário poder preencher, selecionar e isso irá fazer uma busca no banco mysql e irá retornar os dados para o usuário em uma outra página.
Uma das dúvidas que tenho, que por ser muitos campos, com campos do tipo select, input's[text, option, checkbox], é se mando os dados por get ou é nesse caso passo por post?
Answer: O melhor é usar POST pra esse tipo de ação, principalmente se você tiver algum campo do tipo textarea, onde o conteúdo possa ser muito grande e pode extrapolar o limite da url (apesar de não ter um limite estabelecido, geralmente os servidores limitam, e o aconselhável é usar URL's menores do que 2000 caracteres. Fonte)  caso o método for GET.
Porém quando não há a necessidade de um textarea (o que não vejo muito utilidade em um filtro) e tenha uma boa validação contra SQL Injection pode se usar GET sem problemas.
Uma boa melhoria para filtros de muitos campos é criar um histórico de consultas e consultas favoritas.
Comment: Então, não é como criar o filtro e sim qual melhor metodo utilizar, pergunto isso pq, eu sei que se eu enviar por get irá ficar na url do usuário e com isso ele pode copiar e colar e consultar futuramente (isso pode ser bom) mas ao mesmo tempo, como vc mesmo disse, se eu tiver um campo do tipo textarea, por exemplo, poderá estourar o limite da url.
Comment: E aproveitando, editei a pergunta, acho que agora fica um pouco mais claro.
Comment: Isso, mas tipo, você pode limitar o tamanho do textarea, apesar de que não vejo muito utilidade em textarea para um filtro, então neste caso pode-se utilizar o método GET sem problemas algum, lembrando apenas de fazer uma boa validação para evitar _SQL Injection_ e _voilá_.
Comment: Ah sim, não que eu tenha textarea no meu filtro, mas sim alguns campos do tipo input[type=text], select>option, input[type=radio], input[type=checkbox] mas são vários de todos esses.
Comment: Acabei de ver em uma outra pergunta, sobre o [limite da URI](http://stackoverflow.com/a/3091523/3497987). Até atualizei ali a resposta.
Answer: Resumindo acho post mais seguro.
O método GET
GET, um dos métodos do HTTP, é acionado por meio de um formulário HTML através da diretiva method=get incluída na tag . Por meio desse método, os dados constantes no formulário são primeiramente transmitidos ao software servidor e este, por sua vez, armazena os dados temporariamente numa variável de contexto denominada QUERY_STRING.
Um script CGI, chamado através da diretiva action= incluída na tag inicial do formulário, precisa extrair os dados dessa variável de contexto para poder obter os dados que lhe foram enviados (veja também variáveis de contexto). Usando Perl, por exemplo, é possível extrair esses dados com $dados_form = $ENV{'QUERY_STRING'};.
Quando um formulário HTML utiliza o método GET, o fluxo de dados é separado do endereço URL que chama a CGI através de um ponto de interrogação (?). Esta forma de endereçamento e separação pode ser observada no campo de endereços do navegador do usuário, logo após o formulário ter sido enviado. Você verá algo como:
http://www.meusite.com/meuscript.cgi?nome=Maria&id=123O método POST
POST, também um método do HTTP, é acionado por meio de um formulário HTML através da diretiva method=post incluída na tag .
Este método faz com que os dados do formulário sejam diretamente transmitidos ao endereço que constar da diretiva action=. Um script CGI, chamado por action=, precisa extrair os dados através da entrada padrão (standart input) para poder obter os dados transmitidos pelo formulário. Pode-se, por exemplo, usar Perl e indicar read(STDIN, $Dados, $ENV{'CONTENT_LENGTH'});.
Observe que o programa precisa obter o valor da variável de contexto CONTENT_LENGTH para saber quantos caracteres precisam ser lidos através da entrada padrão. Isto é necessário porque não existe um caracter separador no fluxo de dados.
A importância de se conhecer o método
Se você quiser fazer uso de um script CGI pronto, precisa saber por qual dos dois métodos o script espera receber dados. Normalmente isto vem documentado pelo autor do script. Alguns scripts mais inteligentes testam ambos os métodos - neste caso, não importa o método de transferência de dados que você usar no formulário - ambos vão funcionar.
Se você for escrever seus próprios scripts, lembre-se de determinar o método que deve ser utilizado no formulário. Ou programe de maneira inteligente: deixe o script preparado para ambos os métodos.
Fluxo de dados na transmissão de dados de formulários
Um formulário HTML típico é composto por campos nominados (por exemplo para nome, endereço e comentário). Na transmissão do formulário preenchido para o servidor web / programa CGI, os dados precisam ser transmitidos de tal forma que o script CGI seja capaz de identificar os campos do formulário e os valores dos mesmos. É por isso que existe um método de codificação específico que separa os campos do formulário dos seus respectivos valores. Este método de codificação baseia-se nas seguintes regras:
. Cada um dos elementos do formulário, inclusive seus valores, são separados entre si pelo símbolo & ("e" comercial ou ampersand);
. O nome e o valor (dados) de um elemento do formulário são separados por = (sinal de igual);
. Espaços em branco existentes nos dados (p.ex. várias palavras) são substituídos por + (sinal de adição);
. Todos os caracteres ASCII estendidos, com valores de 128 a 255 (hexadecimal 80 até FF), são substituídos por um conjunto constituído pelo sinal de % (porcento) seguido do valor hexadecimal do caracter (p.ex. o nosso ç (c cedilha) é substituído por %E7);
. Todos os caracteres utilizados nestas regras como delimitadores (ou seja, &, +, = e %) também são convertidos em hexadecimal seguindo a mesma regra para os caracteres ASCII estendidos.
Comment: Acho que para uma resposta melhor precisamos de pergunas melhores
Comment: Agora entendendo um pouco melhor Os browsers permitem até 2kb, ou entre 2000 e 2400 bytes.
O limite depende de cada browser
Comment: Obrigado pela resposta, mas ainda assim não me tirou realmente a minha dúvida que tenho e pelo que comentou "Resumindo acho post mais seguro." ainda não acho que seja a resposta mais correta para o que preciso. Valew
Comment: Acho que me entendeu errado, mas ok. O que quis dizer é que para o que perguntei eu gostaria de saber outras coisas, como questão de quantidade de caracteres que se podem ser passados pelo get e pelo post, segurança, mas algo mais concreto em relação a segurança, mas ainda assim obrigado


Is there any way to create the shortest path going through multiple (more than 2) different points using OSMNX?

Question: I was wondering if there was a way to get the shortest path between an origin and a target, but with the path going through different points defined along the way (we could consider them stops, for example, going from A to B but going through C).
For a first approximation I have been using the shortest_path of networkx. I have created as many routes as points I have, using each target as the origin of the next route. But I want to know if there was an easier and more elegant way to do it.
Comment: You need some knowledge about `travelling salesman` first.
Answer: You can just chain the trips together:
import osmnx as ox
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')

point1 = list(G.nodes)[0]
point2 = list(G.nodes)[100]
point3 = list(G.nodes)[200]

path1 = ox.shortest_path(G, point1, point2)
path2 = ox.shortest_path(G, point2, point3)
path = path1 + path2[1:]

Or, to generalize the problem, if you want to solve a path between multiple nodes (visiting an arbitrary number of nodes along the way):
import numpy as np
import osmnx as ox

# use a strongly connected graph so all paths are solvable
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')
G = ox.utils_graph.get_largest_component(G, strongly=True)

# get some random nodes to visit
rands = np.linspace(0, len(G.nodes), num=100, endpoint=False)
nodes = [list(G.nodes)[int(rand)] for rand in rands]

# solve path from 1st node to 2nd node to... nth node
path = list()
for orig, dest in zip(nodes[:-1], nodes[1:]):
    path = path[:-1] + ox.shortest_path(G, orig, dest, weight='length')
fig, ax = ox.plot_graph_route(G, path, node_size=0, route_alpha=0.5)


Question about eliminating seasonality

Question: I am trying to remove seasonality from data. I tried the non-linear trend using the code: trend=lm(NH3cH6~t+cos.t+sin.t). The plot was shown as following:

However, as you can see, the second peak of the trend does not quite fit the data. I want to shift the second peak of the trend a little bit, but I don't know how to modify the code to achieve this. Can anyone help me to improve the fitting of the trend?
Comment: You've fitted a model with period $2\pi$. What's the period of your data? And what's the frequency of the observations?
Comment: Perhaps too obvious, but other small problems too. Fitted function if linear plus sinusoid should be smoother than you have shown and be defined for the whole data range.
Comment: They are two-year daily data. Each peak indicates one year. Thanks! @RobHyndman
Comment: Chemical comment: the "C" in NH$_3$CH$_6$ presumably means carbon and should be upper case.
Answer: Your model fits a linear time trend plus a first order Fourier series approximation for the seasonality. Since you don't define cos.t or sin.t, it is not possible to tell what seasonal period you have used. You can fit a model with correct seasonal period using
t <- 1:length(NH3cH6)
cos.t <- cos(2*pi*t/365)
sin.t <- sin(2*pi*t/365)
trend <- lm(NH3cH6 ~ t + cos.t + sin.t)

However, you may need a higher order Fourier series approximation, and there are facilities in the forecast package in R for doing that.
First, make sure the data is a time series object of the correct frequency:
NH3cH6 <- ts(NH3cH6, frequency=365)

Generate the Fourier terms for the regression (using 3 terms here, but choose the best number by minimizing the AIC of the fitted regression model).
library(forecast)
X <- fourier(NH3cH6,3)

Fit the regression model
fit  <- tslm(NH3cH6 ~ X + trend)

The tslm command will understand what trend means, and will make sure the residuals and fitted values are ts objects with time series characteristics.
To see the result:
plot(NH3cH6)
lines(fitted(fit), col="red")

Answer: I'm not at all sure that a trigonometric wave will be a good fit for these data.  Look at how the peaks seem so narrow and pointy and the troughs seem so wide and flat.  It's also not clear to me why you would include the sum of the sin and the cos functions.  Do you have some theoretical reason behind the formula that you started with?
If you wish to try fitting a simple trig function, you might want to explore nonlinear regression instead.  For example,
# a is the vertical shift (height of horizontal center line)
# b is the amplitude (half the vertical distance from trough to peak)
# c is the phase shift (distance from first trough to x=0)
# d is the period (distance from peak to peak)
trend <- nls(NH3cH6 ~ a + b * sin(2*pi/d*(c+t)), start=list(a=60, b=60, c=-80, d=400))

Alternatively, you could fit a smooth line to the data, e.g., using the R functions loess.smooth() or gam() from the mgcv package.
Comment: A trigonometric model can fit periodic series that have narrow peaks and wide troughs ... if you use more than one harmonic. You use sums of sin and cos functions because the amplitude and phase are unknown; the coefficients on sin and cos are related to the amplitude and phase. The benefit of working with sin and cos is that you end up with linear rather than nonlinear models. Both these issues are discussed [here](http://stats.stackexchange.com/questions/60500/how-to-find-a-good-fit-for-semi-sinusoidal-model-in-r/60504#60504)
Comment: In addition, using a root or log link and a generalized linear model might be a reasonable way to cope with the mild asymmetry you identify, which seems more a consequence of skewness of distribution than anything else.
Comment: Thanks @Glen_b for that link.  Very interesting.  And a useful approach, as long as the period is known.
Comment: @JeanV.Adams As mentioned at the end of that answer, there's discussion of unknown period [here](http://stats.stackexchange.com/questions/60994/fit-a-sinusoidal-term-to-data)
Answer: Fitting trigonometric models seems nice because you can describe relatively complicated trends with relatively few parameters. However, the lessons learned are always the same: don't do it! Even as a pure mathematics problem, there are plenty of convergence issues involved, identifying correct periodicity, amplitude, etc. Add the randomness of a statistical experiment to the equation and you have a mess on your hands.
Smoothers are great at accounting for unknown functions of time, trigonometric or otherwise. The basic boxcar smoother is intuitive and easy to apply in this case, but you can also consider smoothing splines or a LOESS smooth. With a sufficient amount of data, it's possible to fit effects at an annual, quarterly, or monthly level which are consistently estimated over a long period of time.
I am vaguely aware that in advanced atmospheric sciences, the Kalman Filter is somehow applied to estimate more granular seasonal trends. Caveat emptor! But here is an applied paper which looks at just this problem. My basic understanding indicates that the Kalman filter is well suited to this kind of problem since it jointly estimates state change and steady state effects in a model. Please no engineers critique my explanation. The benefit of the filter over smoothers is that they are used to predict values out in the future (or "forecasting" as it's called in such fields). As a result, the Kalman estimated trends are believably more "consistent" whereas smoothers are not really meant to infer many differences for specific values (though you can do it that way, it's not a conventional approach and does have shortcomings, aka "Curse of Dimensionality").

Question about eliminating seasonality


PF temporary reroute to different IP

Question: I have a FreeBSD host that serves as an entry point to additional systems on an internal network. As such I have pf configured to redirect incoming traffic on certain ports (say, port 5000) to the host local address on one of the jails running a network service on that machine. This looks like this:
---port 5000--->[Main host]
                     |
                     |---port 5000--->[Machine A]
                     |~~~~~~~~~~~~~~~~[Machine B]

The redirection is performed by the PF rule:
rdr pass on egress proto tcp from any to $IP port 5000 -> $MACHINE_A_IP

This is the state I almost always want, and that is what is configured by default. However, I'd like to sometimes temporarily redirect port 5000 to the Machine B, like this:
---port 5000--->[Main host]
                     |
                     |~~~~~~~~~~~~~~~~[Machine A]
                     |---port 5000--->[Machine B]

I've tried setting up PF anchors to facilitate this, but as I'm new to PF I find it hard to parse documentation to cover this use case.
How do I issue dynamic PF rules on the main host to temporarily redirect 5000 from Machine A to Machine B?
Comment: How are you expecting to trigger the switchover? If its manual maintenance,  just keep 2 variables & comment-out one, and reload the config. Otherwise you may want to look at  [relayd(8)](http://bsd.plumbing/) [(man)](https://www.freebsd.org/cgi/man.cgi?query=relayd&sektion=8)as an automatic failover if A is down
Comment: I'd expect to do so from either a shell on the machine or a cronjob. It's not an automatic failover situation, they are in fact different services.
Answer: The proper way to achieve this is to use table as a target for redirection. You can change content of table without reloading pf using pfctl. Just be aware that existing firewall states will keep forwarding traffic to the old host until tcp streams are closed or udp "streams" timeout.
Comment: I have since found another way to accomplish this problem, and cannot properly check this any more unfortunately. I'll accept this answer as the correct one if someone else can confirm this is the proper way of doing it! Thank you for the answer.

PF temporary reroute to different IP


Bootstrap Progress Bar | Aria-Now Value set but still blank

Question: So I've made successfully made the bootstrap progress bar, but even when setting the aria-now value the progress bar just stays empty. What am I missing? Built using jade template engine.
div(class='progress bar' role='progressbar' aria-valuenow='45')

Answer: aria- tags are just used by screen-readers for people who are unable to read the content of your site.  They don't impact the DOM at all.  The reason it is empty is because you need to wrap your DIV in a .progress element, and then give .progress-bar it a width property - the width:60% is what gives the progress bar its % (sorry I don't know jade)

If you want to add screen reader data back in you can as per http://getbootstrap.com/components/#progress
Comment: That did it, Thanks. Jade code below as a btw.

div(class='progress')
    div(class='progress-bar progress-bar-danger active' role='progressbar' style='width:60%') $60,000 / $100,000


Longest Common Substring (more than 2 arguments)

Question: I have seen the solution for LCS 2 strings. Below is the code.
I am curious how can I change it so that it can solve properly when more than 2 strings are given.
I would appreciate any help or resource that can be useful
Thank you.
const printLCS = (a, b) => {
    let m = a.length;
    let n = b.length;
    let lcs = new Array(m + 1);
    let lcsLen = 0;
    let row = 0, col = 0;

    for (let i = 0; i <= m; i++) {
        lcs[i] = Array(n + 1);
        for (let j = 0; j <= n; j++) {
            lcs[i][j] = 0;
            if (i == 0 || j == 0) {
                lcs[i][j] = 0;
            } else if (a[i - 1] == b[j - 1]) {
                lcs[i][j] = lcs[i - 1][j - 1] + 1;
                if (lcsLen < lcs[i][j]) {
                    lcsLen = lcs[i][j];
                    row = i;
                    col = j;
                }
            } else {
                lcs[i][j] = 0;
            }
        }
    }

    if (lcsLen == 0) {
        console.log("No Common Substring");
        return;
    }

    let resStr = "";

    while (lcs[row][col] != 0) {
        resStr = a[row - 1] + resStr;
        --lcsLen;
        row--;
        col--;
    }
    console.log(resStr);
}

const myArgs = process.argv.slice(2);
printLCS(myArgs[0], myArgs[1]);

const onErr = (err) => {
    console.log(err);
    return 1;
}

Answer: Although, it might be a bit too late to answer now, I think, I might have found the issue you have.
It is with the function call.
printLCS(myArgs[0],myArgs[1]);

You are specifying the third and fourth argument, while perhaps a better way would be to spread it all like this.
printLCS(...myArgs);


Is there a way to track changes made in each work item? Like the data that's available on the History section

Question: I would like to write a Python function that returns all the changes made to one or more fields of any Azure DevOps work item. My end goal is to have the function return this data in JSON format, so that then I can parse it to a CSV file for reporting purposes.
I've spent all day today learning how to work with the Azure DevOps REST API and finally got to the point where my requests are working (200 OK). I'm a beginner with APIs if you haven't noticed by now.
I managed to write a function that returns a list of a work item's current values based on a WIQL query I give it. I'm just not familiar with which API entity set I should use to look into work item changes, specifically to the changes a field receives, for example changing a Title, or WorkItemType. Hopefully I can get this question answered here!
Answer: The REST API does have endpoints for querying work-item revisions.

Work-Item Revisions: If you know the work-items you're after, you can get the revision history for each individual work-item. This is equivalent to the History tab on the work-item.

Reporting Revisions: If you want to collect all changes in a project from a particular time forward, you can use this endpoint to retrieve and paginate through all changes.

This endpoint has a fields attribute that can be used to specify which fields to return, which may prove to be useful if you're only after a specific-field.
If you don't specify the startDateTime attribute, you'll start at the beginning.
The result includes a isLastBatch which indicates if it's the last paginated batch of data. It also includes a handy nextLink which is the URL to the next set of data.

In PowerShell, it would something along these lines:
# define your secrets and salt to taste
$AccessToken = "<YOUR-PAT>"
$OrganizationName = "<YOUR-ORG>"
$ProjectName = "<YOUR-PROJECT>"

$header = @{
  Authorization = "Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AccessToken)"))
}

# Define your Project URL
$uri  = "https://dev.azure.com/$OrganizationName/$ProjectName"

# Tack on the REST API Endpoint
$uri += "/_apis/wit/reporting/workitemrevisions?api-version=7.1-preview.2"

# append the fields you're interested in
$uri += "&fields=System.Title,System.Description"

# add the date to start processing from
$uri += "&startDateTime=2023/01/31"

# make the URL friendly, in case you have spaces in your project name...
$uri = [Uri]::EscapeUriString($uri)

# create an array to hold your changes
$changes = @()

# set a flag to know if we're done fetching the results...
$done = $false

# fetch and loop until we're done!
while(-not $done) {
   $result = Invoke-RestMethod -Uri $uri -Headers $header -Method GET
   if ($result) {
      $changes += $result.values
   }
   $done = $result.IsLastBatch
   $uri = $result.nextLink
}

# Invoke-RestMethod will convert the JSON data into an object, so if you
# want to drop it back into JSON we can do that here...
$changes | ConvertTo-Json -Depth 10

Alternatively, there is also a Webhook for "WorkItem Updated" that could also be used to get real-time updates to work-items in your projects.


Autenticação Laravel 5 não exibe erros

Question: Boa tarde, estou utilizando o Laravel 5 para refazer um sistema e na tela de login quando não é feita a autenticação o usuário é redirecionado para o formulário novamente mas não consigo retornar nenhum erro.
Model User
protected $connection = 'pgsql2';
protected $primaryKey = 'cod_funcionario';
public $timestamps = false;
protected $table = 'funcionarios';
protected $fillable = ['login', 'senha'];
protected $hidden = ['senha', 'remember_token'];

public function getAuthPassword()
{
    return $this->senha;
}

public function setSenhaAttribute($value)
{
    $this->attributes['senha'] = bcrypt($value);
}

AuthController.php
protected $redirectPath = '/admin';
protected $loginPath = '/admin/auth/login';

public function __construct()
{
    $this->middleware('guest', ['except' => 'getLogout']);
}

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
    ]);
}

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => $data['password'],
        //'password' => bcrypt($data['password']),
    ]);
}

public function postAdminLogin()
{
    if (Auth::attempt(['login' => Request::input('login'), 'password' => Request::input('senha')]))
    {

        return redirect()->intended('admin');
    }
    else{
        return Redirect::to('admin/auth/login');

}

e na view estou tentando exibir os erros da seguinte forma:
@if (count($errors) > 0)

            @foreach ($errors->all() as $error)

{!! $error !!}

            @endforeach

@endif

Comment: Amigo, poste o código que já tem, irá ajudar e MUITO á te ajudarem rs.
Comment: Postei, se precisar de mais algum.
Comment: Veja a resposta que postei.
Answer: Para isso geralmente eu uso Session.
Por exemplo, deu erro de login, faça isso no seu else.
else{
     Session::flash('alert', 'Deu pau no login, tente de novo');
      return Redirect::to('admin/auth/login');
}

Daí na página de login eu coloco, se for blade, se não for usa o normal do PHP mesmo.
@if(Session::has('alert'))
    {!! Session::get('alert') !!}
@endif

Este Session::flash funciona apenas de uma página para a outra. Top, né ?
Não.
Comment: Obrigado, desta forma funcionou.
Comment: Marque como a resposta certa se te ajudou mesmo.

Autenticação Laravel 5 não exibe erros


basis of a second countable, topology

Question: Prove that every basis of a second countable space contains a countable
subfamily which is also a basis.
*I try with the intersection of the bases, the open ones of the finite with those of the other, but I can not. Some clue
Comment: In chapter 1 of General Topology by R.Engelking there is a proof of the generalization of this : If $B$ is a base for the space $X,$ there exists a base$ B'\subset B$ with $|B'|\leq w(X),$.... where $w(X)$ (the weight of $X$) is the least infinite cardinal $k$ such that $X$ has a base $ C$ with $|C|leq k.$.... If $X$ does not have a finite base we can say that $w(X)$  is the least cardinal of a base for $X$, and that if $B$ is a a base for $X$ then there exists a base $B'|subset X$  with $|B'|=w(X).$
Answer: Let $\mathcal D=\{D_1,D_2,\dots,D_n,\dots\}$ be a countable base. Let $\mathcal B$ be any base. For each pair $(m,n)\in\mathbb N\times\mathbb N,$ chose a set $B_{m,n}\in\mathbb B$ such that $D_m\subseteq B_{m,n}\subseteq D_n$ if such a set exists. (You need the axiom of choice here.) The collection of sets $B_{m,n}$ so chosen is a countable base for the topology.

basis of a second countable, topology


Vb6 TabStrip - Como visualizar os controles das TABs fora do escopo

Question: Saudações a todos.
Minha área é C, mas preciso dar manutenção em um produto implementado em visual Basic 6 . Este produto é um configurador de um software em c, a função dele é apenas gerar um arquivo .ini para configuração do executável principal.
Preciso inserir alguns controles dentro das Tabs, mas quando abro o projeto somente a primeira TAB (de cima) fica visível durante a edição do projeto.
Gostaria de saber como fazer as TABS debaixo aparecerem para edição ou como tornar visível os controles das TABS debaixo para edição. A impressão que eu tive é que elas ficam como se fosse em camadas, e dependendo da TAB selecionada em tempo de execução esse controles das TABS são ocultados ou destacados, mas de fato não se é isso mesmo.
Se alguém tiver alguma idéia ou algum link de algum material sobre o assunto porque o pouco material que eu achei não sanou as minhas dúvidas.
Comment: Bem-vindo ao StackOverflow Roberto. Qual é o controle que tem essas "TABS" que você se refere? Por favor, poste um trecho do código que você já tem para termos uma ideia melhor do problema, sugiro que leia esse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Answer: Vai na propriedade (Property Pages) da Tab. Na segunda guia (Tabs) você vai ter o botão Insert Tab com todas as suas propriedades (Index, Caption, Key, Tag, ToolTip...).
Comment: Deu certo Roberto Elias?