Erro ao enviar dados para View

Question: Consulta para trazer os usuários.
public IEnumerable PopulaTabelaUsuario()
{
     var banco = new DbBancoContext();
     var listaUsuarios = (from l in banco.USUARIOS_PROCESSO
         select new{ l.ID_USUARIO, l.NOME_USUARIO }).ToList();
     return  listaUsuarios;
}

Minha controller.
public ActionResult AreaPrincipal()
{
    var lista = new ConsultasNecessarias();
    var usuarios = lista.PopulaTabelaUsuario();
    //var r = new DbBancoContext();
    //var s = r.USUARIOS_PROCESSO.Select(m=>m.NOME_USUARIO).ToList();
    return View(usuarios);
}

Minha View.
@model IEnumerable<ControleVisita.Models.USUARIOS_PROCESSO>
@{
    ViewBag.Title = "Área Principal";
}

@section Menu{
}

            Id Usuário
            Nome

        @foreach (var item in Model)
        {

                @Html.DisplayFor(modelItem => @item.ID_USUARIO)
                @Html.DisplayFor(modelItem => @item.NOME_USUARIO)

        }

Mas quando executo apresenta o seguinte erro.

O item de modelo inserido no dicionário é do
  tipo'System.Collections.Generic.List1[<>f__AnonymousType42[System.Int32,System.String]]',
  mas esse dicionário requer um item do tipo
  'System.Collections.Generic.IEnumerable`1[ControleVisita.Models.USUARIOS_PROCESSO]'.
Comment: O problema nem é do bootstrap, é do tipo de dados que estás a enviar para a view
Comment: O problema esta no facto de ter declarado na view que ia passar um model do tipo USUARIOS_PROCESSO. O seu controller esta a passar na realidade uma classe anonima que contem os dados que selecionou na query (o tal `new {...}`). Solucao sera ou alterar a query para devolver o tal USUARIOS_PROCESSO ou entao alterar a View com o tipo enviado (como duvido que de para colocar um tipo anonimo, eu criaria uma List>)
Comment: Concordo CesarMiguel coloquei apenas pois existe o webgrid mas não queria usar. Gostaria de saber como corrijo a questão dos tipos de dados?
Comment: [off-topic] Rabelos, favor não confundir as tags [tag:mvc] com [tag:asp.net-mvc]
Answer: Usando o select new, será criado um novo objeto do tipo anonimo como resultado da consulta.
Você não pode retornar um IEnumerable anonimo (IEnumerable<AnonymousType>) porque o tipo a ser retornado não é conhecido.
Tente modificar seu método PopulaTabelaUsuario() de consulta para retornar IEnumerable<USUARIOS_PROCESSO>.
public IEnumerable<USUARIOS_PROCESSO> PopulaTabelaUsuario()
{
    var banco = new DbBancoContext();
    IEnumerable<USUARIOS_PROCESSO> listaUsuarios = (
        from l in banco.USUARIOS_PROCESSO
        select new USUARIOS_PROCESSO { l.ID_USUARIO, l.NOME_USUARIO }
    ).ToList();
    return  listaUsuarios;
}

Erro ao enviar dados para View


Finding the sum of an alternating series

Question: I want to find the sum of $$\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^2}$$ I know that this is equal to $\frac{\pi^2}{12}$ thus I was thinking this must just be a taylor series of some trigonometric function but after looking it up, I cannot seem to find one that satisfies this. Any suggestions are greatly appreciated.
From below the user states that $$\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^2} = \sum_{n=0}^{\infty}\left(\frac{1}{2n+1} \right)^2 -\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2 = \sum_{n=1}^{\infty}\frac{1}{n^2} - 2\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2 = \ldots = \frac{\pi^2}{12}$$
I want to know the details of the $\ldots$ part.
Comment: Notice that: $$\begin{align}\sum_{n=1}^\infty\frac1{n^2}-2\sum_{n=1}^\infty\left(\frac1{2n}\right)^2&=\sum_{n=1}^\infty\frac1{n^2}-2\sum_{n=1}^\infty\frac1{4n^2}\\&=\sum_{n=1}^\infty\frac1{n^2}-2\times\frac14\sum_{n=1}^\infty\frac1{n^2}\\&=\sum_{n=1}^\infty\frac1{n^2}-\frac12\sum_{n=1}^\infty\frac1{n^2}\\&=\frac12\sum_{n=1}^\infty\frac1{n^2}\\&=\frac12\frac{\pi^2}6\end{align}$$
Answer: The series can be written as
$$\sum _0 ^{\infty}\left(\frac {1}{2n+1}\right)^2-\sum _1 ^{\infty}\left(\frac {1}{2n}\right)^2=\sum _1 ^{\infty} \frac {1}{n^2}-2\sum _1 ^{\infty}\left(\frac {1}{2n}\right)^2$$
By adding and subtracting:
$\sum _1 ^{\infty} \left(\frac {1}{2n}\right)^2$
Edited part :-
$$\sum _0 ^{\infty}\left(\frac {1}{2n+1}\right)^2+\sum_1 ^{\infty}\left(\frac {1}{2n}\right)^2-2\sum_1 ^{\infty}\left(\frac{1}{2n}\right)^2$$
Now first two sums can be written as
$$\sum _1 ^{\infty} \frac {1}{n^2}$$ So the next two can be written as:
$$\frac {1}{2}\sum _1 ^{\infty} \frac {1}{n^2}$$
Now we know all the summations. Thus the answer is:
$$\frac {\pi ^2}{6}-\frac {\pi^2}{2.6}=\frac {\pi^2}{12} $$
Comment: Could you give a little more detail on the part where you say "adding and subtracting"...
Comment: I have edited the answer.
Comment: I really like your approach but I don't understand how $$\sum_{n=0}^{\infty}\left(\frac{1}{2n+1} \right)^2 -\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2 = \sum_{n=1}^{\infty}\frac{1}{n^2} - 2\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2$$ The rest of your answer is a bit choppy for me and I can't really follow the rest
Comment: See the terms of original series they are as follows $1-\frac {1}{4}+\frac {1}{9}...=1+\frac {1}{9}+\frac {1}{25}-(\frac {1}{4}+\frac {1}{16}+\frac {1}{36}) $ now add all terms with squares of even nos. As we have added we need to subtract . Now we have the series as $1+\frac {1}{4}-\frac {1}{4}-\frac {1}{4}+\frac {1}{9}+\frac {1}{16}-\frac {1}{16}-\frac {1}{16}..... $ now group all positive and negative terms we see its $1+\frac {1}{4}+\frac {1}{9}...-2 (\frac {1}{4}+\frac {1}{16}+\frac {1}{36}...)$ now pull out 4 from all negative terms . We see that the series is simply $0.5\frac{1}{n^2} $
Comment: Ok, thank you. Although how do you get to the $\frac{\pi^2}{6} - \frac{\pi^2}{2\times 6}$ part?
Comment: Specifically how do we go from $$\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^2} = \sum_{n=0}^{\infty}\left(\frac{1}{2n+1} \right)^2 -\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2 = \sum_{n=1}^{\infty}\frac{1}{n^2} - 2\sum_{n=1}^{\infty}\left(\frac{1}{2n}\right)^2 = \ldots = \frac{\pi^2}{12}$$
Answer: Hint. One may see this as a special value of the dilogarithm function
$$
\text{Li}_2(z)=\sum_{n=1}^\infty\frac{z^n}{n^2},\qquad |z|\le1,
$$
recalling that
$$
\text{Li}_2(1)=\frac{\pi^2}6
$$ one may observe that
$$
2\left(\text{Li}_2(z)+\text{Li}_2(-z)\right)=\text{Li}_2(z^2)
$$ giving, by putting $z=1$,
$$
\text{Li}_2(-1)=\sum_{n=1}^\infty\frac{(-1)^n}{n^2}=-\frac{\pi^2}{12}.
$$
Comment: Observe that from my last line one has $$\sum_{n=1}^\infty\frac{(-1)^n}{n^2}=-\frac{\pi^2}{12} \implies \sum_{n=1}^\infty\frac{(-1)^{n+1}}{n^2}=\frac{\pi^2}{12}  $$ as given by the OP.
Comment: Its $n+1$ or maybe my answer is wrong.
Comment: Then why are we getting different answers. Can you see my answer if there is a mistake?


will not generate barcode

Question: I was trying to create a bar code generator in python using a fairly simple code. I am new to some this module and am a bit rusty to python so I was wondering what causes an error in the code
<code>#imports the correct module needed to create the barcodes
from barcode import EAN13
# imports a module that will create the numbers needed for the barcode
from random import randint

codes = []
barcodes = []
for i in range(100):
    code = randint(1111111111111, 9999999999999)
    while code not in codes:
        codes.append(code)

# creates the barcode object
for code in codes:
    barcode = EAN13("{codes}")
    barcodes.append(barcode)

# prints the barcode
print(barcodes(0))

Error caused
will not generate any barcodes because the number cant be saved as a string

i want this to be able to display barcodes
</code>
Answer: You can use the ImageWriter to save as png files. Import and use when creating the barcode.
<code>from barcode import EAN13
from random import randint
from barcode.writer import ImageWriter

codes = []
barcodes = []
for i in range(100):
    code = randint(1111111111111, 9999999999999)
    while code not in codes:
        codes.append(code)

# creates the barcode object
for code in codes:
    code = str(code)
    # barcode = EAN13(code)
    barcode = EAN13(code, writer=ImageWriter())
    barcodes.append(barcode)

# render the first barcode in the list
# barcodes[0].render()

for bc in barcodes:
    bc.save(f'barcode{bc.ean}')
</code>
Comment: thank you burt this displays an error when running for some reason i am unable to open the png that was created
Comment: the error i got was a permission error: ermissionError: [Errno 13] Permission denied: 'barcode7406502820659.png'
Comment: I think you need pillow installed to generate the images **pip install pillow** That may be your issue if you dont have it installed.
Comment: i did that and it was already satisfied
Comment: Permission denied suggests that file 'barcode7406502820659.png' exists and is already open in som app or the directory you are saving the pngs to doesn't exist or maybe cannot be written to. Since they are randomly generated the later seems more likely. Can you double check there is not issue with the directory you are trying to save in?
Comment: how do i know what directory i am saving it too?
Comment: That can depend on what IDE you are using. For most or if you are just running it as a python file in a command window it should be the same directory as the python file. You can specify the directory to be sure, like change the line to **bc.save(f'c:/Temp/bc/barcode{bc.ean}')** and make sure the directory exists before running the code.
Comment: I am using vs code and when runnging with this it throws this syntax error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
Comment: What line? the save line? Are you using backslashes for the path like 'c:\Temp\bc\barc...' If so you can sometimes get away with that but potentially a backslash will be interpreted as an escape character, e.g. the \b in the path would be considered to be a word boundary. That's why I used forward slashes (forward slashes will work for Windows, MACOS and Linux) . If you want to use back slashes then use the 'raw' attribute, r' i.e. **bc.save(fr'c:\Temp\bc\barcode{bc.ean}')** or use double backslash **bc.save(f'c:\\Temp\\bc\\barcode{bc.ean}')**

