Algorithm for two piles of equal heights by removing boxes at top or bottom

Question: Assume you have two piles, each made of N boxes of different heights. You want to remove boxes so as to obtain two piles of equal heights (if possible). You cannot remove a box which is not at the top or the bottom of the pile! One can see for instance that if we remove the red boxes below we obtain two towers of equal heights:

Another way to state this problem is: given two arrays of positive numbers, are there two consecutive sub-sequences (one in each array) whose sums are equal?
This problem looks similar to this one, in which we have an array A of size N and a target t, and we want to find a consecutive sub-sequence of A whose sum is t (equivalently, we have a single pile of boxes and we want to remove boxes at the top and the bottom so as to obtain a pile of height t). This problem can be solved in time O(N). On the other hand, the above-mentioned problem has a trivial O(N^2) solution (see the answers below), but is there also a o(N^2) algorithm (O(N log N) for instance)?
Addendum: The sizes of the boxes are positive integers. They are assumed to be all differents (otherwise the problem can be trivially solved in O(N)). If we denote by H the total size of the two piles, there is a O(H log H) algorithm (see the answers below). Thus, the problem starts to be interesting for H greater than N (an efficient solution for H = N^2 would be a good start ;)
Comment: Can you explain why think this can solved in `O(n)`?
Comment: I assume that the "remove all boxes, 0 = 0" solution is not allowed? :-)
Comment: Is the sum of box heights limited?
Comment: hmm, I would be surprised by a O(n) solution. Something better than the naive O(n^3) would be nice.
Comment: O(n^2) is pretty straightforward (we can just add all different sums to a hash table)
Comment: It can also be done be in `O(H log H)`, where `H` is the sum of heights of boxes, which can be better if the sum of heights is limited by a reasonably small number.
Comment: yes, the true naive algorithm is O(n^2), I don't know why I said O(n^3)... So O(n) would be nice (but I can't explain why it could be possible)
Answer: Let's find all the sums in O(n^2) and add them to a hash table:
for l in [0, n)
    cur_sum = 0
    for r in [l, n)
         cur_sum += a[r]
         hash_table.add(cur_sum)

After that, we need to do the same thing for the second array and check if at least one sum occurs in the hash table.
That's much better than a naive O(n^3) solution.
It's also possible to solve this problem in O(H log H) time, where H is the sum of boxes' heights if all heights are integers, but it's useful only if the total height is limited.
The O(H log H) solution goes like this:
We can find all subarray sums quickly. Let's take a look at what a subarray S sum is. It's a difference of two prefix sums P[r] - P[l] = S. If we add H to both sides of the equation, we obtain P[r] + (H - P[l]) = H + S. So we need to check if there exist two elements in the array P[i] and H - P[i], respectively, that add up to a given value. Let's not just check their existence, but count the number of such pairs. No it looks exactly like a multiplication of two polynomials. The coefficients of the first polynomial are the number of occurrences of a specific prefix sum (C[i] = count(j: P[j] == i)). The second polynomial is essentially the same thing reversed. We can multiply these two polynomials in O(H log H) time using Fourier fast transform (as they both are of degree H). After that, we just need to check the H + i coefficient of the product is non-zero.
Once we know all sums for the first and the second array, we need to check if they have at least one in common.
Comment: Ok, so assume that the total height is around n^2 (to avoid the O(H log H) solution).
Comment: btw, can you explain the O(H log H) solution please
Comment: All the `P[i]`'s must be different (no box of zero height), so you don't need to define `C[i]`. The `H+i` coefficient will be the number of subarrays summing to `i`. Also, you should change `H - P[i]` to `H - P[j]`.
Comment: I believe your O(*H* log *H*) solution requires all of the boxes to have integer-valued heights. That's not an unreasonable assumption, but it's probably worth calling out explicitly.
Comment: @ruakh Yes, that's true.
Comment: The posted algorithm with two loops doesn't look correct as it doesn't take into account all possible sub-arrays denoted by `x`. For example, for 4 elements we've got 10 different sub-arrays as follows: `[x,-,-,-],[-,x-,-],[-,-,x,-],[-,-,-,x],[x,x,-,-],[-,x,x,-],[-,-,x,x],[x,x,x,-],[-,x,x,x],[x,x,x,x]`
Comment: @RZet: It looks right to me. What makes you say that it doesn't take into account all possible sub-arrays? (Of your ten different sub-arrays, which one(s) are you asserting it doesn't take into account?)
Comment: @ruakh Because it only takes into account only sums of the following sub-arrays: `[x,x,x,x],[-,x,x,x],[-,-,x,x],[-,-,-,x]` for `n=4`. Note the inner loop sums all the  elements ahead of the pointer of the outer loop.
Comment: @RZet: Not so. The inner loop takes a *running total* of elements, adding each *partial sum* to the hash-table. (Note the indentation.)
Comment: @ruakh Now agree, the psudo code confused me a bit.
Answer: This sounds similar to the algorithm to find the length of the longest palindrome in a string.  In the palindrome algorithm, the beginning and end of the string is examined to determine if a palindrome exists, if not then the first character of the string is removed from the string so the rest of the string is compared with the result of taking off the last character of the string.
In this case, you are seeking a box that results from taking off the top and bottom of the pile.  If the pile doesn't result in a box of equal size in another pile, then take off the top of the pile and compare the result with taking the bottom of a pile.  The recursive pseudocode could look similar to:
global pile2
global HashTableForPile2  # each value is a box in Pile2
def FindBoxInPile(pile, top, bottom):
    if (top == ReachedBottomInPile or bottom == ReachedTopInPile):
        Stop processing and return False  ## base case
    else:
        # find the box created from the top to the bottom
        for i in range(bottom, top)
            sumPile1 += pile[i]
        # Determine if an identical box is inside both piles.
        # If so, return True; otherwise, recurse.
        # (assuming HashTableForPile2 was calculated earlier)
        if (sumPile1 == HashTableForPile2[sumPile1]):
            return True

    # take top AND bottom off pile
    if (FindBoxInPile(pile1, top-1, bottom+1) == True):
        return True  # A box is inside both piles

    # take top OR bottom off pile and compare result
    elif (FindBoxInPile(pile1, top-1, bottom) == True or
          FindBoxInPile(pile1, top, bottom+1) == True)
        return True  # A box is inside both piles, return True

A dynamic programming solution would run in O(N) time.
Comment: I don't understand your pseudocode. What is supposed to return FindBoxInPile? True if the pile obtained from pile1 by removing the first "bottom" boxes and the last "top" boxes appears in pile2? And what is BoxInside? Why does it take a single parameter?
Comment: I'm sorry I wasn't clear.  I modified the pseudocode to hopefully make it more clear.  My key point is to take the top and bottom off the pile.  If that doesn't result in a box in both piles then take either the top or the bottom off the pile and determine if that results in a box in both piles.  I hope this was helpful to you.
Comment: I'm sorry I still don't understand what you are trying to do. You do recursive calls but I don't see where is the base case. Also I'm not sure we are talking about the same problem... We don't want to find two equal boxes (one in each pile), since usually the sizes of the 2N boxes are all different (ow the problem is too simple). Instead, we want to find two bunches of consecutives boxes (one bunch in each pile) that have the same total height.
Comment: By the way, great question!
Comment: If I understand you correctly, HashTableForPile2 contains all the possible sizes that can be obtained from pile2 by removing boxes at top and bottom. But this requires `O(N^2)` to be built since there are `O(N^2)` ways to remove boxes at top and bottom... And then you compute, one after the other, the sizes that can be obtained from pile1, and you check if they appear in HashTableForPile2. Once again, it requires `O(N^2)` in worst case...


Como instanciar uma variável (para ser primary key) do construtor dentro da tabela?

Question: A pergunta está mal formulada, porém o problema é o seguinte.
Estou trabalhando com BDOR no PostgreSql. Criei duas Types e estou agregando-as na Type animal.
Logo após, usei Herança e criei a tabela mamiferos do tipo animal.
Só que quero usar o atributo nome dentro da type dono_ty como primary key. Quero usar primary key, pois uma mesma pessoa (mesmo cpf) pode cadastrar nas tabelas mamiferos, aves e repteis (vou criar mais duas), daí eu gostaria de fazer um select dessas informações. Como eu poderia resolver?

Ja tentei também as seguintes maneiras:

CREATE TABLE mamiferos OF animal(cpf primary key);
  CREATE TABLE mamiferos OF animal(dono.cpf primary key);
Comment: DÊ uma lida nisso https://pt.stackoverflow.com/q/192911/101
Comment: Eu diria que seria `CREATE TABLE mamiferos OF animal(dono.cpf primary key);`, mas me parece estranho que você queira que cpf seja uma primary key pelo que você diz na introdução "pois uma mesma pessoa (mesmo cpf) pode cadastrar nas tabelas mamiferos, aves e repteis (vou criar mais duas)".
Answer: Heranças são bonitas na teoria, mas são um inferno na prática. Uma excelente alternativa é o uso de uma coluna discriminadora, que na verdade é uma chave estrangeira que aponta para o tipo daquele animal.
Veja como sua ideia pode ser estruturada de outra forma:
CREATE TABLE tb_porte (
  id INTEGER PRIMARY KEY,
  descricao TEXT
);

CREATE TABLE tb_tipo_animal (
  id INTEGER PRIMARY KEY,
  descricao TEXT
);

CREATE TABLE tb_dono (
  id INTEGER PRIMARY KEY,
  nome TEXT
);

CREATE TABLE tb_animal (
  id SERIAL PRIMARY KEY,
  nome TEXT,
  especie TEXT,
  id_porte INTEGER REFERENCES tb_porte (id),
  id_dono INTEGER REFERENCES tb_dono (id),
  id_tipo INTEGER REFERENCES tb_tipo_animal (id), -- Coluna Discriminadora
  dt_consulta DATE,
  diagnostico TEXT
);

Populando tabelas:
-- PORTE DO ANIMAL
INSERT INTO tb_porte (id, descricao) VALUES ( 1, 'PEQUENO');
INSERT INTO tb_porte (id, descricao) VALUES ( 2, 'MEDIO');
INSERT INTO tb_porte (id, descricao) VALUES ( 3, 'GRANDE');

-- TIPO DO ANIMAL
INSERT INTO tb_tipo_animal (id, descricao) VALUES ( 1, 'MAMIFERO');
INSERT INTO tb_tipo_animal (id, descricao) VALUES ( 2, 'AVE');
INSERT INTO tb_tipo_animal (id, descricao) VALUES ( 3, 'REPTIL');

-- DONOS
INSERT INTO tb_dono (id, nome) VALUES ( 1, 'WALT DISNEY');
INSERT INTO tb_dono (id, nome) VALUES ( 2, 'SUPER MARIO');
INSERT INTO tb_dono (id, nome) VALUES ( 3, 'WALTER LANTZ');
INSERT INTO tb_dono (id, nome) VALUES ( 4, 'CEBOLINHA');

