Getting all the related doc and aggregate data from selected doc in single n1ql query

Question: I have just started with couchbase and i have following requirement
I have following docs:
referral doc
<code>{
    "_id": "8c658e34-34cc-4e61-8b26-5abc1cebd95e",
  "_metadata": {
    "created_at": 1472550145662,
    "created_by": "api-tenant-1"
  },
  "_type": "UWTrans",
  "amount": 4,
  "reference": {
    "refTranId": "0c0133f4-ade7-4190-8a43-a59de43846b4",
    "refTranModule": "NSP",
    "refTranType": "BUY"
  },
  "source": "WALLET",
  "tranType": "REFERRAL",
  "userId": "BJsMyG57c18f13"
}
</code>
Now i need to have all the referral doc for specific user id and i also want sum of all the referral amount like this
<code>[
  {
     "totalAmountEarned": 16,
     "transactions": [{
         "_id": "8c658e34-34cc-4e61-8b26-5abc1cebd95e",
         "_metadata": {
             "created_at": 1472550145662,
             "created_by": "api-tenant-1"
         },
         "_type": "UWTrans",
         "amount": 4,
         "reference": {
             "refTranId": "0c0133f4-ade7-4190-8a43-a59de43846b4",
             "refTranModule": "NSP",
            "refTranType": "BUY"
         },
        "source": "WALLET",
        "tranType": "REFERRAL",
        "userId": "BJsMyG1s57c18f13"
     },{
         "_id": "8c658e34-34cc-4e61-8b26-5abc1cebd95e",
         "_metadata": {
             "created_at": 1472550145662,
             "created_by": "api-tenant-1"
         },
         "_type": "UWTrans",
         "amount": 12,
         "reference": {
             "refTranId": "r58133f4-fd8-41h0-82t3-a59b783er6b4",
             "refTranModule": "URP",
             "refTranType": "SOLD"
         },
        "source": "WALLET",
        "tranType": "REFERRAL",
        "userId": "BJsMyG1s57c18f13"
     }]
  }
]
</code>
i want output something like this or similar . I have tried with nest but didn't get desired output
Thank you in advance
Answer: try this query
<code>  SELECT sum(amount) AS totalAmountEarned, array_agg(d) AS transactions
    FROM default d WHERE _type = "UWTrans" AND userId = "BJsMyG57c18f13";
    [
      {
        "totalAmountEarned": 16,
        "transactions": [
          {
            "_id": "8c658e34-34cc-4e61-8b26-5abc1cebd95e",
            "_metadata": {
              "created_at": 1472550145662,
              "created_by": "api-tenant-1"
            },
            "_type": "UWTrans",
            "amount": 4,
            "reference": {
              "refTranId": "0c0133f4-ade7-4190-8a43-a59de43846b4",
              "refTranModule": "NSP",
              "refTranType": "BUY"
            },
            "source": "WALLET",
            "tranType": "REFERRAL",
            "userId": "BJsMyG57c18f13"
          },
          {
            "_id": "8c658e34-34cc-4e61-8b26-5abc1cebd95e",
            "_metadata": {
              "created_at": 1472550145662,
              "created_by": "api-tenant-1"
            },
            "_type": "UWTrans",
            "amount": 12,
            "reference": {
              "refTranId": "0c0133f4-ade7-4190-8a43-a59de43846b4",
              "refTranModule": "NSP",
              "refTranType": "BUY"
            },
            "source": "WALLET",
            "tranType": "REFERRAL",
            "userId": "BJsMyG57c18f13"
          }
        ]
      }
    ]
</code>
Comment: Awesome buddy, Thanks .
Comment: You can also GROUP BY userId if you need to get results for multiple users.


Is it possible to create a method which is not contained within any class?

Question: I read a statement which says "a method is defined and contained within a Java class." But, I am curious how definite is this statement.
Is it ever possible to create a method (function) in Java which does not contain within a class?
Comment: And how would you call it? Every method needs to be defined in a class, because there's nothing else outside classes.
Comment: Why do you have doubts?
Comment: @Dadou Because in C#, a `struct` can be used to replace a `class`. I think there is no `struct` in Java, but just to play safe, I want to check with all the experts here whether it is definite.
Comment: @user3437460 you may want to check with the experts, but simple questions like this don't tend to get answers from them.
Comment: "*... which is not contained within any class?*" does interfaces count?
Answer: Until Java-8, the statement about all methods "being contained within a Java class" has been entirely true. However, with the introduction of lambdas in Java-8 there has been an additional place where a piece of code might appear - a lambda function. Unlike an anonymous class which is still a class, lambdas are a different kind of code-hosting entity.
Java-8 adds another place where a method could appear - an interface. The new language addition lets you specify default implementation of a method inside an interface. It does not mean that you can call it, but you can certainly host some executable code inside a Java-8 interface.
As far as "free-standing" methods go, no language addition has allowed them: all executable logic must be container within something else, but not necessarily a class.
Comment: @emory Would you mind explaining how you would implement a method which is not contained within any class? Interface methods do not implement methods; method implementations inside anonymous classes are inside classes.
Comment: You mean Java 8, don't you? ;-)
Comment: If I am not mistaken, lamda functions are inside classes.  Interfaces are classes.  Regardless, interfaces always could have methods - it is just that prior to 8, all interface methods were public and abstract.
Comment: @emory Interfaces are definitely not classes (outside reflection, anyway). As far as lambdas go, it's actually pretty tricky: the compiler plays it smart, avoiding behind-the-scene class creation when lambdas are non-capturing.
Comment: @dasblinkenlight I will take your word about lamdas.  If we allow that interfaces are not classes, then there is nothing new about java 8.  we have always been able to create a mehod which is not contained within any class.
Comment: `interface Runnable{void run()}`.  the run method is inside an interface not a class (if interfaces are not classes).
Comment: @emory I did write "would implement", as opposed to "would contain", on purpose: I wanted to avoid any ambiguity.
Answer: well...not totally. You can't do it at compile time, but you can do it on the fly. You can add bytes to a class on the fly. If you know the Java Virtual machine spec, you can do it, but i think you might also be able to do it with Apache's BCEL:
http://jakarta.apache.org/bcel/index.html
There are also other options. Make your class abstract, and don't implement that method. make an interface. But, yeah, you could create the byte-code for a method and tie it to a class at runtime.
Answer: No, methods are functions for the Class and must be created within the Class.
Outside the Class, they're illegal.
Answer:
But, I am curious how definite is this statement.

This is very definite.
No it is not possible. The methods should be there in a class.
And if you think logically also then you can find yourself that outside your class there is nothing. So from where you will call your method.
Answer: No it's not possible. Because Java is and always has been object orientated, whenever a program is ran it is ran inside of a class to allow for easier creation and integration of objects. There are however some object orientated languages in which you can create methods outside of classes such as PHP. With PHP this is because it never used to be object orientated  but was changed to operate in an object fashion.


Liberar acesso externo no sql server 2014

Question: tenho uma máquina na amazon, e está instalado o sql server porém não consigo acessar de fora do servidor. Gostaria de saber se há alguma configuração além de liberar o protocolo no Security group.
Answer: O erro mais comum é montar a string de conexão errada.
Você por acaso está adicionando a porta do ENDPOINT na string de conexão?
Você precisa copiar o nome do ENDPOINT (algo como sqlsvr-pdz.c6c8mdfntzgv0.us-west-2.rds.amazonaws.com) e depois colocar uma ',' e a porta de conexão do ENDPOINT, no final a string deve ficar algo parecido com isto:
<code>sqlsvr-pdz.c6c8mdfntzgv0.us-west-2.rds.amazonaws.com,1433
</code>
O ENDPOINT e a porta de conexão você consegue na tela do Management Consoles, na descrição do servidor, você tem essas duas informações.
Lembrando também que o usuário e senha a ser usado no MSSQL Management Studio é o usuário e senha do master user do SQL, não sua conta AWS.


git push - unbale to acess

Question: Ao tentar realizar um git push para o github o mesmo me retorna o seguinte:
git push fatal: unable to access https://github.com/renannasc/fsphpdeveloper.git/': Could not resolve host: github.com
Answer: Esse erro indica problema de conexão, pode ser causado por um antivírus que não seja o padrão fornecido pelo Windows, ou se você esta usando um servidor proxy para acessar a Internet, o Git requer uma configuração especial, pode ser também, uma regra de firewall, ou seja há várias coisas que podem estar causando esse problema.
Comment: A sim entendi muito obrigado!

Irei verificar

git push - unbale to acess


Why cannot use LINQ on DataRowCollection if its base class derives from IEnumerable

Question: I found that it is not possible to directly use LINQ over an instance of IEnumerable<T> i.e. System.Data.DataRowCollection
This class derives from the class System.Data.InternalDataCollectionBase which implements IEnumerable<T>, so it makes completely sense to being able to use LINQ functions over System.Data.DataRowCollection.... but I can't.
Check the following example:
using (DBConnection connExport = DBConnection.OpenConnection())
{
    DataTable dt = GetDataTableFromDatabase();

    DataRow dr1 = dt.Rows.First(); // This LINQ is not allowed
    foreach(DataRow dr in dt.Rows) // But enumerating it works fine
    {
            // Some processing...
    }
}

I have searched on the official docs of LINQ  where I found

The standard query operators allow queries to be applied to any Enumerable-based information source.

I know that the reason should be something very simple, but I cannot figure out what is it. So here I go:
Why is LINQ for instances of System.Data.DataRowCollection not allowed?
[EDIT]: There is already an answer for HOW to overcome this, but not to the WHY, so that's my purpose with this: to understand, not to overcome.
Comment: It's not `IEnumerable`. It's just `System.Collections.IEnumerable`.
Comment: Not the answer but _dt.AsEnumerable().FirstOrDefault()_ will allow you to use LINQ on a DataTable
Comment: Based on your edit you are also looking for *Why cannot use LINQ* Check the @EdPlunkett comment to know why you can't use LINQ. Simply because it is not  `IEnumerable`  that I have already mentioned in my answer too.
Comment: @monsieurgutix I tried but couldn't submit, since the question was already closed. Fifteen Pokémon points more or less is of no great consequence to me anyhow. The important thing is you got your answer.
Comment: I would love that @dasblinkerlight would share your thoughts on users finding an answer, not just closing any question and not coming back to realise that I was really asking for something diffrerent he thought of.
Answer: It's of type System.Collections.IEnumerable not IEnumerable<T> but you can use Cast or OfType to use LINQ here:
DataRow dr1 = dt.Rows.Cast<DataRow>().First();

Comment: As a alternative you can include `System.Data.DataSetExtensions.dll` then just do `dt.AsEnumerable().First()`


Why does computer name change require a reboot in Windows?