will not generate barcode


Detecting Database is Down

Question: I want to detect when a database is down and I know once the database is down it will throw a SQLException. Using Connection.isValid(). What does the timeout paramter represent? It says:

timeout - - The time in seconds to wait for the database operation
  used to validate the connection to complete. If the timeout period
  expires before the operation completes, this method returns false. A
  value of 0 indicates a timeout is not applied to the database
  operation.

What does this mean?
Answer: The isValid() method allows you to check the Connection for validity.
For this method you can specify a timeout in seconds, when this timeout runs out before the internal validity check is finished, the method will return false.
This is useful if you don't want your program to wait a long time in case the validity check takes too long.
If you give 0 as input for timeout, no timeout will be applied and your program will wait until the check is complete.
Answer: Well, "database is down" means it does not respond. It's not like it can just tell you "hey, I'm down". So the timeout means how long does this method wait for response, before considering database as offline.
Comment: What is reasonable amount of time to detect if database is down. What value can be entered here?
Comment: That depends on how "far" network-wise your database is. You may just have poor connection, but this is rarely an issue. Don't put your timeout high, some few seconds, but instead implement a retry logic.
Answer: It represent the time to discard the connection if any connection is idle for that much time.

Detecting Database is Down


Question Regarding Number Theory(Congruence Modulo specifically).

Question: Consider the Group U(55) under multiplication modulo 55. Let x∈U(55) be such that x.x=26 and x>30. Then find the value of x.
Now I want to know that if the above question can be represented in congruence equation. If yes then please tell me how it would be done and recommend a book or something from which I can learn and practice such questions.
Comment: $x^2\equiv 26\pmod {55}$.  To solve it I would suggest noting that $55=5\times 11$ so you can solve $\pmod 5$ and $\pmod 11$ separately.  Alternatively, $55$ is very small so trial and error works just fine.
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.* From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Answer: You basically want to find $x>30$ such that $x^2\equiv26\pmod{55}$.
This is true if and only if $x^2\equiv 26\equiv1\pmod{5}$ and $x^2\equiv 26\equiv4\pmod{11}$.
It is easy to check that the solutions to these congruences larger than 30 are $x=31,46$.

Here is how to solve the congruences. First notice that $x^2\equiv1\pmod 5$ iff $x\equiv\pm 1\pmod5$, and $x^2\equiv4\pmod{11}$ iff $x\equiv\pm2\pmod{11}$.$^{\color{red}1}$ Thus we have four possibilities:
\begin{align*}
                x&\equiv 1  \pmod 5 &\text{and}&& x &\equiv 2  \pmod {11}\\
                x&\equiv 1  \pmod 5 &\text{and}&& x &\equiv -2  \pmod {11}\\
                x&\equiv -1  \pmod 5 &\text{and}&& x &\equiv 2 \pmod {11}\\
                x&\equiv -1 \pmod 5 &\text{and}&& x &\equiv -2  \pmod {11}
            \end{align*}
In general, to solve $x\equiv a_1\pmod{M_1}$ and $x\equiv a_2\pmod{M_2}$, observe that $$x=a_1M_2y_2+a_2M_1y_1$$
is a solution, where $y_2={M_2}^{-1}\pmod{M_1}$ and $y_1={M_1}^{-1}\pmod{M_2}$.  Indeed, if you work $\bmod M_1$, the second term vanishes and the first term simplifies to $a_1$, whereas $\bmod M_2$, the first term vanishes and you're left with $a_2$.$^{\color{red}2}$
Reasoning this way, we get the four solutions
\begin{align*}
   x&=1\cdot 11 \cdot 11 + 2\cdot5 \cdot 9 &{}={}& 211\equiv46\pmod{55}\\
   x&=1\cdot 11 \cdot 11 + (-2)\cdot5 \cdot 9 &{}={}& 31\\
   x&=(-1)\cdot 11 \cdot 11 + 2\cdot5 \cdot 9 &{}={}& -31\equiv24\pmod{55}\\
   x&=(-1)\cdot 11 \cdot 11 + (-2)\cdot5 \cdot 9 &{}={}& -211 \equiv 9 \pmod{55},
\end{align*}
two of which are $>30$.
There are loads of resources available online, a quick DuckDuckGo search gave this set of notes on elementary number theory which covers this sort of thing.

$^1$ In general, there are always 2 or 0 solutions to $x^2\equiv a\pmod m$. Read about quadratic residues for more information.
$^2$ This is essentially how you prove the Chinese remainder theorem. Also, finding only one solutions is enough, because linear congruences always have one solution (up to modulo).


Trying to copy a file from the current directory to F:\ drive in vbscript

Question: Here's what I have so far:
If E = 1 Then
obj.CopyFile "(CD.CurrentDirectory)" "E:\"
End If

(My WScript variable is CD)
Comment: Please [edit] your question and add _properly formatted_ [mcve]. Note that **Trying to copy a file** is not an answerable question in _any_ sense.
Comment: `FileSystemObject.CopyFile "*.doc", "E:\"`
Answer: If you don't specify a path the FileSystemObject will look in the current directory.
Dim fso

Set fso = WScript.CreateObject("Scripting.Filesystemobject")

fso.CopyFile "text.txt", "C:\Users\best buy\Downloads\stackoverflow\"

It worth noting that you can give the new file a different name.

fso.CopyFile "text.txt", "C:\Users\best buy\Downloads\stackoverflow\testing123.txt"


Hide text field in hook_form_alter

Question: I have a field field_agent_name. I want to hide this field in my custom module using hook_form_alter.
How to do this.
Answer: Using the hook_form_FORM_ID_alter format is ideal:
function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_agent_name']['#access'] = FALSE;
}

More info on hook_form_FORM_ID_alter
Comment: @AyeshK according to the docs $form_state should be passed by reference :) the form doesn't need to be returned though
Comment: You dont need to return the $form if its referenced.
Comment: +1 for using form_id_alter. Other than above comment, you do not need $form_state to be passed by reference either.
Answer: Below code worked for me:
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contenttypename_node_form') {
    $form['field_agent_name']['#access'] = 0;
  }
}

Hide text field in hook_form_alter


Can I have an NSArray containing NSArrays

Question: I would like to store multiple values for a label and I have some 10 labels.
So is it possible to have a NSArray of NSArray objects?
Can I do something like this:
<code>[[NSArray alloc] initWithObjects: NSArray1, NSArray2, nil];
</code>
Comment: Did you try it? You can answer this question by using XCode.
Answer: Yes. An NSArray can hold any object subclassed from NSObject. NSArray is subclassed from NSObject. Therefore, an NSArray can hold an NSArray.
Answer: Since you can store any object inside an NSArray, you can store other NSArrays inside just like any other object (i.e. NSNumber, YourCustombObj, etc.).
You can even add NSMutableArrays or NSDictionarys inside NSArrays:
<code>NSArray *array = [NSarray alloc] initWithObjects: mutableArray1, dictionary1, nil];
</code>


tensorflow cudaGetDevice() failed. Status: cudaGetErrorString symbol not found

Question: <code>tensorflow.python.framework.errors_impl.InternalError: cudaGetDevice() failed. Status: cudaGetErrorString symbol not found.
</code>
OS: Windows 10
CUDA version: 10.0
Visual studio: 2017 + 2019
Python version: 3.7.6
Answer: Figured it out:

Uninstall tensorflow
Uninstall CUDA
Uninstall visual studio
Install visual studio
Install CUDA
Install Tensorflow


Show that $\sum_{i=1}^{n}(i-1,n)[(i,n)=1] = \phi(n) \sigma_0(n)$

Question: Let:

$[]$ denote Iverson brackets, where $[P]=1$ if $P$ is true and $[P]=0$ if $P$ is false
$(a,b)$ denote the gcd of $a,b$
$\phi$ denote Euler's totient function
$\sigma_0(n)=d(n)$ denote the number of divisors of $n$

Then can we show
$$\sum_{i=1}^{n}(i-1,n)[(i,n)=1] = \phi(n) \sigma_0(n)?$$
Another way of writing this sum is:
$$\sum_{\substack{1\le i\le n\\ (i,n)=1}} (i-1,n) = \phi(n) \sigma_0(n)$$
Comment: Is $i$ limited by $n$ or in any other way?
Comment: Is $(i,n)$ a maximal common dividor of $i$ and $n$?
Comment: Yes means largest common multiple!
Comment: Limited by $n$.
Answer: This is known as Menon's identity. It has some generalizations, including one by an author who I know well!
It has a fantastic proof by Burnside's lemma. Let $G$ be any group of order $n$ and $U_n$ be the set of units modulo $n$ i.e. $U_n = \{k \in \mathbb N : \gcd(k,n) = 1\}$. This acts on $G$ by the action $(k,g) \to g^k$.
Look at the orbits. Two elements belong in the same orbit if and only if they generate the same cyclic subgroup. Therefore, the number of orbits of this action, equals the number of cyclic subgroups of $G$.
Now, by Burnside's lemma, the number of cyclic subgroups is equal to :
$$
\frac 1{\phi(n)}\sum_{\ \ \ \ \ \ \ k=1 \\ \gcd(k,n) = 1}^n \#\{g \in G : g^k = g\} \tag{*}
$$

Let $G$ be the cyclic group of order $n$. Then the number of cyclic subgroups of $G$ is equal to $\sigma_0(n)$ (one for each divisor), and if $g^k = g$ then $g^{k-1} = 1$, so we get that $\#\{g \in G : g^k = g\} = \gcd(k-1,n)$. Now the identity follows from $(*)$.


SSID authentication periodic failure

Question: Issue: intermittently, devices on my network will be unable to login to the wifi network, receiving an "incorrect password" or "password not recognised" response. Oddly inconsistent, the problem will appear once every few days at unpredictable times. More weirdly, it impacts SOME devices and not others: during any given incident two of us may be unable to login from our iphones but I can see the Chromecast is connected. Sometimes Alexa and my Macbook can't connect while other devices are fine.
I have a roaming network setup: an AVM Fritz Box in charge of DHCP and hosting a 2.4 and 5 ghz SSID. I also have an Apple Airport Extreme set to bridge mode and also hosting a 2.4 and 5ghz identically named SSID.  Each is automatically assigning their channels. All are set to WPA/WPA2 security.
I've witnessed both access points refusing to connect at different times. Last night the signal from the AVM Fritz Box was fine. If I walked an iPhone over to be physically closer than to the Airport Extreme, it logged in just fine. If I return to a point closer to the Airport, it eventually latches on to that signal but fails to connect, reporting incorrect password. But I've turned the Airport signal off entirely, and had the same incorrect password experience with the AVM Fritz Box as well.
I'm in a noisy neighborhood, have tried letting both devices set their own channels and forced them onto channels that were clear. I shut down a Chromecast device that was BLASTING a signal. All of these experiments take days to be proven ineffectual.
In WiFi.log  on my mac I see the following suspicious reports from an incident last night in which even rebooting the Airport Extreme (unplug to power down) didn't fix the problem.
    Sat Dec  2 22:41:40.751 <kernel> wl0: powerChange: *** BONJOUR/MDNS OFFLOADS ARE NOT RUNNING.
