Why does my new guitar become untuned every day?

Question: I am learning guitar as a beginner and a few days back I bought an f-hole acoustic guitar (steel strings). And every day when I sit down to play it, the guitar tuner says that it is out of tune, slightly. So I have to tune it back.
Is it normal or something is wrong with the guitar for which I must go to the shop and ask for some replacement?
B.T.W., I use the Yousician app to tune my guitar.
EDIT: As was asked in the comments, I keep my guitar in a guitar bag and it stays near my bed. I don't know about the weather going cool, it's spring here, right now. And in the morning, sunlight comes through the window pane and falls on the bag (Not scorching heat!). And as I have already said, the tuning changes only slightly and that too, in between stopping play on one night and then playing it the next night. It takes nearly a day to go untuned slightly. Also I haven't taken it outside my home, since the day I bought it.
Comment: Guitar players spend about half their time tuning their instruments and the other half playing out of tune.
Comment: Because "The perversity of the universe tends toward a maximum"
Comment: This is why we have tuners. Most instruments that aren't fixed tuning (e.g., pianos, harmonicas, accordion) have to be tuned, at least a little bit, every time you play them. If you think about it, the musicians in a orchestra are tuning **again** for probably the tenth time that day, right before they start a concert, and then again at the end of intermission! And rock stars tune between songs in a single show (or have their roadies do it while they just switch out for a just-tuned guitar).
Comment: The *relative* tuning of the strings may be acceptable (i.e. the guitar sounds "in tune" when you play it) even if the *absolute* pitch changes slightly because of changes in temperature, humidity, etc. A tuner is measuring the absolute pitch, of course. As a beginner, you might not have learned yet how to "trust your ears" rather than always use the tuner!
Comment: It's worse for instruments that have floating bridges on flexible materials - as a player of guitar and banjo, I'm tuning my banjo so often it reminds me of an old joke - "Banjo players spend half their lives tuning, and the other half playing out of tune!"
Comment: @DavidSchwartz Heh: http://music.stackexchange.com/questions/54429/why-does-my-new-guitar-become-untuned-everyday#comment83221_54431
Comment: @DavidSchwartz Q. How long does it take to tune a 12-string guitar? A. Nobody knows. :-)
Comment: "Slighlty out of tune", which I mean minor corrections required is OK. If you need to tune every string every time, take your guitar to a luthier.
Comment: It is probably worth mentioning (in your question) the environment the guitar is kept in.  If the temperature changes then that is a likely cause.  e.g. the room cooling down at night, or sunlight through the window (or stage lights) shining on it, or central heating raising the temperature.  Do you keep it in a case, or leave it in a room?  Do you take it outside?
Comment: Is the guitar still in tune immediately after you stop playing?  or does the tuning only change in the time between stopping playing and starting again?
Comment: @paulhhowells I have answered your queries in the question itself. Please check.
Comment: Oh, sorry. I read `Most instruments that [aren't fixed tuning] (...)` instead of `Most instruments that aren't [fixed tuning] (...)`. I'll delete my comment @ToddWilcox
Answer: If it's a brand new guitar, it's likely that the strings on it are new as well.
New guitar strings have a certain amount of stretchiness that can cause them to become flat (e.g. go down in tuned pitch) over time.
When I change strings on my guitars I usually manually stretch them to try and remove this stretchiness. Have a look at this question for some more information on this.
If the strings are not the issue then it may be something with the hardware, so taking it to a luthier to have it set up correctly would possibly alleviate the problem.
You probably don't need a replacement - most new guitars don't come out of the factory set up properly (even expensive ones - my Gibson was very poorly set up when I bought it brand new!).
Guitars go out of tune on their own anyway - changes in humidity, temperature etc can influence this, but normally it's not a great amount on a day to day basis.
Comment: The engineering term for what is going on in the strings is "creep"
Comment: Just as an aside on terminology-  technically speaking, new guitar strings don't go flat because of elasticity, but because they stretch.  Elasticity is the relative lack of hysteresis, or internal friction: the more elastic a material is, the less energy is lost in the form of heat when it is bent and released.  Steel strings are more elastic than nylon, as strange as that may sound.  In general, the more elastic materials also stretch less- thus steel strings stretch out and settle down faster than nylon strings.
Comment: @ScottWallace good point - I've replaced `elasticity` with `stretchiness`!
Comment: @Tristan- yep, thanks.  Creep is something you have to deal with in wood too: I sometimes find wood that seems fine for bows, but it's got too much creep, so it doesn't keep its curve.  It's creepy.
Comment: @spiffytech this [link](http://www.dawsons.co.uk/blog/what-is-a-guitar-setup) has some good information on what a set up is, and this Music SE [question](http://music.stackexchange.com/questions/1612/how-do-i-set-up-an-electric-guitar?rq=1) has some specifics for electric guitar. If you want more specific info, it would make a good question on Music SE.
Comment: @SchrodingersCat you're welcome - I really would recommend taking it to a luthier, as a good set up can really improve the playability of an instrument.
Comment: Can you elaborate on what you mean by having the guitar "set up"?
Comment: I have a string stretcher tool that is great, but like @MattJones, once I change strings, I bench each string at each fret to the max.  Retune, repeat. Once the strings hold tune, they'll be good for weeks usually.
Answer: In short: yes, this is totally normal!
German saying: "Der Gitarrist stimmt immer und die Gitarre nie" (the guitarist tunes always and the guitar never, meaning the guitar is never in tune).
Comment: I've heard it as a joke about mandolinists: "A mandolin player spends half the time tuning, and the other half playing out of tune."
Comment: To clarify the play on words, the implicit _stimmt_ in "_und die Gitarre (stimmt) nie_" means "is correct", which is the more common sense of the verb _stimmen_.
Comment: @JoshuaTaylor I've heard that exact same joke, just about banjo players ;)
Answer: This could be new strings settling in.  It could be change in temperature overnight, or even leaving the guitar near a radiator.  It could be your tuning technique.  Some say you should tune over the note then drop down to the right pitch.  Others that you should tune under, then stretch the string, then tune up to the right pitch.  See which one suits your instrument.  But it's generally agreed you shouldn't JUST tune up to the pitch.
Did you put the strings on?  There's a technique for this too.
The shop you bought it from should be happy to give some free advice.  Does it stay in tune when HE tunes it?
If the guitar stays in tune throughout a playing session, I wouldn't worry too much if it slips a little overnight.   But having said that, I recently picked up a guitar that hadn't been touched since its owner died several years ago (a reasonably long and very distinguished life, thanks for asking).  It was perfectly in tune!
Answer: Have you read your guitar tutorial book, or followed your tutorial app properly from step 1?  The first step in every guitar tutorial should say "Strings always go out of tune, so use a tuner to retune every time before playing", and every guitar tutorial I've seen has said that before they tell you how to make a chord.
If yours doesn't, find another one.  Any tutorial that doesn't tell you about tuning is so fundamentally flawed that you cannot trust it to be right about anything else.
If you're not working from a proper tutorial, get one and follow it.  Youtube is great for showing you how to position your hands and stuff like that, but it's almost entirely amateurs putting up stuff they think might be handy.  It's a good resource, but it's not at all an alternative to a properly-thought-out tutorial by someone with genuine teaching experience.
And if you're asking this because you thought you could skip over steps in your tutorial - RTFM!  All of the FM, in order, without skipping bits!
Comment: I have a bass guitar primer by Carol Kaye which recommends tuning should be checked regularly, 'at least once a week'!   And we've heard the stories of how, in the 60s when 'groups' became popular, guitarists would queue up at the Denmark Street music shops on Saturday afternoons to pay a small fee and have their guitars tuned for that night's gig.
Comment: @LaurencePayne Yeah, I've run across a few 60s guitar tutorials in second-hand book shops.  There's some "interesting" methods in them. :)
Comment: "Strings always go out of tune, so use a tuner to retune every time before playing" doesn't mean "you have to tune your guitar every day". My guitar (which is fairly inexpensive) requires only minor corrections to be in tune before playing. Any correctly set up guitar should be the same.
Comment: @el.pescado True - but it *does* require those minor corrections, or at the very least for you to check it.  Note that the OP says his tuner program tells him the guitar is out of tune, not that he (as a beginner) can hear it himself.  You and I probably could hear it, of course.
Answer: This could be due to a variety of things, including:

strings needing to be stretched, or seated firmly in the various areas that they are in physical contact with.
components on the guitar itself needing to become firmly seated (loose neck bolts, bridge, tuners, nut, etc.)
quality of the instrument

The last is the one that I would most want to focus on. If you have a very inexpensive, old or poorly cared for guitar it is likely that one of the many potential issues that plague instruments like that is causing the problem. While it is true that many guitars do require some tuning on a daily basis, it should be entirely unnoticeable to an untrained ear and barely detectable by a mobile phone tuner (the quality of which is mediocre at best).
My advice would be to take it to a luthier and explain the problem and see if they can determine what the issue is, and ask for and be prepared for an honest answer.
Answer: All thing, even steel, under stress will strain (stretch).  Most of it is elastic strain and but some of it is inelastic and permanently stretches the steel.  Over time this strain hardens the steel and less stretching should occur.  The hardening also brings the steel closer to its maximum stress eventually causing it to break.
Answer: Heat and especially humidity affect the wood of an instrument, causing it to shrink or expand, so the strings go out of tune. This is particularly noticeable on a mandolin, but it happens on [acoustic] guitars too. Corollary: do not leave your instrument in the sun, or in the trunk of a car.
Answer: When tuning an acoustic guitar, I do not tune the open strings. I instead tune the Octaves. Since most acoustic guitars do not have intonation adjustment, yet are susceptible to minor warping, I have found you can tune your acoustic, yet your octaves may be slightly off. But if you tune your octaves, if your guitar is slightly out of intonation, this will at least average the difference. Another alternative (besides tuning using harmonics) is to find the A note on all your strings and tune all strings to A. Now you are ensured that everything is relative to 440 hz.
A Guitar, regardless of age or price is constructed of physical materials.
Various materials expand or contract at different temperatures, moisture levels, atmospheric pressures, phases of the moon, etc.,etc.
You can tune your guitar, throw it in the case, go to a gig, whip it out and within minutes watch it slowly go out of tune simply because you are now in a hot, moist, smoky room under intense lights. Instead of a dry, air conditioned apartment.
As a guitarist, you should be aware of your tuning at all times. If you like to pitch bend a lot, you will stretch your strings a bit and should be able to compensate. Watch Jimi Hendrix tune by ear in mid note without missing a beat. Pure genius!
There is a direct ratio between your level of education and how long it takes you to tune up. Paul Simon, a college grad in music can tune a guitar by ear in 8 seconds. You can circumvent this by taking a course in perfect pitch ear training. Yes, perfect pitch can be learned. Just like speed reading. You just have to have that inner desire to be the best of the best and apply yourself 100% to mastering your instrument ;)
Ironically, 99.9% of all guitars are not technically accurate to a tempered scale in the first place! You wanna have you mind blown? If you are interested in accurate pitch, look into True Temperament Guitars:
http://www.truetemperament.com/
Answer: There Might be a Problem with your Bridge adjust that and it will help otherwise keep it in sunlight with the wall at approx 45 degrees neck facing inwards
Comment: AFAIK, acoustic guitars has fixed bridges. Also, leaving a guitar in direct sunlight is a really bad idea. Sorry to say, but this not useful at all and deserves my downvote
Comment: An archtop guitar, which is probably what is meant by an 'f hole guitar' typically has a moveable bridge.  But a badly positioned bridge won't cause tuning instability, and the sunlight/wall stuff is just gobbledegook. So another downvote I'm afraid!