Question: I understand that changing the host name/computer name for a Windows based machine (Client or Server) requires a reboot. I realize that once a computer name is changed, a pending machine name is stored in the system registry and is applied on next boot. I was not able to find much technical documentation on exactly WHY this was required.
Can someone please point me in the right direction on the technical challenges behind why a host name change is not complete without a system reboot ?
Comment: Added a comment to the accepted answer with a link to an MSDN article on why a reboot is required.
Comment: I wouldn't say that the linked article explains *why* a reboot is required. After all, if it was just a matter of copying it to that other location, then the command to change the name could go ahead and copy it. The key sentence in the accepted answer is *"Many Windows services and applications, both those written by Microsoft as well as 3rd party, that use the system's hostname, typically only read it once at startup and never read it again."*
Answer: You don't have to restart immediately after renaming the machine... just don't expect every service and function to pick up on the new name.
Things such as system environment variables are read once, at system startup. If you change those variables, the various components of Windows won't pick up on them until they're restarted. Some of those components are so deeply integrated with the OS, you might as well restart the entire OS.
Many Windows services and applications, both those written by Microsoft as well as 3rd party, that use the system's hostname, typically only read it once at startup and never read it again.
I know if I was writing an application that read the machine's hostname, it would be pretty silly of me to periodically poll for it just in case it changed.
In an operating system such as Linux, you see the same thing. You can change the hostname without rebooting, but you do have to restart some very basic components of the system in order to get them to pick up on the new name. Linux is more modular than Windows, although Windows has come a long way in terms of modularity.
One way to detect whether a Windows system is pending a computer rename operation is to check the registry. If the contents of
HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName
and
HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName
are not the same, that means the system has a pending rename operation that will complete the next time the system reboots.
Comment: Thanks for the tip Ryan. I looked up the code for System.Environment.MachineName (using dotnetpeek). It uses the GetComputerName function in Kernel32.dll which: "Retrieves the NetBIOS name of the local computer. This name is established at system startup, when the system reads it from the registry." (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724295\(v=vs.85\).aspx). In other words, you're right its simply cached on startup. Just wanted some documentation to back it up. Thanks.
Answer: Here's a script for skipping the reboot: https://gist.github.com/timnew/2373475


System.ComponentModel.BackgroundWorker never invokes ProgressChanged

Question: I recently rewrote my Windows Forms application to use BackgroundWorker instances instead of using manually  created "worker threads". After checkin I noticed some tests started to fail. After some debugging I can demonstate my problems by showing you the following 2 tests:
<code>    [Test]
    public void Test_A()
    {
        bool progressChanged = false;
        var worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += (s, e) => worker.ReportProgress(0, null);
        worker.ProgressChanged += (s, e) => progressChanged = true;
        worker.RunWorkerAsync();
        Thread.Sleep(100);
        progressChanged.ShouldBeTrue();
    }

    [Test]
    public void Test_B()
    {
        //Creation of o form component causes (?) this test to fail, even do I dispose it
        var view = new Form();
        view.Dispose();

        bool progressChanged = false;
        var worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += (s, e) => worker.ReportProgress(0, null);
        worker.ProgressChanged += (s, e) => progressChanged = true;
        worker.RunWorkerAsync();
        Thread.Sleep(100);
        progressChanged.ShouldBeTrue();
    }