Sat Dec  2 22:42:16.003 <kernel> wl0: leaveModulePoweredForOffloads: Wi-Fi will stay on.
Sat Dec  2 22:42:16.003 <kernel> AirPort_Brcm43xx::platformWoWEnable: WWEN[enable], in_fatal_err[0]
Sat Dec  2 22:42:16.003 <kernel> AirPort_Brcm43xx::syncPowerState: WWEN[enabled]
Sat Dec  2 22:42:16.489 <kernel> IO80211Interface::updateReport _peerManager is missing
Sat Dec  2 22:42:16.575 <kernel> Setting BTCoex Config: enable_2G:1, profile_2g:0, enable_5G:1, profile_5G:0
Sat Dec  2 22:42:17.073 <kernel> AirPort_Brcm43xx::platformWoWEnable: WWEN[disable], in_fatal_err[0]
Sat Dec  2 22:42:17.213 <kernel> parseRSNIE: groupCipherType = 3 pairwiseCipherType = 5 authSel = 2
Sat Dec  2 22:42:17.213 <kernel> initWithInterfaceAndIE: _myMacAddress f4:5c:89:8a:d8:59
Sat Dec  2 22:42:17.213 <kernel> setPMK: PMK SET!
Sat Dec  2 22:42:17.313 <airportd[64]> ERROR: WiFiProxy (418) is not entitled for com.apple.wifi.events, but allowing anyways for event type 1 [And does this for event types 1..8]

Then there's this oft-repeating block which seems to do with authitication:
Sat Dec  2 22:42:29.117 <kernel> RSNSupplicant: Releasing authenticator for 00:00:00:00:00:00
Sat Dec  2 22:42:29.122 <kernel> AirPort_Brcm4360::getSSIDData(): Get failure: APPLE80211_IOC_SSID: 6
Sat Dec  2 22:42:30.240 <kernel> parseRSNIE: groupCipherType = 3 pairwiseCipherType = 5 authSel = 2
Sat Dec  2 22:42:30.240 <kernel> initWithInterfaceAndIE: _myMacAddress XX.XX.XX.XX.XX.XX
Sat Dec  2 22:42:30.240 <kernel> setPMK: PMK SET!
Sat Dec  2 22:42:30.544 <kernel> Unexpected payload found for message 9, dataLen 0
Sat Dec  2 22:42:34.564 <kernel> Unexpected payload found for message 34, dataLen 2
Sat Dec  2 22:42:34.564 <kernel> payload Data 02 00
Sat Dec  2 22:42:34.569 <kernel> en0: Terminating supplicant.

And this which appears to have something to do with login:
> Sat Dec  2 23:47:47.387 <kernel> IO80211Interface::updateReport
> _peerManager is missing Sat Dec  2 23:48:55.926 <kernel> Setting BTCoex Config: enable_2G:1, profile_2g:0, enable_5G:1, profile_5G:0
> Sat Dec  2 23:48:57.320 <airportd[64]> ERROR: loginwindow (106) is not
> entitled for com.apple.wifi.events.private, will not register for
> event type 100 [And does the same for event types 101, 7, 2, 5, and 6]

Anyone seen this or can parse those log messages to know what's going on?
Answer: I've seen all these messages, ad nauseam.You need a developer login to see this, but it clarifies why we've all been seeing this error.
com.apple.wifi.events.private
is part of CoreWLAN which is incompatible with the sandbox. The entitlement it's asking for is a sandbox entitlement. So, ERROR level message is thrown.
I'm surprised by this. It's an open bug. However, it's probably not the actual problem, although it does seem like A problem.
If you don't use AirDrop or related esoterica, try turning off awdl0 with ifconfig for a week.
sudo ifconfig awdl0 down
See if your WiFi is any more stable.
I have a sense that we all are looking locally for the source of these issues, but most of the functionality of these devices is remote, via iCloud.
Anyway, from the link below:

However, it's not possible for third-party apps to get the entitlement described in that log message, so that's a complete red herring.
There seems to be a problem with CWWiFiClient where it requires that the app have a specific entitlement ("com.apple.wifi.events") even though entitlements are only meaningful in Mac App Store (and hence sandboxed) apps.
This has been noticed by another developer, who filed a bug about it.  Alas, that bug seems to have been misinterpreted, so I've filed my own bug about it.  That bug hasn't yet come back to me, so I presume that it still applies.
As to workarounds, your best option is to use the CWXxxDidChangeNotification notifications.  While these are formally deprecated, they do still work and they're your only way forward until the above-mentioned bug is fixed.

(source)
Comment: Alas, I DO use airdrop, daily -- the experiment suggested here would be more inconvenient than the problem I'm trying to solve. I will say in the last 6 months the problem has abated. The one incident I had last month was fixed by rebooting both routers. But I could not say at this point whether that was because of a fix to the permissions issue you site or any number of changes to my environment here.
Comment: I'm seeing a complete absence in my logs of com.apple.wifi.events.private - you may have sussed it. I'm going to monitor for a repeat of the problem and if I don't see it again in the next 60 days or so I'll mark your answer as accepted and presume Apple addressed this bug. And that my network setup was fine all along!

SSID authentication periodic failure


Is there a continuous, strictly increasing function $f: [0,\infty)\to [0,\infty)$ with $f(0) = 0$ such that $\tilde d = f\circ d$ is not a metric?