How to change or influence the block id and class of a view block

Question: I have a view with 2 blocks. One was cloned from the other.
I changed the machine readable name of both of the blocks (block_events_upcoming and block_events_upcoming_ical), but in the html i get as id and classes the beautys you see below.

Is there a way to change the ids and classes of the block. The css-class option in advanced settings only changes the css class in the block_content div not the top block-div.
Answer: The HTML ID is generated by concatenating block-view_name-block_name and
it seems there's a length limit of 32 characters. My block exceeded that limit.
So for me the solution was to shorten the block-machine-name.
Answer: Have you tried to give your blocks an id through the 'advanced' fieldset of your view? on the 'other' list of settings. That might do the trick.


Adding fees at each payment

Question: I am using Commerce Fees module, as I want to add 5% as fees at the time of purchase.
I have added a fees type, and created a rule for this.
My Problem is that I whenever I go to checkout page where I have added some products such that my total order price is 1000, so I should be getting service tax of 50, but I am getting it to be 52.63 instead.
I am attaching my rules export, please help.
<code> { "rules_5_service_fees" : {
 "LABEL" : "5% Service Fees",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "commerce_fees" ],
 "ON" : { "commerce_fees_order" : [] },
 "DO" : [
   { "data_calc" : {
       "USING" : {
         "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
         "op" : "*",
         "input_2" : "5"
       },
       "PROVIDE" : { "result" : { "tax" : "Calculated Tax" } }
     }
   },
   { "commerce_fees_apply" : {
       "entity" : [ "commerce-order" ],
       "fee" : "service_fees",
       "amount" : [ "tax" ],
       "currency_code" : "USD",
       "include_tax" : "0"
     }
   }
 ]
 }
 }
</code>
Answer: Not as much of an answer as it is a recommendation. You should be doing this at the price calculation (per product) level, not order level. Not doing this can mean you're taking into account the taxes, shipping, other coupons/discounts, etc.
Comment: I think you are right, I will try doing it on product level

Adding fees at each payment


Can I insert deletable characters in python input buffer?

Question: I want to automatically indent the next line of a console app but the user needs to be able to remove it.  sys.stdout.write and print make undeletable characters and I can't write to sys.stdin (as far as I know).  I'm essentially trying to get smart indenting but I can only nest deeper and deeper.  Any ideas on how to climb back out?
Edit: I should have noted that this is part of a Windows program that uses IronPython.  While I could do something much fancier (and might in the future), I am hoping to quickly get a reasonably pleasant experience with very little effort as a starting point.
Comment: Why make this as a console app? (It sounds like it might deserve another approach). If you want to have the user move the cursor freely around the console, you might want to use ncurses rather than just the built-in methods.
Comment: What platform will this be running on? If Linux, you could look into using the readline module.
Comment: There's a [pyreadline](http://pypi.python.org/pypi/pyreadline) that works on Windows.
Answer: The cmd module provides a very simple interface for creating a command line interface to your program. It might not be able to put some buffer characters in front of the next line but if you're looking for an obvious way to let your users know that the command has returned, it can provide a shell-like prompt at the beginning of each line. If you already have functions defined for your program, integrating them into a processor would be a matter of writing a handler that access the function:
import cmd
import math

def findHpyot(length, height):
    return math.sqrt(length **2 + height **2)

class MathProcessor(cmd.Cmd):
    prompt = "Math>"

    def do_hypot(self, line):
        x = raw_input("Length:")
        y = raw_input("Height:")
        if x and y:
            try:
                hypot = findHypot(float(x), float(y))
                print "Hypot:: %.2f" %hypot
            except ValueError:
                print "Length and Height must be numbers"

    def do_EOF(self, line):
        return True

    def do_exit(self, line):
        return True

    def do_quit(self, line):
        return True

if __name__ == "__main__":
    cmdProcessor = MathProcessor()
    cmdProcessor.cmdloop()

Things to consider when writing an interactive shell using cmd

The name after do_ is the command that your users will use so that in this example, the available commands will be hypot, exit, quit, and help.
Without overriding do_help, calling help will give you a list of available commands
Any call that you want to quit the program should return True
If you want to process entries from the function call, say you wanted to be able to handle a call like "hypot 3 4" you can use the local line variable in the function call


Is this 95% Confidence Interval Based on the Corrected Correlation or Uncorrected Correlation in Meta-Analysis

Question: My questions are:

Is the 95% CI in a meta-analysis based on the uncorrected correlation or corrected correlation?
Can a 95% CI have an upper limit that is smaller than the lower limit?

Context:
I'm trying to understand the results of a meta-analysis paper. There are two things that I understand about 95% CIs (please correct me if I am wrong)

if a correlation falls outside of the 95% CI, then it is non-significant.
in a 95% CI, the value of the Upper Limit (CIu) is always higher than the value of the Lower Limit (CIl)

In their table of results, two correlations are reported - an uncorrected correlation (r) and a corrected correlation (p-hat). When the author reports the finding, they refer to p-hat. But some of the p-hat values fall OUTSIDE of the 95% CI, yet the author says that their findings support their hypothesis of a positive relationship. Hence the confusion.
Comment: What do the authors mean by a "corrected" correlation?
Comment: here is what they noted in the Analysis Section, "effect sizes were corrected individually for unreliability in both the antecedent measures and the cohesion measures, utilizing alpha coefficients. When alpha coefficients were not provided, mean reliabilities of similar measures were imputed in order to make corrections"
Answer: We cannot tell what the authors did without reading the paper and I suspect from bitter experience we will be no further forward if we do have it.
A confidence interval has to cover a range of values so the upper limit will be greater than the lower limit and in general the point estimate will fall within that range although there are rare circumstances where that does not happen.
If the confidence interval does not include the null value, which for correlations is zero, then it would usually mean that the point estimate was significantly different from zero although there are some situations where the assumption underlying confidence interval construction differ from the significance test.
It may well be that p-hat falls outside the interval for r but it should not fall outside the interval for p-hat.


Is the set of all exponential functions a subspace of the vector space of all continuous functions?

Question: Given the vector space, $ C(-\infty,\infty)$ as the set of all continuous functions that are always continuous, is the set of all exponential functions, $U=\{a^x\mid a \ge 1 \}$, a subspace of the given vector space?
As far as I'm aware, proving a subspace of a given vector space only requires you to prove closure under addition and scalar multiplication, but I'm kind of at a loss as to how to do this with exponential functions (I'm sure it's way simpler than I'm making it).
My argument so far is that the set $U$ is a subset of the set of all differentiable functions, which itself is a subset of $C(-\infty,\infty)$, but I doubt that argument would hold up on my test, given how we've tested for subspaces in class (with closure).
Comment: What is $a^x$ at $x=0$? What is $a^x+b^x$ at $x=0$? Can it equal some $c^x$?
Comment: If you say _exponential functions_, did you mean to write $a^x$ instead of $x^a$?
Comment: I did and I've corrected that, thank you!
Comment: The zero in $C(-\infty,\infty)$ is the constant function the always returns zero. That function is not in $U$.
Answer: Not, it is not a subspace. For instance the null function does not belong to $ U$.
Answer:
(...) but I doubt that argument would hold up on my test, given how we've tested for subspaces in class (with closure).

Hint: closure under addition means that if you would take two such functions, say $a^x$ and $b^x$, then their sum $a^x+b^x$ should be in the set as well. That function is only in the set if $a^x+b^x = c^x$ for some $c$; is that possible (in general)?
Or the fast and simple test: does the set contain the zero element (in this case: the zero function)?
Answer: As originally written, no, since $0\notin U.$ In addition, your $U$ seems to be the set of monic monomials in $x,$ not exponential functions, which would instead have the form $a^x$ for some positive constant $a.$ Even then, this would not be a subspace, for exactly the same reason.
Edit: Another simple approach would be to show that $U$ (in either version) is not closed under scalar multiplication.
Showing failure to be closed under addition is more difficult in both cases, but not too tricky for the original $U.$
Comment: Didn't think about it not being closed under scalar multiplication--thanks for that. I wasn't super confident about the logic I was using, thank you for the explanation!
Comment: You're very welcome. It's good to keep in mind that some sets may be closed under one, but not the other. For example, the set $\bigl\{(x,y)\in\Bbb R^2:x>0\bigr\}$ is closed under addition, but not scalar multiplication; the set $\bigl\{(x,y)\in\Bbb R^2:x=0\text{ or }y=0\bigr\}$ is closed under scalar multiplication, but not addition.


How to select odd "option" using nth-child() in jquery?

Question: I'm trying to sharpen my jQuery skills by learning to use nth-child selector but with little luck.  I'm sure I'm just doing something slightly wrong, and I will have a follow up question to this again regarding nth-child, so any help is appreciated.
I would have thought my code below would have select "Saab" and "Audi" in the pulldown menu, but what it does is return the "source" select element, select#carsmenu.  What am I doing wrong?
$(document).ready(function() {
      console.log($('#carsmenu:nth-child(odd)').prop('selected', true));
});

<select multiple id="carsmenu">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Comment: You may want to look into using `find()` instead to lessen the confusion. E.g., `$('#carsmenu').find(':ng-child(odd)').prop('selected', true)`.
Comment: Of course, then need to change to `even` instead
Comment: @MikeMcCaughan is :ng-child is something angular specific?
Comment: What if I already have selected `$("#carsmenu")`?  Is there any way to then use an nth-child selector against the returned value(s)?
Comment: @GeorgeJempty No, just a typo from too much Angular work :). Should be the same as your selector `nth-child`.
Comment: @MikeMcCaughan so that might answer my subsequent question/comment: use `nth-child()` inside find when I already have made a DOM selection I want to use as the source
Answer: The :nth-child() selector should written after target element that you want to select it.
$('#carsmenu > :nth-child(odd)').prop('selected', true);

$('#carsmenu > :nth-child(odd)').prop('selected', true);

<select multiple id="carsmenu">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Also you can use :odd selector
$('#carsmenu > :odd').prop('selected', true);

$('#carsmenu > :odd').prop('selected', true);

<select multiple id="carsmenu">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Answer: With #carsmenu:nth-child(odd) this code, you'are selecting select element that odd, what you really want it select child element of select, in your case is <option> tag, you might use below code for selecting child elements :
// This will select volvo and mercedes because of 0-based of nth-child
// another option is `even` which select saab and audi
$('#carsmenu option:nth-child(odd)')