</code>
Test_A success while Test_B fails. This is regardless if I sleep 100 ms or 100 minutes. Why?? My production code seem to work though, but it is annoying not being able to have a regression test suite that works (I have other test creating Forms components and these tests must be executed BEFORE my test using BackgroundWorker)
The next step would be to examine the source code of BackgroundWorker, but before I do that I thought I`d check for help here.
Regards Michael
Answer: Add
<code>WindowsFormsSynchronizationContext.AutoInstall = false;
</code>
In Test_B() before anything else. The BackgroundWorker, wich is very UI (ie: Winforms) oriented, is wild guessing how to sync things, but not like you want. Have a look here for some explanation (especially from Scott Berry): WindowsFormsSynchronizationContext


Range Formula Between Two Values?

Question: I'm in the middle of programming something, and I really need a formula that can go from 0 to 1 depending on the distance an object is to another one. I can get the formula to return 1 if the objects' distance equals 0, but I need it to also take into account a minimum variable.
In short (and perhaps more accurately), if an object is beyond maxdist away, the formula should return 0 or less. If it's closer than mindist, it should return 1 or greater. I can clamp the values when necessary. This is what I have so far.
<code> blenddist = 1.0 - ( ( 1.0 / gimaxdist) * dist)
</code>
Where would I work in mindist to allow me to set the 'zero-point'?
Answer: Let $d$ be the distance, let $m$ be what you're calling $mindist$, let $M$ be what you're calling $maxdist$, let $b$ be what you're calling $blenddist$. Then $$b={d-M\over m-M}$$ does what you ask.
Comment: Thanks, I'll try it out right now.
Comment: Just tried it - it works perfectly. Thanks!

Range Formula Between Two Values?


If you invert a chord, doesn't it lose its defining bass note?

Question: If we invert the chords on a simple song on the piano, then we lose the tonic in the bass.
So doesn't the bass progression get lost (?)
I heard somewhere that to listen by ear one has to listen to the bass notes. But if we change the bass around then how would one hear the chord? doesn't the chord get muddied or something?
However it seems to me that most piano players invert their chords. So how do people get around this "problem"?
Comment: I think you mean you loose the root in the bass. The root note can be the tonic (if you have the tonic chord) but only 3 / 7 chords in an octave actually have the tonic note at all.
Answer: Chord inversion is effectively helping you to build a voicing / melody e.g. in the upper notes. So, not inverting a chord could be considered ineffective from a melodic point of view. Regarding the bass progression, you can still play the root with the left hand, if needed.
Answer: The way one of my music teachers explained it to me was that a root position triad was like a chair with four legs - very stable; a first inversion was like a chair with three legs - still stable, but less so; and a second inversion was like a chair with two legs - rather unstable!
It's not really 'accurate', of course, just a fun way of explaining it. And yet he (and I) would agree that yes - you do sometimes 'lose' something when you invert a chord, whether you think it's some sense of 'stability', or (as I do) some of the sense of consonance.
However, this is a good thing! Why? because we don't necessarily want every moment in our music to feel completely concordant, settled, and resolved; we want to have moments of lower consonance and less stability that lead the listener's ear to expect the piece to move forward towards consonance and stability.
The other benefit it gives you is to allow individual musical lines that move in a more interesting way. The shape of the bass line can capture the ear like any other melody, and by allowing it to move away from the root of the chord to other chord tones, you can give it a lot more freedom.
Answer: You don't lose the harmonic function of the chord. So, if you play a V in root position, 1st, 2nd or whichever inversion, it will work the same, no matter which note is on the bass.
This is because you don't change the chord per se, you just change the way the notes are arranged ( and especially the bass note )
Inversions are an easy way to make a simple chord progression interesting. It'd be boring to play the same chords over and over again, so you can create more interesting patterns by inverting them.
Also, the bass lines become way more interesting if you use inverted chords.
Answer: It's fine. Though there are certainly cases where you'd be more confident or not.
For instance if playing with a group that includes a bass player or bass-like instrument that is playing a bass line, it definitely doesn't matter if you play it. On the other hand if it's a song where the bass line is not just supporting the harmony but is a distinct and important riff itself, then somebody should probably be playing it. So when playing such a piece solo it may even be best to devote your left hand to it entirely.
But generally the answer is that it's fine. The harmonic function will still be felt. In fact, if you don't play inversions—or more accurately if your voicings aren't voice led from one to the next—you may be missing the some of the point of the harmony in that instead of a note moving to the next in a smooth and pleasing manner, it may make a large and potentially awkward intervalic jump.
Answer: Yes, the defining bass note (root) does get lost a little. No,the bass progression doesn't get lost. It's hardly going to be a progression if only the root notes are played in the bass. Other passing notes are usually involved, and they don't always lead directly to the next root. Yes, they can, but that becomes quite predictable, and in music, it's good to do things that the listener isn't expecting. So, playing, say, a C under a C chord is fine - especially in C, but with C,C,B,Bb in that bar, there's a good reason to play an A in the next bar, which looks like it's going to be an F chord. On a G abar, going back to C, a B bass works well, followed by an almost inevitable root C.
It all works, and really, there's no 'problem' to get around.
Answer: There is a difference between the root progression of chords and the actual bass notes used. The OP has touched upon what happens. One may have (for example) a chord progression of C-B0-C with the bass being E-D-C, it's not uncommon. Note that the first two chords are in first inversion. One hears a C chord then a B0 (diminished) chord then another C chord but simultaneously hears a stepwise descending bass line.
First inversions do not radically change the sound of a chord (they do change it though). First inversions are useful to keep the bass line moving when bass line with jumps may not be suitable. That's a decision a composer or arranger must make. Another possibility would be a chords C-B-C with chords being C-G-C or C-G6-C; in the first case the bass is C-G-C which is fine; in the second case the bass line would be C-B-C which moves less; also fine, but different.
Second inversion chords change the sound a bit more and are thus more complex to analyze. Sometimes the second inversions are used in a manner that the do not sound like the main chord at all, but rather as another chord with non-chord notes attached. In the classical Dm-C64-G7-C, the second inversion C64 sounds a bit like a G chord with a couple of notes moving to their "correct" places later. In other places a C-G64-C6, the G sounds like a G chord with a stepwise moving bass. Much depends on the point of view of the composer (or analyst); one can thing of a succession of chords or a bunch of melodies which coincide to produce chords at different places. Both are useful.


using 9 function of 21h interrupt in c++

Question: function 09h interrupts 21h
dx = offset of the text , ds = segment of the text
how can i obtain segment and offset in c++?
Answer: There are a few prerequisites to this answer:

You are using a compiler that generate 16 bit code since DOS calls only work in 16 bit mode and
Your compiler gets the concept of segments.

In which case it's:
char string [] = "Hello World$";
call_int21h_9 (&string);

where call_int21h_9 is something like:
call_int21h_9 (FAR char *string)
// the FAR above is important and very compiler dependent, it tells the compiler
// that the pointer is a 32bit pointer (16 bit segment and 16 bit offset)
{
  mov ah,9
  lds dx,string ; this loads the DS:DX segment:offset from the value on the stack
  int 21h
}

Further to this, there are several ways to compile a 16 bit application depending on how the segments are set up and used. The two most common are small and large (the compiler might call them something else):

Small: All segments are the same value and the total of data + code is < 64k
Large: All code and data exist in many segments and code + data < 1Meg

There are other layouts of segments (one data, many code; one code and many data, etc) and you'll need to consult the compiler documentation to see what's available.
Of course, your biggest problem is getting a compiler that does 16 bit.
Why not just use cout or printf?
Comment: Do you need to convert that to _modern_ C++ or _equally-obsolete_ C++ ?
Comment: cuz , i should convert this code from pascal to c++

Uses dos;
var r : registers;
    text : string[128];
begin
     text :='Hello$';
     r.ah := $09;
     r.dx := ofs(text)+1;
     r.ds := seg(text);
     intr($21,r);
end.
Answer: If you're in real mode, they're the upper and lower 16-bits (respectively) of a FAR pointer to the data.
Environments that use real-mode pointers and let you directly call software interrupts are really rare these days.  On any modern OS, you'd be using a user-mode wrapper which generates a sysenter instruction rather than int.
Answer: #include <dos.h>

FP_SEG(&var);

returns segment of var
FP_OFF(&var);

returns offset of var


is $y = \sqrt{x^2 + 1}− x$ a injective (one-to-one) function?

Question: I have a function  $y = \sqrt{x^2 + 1}− x$ and I need to prove if it's a Injective function (one-to-one).  The function f is injective if and only if for all a and b in A, if f(a) = f(b), then a = b
$\sqrt{a^2 + 1} − a = \sqrt{b^2 + 1} − b$
$\sqrt{a^2 + 1} + b = \sqrt{b^2 + 1} + a$
$(\sqrt{a^2 + 1} + b)^2 = (\sqrt{b^2 + 1} + a)^2$
$a^2 + 1 + b^2 + 2b\sqrt{a^2 + 1} = b^2 + 1 + a^2 + 2a\sqrt{b^2 + 1}$
$2b\sqrt{a^2 + 1} = 2a\sqrt{b^2 + 1}$
$b\sqrt{a^2 + 1} = a\sqrt{b^2 + 1}$
$(b\sqrt{a^2 + 1})^2 = (a\sqrt{b^2 + 1})^2$
$b^2(a^2 + 1) = a^2(b^2 + 1)$
$b^2a^2 + b^2 = a^2b^2 + a^2$
$b^2 = a^2$
$\sqrt{b^2} = \sqrt{a^2}$
$b = \pm a$
then the function is not injective because $b$ in not equal to $a$, but using online solver the function is injective.
Comment: Hint:  the derivative is always negative.
Comment: Your proof is not correct. You showed that $$f(a)=f(b) \Rightarrow a= \pm b$$ but actually you didn't explicitely give an example for $f(a)=f(-a)$. The error arises when you square everything (third line): this is not a reversible step.
Comment: The extra solution comes from the squaring.
Comment: @G-man thanks, could you explain better with an example. Thanks in advance
Comment: Even though it may be reasonable to assume f is defined as $f:\mathbb{R} \rightarrow\mathbb{R}$, it is better to be unambiguous by specifying the domain and codomain.
Answer: When you wrote $$2b\sqrt{a^2 + 1} = 2a\sqrt{b^2 + 1}$$ this gave you a new condition : $a$ and $b$ must have same sign. (The square roots are positive). Hence $a^2=b^2$ implies $a=b$ in this case.
Answer: Hint:
$$y=\sqrt{x^2+1}-x=\frac1{\sqrt{x^2+1}+x}$$
Then $$f(a)=f(b) \Leftrightarrow \frac1{\sqrt{a^2+1}+a}=\frac1{\sqrt{b^2+1}+b}\Leftrightarrow$$
$$\Leftrightarrow \sqrt{a^2+1}+a=\sqrt{b^2+1}+b \Leftrightarrow a=b$$
$f(t)=\sqrt{t^2+1}+t -$ strictly increasing
Comment: Thanks @Roman83. I am honest to say I did't understand how to simplify $\sqrt{a^2 + 1}$ and $\sqrt{b^2 + 1}$


Is this linear model the right choice?

Question: My data is like the below table:
username       Tweet_id      Agegroup      Time     Score
A               unique        Young        1        0.2
A               unique        Young        2        0.3
B               unique        Old          1        0.5
c               unique        Old          4        0.6

Each user(username) may post between one and many tweets, and each tweet(tweet_id) was posted in different times(Time) and has a different score (Score).
I hope to examine the effect of time and age(also an interaction) on Score.
My guess is that tweetid should be nested in the username like a class nested in the school.
I am not sure if I am building up a correct linear mixed model.
Since I have a million row, how I can speed up the test.
Also, How can I generate linear mixed model tables and plot(better to have an interaction plot between age and Time)
lm1 = lmer(score~ 1+agegroup+Time+ (1|username/Tweet_id),data = new_data,control = lmerControl(calc.derivs = FALSE))

Comment: Please explain the data a bit more. Your model has `id` as a grouping variable but this is not in the data extract. Also  if `tweet_id` is nested in `username` then `tweet_id` should not  have the same level for all the usernames in your data  extract. Also you say that `score` is the outcome, but in your model it says `compound`
Comment: @RobertLong, Thanks, I edited the data. The outcome variable is the score. Should Tweet_id be nested in username? If so, is my R code correct?
Comment: I run this code on R, but it seems that it will take forever to run it, and I never get an error nor the result.
Comment: Please provide the exact eror that you get. Also, from the data, it doesn't look like `tweet_id`is nested within username because they are have value `unique` for users A, B and C
Comment: @RobertLong, I don't have the error. Just not sure if I have the right model to run. It seems the correct model should be lmer(compound ~  agegroup + Time + (1 | username), data = sample)?
Comment: Oh sorry, I mis-read your last comment. Your description *does* suggest that tweets are nested within username - I mean, it's kind of obvious - each user has a number of tweets that "belong" to them right ? It's just that your data is not consistent with that - why are all the the `Tweet_id`s labelled `unique` ?
Comment: Yes, each username has a number of tweets that "belong" to them. But each tweet is unique and they have a unique tweet id.
Answer: Your model :
score ~ 1 + agegroup + Time + (1|username/Tweet_id)

Does make sense, apart from you mentioned that you are interested in the interaction between agegroup and Time and that model does not fit an interaction.
I find it strange that all the Tweet_ids have exactly the same value: unique.
Setting that aside it seems your problem is that it takes a long time to fit. This is not surprising given you say you have around a million rows. A few things I can suggest:

Split that data into smaller chunks, say 25,000 rows and see how long the model takes to run 32 of those those. Then try 50,000 on 16 of those, then 100,000 on 8, then 200,000 on 4. From this you will be able to estimate how long it will take with the full dataset. FYI a few years ago I had some mixed models that took 15 days to run :o

check the resources that are being used by the machine you are running it on. If it is mainly CPU then run it on an instance with a faster CPU that is also optimised for compute.
Comment: @wei Does this answer your question ? If so please consider marking it as the accepted answer. If not, please let us know why. Also, if you haven't already, please consider upvoting it.

Is this linear model the right choice?


Erro de passagem (laços) - jogo pedra papel tesoura lagarto e spock

Question: estou fazendo um jogo Pedra, papel, tesoura, lagarto e spock.
A intenção do jogo é criar uma função que me pergunte qual opção eu vou escolher, enquanto o computador escolhe aleatoriamente um desses 5. Uma terceira função deve comparar o resultado das duas jogadas (minha e do computador) e verificar se eu ganhei, perdi ou empatou. No começo, coloquei tbm um comando para que o computador me pergunte quantas rodadas quero jogar. O problema é que aparentemente ele "trava" os valores da primeira rodada, por exemplo, se eu escolho tesoura e o computador escolhe papel, ele sempre computa o resultado dessa rodada (que ganhei) nas próximas rodadas, mesmo que eu escolha outras coisas nas proximas rodadas. Desde já obrigado.
<code>
legenda = '''
[0] pedra
[1] spock
[2] papel
[3] lagarto
[4] tesoura
'''
n = randint(0,4)

print(n)

lista = [[0,'pedra'],[1,'spock'],[2,'papel'],[3,'lagarto'],[4,'tesoura']]

def jogador():
    while True:
        print(legenda)
        esc = int(input(f'Escolha uma jogada: '))
        if esc == 0 or esc ==  1 or esc == 2 or esc == 3 or esc == 4:
            print(f'-> Você escolheu {lista[esc][1]} ')
            break
        else:
            print(f'Opção inválida, digite novamente')
    return esc

def computador():
    print()
    print(f'-> O computador jogou {lista[n][1]}')
    return n

def dif():
    dife = jogador() - computador()
    return dife

def jogada():
    voce = 0
    comp = 0
    print(f'''\t\tPLACAR
VOCÊ\t\t\tCOMPUTADOR
{voce}\t\t\t\t{comp}''')
    num = int(input(f'Quant. de rodadas? '))
    for i in range(0,num):
        jogador()
        computador()
        if dif() == 2 or dif() == 1 or dif() == -3 or dif() == -4 :
            voce += 1
            print('Você ganhou')
            print(f'''\t\tPLACAR
VOCÊ\t\t\tCOMPUTADOR
{voce}\t\t\t\t{comp}''')

        elif dif() == 0:
            print('Empate')
            print(f'''\t\tPLACAR
VOCÊ\t\t\tCOMPUTADOR
{voce}\t\t\t\t{comp}''')
        else:
            print('Você perdeu')
            comp += 1
            print(f'''\t\tPLACAR
VOCÊ\t\t\tCOMPUTADOR
{voce}\t\t\t\t{comp}''')

jogada()```
</code>
Answer: Amigo, fiz uma pequena alteração aqui. coloquei o randint dentro da função computador ao inves de jogar no inicio como feito anteriormente e funcionou. Parabéns pelo codigo.
<code>    from random import randint
    from time import sleep
    legenda = '''
    [0] pedra
    [1] spock
    [2] papel
    [3] lagarto
    [4] tesoura
    '''
    lista = [[0,'pedra'],[1,'spock'],[2,'papel'],[3,'lagarto'],[4,'tesoura']]

    def jogador():
        while True:
            print(legenda)
            esc = int(input(f'Escolha uma jogada: '))
            if esc == 0 or esc ==  1 or esc == 2 or esc == 3 or esc == 4:
                print(f'-> Você escolheu {lista[esc][1]} ')
                break
            else:
                print(f'Opção inválida, digite novamente')
        return esc

    def computador():
        n = randint(0, 4)
        print()
        print(f'-> O computador jogou {lista[n][1]}')
        return n

    def dif():
        dife = jogador() - computador()
        return dife

    def jogada():
        voce = 0
        comp = 0
        print(f'''\t\tPLACAR
    VOCÊ\t\t\tCOMPUTADOR
    {voce}\t\t\t\t{comp}''')
        num = int(input(f'Quant. de rodadas? '))
        for i in range(0,num):
            jogador()
            computador()
            if dif() == 2 or dif() == 1 or dif() == -3 or dif() == -4 :
                voce += 1
                print('Você ganhou')
                print(f'''\t\tPLACAR
    VOCÊ\t\t\tCOMPUTADOR
    {voce}\t\t\t\t{comp}''')

            elif dif() == 0:
                print('Empate')
                print(f'''\t\tPLACAR
    VOCÊ\t\t\tCOMPUTADOR
    {voce}\t\t\t\t{comp}''')
            else:
                print('Você perdeu')
                comp += 1
                print(f'''\t\tPLACAR
    VOCÊ\t\t\tCOMPUTADOR
    {voce}\t\t\t\t{comp}''')

    jogada()