Question: Is there a continuous, strictly increasing function $f \colon [0,\infty)→ [0,\infty)$ with $f(0) = 0$ such that $\tilde d =  f\circ d$ is not a metric? You may take $(X,d)$ to be $\mathbb R$ with the standard metric for this part.
My thoughts are that there isn't any function $\tilde{d}$ which would not be a metric since the distance function $d: X \times X \to \mathbb{R}$ hold the metric space properties. That is, for all $x,y,z\in X$:
(1) $d(x,y) \ge 0$, $d(x,y) = 0$ if and only if $x = y$
(2) $d(x,y) = d(y,x)$
(3) $d(x,y) \le d(x,z) + d(z,y)$
My first thought was if $f$ was a $\ln$ function, then $\tilde{d}$ would not be a metric space, but the question states that $f(0) = 0$, hence $f$ cannot be chosen to be a $\ln$ function anyway.
Just having trouble proving it one way or the other. Any help appreciated.
Comment: Have you tried proving the opposite?
Comment: @Sam: What did you try to solve this problem yourself? What functions $f$ did you try?
Comment: See also:
[Conditions for defining new metrics](https://math.stackexchange.com/q/123454) and
[How do you prove triangle inequality for this metric?](https://math.stackexchange.com/q/1862037).
Answer: (Getting this off the Unanswered list.)
You should have no trouble showing that if $f$ is strictly increasing and $f(0)=0$, then $\overline d=f\circ d$ satisfies $(1)$ and $(2)$ of the definition of a metric. Then it all comes down to checking whether $\overline d$ satisfies the triangle inequality. Suppose that $x,y,z\in X$; we want to show (if possible) that
$$\overline d(x,y)\le\overline d(x,z)+\overline d(z,y)\;.$$
Is it possible that we might have, say, $\overline d(x,z)=\overline d(z,y)=1$, but $\overline d(x,y)>2$? That could happen if, for instance, we had $d(x,z)=d(z,y)=1=f(1)$, $d(x,y)=2$, and $f(2)=4$. The function $f(x)=x^2$ would accomplish that — if we can think of a metric space $\langle X,d\rangle$ that has points $x,y$, and $z$ such that $d(x,z)=d(z,y)=1$ and $d(x,y)=2$. But that's easy, especially since the problem almost suggests that we should look at $X=\Bbb R$ with the usual metric: take $x=0,z=1$, and $y=2$. We now have a counterexample to the triangle inequality for $X=\Bbb R$, $d(x,y)=|x-y|$, and $f(x)=x^2$, so it's not always true that $\overline d$ is a metric.


Cointegration between a variable of significant seasonality and one with no significant seasonality

Question: After running programs of deseasonalization, I had an output in which one variable held significant seasonality, for which I corrected, and another that did not have. My main objective was to comprehend a relationship between those variables.
Both variables were tested to be unit root process and then I went for the Johansen test to test the number cointegration vectors, for which I got that I could reject the null of only one.
What should be the intuition here? Suppose I had a large number of observations and so I would not have the usual problems of unit root testing with small samples and all the other tests were correctly specified. Is there something that the literature says about this? A seasonal variable might have a strong and intuitive relationship with a non-seasonal one?
Edit: So a result like the one below would be contradictory if I previously considered both variables as I(1)?
<code>Trend: constant                                         Number of obs =      102
Sample:  3 - 104                                                  Lags =       2
-------------------------------------------------------------------------------
                                                         5%
maximum                                      trace    critical
  rank    parms       LL       eigenvalue  statistic    value
    0      6      -1064.8773           .     29.3877    15.41
    1      9      -1054.6653     0.29682      8.9637     3.76
    2      10     -1050.1834     0.14320
-------------------------------------------------------------------------------
</code>
Answer: As I understand, you have done the following:

You remove the seasonality for one of the variables, while no seasonality is found for the other variable (hence, nothing is removed there). Thus now you have two variables that are non-seasonal.
You proceed to unit root testing. You find unit roots for both variables.
You go for cointegration testing. You reject the null of one cointegrating vector in favour of more than one cointegrating vector. That means there is more than one stationary combination of the two variables, which implies they are both stationary.  (Of course, the vectors are normalized; otherwise you could have infinitely many versions of the same cointegrating vector just by scaling it.)

At this point you face a contradiction between the unit root tests and the cointegration test. This should not happen under ideal circumstances. If this happens, you should look for issues like structural changes, conditional heteroskedasticity etc. that invalidate the results of either the unit root tests, or the cointegration test, or both.
I do not quite see a problem with one variable being seasonal, as long as you use a seasonally-adjusted version of that variable in the analysis.
Comment: I added an example of an output. So for I(1) variables that would be a contradictory result?
Comment: If I am reading the output correctly, it fits into what I have already written in the answer. On the one hand, you have that individually each variable is I(1). On the other hand, taken together the variables have more than one linear combination that is I(0), which suggest they are not individually I(1).
Comment: Also, do you have a reference for what you are saying? Where can I see a demonstration that a cointegration test between two variables I(1) in which we test away only one cointegrating vector and the resulting conclusion is that this actually contradicts their I(1) condition?
Comment: No, I do not have a reference. Such results are typically not publishable and you are supposed to find the root of the problem before proceeding. In other words, you are supposed to somehow solve the contradiction.


How to define a new cache context for a node

Question: I am preprocessing a node with some data, i want to define a new cache context  based on this data.
function hook_preprocess_node(&$variables) {
    $variables['change'] = rand(0,5);
}

Once i have defined the new context i think i shuold be able to use it as follows.
function  hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode) {
  if($entity->getType() == 'page'){
    $build['#cache']['contexts'][] = 'change';
  }
}

I can't seem to find out how to define a brand new cache context based on the data in my preprocess so that i can use it in hook_entity_build_defaults_alter();
Answer: You will need to define a cache context in yourmodule/src/Context. This will be a class implementing CacheContextInterface, as described in the docs here (see 'How to recognize, discover and create?).
If you search for implements CacheContextInterface in your code base you should be able to see some examples. The class will provide getContext() and getCacheableMetadata() methods.
Comment: note that you also need to define it as a service, not just the class.


Get loop counter/index using for…of syntax in JavaScript

Question: I understand that the basic for...of syntax in JavaScript looks like this:
for (let obj of myArray) {
  // ...
}

But how do I get the loop counter/index when iterating with this syntax?
(With the same question applying to for...in notation for iterating over object property names)
I know I can use an explicit loop counter like:
for (let i = 0; i < myArray.length; i++) {
  const obj = myArray[i];
  console.log(i);
}

Or manually track the index outside of the loop:
let i = 0;
for (let obj of myArray) {
  console.log(i);
  i++;
}

But I would rather use the simpler for...of loop, I think they look better and make more sense.
As an example of a language that lets you do this, in Python it's as easy as:
for i, obj in enumerate(my_array):
    print(i)

Comment: Don't use for...in for arrays. And anyways, it iterates over the property names, not the values of the properties.
Comment: It's an array, not an object, right?  So, `alert(obj)`?
Answer: for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn't use it to iterate over arrays. For them, there's ES5's forEach method that passes both the value and the index to the function you give it:
var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Or ES6's Array.prototype.entries, which now has support across current browser versions:
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}

For iterables in general (where you would use a for…of loop rather than a for…in), there's nothing built-in, however:
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.
Comment: @quantumpotato: `let`s are `var`s with block scope. `const`s are unchanging.
Comment: The downside of `forEach` is that `await` inside is scoped to the function parameter, not the outer scope. So if you want to await inside the loop, you probably want to use `.entries()`.
Comment: stupid question but what does %d and %s actually stand for, or could they be any letter I want them to be?
Comment: @klewis: `%d` formats an integer and `%s` formats a string. They're inspired by [printf](https://en.wikipedia.org/wiki/Printf_format_string). A spec is in progress at https://console.spec.whatwg.org/#formatter.
Comment: Actually, obj will be the array index, but there is no guarantee that it is in order and that it won't include other property names.
Comment: don't you need to do var i = 0, because lets are unchanging?
Comment: I did not know this was possible: `myArray.forEach(function (value, *i*)` (emphasis mine). This is perfect. I knew there had to be a better way than that `myArray.indexOf(value)` garbage I've been doing. +1.
Comment: In the example above, 'i' which should be the index returns undefined, please help.
Comment: @Ade In which example?
Comment: I have sorted my self now. (The mistake I'd made was following your solution whilst still using the ECMA arrow and without the keyword, "function". Thanks Ry.
Comment: Note the other answer below in reference to arrow functions... But the above does work too.
Comment: Which one is faster in Node 18?
Comment: @Antoine: It's usually close enough not to matter in modern V8; I essentially always use `for of`. You can benchmark your own use case to get concrete numbers.
Comment: Note: you should take special precautions if you're using an async callback with something like foreach since it would run the loops in parallel if you were hoping to run in serial.
Comment: From MDN: "The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#description
Answer: In ES6, it is good to use a for... of loop.
You can get index in for... of like this
for (let [index, val] of array.entries()) {
  // your code goes here
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
Comment: I think this solution is better than the forEach one... It uses the nomral for...of loop syntax, and you don't have to use a separate function. In other words, it's syntactically better. The OP seems to have wanted this.
Comment: Also this allows `await` to work in sequence, whereas `forEach` does not.
Comment: It's supposed to do that, Joshua - the object is an iterator, an object with a `next()` method that will return subsequent entries in the array each time it is called. There's no (visible) data in it; you get the data in the underlying object by calling `next()`, which for-of does behind the scenes. cc @tonyg
Comment: Be aware this only works for `Array`. `for...of` works on any `Iterable`. You might have to convert to `Array` with `for (const [index, value] of [...array].entries())`. Iterables include `HTMLCollection` `NodeList`, and other DOM classes.
Comment: `entries()` is returning an empty object: `{}`. Any idea why that would be? My `array` is an Array of Objects.
Comment: Why use `let` instead of `const`?
Comment: @JoshuaPinter try `Object.entries(array)` instead of `array.entries()`
Comment: woah, I take it back. I was using a repl and `array.entries()` always returns `{}` but if you actually use the code above, using `for ... of array.entries()` it works just fine. Sorry about that.
Comment: nicely done! ...
Comment: I agree with @Ben. The values don't change in scope so should be `const`, not `let`.
Answer: How about this
let numbers = [1,2,3,4,5]
numbers.forEach((number, index) => console.log(`${index}:${number}`))

Where array.forEach this method has an index parameter which is the index of the current element being processed in the array.
Comment: The chosen answer was posted 6 years before this one and has the same thing already in it...
Comment: Foreach is not good for optimization, since `break` is not available.
Comment: @smartworld-dm I do agree with this but there is the simple return statement.
Answer: Solution for small array collections:
for (var obj in arr) {
    var i = Object.keys(arr).indexOf(obj);
}

arr - ARRAY,
 obj - KEY of current element,
 i - COUNTER/INDEX
Notice: Method keys() is not available for IE version <9, you should use Polyfill code.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Comment: I'd suggest: use a counter instead, increment it in loop.
Comment: Adding on to mayankcpdixit, use a counter instead because indexOf could have a negative performance impact.
Comment: The larger the object, the slower this will get. This does not scale.
Comment: This is kind of pointlessly slow and complicated because `var i = 0;` and `i++;` is shorter and more efficient. Plus it doesn't work for enumerable properties that aren't own properties.
Comment: @trusktr: And if it is required… you should still not use this. Just alter the counter when you alter the collection. If it doesn't have to be in-place, do a nice functional transformation instead.
Comment: This has horrible performance characteristics, and should not be suggested ever.
Comment: And it won't work it some value are duplicated in the array
Comment: why learn the non performant way ever when the better options are just as easy?  this is how people learn bad habits and don't know they are bad habits.
Comment: @mayankcpdixit Incrementing a counter won't work in for..of loops that modify the array during iteration.
Comment: @Ryan `var i = 0;` and `i++;` won't work in loops that modify the array during iteration. @rushUp's answer is superb, because the index will be the original index of each item before iteration, regardless of the array being modified during iteration.
Comment: @trusktr: Why are you replying to a comment about this answer, which iterates over an array in ϴ(n²) time?
Comment: @trusktr yes! but `for...of` is still relatively new. If you're using `for...in`, _counter_ would be a good coice.
Comment: @Ryan If modifying the collection during iteration isn't required, then yeah, a regular for loop is a good way to make it faster. :}
Comment: @Ryan That makes code harder to read. I would say it depends on the use case. If you are using it for something that the end user will not perceive performance-wise, then use it. For 60fps graphics? Maybe not.
Comment: @trusktr: Which option to pick depends on the use case. Whether to pick *this* option does not. There is no reason to get a new `Object.keys` and call `indexOf` on it for each item, ever. It takes time proportional to n² instead of n and is even less readable than a regular explicit loop.
Comment: @JaysonMinard To be fair, the author did specify "small arrays". Performance is usually not a concern there.
Comment: How on Earth did anybody upvote this?
Answer: For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
loop over an Array:
var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

loop over an Object:
var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}

Comment: @FelixSanz: Waste resources? No way. That is a premature micro-optimisation that is hardly ever necessary, and `var i=0; i<a.length; i++)` is the standard loop pattern that is optimised by every decent javascript engine anyway.
Comment: @FelixSanz: Yes, and `var i=0; i<a.length; i++` is the best practise.
Comment: KISS applies everywhere. [Premature optimisation](https://en.wikipedia.org/wiki/Premature_optimisation) is an anti-practise.
Comment: Never do `(var i=0; i<a.length; i++)` as is wasted resources. Use `(var i=0, var len = a.length; i<len; i++)`
Comment: [KISS](http://en.wikipedia.org/wiki/KISS_principle). If you write loops where you really need this you either are doing something wrong, or you have a better argument for its necessity than "best practise". Yes, it is a standard practise, but not for generic performance optimisation, but only for micro-optimisation.
Comment: best practices are best practices!
Comment: KISS is just a principle. You are not proving it applies here, i did. so i won't reply anymore. do whatever you want.
Answer: As others have said, you shouldn't be using for..in to iterate over an array.
for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }

If you want cleaner syntax, you could use forEach:
myArray.forEach( function ( val, i ) { ... } );

If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.
Answer: Answer Given by rushUp Is correct but this will be more convenient
for (let [index, val] of array.entries() || []) {
   // your code goes here
}

Comment: `|| []` is unnecessary and will never be used; `array.entries()` is always truthy.
Comment: [index, val] never works for me, it says "undefined"
Comment: can you share your array ?
Comment: Why repeat an existing answer? Downvoted.
Answer: Here's a function eachWithIndex that works with anything iterable.
You could also write a similar function eachWithKey that works with objets using for...in.
// example generator (returns an iterator that can only be iterated once)
function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }

// convers an iterable to an array (potential infinite loop)
function eachToArray(iterable) {
    const result = []
    for (const val of iterable) result.push(val)
    return result
}

// yields every value and index of an iterable (array, generator, ...)
function* eachWithIndex(iterable) {
    const shared = new Array(2)
    shared[1] = 0
    for (shared[0] of iterable) {
        yield shared
        shared[1]++
    }
}

console.log('iterate values and indexes from a generator')
for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)

console.log('create an array')
const anArray = eachToArray(eachFromTo(10, 13))
console.log(anArray)

console.log('iterate values and indexes from an array')
for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)