-- ANIMAIS
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('MICKEY',      'RATO',        1, 1, 2 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('PATETA',      'CACHORRO',    1, 1, 2 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('DONALD',      'PATO',        1, 2, 2 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('PICA-PAU',    'PASSARO',     3, 2, 1 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('WALLY GATOR', 'JACARE',      3, 3, 3 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('YOSHI',       'DINOSSAURO',  2, 3, 3 );
INSERT INTO tb_animal ( nome, especie, id_dono, id_tipo, id_porte ) VALUES ('BIDU',        'CACHORRO',    4, 1, 1 );

Consulta Exemplo:
SELECT
  a.nome AS no_animal,
  d.nome AS no_dono,
  a.especie AS ds_especie,
  t.descricao AS no_tipo,
  p.descricao AS ds_porte
FROM
  tb_animal AS a
LEFT JOIN
  tb_dono AS d ON (d.id = a.id_dono)
LEFT JOIN
  tb_tipo_animal AS t ON (t.id = a.id_tipo)
LEFT JOIN
  tb_porte AS p ON (p.id = a.id_porte)

Saída:
|   no_animal |      no_dono | ds_especie |  no_tipo | ds_porte |
|-------------|--------------|------------|----------|----------|
|      MICKEY |  WALT DISNEY |       RATO | MAMIFERO |    MEDIO |
|      PATETA |  WALT DISNEY |   CACHORRO | MAMIFERO |    MEDIO |
|      DONALD |  WALT DISNEY |       PATO |      AVE |    MEDIO |
|    PICA-PAU | WALTER LANTZ |    PASSARO |      AVE |  PEQUENO |
| WALLY GATOR | WALTER LANTZ |     JACARE |   REPTIL |   GRANDE |
|       YOSHI |  SUPER MARIO | DINOSSAURO |   REPTIL |   GRANDE |
|        BIDU |    CEBOLINHA |   CACHORRO | MAMIFERO |  PEQUENO |

Veja funcionando no SQLFiddle
Referencia: Herança em banco de dados relacionais


Midpoints of arcs in cyclic quadrilateral

Question: Do you have any hint? I don't want a solution, please. Only some hints.
Let $A,B,C,D$ the four vertex of a cyclic quadrilateral, and $E,H,F,G$ the midpoints of arcs $AB$, $BC$, $CD$ and $DA$. Show that $EF\perp GH$
Comment: Hint: [Proving the Secant Angles in the Circle](https://math.stackexchange.com/questions/1766022/proving-the-secant-angles-in-the-circle).
Comment: Simply search for "far arc near arc"
Answer: Since the angle subtended by an arc at the circle is proportional to the arc, for arcs $\overset{ \huge\frown}{ABC} = 2\overset{ \huge\frown}{EBH}$,
$$\angle ADC = 2\angle EFH$$
And for arcs $\overset{ \huge\frown}{ADC} = 2\overset{ \huge\frown}{GDF}$,
$$\angle ABC = 2\angle GHF$$
Consider the cyclic quadrilateral $ABCD$, its opposite angles add to $180^\circ$,
$$\begin{align*}
\angle ADC + \angle ABC &= 180^\circ\\
\angle EFH + \angle GHF &= 90^\circ
\end{align*}$$
So $\triangle FIH$ is a right-angled triangle, where $I$ is the intersection of $EF$ and $GH$.


What are typical means by which a random number can be generated in an embedded system?

Question: What are typical means by which a random number can be generated in an embedded system? Can you offer advantages and disadvantages for each method, and/or some factors that might make you choose one method over another?
Answer: First, you have to ask a fundamental question: do you need unpredictable random numbers?
For example, cryptography requires unpredictable random numbers. That is, nobody must be able to guess what the next random number will be. This precludes any method that seeds a random number generator from common parameters such as the time: you need a proper source of entropy.
Some applications can live with a non-cryptographic-quality random number generator. For example, if you need to communicate over Ethernet, you need a random number generator for the exponential back-off; statistic randomness is enough for this¹.
Unpredictable RNG
You need an unpredictable RNG whenever an adversary might try to guess your random numbers and do something bad based on that guess. For example, if you're going to generate a cryptographic key, or use many other kinds of cryptographic algorithms, you need an unpredictable RNG.
An unpredictable RNG is made of two parts: an entropy source, and a pseudo-random number generator.
Entropy sources
An entropy source kickstarts the unpredictability. Entropy needs to come from an unpredictable source or a blend of unpredictable sources. The sources don't need to be fully unpredictable, they need to not be fully predictable. Entropy quantifies the amount of unpredictability. Estimating entropy is difficult; look for research papers or evaluations from security professionals.
There are three approaches to generating entropy.

Your device may include some non-deterministic hardware. Some devices include a dedicated hardware RNG based on physical phenomena such as unstable oscillators, thermal noise, etc. Some devices have sensors which capture somewhat unpredictable values, such as the low-order bits of light or sound sensors.
Beware that hardware RNG often have precise usage conditions. Most methods require some time after power-up before their output is truly random. Often environmental factors such as extreme temperatures can affect the randomness. Read the RNG's usage notes very carefully. For cryptographic applications, it is generally recommended to make statistical tests the HRNG's output and refuse to operate if these tests fail.
Never use a hardware RNG directly. The output is rarely fully unpredictable — e.g. each bit may have a 60% probability of being 1, or the probability of two consecutive bits being equal may be only 48%. Use the hardware RNG to seed a PRNG as explained below.
You can preload a random seed during manufacturing and use that afterwards. Entropy doesn't wear off when you use it²: if you have enough entropy to begin with, you'll have enough entropy during the lifetime of your device. The danger with keeping entropy around is that it must remain confidential: if the entropy pool accidentally leaks, it's toast.
If your device has a connection to a trusted third party (e.g. a server of yours, or a master node in a sensor network), it can download entropy from that (over a secure channel).

Pseudo-random number generator
A PRNG, also called deterministic random bit generator (DRBG), is a deterministic algorithm that generates a sequence of random numbers by transforming an internal state. The state must be seeded with sufficient entropy, after which the PRNG can run practically forever. Cryptographic-quality PRNG algorithms are based on cryptographic primitives; always use a vetted algorithm (preferably some well-audited third-party code if available).
The PRNG needs to be seeded with entropy. You can choose to inject entropy once during manufacturing, or at each boot, or periodically, or any combination.
Entropy after a reboot
You need to take care that the device doesn't boot twice in the same RNG state: otherwise an observer can repeat the same sequence of RNG calls after a reset and will know the RNG output the second time round. This is an issue for factory-injected entropy (which by definition is always the same) as well as for entropy derived from sensors (which takes time to accumulate).
If possible, save the RNG state to persistent storage. When the device boots, read the RNG state, apply some transformation to it (e.g. by generating one random word), and save the modified state. After this is done, you can start returning random numbers to applications and system services. That way, the device will boot with a different RNG state each time.
If this is not possible, you ned to be very careful. If your device has factory-injected entropy plus a reliable clock, you can mix the clock value into the RNG state to achieve unicity; however, beware that if your device loses power and the clock restarts from some fixed origin (blinking twelve), you'll be in a repeatable state.
Predictable RNG state after a reset or at the first boot is a common problem with embedded devices (and with servers). For example, a study of RSA public keys showed that many had been generated with insufficient entropy, resulting in many devices generating the same key³.
Statistical RNG
If you can't achieve a cryptographic quality, you can fall back to a less good RNG. You need to be aware that some applications (including a lot of cryptography) will be impossible.
Any RNG relies on a two-part structure: a unique seed (i.e. an entropy source) and a deterministic algorithm based on that seed.
If you can't gather enough entropy, at least gather as much as possible. In particular, make sure that no two devices start from the same state (this can usually be achieved by mixing the serial number into the RNG seed). If at all possible, arrange for the seed not to repeat after a reset.
The only excuse not to use a cryptographic DRBG is if your device doesn't have enough computing power. In that case, you can fall back to faster algorithm that allow observers to guess some numbers based on the RNG's past or future output. The Mersenne twister is a popular choice, but there have been improvements since its invention.
¹  Even this is debatable: with non-crypto-quality random backoff, another device could cause a denial of service by aligning its retransmission time with yours. But there are other ways to cause a DoS, by transmitting more often.
²  Technically, it does, but only at an astronomical scale.
³  Or at least with one factor in common, which is just as bad.
Comment: @Jesko From a strictly cryptographic perspective, it's fine to seed just once. A seed that's good enough to generate one 128-bit key is good enough to generate random data for the lifetime of the device. From a security perspective, that's another matter: it makes the system completely vulnerable to a leak of the RNG state (e.g. through a read vulnerability that would otherwise be recoverable by feeding more entropy into the RNG state). Some security standards require mandatory periodic reseeding.
Comment: Nice answer.  I assume you would seed the PRNG with the hardwware RNG just once, as opposed to seeding for each RN?
Comment: @ScottSeidman Typically you'd seed the PRNG once at each boot. Sometimes more, for defense in depth: if your HRNG didn't have as much entropy as you'd thought, then maybe your device started by generating not-random-enough numbers, and later injecting more entropy improves the randomness. You can inject as much HRNG output as you want without worsening security (if done correctly, mixing in entropy can only increase entropy); the reason why you wouldn't want to call the HRNG all the time is that it would hurt performance a lot.
Comment: I would like to read more about the possibility of preloading a seed during manufacturing. I have a rough idea how this would be done, but can somebody point me in the right direction how this works?
Comment: @Jesko I don't know what there is to explain in general… It varies a lot depending on the manufacturing process. The basic idea would be that when you install the operating system, you don't install an identical copy on all the devices: you put random content in the file containing the RNG state. But that's a highly simplified view of the process in the best of cases and there's a lot of variation.
Comment: @Gilles I have to clarify: I was looking for more information from a cryptographic perspective, not the technical process. For example, is it cryptographically secure to just seed once (at manufacturing) and is there a recommendation on how much entropy this seed should have?
Answer: One way to do it would be to create a Pseudo Random Bit Sequence, just a train of zeros and ones, and read the bottom bits as a number.
PRBS can be generated by tapping bits off a shift register, doing some logic on them, and using that logic to produce the next bit shifted in.  Seed the shift register with any non zero number.  There's a math that tells you which bits you need to tap off of to generate a maximum length sequence (i.e., 2^N-1 numbers for an N-bit shift register).  There are tables out there for 2-tap, 3-tap, and 4-tap implementations.  You can find them if you search on "maximal length shift register sequences" or "linear feedback shift register.

from: http://www.markharvey.info/fpga/lfsr/
HOROWITZ AND HILL gave a great part of a chapter on this.  Most of the math surrounds the nature of the PRBS and not the number you generate with the bit sequence.   There  are some papers out there on the best ways to get a number out of the bit sequence and improving correlation by playing around with masking the bits you use to generate the random number, e.g., Horan and Guinee, Correlation Analysis of Random Number Sequences based on Pseudo Random Binary Sequence Generation, In the Proc. of IEEE ISOC ITW2005 on Coding and Complexity; editor M.J. Dinneen; co-chairs U. Speidel and D. Taylor; pages 82-85
An advantage would be that this can be achieved simply by bitshifting and simple bit logic operations.  A one-liner would do it.  Another advantage is that the math is pretty well understood.  A disadvantage is that this is only pseudorandom, not random.  Also, I don't know much about random numbers, and there might be better ways to do this that I simply don't know about.
How much energy you expend on this would depend on how random you need the number to be.  If I were running a gambling site, and needed random numbers to generate deals, I wouldn't depend on Pseudo Random Bit Sequences.  In those cases, I would probably look into analog noise techniques, maybe Johnson Noise around a big honking resistor or some junction noise on a PN junction, amplify that and sample it.  The advantages of that are that if you get it right, you have a pretty good random number.  The disadvantages are that sometimes you want a pseudorandom number where you can exactly reproduce a sequence by storing a seed.  Also, this uses hardware, which someone must pay for, instead of a line or two of code, which is cheap.  It also uses A/D conversion, which is yet another peripheral to use. Lastly, if you do it wrong -- say make a mistake where 60Hz ends up overwhelming your white noise-- you can get a pretty lousy random number.
Comment: Remembering back now, I think we had to pedal our own generators to power the boards, and if we needed resistors, we had to carve them out of wood with rusty knives.
Comment: Hardware is only half the battle. Hardware RNG tend to have biases, which should be eliminated by passing the output of the HRNG through a software PRNG.
Comment: Anecdotally, for my first final project in my 1987 microprocessor course implemented a PRBS on a motorola 68000 (or maybe 68020) educational board.  We had no compiler or assembler.  I had to figure out the Assembler code, look up the hex values, and type them in with a keyboard.  To edit, I could retype if the new code took up the same amount of memory, or fill with NOPs if it were shorter.  If it were longer, the whole code after that needed to be retyped.  We learned to throw in plenty of NOPs!!
Answer:
What are typical means by which a random number can be generated in an embedded system?

Giles indirectly stated this: it depends on the use.
If you are using the generator to drive a simulation, then all you need is a uniform distribution and a linear congruential generator (LCG) will work fine.
If you need a secure generator, then its a trickier problem. I'm side-stepping what it means to be secure, but from 10,000 feet think "wrap it in a cryptographic transformation", like a SHA-1/HMAC or SHA-512/HMAC. There are others ways, like sampling random events, but they may not be viable.
When you need secure random numbers, some low resource devices are notoriously difficult to work with. See, for example, Mining Your Ps and Qs: Detection of Widespread Weak Keys in Network Devices and Traffic sensor flaw that could allow driver tracking fixed. And a caveat for Linux 3.0 kernel users: the kernel removed a couple of entropy sources, so entropy depletion and starvation might have gotten worse. See Appropriate sources of entropy on LWN.
If you have a secure generator, then your problem becomes getting your hands on a good seed (or seeds over time). One of the better methods I have seen for environments that are constrained is Hedging. Hedging was proposed for Virtual Machines where a program could produce the same sequence after a VM reset.
The idea for hedging is to extract the randomness provided by your peer, and use it to keep you secure generator fit. For example, in the case of TLS, there is a client_random and a server_random. If the device is a server, then it would stir in the client_random. If the device is a client, then it would stir in server_random.
You can find the two papers of interest that address hedging at:

When Good Randomness Goes Bad: Virtual Machine Reset
Vulnerabilities and Hedging Deployed Cryptography
When Virtual is Harder than Real: Resource Allocation Challenges in
Virtual Machine Based IT Environments

Using client_random and a server_random is consistent with Peter Guttman's view on the subject: "mix every entropy source you can get your hands on into your PRNG, including less-than-perfect ones". Gutmann is the author of Engineering Security.
Hedging only solves part of the problem. You will still need to solve other problems, like how to bootstrap the entropy pool, how to regenerate system key pairs when the pool is in a bad state, and how persist the entropy across reboots when there's no filesystem.
Answer: Although it may not be the most complex or sound method, it can be fun to use external stimuli as your seed for random number generation.  Consider using analogue input from a photodiode, or a thermistor. Even random noise from a floating pin could potentially yield some interesting results.


Tensor contraction resulting index order

Question: I am trying to implement tensor contraction in C++ through multidimensional arrays, and while the idea of how to sum over the contraction indices is clear, I am uncertain as to the order in which the dimensions should be arranged in the resulting tensor. Assume I have tensors $A$ and $B$ with indices $\alpha_1...\alpha_N$ and $\beta_1...\beta_M$, and assume that $\alpha_{i_1},...,\alpha_{i_p}$ are upper indices, and $\beta_{j_1},...,\beta_{j_p}$ are lower indices, such that the dimension matches between those, and I pair them in that order to sum over those. How would the dimensions in the resulting tensor be arranged? Do I get a tensor with indices arranged as:
$$C_{\alpha_1...\alpha_{i_1-1}\alpha_{i_1+1}...\alpha_{i_p-1}\alpha_{i_p+1}...\alpha_{i_N}\beta_1...\beta_{j_1-1}\beta_{j_1+1}...\beta_{j_p-1}\beta_{j_p+1}...\beta_{M}}$$
I was reading through the following reference: http://www.cs.cornell.edu/cv/SummerSchool/Contractions.pdf
However the way indices are arranged there in the resulting tensor is:
$$C(i,j,p,q) = \sum_{k}\sum_{s}A(i,s,p,k)B(s,j,k,q)$$
Which doesn't seem to match the above.
Comment: In mathematics there is no defined order in tensor product or contraction. Index order matters when 1) you want tensor to match some particular definition 2) you want to highlight the symmetry of the result, for example, $A_{ikjl}$ makes sense better if there is symmetry on $ik$ and $jl$, than $ij$ and $kl$. So I would leave this to user (see https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html): `multiply(A, B, "ispk,sjkq->ijpq")`
Comment: There is no convention. Tensors are loved because the order of terms doesn't matter and all the syntax information is in indices, so one can use the order of terms to convey some semantic information (like we do with simple multiplication). However, if you insist on fixed order, why use indices at all? You can define tensor product (append dimensions as they are in order). And then contraction (cross out dimensions). So $C_{ijkl}=A_{ipjq}B_{pkql}$ is `Tcontract(Tproduct(A,B),2,5,4,7)`
Comment: @VasilyMitch Thank you for clarifying this. What if I want to generalize what we have for matrices, is there a convention regarding the ordering that will make more sense with respect to other mathematical objects?
Comment: @VasilyMitch You can formulate your comments as an answer so I can accept it as the answer to my question if you want.
Answer: In mathematics there is no defined order in tensor product or contraction. Index order matters when 1) you want tensor to match some particular definition 2) you want to highlight the symmetry of the result, for example, $A_{ikjl}$ makes sense better if there is symmetry on $ik$ and $jl$, than $ij$ and $kl$. So I would leave this to user (see numpy.einsum ):
multiply(A, B, "ispk,sjkq->ijpq")
Shortly, there is no convention. Tensors are loved because the order of terms doesn't matter and all the syntax information is in indices, so one can use the order of terms to convey some semantic information (like we do with simple multiplication). However, if you insist on fixed order, why use indices at all? You can define tensor product (append dimensions as they are in order) and contraction (cross out dimensions). So $C_{ijkl}=A_{ipjq}B_{pkql}$ is
Tcontract(Tproduct(A,B),2,5,4,7)


Voltar para mesma página depois da crud de uma modal

Question: Tenho uma pagina com uma datatables, no evento select desta tabela abra uma modal passando o id do registro selecionado para modal, na modal eu faço a exclusão deste registro, logo após eu fecho a modal e redireciono para a pagina que estava anteriormente, porem a tabela fica vazia, ou seja, não atualizou com os novos registros.
Tabela:
JavaScript
$('#TabEvolucao').DataTable({
        "processing" : true,
        "select": true      ,
        "ajax" : {
            "type" : "POST",
            "url" : "estrutura/tabevolucao.php",
            dataSrc : '',
            "data" : function(d){
                d.idcliente = vlsidcliente;
                d.acao = "select";
                }
        },
        "columns" : [   {"data" : "id"},
                        {"data" : "data"},
                        {"data" : "descricao"},
                        {"data" : "nome"},
                        {"data" : "ativo"}
                    ],
        "aaSorting": [[1,'asc']],
         "iDisplayLength": 7,
         "bFilter": true,
         "aaSorting": [[1,'asc']],
        "language": {
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página ",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
                },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }

    });

Enviando dados do registro selecionado para modal:
JavaScript
var table = $('#TabEvolucao').DataTable();
    table
        .on( 'select', function ( e, dt, type, indexes ) {
            var rowData = table.rows( indexes ).data().toArray();
            //events.prepend( '
'+type+' selection - '+JSON.stringify( rowData )+'
' );
            //var dt = JSON.stringify( rowData );

            var id = rowData["0"].id;

            document.getElementById('idevolucao').value = id;

            $('#modalVWEVOLUCAO').data('id', id).modal('show');

        } )

Botão excluir na MODAL
JavaScript
$('#btnUpdateYesEVO').click(function () {
        var id = $('#myModalUpdateEVO').data('id');
        var idevolucao = document.getElementById('idevolucao').value;
        var descricaoevolucao = document.getElementById('descricaoevolucao').value;
        var boatao = document.getElementById('acaobotaoevolucao').value;
        var iduser=$('#iduser').val();

        if(boatao == 'DESATIVAR'){

            $.post('estrutura/excluirevolucao.php',{
                    acao:'delete',
                    id:id,
                    user_id:iduser
                    },function(r) {
                       var m = jQuery.parseJSON(r);
                       if (m.success) {

                        $('#myModalUpdateEVO').modal('hide');
                        toastr["success"](m.msg);
                        $("#listevolucao").load(location.href + " #listevolucao>", "");//<<<<<< esta aqui o problema

                       } else {
                        toastr["error"](m.msg);
                        $('#myModalUpdateEVO').modal('hide');

                       }
                    });
        }

Comment: Confundir Java com Javascript é a mesma coisa que confundir cachorro com cachorro-quente. A sua pergunta é sobre Javascript, e não sobre Java.
Comment: Tudo bem Victor, consegue ajudar nessa pergunta?
Comment: Descobri, basta atualizar a tabela.. $('#TabEvolucao').DataTable().ajax.reload();
Comment: Então poste a sua solução como resposta.
Answer: segue solução:
$('#TabEvolucao').DataTable().ajax.reload();

Como ficou meu código:
$('#btnaddEVO').click(function () {
        var id = $('#modalADDEVO').data('id');
        var adddataevolucao = $('#adddataevolucao').val();
        var adddescricaoevolucao =$('#adddescricaoevolucao').val();
        var iduser=$('#iduser').val();

        $.post('estrutura/adicionaevolucao.php',{
                    acao:'insert',
                    id:id,
                    user_id:iduser,
                    data:adddataevolucao,
                    descricao:adddescricaoevolucao
                    },function(r) {
                       var m = jQuery.parseJSON(r);
                       if (m.success) {

                        $('#modalADDEVO').modal('hide');
                        toastr["success"](m.msg);
                        $('#TabEvolucao').DataTable().ajax.reload();

                       } else {
                        toastr["error"](m.msg);
                        $('#modalADDEVO').modal('hide');

                       }
                    });

    });

Comment: Lembre-se só que se vc inicializar o DataTable novamente ele recria a lista e isso pode perder alguma propriedade que vc colocou, por exemplo, de ordenação na inicializacao.


Facebook's Flow type for a nested object with ids

Question: I couldn't find in the docs how to make a type for a nested object with
ids such as:
const form = {
    title: string,
    fields: {
        f1: {
            id: string,
            title: string
            ...
        },
        f2: {
            id: string,
            title: string
            ...
        }
    }
};

If the property "fields" was an array I would do something like:
type form = {
    title: string,
    fields: Array<Field>
}

So I am looking for something like:
type form = {
    title: string,
    fields: ObjectOf<string: Field>
}

The last code blocks's syntax is of course false and is used to illustrate what I'm aiming for. How can I describe a nested object with ids?
Answer: Have you tried using Objects as maps?
That would be
type Form = {
  title: string,
  fields: {[string]: Field}
}

Hope it helps!
Answer: This seems to do what you need:
/* @flow */

type Field = {
  id: string,
  name: string
}

type Fields = {
  [key: string]: Field
}

type Form = {
    title: string,
    fields: Fields,
}


Substituir duplo for por duplo lapply

Question: Pessoal estou tentando substituir meu código que possui duplo for por um com duplo lapply com objetivo de otimizar o programa já que o r trabalha de forma matricial, esta funcional desta forma:
k<-1
for(i in 1:nrow(tab1)){
   for(j in 1:nrow(tab2)){

      tab3$col1[k]<-tab1$col1[i]
      tab3$col2[k]<-tab2$col3[j]
      k<-k+1

    }

  }

Gostaria que ficasse assim, mas não sei como fazer podem ajudar?Obrigado
lapply(1:nrow(tab1),fuction(i){
  lapply(1:nrow(tab2), function(j){

   ??????????

  })
})

Comment: Acho em python não vai ficar muito mais rápido também. Assim como no R, loops são ineficientes no python. A melhor solução seria fazer em C ou C++... Da uma olhada no pacote RCpp.
Comment: Teoricamente, trocar pelo lapply não vai fazer diferença nenhuma. O R só é mais rápido se vc usar funções vetorizadas, escritas em C/C++ caso contrário o for e os outros são equivalentes.
Comment: Porque não `tab3$col1 <- tab1$col1` e `tab3$col2 <- tab2$col3`? Note que como o seu código está, a instrução `k <- k + 1` vai executar `nrow(tab1)*nrow(tab2)` vezes. É isso que quer?
Comment: O código possui várias estruturas condicionais que quando satisfeitas gravam registros diferentes em cada linha, mas como o amigo disse que a troca do for pelo lapply não faz diferença vou procurar outra solução porque do jeito que está demora muito a ler as tabelas acho que vou partir para uma solução em PYTHON. Obrigado
Comment: Puts no phyton também! Valeu Daniel vou partir pro C então
Answer: Olá!
Na verdade os apply's podem ser até mais lentos que loops, se no loop você tomar o cuidado de pré-alocar seu vetor.
Quanto ao seu problema, parece que você quer fazer todas as combinações de
tab1$col1 e tab2$col3.
Sugiro usar expand.grid():
tab3 <- expand.grid(col1 = tab1$col1, col2 = tab2$col3)

A ordem será diferente, mas isso se resolve fácil com order().
Um abraço!

Substituir duplo for por duplo lapply


How can we delete a particular screen view from Google analytics screen view list?

Question: I integrated google analytics to my android app. By mistake I sent some wrong screen views. Is there any way to delete that screen view from Google Analytics? Can anyone please help?
Comment: No way (other than deleting the view/property/account which of course will also delete any other data). Easiest way is to build a segment that excludes those screen views.
Comment: you can delete the Activity screen from your app manually, but from Google Analytics you are not allowed to do that rather than what @Eike said.
Answer: I can't think of a way to delete the screen views. But you can use filters in either google analytics dashboard or in the API you use to fetch the data.


Default gateway config in FlexFabric 5700

Question: We've taken delivery of a brand new set of shiny FlexFabric 5700 10GbE switches. I've read through the config and setup guides provided by HP and they're great, except that they outright lie about configuring a default gateway for the management interface of the switch.
Their recommendation is to use the following steps:
system-view
interface m-eth0
ip address 10.0.0.2 24
ip gateway 10.0.0.1

For starters, m-eth0 doesn't exist. So we replace that with the correct interface name: M-GigabitEthernet0/0/0
We try that.
Unfortunately, the ip command has no gateway section. It only has address and irdp.
Has anyone run into this issue and if so, where can I find the default gateway settings for the management interface for these things?
Answer: I couldn't find this anywhere else so if hopefully this helps somebody
The command is:
ip route static 0.0.0.0 0.0.0.0 x.x.x.x (IP of default gateway)
Answer: Thanks for this, saved me some time.  Ended up with this quick setup for basic telnet access (prior to setting up SSH, VLANs and all that responsible stuff ;-P
Assign an IPv4 address to the management Ethernet port:

{sysname} system-view
[Sysname] interface M-GigabitEthernet0/0/0
[Sysname-m-gigabitethernet0/0/0] ip address x.x.x.x 24
[Sysname-m-gigabitethernet0/0/0} quit
[Sysname] ip route-static 0.0.0.0 0.0.0.0 y.y.y.y

Note: Fundamentals Configuration Guide has incorrect commands:

[boot] interface m-eth0
[boot-m-eth0] ip gateway 192.168.2.2

Allow and configure Telnet:

 system-view
[Sysname] telnet server enable
[sysname] aaa session-limit telnet 1
[Sysname] line class vty
[Sysname-line-class-vty] user-role network-admin
[Sysname-line-class-vty] authentication-mode password
[Sysname-line-class-vty] set authentication password simple zzz
[Sysname-line-class-vty] idle-timeout 30
[Sysname-line-class-vty] quit
[Sysname] save safely
Answer: As an aside, everything above will assign an IP to a M-Gigabit or M-TenGigabit interface.  However, if you're looking to manage the switch, you probably want to specify the IP address on your primary vLAN. So...

[HP] system-view
[HP] interface vlan-interface 1
[HP-Vlan-interface1] ip address X.X.X.X 24

This set off commands will set the IP address for VLAN 1, which is the primary vLAN on the box, allowing any connected port access to the HTTP interface.
Answer: Note that the M-eth0 interface referred to in the documentation appears only when the switch boots to "emergency shell" mode.  This happens when the switch can't find a usable system file.
The documentation is not wrong as this is always mentioned in the "Emergency shell commands" section.  But there is a lack of information about the other M-Gigabitethernet0/0/0 interface and how it fits into the overall routing of the different switches.
Comment: Agreed - the official docs are a bit lacking in that department.


Using a node reference in Drupal 7, is there a way to tell what the parent node is?

Question: I have a content type called Movie, it has a node reference to a content type called LeadActor. The LeadActor content type can have node references of its own back to several different Movies nodes.
When I have a page that displays the full content of a Movie, I've changed the node template to have a link to the LeadActor.
When a user uses the link to LeadActor from a Movie page, is there anyway for me to know what Movie the user came from when I'm on the LeadActor page?
I've thought about adding an extra argument to the LeadActor page link - the node id to the Movie, but I was wondering if there might be a cleaner way to handle this.
I'm using Drupal 7 and the node reference (references) module. I've also tried using the corresponding node references module - but so far I haven't been able to understand if this will work.
Thanks for your help.
Comment: Your question is more likely to get answered if you accept the answers that helped you on your previous questions. See the [faq#howtoask] for more information on how to accept answers.
Answer: Reading the text of your question, it looks like you don't necessarily need to know what the parent is but more where the visitor is coming from (and if it is a movie which one).
A possible solution, as you mentioned, would be to add some parameters to the URL.  A simpler option might be just a tiny bit 'o javascript.

Then use the referrer (previously browsed URL) and compare it against the list of movie URLs via JQuery.  If one matches, add a css class to style the link as an indicator.

Where

duck

duck

goose

Answer: There is a module called reference from URL it can help
But I think you need only to know which album so send nid as an argument with the link
"Change the node tpl of albums to add nid to the link"
then in artist check args() to get nid


Make All Columns in HTML Table Editable Except One

Question: I have an HTML table that has an edit button. When the edit button is clicked, it allows the row to become editable. Right now the entire row is editable, however, I am wanting the MR_ID row to NOT BE EDITABLE. How can I do this? I tried something in my code but it doesn't seem to be working.
If I need to provide any more code, please let me know and I will do so.
This is the beginning of my if statement where I believe the problem should be:
  $(document).on("click", "#html_master .edit", function () {
  var $this = $(this);
  var tds = $this.closest('tr').find('td').filter(function () {
    return $(this).find('.edit').length === 0;
  });
  if ($this.val() === 'Edit') {
    $this.val('Save');
   if($this.id != '.mr_id'){
        tds.prop('contenteditable', true);
   }
}

HTML/PHP for the table:
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows){
    ?>
    <tr id="<?php echo intval ($rows['MR_ID'])?>">
        <td class="mr_id" id="<?php echo intval ($rows['MR_ID'])?>" contenteditable="false"><?php echo intval ($rows['MR_ID'])?>
        <td class="mr_name" id="mr_name-<?php echo intval ($rows['MR_ID'])?>" name="field" contenteditable="false"><?php echo $rows['MR_Name']?>
        <td class="buyer_id" id="buy_id<?php echo intval ($rows['MR_ID'])?>" contenteditable="false"><?php echo $rows['Buyer_ID']?>
        <td class="poc_n" id="poc_n-<?php echo intval ($rows['MR_ID'])?>" contenteditable="false"><?php echo $rows['MR_POC_N']?>
        <td class="poc_e" id="poc_e-<?php echo intval ($rows['MR_ID'])?>" contenteditable="false"><?php echo $rows['MR_POC_E']?>
        <td class="poc_p" id="poc_p-<?php echo intval ($rows['MR_ID'])?>" contenteditable="false"><?php echo $rows['MR_POC_P']?>
        <input type="button" class="edit" name="edit" value="Edit">

 <?php
  }
 ?>

Comment: what is `$this`.  If it is a jquery object, then you can't get id by doing `.id` also looks like you compare against a class, should it not be just `'mr_id'` (with no leading dot)
Comment: I added some extra code to the javascript to help you out with what `$this` is
Comment: When you click edit, are you wanting every `td` but `mr_id` to be editable?
Comment: Yes that is correct
Answer: You can put that right into your initial find statement.
var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
  return $(this).find('.edit').length === 0;
})

Another option, if the edit cell is always last, is to bundle that into the not statement
var tds = $this.closest('tr').find('td').not('.mr_id, :last-child')

Answer: Just extend your filter to not include the mr_id column:
$(document).on("click", "#html_master .edit", function() {
  var $this = $(this);

  var tds = $this.closest('tr').children().filter(function() {
    var $thisTd = $(this);
    return $thisTd.find('.edit').length === 0 && !$thisTd.hasClass('mr_id');
  });

  if ($this.val() === 'Edit') {
    $this.val('Save');
    tds.prop('contenteditable', true);
  }
});

Comment: If you're already using jQuery, there's no need to do all that. A simple `.not` is a lot cleaner
Comment: @jmcgriz, he is already using a filter - may as well extend it - your tds are including the .edit column as well
Comment: I was just building onto what he already has, not replacing it. I'll edit for clarity


BIM 360 Rename Folder API

Question: In BIM 360 folders have a 'name' and a 'display name'. The folder patch endpoint only supports changing the 'name'. It should also provide a means to change 'display name' because that is what applications will use. We discovered this when testing the rename functionality in our application. When getting the folder the 'name' was being returned with the new value, but the 'display name' was the original value.
Comment: I can reproduce this issue. Please bear with me checking with engineer team.
Answer: sorry for late reply. Our engineer team told me the API help doc incorrectly puts the description for displayName limitation in the response. PATCH folder should use name instead. I have asked engineer team to fix the document to put the desc to Request. Apology for the issue.

BIM 360 Rename Folder API


CMake: correct way to have differing link flags?

Question: I have both C++ and C files in my project.  I have separate and different compile flags settings for each, using CMAKE_CXX_FLAGS and CMAKE_C_FLAGS.  How do I create different linker flags for each?
It would have been nice if something like CMAKE_CXX_EXE_LINKER_FLAGS and CMAKE_C_EXE_LINKER_FLAGS existed, but there is only CMAKE_EXE_LINKER_FLAGS.
Answer: There are
CMAKE_CXX_LINK_EXECUTABLE
CMAKE_C_LINK_EXECUTABLE

that look like they can solve your problems.
Keep in mind that you are getting into compiler and platform specific stuff, it's up to you to put the right combinations of conditional to select the right set of macros, if you need a multiplatform, multicompiler, project.

Build rules
Answer: It turns out in CMake version 3.0.2 at least, there are the following variables, CMAKE_C_LINK_FLAGS and CMAKE_CXX_LINK_FLAGS, used in ./share/cmake-3.0/Modules/CMakeCXXInformation.cmake.
They were not documented anywhere I had looked, and are not present in the generated files or cache, hence why I didn't find them.  But they appear to do what I need.
Hopefully, CMake will continue to support them, and not remove them suddenly without warning, as is sometimes the case with undocumented features.


How do we move a mistakenly configured EC2 instance from dedicated tenancy back to shared?

Question: A friend accidentally configured an EC2 instance to use "dedicated" tenancy, not realizing that it didn't actually provide a dedicated server and was surprised it cost an additional $2/hour, so we're trying to untangle this now. We want to just change it over to use the default "shared" tenancy and not spend $1400/month for no reason.
The problem is that this is apparently a one-way operation. According to the AWS EC2 user guide, You can shut down an instance change its "shared" tenancy to "dedicated", but you can't undo it once it's launched:

After you launch an instance, there are some limitations to changing its tenancy.

You cannot change the tenancy of an instance from default to dedicated or host after you've launched it.
You cannot change the tenancy of an instance from dedicated or host to default after you've launched it.

It's true, the console doesn't give you the option to change tenancy back to "default". If you shut down the instance and use ec2 modify-instance-placement from the CLI like this:
aws ec2 modify-instance-placement \
    --instance-id i-0e6ddf6187EXAMPLE \
    --tenancy default

It causes the error: "An error occurred (InvalidTenancy) when calling the ModifyInstancePlacement operation: Invalid value 'default' for Tenancy."
Another approach is to launch a new instance with the correct tenancy, but using some kind of a snapshot of the current one and re-using the old one's EBS volumes. I could not for the life of me figure out how to do this in the AWS console, and I'm not sure the script I've cobbled together does the job.
In any case, we want to undo this mistaken configuration and end up with a running instance that is exactly the same as the current one, except with shared (default) tenancy. The instance is backed up, it is running Windows Server 2012 and SQL Server, has one public elastic IP, two EBS volumes and short downtime is allowable. What's the best way to get it done quickly and safely? Thanks for your advice in advance.
Answer: Create a snapshot of the volume, create an AMI from that, and then launch a new instance. Documentation is here for Linux, here for Windows. I would copy out the steps but it's fairly pointless duplication, given AWS documentation is well maintained and regularly updated.
Comment: Thanks, reading now. Not sure if it matters this is Windows Server 2012, I noticed your link went to the Linux guide and there didn't seem to be a corresponding page in the Windows side: https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/AMIs.html I've edited my question with this clarification.
Comment: The concept is the same - create AMI, create new server. I've added a link.
Answer: 2022 Update:
When the instance is in stopped state. Tenancy change via CLI using the following command works.
    aws ec2 modify-instance-placement \
    --instance-id i-0e6ddf6187EXAMPLE \
    --tenancy default


Elevation is not shown on toolbar in pre-lollipop devices

Question: I want to show the same elevation effect on my toobar on a KitKat device as seen on a Lollipop device. Below are screenshots for both the KitKat and Lollipop devices. I have referred to this link but my problem is not solved yet.
Lollipop Device:

Kitkat Device:

ContentMain.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.global.market.checkinternet.MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        android:background="#3F51B5"
        style="@style/MyCustomTabLayout"
        app:tabTextColor="#ffffff"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

</LinearLayout>

app_bar_main.xml
    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:fitsSystemWindows="true"
    tools:context="com.global.market.MainActivity">

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

Comment: Elevation is not available below lollipop
Answer: As mentioned, elevation is not available below lollipop devices but, there are few alternative ways for doing that.
I've personally tried everything and none worked but could managed it by adding a layout-v19 folder in res folder of project. So, it will be a specific API-19 layout. There, you can add a view under Toolbar-AppbarLayout (depends on your design) with 4dp height or any other methods as following links:
https://github.com/vipulasri/Toolbar-Elevation-Pre-Lollipop
And this: https://mobikul.com/show-shadow-toolbar-api-21/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar" />
    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <View
            android:id="@+id/shadow_view"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="@drawable/dropshadow" />

    </FrameLayout>

</LinearLayout>

dropshadow.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient android:startColor="@android:color/transparent"
        android:endColor="#60555555"
        android:angle="90"/>

</shape>

And in java-kotlin side, check if it is API-19, then inflate the layout there:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        v = inflator.inflate(R.layout.item_showdetail_asset_kitkat, this);
    } else {
        v = inflator.inflate(R.layout.item_showdetail_asset, this);
    }

Hope this helps.


Picking priors in Bayesian MCMC linear regression

Question: Let me preface this by saying that I am an applied statistician teaching myself Bayesian regression.  If we can do this without Greek letters that would be great.
Suppose I am modeling a continuous outcome on some predictor. We'll assume a jeffrey's prior for the variance.  Now I need a prior for my predictor and the constant.  Essentially what I am doing is setting up a distribution that the values for the parameters (the coefficients for the constant and predictor) will be drawn from, correct?
Assuming I want informative priors, my immediate inclination is to go with a normal prior.  I set the mean to my "best guess" of what the effect of the predictor ought to be and then set the variance.  I like the normal distribution because it is essentially favoring values near my guess while discounting those far from it (i.e. the tails) and discounting them in a symmetrical way.  I'm also specifically wondering if I can make use of the standard deviation to characterize my confidence in my guess.  An example will illustrate.
I get that larger variances mean less weight assigned to the prior belief.  However, I am curious if I can interpret this in terms of standard deviations.  For example, if I believe the effect will be 5, I set the mean at 5.  Let's say I'm 95% confident that the effect will be between 15 and -5.  This would call for a standard deviation of 5 so I'd set the variance at 25.  Is this a proper way to describe my confidence in the prior?
As another example, if I were absolutely positive that the effect was going to be somewhere between -10 and 20 I would use a uniform prior ranging from -10 - 20, correct?  Am I also correct in assuming that all this is true regardless of the actual distribution of the independent variable (i.e. it could be continuous or dichotomous)?
Answer: Basically, yes. Normal priors are common and your approach to selecting the s.d./variance is perfectly reasonable. I'd recommend reading any of Andrew Gelman's stuff about prior distributions. His book Bayesian Data Analysis is a very good and approachable resource for (almost) all things Bayesian.

Essentially what I am doing is setting up a distribution that the values for the parameters (the coefficients for the constant and predictor) will be drawn from, correct?

In a sense, yes, but I don't think this is the best way to think of priors. Priors are there to dampen/accentuate the likelihood in certain regions of parameter space, i.e. to weight the likelihood in some way.
If we choose improper uniform priors (i.e. completely uninformative), the posterior distribution is just a normalised likelihood, which is very sensitive to the data. The mode of this distribution is the estimate you would get from running any common linear regression procedure (lm in R for example).
This is fine if we have complete faith in our data -- we're sure it reflects the population distribution pretty well.
If we have reason to be suspicious of the data, it makes sense to include a prior. The effect of this is that if the data happen to result in lots of likelihood at some unreasonable parameter value, our prior should cancel it out by attaching a very small weight to that value; remember we multiply the prior and the likelihood (pointwise) to get the posterior distribution.
So you aren't really drawing parameter values from the prior, rather you're expressing a restriction on the parameter values you're willing to accept as reasonable by weighting the likelihood. As a very loose approximation, we're just modifying the likelihood before we run lm to find its maximum to make sure our estimates don't come out as being unreasonable/at odds with our prior understanding of the process.


Olympic Diving: how is the difficulty of a dive decided?

Question: Shi Tingmao's fourth dive in the 2016 Rio Olympic 3m final was "Forward 3½ Somersaults" with a difficulty coefficient of 3.1.
How are such values determined?
In general, is the difficulty coefficient fixed or variable over time?
Answer: The values come from the FINA Table of Degrees of Difficulty*
The tables are a matrix that combine the direction and number of any spins and twists, with the shape that is held during the dive.

As you can see, a Forward 3½ Somersault combined with a Pike results in a 3.1 difficulty coefficient.
* The link provided is for the 1m and 3m springboards. For 5m, 7.5m and 10m platform diving see here
Comment: Up for you. [Here](http://http://www.fina.org/content/appendix-1-fina-degree-difficulty-formula-and-components-springboard) is it possible to view the matrix quoted in ImClary answer


Como selecionar na tabela de usuário os usuários que estejam com o campo STATUS =1?

Question: Tenho uma tabela chamada USUARIOS com os campos NOME, STATUS. Suponhamos que eu tenha 10 usuários cadastrados.
Como eu posso checar se os 10 usuários possuem o STATUS = 1 e caso afirmativo, exibe na tela um (OK).
Eu sei que tem que fazer um SELECT, até aqui tranquilo, mas qual a melhor forma de se fazer isso sem usar array ou loop?
Answer: Uma solução seria selecionar todos os usuários com o valor 1 na coluna STATUS e fazer a contagem dos mesmos.
$con=mysqli_connect("localhost","utilizador","password","base_dados");
if (mysqli_connect_errno())
{
    echo "Erro na coneção á BDL: " . mysqli_connect_error();
}

// Executa a query
mysqli_query($con,"SELECT status FROM usuarios where status = 1;");

$n_utilizadores = mysqli_affected_rows($con);

echo "Existem " . $n_utilizadores. " com STATUS = 1";

if ($n_utilizadores == 10)
{
    echo "OK";
}

Poderá também inverter a query e perguntar á BD se existe algum utilizador com o campo STATUS = 0, caso exista 1 ou mais retorna erro caso contrário retorna OK
Answer: Bom cara acho que pra fazer isso a melhor forma é usar um loop com foreach, onde te trara todas as informações buscadas no banco com o select permitindo com que você consiga manipular os dados da melhor forma que te agrade.
//Exemplo da variável que armazena sua busca com o select
  $armezanaValoresDoSelect= "sua busca no banco";

    foreach($armazenaValoresDoSelect as $NewValues){
         //faça uma validação onde se a $NewValues['status'] == 1 echo "ok";
    }

O foreach fará um loop enquanto houver dados a ser manipulados. Este é o melhor jeito que eu conheço para manipular dados de bancos, gerando loopings. Espero ter a ajudado!
Answer: foreach é uma boa opção, sem loop não será possível, a não ser que esteja usando Bootstrap, daí talvez hajam outras opções.
Comment: Eu quero fazer algo assim: Se exibir 10 registros retornados pelos SELECT, verifica se os 10 possuem o 1 no campo STATUS, existe algum exemplo ?
Comment: Cara se você não usa bootstrap vai ter que ser por loop. Vou fazer um exemplo em for.
Coloca tudo num array e faz o for, impossível outra maneira.
Comment: Pensei aqui, como você tem várias informações para cada usuário, cada usuário tem que ser um array dentro de um array mãe, vai ficar bem confuso amigo.
Comment: @MatheusCardozo o campo resposta é para uma resposta válida, para dicas pode usar o campo de comentários, você ainda pode editar sua resposta e colocar um exemplo... Evita negativos...Gl ;)
Comment: @MatheusCardozo O que o bootstrap tem a ver com o problema dele? Da uma revisada nisso ai man..


Advanced forum topic list pagination settings is not applied

Question: I tried to change the pagination settings (number of elements displayed) in the view corresponding to the topic list, but in the front end, this setting doesn't seem to be applied.
the original value was 20 elements displayed, but the value really applied is 25.
Does anybody know why is that and how can i set this setting properly ?
Comment: I tried clearing the cache, the parameter is well saved as i see it when i refresh the view edition, and there is only one display. I suspect advanced forum module is overriding this setting maybe
Comment: Hello and welcome. This setting generally works. Are you sure you cleared cache? And that you actually saved your view after this change? Ant that you are editing proper display?
Answer: I found the solution :
The pagination settings in the view are ignored, instead the number of topics displayed on a page is set in the forums configuration in /admin/structure/forum/settings


how can i open png and jpg files with python?

Question: i need a program to open png files. I found this on the internet, but this gives me an error.
from PIL import Image

im = Image.open("D:/foto's/fbshare.png")

im.show()

this is the error:
AttributeError: partially initialized module 'PIL.Image' has no attribute 'open' (most likely due to a circular import)

does anybody have the solution to this problem?
Comment: Do you have another file with the same name in there?
Comment: try import PIL.Image
Comment: or try just - import Image; if needed pip install image first
Answer: I use matplotlib.image as mpimg and matplotlib.pyplot as plt:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image_path = "D:/foto's/fbshare.png"
image = mpimg.imread(image_path)
plt.imshow(image)
plt.show()

Comment: i am sorry, yes it did it works perfectly
Comment: it gives me this error ModuleNotFoundError: No module named 'matplotlib.mpimg'
Comment: Done! Yes, I mixed mpimg with the real name `matplotlib.image`.
Answer: The solution is not to name the file the same as any of the modules being imported in that file.
read more in the example here:
https://geektechstuff.com/2020/06/13/attributeerror-partially-initialized-module-has-no-attribute-python/


Let $G ⊂ S_7$ be a subgroup of order 8. Then there exists $i$ such that $\sigma(i)=i.$

Question: I am looking for the solution of the following question.
Let $G ⊂ S_7$ be a subgroup of order 8. Prove that there exists $i ∈\{1,...,7\}$ such that for any $σ ∈ G$ we have $σ(i) = i$
Thank you in advance.
Answer: If you consider $G$ has a group acting on $\{1,\dots,7\}$, you can decompose this set in orbits under the action of $G$:
$$\{1,\dots,7\}=A_1\sqcup \dots \sqcup A_n;$$this implies
$$7=|A_1|+\dots + |A_n|.$$
Now every orbit is in bijection with a coset of $G$:
$$A_i\cong G/G_{x_i},$$
where $x_i\in A_i$ and $G_{x_i}=\{\sigma \in G| \sigma(x_i)=x_i\}$; in particular we have
$$|A_i|=\frac{8}{|G_{x_i}|}.$$Since the sum of the cardinalities is odd, one of the $|A_i|$ must have odd cardinality. But $\frac{8}{|G_{x_i}|}$ divides $8$, so the only possible value is $1$. Thus one of the orbit is reduced to a point, which means the point is fixed by all $G$.


C++ linker has problems finding openssl MD4 function

Question: I have a program that I am writing and that needs to calculate some hashes. I need SHA, MD, HMAC algorithms. That is why I chose openssl as solution.
My code is the following:
#include <openssl/md4.h>

void calc();

void calc(unsigned char* data, unsigned long len) {
  unsigned char* h = new unsigned char[128];
  MD4(data, len, h);
}

Compiler returns me the following:

myfile.cpp:(.text+0x3e): undefined reference to `MD4' collect2: ld
  returned 1 exit status

I compile simply using:
g++ myfile.cpp -o myapp.o

under Linux Fedora.
I downloaded openssl libraries from here and compiled them cby using ./configure and then make install in the downloaded untarpalled directory. I also copied in /usr/local/include directory the include directory in the one I downloaded so that headers can be found by compiler because /usr/local/include is in my $PATH env var.
However the problem is that the linker cannot find the function. I understand that the reason might be two:

The compiler can find headers but cannot find implementations.
There are problems because openssl is written in C not in C++.

How should I proceeed? Thankyou
Edit1
I actually changed something in my openssl installation.
I installed openssl again and I could see that it places everything under /usr/local/ssl where I can find /usr/local/ssl/include and /usr/local/ssl/lib directories. I change my compilation string in:
g++ -I/usr/local/ssl/include -L/usr/local/ssl/lib -lssl -lcrypto

In the directories that I mentioned before I can find, respectively, /usr/local/ssl/include/openssl directory with all headers there and /usr/local/ssl/lib/libssl.a and /usr/local/ssl/lib/libcrypto.a libraries.
Before I did this change when I used the old compilation command, the compiler was telling me: Cannot find -lssl. With these changes, now it can find libs and headers, but ld always fails in the same way:

myfile.cpp:(.text+0x3e): undefined reference to `MD4' collect2: ld
  returned 1 exit status

A little disappointed.
What do you think?
Comment: You probably need to specify the name of the library in your compile command: `g++ myfile.cpp openssl-something -o myapp.o`, perhaps even include the path to the library.
Answer: Linking against openssl usually requires -lssl.
g++ -o myapp myfile.cpp -lssl

By the way, it sounds like you may have done the installation a little incorrectly.
You shouldn't have to copy header files anywhere. And you may not have copied the shared libraries anyway.
The compilation should go something like this:
./configure --prefix=/usr/local/openssl
make
make install

And then you compile your program like:
g++ -c -o myapp1.o myfile1.cpp -I/usr/local/openssl/include
g++ -c -o myapp2.o myfile2.cpp -I/usr/local/openssl/include
g++ -o myapp myapp1.o myapp2.o -I/usr/local/openssl/include -L/usr/local/openssl/lib -lssl -lcrypto

Comment: You only have the static libraries installed. When linking statically, order of the libraries makes a huge difference. Try... `g++ myapp.o -o myapp -I/usr/local/ssl/include -L/usr/local/ssl/lib -lssl -lcrypto`
Comment: When you are using static libraries, the GNU linker has to have them in order of their dependency, if lib A requires lib B, then it needs to see them as `-lA -lB`. Since your `myapp.o` required `-lssl -lcrypt`, it needed to see `myapp.o -lssl -lcrypt`.
Comment: I do what you told me, after fixing the installation ad providing correct L and I options and l options adding crypto as well, it can find those headers and implementations because the compiler tells me no more that it cannot find `lssl`, but the same problem persists...
Comment: Hmm. Interesting. That is very strange. What happens if you run `/usr/local/ssl/bin/openssl version` on the command line?
Comment: It tells me `OpenSSL 1.0.1c 10 May 2012`
Comment: It corresponds to the version I installed from the link I posted in the question.
Comment: And if you do `/usr/local/ssl/bin/openssl list-message-digest-commands` it shows `md4`?
Comment: Is it something related to C functions that the linker cannot link because of differences between C and C++? You know those errors related to `extern "C"` stuff... but I do not know what to think about this...
Comment: So make sure the `crypto` and `ssl` libraries are listed after your own object files.
Comment: Compile `.cpp` files first with the `-c` flag. I updated the example in my answer. Does that work for you?
Comment: Sorry Geoff, I did not mention it, but I have more files to compile... it tells me I cannot compile with -c option multiple files...
Comment: Yes. You have to compile each `.cpp` file individually with `-c`.
Comment: Updated the example to give you an idea of what I mean.
Comment: It compiled successfully... please could you explain what exactly you did please? Why is it working now? Which was the problem here? Thankyou btw...
Comment: I see Geoff, thak you very much for spending your time on my problem. Before I forgot to check your answer as correct, sorry for being late. Thanks again :)
Answer: The error is caused because you do not link the program to the openssl library during compilation.
Fix it with
g++ myfile.cpp -o myapp.o -lssl

See OpenSSL link options -lssl and -lcrypto in GCC
for how to link a program to openssl.


Solved 'ERROR 1054 Unknown column' importing into MariaDB 10.4

Question: I recently tried to migrate a database from an old Debian 8, MariaDB 10.1 server to a new Debian 10, MariaDB 10.4 but met with this nasty error
<code>ERROR 1054 Unknown column 'pusername' in 'field list'
</code>
I tried to import the same sql into a Debian 10, MariaDB 10.3 and it imported flawless. I then tried to export dump from this 10.3 and import it in my MariaDB 10.4 but again same exact error as above.
I read alot but could not find what could be causing it.
Any remedies ?
Here is a screenshot
Answer: Ok I figured it out...
it was an old stale trigger' that was carried over for years.... wonder none of the previous version upto MariaDB 10.3 complained about it.  Removed the trigger from source DB, exported and then successfully imported  into new Server with MariaDB 10.4.12


Is there a lilypond 'insert whitespace to fill line"?

Question: I'm trying to make music-snippet images using lilypond, but I'd like each snippet to always have trailing "whitespace" so that each of these images is of the same width.
I'm following the suggestions from the documentation, so I have a .ly file something like:

    \paper{
    indent=0\mm
    line-width=120\mm
    oddFooterMarkup=##f
    oddHeaderMarkup=##f
    bookTitleMarkup = ##f
    scoreTitleMarkup = ##f
    }
    \relative c' { c4 d e f | g a b c } %insert whitespace to fill line here

and compile it using
$>lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts --png test.ly

and it produces a file that is 241 pixels wide.
If I make the snippet three bars, with c4 d e f | g a b c | c b a g, I get a file that is 335 pixels wide.
Ultimately, I'm going to insert these images into a document, and I'd like to be able to use the same width for all of the images, and have the staff/notes be the same size.
I don't want to key off of the height of the images (which is the same) in this case, because some of the snippets will span multiple lines.
Comment: May I refer you to the LilyPond Users mailing list!? See also my answer on this question: http://meta.stackexchange.com/questions/168297/on-which-site-are-lilypond-questions-on-topic/204277#204277
Comment: I am a novice when it comes to Lilypond, but I'd try to achieve this by padding the shorter snippets with invisible dummy notes.
Comment: I'm putting them into an org-mode document; I have found that in that context I always want to set the figure width; to keep myself sane, I want to be able to set the _same_ width for all of the snippets -- thus I want Lilypond to do the padding for me.
Answer: You can fix this by adding in the \paper section:
  ragged-last = ##f

This will ensure that if your score is only one line, it will use the full line width you've specified.
Comment: True but not the solution I'm looking for -- short snippets get stretched out to fill the line, resulting in unattractively large spaces between the notes.
Comment: I see, so you really want completely white space to fill the right.  I don't know what you're using to write the final document, but it seems like if you can left-justify your images to the desired margin, you should be all set with your original lilypond source.  You'll end up with appropriate white space in the document itself rather than in the image you insert to the document, and you'll still have the peace of mind knowing that the line-width you set in lilypond will keep things from overflowing to the right.


Creating content with content type: only Title is displaying on first click not the other fields

Question: I have a content type to submit events/workshops etc for a conference.
The fields I have are like this:
Label; Machine name; Field type; Widget; Event Title; title; Node module element;
Fields:
Panel Image; field_panel_image; Image; Image;
Room; field_room; Entity Reference; Drag & Drop;
Timeslot; field_timeslot; Entity Reference; Drag & Drop;
Speaker First and Middle Name; field_speaker_first_and_middle_n; Text; Text field;
Speaker Last Name; field_speaker_last_name; Text; Text field;
Speaker Email(s); field_speaker1_email; Text; Text field;
Speaker Affiliation(s); field_speaker1_affiliation; Text; Text field;
Speaker Biography; field_speaker1_biography; Text; Text field;

Problem is that when the authorized user clicks on the link which leads to
the add content type form it does just display the "Event Title" field.
When I am logged in as admin I see the whole form.
But the "normal" authorized user needs first to hit save after typing in the event title and then the site displays the title of that just created node and an edit button. When the authorized user clicks on "edit" s/he sees the whole form.
Is there a way where the authorized user sees the whole form immediately when
s/he calls up that content type form?
(Some of the fields mentioned above (room and time slot) have the permissions set so that just admins should be able to see it. But the other permissions are set for authorized users as well.
Thank you.
Marcus
../admin/reports/status:
Drupal 7.58
Web server Apache/2.4.10 (Debian)
CKEditor 4.5.4
Code per Node CodeMirror v5.36.1 is installed.
CodeMirror is installed and it is a compatible version. Excellent!
Configuration file Protected
CSS Injector directory writable
CSS Injector Directory public://css_injector is writable
CTools CSS Cache
Database system version
Database updates
Date iCal iCalcreator library is installed, version: 2.20.2 found
Drupal core update status
File system Writable (public download method)
GD library PNG support 2.1.1-dev
GD library rotate and desaturate effects  2.1.1-dev
jQuery Update jQuery 1.7.2 (configure) and jQuery UI 1.10.2
Warning
Module and theme update status
There are updates available for one or more of your modules or themes. To ensure the proper functioning of your site, you should update as soon as possible. See the available updates page for more information and to install your missing updates.
Node Access Permissions  540 permissions in use
If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions. Rebuild permissions
OpenSSL Enabled (OpenSSL 1.0.1t 3 May 2016)
PHP    5.6.33-0+deb8u1 (more information)
PHP extensions  Enabled
PHP memory limit  256M
PHP register globals  Disabled
Plupload library 1.5.8
SOAP Enabled
Unicode library PHP Mbstring Extension
Update notifications Enabled
Upload progress Not enabled
Your server is capable of displaying file upload progress through APC, but it is not enabled. Add apc.rfc1867 = 1 to your php.ini configuration. Alternatively, it is recommended to use PECL uploadprogress, which supports more than one simultaneous upload.
Views Data Export temporary directory Exists

MODULES ENABLED
Name
Administration menu Adminimal Theme (adminimal_admin_menu)
Auto Assign Role (autoassignrole)
Automatic Entity Labels(auto_entitylabel)
Backup and Migrate(backup_migrate)
Better Exposed Filters(better_exposed_filters)
Block Class (block_class)
Bootstrap Login Modal(bootstrap_login_modal)
Calendar (calendar)
CKEditor Link (ckeditor_link)
CKEditor (ckeditor)
COD Email (cod_email)
COD Session (cod_session)
Code per Node (cpn)
Coffee (coffee)
Commerce Billy Mail(commerce_billy_mail)
Commerce Coupon(commerce_coupon)
Commerce Event Ticket(commerce_event_ticket)
Commerce Features(commerce_features)
Commerce iATS (commerce_iats)
Composer Autoloader(composer_autoloader)
Conditional Fields(conditional_fields)
Contact (contact)
Content Access (content_access)
Content Type Clone(content_type_clone)
Contextual links (contextual)
CSS Injector (css_injector)
Database logging (dblog)
Date All Day (date_all_day)
Date iCal (date_ical)
Date Tools (date_tools)
Devel generate (devel_generate)
Devel (devel)
Display Suite Extras (ds_extras)
Display Suite Format (ds_format)
Display Suite Forms (ds_forms)
Display Suite UI (ds_ui)
Distribution Update Status Manager (distro_update)
Draggableviews (draggableviews)
Empty Front Page(empty_front_page)
Enabled modules (enabled_modules)
Entity Reference Autocreate(entityreference_autocreate)
Entity reference autofill addressfield(entityreference_autofill_addressfield)
Entity reference autofill OG(entityreference_autofill_og)
Entity Reference Drag & Drop(entityreference_dragdrop)
Exclude node title(exclude_node_title)
Features Diff (features_diff)
Field group multiple(field_group_multiple)
Field reference (field_reference)
Field tools taxonomy(field_tools_taxonomy)
Field tools (field_tools)
Fieldable Panels Panes(fieldable_panels_panes)
FileField Sources Plupload(filefield_sources_plupload)
Google Analytics (googleanalytics)
Hidden CAPTCHA (hidden_captcha)
Image CAPTCHA (image_captcha)
Image URL Formatter(image_url_formatter)
IMCE plupload (imce_plupload)
jQuery Countdown Timer(jquery_countdown_timer)
Media WYSIWYG (media_wysiwyg)
Media: oEmbed (media_oembed)
Menu Block (menu_block)
Mime Mail (mimemail)
Module filter (module_filter)
Multifield table (multifield_table)
Organic groups access control(og_access)
Organic groups field access(og_field_access)
Organic groups register(og_register)
Panels In-Place Editor (panels_ipe)
Payment UI (commerce_payment_ui)
PHP filter (php)
Rules Scheduler (rules_scheduler)
Session Room - Schedule validation (validate_session_booking)
Statistics (statistics)
Stylizer (stylizer)
ThemeKey UI (themekey_ui)
Comment: Please specify Drupal version; names and versions of the relevant modules that are in use. Also, if you're using any node or field access modules make sure to rebuild the permissions, you can check that at the status page under reports.
Comment: thanks for this. I edited the text and added the info on enabled modules, drupal version etc
Comment: I can think of 3 possible solutions based on the installed modules and how you describe the issue. I believe one of them will help you solve it.
Comment: Have you tried rebuilding the permissions?
Comment: Yes. I did that to. This and disconnecting from organic groups did the trick
Answer: Make sure you rebuilt the permissions first.
If the issue still exists, first check the permissions at <code>/admin/people/permissions</code> page. If the desired roles don't have required permissions for those fields.
For what you ask, create/edit/delete permissions must be given to desired roles.
Also check "Organic Group" settings. Field permissions might be misconfigured. This is more likely the issue.
Comment: Thanks for the tips osman. Disconnecting form organic group one of the fields within the content type did the trick.....
Answer: If the previous two answers don't apply;
Third possible solution might be related with Conditional Fields.
Make sure to check all fields for their settings. Check if any of them has conditions defined making them available only on edit page, but not on create page as well.


Python server: How can I continously queue tasks while making sure only one at a time is processed

Question: I have two tasks of which one is called every two seconds and the other one is called at random times. Both need to access an object that can't be called before the previous call is finished (if that happens I need to reboot the hardware device manually).
The object is from a class which allows the communication with a hardware device via sockets.
To do so I created a thread class, in order to run everything in the background and no other tasks are blocked. Within this class I implemented a queue: Two different functions put Tasks into the queue and a worker is supposed to execute the tasks !!NOT!! simultaneously.
As this entire project is a server it should run continuously.
Well here is my code and it obviously is not working. I would be very happy if anyone has a clue on how to solve this.
Update: 26.10.2020
In order to make my issue more clear I updated the code based on the answer from Artiom Kozyrev.
import time
from threading import Lock, Thread
import threading
from queue import Queue

class ThreadWorker(Thread):
    def __init__(self, _lock: Lock, _queue: Queue, name: str):
        # daemon=False means that process waits until all threads are finished
        # (not only main one and garbage collector)
        super().__init__(name=name, daemon=False)
        # lock prevents several worker threads do work simultaneously
        self.lock = _lock
        # tasks are send from the main thread via Queue
        self.queue = _queue

    def do_work(self, job):
        # lock context manager prevents other worker threads from working in the same time
        with self.lock:
            time.sleep(3)
            print(f"{threading.current_thread().getName()}: {job * 10}")

    def run(self):
        while True:
            job = self.queue.get()
            # "poison pillow" - stop message from queue
            if not job:
                break
            self.do_work(job)

def TimeStamp(msg):
    tElapsed = (time.time() - tStart)  # Display Thread Info
    sElap = int(tElapsed)
    msElap = int((tElapsed - sElap) * 1000)
    usElap = int((tElapsed - sElap - msElap / 1000) * 1000000)
    print(msg , ': ',  sElap, 's', msElap, 'ms', usElap, 'us')

def f1():
    TimeStamp("f1 start")
    time.sleep(2)
    TimeStamp("f1 finished")

def f2():
    TimeStamp("f2 start")
    time.sleep(6)
    TimeStamp("f2 finished")

def insertf1():
    for i in range(10):
        q.put(f1())
        time.sleep(2)

def insertf2():
    for i in range(10):
        time.sleep(10)
        q.put(f2())

q = Queue()
lock = Lock()
workers = [ThreadWorker(lock, q, f"Th-worker-{i}") for i in range(5)]  # create workers
for w in workers:
    w.start()

tStart = time.time()
threading.Thread(target=insertf1, daemon=True).start()
threading.Thread(target=insertf2, daemon=True).start()

The output is:
f1 start :  0 s 0 ms 0 us
f1 finished :  2 s 2 ms 515 us
f1 start :  4 s 9 ms 335 us
f1 finished :  6 s 9 ms 932 us
f1 start :  8 s 17 ms 428 us
f2 start :  10 s 12 ms 794 us
f1 finished :  10 s 28 ms 633 us
f1 start :  12 s 29 ms 182 us
f1 finished :  14 s 34 ms 411 us
f2 finished :  16 s 19 ms 330 us
f1 started before f2 was finished, which is what needs to be avoided.
Comment: If you have only a single thread consuming from the queue, I don't understand why you worry about 2 jobs running simultaneously?
Comment: One job is an existing background thread, where a new thread is created once a socket connection is established: CallFromExtern().  The other job should run in the background aswell not to disturb the user experience. Both jobs need access to a similar object but different functions. If a user executes this request and the server is currently using that object the hardware device will crash and needs to be manually rebooted. Therefore I need a queue so this object is thread save and never called before the objects function is finished.
Comment: Your `ControlQueue` class  inherits from both `threading.Thread` and `queue.Queue`, and at the same time it has instances of those two classes inside. Such a program structure is possible, but since you never seem to use the inherited `queue.Queue` functionality at all, I would recommend to review the design decisions, first of all determine how many threads and queues are needed, and what their role is.
Comment: You are not putting `f1` and `f2` in the queue.  You are putting the *results* of calling those functions in the queue.
Answer: To do so you need to combine Queue and Lock. Lock will prevent worker-threads from working in the same time. Find code example below:
import time
from threading import Lock, Thread
import threading
from queue import Queue

class ThreadWorker(Thread):
    def __init__(self, _lock: Lock, _queue: Queue, name: str):
        # daemon=False means that process waits until all threads are finished
        # (not only main one and garbage collector)
        super().__init__(name=name, daemon=False)
        # lock prevents several worker threads do work simultaneously
        self.lock = _lock
        # tasks are send from the main thread via Queue
        self.queue = _queue

    def do_work(self, job):
        # lock context manager prevents other worker threads from working in the same time
        with self.lock:
            time.sleep(3)
            print(f"{threading.current_thread().getName()}: {job * 10}")

    def run(self):
        while True:
            job = self.queue.get()
            # "poison pillow" - stop message from queue
            if not job:
                break
            self.do_work(job)

if __name__ == '__main__':
    q = Queue()
    lock = Lock()
    workers = [ThreadWorker(lock, q, f"Th-worker-{i}") for i in range(5)]  # create workers
    for w in workers:
        w.start()
    # produce tasks
    for i in range(10):
        q.put(i)
    # stop tasks with "poison pillow"
    for i in range(len(workers)):
        q.put(None)

Edit based on additions to the question (Lock added)
The main idea is that you should not run f1 and f2 without Lock.
import time
from threading import Lock, Thread
import threading
from queue import Queue

class ThreadWorker(Thread):
    def __init__(self, _lock: Lock, _queue: Queue, name: str):
        # daemon=False means that process waits until all threads are finished
        # (not only main one and garbage collector)
        super().__init__(name=name, daemon=False)
        # lock prevents several worker threads do work simultaneously
        self.lock = _lock
        # tasks are send from the main thread via Queue
        self.queue = _queue

    def do_work(self, f):
        # lock context manager prevents other worker threads from working in the same time
        with self.lock:
            time.sleep(3)
            print(f"{threading.current_thread().getName()}: {f()}")

    def run(self):
        while True:
            job = self.queue.get()
            # "poison pillow" - stop message from queue
            if not job:
                break
            self.do_work(job)

def TimeStamp(msg):
    tElapsed = (time.time() - tStart)  # Display Thread Info
    sElap = int(tElapsed)
    msElap = int((tElapsed - sElap) * 1000)
    usElap = int((tElapsed - sElap - msElap / 1000) * 1000000)
    print(msg, ': ',  sElap, 's', msElap, 'ms', usElap, 'us')

def f1():
    TimeStamp("f1 start")
    time.sleep(1)
    TimeStamp("f1 finished")
    return f"Func-1-{threading.current_thread().getName()}"

def f2():
    TimeStamp("f2 start")
    time.sleep(3)
    TimeStamp("f2 finished")
    return f"Func-2-{threading.current_thread().getName()}"

def insertf1():
    for i in range(5):
        q.put(f1)  # do not run f1 here! Run it in worker thread with Lock

def insertf2():
    for i in range(5):
        q.put(f2) # do not run f2 here! Run it in worker thread with Lock

q = Queue()
lock = Lock()
workers = [ThreadWorker(lock, q, f"Th-worker-{i}") for i in range(5)]  # create workers
for w in workers:
    w.start()

tStart = time.time()
threading.Thread(target=insertf1, daemon=True).start()
threading.Thread(target=insertf2, daemon=True).start()

Comment: Thank you for your answer but it creates the issue as I had before.
To test it I created two threads:
threading.Thread(target=insertf1, daemon=True).start()
threading.Thread(target=insertf2, daemon=True).start(). Both threads insert functions f1 (every 2 seconds) and f2 (every 10 seconds) into the queue. f1 takes 2 seconds to execute and f2 takes 6 seconds to execute.
Comment: Now I printed the start and stop time for each task:
f1 start :  4 s 9 ms 335 us
f1 finished :  6 s 9 ms 932 us
f1 start :  8 s 17 ms 428 us
f2 start :  10 s 12 ms 794 us
f1 finished :  10 s 28 ms 633 us
f1 start :  12 s 29 ms 182 us
f1 finished :  14 s 34 ms 411 us
f2 finished :  16 s 19 ms 330 us

As you can see f1 is started before f2 is finished.
Comment: @BastHut can you add to the question what you changed in code to add Lock for the functions? And actually threads in my example are not ```daemon=True```, otherwise they will be finished when the main thread completes its work
Comment: I updated the main question based on your code, including the output
Comment: @BastHut I added information to my initial answer, I checked your code and see that f1 and f2 were not run with Lock. I changed insert1 and insert2 logic, now they do not give to Queue ready result, but send function to worker where the function is called. Note You have another choice, you can change  your code in other way and use Lock inside f1 and f2 then you'll send ready results to workers instead  of function itself.


Apache SNI: Is it possible to mix non-secure hosts with secure hosts on the same interface?

Question: On a shared server, we have some sites that only run on port 80. However, there are other sites that run on both port 80 and 443.
For example:
<VirtualHost *:80>
  ServerName unsecure.com
</VirtualHost>

<VirtualHost *:80>
  ServerName secure.com
  RedirectPermanent / https://secure.com
</VirtualHost>

<VirtualHost *:443>
  ServerName secure.com
</VirtualHost>

Requests to https://unsecure.com will be presented the certificate for secure.com. Is there any way to avoid this other than separating out the interfaces (i.e. foo:80 and bar:443 which isn't possible in this situation). Many of these sites on port 80 are legacy sites, and setting them up to use SSL isn't as straightforward as we had hoped.
Comment: Sending an `ERR_SSL_UNRECOGNIZED_NAME_ALERT` error code will avoid the user seeing a warning about an invalid certificate. In Chromium the [error page](https://static.188.8.131.52.clients.your-server.de/) produced by `ERR_SSL_UNRECOGNIZED_NAME_ALERT` looks similar to the one produced in case of a RST packet which is what they'd see if you simply weren't listening on port 443. I don't know if this is something Apache can do, which is why I am posting this as a comment rather than an answer.
Answer: You don't need separate network interfaces, just separate IP addresses. Sites which are deployed with https get one IP address, while sites with http only get the other IP address. When a site is migrated to https, its DNS address records also get chnaged to the other IP address.
In Apache, you will change the Listen directives to correspond to those IP addresses. For example:
Listen 198.51.100.37 80
Listen 203.0.113.252 80
Listen 203.0.113.252 443

This is the only way to do it reliably.
Comment: I'm curious why you are not mentioning `unrecognized_name` which you did [mention](https://serverfault.com/a/894439/214507) when I asked a similar question in the past.
Comment: Because it's not relevant?
Comment: As far as I can tell `unrecognized_name` would both be an answer to what seems to be the problem to be solved as well as to what the question is literally asking for. The question asks how to avoid clients being presented with a wrong certificate. If the server sends `unrecognized_name` the client is not presented with any certificate at all as asked for. I believe the desired result is to provide a response which the client will treat the same as it would have treated a RST. As far as I can tell at least Chromium does treat `unrecognized_name` the same way as it would treat RST.
Comment: @kasperd That also depends on the server actually terminating the handshake with `unrecognized_name`, which is not something it's required to do. And I don't even know if Apache does.
Comment: I don't know if Apache can even be configured to sent `unrecognized_name` when it doesn't have a certificate for the name. That's why I haven't posted an answer myself. What I do know is that sending that message in case of an unrecognized name and then closing the connection has worked excellent for me when implemented in my own software. The exact message I have been using looks like this: `const char reply[7] = {0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x70};`