</code>
Comment: Obrigado! Consegui resolver o problema de não atualizar o numero aleatório. Porém, o placar só aparece a cada 6 rodadas, não sei por qual motivo.


Linked list toArray Java

Question: How would I go about converting a linked list of integers to an array without using the built-in toArray method? I need to convert a sorted linked list to an array for a school project. I have the linked list part completed, and I just can not figure out how to convert this to an array. Any help would be appreciated
Answer: Think of what you need. You must be able to iterate over your linked list and grab the values. So you need:

an array the size of the list (does your list have a way to get that or to help create it?)
a for loop to iterate over the list.
a way of placing the value in the list in the corresponding location of the array.
Comment: I've got a size counter, and it accurately keeps track of the size. I just can't figure out how to add the data from the list into the array now.
Comment: If presume you can iterate thru the list so you can get the value and print it (otherwise, it isn't much use). So just do that and as you grab each value indexed by some variable, assign it to an array. Have you ever copied one array to another? It's the same operation.

Linked list toArray Java


Android - What is the best way to use a custom font application wide

Question: I want to use Google's Raleway font in my android app. I have read a lot of blogs and a number of answers on stackOverflow but haven't found the exact answer.
The best answer i found is here that explains to create custom TextViews efficiently.
If i have two use two variations of the font say Raleway-Regular and Raleway-SemiBold, do i have to create two custom TextViews or is there any better way to achieve that ?
Comment: You can make your own textView
Comment: @KhizarHayat - If i have two use two variations of the font say Raleway-Regular and Raleway-SemiBold, do i have to create two custom TextViews ?
Comment: no use one textview assign it at runtime
Comment: or you may be assign using TypeFace
Comment: A lot of people are recommending [Calligraphy](https://github.com/chrisjenx/Calligraphy) . Which of the two methods you recommend ?
Comment: i have not used Calligraphy, i made my own textView and use TypeFace. may be Calligraphy is better option but i have not experienced that library
Answer: I have done the task the following way
Download the ttf of that font and then paste it inside the asset folder(you have to create the assets folder inside /src/main/assets)
then change the font the following way:

Typeface face = Typeface.createFromAsset(getAssets(), "condenced.ttf");
  tv_the.setTypeface(face);

you can download the multiple ttf files and can display the different fonts to different fields.
Hope this helps.
Comment: I want a solution that is application wide, in this case i'll have to set the typeface multiple times that is not acceptable.
Answer: I am using Calligraphy library for my project and it works perfect.
Answer: For me the best way to use a custom font is this library:
Calligraphy


Statistical significance of the difference between two Linear Regression slopes

Question: How to test the statistical significance of the difference between two Linear Regression slopes?
There are two time-series: T1 and T2. They come from different studies and mean different things. On T1 we do a Linear Regression and get the coefficient B1. On T2 we do a Linear Regression and get the coefficient B2.

For comparison of the slopes, do I need the dependant variable to be the same?
Can time be this dependant variable?
What are the recommended statistical tests to apply in this case? T-test?

Thank you for your time!
Comment: Please give more context so someone can provide a helpful answer. Obviously, if the two slopes are measured in different units then it doesn't make sense to compare their numerical value. You can't compare a slope that is expressed as miles per gallon with another slope that is inches per year.
Answer:
I am not sure what do you mean by "comparison of the slopes", because if you have just two models, you would get just two slopes: let's say: a1 and a2. Then how would you like to test the statistical significance of the differences between just these two?

Anyway, if you would like to compare two models, it would be helpful that the dependent variable is the same in both models. This way you would be able to show, e.g., that the model no. 1 is better than model no. 2 because (even though different independent variables were used), the model no. 1 allows for a better prediction of the values the dependent variable takes. See my question: Statistical significance of the difference between two regression models

As far as I understand, in time-series models, time is an independent variable (usually denoted as "X"). I.e., given time (and optionally some other parameters), you attempt to predict the values of the dependent variable (usually denoted as "Y"). I.e. your output value depends on time (or at least that is that you hope for to show). More on the difference between independent and dependent variables: https://www.scribbr.com/methodology/independent-and-dependent-variables/ ; and: https://www.khanacademy.org/math/cc-sixth-grade-math/cc-6th-equations-and-inequalities/cc-6th-dependent-independent/a/dependent-and-independent-variables-review

As I stated before, I am not completely sure what did you mean in points 1. and 2. , but generally, yes, I would use a t-test, see my question: Statistical significance of the difference between two regression models


C# mvc5 add Textbox by Controller

Question: is it possible to add a texbox by controller to a View?
I have a dynamic number of textboxes and need a way to add this by the Controller to the View. Is this Possible?
Comment: You could do this by using a collection in your view model and then foreach over that collection in your view.
Answer: <code>      Do Something like this. Just a quick written code. Might be syntax errors.

      DynamicTextBoxCreation.cs
      public class DynamicTextBoxCreation
        {
            public List<string> textBoxList;

            public ActionResult DynamicTextBox()
            {
               /* Fill your dynamic list here from DB or from any other logic */
               return textBoxList;
            }
        }

        DynamicTextBox.cshtml
        @model DynamicTextBoxCreation;
        @code{
          var i = 1;
        }

        foreach(var tbItem in textBoxList)
        {
            @Html.TextBox(' + tbItem + i + ', "", new {@class = "css-class", @onclick = "alert('demo');"});
            i += 1;
        }
</code>

C# mvc5 add Textbox by Controller


Existe uma maneira universal de descobrir se um período se sobrepõe pelo menos em parte a outro período?

Question: Se eu tenho uma faixa de tempo com início e fim e outra faixa com início e fim, existe uma maneira fácil e universal que não dependa muito da linguagem, exceto pela sintaxe específico que posso aplicar para descobrir se qualquer momento desses dois períodos se chocam entre sim?
Answer: Tem que comparar o início e fim desses tempos. Vou usar JavaScript porque tem algo que pode ver funcionando aqui mesmo na resposta, mas o princípio é o mesmo em qualquer linguagem.

function overlaps(x, y) {
    return Math.max(0, Math.min(x.fim, y.fim) - Math.max(x.inicio, y.inicio)) > 0;
}
var a = { inicio : new Date(2023, 2, 30, 10, 10, 10), fim : new Date(2023, 2, 30, 10, 10, 20) };
var b = { inicio : new Date(2023, 2, 30, 10, 10, 05), fim : new Date(2023, 2, 30, 10, 10, 15) };
var c = { inicio : new Date(2023, 2, 30, 10, 10, 05), fim : new Date(2023, 2, 30, 10, 10, 09) };
var d = { inicio : new Date(2023, 2, 30, 10, 10, 05), fim : new Date(2023, 2, 30, 10, 10, 10) };
var e = { inicio : new Date(2023, 2, 30, 10, 10, 20), fim : new Date(2023, 2, 30, 10, 10, 30) };
var f = { inicio : new Date(2023, 2, 30, 10, 10, 12), fim : new Date(2023, 2, 30, 10, 10, 18) };
console.log(overlaps(a, b));
console.log(overlaps(a, c));
console.log(overlaps(a, d));
console.log(overlaps(a, e));
console.log(overlaps(a, f));

Coloquei no GitHub para referência futura.
Note que quando está no limite do tempo não considera sobreposição. Isso poderia ser feito, talvez até configurável com parâmetro na função, bastaria comparar com <= em vez de <, mas geralmente os momentos colados não são considerados sobreposição.
Não está importando se a sobreposição é parcial ou total.


Android Studio 3.1 stuck at Configure Build over 30 Minutes

Question: So I just updated my Android Studio to 3.1 from 3.0.1. As I am typing this, over 30 minutes have been passed and Android Studio is stuck at Configure build.
What have I done:

change gradle version in project gradle file
checked my internet (it is working fine)

Below is a snapshot of my screen with internet results

These dependencies in particular are taking all the time.

My project build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 And here is my application build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.smk.carsapp"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
configurations {
    all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:exifinterface:27.1.0'
    implementation 'com.android.support:support-v13:27.1.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.wdullaer:materialdatetimepicker:3.5.1'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.github.bumptech.glide:glide:4.6.1'
    implementation 'com.jsibbold:zoomage:1.1.0'
    implementation 'com.siclo.ezphotopick:library:1.0.8'
    //    TEST
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation files('libs/ksoap2-android-assembly-3.6.2-jar-with-dependencies.jar')
}
repositories {
    mavenCentral()
    maven {
        url 'https://dl.bintray.com/siclo/SicloAndroidOSS'
    }
}

Comment: you can try this https://stackoverflow.com/questions/49510176/android-studio-gradle-sync-failed-could-not-head-received-status-code-5/49510333#49510333 if you want to resolve fast !!
Comment: wait until it finishes, yesterday when I update mine studio, it took around 30-40 for updation.
Comment: @Lucifer I waited for over an hour and then I cancelled. I don't think that would've been helpful.
Comment: @SantanuSur Looks like it might resolve my issue. Currently downloading gradle-4.4-all.zip will update after it is finished
Comment: @SantanuSur Thank you very much. changing 4.1 to 4.4 fixed my issue.
Answer: try this :
Android Studio go to File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle
Check the 'Offline work' under 'Global Gradle settings'
It will reduce 80% gradle build time.

and check gradle dependencies
buildscript {
  dependencies {
     classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
 }
 }

Add dexOption and give the following heapSize
dexOptions {
incremental = true;
preDexLibraries = false
javaMaxHeapSize "4g"
}

Answer: Fixed:
I changed the distributionUrl in gradle-wrapper.properties as pointed by Santanu here.

In gradle-wrapper.properties use this :-
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
Instead of 4.1-all.zip .
Answer: Click to open ScreenShot
Enable Toggle Offline Mode Solved my issue. Check screenshot for more details.
Just select this one if it's not selected. its worked for me previously its take 25 30 minutes now it only takes a few seconds
Comment: Answers should be specific to the user. Please add some code so the author can replicate your solution. https://stackoverflow.com/help/how-to-answer
Comment: I just enabled offline mode.Check screenshot.


Wrong Time Signature or Syncopated?

Question: I am trying to assess the time signature of a song I'm transcribing. Initially, I thought it was in 4/4, but with this, very few of the verse chord changes happen on the beat. 4/4 might still be correct, but is there a term (like syncopated) that describes this?
If it helps, the song I'm trying to transcribe is Coconut Records - West Coast. Here's what I've transcribed so far in respect to the chord changes & beats. The numbers represent the measure number and the first beat in each measure, each dot represents the 2nd, 3rd, and 4th beat in the measure.
Intro
Riff1           Riff2
1 . . . 2 . . . 3 . . . 4 . . .

Verse 1
    Bb  EbGm      Bb  EbBb
5 . . . 6 . . . 7 . . . 8 . . .
Bb  EbGm       Bb   EbCm       Dm
9 . . . 10 . . . 11 . . . 12 . . .

Chorus
     Gm  Eb   Cm  Dm   Gm  Eb   Cm
13 . . . 14 . . . 15 . . . 16 . . .
Dm   Gm  Eb   Cm  Dm   Gm  Eb   Cm
17 . . . 18 . . . 19 . . . 20 . . .
Dm
21 . . .

Verse 2
Bb   EbGm       Bb   EbBb
22 . . . 23 . . . 24 . . . 25 . . .
(Same chords as verse one)...

Answer: Intro   |4|4|4|4|

        |2|

Verse   |3|4|3|4|
        |3|4|3|4|4|

Refrain |4|4|4|4|
        |4|4|4|4|

        |2|

Vers    |3|4|3|4|
        |3|4|3|4|4|

Refrain |4|4|4|4|
        |4|4|4|4| etc.

Well, the intro is like the refrain - straight 4 beats, then you have a little break of 2 quarters, verse is 4 groups of 7 quarters (3+4) with a little 4 quarter extension (bridge) at the end...
Drums come in on bar 4 of the first verse!

Intro   |4      |       |       |       |

        |2      |

Verse   |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Bb   |
        |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Cm   | Dm   |

Refrain |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm |
        |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm |

        |2 Dm   |

Verse   |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Bb   |
        |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Cm   | Dm   |

Refrain |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm |
        |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm | etc.

Of course you could - because of the chord changes - interpret the Refrain with the additional 2 quarter bar as

Intro   |4|4|4|2|

        |4|

Verse   |3|4|3|4|
        |3|4|3|4|4|

Refrain |4|4|4|4|
        |4|4|4|2|

        |4|

Vers    |3|4|3|4|
        |3|4|3|4|4|

Refrain |4|4|4|4|
        |4|4|4|2| etc.

respectively

Intro   |4      |       |       |2      |

        |4      |

Verse   |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Bb   |
        |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Cm   | Dm   |

Refrain |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm |
        |4 Gm Eb| Cm Dm | Gm Eb |2 Cm   |

        |4 Dm   |

Verse   |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Bb   |
        |3 Bb_Eb|4 Gm   |3 Bb_Eb|4 Cm   | Dm   |

Refrain |4 Gm Eb| Cm Dm | Gm Eb | Cm Dm |
        |4 Gm Eb| Cm Dm | Gm Eb |2 Cm   | etc.

But you'd better go for the first variant because before the repetition of the last Refrain they keep on playing 4 straight 4 beat bars and repeat them - until they are stuck with the Dm for the Coda (fade)...
Comment: Thanks for such a detailed answer! Seems it's just a song with an interestingly shifting time signature, so no matter which way I slice it it'll never be a consistent signature through the song.
Answer: Lets get clarity on what syncopation is. Syncopation is at its core a emphasis on the weak part of a beat. If you would have syncopation in 4/4 time it would be something resembling this.

The 4/4 Time signature would have the strong pulses on the 1 and third beats and by playing a long note on the second pulse you would be emphasizing a weak pulse.
Now bringing it back to your example you may very well have syncopation depending on how your strumming is accentuated. Seeing as there is no indications of emphasis it is really hard to say for sure.
What I rather see here is simply 4/4 time signature with a lot of chord changes that change on the quaver beats ie two changes in one pulse.
This could be played by accenting certain strums in slew of ways that may include syncopation or not.
Comment: I don't think this is relevant to this question. In a rock groove, it's not really true at all that beats 1 and 3 are "strong" while 2 and 4 are weak. In fact it's rather the opposite: 2 and 4 are indicated by clear accents on the snare drum. In the example song, the drums make it thus quite unmistakable that the signature is 4+3/4, instead of 4/4 with syncopated chord changes. Of course you could still interpret this some other way with both chords and drums on unusual beats, but this would be rather more complicated. Better apply Occam's razor.
Comment: No syncopation here. The bar length changes as the song goes on. With syncopation, there would still be a four count present all through. There is not.

Wrong Time Signature or Syncopated?


Regression Analysis in Expenditure based problems

Question: I have a doubt regarding prediction of expenditure of a single person's data. For example, if we have data of expenditure of 5 days say 'food', can we predict the the expense of 6th day using regression analysis.  To be more specific, if my expenditure of food are 50, 100, 155, 145 and 100 for day 1, day 2, day 3, day 4 and day 5 respectively.  Can we use linear regression in this case?.  If yes what will be the independent variable.  I have a very little knowledge in statistics, so please help me in this regard
Comment: With no other information a best guess in a least squares sense for day 6 is the mean of expenditures for days 1 to 5, which is in fact a regression result. Any good regression code will return the mean given only a response variable. Otherwise I don't know how seriously your example should be taken, but a statistical person would ask: Is expenditure the cost of food eaten that day, or the amount spent per day? What days of the week are meant? For example, the 6th day might be a non-shopping day. More generally, no good model beyond calculating a mean is possible without more information.
Comment: Look at your question. It is: can we use linear regression and comments explain yes and say more. If it's now can we do anything else? Then yes again. You could use the median, for example. But the question now lacks even what little focus it had.
Comment: Thankyou.  By expenditure I meant the cost of food eaten that day. From monday to friday.
Comment: So, you have more information that you gave us. The question could be cultural here as much as statistical. Is Saturday's expenditure expected to differ from the mean of Monday to Friday?
Comment: yeah... anything other than average?
Answer: Expanding a bit on Nick's comments:
Right now, you have two variables: Day and expense. If that's all the data you have then the only possible regression would be to have expense as the dependent variable and day as the independent variable. You could do this and you will get an intercept and a coefficient for day. It doesn't violate any rules to do so. The equation you get is:
$Expense = 66.5 + 14.5D$
But then you want to extrapolate to day 6. And it becomes clear that a linear trend by day makes no sense. It would mean that the expense on (say) day 100 would be $66.5 + 145 = 220$.
The best approach, with so little data, is to just use either the mean or the median, depending on exactly what you are trying to predict.
If you gathered data for a lot more days then you could do something sensible, perhaps using day of week as an independent variable or looking for cyclical patterns.


Playing m7th chord on the 5th note of a major scale

Question: Daniel Caeser & H.E.R.'s song "Best Part" has the following chord progression:
Dmaj7, Am7, Gmaj7, A#maj7
The song sounds like it is in D major, which means that the A chord should be Amaj or A7, but then why does the Am7 sound so amazing in this progression?
Answer: Those are common and useful tricks.
The way I'd explain the whole chord sequence is, it modulates between keys all the time:

Dmaj7 : establishes D major as the key
Am7 : gotcha! it wasn't D, it was G major!
Gmaj7 : yeah ... see, I told you, it was G major.
Bbmaj7 : oooops! the key is D minor! Fooled you twice!!
Dmaj7 : ha ha ha! the key is in fact D major ! You're so easy to fool! ;)
etc.

If we just look at the Am7, there are many ways to look at it.

You can see the Am there just as a fancy D7, because it has the C note
in it, the very thing that makes D7 push strongly towards G (using
the "V-I motion" mechanism).
Or you can look at it as "simulating" or "borrowing" or whatever, pretending for a short while that you're in the key of G major, where the Am - D7 - G would be a II - V - I movement.

Try replacing the Am7 with a D7. Then try replacing it with a D11 (i.e. C6/D) ... almost the same? No? What's different? Then take any song that has a D7 - G movement, and replace the D7 with Am7. Same? Different?
One of my favourite chord sequences is in Skee-Lo's "I Wish", based on a sample from Bernard Wright's "Spinnin'" (AFAIK). In "C" it would go like this: Cmaj9 - Abmaj9 - Bmaj9 - Gmaj9 (repeat). It modulates between keys in a very juicy way.
Answer: Why is it that the A chord should be A maj or A7? There is nothing anywhere saying it should. You've seemingly fallen into the trap that music theory prepares for all of us. It masquerades as the rules. Simply not true!!
One explanation - apart from the blindingly obvious one which you perceived - is that it belongs to the parallel key. That is, D minor instead of D major. That set of different chords can usually be borrowed from, as here.
Another is that Am7 has nearly the same note make-up as D9, which 9 times out of 8 moves directly onto a G of some sort. Here, Gmaj7.


Ordenando resultados de relacionamento "ManyToManyField" com a mesma tabela em Django

Question: Estou com o relacionamento Many to Many com a mesma tabela, e preciso ordenar o resultado com a mesma sequencia da criação.
ex: adiciono Django básico, Django intermediário, Django avançado;
Tem q aparece nessa sequencia na visualização.
Já tentei {% for req in course.requirements.all|dictsort:"id" %} na view, mas sem resultado. Alguém poderia me dar uma ajuda. Desde já agradeço. Obrigado...
model.py:
class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = models.ManyToManyField("self", blank=True, symmetrical=False)
    created_at = models.DateTimeField(auto_now_add=True)

admin.py
class CourseContentInline(admin.TabularInline):
    model = CourseContent

class CourseAdmin(AjaxSelectAdmin):
    list_display = ('name')
    search_fields = ['id', 'name']
    list_filter = ['created_at']
    prepopulated_fields = {"slug": ("name",)}
    inlines = (CourseContentInline,)
    form = make_ajax_form(Course, {
        'requirements': 'courses',
    })

admin.site.register(Content, ContentAdmin)

view.py
def details(request, slug):
course = get_object_or_404(Course, slug=slug)
course_content = CourseContent.objects.filter(course=course)

context = {
    'course': course,
    'course_content': course_content,
}

return render(request, 'portal/courses/details.html', context)

details.html

{% if course.requirements.count >= 1 %}

Pré-Requisitos

            {% for req in course.requirements.all %}
                - {{ req.name }}

            {% endfor %}

{% endif %}

área admin

visualização
Answer: Problema resolvido!!!
O problema foi resolvido com o uso do pacote "django-sortedm2m". Dessa forma consegui ordenar o resultado de uma maneira simples e eficaz.
instalação
pip install django-sortedm2m

settings.py
INSTALLED_APPS = [
    'sortedm2m',
]

model.py
from sortedm2m.fields import SortedManyToManyField

class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = SortedManyToManyField("self", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

criar e rodar as migrations
./manage.py makemigrations
./manage.py migrate

Problema resolvido!!!


How to reverse proxy specific extension names with Nginx

Question: Say I am trying to proxy all requests coming in for jpg, png and mp3 files like so:
http://example.com/some/url/file.png
to
http://example.net/data/some/url/file.png
Notice it's the exact same path to another server but with data added.
Her's what I have so far:
location ~* .(jpg|png|mp3)$ {
        proxy_pass https://example.net/data/;
        proxy_redirect https://example.net/data/ /
    }

However I keep getting error
"proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block

What is going wrong and how can I correctly write this location block?
Answer: You need to change an URI using rewrite directive if you want to pass a different URI to the backend in the regex matching location block (the same is true for the named locations):
location ~* \.(jpe?g|png|mp3)$ {
    rewrite (.*) /data$1 break;
    proxy_pass https://example.net;
    proxy_redirect https://example.net/data/ /
}


Evaluating using BRA KET Notation?

Question: Evaluate $\langle 0 \mid x^3 \mid 1\rangle$, assuming that all the wave functions you encounter are normalized eigenfunctions of the harmonic oscillator Hamiltonian, without Mathematica, Maple, or software! (I am aware that this overlaps with Physics, however it's primarily the math notation and logic I'm having problems with. The hamiltonian is just a definition and to me is more of a mathematics discipline)
Steps:
$$\langle 0 \mid x^3 \mid 1\rangle= \int^x_{-x} \Psi_0^* (x) x^3 \Psi_1 (x) dx = \sqrt{\frac{2m\omega}{\hbar}}\sqrt{\frac{m\omega}{\pi\hbar}}\int^\infty_{-\infty}x^4 e^{-m\omega x^2/\hbar}dx$$
So the hint I got was to rewrite the right hand side of the equation, which I found to be:
$$\int^\infty_{-\infty}x^4 e^{-m\omega x^2/\hbar}dx = \frac{d^2}{d\alpha^2} \sqrt{\frac{\pi}{\alpha}}, \quad \alpha = \frac{m\omega}{\hbar}.$$
The second hint was to perform the derivatives, sub back the definition for $\alpha$ and don't forget the prefactors. Might be quicker to solve with raising and lowering operators.
The step I'm not understanding is how to apply the derivatives when they're on the other side of the equation? Are they movable, algebraically?
Comment: I agree that it would be quicker (and more elegant) to do this with ladder operators. What do you mean by the derivatives being on the other side of the equation? They're being applied to an expression involving $\alpha$ on the right-hand side; you can apply them to that expression, and the result will still be equal to the left-hand side. By the way, the integral bounds on the first integral should be $\pm\infty$ as in the other two integrals.
Answer: Do a sub $\frac {m\omega x^2}{\hbar^2} = t^2$, then $x = \frac {\hbar t}{\sqrt {m\omega}}$ and $dx = \frac {\hbar dt}{\sqrt {m\omega}} $, so integral can be rewritten as
$$
\int_{-\infty}^\infty x^4 e^{-\frac {m\omega x^2}{\hbar^2}} dx = \int_{-\infty}^\infty \frac {\hbar^4 t^4}{m^2\omega^2} \frac {\hbar}{\sqrt{m\omega}}e^{-t^2}dt = \frac {\hbar^5}{\left(m\omega\right)^{\frac 52}} \int_{-\infty}^\infty t^4e^{-t^2}dt
$$
So the problem reduces to determination of latter integral
$$
\int_{-\infty}^\infty t^4 e^{-t^2}dt = \left .-\frac {t^3 e^{-t^2}}2\right|_{-\infty}^{+\infty} + \frac 32 \int_{-\infty}^\infty t^2 e^{-t^2} dt = \\
= \frac 32 \left(\left .-\frac {t e^{ -t^2}}2 \right|_{-\infty}^{+\infty} + \frac 12 \int_{-\infty}^\infty e^{-t^2}dt\right) = \frac 34 \sqrt \pi
$$
and final integral is
$$
\left <0 \left | x^3 \right | 1\right > = \frac {m\omega}\hbar \sqrt{\frac 2\pi} \frac {\hbar^5}{\left(m\omega\right)^{\frac 52}}\frac 34 \sqrt \pi = \frac {3\sqrt 2 \hbar^4}{4 \left( m\omega\right)^{\frac 32}}
$$
PS: If it's too vague – I used integration by parts twice and at the end used the fact that
$$
\int_{-\infty}^\infty e^{-t^2}dt = \sqrt \pi
$$
It's Euler-Poisson or Gaussian integral.
Answer: Using your definition of $\alpha$, we get
$$\langle 0 \mid x^3 \mid 1\rangle= \sqrt{\frac{2}{\pi}} \alpha \int^\infty_{-\infty}x^4 e^{-\alpha x^2}dx \ .$$
The important observation concerning the derivative with respect to $\alpha$ is that
$$ \frac{\partial^2}{\partial\alpha^2} e^{-\alpha x^2} = \frac{\partial}{\partial\alpha} \left[-x^2 e^{-\alpha x^2}\right] = x^4 e^{-\alpha x^2}
$$
Substituting back into your original integral, switching integration by $x$ and derivative w.r.t. $\alpha$
$$\langle 0 \mid x^3 \mid 1\rangle= \sqrt{\frac{2}{\pi}} \alpha \int^\infty_{-\infty} \frac{\partial^2}{\partial\alpha^2} e^{-\alpha x^2}dx =
\sqrt{\frac{2}{\pi}} \alpha \frac{\partial^2}{\partial\alpha^2} \underbrace{\int^\infty_{-\infty} e^{-\alpha x^2}dx}_{\sqrt{\pi / \alpha}}$$
Thus, your final result is
$$ \sqrt{\frac{2}{\pi}} \sqrt{\pi} \alpha\, \frac{\partial^2}{\partial\alpha^2} \frac{1}{\sqrt{\alpha}} = \sqrt{2} \alpha \frac{1}{2} \cdot \frac{3}{2} \alpha^{-5/2}
= \sqrt{2}\, \alpha^{-3/2}$$
With this "derivative trick" you could also compute $\langle 0 \mid x^{33} \mid 1\rangle$, if you are able to take the 33rd derivative of $1/\sqrt{\alpha}$ w.t.r. to $\alpha$

Evaluating using BRA KET Notation?


Should I use Mean Square Error or Classification Rate?

Question: I am a self-taught person and I would like your help. I am learning about predictive modeling in general, and I'm also trying to do predictive modeling for a specific problem.
I am exploring alternative ensemble learning algorithms (CART, Random Forest). For this problem and model, I am trying to predict three categories with arbitrary labels 0/1/2. I get a good value of accuracy (0.81), but very high error (Mean squared error = 0.37).
My question: How do I interpret these diagnostics?  Is this a bad model? How should I interpret mean squared error? How should I define the intervals for mean squared error for an acceptable model?
Comment: It seems to me that the question you're asking in your post is different from the title of the post. Could you make the two consistent?
Comment: Thanks for ur comment!  I am trying to predict a phenomena, I collected the features (based on the study I ve done) and defined the target variable (labeled it so it's three cases 0/1/2). When I used CART to predict, I found that accuracy is 0.81 and Mean squared error = 0.37. It appeared to me that the error is too high, can you explain how can I comment on this model, should I say that I have a good model (based on the accuracy), or should I say that I have bad model based on Mean squared error
Comment: Are the numbers 0/1/2 arbitrary labels to the categories or is there some sort of natural ordering? In other words, if you predict class 1 but its actually class 0 are you closer to correctly predicting than if you had predicted class 2?
Comment: yes, 0/1/2 are arbitrary labels to the categories. I just labeled desired results to numbers.
Answer: Since your labels for the three groups are arbitrary, your classification rate is more meaningful than Mean Square Error (MSE) and MSE ought to be ignored. MSE tells how you how far your classifications are from the true values. Since the values you are assigning your groups are arbitrary, there's no sense of how far or close a classification is from the true value. You've either correctly classified or you didn't and classification rate measures this.
You can see this for yourself - if you reassign the arbitrary labels to your three groups you'll see a different MSE result.
Comment: Why did you delete a similar answer to this and post this new one  rather than edit the old?
Comment: Because the OP made a comment that was no longer relevant. Im happy to reverse it.


Selenium: finding elements in searchContext

Question: everyone!
I'm stuck with following problem:
There is some
SearchContext searchContext;
By by;

which could be WebDriver or WebElement.
Assume that both of them are already initialized (and we don't know how);
Now we want to find elements with such xpath, seems to do following
List<WebElement> elements = searchContext.findElements(by);

But, if searchContext is WebElement and
by = By.xpath("//div");

it wouldn't work! (no elements would be found), because we need to do
by = By.xpath("./div");

(see Locating child nodes of WebElements in selenium)
But, how i've mentioned, we know nothing about how by was initialized;
So, my question is: is there any way to find elements properly despite the problems above?
I've got two variables: by and searchContext, and I should to find specified element in searchContext.
Answer: As I understand, there is now way to do it.
Only way to do it - is manually specify By.xpath properly:
By child = By.xpath("/div");
By descendant = By.xpath("//div");

in case of WebDriver.isAssignableFrom(searchCOntext.getCLass()),
and
By child = By.xpath("div");
By descendant = By.xpath(".//div");

in case of WebElement.isAssignableFrom(searchCOntext.getCLass()).
IMHO, it's bad.
Answer: You can do it in some helper method which will throw Exception if this happens
public List<WebElement> returnSearchContext(By by, SearchContext searchContext){
  List<WebElement> elements = searchContext.findElements(by);
  if (elements.getSize()>0){
     return elements;}
   else{
     throw new ElementNotFoundException();
   }
}

I am writing this without access to any IDE, so I might do some errors in my example code. For instance, I think that the exception will need some parameters. But I hope you get the idea.
Comment: Thank you for reply!=)
Unfortunately, this wouldn't solve the problem, it's just a way to handle a failure.
It is my fault - formulation of my question wasn't clear enough. I make it more concrete.
Comment: stupid me :) Is the issue only "that easy"? Meaning - when the search context is WebElement, do you really need to find only child DIV, or is it complicated?


RadioButton.setChecked() doesn't appear to work

Question: This is the code in my arrayadapter that will set the RadioButtons status:
public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        attendance_holder holder = null;
        People_Attendance people_array[] = people_attendance.toArray(new People_Attendance[people_attendance.size()]);
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new attendance_holder();
            holder.txtName = (TextView)row.findViewById(R.id.name_txt);
            holder.txtNumber = (TextView)row.findViewById(R.id.number_txt);
            holder.attendance_group = row.findViewById(R.id.Attendance_Group);
            holder.not_attending = (RadioButton) holder.attendance_group.findViewById(R.id.not_attending_radio);
            holder.attending = (RadioButton) holder.attendance_group.findViewById(R.id.attending_radio);
            holder.invited = (RadioButton) holder.attendance_group.findViewById(R.id.invited_radio);

            row.setTag(holder);
        }
        else
        {
            holder = (attendance_holder)row.getTag();
        }

        holder.txtName.setText(people_array[position].name);
        holder.txtNumber.setText(people_array[position].number);
        if (people_array[position].attendance_status == "INVITED"){
            holder.invited.setChecked(true);
        }else if(people_array[position].attendance_status == "ATTENDING"){
            holder.attending.setChecked(true);
        }else if(people_array[position].attendance_status == "NOT ATTENDING"){
            holder.not_attending.setChecked(true);
        }else{
            Log.d("ATTENDANCE", people_array[position].attendance_status);
        }

        return row;

    }

I have used the Log.d() in my code to show the string, so I know it's not an empty string or bad string that's the problem. I would therefore think that either my if statements are wrong in someway, or that I am using RadioButton.setChecked() wrong. Then RadioButtons then do not get checked in the way they should do. The RadioButtons are in a RadioGroup.
Any thoughts??
Thanks for the help!!
Comment: post complete getView code
Comment: possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)
Comment: @Reimeus quite possibly, but I didn't realize that was the problem in the question. :)
Answer: You cannot compare Strings using the = operator in Java. Use equals() instead. While using = compiles fine, it just compares the memory addresses, which certainly is not what you want.
Eg this:
people_array[position].attendance_status == "INVITED"