The good thing with generators is that they are lazy and can take another generator's result as an argument.
Answer: That's my version of a composite iterator that yields an index and any passed generator function's value with an example of (slow) prime search:

const eachWithIndex = (iterable) => {
  return {
    *[Symbol.iterator]() {
      let i = 0
      for(let val of iterable) {
        i++
          yield [i, val]
      }
    }
  }

}

const isPrime = (n) => {
  for (i = 2; i < Math.floor(Math.sqrt(n) + 1); i++) {
    if (n % i == 0) {
      return false
    }
  }
  return true
}

let primes = {
  *[Symbol.iterator]() {
    let candidate = 2
    while (true) {
      if (isPrime(candidate)) yield candidate
        candidate++
    }
  }
}

for (const [i, prime] of eachWithIndex(primes)) {
  console.log(i, prime)
  if (i === 100) break
}
Comment: Why do you have a function `eachWithIndex[Symbol.iterator]` instead of just a function `eachWithIndex`? `eachWithIndex` doesn't satisfy the iterable interface, which is the whole point of `Symbol.iterator`.
Comment: @Ry- Good catch, changed `eachWithIndex` to accept iterable and return a closured composite iterable.
Answer: On top of the very good answers everyone posted I want to add that the most performant solution is the ES6 entries. It seems contraintuitive for many devs here, so I created this perf benchamrk.

It's ~6 times faster. Mainly because doesn't need to: a) access the array more than once and, b) cast the index.
Comment: I've got to say you are not comparing apple to apple in the above test case. In classic, extra const v is defined plus the unnecessary type conversion Number(i) all led to its overhead. By removing those bits, my result shows the contrary: classic is 4 times faster. Please check the updated version [here](https://jsperf.com/enumerate/5)
Comment: @Marshal  Your link is dead
Comment: @javadba, That's because [jsperf is down](https://stackoverflow.com/questions/37695890/how-to-profile-javascript-now-that-jsperf-is-down). I'll create a new answer
Comment: Saying it's the "most performant solution" based on a benchmark that only includes one other approach (that also happens to be wrong) is pretty misleading. How about comparing it against the top answers?
Answer: One answer that seems to be missing is that in Python, the enumeration is a function. So: you could just do the same in JavaScript and then destructure during your for...of loop:

// Stick this in any random utils.js that you can import from
function enumerate(arr) {
  return arr.map((element, i) => [i, element]);
}

const myArray = ['a','b','c','d','e'];

// And then loop over *that* instead of the plain array:
for (let [i, element] of enumerate(myArray)) {
  console.log(i, element);
}

But I'd probably go with a map instead, of course:
myArray.forEach((element, i) => {
  console.log(i, element);
});

Answer: // this loop is used in advanced javascript
//For Example I have an array:
let array = [1,2,3,4,5];
1) for(let key in array){
      console.log(key);//this shows index of array {Result: 0,1,2,3,4}
      console.log(array[key]);//this show values of array {Result: 1,2,3,4,5}
   }
//Hopefully, You will quickly understand;

Answer: To use for..of loop on array and retrieve index you can you use array1.indexOf(element) which will return the index value of an element in the loop. You can return both the index and the value using this method.

array1 = ['a', 'b', 'c']
for (element of array1) {
    console.log(array1.indexOf(element), element) // 0 a 1 b 2 c
}

As mentionned in comments, this will return false index when the array contains non uniques values. (considering arr = ['a', 'b', 'c', 'a'], index of arr[3] will return 0 instead of 3) so this should be better suited for Sets than for Arrays.
Comment: This is unnecessarily quadratic and will produce incorrect results when the array contains duplicates.
Comment: useful with iterable objects, thanks pal, my_list.indexOf(element), though lambda expressions forEach is very useful.
Comment: Please explain your code a little as to what it does rather than adding snippets only. Plus it doesn't exactly answer the question. The question is rather about objects and taking an example of an array would perhaps be oversimplification. (From Review)


Trocar de Fragements sem carregar a tela toda

Question: Estou com um problema no meus estudos,
quando eu troco de Fragement e depois eu volto para a Fragment de origem os dados são carregados todos de novo.
E como os dados vem da web, leva um tempo e recursos preciosos,
queria uma forma que enquanto o app estivesse aberto as telas já bertas não fossem recarregadas.
na minha onNavigationItemSelected que fica na MainActivity
o código de transição de fragements é o seguinte
if(mFragmentManager.findFragmentByTag("one") != null) {
                        //if the fragment exists, show it.
                        mFragmentManager.beginTransaction().show(mFragmentManager.findFragmentByTag("one")).commit();
                    } else {
                        //if the fragment does not exist, add it to fragment manager.
                        mFragmentManager.beginTransaction().add(R.id.content, new CategoriaFragment(), "one").commit();

}

porém isso só esta evitando que a tela seja recarregada quando clicada no menu que abre  a tela atual.
Minha Activity principal é nela que eu chamo as minhas fragments e controlo a transição entre elas.
public class MainActivity extends AppCompatActivity {
    private String tituloNavBar;
    private TextView mTextMessage;
    private CategoriaFragment mCategoriaFragment;
    private BuscaFragment mBuscaFragment;
    private FragmentManager mFragmentManager;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.navigation_home:
                    tituloNavBar = getResources().getString(R.string.nav_bar_last);
                    titulo(tituloNavBar);
                    setFragment(mBuscaFragment,"Busca");
                    return true;
                case R.id.navigation_dashboard:
                    tituloNavBar = getResources().getString(R.string.nav_bar_start);
                    titulo(tituloNavBar);
                    if(mFragmentManager.findFragmentByTag("one") != null) {
                        //if the fragment exists, show it.
                        mFragmentManager.beginTransaction().show(mFragmentManager.findFragmentByTag("one")).commit();
                    } else {
                        //if the fragment does not exist, add it to fragment manager.
                        mFragmentManager.beginTransaction().add(R.id.content, new CategoriaFragment(), "one").commit();
                    }

                    return true;
                case R.id.navigation_notifications:
                    tituloNavBar = getResources().getString(R.string.nav_bar_filter);
                    titulo(tituloNavBar);
                    return true;
            }
            return false;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentManager = getSupportFragmentManager();
        tituloNavBar = getResources().getString(R.string.app_name);
        titulo(tituloNavBar);
        if(mBuscaFragment == null)
            mBuscaFragment = new BuscaFragment();

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        //Fragmente padrão
        setFragment(mBuscaFragment,tituloNavBar);

    }

    //Substituido pela logica acima
    private void setFragment(Fragment fragment, String name){
        FragmentManager fm = getSupportFragmentManager();
        if (fm != null) {
            FragmentTransaction ft = fm.beginTransaction();
            ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_in_left);
            ft.replace(R.id.content, fragment);
            ft.commit();
        }
    }
    private void titulo(String titulo){
        setTitle(titulo);

    }

}

é uma activity que contem um menu e pode chamar 3 fragments,
da seguinte forma
Activity principal
         - Fragment de busca
         - Fragment de categoria
         - Fragment de filtro