$(document).ready(function() {
  console.log($('#carsmenu option:nth-child(even)').prop('selected', true));
});

<select multiple id="carsmenu">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Comment: Yes and it selects Volvo and Mercedes instead because it is 1-based not 0-based
Comment: you might need used even instead
Answer:

$(document).ready(function() {
  //It is possible as this,
  console.log($('#carsmenu :nth-child(odd)')); //Volov & Mercedes, it starts counting from the first child "Volvo" and takes every second "Mercedes"--> ...
  console.log($('#carsmenu :odd')); //Saab & Audi, it starts counting from element 0, which does not exist, and takes every second --> "Saab" --> "Audi" --> ...

  //but for a better readability:
  console.log($('#carsmenu option:nth-child(odd)')); //Volov & Mercedes
  console.log($('#carsmenu option:odd')); //Saab & Audi

  //add the ".prop('selected', true);" to which you want to have selected.
});

<select multiple id="carsmenu">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>


Substituir conjunto de palavras no Excel

Question: Eu tenho uma planilha Excel com algumas colunas, por exemplo:
Fruta | Veículo | Profissões
--------------------------

Banana   Carro   Médico
Pera     Moto    Programador
Maça     Barco   Engenheiro
Morango  Avião   Advogado

E em outra coluna...
Coluna 1
--------
Banana
Pera
Carro
Médico

E gostaria que essa coluna se transformasse em:
Coluna 1
--------
Fruta
Fruta
Veículo
Profissão

Como eu poderia realizar essa substituição automatizada de vários dados da planilha?
obs.: Não importa a ferramenta ou linguagem de programação para realizar tal feito
Comment: Mas você está a procura de uma formula ou de código VBA ?
Comment: Procuro a forma mais objetiva e sucinta, mas qualquer ajuda é válida.
Answer: É possível definir uma função que faça essa busca e retorne o título da coluna, que é o nome de cada grupo. Abaixo um exemplo funcional, com base nos dados da pergunta:
Definindo a function VBA
A função abaixo irá receber o valor procurado e um intervalo de colunas, a partir disso ela faz um loop em cada coluna, pesquisando o valor procurado. Ao localizar (ou não), ela encerra e retorna o resultado. Está com comentários para mais entendimento:
Public Function ProcMultiplasColunas(ByVal ValorProcurado As String, ByVal RangeColunas As Range) As String

Dim ColunaLoop As Long
Dim ColunaLocalizada As String
Dim Corresp As Variant

ColunaLocalizada = ""

For ColunaLoop = 1 To RangeColunas.Columns.Count Step 1

    'Usa função nativa de corresp(match)
    Corresp = 0
    On Error Resume Next
    Corresp = Application.WorksheetFunction.Match(ValorProcurado, RangeColunas.Columns(ColunaLoop), 0)
    On Error GoTo 0

    'Verifica se localizou, seta a coluna e encerra For
    If Corresp <> 0 Then
        ColunaLocalizada = RangeColunas.Cells(1, ColunaLoop)
        Exit For
    End If

Next ColunaLoop

'Testa se localizou algum valor e encerra a função
If ColunaLocalizada = "" Then
    ProcMultiplasColunas = "#NÃO LOCALIZADO!"
Else
    ProcMultiplasColunas = ColunaLocalizada 'retorna a coluna localizada para a função
End If

End Function

Esse procedimento retorna o resultado esperado:

Sub para substituir conteúdos
Precisamos que o processo execute linha a linha, isso foi definido a partir de um For, que aplica a function definida anteriormente. Ela sobrescreve o conteúdo da célula em análise. Está com comentários para mais entendimento:
Sub substituiValores()

Dim linha As Integer 'declara a linha como inteiro

For linha = 2 To 5 'verificará da linha 2 até a 5 - precisa ajustar ou aprimorar
    If Cells(linha, 1) <> "" Then 'verifica se tem conteúdo na célula e executa a fórmula
        Cells(linha, 1) = ProcMultiplasColunas(Cells(linha, 1), ThisWorkbook.Sheets("Planilha2").Range("A:C"))
    End If 'fecha if
Next linha 'próxima linha, se não foi encerrado no if verdadeiro

End Sub

Pontos de atenção

Pode ter problemas de performance, dependendo da máquina e tamanho das bases;
As executar a sub, os valores originais são perdidos, sem recuperar ou "desfazer (ctrl z)". Repare que está definido para ele deixar um "#NÃO LOCALIZADO!", porém, fica impossível de saber qual foi o conteúdo original não localizado (uma vez que sobrescreveu).
Esse não é o único caminho. Existem outros meios de contornar essa necessidade, como reorganizar a base de grupos (título e lista). Se ela for reorganizada (se possível), uma simples função de procv atenderia, por exemplo. Outra possibilidade talvez exista com definições matriciais (fórmulas "Ctrl-Shift-Enter" ou "CSE"), somente como exemplo também.


Using Excel to calculate multiple future dates

Question: I am working on a revenue report that predicts deposit date related to "Revenue Date" based on observed patterns.  For example, one stream of revenue is always deposited the next business day, so I would need a formula that adds one day to anything with a "Revenue Day" identified as Monday through Thursday (because these would be deposited Tuesday-Friday, respectively), and adds three days to a "Revenue Day" identified as Friday (because this would be deposited on Monday), and adds two days for Saturday, and one for Sunday.
I managed to get the correct result for Monday-Thursday using this formula, where G1 is the weekday and H1 is the date:
=IF(OR(G1="MONDAY", G1="TUESDAY", G1="WEDNESDAY", G1="THURSDAY"), H1+1)

Unfortunately, I can't figure out how to also get it to add 3 days to Friday, 2 days to Saturday, and 1 day to Sunday. Is this possible?
Comment: Please add some code explaining what you have tried
Comment: Thanks for the quick response!  I used: =IF(OR(G1="MONDAY", G1="TUESDAY", G1="WEDNESDAY", G1="THURSDAY"), H1+1) to get the correct result for Monday-Thursday where G1 is the weekday and H1 is the date.  I can't figure out how to also get it to add 3 days to Friday, 2 days to Saturday, and 1 day to Sunday.
Answer:
Your if formula should take 3 parameters  IF(condition, do if condition is true, do if condition is false).
Use ; instead of ,
Sundays does the same this as Moday-Thursday, so no need for a special case for it

... So i would guess that you need something like this :
 =IF(OR(G1="SUNDAY";G1="MONDAY";G1="TUESDAY";G1="WEDNESDAY";G1="THURSDAY");H1+1;IF(G1="FRIDAY";H1+3;IF(G1="SATURDAY";H1+2;"bad input")))

Comment: Thanks!  I put in this formula:  =(IF(OR(G1="MONDAY", G1="TUESDAY", G1="WEDNESDAY", G1="THURSDAY"), H1+1)) (IF(G1="FRIDAY", H1+3)) (IF(G1="SATURDAY", H1+2)) (IF(G1="SUNDAY",H1+1))  But now I get a #VALUE! error.  Any ideas what that could be?
Comment: @KPearson You don't follow the correct syntax. I edited my answer to fix you solution
Comment: Thank you so much!


What would cause the VSCode command line to not respect the folder argument?

Question: I'm using the shell script defined here (https://code.visualstudio.com/Docs/setup), and while I can type code . to open up VS Code, it does not select the current directory to show in the tree.
Answer: With the 0.3.0 update this issue has been fixed. Please use this updated command:
code () {
    VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*
}