Should be:
people_array[position].attendance_status.equals("INVITED");

Comment: This worked! Thanks for the help!! So can "==" operator only be used for integers and booleans?? Is it because strings are objects, and not primitives?? thanks! :)
Comment: Exactly, it's because Strings are no primitives. Glad I could help.
Answer: if(people_array[position].attendance_status.equals("INVITED")

use this instead of
people_array[position].attendance_status == "INVITED"

You can simplify the code as below.
holder.invited.setChecked(people_array[position].attendance_status.equals("INVITED"));
holder.attending.setChecked(people_array[position].attendance_status.equals("ATTENDING"));
holder.not_attending.setChecked(people_array[position].attendance_status.equals("NOT ATTENDING"));

Comment: Nice simplification! Thanks!:)
Answer: This is the code you should be using. You cannot compare strings like that. You have to use the .equals() function.
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    attendance_holder holder = null;
    People_Attendance people_array[] = people_attendance.toArray(new People_Attendance[people_attendance.size()]);
    if(row == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new attendance_holder();
        holder.txtName = (TextView)row.findViewById(R.id.name_txt);
        holder.txtNumber = (TextView)row.findViewById(R.id.number_txt);
        holder.attendance_group = row.findViewById(R.id.Attendance_Group);
        holder.not_attending = (RadioButton) holder.attendance_group.findViewById(R.id.not_attending_radio);
        holder.attending = (RadioButton) holder.attendance_group.findViewById(R.id.attending_radio);
        holder.invited = (RadioButton) holder.attendance_group.findViewById(R.id.invited_radio);

        row.setTag(holder);
    }
    else
    {
        holder = (attendance_holder)row.getTag();
    }

    holder.txtName.setText(people_array[position].name);
    holder.txtNumber.setText(people_array[position].number);
    if (people_array[position].attendance_status.equals("INVITED")){
        holder.invited.setChecked(true);
    }else if(people_array[position].attendance_status.equals("ATTENDING")){
        holder.attending.setChecked(true);
    }else if(people_array[position].attendance_status.equals("NOT ATTENDING")){
        holder.not_attending.setChecked(true);
    }else{
        Log.d("ATTENDANCE", people_array[position].attendance_status);
    }

    return row;

}