o resultado de qualquer um desses fragments resultaria em uma nova activity, seria para mostrar o detalhes, e essa activity teria mais 3 fragments.
Comment: Como você está implementando sua tela principal? Por que, dependendo de sua aplicação, vai ser necessário uma verificação ´para atualizar o layout. Explique melhor como é essa sua aplicação, por favor.
Comment: Danilo, no seu fragment você está carregando os dados no onResumo ou no onCreate?
Comment: Amigo o seu problema todo esta no ciclo de vida do fragment, te indico a ver esse [vídeo](https://www.youtube.com/watch?v=v7uVghlmWaM). Pelo que eu to entendo do seu problema, vc carrega todo seu layout no onCreat(), e é indicado utilizar o onResume para evitar que se carregue o fragment sem necessidade, também vi que você usa o .add ao invés do replace, veja esse vídeo e de uma estudada na [documentação](https://developer.android.com/guide/components/fragments.html?hl=pt-br)
Comment: @lucas_marciano adicionei uma explicação no final
Comment: Tudo no onCreate, me recomenda uma forma melhor?
Comment: Obrigado, com o vídeo eu conseguir fazer minha fragment não ser destruída ao rotacionar o aparelho, mas não mantinha a fragement quando era feita a troca de fragement, mas com o código abaixo eu cheguei a solução.

Obrigado, pois eu também queria manter minha fragment na rotação também
Answer: Conseguir solucionar meu problema, na Activity eu usei esse código para chamar as Fragments
if(mFragmentManager.findFragmentByTag(BuscaFragment.KEY) != null) {
                        //if the fragment exists, show it.
                        mFragmentManager.beginTransaction().show(mFragmentManager.findFragmentByTag(ConcursoFragment.KEY)).commit();
                    } else {
                        //if the fragment does not exist, add it to fragment manager.
                        mFragmentManager.beginTransaction().add(R.id.content, new ConcursoFragment(), ConcursoFragment.KEY).commit();

                    }
                        if(mFragmentManager.findFragmentByTag(CategoriaFragment.KEY) != null){
                        //if the other fragment is visible, hide it.
                        mFragmentManager.beginTransaction().hide(mFragmentManager.findFragmentByTag(CategoriaFragment.KEY)).commit();
}

na logica
if(mFragmentManager.findFragmentByTag(CategoriaFragment.KEY) != null)

aqui ele verifica se a ultima fragmente não é nula, se ela não for nula em vez de destruir ele só oculta, assim para próxima vez ele usa o show em vez do add no condicional acima
se alguém tiver uma solução melhor do que essa, por favor compartilhe


Configure AD VM on Hyper-V to provide AD services on user network (on one NIC) and logging on management network (separate NIC)

Question: As the topic suggests, I want to have the AD VM on Hyper-V connect to two different VLANs (100 and 200) which are different physical networks. One physical network (VLAN 100) is where all the user desktops lie (Need AD for user authentication) and one physical network is (VLAN 200) where I will forward the Event logs (Application, Security Events on the AD VM to.
These are two separate VLAN networks which require different physical NICs, in order to address a requirement to have logging on a separate segment.
How should I connect the AD VM to one Virtual Switch for user desktop segment and to another Virtual Switch for logging segment? Any pointers will be most appreciated!
Comment: Have you reviewed the documentation from Microsoft (and others) that Multi-homed domain controllers are not recommended?  Here is a documented workaround (https://support.microsoft.com/en-us/topic/9743befb-e48c-8175-8a16-8e96b68c42a9), though in my experience these workarounds are not 100% reliable and may (depending upon how the second VLAN is configured) eventually lead to authentication and replication failures.

If traffic on VLAN200 is restricted, clients and other DCs may get an SRV for VLAN200 and attempt to contact the DC on that address, and fail.
Answer:
How should I connect the AD VM to one Virtual Switch for user desktop
segment and to another Virtual Switch for logging segment?

Connect each virtual NIC to each respective virtual switch and assign each virtual NIC a valid ip address in each respective network.


Use a method with parameters in a component?

Question: I am using an API to retrieve the data.
I created a method in my component which allows to retrieve a boolean to know if a user is banned or not:
methods: {
        getBan(id) {
            HTTP.get(`ban/${id}`)
                .then(response => {
                    this.bans = response.data.status;
                })
                .catch(error => {
                    alert(error);
                });
        }
}

In my template I also retrieve all of my users as well as the id of each user:

User id: {{ user.id }}

In my method, I am trying to store the data in an array.
    data() {
        return {
            users: [],
            bans: []
        };

I would like to retrieve the boolean state of my getBan(id) method.
I tried several ways, like putting my getBan(id) method directly in my user loop, like this:
Status ban: {{ getBan(user.id) }}

Obviously it can't work since in my method I store my data in a "Bans" array.
I wanted to know how I could suddenly get the data from my getBan(id) method ?
Comment: What does `bans & users` having? you need to write example with data and What does API response return?
Answer: You should use it something in code, maybe in one of hooks like created or mounted. And afterwards you can just use user to show his props somehow in your template.
data: {
  return {
     user: {}
  }
},
mounted: {
  const { data: user } = await HTTP.get(`user/${id}`)
  this.user = user
}

{{ user.id }}

Comment: Thank you for the answer.

I understood what you did. However I want to know how to fill my ʻid` parameter directly from my template or maybe I'm wrong and have to do this differently?
Answer: You juste have a little error :
You forgot a "s"

{{ getUserById(user.id) }}

{{ getUserById(users.id) }}

Answer: Try this

{{ getUserById(users.id) }}

   ....

   async gerUserById(id) {
      const { data } = await HTTP.get(`user/${id}`)
      this.users = data
      return this.users;
    }

Comment: Thank you for your reply. I get a "[object Promise]".Guess I have to go through a Promise?
Comment: `await HTTP.get(user/${id})` is equal as doing `HTTP.get(user/${id}).then(response =>`, you need to check if `HTTP.get(user/${id})` is returning a promisifyed data or not and change it accordingly
Comment: I am receiving data but it loops endlessly in each user. Do you know why ?
Comment: you need to add more details in the question, to see what's going on, we can't assume what you're doing right. Add more details, then let's see where it's gone wrong
Comment: Still not suffice, you need put the example with data


Are middle eastern flutes generally played with the left hand closer to the mouth?

Question: I've seen different people on the internet play middle eastern flutes like the Ney and Kaval either with their left hand or right hand closer to the mouth. I'm unsure which of these is best for me to learn (also considering the future possibility of learning other flutes as well). Is there one particular way that is "standard" or "best"? Are flute types for both hand positions generally available for sale?
Also, is there a difference in this regard between middle eastern flutes like Ney and Kaval, and Western flutes?
What explains that some people play with left hand on top and others with right hand on top? Is it because they are left- or right-handed respectively? I would guess that whether one is left- or right-handed shouldn't matter much in this regard?
Comment: Does this answer your question? [which hand side hole flute should buy for right handed person?](https://music.stackexchange.com/questions/74832/which-hand-side-hole-flute-should-buy-for-right-handed-person)
Comment: Shouldn't the question as well as the answers use "dominant" and "non-dominant" instead of "right" and "left". I don't know much about flutes, But I think it makes sense to say that there are instruments for lefties too **right**? (like how there are Lefty guitars)
Answer: So far as the sound produced goes, it makes no difference at all what hand - or fingers - you use.
However, if you want to be able to switch rapidly from that class of Middle Eastern straight flutes to general "blockflotes" aka recorders, or to "querflotes," the transverse flutes, and so on, I would strongly recommend using the left hand to work all the upper holes. For Ney models with 5 or more holes on top, use the right hand for the lower holes.  All European instruments -- including double- and single-reed families, work this way.
Comment: I'd just point out that the European standardization of left hand above the right wasn't always the case.  Recorders and reed instruments in the Middle Ages and Renaissance usually had duplicate holes or keys for the lowest note, showing that they were meant for either option.
Answer: Typically middle eastern flutes like neys and kavals are built with the holes in a straight line and they can be played either way. The same generally applies for Indian bansuri flutes, Chines dizis and Irish flutes and whistles. Sometimes these flutes will have an added hole for the fourth finger which is offset, so in these cases the flute will only be playable in one direction (or in the other direction but ignoring the extra hole). When ordering an Indian flute with a seventh hole it's necessary to specify which way the flute will be played.
Western woodwind instruments were played with either hand on top up to the eighteenth century when keys started to be added. The first key on the modern flute was the D-sharp/E-flat key which was on an extra joint and could be rotated for either hand. As more keys were added people finally settled on having the left hand on top and all modern western instruments are built this way. If you think there is any possibility that you might want to play a modern flute in the future you should learn to play this way.
The concept of right- or left-handedness is irrelevant for woodwind instruments because neither hand dominates, although I once saw a "left-handed" keyed Irish flute, and I've heard of "left-handed" recorders.


Partition list based on elements of another list as keys

Question: How can I combine these two lists and use alist as keys and blist as values? What I would like to do is group the values in blist with the corresponding keys. So let's say values 3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5 should have 'Inner OD' as key and the remaining should have a key 'Outter OD': None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3
so basically I would want it to look like this
{'Inner OD': [3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5], 'Outter OD': [None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]})

Any help would be greatly appreciated.
alist = [u'Outter OD', u'Outter OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD',    u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD']

blist =  [3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]

Answer: Something like this:
res = {}
for i in range(len(alist)):
    if alist[i] in res:
        res[alist[i]].append(blist[i])
    else:
        res[alist[i]]=[blist[i]]

returns {'Inner OD': [2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6], 'Outter OD': [3, 4, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]}
Comment: You are welcome! Please mark the answer correct if it is :)
Answer: Yet another solution. It does nothing better than @Tryph's answer (which does nothing better than the @Gábor Erdős's answer) but I think using defaultdict makes the logic a bit cleaner:
from collections import defaultdict

res = defaultdict(list)
for a, b in zip(alist, blist):
    res[a].append(b)

A defaultdict behaves almost the same as a dictionary, so you can probably just use the res above for the rest of your code; but, if you want, you can turn it into a regular dictionary with
res = dict(res)

Answer: It does nothing better than the @Gábor Erdős answer but I think it is a bit clearer:
>>> alist = [u'Outter OD', u'Outter OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD',    u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD',u'Outter OD', u'Outter OD', u'Outter OD']
>>> blist =  [3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]
>>> res = {}
>>> for key, val in zip(alist, blist):
...     if key in res:
...         res[key].append(val)
...     else:
...         res[key] = [val]
...
>>> res
{u'Inner OD': [2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6], u'Outter OD': [3, 4, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]}

more information about the zip builtin function in the doc


Who found the method for matrix inversion and how was the method(s) derived?

Question: I understand how to go about the process for finding an inverse of a square matrix but how did the algorithm come about?
Comment: which algorithm?
Comment: @Chinny84 Adjoint method or Augmented Matrix method
Comment: @Drew: for the "adjugate method" (it isn't the adjoint) cf Wikipedia on [Cramer's rule](https://en.wikipedia.org/wiki/Cramer%27s_rule). The "Augmented Matrix method" doesn't solve anything. You apply Gaussian elimination on the augmented matrix!
Comment: @user251257 I am referring to [this](http://www.mathwords.com/i/inverse_of_a_matrix.htm).
Comment: @Drew: I know that some people call the adjugate the adjoint ... but it is really not common anymore.
Comment: The method was apparently known [by the Chinese in the 2nd century](https://en.wikipedia.org/wiki/Gaussian_elimination#History)
Answer: The concept of matrix inversion comes from the problem of solving a system of linear equations.
The history of the algorithm(s) used to find the solution of a linear system spans over some centuries: from the first method of chinese mathematicians (200 AC), to the works of Gabriel Kramer ( 1750) and Gauss (1811).
Here you can see a brief history.


create a custom field which is allowing multiple values using custom module

Question: I created custom content type and one custom field(text) successfully. But my requirement is, my custom field should allow to add multiple values.
Answer: for unlimited set the cardinality to -1  'cardinality' => -1
example:
function _namecards_namecard_installed_fields() {
  $t = get_t();
  return array(
    'namecards_namecard_phone' => array(
      'field_name' => 'namecards_namecard_phone',
      'label' => $t('Phone'),
      'type' => 'text',
      'cardinality' => -1,
    ),
    'namecards_namecard_fax' => array(
      'field_name' => 'namecards_namecard_fax',
      'label' => $t('Fax'),
      'type' => 'text',
      'cardinality' => -1,
    ),
  );

}

Comment: What if I want to set minimum and maximum constraint on this field. For example user must enter at least 2 values and can maximum add 5 only.
Comment: @PankajJarial that needs to be a separate question. But you would simply do the logic in your form validation. [Take a look at line 83 to 89 here](http://cgit.drupalcode.org/examples/tree/fapi_example/src/Form/SimpleForm.php).


How filter node inside view block by even nid (or odd nid)

Question: I have a view 2 blocks where I show some images and I'm trying to show the images with an even nid in the 1st block and the images with odd nid in the 2nd block
Do you guys have any idea if it's possible? and how?
Comment: Are you custom-coding the block  or do you use views to do it ?
Comment: @IsmaH I'm using views
Comment: Hi. See my version of the regex answer. But I do have a question: are you creating a View of nodes (in other words, are the images part of a node, as in an Image field type?). Or are you creating a View of file entities? If your View is of file entities (not Content entities) then you should filter by File ID (fid), not Node ID (nid)
Comment: Thank you @argiepiano for the help but I solved with some code in the tpl file, I really appreciate your effort :D
Answer: @IsmaH answer is on the right track (use Regex for filtering nid). The problem in his answer is that this filter uses mySQL Regular Expressions - this is why his proposed regex is not working.
This worked for me:
^.*[13579]$
or this for even numbers: ^.*[02468]$
Notice: no slashes at the beginning and end of the expression.
Answer: You should create two blocks.
Let's call them EvenBlock et OddBlock. On each one of them, visit the view editing page (back office).
On "FILTER CRITERIA" Clic on add and type "NID" in the search bar then select "Content: Nid".
Then chose " Regular expression" and write a REGEX to match odd nid (I think "^\d*[13579]$") for the OddBlock and even nid ("^\d*[02468]$") for the EvenBlock.
Then save ^^
Comment: Are you sure about the regex values?
Comment: I think so. If it doesn't work try without the " "
Comment: Tried that too and it didn't work
Comment: https://regex101.com/
You can test the regex is. I think it is working. Otherwise, you can try to put it like #^\d*[13579]$# or /^\d*[13579]$/
Comment: Still not working ?


O que significa o símbolo "$" com parênteses para valores de uma variável

Question: Gostaria de saber o que significa essa expressão que a variável recebe no JavaScript:
var wheight = $(window).height();

Dúvidas

O que seria o símbolo "$" com parênteses? E  o ponto?
O que vem depois do ponto? O que vem dentro do parêntese?
Comment: Ok, obrigado pela ajuda
Comment: [Se pesquisar direitinho vai ver que essa pergunta é duplicada](https://pt.stackoverflow.com/questions/tagged/jquery?tab=Votes)
Comment: [Talvez essa responda](https://pt.stackoverflow.com/questions/37770/qual-a-diferença-entre-this-e-this-e-this)
Answer: Em javascript você pode utilizar o simbolo do "$" como nome (identificador) de variável ou função.
por exemplo :
var $ = 0;

ou
function $(){}

No código postado, você provavelmente esta utilizando a biblioteca jQuery, que atribui o seu código em uma função, que recebe como parâmetro um Elemento html ou um seletor html.
Ao invocar o método ele retorna um objeto, que possui atributos ou funções podendo ser invocadas através do objeto retorna com o ponto.


Is there a way I can queue long running tasks?

Question: Is there a way I can do the following in a unix terminal:

Start a long running process
Add another long running process to start when the previous is done
Repeat step 2 until I have queued the processes I need to have run

Reason I ask is that I have some long running stuff I need to do. I could put all the commands in a simple bash script and just execute that, but the problem is that I am not always sure exactly what I need to run. So if I start the script and then remember another one I should run, I need to hit ^C a bunch of times until all the processes are killed, edit the script and add my new process and then start the whole thing again.
What I specifically am doing right now is to copy a lot of large files on to various external hard drives, and since I don't know exactly which ones I need to copy and to where right now I'd like to start the ones I do know I need to copy, and then add to the queue as I figure out the rest.
Hope that made sense... Is anything like this possible?
Answer: The shell is perfect for that.

Start the first program.
Press Ctrl-z to suspend the program.
Start the next program.
Repeat steps 2 and 3 to add more programs to the queue. All the programs will be in Suspended mode.
Now run the queue like this:
while fg; do :; done

You may not suspend this while loop or exit bash until the queue is done.

If you will need to log out (e.g. the programs will run for many days) then consider running the above steps in screen.
Comment: This works well for two programs, but gets unwieldy fast after that. When you're repeating step 2 to add Program3, you have to press `ctrl-z` twice if Program1 is still running, and after that you end up with stopped jobs which don't run unless you call on them explicitly, or else which run in reverse order if you just keep typing `fg`.
Comment: With the updated version, the `fg` is doing nothing. That's what the "no job control" message is telling you. So that doesn't work so well either.
Comment: You are right again. Thanks! I re-wrote the instructions - now it's bullet proof.
Answer: Not very elegant, but quick and dirty:
process1 &
while kill -0 $! ; do sleep 1; done && process2 &
while kill -0 $! ; do sleep 1; done && process3 &

You would need to substitute actual PIDs for $! if you've run intervening background jobs.
Answer: The answer to your general question is: Absolutely. In the early days of computing, batch processing was the only way to do anything, and even when multi-user interactive systems were invented, batch-processing capability was the norm for large jobs. And it's still commonly done today in medium and large-scale environments using systems like Sun Grid Engine or Torque.
However, that's probably overkill for what you need. You could set up a more lightweight system to run scripts in a serial queue, but I don't think that approach is particularly well-suited to your specific task. Presuming parallel copies to different drives are acceptable, I think I'd attack it like this:

Create directory structure corresponding to your your target drives:
~/copysystem/drive1/
~/copysystem/drive2/
~/copysystem/drive3/
Install Incron.
Set up an incrontab entry for each of these directories, which runs your copy script automatically on IN_MOVED_TO.
Make your script either a) kill any previous instances of the same script when it starts or b) use a mkdir-based lockfile and block until the lock is cleared.

Then, all you need to do is move files to the various ~/copysystem/drive# directories, and they're all copied magically to your destination.
Especially in case of 4a, you probably want to use rsync -aP to copy your files, so that you can restart partial transfers from the middle. (Possibly in combination with --remove-sent-files, if you want to get rid of the originals.)
If you want to skip the complication of using incron, you can still take advantage of making your scripts block on a lock file. That works something like this:
#!/bin/bash
LOCKDIR="/var/run/copysystem/copysystem.lock"

while ! mkdir $LOCKDIR ; do
  echo "waiting for lock"
  sleep 5
done
trap rmdir $LOCKDIR EXIT

rsync commands go here....

This works because mkdir is an atomic operation — if it succeeds, you know the directory didn't exist. That's important, because if you use something like ! -f && touch, there's a race condition. (Same with scanning the process table for rsync commands, or the like.)
Comment: Using that last script of yours: Can I create the script, fix the rsync command, save the script, run the script, edit the script, change the rsync command to something else, rinse and repeat? Like, once I have started a script, can I edit it, or will that mess up the running script?
Comment: You'll get unpredictable results that way. Somewhat surprisingly, shell scripts are read line by line as they're executed. So, don't do that. But that seems like a bad approach anyway. If there's something that's changed (a filename or destination location) pass it in as an argument.
Comment: oh, so does that mean I could actually edit the script while it is running and change where it goes? Like add things or remove things at the end of the script, while it is working on something earlier in the script?
Comment: Well, like I said, you'll get unpredictable results. It's really not meant to work that way.
Answer: If this is something you'll be doing regularly, then its worth setting up some sort of scheduler to manage it for you.
I like the elegance of Aleksandr's solution - and it addresses all the points you originally raised - but I can see it does have limitations.
I've previously used the BSD lpd as a method for queueing jobs - the 'printer driver' is just a shell script so its easy to adapt to different tasks (in my case that meant managing 4 modems for polling data, sending faxes, SMS and other stuff).
Answer: What you want is a non-interactive command queue. Good news! I wrote one for you.
enqueue_cmd:
#!/usr/bin/perl -w

# Enqueue a job

use strict;

use Fcntl qw(:flock);

my $JOB_QUEUE_FILE = '/var/tmp/job_queue';
my $LOCK_TRIES = 5;
my $LOCK_SLEEP = 1;

my $jq;
open $jq, ">> $JOB_QUEUE_FILE" or die "!open $JOB_QUEUE_FILE: $!";

my $locked = 0;

LOCK_ATTEMPT: for (my $lock_tries = 0; $lock_tries < $LOCK_TRIES;
    $lock_tries++)
{
    if (flock $jq, LOCK_EX) {
            $locked = 1;
            last LOCK_ATTEMPT;
    }

    sleep $LOCK_SLEEP;
}

$locked or die "could not lock $JOB_QUEUE_FILE";

for (@ARGV) {
    print $jq "$_\n";
}

close $jq;

dequeue_cmd:
#!/usr/bin/perl -w

# Dequeue a jobs and run them

use strict;

use Fcntl qw(:seek :flock);
use FileHandle;

my $QUEUE_FILE = '/var/tmp/job_queue';
my $OUTPUT_FILE = '/var/tmp/job_out';
my $LOCK_TRIES = 5;
my $LOCK_SLEEP = 1;
my $JOB_SLEEP = 1;

my $locked;

my $jo;
open $jo, ">> $OUTPUT_FILE" or die "!open $OUTPUT_FILE: $!";
$jo->autoflush(1);

my $jq;
open $jq, "+< $QUEUE_FILE" or die "!open $QUEUE_FILE: $!";

my @jobs = ( );
my $job;

JOB: while (1) {

    if (-s $QUEUE_FILE == 0) {
            sleep $JOB_SLEEP;
            next JOB;
    }

    $locked = 0

    LOCK_ATTEMPT: for (my $lock_tries = 0; $lock_tries < $LOCK_TRIES;
            $lock_tries++)
    {
            if (flock $jq, LOCK_EX) {
                    $locked = 1;
                    last LOCK_ATTEMPT;
            }

            sleep $LOCK_SLEEP;
    }
    $locked or die "could not lock $QUEUE_FILE";

    seek $jq, 0, SEEK_SET or die "could not seek to start of file";

    push @jobs, <$jq>;

    truncate $jq, 0 or die "could not truncate $QUEUE_FILE";
    seek $jq, 0, SEEK_SET or die "could not seek to start of $QUEUE_FILE";

    flock $jq, LOCK_UN;

    for $job (@jobs) {
            chomp $job;
            print $jo "## executing $job\n";
            print $jo `$job`;
    }

    sleep $JOB_SLEEP;
}

First, run nohup ./dequeue_cmd &, Then add your commands like so:
./enqueue_cmd "echo 'hello world'" "sleep 5" "date"
./enqueue_cmd "ls /var/tmp"

The output appears in /var/tmp/job_out:
tail -F /var/tmp/job_out
## executing echo 'hello world'
hello world
## executing sleep 5
## executing date
Fri Dec 10 16:35:43 PST 2010
## executing ls /var/tmp
ff
job_out
job_queue
ss


What are the solutions to $ac+bd=1$, for $a$ and $b$, where $a,b,c,d$ are integers and $c$ and $d$ have HCF $1$?

Question: What are the solutions to $ac+bd=1$, for $a$ and $b$, where $a,b,c,d$ are integers, and $c$ and $d$ have HCF $1$?
A few examples:
Give all the solutions for $a$ and $b$ for the following:
$$3a+5b=1 \\
3a+7b=1 \\
4a+5b=1$$
General case:
$ac+bd=1$
I was able to do the above to provide a general formula in terms of $a$ and $b$ in terms of $n$, where $n\in \{1,2,3\ldots \}$ for the first $3$ but struggled with the general case.
I'm presuming there's some sort of way to get $a$ and $b$ in terms of $c$ and $d$, but I'm not sure.
Cheers.
Comment: Given two integers $c,d$, you can compute their gcd using [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm). As a by-product of the algorithm, you will find a pair of $a,b$ such that $\gcd(c,d) = ac+bd$.
Comment: This can help https://en.wikipedia.org/wiki/Diophantine_equation#One_equation
Answer: By the identity of Bezout, (others call it a lemma and even a theorem;French use identity) if $(c,d)=m$ then
$a\mathbb Z+b\mathbb Z= m\mathbb Z$ so in the case of $m=1$ you do have $a\mathbb Z+b\mathbb Z= \mathbb Z$. There are infinitely many solutions.


Android + FATAL EXCEPTION: Timer-0 (Removing ImageView using timer)

Question: In my Android application, I am using timer to show corresponding ImageViews using TIMER.
I got an error
02-27 06:39:33.999: E/AndroidRuntime(1325): FATAL EXCEPTION: Timer-0
02-27 06:39:33.999: E/AndroidRuntime(1325):       android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that  created a view hierarchy can touch its views.
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.requestLayout(View.java:15468)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.requestLayout(View.java:15468)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.requestLayout(View.java:15468)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.requestLayout(View.java:15468)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.requestLayout(View.java:15468)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.setFlags(View.java:8437)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.view.View.setVisibility(View.java:5714)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at android.widget.ImageView.setVisibility(ImageView.java:1161)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at com.SAI.timer.MainActivity$1.run(MainActivity.java:51)
02-27 06:39:33.999: E/AndroidRuntime(1325):     at java.util.Timer$TimerImpl.run(Timer.java:284)

And the code is : (How to Make A Image view disappear here,)
public class MainActivity extends Activity {

MediaPlayer mp;
ImageView firstImageView,secondImageView,thirdImageView,fourthImageView,fullImageView;
Timer t;
TimerTask welcome;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firstImageView = (ImageView)findViewById(R.id.imageView1);
    secondImageView = (ImageView)findViewById(R.id.imageView2);
    thirdImageView = (ImageView)findViewById(R.id.imageView3);
    fourthImageView = (ImageView)findViewById(R.id.imageView4);
    fullImageView = (ImageView)findViewById(R.id.imageView5);

      firstImageView.setOnClickListener (new ClickListener());
      secondImageView.setOnClickListener(new ClickListener());
      thirdImageView.setOnClickListener (new ClickListener());
      fourthImageView.setOnClickListener(new ClickListener());

      mp = MediaPlayer.create(getApplicationContext(), R.raw.yes);

      t = new Timer();
      welcome = new TimerTask(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                fullImageView.setVisibility(View.GONE);

            }
        };

}

class ClickListener implements OnClickListener {
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.imageView1:

            mp.start();

                firstImageView.setVisibility(View.GONE);
                secondImageView.setVisibility(View.GONE);
                thirdImageView.setVisibility(View.GONE);
                fourthImageView.setVisibility(View.GONE);

                fullImageView.setVisibility(View.VISIBLE);
                fullImageView.setImageResource(R.drawable.ic_launcher);

                t.schedule(welcome, 5000);

            break;

        case R.id.imageView2:

            Toast.makeText(getApplicationContext(), "Oh !!! Wrong Yaar", Toast.LENGTH_SHORT).show();

            break;

here I want to Make the "fullImageView" Disappear(View.GONE) after the the media playing(5 Secs) is stopped.
And Return to the previous activity showing remaining Imageviews As in the Above code:-)
Comment: I guess he needs an explanation on how to use timers.
Comment: My hint: get your question in a proper state and try to explain with more then 2 words what you try to achieve...
Comment: Something like [this question](http://stackoverflow.com/questions/1877417/how-to-set-a-timer-in-android), I suppose.
Answer: Use this Handler to do anything after 5000ms
try {
                    new Handler().postDelayed(new Runnable() {
                          @Override
                          public void run() {
                     //Your process to do

                          }
                      }, 5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

Comment: Exactly, This may be a basic question , But its very Useful Thank you for your reply Selvan. Thanks a lot @stackoverflow. You are saving our Lives.


Translate an SQL update query into Drupal language

Question: I need to convert the following query that works against a database table
"UPDATE MYTABLE SET field_temp= %s", UNIX_TIMESTAMP(field);
into Drupal language
db_update('MYTABLE')
      ->fields(array(
          'field_temp' => UNIX_TIMESTAMP('field'), //or strtotime()
         ))
        ->execute();

seems to be not working.
UPDATE
db_update('MYTABLE')
        ->expression('field_temp',  "UNIX_TIMESTAMP('field')"),
        ->execute();

will run into:
PDOException: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:

Some more details:

'field' is datetime format type, field_type is 'int' format type
I am running this script through a hook_update_N
I am debugging it by running update.php
Comment: As a tip for debugging, running this code will have given you a white screen, possibly with an error message depending on your server configuration. If there was no error message you could still check your web server error logs for any errors and will have had an error about a call to undefined function UNIX_TIMESTAMP(), which would give you some direction on where to start looking for the problem.
Comment: What is the incorrect date time value in the error message? It should come right after the part you pasted in here. The more complete the error messages the better. The date should be in the form "YYYY-MM-DD HH:MM:SS" if it is a datetime, which should be acceptable for the UNIX_TIMESTAMP() function. - Is 'field' the name of a database field or is it pseudo code?  If it is a db field it should be UNIX_TIMESTAMP(field), without the quotes. The quotes makes it a string, not a field.
Answer: You need to add an expression():
db_update('MYTABLE')
  ->expression('field_temp', "UNIX_TIMESTAMP(field)")
  ->execute();

Comment: Yeah also, the code in the question is trying to use a php function called UNIX_TIMESTAMP() as opposed to a mysql function. Note the quotes.
Comment: Thank you @Clive, you are right. The info that I am giving is only refered to Select queries.
Comment: If 'field' is another db field it should be minus the internal quotes:   ->expression('field_temp', 'UNIX_TIMESTAMP(field)')
Comment: You should use a dynamic query if you need more complex queries, dynamic query generation or alterability. For simple queries, static queries ("db_query()") is the best choice
Comment: @Enxebre I'm afraid not, you should ALWAYS use a `db_update()` for an update query, unless you physically can't reproduce the query with Drupal's Api. From the `db_query()` docs: _Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively._


How to use "synthetic modes"

Question:
Im having trouble understanding a concept in Persichetti's book 20th century harmony (Page 43) where he introduces new scales he calls synthetic scales.
Just before that he talks about the church modes & how you can build chords, and why you should avoid tritones, etc.... with that same concept how do I apply that to a scale like the octatonic scale? Do I still need to avoid the the Tritones for that scale in order to stay true to the mode?
How do I find the characteristic notes in a scale like the octatonic or super Iocrian? He talks about using tetrachords in order to find the primary chords which I kinda understand, but what confused me was when he talks about testing further possibilities of each scale by scanning Intervallic points between the original and mirrored versions of the scale in order to find "hidden potentialities, cadential patterns, passing textures and outer voice movement."
How do I start this process so I can test and use any scale
Comment: Take the bog standard scales above like the harmonic minor and pentatonic major scales. How do you (already) use them? How do you answer your questions for those scales?
Comment: what I'm asking is how do you find the primary chords for these scales? Should I still avoid the tritone? How do I cadence in a scale like the octatonic scale?
Comment: This is a good question.  I might suspect that chords built on these scales may not be as meaningful as those built on Major and Melodic minor.  The standard approach of stacking 3rds, or every other note, may start to fail.
Comment: Having not read Persichetti's book, I don't understand why you would be avoiding tritones in any scale. Can you elaborate or give a little context?
Comment: And what do you mean by "mirrored version" of a scale?
Comment: You would avoid the tritone because it would take away from the flavour of the mode, each church mode has atleast one diminished chord, so you can omit the 5th or alter one of the notes of the tritone
Comment: A mirrored scale is the same scale but backwards
Answer: I haven't read Persichetti's book so I maybe don't understand the context of your questions well enough to give you a satisfying answer.  That said, I have studied 20C music at length and frequently use all sorts of synthetic scales in my own compositions, so hopefully something I say will be useful.
Terminology might differ by region, but I think in general the term synthetic scale simply refers to any scale that is somehow an artificial construct of the mind, ie invented, rather than having originated "naturally" within a particular music culture (the way the diatonic church modes did in the West). This includes scales which are derived from traditional scales -- eg by altering notes or by combining diatonic tetrachords that don't normally go together -- as well as scales which are invented based on some sort of theoretical principle -- eg symmetrical scales like whole tone or octatonic, which are created by equally dividing the octave into repeated intervalic patterns.
This is a huge and heterogeneous category, so it is difficult to impart general guidelines for how to use them. Which scale are we talking about? What are you trying to achieve musically? Presumably you're not going for functional harmony, but maybe you still want a tonic? In composition, anything goes. The exciting thing about abandoning the rules of common practice music is that you get to make your own set of rules.
To become familiar with a new scale/mode, I suggest noodling in that scale on a polyphonic instrument such as piano or guitar. That way you can explore the harmonic possibilities. If you're interested in having a tonic, then I'd suggest that you drone the tonic while you noodle, because you'll want to hear how each note feels relative to the tonic.  If you're really interested in harmony, I'd suggest being systematic.
How to handle harmony? I don't think I can give any generally applicable guidelines here. Literally any combination of notes is a valid chord. Some will be useful and some won't. In most cases, you're unlikely to find chords which will drive your music the same way dominant quality chords drive common practice music. But you might be able to achieve a pseudo-functional effect by resolving intervals (eg tritones) in traditional ways, only in the context of the new scale.

Do I still need to avoid the the Tritones for that scale in order to stay true to the mode?

I don't see why you would need to avoid tritones in any scale. Both tonal and atonal music and full of tritones. Melodic tritones are typically avoided in common practice music, but they're allowed -- even required -- by its harmony.

How do I find the characteristic notes in a scale

Every note in a scale is important. The idea of some notes being somehow "characteristic" of a scale only makes sense when you consider scales relative to each other.  Take dorian mode for example.  When compared against the natural minor scale its characteristic note is its raised 6th degree, whereas when compared against the major scale its characteristic notes are its lowered 3rd and 7th degrees.  Simply put, distinguishing features depend on context. It might not be the scale degrees themselves which are characteristic, but maybe a particular intervallic pattern.
That's all pretty vague, I know, but it's a broad question. Hopefully you'll find some utility in my answer.
Comment: I understand what your saying, but I'm trying to use these scales while keeping a sense of direction in mind. In his book he explains that the tritone should be avoided because it needs to resolve, just like in a major mode. So in order to keep the sound of the mode the tritone is avoided. So for example if I was in Dorian mode the characteristic note is the raised 6th degree, so therefore the primary chords (or dominant equivalent) are chords with that note because they need to be emphasized. I'm just wondering how to find these primary chords in a synthetic or exotic scale like octatonic
Comment: Ok, I think I understand what you're after. I couldn't get access to this book without paying, but I did find a free summary which was quite detailed. So I now have the context I was missing before. I will edit my answer accordingly when I have time.
Comment: I did a lot of searching and Im starting to understand it now.... if you want I can explain & does this website have an inbox? I can send you a link to the book if you want

How to use “synthetic modes”


Can Lilypond typeset French beaming?

Question: Consider following example:

<code>{
    g'16 d'' e'' d''
}
</code>
Is there a way to obtain the so-called French beaming? Here, vertical stems are not shown in between the beams (examples from here).
Answer: Yes, I'm not sure why I can't find it in the documentation, but French beaming is relatively trivial to achieve with LilyPond:
<code>{
    \override Stem.french-beaming = ##t
    g'16 d'' e'' d''
}
</code>

Can Lilypond typeset French beaming?