Update for our VS Code 1.0 release: please use the command Install code command in path from the command palette (View | Command Palette).
Comment: Wow! And it opened a second window too -which is perfect. Thank you, thank you, thank you!
Answer: I've tested the sample on the setup page and it works fine.
code () {
    if [[ $# = 0 ]]
    then
        open -a "Visual Studio Code"
    else
        [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
        open -a "Visual Studio Code" --args "$F"
    fi
}

I did however add it to the bottom of my ~/.bashrc  instead of my .bash_profile.  The .bash_profile simply sources the .bash_profile so it should be equivalent.
if [ -e ~/.bashrc ]
then
    . ~/.bashrc
fi

You can test that you are running in a bash shell by executing:
echo $SHELL

This should return /bash/bash.
Comment: We will look into this issue, it was reported already as a bug.
Comment: This only works if Code is closed. if Code was already open, it focuses it, but doesn't change directories.
Comment: The fact that Code is already open should have been stated in the original question.  In that case you could detect if it is already open and then run AppleScript to change the currently opened folder.  Unfortunately Visual Code does not currently have AppleScript or Automator support.  You could rewrite the bash function to shutdown code and reopen it if it is already open.  These solutions are complex and it might be better to simply use the File -> Open ... menu option.


Nginx secure link with rewrite

Question: I want to make a secure URL with Nginx secure-link model and rewrite. So the secured link be like:
http://example.com/media/ZYSwFWTSM8DHh8CNupbbzw/1593525536/videos/tmp/793.mp4
And the Rewrite convert it to:
http://example.com/media/videos/tmp/793.mp4?md5=ZYSwFWTSM8DHh8CNupbbzw&secure=1593525536
So at the end open this video link:
http://example.com/media/videos/tmp/793.mp4
This is my Nginx server config:
location /media {
       rewrite  /videos/([a-zA-Z0-9_\-]*)/([0-9]*)/tmp/(.*)\.mp4$ /media/videos/tmp/$3.mp4?md5=$1&expires=$2;
}

location /media/videos {
       secure_link $arg_md5,$arg_expires;
       secure_link_md5 "$secure_link_expires$uri SecretWord";

       if ($secure_link = "") { return 403; }
       if ($secure_link = "0") { return 410; }
}

The problem is that I getting "403 Forbidden" when I try to open these secured links:
http://example.com/media/ZYSwFWTSM8DHh8CNupbbzw/1593525536/videos/tmp/793.mp4
Although these links are working very well:
http://example.com/media/videos/tmp/793.mp4?md5=ZYSwFWTSM8DHh8CNupbbzw&secure=1593525536
also When I remove the secure_link model config, and try this link:
http://example.com/media/ZYSwFWTSM8DHh8CNupbbzw/1593525536/videos/tmp/793.mp4
The video working.
So I really don't know what is the problem because The rewrite config or secure_link_module working itself but they are not working together.
Answer: Try this
location /securemedia {
       rewrite  /securemedia/([a-zA-Z0-9_\-]*)/([0-9]*)/(.*)$ /media/videos/$3?md5=$1&expires=$2;
}

location /media/videos {
       secure_link $arg_md5,$arg_expires;
       secure_link_md5 "$secure_link_expires$uri SecretWord";

       if ($secure_link = "") { return 403; }
       if ($secure_link = "0") { return 410; }
}

example url
http://example.com/securemedia/ZYSwFWTSM8DHh8CNupbbzw/1593525536/videos/tmp/793.mp4

Nginx secure link with rewrite


Show fields only when other column does not contain nulls

Question: I have a table that stores pets and a certain number of vaccines. In one column the identifier, in another column the name of the vaccine and in the third column, the date of completion. In case the date is null, it means that the pet has not received that vaccine yet.
This estructure is the next one:
CREATE TABLE pets (
  pet VARCHAR (10),
  vaccine VARCHAR (50),
  complete_date DATE
);

INSERT INTO pets VALUES ('DOG001', 'Adenovirus', '2021-01-03');
INSERT INTO pets VALUES ('DOG001', 'Parvovirus', '2021-02-03');
INSERT INTO pets VALUES ('DOG001', 'Leptospirosis', null);
INSERT INTO pets VALUES ('CAT774', 'Calcivirosis', '2021-01-06');
INSERT INTO pets VALUES ('CAT774', 'Panleukopenia', null);
INSERT INTO pets VALUES ('DOG002', 'Adenovirus', '2020-12-21');
INSERT INTO pets VALUES ('DOG002', 'Parvovirus', '2021-02-01');
INSERT INTO pets VALUES ('DOG002', 'Leptospirosis', '2021-03-01');

pet
vaccine
complete_date

DOG001
Adenovirus
2021-01-03

DOG001
Parvovirus
2021-02-03

DOG001
Leptospirosis
null

CAT774
Calcivirosis
2021-01-06

CAT774
Panleukopenia
null

DOG002
Adenovirus
2020-12-21

DOG002
Parvovirus
2021-02-01

DOG002
Leptospirosis
2021-03-01

What I need is a list of all the pets that do not have a null "date", considering all the vaccines.
In this example, the result should be simply 'DOG002' since it is the only animal with all its dates with non-null values.
Comment: `SELECT pet FROM pets WHERE complete_date IS NOT NULL EXCEPT SELECT pet FROM pets WHERE complete_date IS NULL` is one way to do it, though not necessarily the most obvious or efficient way.
Answer: A conditional aggregate in the HAVING would be one method:
SELECT Pet
FROM dbo.Pets
GROUP BY Pet
HAVING COUNT(CASE WHEN Complete_Date IS NULL THEN 1 END) = 0;

Answer: I think Larnu posted what you are looking for (+1)... BUT... just in case you want to see the pet's details.
Just another option is WITH TIES.
Select top 1 with ties *
 From  pets
 order by sum(case when complete_date is null then 1 else 0 end) over (partition by pet)

Answer: SELECT DISTINCT Pet FROM Pets
WHERE Pet NOT IN (SELECT Pet FROM Pets WHERE Complete_Date IS NULL)

Answer: CTE can also be used to achieve the above result
with CTE as
(
 select pet,
 vaccine,
 complete_date,
 SUM(IIF(complete_date is null ,1,0)) over (PARTITION BY pet) as pet_flag
 from pets
)

select distinct Pet from CTE where
pet_flag = 0

Comment: Pet peeve, but `;` is a statement *terminator* not a "beginningator". It goes at the end of **all** your statements not at the start of the ones that require the *prior* one to be properly terminated.
Comment: yeah that right @Larnu - I have corrected it now


ROBLOX - Trying to get my desired effect?

Question: sorry about the vague title, I have no idea on how to explain what I'm trying to do.
I'm trying to replicate a "choosing"(?) effect from a ROBLOX game shown here
I've gotten to basically the exact same thing, except for one problem. It always stops on the same part every time (the top). Posting here is my current last resort (the scripting subforum on roblox is incredibly inactive)
for i = 1, 3 do
    for _, ll in pairs(P:GetChildren()) do
        lastbcolor = ll.BrickColor
        ll.BrickColor = BrickColor.Yellow()
        wait(t)
        ll.BrickColor = lastbcolor
        lastpicked = ll
        print(t)
        t=t+0.2 -- to slow down
    end
end

Answer: math.randomseed(os.time())
local t = P:GetChildren()
local N = #t                  -- number of menu items
local K = 1
for R = 20 + math.random(N), 1, -1 do
  ll = t[K]
  local lastbcolor = ll.BrickColor
  ll.BrickColor = BrickColor.Yellow()
  wait( R^-.7*.7 )
  ll.BrickColor = lastbcolor
  K = K % N + 1
end
ll = t[K]
-- blink
for R = 1, 5 do
  local lastbcolor = ll.BrickColor
  ll.BrickColor = BrickColor.Yellow()
  wait( .3 )
  ll.BrickColor = lastbcolor
  wait( .3 )
end


Does the default self-signed cert break Exchange 2010 Activesync?

Question: I have a customer who has been using a neglected Exchange 2003 server for at least 10 years. I'm in the middle of a migration to Exchange 2010. Pretty much done, actually. The only thing left on my checklist is Activesync. My mobile device won't connect to the new server's Activesync unless it's on the internal WLAN. I'm suspecting that this is because name on the self-signed SSL cert doesn't match the external Activesync URL. Microsoft's testexchangeconnectivity tool seems to confirm this.
The 2003 server has been using an expired self-signed cert for about six years. Activesync worked; it just gave users a certificate warning during the initial connection, and they were forced to accept the cert. While researching my problem, I've found some sources that hint that Exchange 2007/2010 Activesync simply won't work with the default self-signed cert. Is this true? If so, does anyone know why? I'm just confused about why the server would check it's own SSL cert. I wouldn't expect the server to care about the self-signing or the name mismatch. As long as the clients are accepting the certificate, I figured Activesync would work.
I can probably convince the customer to get a UCC, but the AD domain is a .local one. I won't be able to include the internal hostnames as SANs on the UCC. This will likely cause certificate warnings for users on the LAN, which is something that I'd like to avoid. Unfortunately, I'm too far along in the Exchange migration to move AD to a new domain that can be included as a SAN. (I can revisit that option during the migration to Exchange 2013, but it's too late to do it now.) I suppose that the other option is to set up my own CA and create my cert... but then I'll have to install certs on every mobile device in the company.
Answer: The correct way to do it with a. Local is to use the external domain. You set the path to the external'one, you register the certificate (some cheap exist) and you doa split dns setup, so internally the external host will resolve to the internal'one. This is the only clean way.


Use Subdomains as variable with Domain Access

Question: I'm new to Domain Access module. It seems it is built to allow you to run different sites off the same database. I'm looking for something more simple than that.
I want to the subdomain title to be included in the site name. I want a content type to be assigned to different subdomains and for that content to be the only content of it's type visible on the same subdomain.
Aside from that, everything else on the site should remain the same. Theme, users, layout, etc.
How can I best do this with DA module? Is it possible to use the domain as a variable (for use in views, panel's context and a token for the site name)?
Answer: I did this by installing Domain Access module. When skimming Domain Access module's documentation before, it seemed extremely complicated. However, the documentation is geared towards you learning all about how it works. The actual steps to install are more than a regular module, but not too complicated.
It allows me to restrict content to a specific domain and to have different site names for each domain.
Answer: Edit: I see the 7.x version of Subdomain does not yet support Content type domains.
If you use Domain Access, you can manually create all the required subdomains and you can define a site name for each (I believe this requires the included submodules Domain Configuration and Domain Settings). You can set a default front page for each domain you create (such as a Views page). If you want to filter by content type, you will have to configure a view for each subdomain. It may be better, however, to use the DA module's model of content affiliation, that is, when you create a node you can assign it to a specific (sub)domain. If you want to restrict on which domains nodes are viewable, you will have to do this anyway, so the differentiation by content types might not be necessary (depending on your needs).
If you do need different content types for each subdomain and you can't trust your users to choose the right domain content affiliation, you can use Domain Content Types to restrict which content type can be used for each domain, e.g. the 'News' content type is configured for use only on the domain news.example.com.

It seems the Subdomain module will do exactly what you want:

Content type subdomains: e.g. "News" content at
  http://news.example.com

This is also a much more light-weight solution than Domain Access - always a good thing.
Comment: Do you have experience with this module in this situation?
Comment: Admittedly, no. But I've used DA and while you can of course build the necessary views to show the right content for each subdomain, DA seems overkill for this use case.
Comment: I ended up going with Domain Access. There will be a few pieces that could be trickier, but for the site names and content, it worked out with very little config


Cache Youtube API XML response with Nokogiri error - Marshalling error?

Question: I would like to minimize my calls to the Youtube API as this data doesn't refresh often. When I try to cache this:
Rails.cache.fetch("youtube-#{@yt_name}", :expires_in => 1.day) do
  @youtube_doc = Nokogiri::XML(open("https://gdata.youtube.com/feeds/api/users/#{@yt_name}/uploads"))
end

I get an error in heroku:
Marshalling error for key 'youtube-NAME': no marshal_dump is defined for class Nokogiri::XML::NodeSet
You are trying to cache a Ruby object which cannot be serialized to memcached.

Any ideas?
Answer: You may want to cache the XML rather than the Nokogiri object. Try this:
xml = Rails.cache.fetch("youtube-#{@yt_name}", :expires_in => 1.day) do
  open("https://gdata.youtube.com/feeds/api/users/#{@yt_name}/uploads").read
end
@youtube_doc = Nokogiri::XML(xml)

Comment: Awesome. But I am getting 'File name too long' as it reads in the entire feed. Any ideas on how to get around this problem?


How to use $(window).delegate('selector','resize',function handler) when selector is into an iFrame?

Question: I need to use as a selector an element from DOM inside an iFrame.
Thanx in advance.
Comment: possible duplicate of [jquery/javascript: accessing contents of an iframe](http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe)
Answer: You can not access anything in an iframe with JavaScript running outside this frame.
Browsers has a same origin policy to prevent security problems like phishing
(If you host the content of this iframe your self you may have a look at jQuery load() to load HTML chunks into your page)
Comment: The iframe has been dinamically created from my code, therefore I have full access to its elements.
Comment: ok, maybe you should try to load it with jQuery load(), then the html is injected into your page instead if iframe
Comment: The contents of the iframe is not the problem because it's added dinamically as well. I'd like to use delegate using an element into an iframe as a selector, but i don't know the syntax of the selector for this case.


How to calculate last four digits of $2^{2017}$?

Question: can u suggest me any short trick of solving these kind of problems. How to find last four digits of any number raised to some power ?
Comment: See https://math.stackexchange.com/questions/1844558/how-to-find-last-two-digits-of-22016
Comment: The standard approach is to use modular arithmetic, with the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) and [Euler's theorem](https://en.m.wikipedia.org/wiki/Euler%27s_theorem).
Comment: Just to mention : TIFR GS 2018, conducted a few days ago, asked for the last three digits of this number. The answer was $072$, and the official (or rather, mine) solution says : note that $2^{n}$ and $2^{n+20}$ have the same last three digits after some time(for $n > 7$)! And therefore you find the last three digits of $2^{17}$. For four digits, you will have to proceed a little further.
Comment: Have a look at https://math.stackexchange.com/a/2562678/44121
Answer: Since $10^4 = 2^4 \times 5^4$, my first reaction is one should use Chinese remainder theorem.
For $2^4$, it is clear $2^{2017} \equiv 0 \pmod {2^4}$.
For $5^4$, we use following theorem

For $a,b \in \mathbb{Z}_{+}$ such that $\gcd(a,b) = 1$, we have $$a^{\varphi(b)} \equiv 1 \pmod b$$ where $\varphi(\cdot)$ is the Euler totient function.

For $a = 2$ and $b = 5^4$, we have $\varphi(5^4) = 4(5)^3 = 500$. This leads to
$$2^{2017} = 2^{4(500)+17} \equiv 2^{17} \equiv 65536\times 2 \equiv 1072\pmod {5^4}$$
It turns out we are lucky. Since $1072 \equiv 0\pmod {2^4}$ already, we don't need CRT to conclude $2^{2017} \equiv 1072 \pmod {10^4}$.
As a result, the last $4$ digits of $2^{2017}$ is $1072$.
Comment: Another coincidence is that the answer uses same digits as the exponent 2017. +1
Answer: Hint: You want to find $2^{2017} \bmod 10000$. To do that, it suffices to find it $\bmod 16$ and $\bmod 625$. Finding it $\bmod 16$ is easy; to find it $\bmod 625$, use Euler's theorem that, if $\gcd(a,n)=1$, then
$$a^{\varphi(n)} \equiv 1\bmod n,$$
where $\varphi(n)$ is the Euler totient function. Can this reduce $2^{2017}$ into something more manageable?
Comment: We need $\pmod{10^4}$ right?
Comment: @labbhattacharjee Yes. I've fixed my answer.
Answer: Like  How to find last two digits of $2^{2016}$,
I shall find $2^{2017-4}\pmod{10^4/2^4}$
As $2^2=5-1$
$\displaystyle2^{2012}=(5-1)^{1006}\equiv1-\binom{1006}15+\binom{1006}25^2-\binom{1006}35^3\pmod{5^4}$
Now $\displaystyle1006\equiv6\pmod{5^3}\implies\binom{1006}15\equiv5\cdot6\pmod{5^4}$
$\displaystyle\binom{1006}2\equiv15\pmod{5^2}\implies\binom{1006}25^2\equiv5^2\cdot15\pmod{5^4}$
and $\displaystyle\binom{1006}3\equiv0\pmod5\implies\binom{1006}35^3\equiv0\pmod{5^4}$
$\displaystyle\implies2^{2012+1}\equiv2(1-5\cdot6+5^2\cdot15)\equiv346\cdot2\pmod{5^4}$
Multiply out by $2^4$
Comment: A little more efficient than my binomial method I think.
Answer: This is a particular case of computing $a^k$ modulo $n$. Here $n=10000$.
The systematic method for doing this is "repeated squaring". As
$2^{2017}=2(2^{1013})^2$, first work out $2^{1013}$ modulo $10000$,
that is its last four digits. If these last four digits form the number
$a$ then $2^{2017}\equiv 2a^2\pmod{10000}$, so find the last four digits
of $2a^2$.
Of course to find the last four digits of $2^{1013}$ one proceeds recursively: $2^{1013}=2(2^{506})^2$, so find the last four digits of $2^{506}$ etc.
Answer: To compute this in terms of powers of $5$ and reduce modulo $5^4$ you can compute $$2^{2017}=2\cdot (1-5)^{1008}\equiv 2\cdot\left(1-5\binom{1008}1+25\binom {1008}2-125\binom {1008}3\right)\equiv$$and because of the factors $5^r$ you can reduce the binomials modulo $125, 25, 5$ respectively so $$\equiv2\cdot\left(1-5\cdot 8+25\cdot3-125\cdot 1\right)\equiv $$(which I did in my head using the indicated short cut) $$\equiv2\cdot-89\equiv 447$$
And $447$ leaves remainder $-1$ when divided by $16$ while $625$ leaves remainder $1$, so $447+625=1072$ will match residues modulo both $16$ and $125$.
Answer: As others have noted, you want $2^{2017} $ mod $10000$.
Using the Carmichael function of $10000=2^45^4$, which is $5^34=500$,
we have $2^{2017}\equiv{2^{17}}=131072\equiv1072\bmod10000$.


Collaborative Filtering: How to update user vectors online?

Question: As the subject says:
How would one update user vectors online while having static item vectors? Run the learning step only on the user vectors? But that would still take too much time to be considered online I guess.
From Logistic Matrix Factorization for Implicit Feedback Data:

A common practice for collaborative filtering based recommender systems is to first learn a set of item vectors and then update user vectors more frequently in an online fashion while keeping the item vectors static. Recommendations can then be computed in real time by performing an approximate nearest neighbor (ANN) search over the space of item vectors in I. ANN search requires keeping a data structure such as a k-d tree or locality sensitive hashing (LSH) based trees in RAM. The size of these data
  structures is proportional to both the number of items as well as the dimensionality of the latent factor vectors and so reducing the number of latent factors can greatly reduce the size of these objects.
Answer: Yes, it's probably referring to running the optimization for user vectors only.
Note that the paper you've referred to does alternating minimization in the user and item latent factors, so optimizing only the user factors is actually much faster than optimizing the full model.
Moreover, for fixed item factors, the objective separates across users; when you get a new signal from a user, you only have to retrain that user's latent vector, which should be quite fast and easily achievable online.


$pq+1$ is a square $\iff$ $p$ and $q$ are twin primes

Question: This exercise if from Beachy and Blairs Abtract algebra book.
Assume that $p$ and $q$ are primes.
Show that: $pq+1$ is square $\iff$ $p$ and $q$ are twin primes.
The backward direction is:
Assume that
$$p=q+2$$
then
$$pq+1=q^2+2q+1=(q+1)^2.$$
For the forward direction: we assume that
$$pq+1$$
is a square that is
$$pq+1=n^2\Rightarrow pq=(n-1)(n+1).$$
Now since $p$ and $q$ are primes by assumption and prime factorisation is unique we have
$$p=n-1\qquad q=n+1$$
so $p$ and $q$ are two apart therefore are twins.
First of all in my original question I forgot a really important assumtion that both of $p$ and $q$ are primes from the beginning. I am sorry for this mistake. So some of the comments may be irrelevant now when I edited the question (I hope it is correct now). Thanks for the comments and again sorry for the incorrect citation of the question.
Comment: Are you sure that $p$ and $q$ being primes is not a hypothesis for the whole of the "if and only if"?
Comment: This is an old question with several solutions on the web, e.g., see [here](https://answers.yahoo.com/question/index?qid=20080626165502AATdpqp), or [here](http://mathhelpforum.com/number-theory/105603-primes-squares.html).
Comment: $p=2$, $q=4$ satisfies $pq+1=n^2$ but $p$ and $q$ are not twin primes.
Comment: Well, for example $15^2 = 225 = 14 \times 16 +1$ but $14$ and $16$ are not primes ...
Comment: @PabloRotondo you were totally correct! thank you for the comment
Answer: Yes, you are missing somethin, in fact your proof is wrong on at least two points.

First of all, you need to assume that $p$ and $q$ are primes for the forward direction to even work, since otherwise, you could have $p=6$ and $q=4$ to get $pq+1=25=5^2$.
Second of all, you go from
$$pq=(n+1)(n-1)$$ straight to "therefore, $p$ and $q$ are two appart, which is faulty logic since you assume $$ab=cd \implies \{a,b\}=\{c,d\}$$ which is false in general. For example, $3\cdot 8 = (5+1)(5-1)$, however that does not mean that $\{3,8\}=\{4,6\}$. Of course, if you know that $a$ and $b$ are primes, then it is possible to show this, but still, you can't just assume it is true.

After the edit:
Your proof is now correct. Using the unique factorisation is a quick and easy way to prove the statement, and it's also clear why you need to assume $p,q$ are primes (and how $4,6$ fails in that step).
Comment: @Vinyl_coat_jawa If you correct your proof by editing the question, I will be happy to review it. Just leave a message in the comments to my answer so I get a notification.
Comment: I think the fact that the OP shows with its "proof" that he does not need the fact that $p,q$ are twin primes to show that $pq+1$ can be a square demonstrate at minimum that the assumption (the equivalence) is flat wrong, as you yourself demonstrated. in fact $ n \in \mathbb{N}, n(n+2)+1$ is a square, trivially...
Comment: ok. I get to it straight away. thank you again
Comment: i edited now, I think it is correct.
Comment: @Vinyl_coat_jawa Your proof is now correct. Using the unique factorisation is a quick and easy way to prove the statement, and it's also clear why you need to assume $p,q$ are primes
Comment: exactly, again sorry for the wrong question. but now my question is not a question anymore, so how to remove it? this is something I usually wonder about
Comment: @Vinyl_coat_jawa Since people can still learn from your question, you shouldn't remove it. Instead, I suggest you accept my answer...
Comment: ok, actually i do not think I can remove it.


Filtrar Array e retornar um novo array com os objetos que foram filtrados

Question: Utilizando Javascript, criei uma função o mais simples possível que receba um _Array_ de objetos Pessoa (exemplo: {name: "Alex", age: 24}) que retorne um novo _Array_ somente com os objetos Pessoa que possuem idade entre 20 e 30 anos.
function Pessoa(nome, idade) {
    this.nome = nome;
    this.idade = idade;
}

var alex = new Pessoa("Alex", 20);

if (idade >= 20 && idade <= 30) {

}

Acho que está um pouco errado, alguém poderia me ajudar?
Comment: Está muito errado. Não vou fazer para você. Mas já sabe o que é *array*? Sabe como criá-lo? Se não sabe esse exercício é avançado demais para você. Sabe como criar função, entende o conceito? Precisa entender bem como essas coisas funcionam antes de fazer isto.
Comment: Você nem mesmo criou um objeto Pessoa. E essa idade dentro desse if, ela nem sequer existe. E se for mesmo um array de objetos, você vai precisar de um foeach pra iterar em cada objeto dos itens do array.
Answer: A principio você pode usar a função filter para realizar a tarefa, por exemplo;
const inventors = [
  { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
];

var olders = inventor.filter(function(inventor){
    return inventor.year >= 1500;
});

console.log(older);

a variavel olders tera um array com os objetos onde a condição foi suprida (year >= 1500)
Na sua função você poderia fazer basicamente.
function pessoa(objec) {
    var olders = objec.filter(function(person){
        return person.age >= 20 && <= 30;
    });
    return olders;
}


Why is Nginx not parsing .php5 files the same as .php files?

Question: I have installed nginx with ISPconfig. Everything works fine except some websites I have ported from apache server unfortunately have .php5 extension and I don't know how to make nginx to parse them. I have tried many solutions and variations, but still can't make it work.
I will paste my settings from files, and if someone had similar experience that want to share, I would be thankful.
Part of settings from files:
/etc/php5/fpm/php.ini

cgi.fix_pathinfo=0

/etc/nginx/sites-available/default
server {
        listen 80 default_server;
        root /usr/share/nginx/html;
        index index.html index.php index.htm;
        location / {
                try_files $uri $uri/ /index.html;
        }
}
location ~ \.php$ {
        #       fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #       # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        #
        #       # With php5-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php5-fpm:
        #       fastcgi_pass unix:/var/run/php5-fpm.sock;
        #       fastcgi_index index.php;
        #       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #       include fastcgi_params;
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

Vhost configuration file for specific domain that has error:
      location ~ \.php$ {
            try_files /58c4be432bbd2af65343c142b9ec45ec.htm @php;
        }

        location @php {
            try_files $uri =404;
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:9048;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
        }

        location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }
/etc/php5/fpm/pool.d/www.conf has unCommented:
security.limit_extensions = .php .php3 .php4 .php5
And when someone access that .php5 page (website has over 500 backlinks to them) browser starting to download, like php-fpm is not parsing .php5 file:
XX.XXX.X.XXX - - [26/Feb/2014:22:53:07 +0000] "GET /sitemap.php5 HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36"
XX.XXX.XX.XXX - - [26/Feb/2014:22:54:27 +0000] "GET /index.php5 HTTP/1.1" 200 71941 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"
XX.XXX.X.XXX - - [26/Feb/2014:22:56:43 +0000] "GET /sitemap.php5 HTTP/1.1" 200 71941 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"
How can I setup nginx to parse .php5 pages like .php?
Thank you in advance.
Comment: @MichaelHampton Hi, I have checked file permissions, ownership, limit extenstions, error/access logs, different location ~ \.(php|php5)$ directives, different nginx config setups, but nothing. I got every time errors for example 206, 304, 403 or just getting file to be downloaded (not parsed). Any idea what should I check?
Answer: If you make every line with:
      location ~ \.php$ {

look like:
      location ~ \.(php|php5)$ {

It should do what you want.  Leave the @php lines alone (@php is an internal block).
That regex could be shorter of course but it would be less clear.
ALSO:
In your location @php block pass to the socket instead of localhost:
      fastcgi_pass unix:/var/run/php5-fpm.sock;

Comment: I have tried the same :\  and I have even tried to copy the same \.php$ code and just to add the php5. I got this kind of errors (access denied):

2014/02/28 14:42:06 [error] 11553#0: *13 FastCGI sent in stderr: "Access to the script '/var/www/site.com/web/sitemap.php5' has been denied (see security.limit_extensions)" while reading response header from upstream, client: 18.104.22.168, server: site.com, request: "GET /sitemap.php5 HTTP/1.1", upstream: "fastcgi://127.0.0.1:9048", host: "www.site.com", referrer: "http://site.com/"
Comment: p.s. After every change I restart php5-fpm and nginx to be sure..but still no progress
Comment: THANK YOU @quadruplebucky!!! I am so happy :) it works now when I added fastcgi_pass unix:/var/run/php5-fpm.sock;  you are king!
Comment: the reason that works is because fastcgi_param (environment vars) don't survive "outside" (on the network) but are preserved when php-fpm accesses a local unix socket.
Comment: @quadruplebucky, I have same problem. I have raised a question here. can you please look once. http://stackoverflow.com/questions/33409539/nginx-shows-php-code-instead-of-executing
Comment: Instead of `location ~ \.(php|php5)$ { ... }` you can use more simple `location ~ \.php5?$ { ... }`


java 8 - how to group by every element from the list

Question: I have 2 lists: 'groups' and 'people'. In the end I want to get a map grouped by every 'group'.
The code below doesn't compile due to last flatMap method, saying that 'Non-static method cannot be referenced from a static context'.
private static Map<Group, List<Person>> getAllGroupsOfSelectedPeople(List<Person> people) {
       List<Group> groups = getCurrentlyActiveGroups(people);
       return people.stream()
               .filter(p -> CollectionUtils.isNotEmpty(p.getSocials()))
               .filter(p -> p.getGroups().stream().anyMatch(groups::contains))
               .collect(Collectors.groupingBy(p -> p.getGroups().stream().flatMap(List::stream)));
   }

Comment: Could you share Group and Person main methods ?
Answer: flatMap should be used before the collect step, to generate all pairs of Group and Person. Then you can group these pairs.
private static Map<Group, List<Person>> getAllGroupsOfSelectedPeople(List<Person> people) {
       List<Group> groups = getCurrentlyActiveGroups(people);
       return people.stream()
               .filter(p -> CollectionUtils.isNotEmpty(p.getSocials()))
               .filter(p -> p.getGroups().stream().anyMatch(groups::contains))
               .flatMap(p -> p.getGroups()
                              .stream()
                              .map(g -> new SimpleEntry<Group,Person>(g,p)))
               .collect(Collectors.groupingBy(Map.Entry::getKey,
                                              Collectors.mapping(Map.Entry::getValue,
                                                                 Collectors.toList())));
}


Can brownian motion have two indices?

Question: Is there such a thing as Brownian motion with two indices? In particular, does something like this exist: $$W_t(s)= \epsilon_t \sqrt{s}\,,$$
where, for fixed $t$, the usual properties hold:

$W_t(0)=0$.
$s \to W_t(s)$ is continuous in $s$.
$\{W_t(s)\}_{s\geq0}$ has independent stationary increments in $s$
for any $s$, $W_t(s)$ is $N(0,1)$,

but where, additionally, for fixed $s$, $W_t(s)$ is a discrete-time normal random variable, following, say, an AR(1) process with respect to $t$?
The $s$-index would be spatial, for instance, and the $t$-index temporal.
How would one handle conditional expectations $\mathrm{E}_t[\cdot]$, $\mathrm{E}_s[\cdot]$,
$\mathrm{E}_{s,t}[\cdot]$?
Answer: You might be interested in multivariate Brownian motion. That is, a Brownian motion that takes values in $\mathbb{R}^d$ rather than $\mathbb{R}$. You can then take $t=1,...,d$. If you choose an appropriate covariance matrix, this should result in a sample of length $d$ of an AR process, at each time point.
There are also generalizations to infinite dimensions.
Comment: I see, that's a nice suggestion, thank you! And the AR coefficient, call it $\rho$, would then be determined by the covariance matrix that one assumes?
Comment: It's the other way around: the AR coefficient determines the covariance matrix. Not all covariance matrices correspond to a Gaussian AR process, but each Gaussian AR process does correspond to a multivariate normal distribution with some covariance matrix.
Comment: Note that the covariance matrix for a particular AR process is unique if you assume stationarity (and otherwise it is not, because you can choose an arbitrary initialisation)

Can brownian motion have two indices?


Why doesn't UITextfield bind value when selected `My Own Password` after field is autofilled?

Question: This is how I define actions for my password UITextFields:
mainView.passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag)

mainView.passwordTextField.rx.controlEvent([.editingChanged])
        .asObservable()
        .subscribe { [mainView, viewModel, weak self] ale in
            print(">>>>>")
            print(viewModel.password.value)
            self?.updateView()
        }.disposed(by: disposeBag)

And this is how it look like after password autofill is called there:
>>>>>>
cckSG%in51ZZ65y

And when I select from suggest autopassword My own password all fields are reset and are empty, but nothing is called. And in viewModel.password.value there is still previous non empty value. How can I resolve it?
Answer: I'm not sure entirely what the problem is based on the description but please be aware that .rx.text and .rx.controlEvent() only report changes made by the user, not changes made programmatically. Maybe that is the confusion you are having?
Also, the code you post doesn't make too much sense. You are already binding the changes in passwordTextField to the view model's password property (I assume it's a BehaviorRelay). So why read from it in the subscribe when you are already writing to it in a different subscribe? You can't really be sure which subscribe's closure will be called first.
Answer: editingChanged is described as "touch event" in UIKit doc. So the system-provided autofill may be simulating touches. The field clearing effect of "My own password" then probably does not simulate touches. Try observe some other control events not related to touches, ultimately allEvents.
Thought #2: or subscribe to the text itself, not to the control events.


Getting and displaying network signal strength on a windows form

Question: Is there a way to acquire and display the current  wireless signal strength of an application's device in C#? I have an application that detects whether there is connectivity via a timer, however I need to know the current signal strength, then display it graphically in a status bar. Below is my current code to detect basic connectivity every few seconds. What can I add to display the strength as well? Thank you. The timer code was given by  S.O. user :parapura rajkumar
<code> private void Form1_Load(object sender, EventArgs e)
    {
        //create an object to hold app settings FIRST

        appsetting apps = new appsetting();
        apps.getsetting();
        netMessage.Clear();

        //creates a timer for refresh rate on connectivity check

         var timer = new Timer();
         timer.Tick += new EventHandler(timer_Tick);
         timer.Interval = 2000; //2 seconds
         timer.Start();
    }

    //starts the timer
 void timer_Tick(object sender, EventArgs e)
 {
    //if connection is not detected
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() ==f
    false)
    {
        //clear the buffer
        netMessage.Clear();

        //turn RED indicator on and display message
        netConnect.BackColor = Color.Red;
        this.netMessage.Text = ("No Connection");
        noConn = true;//set "No connection" to true
        conn= false;

    }
    else
        //turn GREEN indicator on and display message
        netConnect.BackColor = Color.Lime;
        this.netMessage.Text = ("Connected");
        conn = true;// set connection to "true
        noConn = false;

            //if box is red but connection is established, turn it back to green

            if (noConn == true &&
            System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() ==
            true)
            {
                 netConnect.BackColor = Color.Lime;
                 this.netMessage.Text = ("Connected");
                 conn = true;
                 noConn = false;
             }

}

    //need to display signal strength in a text box with color codes or status bar HERE
</code>
Comment: Perhaps [this answer](http://stackoverflow.com/a/3274126/1220971) to [this question](http://stackoverflow.com/questions/3273967/detect-wifi-connectivity-in-c-sharp) might help.
Answer: After some research and reference to some other questions, I was able to solve my issue via the open source API given at: managedwifi.codeplex.com
Simply download the api, then add it to your project via add->csproj.
Use 'public int RSSI' that is given in the WlanClient class.
Cheers


Where should I save files

Question: I've a question, not about code, but about a good practice.
I've searched on Google but I didn't find anything.
In my app (iOS) I have the possibility to download a file, but I don't know where I have to store it, for now I put it in the Documents folder, but I'm pretty sure that it's not its place.
If you have the answer, or a link that could explain where I have to store it, it could be helpful.
Thanks !
Answer: Apple has a strong opinion about that: https://developer.apple.com/icloud/documentation/data-storage/index.html
In short:

documents and user generated data -> Documents directory
downloaded and/or easily to regenerate -> Caches directory
temporary data -> tmp directory -

The location you use (and maybe properties you set) is important for how the backup works as well.
Comment: Thank you for the link ! It was exactly what I needed !
Answer: dont use temp directory to store data.then the path will unknown to user.save it on documents directory using the function called savetophotoalbum in IOS. it will save the datas on the Photos and also only limited space is allocated to an IOS app on your phone.it will last to crash in the future when you try to store lot of data on temp directory

Where should I save files


Menu interfering with my gridview control

Question: I implemented gridviewscroll from http://gridviewscroll.aspcity.idv.tw/Demo.aspx#Freeze
on my web application but the menu seems to hide behind the gridview like in the below picture:

the actual menu looks like this on other webforms:

My question is how do I send the gridview behind or how else can i work around this issue?
P.S. if you need any code to clarify things, ask me.
It works well on other GridViews, i tried increasing the z-index but it doesn't work.
nav ul ul {
    display: none;
}

    nav ul li:hover > ul {
        display: block;
    }
    nav ul {
    background: #FFF4D5;
    background: linear-gradient(top, #FFF4D5 0%, #bbbbbb 100%);
    background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
    background: -webkit-linear-gradient(top, #FFF4D5 0%,#bbbbbb 100%);
    box-shadow: 0px 0px 9px rgba(0,0,0,0.15);
    padding: 0 20px;
    border-radius: 10px;
    list-style: none;
    position: relative;
    display: inline-table;

}
    nav ul:after {
        content: ""; clear: both; display: block;
    }

    nav ul li {
    float: left;
}

    nav ul li:hover {
        background: #66FFFF;
        background: linear-gradient(top, #663300 0%, #663300 40%);
        background: -moz-linear-gradient(top, #663300 0%, #663300 40%);
        background: -webkit-linear-gradient(top, #663300 0%,#663300 40%);

    }
        nav ul li:hover a {
            color: #CC3300;

        }

    nav ul li a {
        display: block; padding: 25px 40px;
        color: #FFF4D5; text-decoration: none; z-index:-1;
    }

nav ul ul {
    background: #66FFFF; border-radius: 0px; padding: 0;
    position: absolute; top: 100%;
}
    nav ul ul li {
        float: none;
        border-top: 1px solid #6b727c;
        border-bottom: 1px solid #575f6a;
        position: relative;

    }
        nav ul ul li a {
            padding: 15px 40px;
            color: #663300;

        }
            nav ul ul li a:hover {
                background: #FFF4D5;
            }
    nav ul ul ul {
    position: absolute; left: 100%; top:0;
}

Answer: You need to increase the z-index property for the menu CSS
Comment: Are you adding the z-index high enough in the menu tree? It should be on the node that is a sibling of the node wrapping the grid
Comment: @JDandChips you are correct i was placing the z-index at an lower level, i took that out and placed it where my  is and it worked. thnx mate


Efficient synchronization primitives for a single-threaded async app in Rust

Question: I have a tokio-based single-threaded async app where using Arcs or other Sync types seems to be an overhead. Because there is no need for synchronization between threads, I am looking for something like tokio::sync::oneshot::channel, Sender and Receiver of which should be !Sync and could be wrapped into Rc instead of Arc.
Are there any specially crafted synchronization primitives for usage in
single-threaded async apps in Rust?
Comment: I'm not sure you understand the synchronization tools you're referring to. `Arc` is generally very low overhead - it's just a reference counted smart pointer, the only overhead is the atomic increment/decrement when it's cloned/dropped. Unless you're creating them in a hot loop, it shouldn't affect performance much. One-shot channels use an `Arc` internally, and so it's unlikely you could improve performance by using them instead of `Arc`.
Comment: @kmdreko Tokio also has [LocalSet](https://tokio-rs.github.io/tokio/doc/tokio/task/struct.LocalSet.html) which I am using successfully.
Comment: @apetranzilla Well, a hot loop is a very likely usage case, and why to pay for atomic operations if I don't need them?
Comment: We can't offer any advice without seeing more of your use case. Do you have some sample code?
Comment: @apetranzilla Of course. I will make short samples to demonstrate the problem and update the question (this may take some time)
Answer: You can take a look at the various Local types in futures-intrusive. E.g. the LocalOneshotChannel requires no mutex.
Comment: Thank you, that's a very interesting package written by you! I'm planning to do some testing and comparison later, and update the question to publish the results.


Performance difference between E5405 and X3460

Question: I'm looking at purchasing one of two servers. They're of similar specs except the CPUs. Server 1 comes equipped with 2 x E5405 and server 2 only has one X3460. I've got a few servers that are configured like the first server and while I'm very happy with the performance I'm wondering if I can do better with newer hardware.
The server will be used for hosting game servers - mostly for the Source engine.
Answer: This might help you out a bit: Intel's ARK comparison of the two.
X3460 = Newer, more threads (but not more cores), better clock speed, higher FSB, less (but faster) cache, more instruction sets, and much better virtualisation support.
Ideally, you want two X3460's and I can't imagine the price difference would be that much more than two E5405's.This is not possible, due to what Chopper 3 pointed out below
Unfortunately though looking at a spreadsheet doesn't really tell you much about how it's going to work in real life.
Personally, I would bite the bullet and try it. If it's inferior (because you need more cores, not more raw speed) then you've got the option of adding a 2nd processor (for additional cost), or waiting until you need another server and replacing it with the server of the first specs.
I know that's not an ideal answer though. Maybe your OEM will loan you one for a week to try it out?
Comment: Just out of interest the X3460 isnt dual-processor capable, the dual-processor capable version is the X5560.
Comment: @Chopper - thanks, I haven't dealt with single-socket xeons in a while. I missed that on their comparison...
Comment: Me neither but I'm a chip-geek :)
Answer: There was a huge overall leap in power between the 54xx series and 55xx models, both in terms of compute and memory/IO speed. I'd strongly recommend the newer chip.
Comment: That's what I'm thinking as according to most benchmarks the X3460 is twice as good.


To Be Filled By O.E.M. We are the 'OEM' and we don't know how to do it. Any hint?

Question:
We send appliances to customers, and since some days ago the machines come from a new vendor.
The machines have new BIOS and motherboards: http://www.dmtf.org/standards/smbios
We would like to use /sys/class/dmi/id to identify the machines, so they become unique by its serial number.
This is the output that we can get from id directory:
<code>id # for filename in *; do [[ -f ${filename} ]] && echo ${filename}: && cat ${filename}; done

bios_date:  07/12/2010
bios_vendor: American Megatrends Inc.
bios_version:  080015
board_asset_tag: To Be Filled By O.E.M.
board_name: To be filled by O.E.M.
board_serial: To be filled by O.E.M.
board_vendor: To be filled by O.E.M.
board_version: To be filled by O.E.M.
...
</code>
We have tried some tools to edit these BIOS values without success.

Has anyone edited DMI data before? Please teach me. :)
Comment: You should be asking your supplier, not us.
Comment: Thanks Robert, easier to read.    John, we are to small for them, they just sell, anyway we will try your approach once again.
Comment: if you're large enough to buy from them you are large enough to ask them to support the product you are buying.
Comment: The OEM is the _Original Equipment Manufacturer_. If you buy the machines from someone else, then the someone else is the OEM, not you. You need the OEM to configure that.
Comment: The OEM in this case is the motherboard manufacturer, not you.
Answer: If you are the OEM then you should have an account with your BIOS provider, and your BIOS provider should be supplying you with a utility to customize the BIOS.
Comment: We are the OEM was just a mater of speeak. We are a small company buying stuff directly to the manufacturer. we are not the OEM, otherwise the question would be just silly.
Answer: Have you tried some of regular bios editors, like Award bios editor, AMI bios editor.
Some of them will let you edit basic fields or depends on how updated bios editor is...
I've seen cases where manufacturer gives utilities to edit basic fields in the BIOS, it's worth of trying and asking such utility (post logo, your own serial number or so).
Comment: Not since 2011. :)


Can a thread call .WaitOne() of a Mutex more than once before calling .ReleaseMutex() and vice versa?

Question: In my code, it would be convenient if my thread calls .WaitOne() more than once before calling .ReleaseMutex().
And vice versa:  Calling .ReleaseMutex() a few times before restarting a loop which begins with call to .WaitOne().
Some operating systems / compiler combinations allow this.  Some don't.
Comment: What happened when you tried it?
Answer: The .NET System.Threading.Mutex class uses a Win32 kernel mutex object which is re-entrant.  The following note from the documentation explains correct usage:

The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex.

Clearly then, the OS is counting the number of times the mutex is entered -- it is NOT a binary state of "locked or unlocked" (beside the count, there's an additional state of "abandoned").
Answer: Mutex has 2 state only: locked or unlocked. It can't be locked twice or unlocked twice. Something that you want is Semaphore: See Here. Semaphore has counter and after each WaitOne counter decreases by 1, and after each call of Release counter increases by 1.
Comment: Not a semaphore, but a recursive mutex - those are different.


Why does gradient descent fail training a network for predicting times table?

Question: I am training a feedforwardnet with gradient descent traingd as backpropagation algorithm to predict times table.
X = [repmat([1:10]', 10, 1) repelem([1:10]', 10)];
y = X(:, 1) .* X(:, 2);

net = feedforwardnet(8);                % Create a neural network with 8 neurons in the hidden layer
net.layers{1}.transferFcn = 'logsig';   % Hidden layer activation function set to logsig
net.trainFcn = 'traingd';               % Set backpropagation algorithm to gradient descent
net.divideParam.trainRatio = 0.6;
net.divideParam.testRatio = 0.2;
net.divideParam.valRatio = 0.2;
[net, TR] = train(net, X', y');         % Train the network

But when I try to train my network it directly fails, I mean validation error keeps increasing from the start as you can see below.

I couldn't figure out the reason so I wanted to ask it here.
When I train my network using Levenberg-Marquardt trainlm as backpropagation algorithm then everything works fine.
Answer: Some hypotheses:

Scaling the data could improve the conditioning of the problem. See: In Machine learning, how does normalization help in convergence of gradient descent?
Training a neural network is hard in general; maybe a different configuration of hyperparameters (especially learning rate) would allow gradient descent to succeed. See: What should I do when my neural network doesn't learn?
Gradient descent isn't a very good optimizer; LM is way better. And we should hope that LM is better, because it's doing more work to find a good direction! So in this sense, it's not surprising that gradient descent doesn't do a great job compared to LM.
Here's a fun comparison of SGD and LM on a very simple problem:

I bet a lot of you have tried training a deep net of your own from scratch and walked away feeling bad about yourself because you couldn't get it to perform.
I don't think it's your fault. I think it's gradient descent's fault. I'm going to run gradient descent on the simplest deep net you can imagine, a two layer deep net with linear activations and where the labels are a badly-conditioned linear function of the input.
  $$
\min_{W_1,W_2} \mathbb{E}_x \left\|W_1 W_2 x - Ax \right\|^2
$$

Here, the condition number of $A$ is 1020. Gradient descent makes great progress early on, then spends the rest of the time making almost no progress at all. You might think this it's hit a local minimum. It hasn't. The gradients aren't decaying to 0. You might say it's hitting a statistical noise floor of the dataset. That's not it either. I can compute the expectation of the loss and minimize it directly with gradient descent. Same thing happens. Gradient descent just slows down the closer it gets to a good answer. If you've ever trained Inception on ImageNet, you'll know that gradient descent gets through this regime in a few hours, and takes days to crawl through this regime.
The black line is what a better descent direction would do. This is Levenberg-Marquardt.
If you haven't tried optimizing this problem with gradient descent, please spend 10 minutes coding this up or try out this Jupyter notebook. This is the algorithm we use as our workhorse, and it fails on a completely benign non-contrived problem. You might say "this is a toy problem, gradient descent fits large models well." First, everyone who raised their hands a minute ago would say otherwise. Secondly, this is how we build knowledge, we apply our tools to simple problems we can analyze, and work our way up in complexity. We seem to have just jumped our way up.

From Ali Rahimi and Ben Recht. "Reflections on Random Kitchen Sinks."  argmin.net blog. Dec. 5, 2017.
Comment: Oh so I guess this normalizes outputs, hence errors. I misunderstood it I guess.
Comment: Well, I've finally figured it out. It turns out that I had to normalize the error (`mse`) as well. But why is that? I'd never read about it anywhere else before. Could you please explain that briefly? Or if you have any sources that explain, I would appreciate it. In MATLAB I had to specifically use `net.performParam.normalized = 'standard'` but in R I had no problem with that, don't know whether it is normalized by default in R though (using `neuralnet`).
Comment: @AndréYuhai When you say "normalize the error" what do you mean? Are you normalize the *target* variable? Or something else? Reading the documentation will explain how `neuralnet` works.
Comment: Couldn't really find any link to the explanation on MATLAB's website but this is what I get when I use `help` command.
"'normalization' - this can be 'none' (the default), or 'standard', which
    results in outputs and targets being normalized to [-1, +1], and
    therefore errors in the range [-2, +2), or 'percent' which normalizes
    outputs and targets to [-0.5, 0.5] and errors to [-1, 1]."
Comment: The input data is being mapped to [-1, 1] by default using `mapminmax`, I will try fiddling with the learning rate and will read the links you've shared. Thank you. :)
Comment: @AndréYuhai yeah, I don't use matlab so I didn't know that.
Comment: Oh, I should've mentioned. Sorry. :)


App Engine Flex service is running but it cannot be found

Question: How do I shutdown an App Engine Flex service that I already deleted and cannot access?
Yesterday I deployed a new App Engine Flex service which I then deleted. For whatever reason the service is still running a day later. I can confirm by looking at the logs viewer that it's still running and generating logs.
When I go to the GCP console, it doesn't show the service, or a version or an instance of it running, yet it's definitely running.
It's as if there's an orphaned instance running.
Comment: Sometimes the instances don't get killed when you delete a service because some requests are still pending. Normally after some time (maybe 24 hours, depending on the scaling settings),  the requests timeout and the instance gets killed. Since it's been some time since you posted the question, can you confirm that the instance has already been killed?
Comment: I'm having the same problem. It's been quite a few days now.
Comment: @TasosZG It finally shut itself down this morning after 6 days.
Comment: We're also experiencing this issue with app engine for Ruby.
It is pretty annoying because it exhausts our 3rd party api quotas and messes up the background job processing.

related topic: https://groups.google.com/forum/#!topic/google-appengine/RNtQq2tjdU0
Answer: To kill a Google App Engine you should go into the settings menu and select disable application.
You can take a look into the Managing GCP Projects, App Engine Applications, and Billing Documentation.
Also, you can take a look at this Cleaning up documentation if you want to see more related information.


How to add a custom field to personal campaign page - Civicrm

Question: I'm using Drupal 7 and Civicrm 4.4.1 and I enabled the Personal Campaign Pages so individuals can create campaigns.  It comes with the standard default fields such as Title, Goal Amount, Welcome, and Your Message.  I would like to add another field to that form which I can then access through views to display in a table.
The field I'd like to add is called sponsor, so I could then show the sponsor when listing a view of all Personal Campaign pages.  I've tried creating a custom field dataset and applying it to the Contribution type that I'm using, but I didn't have any success.
Any ideas on how to create a custom field for these pages?
Answer: At this time, you cannot currently add custom data to Personal Campaign Pages (see the list at example.org/civicrm/admin/custom/group?action=add&reset=1).  If you wanted to do that, your best bet would be to write the code (or pay someone to write the code) that does this, and get this contributed back into CiviCRM.
Answer: https://drupal.org/node/2234823

Using CiviCRM Custom Data Profiles
If your Drupal website is integrated with CiviCRM, you have an opportunity to bring much more personalized content into the Drupal user profile page through CiviCRM's Contact Record Fields. The most straight forward way to bring CiviCRM contact record data to the Drupal user profile page is by configuring the appropriate CiviCRM Custom Data Profiles to be visible in the Drupal user profile page. This can be done by being logged in with permissions to administer CiviCRM, navigating to CiviCRM -> Administer -> Custom Data and Screens -> Profiles. Edit the Profile you would like to expose in the user profile page and adjust the setting for it to be used for: View/Edit Drupal User Account. You can also use these settings to remove CiviCRM content from the Drupal user profile page by un-setting it to be used for the Drupal User Account.
Comment: Whilst true, this answer doesn't actually relate to the question being asked.
Answer: Here's a patch to add custom field capability for PCP pages....
This diff is against CiviCRM 4.5.0
Doesn't output the custom fields on the template, but you can figure that part out :)
This will allow you to add custom field groups to the PCPs, and save values to them on PCP add/edit pages....
<code>diff -r original/civicrm/CRM/Core/BAO/CustomGroup.php new/civicrm/CRM/Core/BAO/CustomGroup.php
1102a1103,1104
>       case 'Pcp':
>         $tableName = 'civicrm_pcp';
1168a1171
>       case 'Pcp':
1521a1525
>
1698a1703,1704
>       case 'Pcp':
>         return 'civicrm_pcp';
1721a1728
>
diff -r original/civicrm/CRM/Core/SelectValues.php new/civicrm/CRM/Core/SelectValues.php
179a180
>       'Pcp' => ts('Personal Campaign Pages'),
diff -r original/civicrm/CRM/Custom/Form/CustomData.php new/civicrm/CRM/Custom/Form/CustomData.php
54c54
<   ) {
---
>   ) {
145c145
<     }
---
>     }
diff -r original/civicrm/CRM/PCP/BAO/PCP.php new/civicrm/CRM/PCP/BAO/PCP.php
85c85,92
<
---
>     //start custom field code addition
>     //store custom data
>     if (!empty($params['custom']) &&
>       is_array($params['custom'])
>     ) {
>       CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pcp', $dao->id);
>     }
>     //end custom field code addition
diff -r original/civicrm/CRM/PCP/Form/Campaign.php new/civicrm/CRM/PCP/Form/Campaign.php
63a64,87
>
>     //start custom field code additions
>     //check for custom data type.
>     $this->_cdType = 'Pcp';
>     $this->assign('cdType', FALSE);
>     if ($this->_cdType) {
>       $this->assign('cdType', TRUE);
>       $this->set('type', 'Pcp');
>       $this->set('entityID', $this->_pageId);
>       $this->set('cgcount', 1);
>       CRM_Custom_Form_CustomData::preProcess($this);
>     }
>     //end custom field code additions
>
>         // when custom data is included in form.
>     if (!empty($_POST['hidden_custom'])) {
>       $this->set('type', 'Pcp');
>       $this->set('entityID', $this->_pageId);
>       $this->set('cgcount', 1);
>       CRM_Custom_Form_CustomData::preProcess($this);
>       CRM_Custom_Form_CustomData::buildQuickForm($this);
>       CRM_Custom_Form_CustomData::setDefaultValues($this);
>     }
>
70c94,99
<
---
>     //load only custom data defaults.
>
>     if ($this->_cdType) {
>      $defaults = CRM_Custom_Form_CustomData::setDefaultValues($this);
>     }
>
93c122
<
---
>
103a133,140
>     $this->assign('customDataType', 'Pcp');
>     $this->assign('entityID', $this->_pageId);
>
>     if ($this->_cdType) {
>       CRM_Custom_Form_CustomData::buildQuickForm($this);
>     }
>     //lets assign custom data type and subtype.
>
229c266,274
<
---
>
>        //process custom data.
>     $customFields = CRM_Core_BAO_CustomField::getFields('Pcp', FALSE, FALSE);
>     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
>       $customFields,
>       $this->_pageId,
>       'Pcp'
>     );
>
232d276
<
Only in new/civicrm: groupcountsearch.txt
diff -r original/civicrm/templates/CRM/PCP/Form/Campaign.tpl new/civicrm/templates/CRM/PCP/Form/Campaign.tpl
97a98,120
>
> {* load the custom data *}
> {if $cdType}
>     {include file="CRM/Custom/Form/CustomData.tpl"}
> {else}
>
> {* include custom data js *}
> {include file="CRM/common/customData.tpl"}
>
> {literal}
> <script type="text/javascript">
>   CRM.$(function($) {
>     {/literal}{if $customDataSubType}
>       CRM.buildCustomData( '{$customDataType}', {$customDataSubType} );
>     {else}
>       CRM.buildCustomData( '{$customDataType}' );
>     {/if}
>     {literal}
>   });
> </script>
> {/literal}
>
> {/if} {* load custom data *}
99a123
>
</code>


How do you develop for a 1024x768 resolution?

Question: Hey everyone, I hope I'm asking this question in the right place and I apologize in advance if it's not. I'm completely new to making websites and am still very much in the process of learning. My question isn't anything coding specific, but what I want to know is what are the general guidelines I should follow for making a site fit into a 1024x768 resolution? For example, working in percentages rather than pixels. I'm currently working on a 15inch macbook pro at a 1440x900 resolution for reference if that matters. I hope this isn't a completely vague question, and thank you in advance for any help.
Comment: Best to rephrase your question to either "How do you develop for 1024x768" or "How do I make websites that scale up and down nicely between 1024x768 and 1920x1200"
Answer: This very much depends on the type of website you want to make. When you are learning, the best way is to look at other sites that look and feel similar to what you're trying to achieve and have a look at their CSS. Don't copy their CSS outright, but try to understand how they implement different parts of the design.
Generally though, since you are going the fluid layout route (the best way for a generic site IMO), is to provide relative values for widths etc., and follow that up with absolute values for the min/max values for width etc. For example you may have something like the following for some container div in your design:
div.contentbox
{
   width:80%;
   min-width:800px;
   max-width:1280px;
}

You may have to look at floating divs to make sure they stay aligned to the edges at different browser sizes, you may want to look at keeping things centred using margin:auto.
There are loads of tricks you generally go through to keep a site looking same-ish in different browser sizes. The best thing for you is to start making it, and and when you have a specific problem, google it (someone's bound to have faced a similar problem in the past), and if you got nowhere or need a bit more help, ask here.
Answer: Google around for the "960 design": you're not alone if you fix your website content width to 960 pixels, which will fit nicely in 1024x768 screen resolution.
The other option is of course to generally use "fluid" layouting where the site will look nice on any resolution.
Comment: Thanks, I think the fluid layout sounds the most appealing since I do want to accomodate for bigger sizes as well.