How to tell if an electric guitar has good quality

Question: I have been told that two "identical" mass-produced guitars - same series, same model - can be very different in quality.
I am about to buy a new Fender from a guy who has been trying to sell it for some time (several months). The guitar looks pretty good to me, but I am concerned with its quality, since no one bought it. He is selling it a few hundred dollars cheaper than what you would find in a store, but also a few hundred dollars more than a second-hand one.
Before I go and test the guitar in person, I have this question: What can I observe to make sure it has good quality, especially when comparing to another copy of the same model?
Answer:
Check the neck for bowing, twisting, and any other defect.  Also check the action on the neck.  Check play every fret on each string and be sure that they all ring purely and that they don't squeak out.  Check if the frets are worn down, which could cause squeaking.  Check the intonation (play a harmonic on the 12th fret, then play the same string with the 12th fret pushed down, and see if they match closely).
Check the country of origin.  American Fenders are more valuable than Mexican and Japanese models.
Test it through an amp.  Be sure that all the knobs function properly.  Check the pickup selector.  Gently shake the cable at the input to be sure that it doesn't go off/on.
Does it feel good?  Each guitarist needs a certain size neck to fit their hand size and style of playing.
Do you like the guitar?  It could be perfect, but may or may not be for you.  Do you like how it looks?

Good luck!
Answer: You seem to have done a little research on what the particular model Fender Guitar in question should sell for.  And from your question, it appears that you have some concerns about why this one seems to have been on the market for some time.
While the other answers offer good general advice about assessing the condition of a particular guitar, my answer will be more about your concern about the value of the guitar based on make and model - assuming that it is in good condition and passes your inspection.
Obviously if you are looking at a guitar that is "several hundred dollars" less than retail and "several hundred dollars more than used" - you must be looking at a guitar that you will spend more than several hundred dollars for - so I can certainly understand that you would not want to pay "several hundred dollars" more than you should - from a sound investment point of view.
In general where I live (in the U.S.A.), a used guitar (even a brand name like Fender or Gibson) that is not a collectible or vintage or rare guitar, would be considered a good buy - if priced at about half of what it sells for new.  This assumes it was well cared for and is in good condition with no damage or flaws that the other answers have properly advised you to look for.
Music stores who buy and sell used instruments will usually price them at between 60% and 70% of original price new.  I am willing to pay a little more to buy a used instrument from my local Guitar Center, because I know that I have 30 days to return it if I discover problems with it after I take it home and start playing it.
Private seller's can price their instruments anywhere between the average used and new price.  That does not mean they are ever going to get what they are asking for it.  It does not necessarily mean that there is anything wrong with the guitar. It is quite possible, that the person selling this particular Fender, is just holding out for a higher price than the going rate for a used guitar of that make and model.
However, there are a few things you should be wary of when buying anything used, and particularly a Fender guitar.
Be sure the instrument is not stolen.  You may know the person selling this guitar so you may not have that concern.  But for future visitors to this site who may have similar concerns, consider that if a crook wants to sell a stolen musical instrument, he is not going to go to a pawn shop where he/she knows the serial number will be checked against police records.  The crook could easily get a pay as you go cell phone (or steal one) and run an ad and sell some stolen goods and then sell the phone and disappear.
Another thing to be very concerned with on Fender and Gibson guitars, is the possibility that it is a counterfeit.  It may be possible that the seller does not even know it's a counterfeit because he/she bought it used.  But there is a copious supply of counterfeit Fender and Gibson guitars circulating around the world. If you choose to buy one, you don't want to pay the price of a legitimate Fender or Gibson.
Here is a good article from the official Fender Forums about how to spot a fake or counterfeit Fender guitar How to spot a fake Fender Guitar
If you don't know the Seller, you might ask for the serial number.  Just say you want to research the value and you know that the serial number will tell you the age, model and other information to help you gather more information to satisfy yourself about the value.  If the Seller refuses to give you the serial number, perhaps it's because he/she knows it's either a)stolen or b)fake.
Once you are convinced that the guitar is not stolen and not a counterfeit, and you have checked the action, the hardware, the electronics, the neck, the tuners, the truss rod, as described in the other great answers here, you can further research the value by consulting the Blue Book of Guitar Values Blue Book of Guitar Values
I buy used instruments often (usually from folks I know or retailers with a return policy) and I like to know that I am paying a price that is fair.  So the first thing I do is look at what other used guitars of the same make and model and year have been selling for on E-Bay, or Craig's List or search on Guitar Center's website for a used one like it.  I like to know the year because manufacturers often change the specs from year to year in ways that affect the value.  Sometimes an older model is worth more than the newer version of the same model - sometimes just the opposite.
If it were me personally and I was buying a guitar that I was not all that familiar with from a private seller whom I did not know - here is what I would do.  After I looked at the guitar and confirmed that it appeared to be in good condition and that I liked what I saw - I would say - "You know I really like this guitar and I am interested in buying it.  But I have no idea what it's worth and $1,800 is a lot of money for me.  Would you mind if we take it up to (Guitar Center/Music Go Round/Any Place that buy's used guitars) just to see what they would pay for it and what they would sell it for?  I am certainly willing to pay more than they will pay, but as long as your price is a little less than what they would sell it for, I will feel good about your price."
I have done that a twice - but fortunately there is both a Guitar Center and Music Go Round in my area.  The folks that evaluate used instruments at places like that, know what to look for and have the guitar value guides at their disposal.  So if I am spending more than $1000 on a guitar from a private Seller, I feel much better if someone in the business of buying and selling used guitar, confirms the value. Another option might be just to say you would like a professional guitar repair technician or luthier to take a look at it for you.  Many folks in the guitar repair business have access to value guides as well.
With a thorough inspection, a little research and due diligence, a little haggling, and a little luck, perhaps you will acquire a new addition to your guitar collection at a price you will be happy with.  Good luck.
Comment: +1 for "Be sure the instrument is not stolen." since that indeed lowers the price of an instrument that may technically be in perfect shape!
Answer: There are a few things you might not be able to check easily when you go to see it:

Whether the truss rod works.  Even if the action and setup seem perfect, do you know that the neck's truss rod will respond properly when you change to heavier strings, or decide that you want to play with a higher or lower action?
Whether the guitar picks up electrical hum.  It may not be a problem in the place you try it, but in another environment you may have problems with hums and buzzes if the instrument is not shielded correctly.
Whether it's genuine.
There are many fake guitars about; some are very convincing! How do you know that yours is a real Fender?

If you have problems with any of these things, will the seller take it back? Probably not. A shop, on the other hand, would have to (if it was sold as new), and that's why second hand things are so much cheaper than new ones. If your seller is asking a lot more than a typical second hand price, be careful - it might not be worth the risk.
Comment: If I was selling a guitar, I wouldn't be happy for a complete stranger to get out an Allen key and start turning my truss rod. Especially is he had to undo the plate over it.
Comment: @Tim exactly - you still have to take some things on faith some when buying s/h!
Answer: I would like to this add up to Mark's and the other's answers as a comment but I dont have the rep for it :)
My addition is:

Check all frets for chocking, it might be due to a faulty neck or due to a bad setup. So check the neck straight down and see if it seems reasonable, eg if bended backwards it would make sense that first frets might chock but if the neck seems fine, chocking frets could be due to a twist.
As the others said, plug it in an amp to check the electrics, just add distortion at some point, any faults will be brought up by the distortion, something that might not have been audible with a clean sound only.
Check how the weight seems to you. If somebody sells a gibson LP, and everything is working fine, the sound seems ok, but it weighs like a feather, then its definitely not genuine. Fake guitars might be impossible to distinguish, but the weight of the wood always gives something away.
Be careful when testing an instrument, because you dont have a point of reference as the instrument is new, the amp is different, the other person's setup is different than yours. If he gives you a lousy guitar plugged into great effects and a perfect tube amp, you will be falsely amazed!

Good Luck!


How to make a CCK field appear as single-value on one Node Type, and multi-value on another Node Type?

Question: I have a CCK field (text, options widget, predefined value list) I'm using on two Node Types.  On one Node Type, I'd like to allow an unlimited number of selections.  On the other Node Type, I'd like to restrict the user to a single selection.
Currently, I've configured the CCK field to allow unlimited values, and am using this hook_form_alter() code:
/*
 * Implementation of hook_form_FORM_ID_alter().
 */
function custom_form_custom_node_form_alter(&$form, &$form_state) {
  // http://drupal.org/node/726282
  $form['#after_build'][] = 'custom_after_build';
}
function custom_after_build($form, &$form_state) {
  $form['field_custom' ]['value']['#multiple'] = false;
  return $form;
}

So far, so good: the field shows up as single-value on one Node Type, and multi-value on the other.
But when I click Save, the data doesn't end up in the node — I presume this is because the single-value and multi-value fields store data differently, and CCK's submit handler is expecting the data in a different format.
What do I need to do to get the single-value field data into a format CCK will understand for a multi-value field?
So far I've tried:

implementing a #validate handler to alter the $form_state array to match the $form_state array produced by submitting a multi-value field — no effect
implementing hook_nodeapi() $op==='validate' to alter the field values in the $node object — no effect
Answer: You need to implement the hook_nodeapi and use the operation "presave"
Presave will have all the data submitted from the form and you can then alter it here just before it goes into the database.
If you have the devel module do a dpm($node); to see what data you are getting.
the important thing is that the field for multi values will be expecting an array so it may be as simple as grabbing the data from the form and adjusting it to pass it as an array.
EDIT
Aah ok validation....
I would probably turn off validation for that item by using the: '#element_validate' property, this way you can target validation for that specific element see the fapi docs on drupal.
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#element_validate
Comment: The form isn't getting as far as the `presave` nodeapi op — it gets hung up during the validation phase, since this now-single-value field doesn't think it has valid data.
Comment: Regarding the edit:  Thanks, @Andre — that sounds like a far less invasive option than the answer I proposed.
Answer: A working, but ugly, solution — manually remove the form validation errors:
/*
 * Implementation of hook_form_FORM_ID_alter().
 */
function custom_form_custom_node_form_alter(&$form, &$form_state) {
  // http://drupal.org/node/726282
  $form['#after_build'][] = 'custom_after_build';
  $form['#validate'][] = 'custom_validate';
}
function custom_after_build($form, &$form_state) {
  $form['field_custom' ]['value']['#multiple'] = false;
  return $form;
}
function custom_validate($form, &$form_state) {
  // since we're now rendering a single-value-field, we need to move the data back into the multivalue-field format CCK expects
  $selectedValue = $form['field_custom']['#value']['value'];
  $form_state['values']['field_custom'][0]['value'] = $selectedValue;

  // clear related form errors set by other validation handlers
  $errors = form_get_errors();
  form_set_error(NULL, '', TRUE);
  foreach ($errors as $k => $v) {
    if ($k !== 'field_custom][value') {
      form_set_error($k, $v);
    }
  }

  // clear related messages set by other validation handlers
  $errors = drupal_get_messages('error');
  foreach($errors['error'] as $error) {
    if ($error !== 'Custom field is required.') {
      drupal_set_message($error, 'error');
    }
  }
}


How to pass a bash script variable to AWK using $() and collect the ouput

Question: The problem is in following:
solaris:~/src/brk$ cat .file
one xxx 123
two yyy 123

three bbb 321

four xyz 123

Script:
solaris:~/src/brk$ cat scr.sh
...
PATH="dist/"
LINE=$(awk '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf $2" "}' .file)
echo "LINE=$LINE"
...

Output:
xxx yyy bbb xyz

I want the following output:
dist/xxx dist/yyy dist/bbb dist/xyz

How can I modify awk expression to get the desired output?
Comment: possible duplicate of [Passing variables into awk from bash](http://stackoverflow.com/questions/16340775/passing-variables-into-awk-from-bash)
Answer: You can set variables in awk using the -v switch:
PATHI="dist/"
LINE=$(awk -v p=$PATHI '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf p$2" "}' .file)

Comment: Ops, thank you. I thought -v won't work inside $() but it works. Then this question is duplicate of duplicate and I probably need to remove it.
Answer: Do not use PATH as a variable name! That is already used by the shell. Always use lower-case variables in bash for this reason: the ones used by the shell are always uppercase. Than, you can pass a variable to awk:
dir="dist/"
line=$(awk -v dir=$dir '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf dir$2" "}' .file)


Double staccato?

Question: I was reading in "Gandalf" by Johan de Meij in the flute part, and found what looks like a note with two staccato markings on it (vertically stacked dots). I have attached a picture for reference.
Comment: Most likely someone's idea of "super extra staccato"
Answer: It's a misprint. There's a notation for Staccatissimo.  This isn't it.
Comment: It looks like the engraver put the note heads on the D line and then corrected them to A but forgot to remove the staccato dots for the Ds.  And it does look very much like it was engraved by hand.  Look at the uneven termination of the crescendo wedge and the unequal length and distribution of the dashes in the dashed (all'ottava?) bracket above the staff.
Comment: Out of curiosity, what _is_ the notation for staccatissimo?
Comment: https://en.wikipedia.org/wiki/Staccato#Staccatissimo has a picture of the notation.
Comment: @AndyBonner more evidence in favor of the hypothesis that the note heads were originally on the D line.  Had they originally been engraved for low As, the stems would have been longer and the beams and therefore also the _ff_ lower, as in the next beat.
Comment: @phoog Not to mention, it would be nice if the *ff* were moved down a bit and the beams of the sixteenths were allowed to get out of the staff.

Double staccato?


Second derivative near a minimum positive?

Question: If I have a smooth real valued non-constant function $f$ with isolated minimum at $x_M$ does that mean that close to $x_M$ its second derivative must be positive? I.e. must there exist $a > 0$ so that
$$
\begin{align}
f''(x_M + \varepsilon) > 0 \\
f''(x_M - \varepsilon) > 0
\end{align}
$$
for all $\varepsilon \in (0, a]?$ If not can someone give an example?
Comment: What do you mean by "isolated minimum"?
Comment: It's true. But a small correction: there exists a positive $a$.
Comment: @MichaelHoppe How is this a counterexample? The second derivative of $x^4$ is $12 x^2$ which is always positive away from the minimum at $x = 0$.
Comment: @GregMartin I mean with that $f(x) > f(x_M)$ for $x$ near $x_M$.
Comment: Take $x^4$ as an counterexample.
Answer: No, nothing can be said about the sign of $f''$ in the vicinity of an isolated minimum.
An example is the function $f$ defined by
$$
 f(x) = e^{-1/x^2}\left(3 + 2 \sin(\frac {1}{x^2})\right)
$$
for $x \ne 0$ and $f(0) = 0$. $f$ is infinitely often differentiable and has an absolute minimum at $x=0$. For $x \ne 0$ is
$$
 f''(x) = \frac{2e^{-1/x^2}}{x^6 }
\left( 6 - 8 \cos(\frac {1}{x^2}) - 9x^2+6x^2\cos(\frac {1}{x^2})-6x^2\sin(\frac {1}{x^2})\right) \, .
$$
For sufficiently small $|x|$ is
$$
f''(x) \le \frac{2e^{-1/x^2}}{x^6 }
\left( 7 - 8 \cos(\frac {1}{x^2})\right)
$$
and that is negative if $\cos(1/x^2) = 1$, which happens arbitrarily close to zero.


How can I override confirm dialog box in Dropzone.js?

Question: I am trying to implement dropzone on my project. I have created a custom confirm dialog box and I have used it on every parts of my project. I want to use the same custom confirm dialog box on dropzone as well. How can I do it?
const initDropzone = (obj) => {
const newobj = obj;
console.log(newobj);
console.log(newobj.options);
newobj.confirm = function (question, accepted, rejected) {
  console.log('asking question');
  mscConfirm({
    title: 'Management Console',
    subtitle: question,
    dismissOverlay: true,
    onOk() {
      accepted();
    },
  });
};
return newobj;
}

Answer: Here is what worked for me... I have added this code:
$("div#resource_upload_{{ $lecture->id }}").dropzone({

    // here go your other dropzone options

    // this option stops the files form auto-uploading
    autoProcessQueue: false,

    // here we add the question
    init: function (){

    // get the dropzone object
    myDropzone = this;

    // overwrite the addedfile function
    myDropzone.on("addedfile", function(event) {

        // this is my confirm function, you can insert your
        var r = confirm("Press a button!");

        if (r == true) {
            txt = "You pressed OK!";
            // this starts the upload proces....
            myDropzone.processQueue();
        } else {
            // ...or not
            txt = "You pressed Cancel!";
        }
    });
});

So, autoProcessQueue stops the files from uploading, and then you overwrite the "addedfile" function, and do as you please in it.
myDropzone.processQueue() continues the file upload.
Hope this helps.
Answer: You can overwrite the default confirm.
Dropzone.confirm = function(question, accepted, rejected) {

    showConfirm(question);

    $(document).on('click', '#accept-confirm', function() {
        hideConfirm();
        accepted();
    });

}

I'm jus trying to figure out how to handle accepted & rejected myself though because my way only allows me to remove one uploaded file. After the first one I get an error

Uncaught TypeError: Cannot read property 'removeChild' of null

It is in the docs under http://www.dropzonejs.com/#dropzone-methods but there's not much info about it.
Answer: If you override the removedFile function, you can add customised script to confirm deletion as the file preview won't be automatically removed.
For example:
new Dropzone("#dropzone_container", {
        autoDiscover: false,
        uploadMultiple: true,
        parallelUploads: 1,
        maxFiles: 10,
        addRemoveLinks: true,
        //This will override the removedfile event
        removedfile: function (file) {

               //This is where you can add custom script to confirm deletion;
               //You could use Sweetalert 2 or whatever you prefer than the ugly JS ugly alert box

               //This will manually removed the file
               file.previewElement.remove();
        }
);

Comment: This event appears to fire after the fact. I call it and the confirm still appears. Looking at the source, removedFile is called once user has Okayed `confirm`