Why isn't D the "most central" note?

Question: When laying out the notes in the two-dimensional Wicki-Hayden layout, which is the most symmetrical layout I know of, it is visually clear that D is the "most central" note.
Why, then, doesn't D play a central role in music theory?  Or does it?  And similarly for the related Dorian scale.
Comment: No, I mean first in the order of listing (i.e., mode number 1) in every medieval and Renaissance source. You could look at Zarlino, Cerone, Kircher, the Liber Usualis, etc.
Comment: It did play a central role, but because of tradition, not symmetry. D was the final of the first mode and the first psalm tone.
Comment: Do you mean 'first' in chronological order? Interesting! Any source/reference for that?
Answer: D's central position in Wicky-Hayden layout is an artifact of the fact that Dorian mode is a symmetric scale (its descending interval pattern and ascending interval pattern are the same) in some tunings, including the twelve tone equal temperament (and it's the only such diatonic mode).
Even though I'm sure this mathematical property of Dorian mode has been exploited by some musicians, I'm not sure whether it has any real psycho-acoustic importance. Not all mathematical properties have psychological consequences.
In this case, Western musical tradition does not seem to care about this symmetry as much as it cares about the fact that I-IV-V triads create a major (Ionian) scale (another mathematical property).
Besides, this symmetry does not exist in just intonation (with its greater and lesser whole tones, between C-D and D-E respectively). It's a by-product of certain tunings.
Comment: This symmetry exists in just intonation. Putting the base tone in the center, the interval series  10:9, 16:15, 9:8,9:8,16:15,10:9, complies both with the diatonic and the symmetry. It has only G major and D minor. Another idea would be: | A | 10:9 | H | 27:25 | C | 10:9 | D | 10:9 | E | 27:25 | F | 10:9 | G |. It has G major and F major as well as E minor and and D minor. If these systems were not in use (or even not discovered yet), this might have prevented people from thinking in this symmetry.
Answer: One could equally say that G#/Ab is also 'central'.I guess that looking at a keyboard,each is valid. But a violin, a guitar, a sax., a trumpet?
In written music, one could argue that D is in fact not central, as C takes that position, being in the exact middle of the treble and bass clefs.Symmetry is co-incidental, and not that important, otherwise all girls would be called Hannah and boys Bob!
Answer: Good question. I've wondered about this before too. For example, in my answer to this question I used D as my central note in the table, because its half way between the sharp keys and the flat keys. Similarly, the Dorian scale is symmetric so that it is its own inversion -- sort of a musical palindrome (WHWWWHW). Also Sir Issac Newton recognized this symmetry: when comparing the color wheel to a musical scale, he started with red at D.
As for why this symmetry isn't more generally significant, I'm not sure there's really a good answer, unless it has to do with music in general eschewing symmetry. These asymmetries give the scale directionality and purpose. For example the half-step between the leading tone and the tonic gives rise to the whole idea of tonality, and dominants resolving to tonic.
Answer: D is the most important note.  Take a look at the Graduale Romanum (or any repository of Gregorian chant) and see how D dominates as the final. Look at the music from the middle ages, or of Machault, of Dunstable and Dufay - same story. But these last two started a trend to base harmony on triads, and they are either major or minor - and so they modes we know today as "major" and "minor" inexorably became central, and by about 1600 all other modes were considered "out" - at least as far as classical music is concerned; in folk music(s) D is still pretty important.
Comment: This is probably closest to the correct answer.  D was at the heart of the modal system for nearly 1000 years, much longer than C has been the "central" note of Western music.  The other answers are correct that harmonic concerns and theories about the superiority of the major triad eventually transferred the status from D to C, but this was a relatively late development in Western music (circa mid-1700s).
Answer: Here's my two cents (the way I've justified this to myself at least)
Let's look at the A minor pentatonic scale, which is symmetric: A C D E G. (intervals 3,2,2,3 semitones.) Now another way building it up from fifths: C G D A E. Indeed either way it looks like D is the central note.
Now let's look at this scale harmonically. We have four fifths, two minor thirds, and one major third, C-E.
With this major third, we can construct a total of two triads: C major C E G and its relative minor, A minor A C E. These are the only fully consonant triads available in this scale.
So the most fundamentally harmonic thing about this set of notes is the pair C-E. Now we normally name an interval by the lower note, as it is the more fundamental. Hence the note that most stands out in this group of notes is the C. So we can reorder to get C D E G A, known as C pentatonic major, or (uniquely out of the five possibilities) simply C pentatonic.
The same applies for the diatonic scale of Am/Cmaj (or simply C). We ad one extra fifth at the beginning and the end and get the following portion of the cycle of fifths: (F) C G D A E (B). Now we have three major thirds, which enables us to build three relative major/relative minor chord pairs: Fmaj/Dm, Cmaj/Am and Gmaj/Em.  But again, the most central of these is the major third C-E.
Comment: @Tim the Wicky-Haden layout, like the piano keyboard, is biased toward the natural notes (A minor / C Major.) I understood the OP's question as *"if the piano keyboard and diatonic scale is symmetrical about D, why isn't D considered the most important natural note?"* Or to put it another way *"why isn't the Dorian, which is symmetrical, considered more important than major and minor?"* Obviously if you change to a different key it will be symmetrical about a different note (always the root of the Dorian mode, a tone above the root of the major scale, or a fourth above the root of the minor.)
Comment: @Tim Yes, the intervals are the same in all minor pentatonics. Ab minor is enharmonic to the more familiar scale G# minor (the relative minor of B major, whose "central major 3rd" is B-D#.) Bb minor is the relative minor of Db major, whose "central major 3rd" is Db-F. If you look at pythagorean tuning, you can see that the notes of both the pentatonic and diatonic can be picked out of a straight sequence of 5ths. It's what makes those scales so universal. The Wicky-Haden layout mentioned by the OP also makes this very apparent.
Comment: would this concept work if one took, say, Ab min.pent, or Bb min. pent. ? They will still be symmetric ? The intervals will remain the same, but they'll be centred somewhere else.                 It's interesting that the cycle of 4ths/5ths can be wheedled out of the pent., though.
Comment: So, if it's all a moveable feast, how does D feature as the centre in any apart from Am pent.?
Answer: D does play a central role in music theory, in the sense that it's the center of the Circle of Fifths which is intimately linked to key signatures.
... F♭ C♭ G♭ D♭ A♭ E♭ B♭ F C G D A E B F♯ C♯ G♯ D♯ A♯ E♯ B♯ ...
This is why the Wicki-Hayden keyboard (which features a chain of P5's along its /-diagonal) has D in the middle.
However, as you point out in your question, the central note D gets little emphasis in music theory.  Rather, it's the seven notes in the center, forming the diatonic scale of "natural" notes, that are collectively emphasized.
On the piano keyboard, this emphasis physically takes the form of the separation between white and black keys. On the Wicki-Hayden keyboard, it takes the form of naturals being placed in the center of the keyboard while the black keys are relegated to the edges.
As for the lack of emphasis on D itself, this largely because modern Western music typically uses only two of the seven modes of the diatonic scale: Ionian (major, C-D-E-F-G-A-B-C) and Aeolian (natural minor, A-B-C-D-E-F-G-A), leaving other modes, including Dorian (D-E-F-G-A-B-C-D) neglected.  Why this is the case is the topic for another question.
Answer: I think the real answer may be that modes in some ways weren't as fundamental to Western polyphonic music as hexachords were, and those were based around a central "natural" hexachord based on (a somewhat movable) C/ut ("ut" being the original term for "do"). This hexachord ran from C to A, and was symmetrical around E-F (mi-fa). It was accompanied by a "hard" hexachord (ut to la starting on G, which supplied B♮) and a "soft" hexachord (ut to la starting on F, which supplied B♭). The modes were seen as a kind of movement between the hexachords guided by their solfeggio aspects.
This was from Guido d'Arezzo's singing theories, but Guido was the person who started the ball rolling towards modern notation, and early notated polyphonic music was entirely vocal, so his influence on matters like this was incalculable. Information on this can be found here: Hexachords, solmization, and musica ficta.
I'll be frank to admit that I'm still wrapping my head around all this, but it strikes me that a relocatable "mi-fa" may do a better job of explaining modal mutations in even modern music (for example, the use of sharp 6 and sharp 7 in the minor) than a multiplicity of scales does.
Answer: The mathematical symmetries in our scales, which have D as the symmetry axis, aren't reflected in music because upward and downward intervals do not have symmetrical acoustic functions.
If you bang a low C on the piano with the pedal down, you will likely hear the first few notes of the harmonic series, especially C's, G's, and E's. This suggests that the notes C, E, and G will sound good together, and that among them, C is naturally the root (most important) note. This process does not work in reverse. No matter how hard you hit a high C key, you will not hear the "undertones" F and A-flat. When the ear hears a minor chord such as C-Eb-G, it is happier to accept it as a deviation from the major, with lowered third and C still functioning as root, than as an inverted formation with G as the root.
So if we think of the diatonic scale as a stack of 5ths, F-C-G-D-A-E-B, then it stands to reason that F and C are much more stable and likely to be used as tonics than E and especially B. And indeed, looking cross-culturally and cross-historically, this is true. The intermediate notes G, D, and A are also viable tonics. Our preference for C reflects more recent trends in Western music, especially the use of the dominant seventh chord G-B-D-F where the resolution of the tritone (B to C, F to E) strongly emphasizes C major.
Answer: Any answer that supports the assertion on which this question is based, but which does not explicitly reference a particular instrument or clef is not entirely correct in that regard. There is no really 'central' note in Western music theory (even before atonalism).
The popular clefs and the white keys on a 12-EDO keyboard completely facilitate the major scale starting on C. They completely facilitate the natural minor scale on A. They completely facilitate the Dorian mode on D. Modern music practice likes mid-range major scales on keyboard instruments, so middle C is a popular tone. Why the Ionian mode and the common keyboard are so popular today is another question, and would probably deserve more than a few sentences, but here goes anyway.
One answer is the major triads built on I-IV-V as mentioned in another answer, but that bites its tail a bit: where does the idea of major triads come from, not to mention the diatonic scale? The simplest way to construct the major scale is either through 3-limit (Pythagorean, steps of a perfect fifth up (overtone) or down (undertone)) or 5-limit (perfect fifths and major thirds) means, and to observe the decisions made in the process.
A rough measure of triadic harmonicity is to multiply the harmonics together, so a perfectly major triad ranks very well by this measure 1:3:5 = 15. Also we tend to accept dissonances better in a higher range, so major triads may be said to 'outperform' minor triads by this measure, too, since the minor third is in the higher range.
Comment: What do you mean by "Also we tend to accept dissonances better in a higher range, so major triads may be said to 'outperform' minor triads by this measure, too, since the minor third is in the higher range."?  When you say "higher" do you mean higher in the overtone series?  Or do you mean to say that dissonances that appear at higher frequency are more acceptable?
Comment: Good question, since the 'truest' distance measure in music is harmonic distance (arguably). In that case, I just meant higher in pitch. For instance, to my ear a CFG sounds 'more consonant' than CDG, even though they are just inversions of the same intervals. Granted, the effect is less striking between minor and major (and some may consider it negligible).
Comment: I believe I understand now.  The one concern I would have is how this would be applied to other types of intervals.  If your thoughts of a major triad being more consonant than a minor triad have to do with the fact that the major third is a half-step larger, then why wouldn't a TT be more consonant than a P4?  I think the real reason why the major triad seems more consonant is that the major third appears in the overtone series earlier, meaning that they are more related to the fundamental.
Comment: But a TT does not share the same intervals with a P4, whereas both a major and a minor triad can be decomposed into intervals { M3, m3, P4, P5, m6, M6, 8ve }. So it requires a case of "all things otherwise equal".
Comment: That makes more sense.  How about the 7?  When I hear a m7 it sounds considerably less dissonant than a major seven.  It also appears sooner in the overtone series.
Comment: Yes, notice that the harmonic distance eventually approaches the pitch-wise distance, so we can roughly say that tiny intervals have a rather high dissonance. The minor seventh is usually considered a rough approximation of the 7th harmonic. Not a very good one, though, just as M3 is also famously bad in modern tuning. That's why many folks prefer 19-EDO, 22-EDO, 31-EDO, or 41-EDO over 12 equal divisions per octave. (They just haven't worked out that little problem called theory yet :))
Comment: (Many instruments are still capable of working pure M3 and harmonic sevenths into the usual scheme. It's claimed that this is the origin of 'blue' notes in jazz, and that barbershop quartets have an intricate way of achieving truer harmonics.)
Answer: There are piano methods which point out the symmetry of the keyboard is based around D or G#/Ab rather than the ubiquitous all white keys C major scale.
I think the place I first heard of it is: Mastering Piano Technique: A Guide for Students, Teachers, and Performers, By Seymour Fink

Why isn't D the "most central" note?


Splitting an Int to 3 bytes and back in C

Question: I have the following code to split an int into 3 bytes and then back:
#include <stdio.h>
#include <stdint.h>

int main()
{
    int a = 626;
    uint8_t msb = (a >> 16) & 0xff;
    uint8_t msb1 = (a >> 8) & 0xff;
    uint8_t lsb = a & 0xff;

    printf("MSB: %u, MSB1: %u, LSB: %u\n", msb, msb1, lsb);

    uint8_t h1 = msb << 16;
    uint8_t h2 = msb1 << 8;
    uint8_t h3 = lsb & 0xff;

    int b = h1 | h2 | h3;

    printf("Final: %d\n", b);

    return 0;
}

When I run this code the output is as follows:
MSB: 0, MSB1: 2, LSB: 114
Final: 114
I should get Final as 626 but I get 114. It would be great if someone could help out. Thanks
Comment: `uint8_t h1 = msb << 16;` - have you noticed the resulting type?
Comment: `int` being _three_ bytes wide is unusual, are you sure it shouldn't be four?
Comment: `int` is not guaranteed to have more than 16 bits. If you want a specific width, use fixed width types! Also shifting signed integers is problematic. Depending on value, shift count and direction it is implementation defined or even undefined behaviour. Use unsigned types!
Comment: @zwol: OP confuses byte and "8 bits". He seems to want 8 bits. And there are indeed CPUs with 24 bit integers.
Comment: @Olaf Yes, there are, but they are unusual and I doubt OP would be asking a question like this if they were working on one of them.
Comment: @zwol: I'm not sure. The question is typical for a beginner in the job first time confronted with such an architecture. Many C courses at universities are not worth the time. Problem is the students are often not even aware they are not really prepared for the job. ("You need to have a certain degree of understanding of the matter to understand you don't understand a problem")
Answer: A possible solution is
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    int a = 626;
    uint8_t msb = (a >> 16) & 0xff;
    uint8_t msb1 = (a >> 8) & 0xff;
    uint8_t lsb = a & 0xff;

    printf("MSB: %u, MSB1: %u, LSB: %u\n", msb, msb1, lsb);

    uint32_t b = msb;
    b = (b<<8) | msb1;
    b = (b<<8) | lsb;

    printf("Final: %d\n", b);

    return 0;
}

As you can see:

I changed the type of b: left shift signed values can be UB.

6.5.7/4 [...]  If E1 has a signed type and nonnegative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

What you did it was right shift a char (8 bits) right by 8 or 16, which means you lost all your bits. So as you can see you can, first of all, assign first value to a larger variable (unsigned int) and after that shift it.
Answer: Try using something bigger than uint8_t
e.g. uint32_t
Answer: First make sure you aren't mixing signed and unsigned integers. Then I will assume the input integer is an unsigned 32.
My solution is the following :
#include <stdio.h>
#include <stdint.h>

int main()
{
    uint32_t a = 626;
    uint8_t bytes[4];

    bytes[0] = a & 0xff; //contains Lsb
    bytes[1] = (a >> 8) & 0xff;
    bytes[2] = (a >> 16) & 0xff;
    bytes[3] = (a >> 24) & 0xff; //contains msb

    printf("Bytes: %u, %u, %u, %u\n", bytes[0], bytes[1], bytes[2], bytes[3]);

    uint32_t b = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0];

    printf("Final: %u\n", b);

    return 0;
}

Where as Mischa said. You need to work the result back in something larger than 8 bits. Otherwise you are loosing the bits when shifting more than 8 bits.
Comment: If using all recommended warnigs, you will get a truncation warning. Add a cast where necessary (I'll leave to you or OP figuring out which are:).
Comment: Your solution has the same problem as OP. When you `bytes[3] << 24`, you lost the bits. Check @LPs answer for details.


Monitoring multiple apache hosts inside of a folder

Question: I did some searches before typing this so please don't throw too many cans at me if I didn't get the search done correctly :)
I have a VPS serverwith a tiny slew of drupal instances. Something like 25/30 that have accumulated over time. I was wondering if there is some kind of program that is pretty elegant at tracking statistics of all enabled apache hosts or something like that, without having to install something huge like awstats that also requires a manual entry for each virtual host.
Sometimes my IO rate goes crazy on the server and I cant quite figure out who is doing it, if that sheds any light on the nature of my need.
Thanks so much in advance.
Comment: What do you mean by "tracking statistics of all enabled Apache hosts"? Web/visitor statistics or server performance broken down by vhost?
Comment: server performance broken down by vhost
Answer: 25/30 drupal and i/o problems :-)
Drupal 7 makes some really intensive usage of a bad file_scan_directory function.
Check this drupal bug for example or this and that.
The problem for you is 25/30 websites but all of them are managed by the same apache processes. So it is quite hard to isolate the real problematic drupal instance from the system monitoring tools.
With advanced mode for apache status you could check which Virtualhost is currently running on which apache process (if the long request is long enough for you to catch it). You could also use various calls to lsof command to identify  which of the apache children is parsing the disk, and what directories are implied (that would give you the drupal instance). Of course it will be easier with one virtualhost for each Drupal (no multisite drupal deployment).
Now you should at least track the response time of each website, using nagios with check_http, or munin, or one of all the various monitoring tools and web services available. Note that for most of these http monitoring tools the most important parameter is to indicate the server IP and DNS, so that the 25 or 30 different websites are really checked, and not only the first one (default virtualhost). If they all respond in the same time chances are that you forgot to tell the monitor tool the right DNS to use on that http request.
Having the response time for all the websites you will see after any upgrades if one of the drupal instance as lost 1s in the average response time (for example) and this one will be the right target for a deeper analysis.
Answer: I assume that from the statistics point of view Awstats would do the job.
Also I assume that your point here is to prepare for possible new Virtual Hosts, and because of that, automate the generation of statistics for new sites.
Well, here's a try.

Use Awstats and install it normally.
Make sure your virtual hosts are configured in a standard way so that reading their configuration can be automated. Since you use Apache, you may grep for ServerName directive from inside the sites-enabled -directory.
Create a template config file /etc/awstats/template/awstats.template.conf containing $SITE in both LogFile and SiteDomain directives to enable the customization later on.
Now, create a wrapper to look for sites that do not have awstats configured and run the actual update. It could be something like this:

    #!/bin/sh
    # WARNING, UNTESTED CODE !

    AWSTATSDIR=/etc/awstats
    HTTPDIR=/etc/apache2/sites-enabled

    # Searching for new sites
    grep -i ServerName $HTTPDIR/*|grep -v "\#"|awk '{print $3}'|while read SITE
    do
        if [ ! -f $AWSTATSDIR/awstats.${SITE}.conf ]; then
            # Here creating the custom config based on the $SITE variable placed into template
            sed -e "s/\\\$SITE/$SITE/g" $AWSTATSDIR/template/awstats.template.conf > $AWSTATSDIR/$awstats.$SITE.conf"
        fi
    done

    # Ships with the package, runs updates all /etc/awstats/awstats.*.conf configs.
    /usr/share/awstats/tools/update.sh

And in the cron, simply:

    */10 * * * /path/to/above/script.sh
Answer: Try monitoring your server usage using tools like NewRelic, Amon (a NewRelic-like but self-hosted) or Munin.
Answer: Let's look at this from a slightly different angle.  You've got 30 sites on your VPS.  Presumably, you do not actively maintain all of them.  I'd also image that you do not want one compromise to compromise the rest of your sites.
In my opinion, the only way to run large numbers of PHP sites on the same machine is to make sure that all their code executes as different users.  The easiest way to do that is to install and configure suPHP.  This also helps you with your actual problem, as once each website is running as it's own user, you can easily determine which ones are using up all of your resources.
It's going to be fairly tricky for you to track down which website is causing the load if everything is running as the same user.
Answer: You will probably use some log analysis tool like awstats (that you mentioned). You can also use one of the open source 'google analytics' competitors like Open Web Analytics.
Answer: There is a good utility to detect who's read\writes to disk: iotop
Comment: Not when those apache processes are servicing multiple virtualhosts and you need to isolate which one of them is the troublemaker.
Comment: U could use `/server-status` or log analisys tools
Answer:
you can use Piwik - you can install it and monitor even from a remote server
or can install awstats on a local web server in your LAN and via cron jobs download and process daily web server's log files you are monitoring


Como obter os itens duplicados para Ids especificos?

Question: Como obtenho a lista de itens que se repetem com o mesmo fpId e eclId?
var lst = (from fp in FPIds
        from et in ETIds
        from ec in ECIds
        join eclp in ECLP on ec equals eclp.ecId
        join ecl in ECL on eclpId equals clId
        select new  {
                fpId = fp,
                etId = et,
                ecId = ec,
                eclId
        }).ToList();

Comment: Recomendo você não encurtar nomes de variáveis, deixa o código muito confuso para quem for ler.
Answer: consegui resolver dessa forma, postei como resposta, pois pode ajudar outras pessoas. Obrigado!
if (lst.GroupBy(p => new { p.fpId, p.eclId })
       .Where(x => x.Count() > 1)
       .Sum(x => x.Count()) == 0){

                }


use route in controller

Question: i'm trying to fetch data(jobs) and display each single job i have route for jobs and route for single job but when i use route in controller i get route not defined even all is good please check my question
ajax call

use route in controller


Transforming a closed polyline to a boundary of convex polygon

Question: Let $\ell$ be a closed polyline on a plane, i.e.
$$\ell = \bigcup_{i=1}^n A_iA_{i+1}$$
where $n\ge 3$ is an integer and $A_1, \ldots, A_n$ are points on a plane such that for every $i=1,2,\ldots, n$ points $A_i, A_{i+1}, A_{i+2}$ are not collinear (we assume that $A_{n+1}=A_1$ and $A_{n+2}=A_2$).
Show that there exists a convex polygon $B_1B_2\ldots B_n$ such that for every $i=1,2,\ldots,n$
$$B_iB_{i+1}=A_iA_{i+1}$$
(again, $B_{n+1}=B_1$).
Comment: Can the sides of the polyline intersect?
Comment: They can intersect.
Answer: $n$ sides $l_i=A_iA_{i+1}$ can form a convex polygon if and only if every side is less than the sum of the other sides. If we define $n$ vectors $\vec{l_i}=A_{i+1}-A_i$, then by definition $\sum_{i=0}^n\vec{l_i}=0$. It follows that for every $k$ between $1$ and $n$:
$$
l_k=|\vec{l_k}|=\left|\sum_{i\ne k}\vec{l_i}\right|\le
\sum_{i\ne k}|\vec{l_i}|=\sum_{i\ne k}{l_i}.
$$
Notice that inequality is strict if vectors $\vec{l_i}$ are not all on the same line.


copy one column data from result set to a column in another table , in oracle

Question: I want to update a column in table A (100 row within 5000 row) with 100 row of a column in another table, randomly . some thing like this(but in a loop for 100 records):
  update kc7crdtfile
     set kc7crdtfile.k7748crid = (select y.k7749crid from KC7CTBURQ y where rownum<100)
   where kc7crdtfile.k7749crid IS NULL
     AND kc7crdtfile.k7732sts in (5, 6, 7, 9, 12)

Comment: Your update will throw error: Single row subquery returns multiple rows. What joins or identifies the 100 rows from table A with the other table? In other words, what is the matching column between kc7crdtfile and KC7CTBURQ?
Comment: Each `k7748crid` can only have one value, not 99 values. You have to specify which value you want your `update` to choose.
Answer: If you have a column linking the two tables other than k7748crid, you could use a correlated update.  Refer : Example
Running a single update using the above would be efficient for large records than a loop.But, since you expect only 100 rows to be updated, you may also use an implicit cursor loop by filtering out the updated values using ROWNUM = 1 .This would work even if there is no linking column between the two tables other than k7749crid.
BEGIN
   FOR rec IN (SELECT y.k7749crid
                 FROM KC7CTBURQ y
                WHERE ROWNUM <= 100)
   LOOP
      UPDATE kc7crdtfile k
         SET k.k7748crid = rec.k7749crid
       WHERE     k.k7749crid IS NULL
             AND k.k7732sts IN (5,
                                6,
                                7,
                                9,
                                12)
             AND NOT EXISTS
                    (SELECT 1
                       FROM kc7crdtfile k2
                      WHERE     k2.k7748crid = k.k7748crid
                            AND k2.k7749crid IS NULL
                            AND k2.k7732sts IN (5,
                                                6,
                                                7,
                                                9,
                                                12))
             AND ROWNUM = 1;
   END LOOP;
END;
/


run some script when session end in Yii 1

Question: My session configuration in config file (main.php) is:
'session' => array(
    'class' => 'CDbHttpSession',
    'timeout' => 60*60, // 1 hour
),

And I put this code in layout file:
<?php if (!Yii::app()->user->isGuest) { ?>
    <meta http-equiv="refresh" content="<?php echo Yii::app()->params['session_timeout'];?>;"/>
<?php } ?>

So far, there are no announcement when the session end. When I refresh the browser, the session is already end.
After session (or almost) expired, I want to tell user that the session is going to expire like countdown timer dialog or something.
I have tried this extension http://www.yiiframework.com/extension/timeout-dialog/. but it didn't work for my website with the configuration. The extension show the dialog when the session is 1 minute left, but when I clicked the button to resume the session, it didn't work because the session still running. I know it  because when I refresh the browser, the session is already expired.
So, what I must do?
At least, I want to know how to get the remaining time of the session when browser refreshed, so I can modified the announcement by myself.
thanks :)
Answer: I think I solved the problem by myself.
Here the explanation:
It's important to be known that Session works on server. When browser accessing to server, session timeout will be restarted. There are no ways to know the remaining time of the session.
So, to warn user that session will expire must be handled in client with javascript or jQuery. I created handlers that will warn user when the website idle (no activities) or when the session timeout is almost expired. User will be warned by a confirmation dialog that asks to user whether would keep sign in or log out. When user decide to keep sign in, client will do ajax to do whatever-script in server (because that will restarted the session timeout).
Because my Yii website using bootstrap 3, So the dialog panel that I create will use bootstrap code.
This is in view layout:

<button id='tombolmodal' style="display:none" type="button" class="btn btn-info btn-lg" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#myModal">Open Large Modal</button>

                   ATTENTION!

                    It seems you are in inactive

                     seconds left to logout your account

            <?php $this->widget('booster.widgets.TbButton',
                array(
                    'buttonType' => 'ajaxSubmit',
                    'context' => 'primary',
                    'label' => 'Keep Sign In',
                    'url' => CController::createUrl('site/keepalive'),
                    'ajaxOptions' => array(
                        'type' => 'GET',
                    ),
                    'htmlOptions' => array(
                        "data-dismiss"=>"modal",
                        'id'=>'staysignin',
                    )
                )
            );
            ?>
            <?php $this->widget('booster.widgets.TbButton',
                array(
                    'context' => 'default',
                    'label' => 'Logout',
                    'htmlOptions' => array(
                        "data-dismiss"=>"modal",
                        "id"=>"forcelogout"
                    )
                )
            );
            ?>

And this is my SiteController:
public function actionKeepalive()
{
    if(Yii::app()->request->isAjaxRequest){
        Yii::app()->session->open();
    }
}

public function actionLock($id)
{
    $user = User::model()->findByPk($id);
    Yii::app()->user->logout();
    $this->render('lock', array( //refers to lockscreen page
        'user'=>$user,
    ));
}

And don't forget to write the code from my question above.
That code worked very well in my website.

This code is still have a weakness. When you log in with same account in different browser, they are not related to each other. they are independent. So, if the session in first browser has expired, the session in other browser may not expired yet or even has already expired earlier.
You can also see the implementation in Yii2 from this link: http://www.hafidmukhlasin.com/2014/10/01/yii2-create-lock-screen-web-application-with-javascript/
Thanks. Correct me if I wrong


Modify text of error message for required field

Question: I have a checkbox with a link in its title text. This is a required field and the error message references the title including the link. How can I modify the error message to remove the link from the error message text?
hook_field_validate() appears not to be called; that was my first attempt after doing some searching.
Comment: I created a module that allows specifying a custom error message:[Required Error Message](https://www.drupal.org/project/required_error_message).
Comment: If I understand you correctly, you want this: http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_status_messages/7
Answer: Quick and easy fix is to use the String Overrides module. Here is a quote about it (from the module's project page):

Provides a quick and easy way to replace any text on the site.
Features:

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
Answer: You can try to override the strings or theme the message as has been mentioned already. Another option is to override the validation function for that form or that field, and raise the error yourself with the message you want.
You can use hook_form_alter in various ways. You could simply replace the #validate function on the submit button on the form, and thus provide your own validation function. In that function call form_set_error to raise the validation problems.
If you want to keep the core validation for most fields and just override the validation for one field you could set #limit_validation_errors to the submit button. This allows you to define which part of the form should have errors validated (and thus, which ones should not). You'll still want to add your own validation function for the form elements you've just ignored - so add it to the functions in the #validate of the submit button.
Answer: If a field is required then the validation check for an empty value is done inside Drupal's form handling and it'll never reach your custom code.
If you were to write a custom implementation of theme_form_element() in your theme or module you could add an extra data member say #display_title with your link in it and show that as the label text in the form if present. Forms validation would then use the regular #title value for messages.
Answer: If this is the only thing you want to change, you can override strings in your settings.php file. Check out the default.settings.php file for examples on how to do this. For only changing a string or two, this is better than adding the overhead of another module.
Answer: In Drupal 8, you can alter the messages in the hook_preprocess_HOOK. Example here: How to remove status messages from admin theme?
I am not sure whether you can do the same in Drupal 7, but you could apply the same logic in the theming layer, see: function theme_status_messages


How to install UCC GoDaddy SSL Certificate on Amazon EC2 ELB

Question: I've read through this: Install SSL on Amazon Elastic Load Balancer with GoDaddy Wildcard Certificate but am still a bit unsure.
I have a subdomain: platform.mysite.com that is pointed to an ELB in Amazon.
That ELB has 5 instances that it sits in front of.
I read through this: http://www.nczonline.net/blog/2012/08/15/setting-up-ssl-on-an-amazon-elastic-load-balancer/ as well and can figure most of it out except I'm lost as to generating the CSR. Which machine do I do it on?
Do I need the same CSR for every instance?
Thanks
Answer: It doesn't matter which machine you create the private key or csr on, just so long as the machine is secure.  I use openssl to create the csr:
openssl req -new -newkey rsa:2048 -nodes -out csr.pem -keyout privkey.pem

You only need a third party signed certificate for ELB, not the other instances.  You can use a self-signed certificate for the instances, or, if you're comfortable, you can choose to make your traffic from the instances to the load balancer be regular http.  The load balancer works independently of the instances as far as ssl goes.
Update:
There are a couple of other things you are going to know.   You will have to decrypt the private key:
openssl rsa -in privkey.pem -out decryptedprivkey.pem

You might not be able to use the web-based certificate upload feature of the AWS Console because of GoDaddy's intermediate certificate.  To do this I use the IAM CLI from Amazon:
iam-servercertupload --aws-credential-file aws-credential.properties -b yourdomain.crt -c gd_bundle.crt -k decryptedprivkey.pem -s yourcertificatename

Comment: I don't really have much knowledge with the iam CLI... is there no way for me to upload the intermediate file?
Comment: Not that I know of.  The command line is not hard, though.  Just download and extract them to a directory and put your credentials in the file provided, and you're ready to go.


Achar item no array

Question: Gostaria de saber se meu código está certo. pois gostaria de pegar o nome vinculado com que está vinculado com o código(id), onde mmot recebe um numero para ser procurado dentro do array. Obrigado
    $url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

    function get_page($url){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

        foreach ($result as $key) {
            if($key['codigo'] == $mmot){
                $mmot = $key['$mmot']['nome'];
            }
        }

    }

    $marcafinal = $mmot;

Comment: se você der o return no $result ele encerrara a função ai sem executar o foreach
Comment: Oi, tentei fazer o que vc falou e tirei o return, mas continua me retornando nenhum valor :(
Comment: postei um exemplo que teste, caso queira testar ai, testei e ta ok
Answer: Essa forma da certo e nem precisa usar o curl, caso precise só editar da forma que achar melhor, exemplo funcionando:
 <?php
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');
$mmot = "60";

function get_page($url,$mmot){
    $result = json_decode($url,true);

    foreach($result as $key)
    {
        if($key['codigo'] == $mmot)
        {
            return $key['nome'];
        }
    }

}

$marcafinal = get_page($url,$mmot);

echo "Valor: ".$marcafinal;

?>

Comment: Oi usei o seu exemplo e me voltou esse erro aqui
Warning: file_get_contents(https://parallelum.com.br/fipe/api/v1/carros/marcas/70/modelos/): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in

Fatal error: Cannot redeclare get_page() (previously declared in C:\xampp\htdocs\plus\inserir.php:59) in
Comment: é que esse link (https://parallelum.com.br/fipe/api/v1/carros/marcas/70/modelos/) não existe no site, ele não retorna nada só um erro 404 que não foi encontrado nada, já esse link (https://parallelum.com.br/fipe/api/v1/motos/marcas) ele retorna um json certinho, tente ver se não mudaram o link da api
Comment: ta, obrigado. :)
Comment: dei uma olhada na api e vi que o codigo 70 não existe, se você testar esse link (https://parallelum.com.br/fipe/api/v1/carros/marcas) consegue ver todas as marcas,  e se usar dessa forma (https://parallelum.com.br/fipe/api/v1/carros/marcas/59/modelos) onde o 59 é um código válido, ele aparecerá os modelos desse código
Answer: Seu código está cheio de problemas, mas vou tentar mostrar um por um aqui. Entendi que está fazendo uma chamada pelo curl e que quer manipular a resposta, então vamos lá:
// $url está sendo declarado fora do escopo de onde será usado, no caso, o seu método
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

// essa função não foi chamada em lugar nenhum
function get_page($url){ // $url é redeclarado como alterador de parametro e ofusca a variável ali em cima

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    // está retornando o corpo da response, o bloco for ali em baixo não será executado
    return $result;

    // você sabe o que está vindo no $result para enumerar ele?
    foreach ($result as $key) {

        // quem é codigo e quem é $mmot (que nem foi declarado)?
        if($key['codigo'] == $mmot){

            // aqui nunca será processado, pois será atirado um erro na linha acima.
            // mas se $mmot fosse declarado, a linha abaixo também não faria lógica, já que está procurando a chave '$mmot' na coleção $key.
            $mmot = $key['$mmot']['nome'];
        }
    }

}

$marcafinal = $mmot;

Sua pergunta não está clara e a refatoração do seu código seria aproximadamente isso:
$url_endpoint = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    $responseValues = json_decode($result, true); // isso se sua API for JSON

    // Você precisa associar esse $mmot a algo, não pode deixar ele vago e sem declaração.
    $mmot = 0;
    $returnValue = null;

    foreach ($result as $key) {
        if($key['codigo'] == $mmot){
            $returnValue = $key['nome'];
        }
    }

    return $returnValue;
}

$marcafinal = get_page($url_endpoint);

Fiz isso levando em consideração que $mmot é um código que leva até o objeto JSON que procura por nome. Assim, você deverá especificar $mmot no método onde deixei claro ali, ou passar como um parâmetro.
Answer: Ta errado, você está declarando o $mmot dentro do if e usando ele na condição, acredito que você tenha que declarar ela antes
Comment: o $mmot ta declarado antes sim, eu declarei ele antes de fazer a função.
Comment: @VictorAugusto Então talvez esteja faltando você passar ele como parâmetro da função *(como foi mostrado em outras respostas aqui)* ou colocar dentro da função uma indicação que `$mmot` é global  => `global $mmot;`, OBS. Vale a pena você editar sua pergunta para colocar a informação que você colocou neste comentário.
Answer: Código testado e funcionando:
<?php

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function procuraMmot($mmot) {
    $retorno = '';
    $url = 'https://parallelum.com.br/fipe/api/v1/motos/marcas';
    $resultado = json_decode(get_page($url), true);

    foreach ($resultado as $value) {
        if($value['codigo'] == $mmot){
            $retorno = $value['nome'];
        }
    }
    return $retorno;
}

$resultado = procuraMmot(60);
echo "resultado: $resultado";

Achar item no array


API de Dicionário em Java

Question: Olá, procuro uma API, de dicionário, em Java para criar o programa nos seguintes passos:

Usuário entra com uma string, no caso, uma palavra;
Imprimo na tela a invocação de um método dessa API;
O qual retornará uma frase, com o significado da palavra que o usuário digitou em questão;

Exemplo: entro com a palavra "bolo", e receberei na tela o seu
  significado.

Gostaria que essa possível API suportasse múltiplos idiomas.
Answer: Pelo que entendi você quer uma API para fazer chamados em dicionários correto?
JWNL (usa  a base de dados da Java WordNet Library que é majoritariamente em ingles, existem versões em outras línguas)

http://sourceforge.net/projects/jwordnet/

exemplo de código:
<code>/** A class to demonstrate the functionality of the JWNL package. */
public class Examples {
    private static final String USAGE = "java Examples <properties file>";

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(-1);
        }

        String propsFile = args[0];
        try {
            // initialize JWNL (this must be done before JWNL can be used)
            JWNL.initialize(new FileInputStream(propsFile));
            new Examples().go();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    private IndexWord ACCOMPLISH;
    private IndexWord DOG;
    private IndexWord CAT;
    private IndexWord FUNNY;
    private IndexWord DROLL;
    private String MORPH_PHRASE = "running-away";

    public Examples() throws JWNLException {
        ACCOMPLISH = Dictionary.getInstance().getIndexWord(POS.VERB, "accomplish");
        DOG = Dictionary.getInstance().getIndexWord(POS.NOUN, "dog");
        CAT = Dictionary.getInstance().lookupIndexWord(POS.NOUN, "cat");
        FUNNY = Dictionary.getInstance().lookupIndexWord(POS.ADJECTIVE, "funny");
        DROLL = Dictionary.getInstance().lookupIndexWord(POS.ADJECTIVE, "droll");
    }

    public void go() throws JWNLException {
        demonstrateMorphologicalAnalysis(MORPH_PHRASE);
        demonstrateListOperation(ACCOMPLISH);
        demonstrateTreeOperation(DOG);
        demonstrateAsymmetricRelationshipOperation(DOG, CAT);
        demonstrateSymmetricRelationshipOperation(FUNNY, DROLL);
    }

    private void demonstrateMorphologicalAnalysis(String phrase) throws JWNLException {
        // "running-away" is kind of a hard case because it involves
        // two words that are joined by a hyphen, and one of the words
        // is not stemmed. So we have to both remove the hyphen and stem
        // "running" before we get to an entry that is in WordNet
        System.out.println("Base form for \"" + phrase + "\": " +
                           Dictionary.getInstance().lookupIndexWord(POS.VERB, phrase));
    }

    private void demonstrateListOperation(IndexWord word) throws JWNLException {
        // Get all of the hypernyms (parents) of the first sense of <var>word</var>
        PointerTargetNodeList hypernyms = PointerUtils.getInstance().getDirectHypernyms(word.getSense(1));
        System.out.println("Direct hypernyms of \"" + word.getLemma() + "\":");
        hypernyms.print();
    }

    private void demonstrateTreeOperation(IndexWord word) throws JWNLException {
        // Get all the hyponyms (children) of the first sense of <var>word</var>
        PointerTargetTree hyponyms = PointerUtils.getInstance().getHyponymTree(word.getSense(1));
        System.out.println("Hyponyms of \"" + word.getLemma() + "\":");
        hyponyms.print();
    }

    private void demonstrateAsymmetricRelationshipOperation(IndexWord start, IndexWord end) throws JWNLException {
        // Try to find a relationship between the first sense of <var>start</var> and the first sense of <var>end</var>
        RelationshipList list = RelationshipFinder.getInstance().findRelationships(start.getSense(1), end.getSense(1), PointerType.HYPERNYM);
        System.out.println("Hypernym relationship between \"" + start.getLemma() + "\" and \"" + end.getLemma() + "\":");
        for (Iterator itr = list.iterator(); itr.hasNext();) {
            ((Relationship) itr.next()).getNodeList().print();
        }
        System.out.println("Common Parent Index: " + ((AsymmetricRelationship) list.get(0)).getCommonParentIndex());
        System.out.println("Depth: " + ((Relationship) list.get(0)).getDepth());
    }

    private void demonstrateSymmetricRelationshipOperation(IndexWord start, IndexWord end) throws JWNLException {
        // find all synonyms that <var>start</var> and <var>end</var> have in common
        RelationshipList list = RelationshipFinder.getInstance().findRelationships(start.getSense(1), end.getSense(1), PointerType.SIMILAR_TO);
        System.out.println("Synonym relationship between \"" + start.getLemma() + "\" and \"" + end.getLemma() + "\":");
        for (Iterator itr = list.iterator(); itr.hasNext();) {
            ((Relationship) itr.next()).getNodeList().print();
        }
        System.out.println("Depth: " + ((Relationship) list.get(0)).getDepth());
    }
}
</code>

API de Dicionário em Java


Error during restore of MSSQL database - how to get version number of the one which created the bak file?

Question: I have received a .bak file from MSSql database from a friend of mine. He is quite desperate because his system failed, and he was able to recover the last database backup.
This should be enough to get things going, but he cannot recover the file using latest MSSql 2016.
When restoring, he gets an error message [sorry, the message is in polish language, so I'm doing my best with translation]:
Database cannot be restored on Your SQL Server 12.0.4100.1.
(Version of SQL Server which created the backp: -1.-1 file format: -1, preferred file format: 782).

At the moment, where I am it is after midnight, and the only computer I have is my macbook with storage shortage, so I can't just install Windows and SQL Server on it to have a go at trial and error with the database restore.
I am wondering, if there's something obvious I am try on a windows machine with SQL Server?
My best bet is to try and get the version of SQL Server which created the archive, hoping it will be able to restore it. Howver how can I learn about the version? -1 is not helping me much...
Is there something else I could do to restore the database or to learn the version this backup originates from?
Comment: Does your friend not know what version SQL Server he was running and which created the database backup?
Comment: No, the database was bundled as part of the application he uses. Unfortunately, the support of that app was unhelpful. After looking at the error message they just said that the backup is corrupted and there's nothing they can do. That's the backup their application created as part of daily backups.... Unfortunately, this is the only daily we have.
Answer: It seems that the bak file contains a header that can be read using RESTORE HEADERONLY FROM DISK = 'C:\path\to\mydatabase.bak'
sauce: http://www.imiscommunity.com/restore_headeronly_how_to_check_the_version_of_a_sql_server_bak_file


How to switch between lines in JTextArea in swing

Question: Am trying to set the goto line number for switching between lines in my swing application. I got the number of lines in the JTextArea instance using getLineCount() but don't know how to switch between lines?
Could any one suggest me?
Answer: You can set the caret position with textArea.setCaretPosition. Something like this would work
textArea.setCaretPosition(textArea.getDocument().getDefaultRootElement()
                         .getElement(index).getStartOffset());

In the example below, I just use a JComboBox that I populate with the indexes using the line numbers of the JTextArea. When you select on an number in combo box, the caret will move to that line of the JTextArea.
The program is not a great program though. You would probably want to populate the ComboBoxModel dynamically with the addition and removal of lines. But this should give you the answer you're looking for.
Disclaimer
I haven't added any functionality to bring the scrollpane focus the the current line. You may want to look at @Balder comment below for help with that.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestCaret {

    public TestCaret() {
        JTextArea textArea = createTextArea();
        JComboBox cBox = createComboBox(textArea);

        JFrame frame = new JFrame();
        frame.add(new JScrollPane(textArea));
        frame.add(cBox, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JComboBox createComboBox(final JTextArea textArea) {
        DefaultComboBoxModel<Integer> model  = new DefaultComboBoxModel<>();
        int lines = textArea.getLineCount();
        for (int i = 0; i < lines; i++) {
            model.addElement(i);
        }
        final JComboBox cBox = new JComboBox(model);
        cBox.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                int index = (Integer)cBox.getSelectedItem();
                textArea.setCaretPosition(
                        textArea.getDocument().getDefaultRootElement().getElement(index).getStartOffset());
                textArea.requestFocusInWindow();
            }
        });
        return cBox;
    }

    private JTextArea createTextArea() {
        JTextArea textArea = new JTextArea(10, 50);
        textArea.setMargin(new Insets(15, 15, 15, 15));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        String text
                = "0 Hello World\n" +
                "1 Hello World\n" +
                "2 Hello World\n" +
                "3 Hello World\n" +
                "4 Hello World\n" +
                "5 Hello World\n" +
                "6 Hello World\n" +
                "7 Hello World\n" +
                "8 Hello World\n" +
                "9 Hello World\n";
        textArea.setText(text);
        return textArea;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new TestCaret();
            }
        });
    }
}

Comment: To also automatically scroll the JScrollPane, you can use this approach: [Center Line in Scroll Pane](http://tips4java.wordpress.com/2009/01/04/center-line-in-scroll-pane/). Simply add `RXTextUtilitites.centerLineInScrollPane(textArea);` to peeskillets example.
Comment: Thanks a lot, a small change in the code
textArea.getDocument().getDefaultRootElement().getElement(index-1).getStartOffset());
instead of
textArea.getDocument().getDefaultRootElement().getElement(index).getStartOffset());
Answer: One way would be to set up a while statement in the following manner:
String line = null;
while ((line = text.readLine())!=null && line.getLineNumber() < desiredNumber) {}

At the end, line will refer to the line with the desired line number.


time / timezone of Linux VM on Hyper-V

Question: HI there
I installed a CentOS VM on Hyper-V server and am quite confused on the time settings.
my Hyper-V is set to (UTC-05:00) Eastern Time (US&Canada), and when installed the CentOS VM, on TimeZone selection, I chose System clock uses UTC and America/New York.
everything looks alright except the clock is showing (UTC-05:00-04:00) EDT.
I am new to Hyper-V and Linux VM, but i think what happens is the Linux VM takes the Hyper-V host time literally as UTC, since i choose America/New York timezone, it does the UTC-4 (with daylight saving), so the clock is 4 hours behind. I am not sure how to fix this. i  reset the clock but when rebooted the VM starts with the wrong time again..
how should this work? do i have to set the Hyper-V server to "real" UTC time? this doesn't seem right, and i am hoping i am missing something simple. i didn't find anything related to this yet, so any help/insight is much appreciated. i wouldn't think this is a new problem?
also i disabled the time synchrnization integration service as i haven't installed the integration service on the guest yet.
Thanks for your help.
Answer: Windows (and Hyper-V by extension) keep the "CMOS Clock" (even on VMs) in local time, not UTC. Most *nix platforms keep it in UTC then display it in local time.
By default Hyper-V will set the clock of the VM, which in this case will set the VMs clock to your local time (EST/EDT). The *nix VM will need to be set to recognize this, as it's not the default (usually).
Alternately, you can disable Hyper-V's time sync, and have the *nix client sync it's own clock via NTP or similar. This will lead to occasional clock irregularities because the VM's clock isn't an independent piece of hardware, it's software running on the host (and isn't perfect; this isn't a problem unless your application requires a high precision clock).
Edit:
I don't know Linux, got this from someone else: For CentOS edit /etc/sysconfig/clock to include these lines:
UTC=false
ZONE="America/New York"

There may be other lines in the file, not sure what they should be. Enable Hyper-V's Time Sync, and the VM should have the correct time (as long as the host does).
Comment: I don't know how HyperV will deal with it, but inconsistencies between VM and Host time are deadly to Linux (at least on Xen and KVM), mainly when Host time changes too fast and too much (clock skew). The solution was to use the `ntpd` daemon on everything (hosts and VMs) to keep it from happening.
Comment: @Coredump, I've never seen any problem like that using Hyper-V; I know Xen is a different story as you say. I've always used Hyper-V's clock sync without issues, but these were always test/dev environments, not production.
Comment: @Chris S, thanks for your answer, but i am not sure i understand it. or can translate this to action:). as you said, the VM is taking the Hyper-v's current time as UTC time then set it to it's EDT timezone. i think i've disabled the time sync--by disabling the integrationservice's time sync (which isn't installed), i can set NTP up, but i think this is different. the initial time is wrong. i need to somehow break the link between hyper-v and vm on reboot, or when booting up, to get the time from NTP, but i dont know how to do this.
Comment: Hyper-V's time sync doesn't rely on the integration service, you don't need them installed for it to work. There's no way to break the time sync on reboot or initial boot. It's a VM, there's no real computer to keep time; when it's off the "machine" doesn't exist. Setting time via NTP on boot is something both ntpd and ntpdate can do at boot. See your `rc.conf` or equivalent for details. Also you can set your VM to recognize that the 'CMOS Clock' is in local time, see your OS's Time Zone settings for details.
Comment: @Chris S, thanks for your reply, sorry that i am too thick. what i taken from above is 1>the vm takes Hyper-V's time as the initial time (CMOS clock) and appends it's timezone to it 2>after boot, force ntpdate sync to the correct time through a ntpserver 3>after this using the ntpd to maintain correct timing. this process needs to repeat each time the machine is booted. my setup doesn't have a rc.conf.. were you referring to a specific link for OS's Time Zone setting? i am in the process of trying to figure out how to do above step 2 and 3. please comment if i am on the right path. many thanks
Comment: 1. Right, when the VM is started the VM's clock is copied from the host's clock. There is no TZ info, so the VM will not know if the host is keeping time in UTC or a local TZ. 2. Using ntpdate or ntpd you can change the VM's clock to something that makes sense for the VM, yes. 3. ntpd can set the time initially and maintain it. I asked someone about the clock setup, see my edit.
Comment: @Chris S, I appreciate your help. i think my problem is that the linux VM has to be in UTC, but the host hyper-v isn't. yes your answer would work for vm when it has the same tz as the hyper-v host. i have to do above,and i think anyone who wants to keep the linux vm in a different timezone from the hyper-v host. the problem is that ntpd isn't consistent! sometime it would work, sometime it doesn't. if i explicit run ntpdate it can work..
Answer: Please see the following:
NTP time sync not working in a DOMU Centos 5.5 server
Comment: Xen and Hyper-V work very, very differently. These are pretty much different problems.
Comment: thanks Greg for your help. i think the problem you solved is different from mine. i am having trouble to set the correct time at boot time, i think yours is for syncing time when clock is running incorrectly (time skew/drift).

time / timezone of Linux VM on Hyper-V


Group by person with highest result and then by date

Question: I found many related topics here but nothing that really addressed my problem.
SalesTable:
PersonID | SaleAmount | SaleDate | TransactionID
6117 | 10 | 2013-03-13 | 1
6117 | 10 | 2013-03-11 | 2
6400 | 100 | 2013-03-12 | 3
6400 | 10 | 2013-02-05 | 4
6525 | 0 | 2013-03-14 | 5
6400 | 0 | 2013-04-01 | 6

I only want the highest sale amount transaction from each person.
If all transactions from same person has same sale amount then return latest one by date.
Expected result:
PersonID | SaleAmount | SaleDate | TransactionID
6117 | 10 | 2013-03-13 | 1
6400 | 100 | 2013-03-12 | 3
6525 | 0 | 2013-03-14 | 5

I was able to group by person with highest sale no problem but couldnt get the latest transaction if all sale amount was same from one person.
select personid, max(saleamount) from SalesTable group by personid

This would be wrong
select personid, max(saleamount), max(saledate)
from SalesTable
group by personid

because it would give me the wrong date for 6400
6117 | 10 | 2013-03-13 | 1
6400 | 100 | 2013-04-01 | 3
6525 | 0 | 2013-03-14 | 5

Comment: Please specify the RDBMS that you are targeting by adding the appropriate tag (Oracle, SQL Server, MySQL, etc.). There may be answers that take advantage of language or product features that are not universally supported. Also, by tagging it with a specific RDBMS, your question may receive attention from people better suited to answer it
Answer: Try:
with cte as
(select s.*,
        rank() over (partition by PersonID
                     order by SaleAmount desc, SaleDate desc) rn
 from SalesTable s)
select PersonID, SaleAmount, SaleDate, TransactionID
from cte
where rn=1

Comment: great! I think you just missed a "s" behind from SalesTable


what is asm stand for in linux/include/asm

Question: read from howto_add_systemcall

"In general, header files for machine architecture independent system
  calls and functions are kept under linux/include/linux/ and machine
  architecture dependent ones are kept in linux/include/asm/"

so what does asm stand for here?
I've searched wiki, but not found the answer.
Answer: I guess it stands for Architecture Specific Macros (asm) initially.
After that, any architecture specific stuff are placed there.
Answer: "asm" stands for "assembler" or "assembly language".
Comment: @AylwynLake I think it's a historical artifact. Much of the "architecture specific" information is collected in directories called "asm", despite it mostly just being header files. I believe that this came about simply because much architecture specific code was assembler traditionally, and the directory name stuck.
Comment: but the files in asm directory are not write in assembler
Answer: Assembly code for handling system calls for x86 architecture are located at,
<code>arch/x86/kernel/entry_32.S (or _64.S)
</code>


Solving a general equation with sum of exponential

Question: Let $n>1$, and $K > 0$, consider the following equation
$$ \sum_{i=1}^n \alpha_i e^{\beta_i x}= K$$
where $\alpha_i, \beta_i \geq 0$ are known and $x \in \mathbb{R}$ unknown.
Is it possible to find an analytical solution $x$, if any, to the equation above?
Comment: After some googling, I found that most proposed methods are numerical. So, I am wondering if there is some analytical trick to study this equation.
Answer: I do not think there is any general analytic way to tackle such a problem. You can see it, if you put $y=e^x$ and then your equation becomes
$$\sum_{i=1}^na_iy^{b_i}=K$$
which, even in the simplest case that $b_j$'s are natural numbers, where you get a polynomial equation, and if the degree is higher than $5$ there is no general closed-form algebraic solution by Abel's impossibility theorem.
For your original problem, in special cases, though, you may be able to work something out in terms of special functions.
Comment: That was exactly what I was trying to do and found out that it is hard to go forward. I just needed "Abel–Ruffini theorem" as u mentioned to be convinced that it is not possible. Thanks!


MySQL Index on multiple columns

Question: I have a select query where I need to include following columns(almost all the columns from the table):
SELECT  ANI,CALL_ID, DATE_TIME, ABANDON_RATE, CALL_TYPE, CAMPAIGN, CAMPAIGN_TYPE, CUSTOMER_NAME, DISPOSITION, DNIS, LIST_NAME,
        SESSION_ID, SKILL, AGENT_EMAIL, AGENT_GROUP, THIRD_PARTY_TALK_TIME, AFTER_CALL_WORK_TIME, HOLD_TIME, CALL_TIME, HANDLE_TIME, IVR_TIME,
        MANUAL_TIME, TALK_TIME, QUEUE_WAIT_TIME, advertiserName, affiliateName, callerID, campaignName, ChargentSFA__Biling_Phone__c, CONTACT_CREATE_TIMESTAMP,
        CONTACT_ID, CONTACT_MODIFIED_TIMESTAMP, Date_Added, destinationPhoneNumber, leadsource, number1, salesforce_id, source, transactionID,
        IVR_PATH
FROM call_data_report
WHERE ANI= '123456' OR DNIS = '123456'
ORDER BY DATE_TIME desc;

This query takes too much time to execute(more than 3 mins). In order to improve the query performance I have created an index on the columns used in the where clause i.e. ANI and DNIS.
create index ani_idx on call_data_report(ANI,DNIS)

But, when I checked the output of EXPLAIN for above select query it is showing me that it is not using index. Is it becuase of all these columns? What type of index do I need to create to improve the performance of above query.
Note: ANI and DNIS having NULL values in the columns.
Thanks!
Answer: A composite index is only useful when you're combining the tests with AND, not OR. When you have an OR condition, it has to test each column independently, but a composite index is a tree that has all the values of DNIS within their related ANI. So you should create separate indexes for each column.
MySQL also isn't generally good at optimizing OR queries. It would probably be better if you split it into two queries that you combine with UNION:
SELECT ...
FROM call_data_report
WHERE ANI = 123456
UNION
SELECT ...
FROM call_data_report
WHERE DNIS = 123456

Comment: Hi @Barmar, Thank you for the information regarding the query optimization. I have created two separate indexes on ANI and DNIS. But when I execute the EXPLAIN SELECT ... FROM call_data_report WHERE ANI=12345 it is giving me the following output.

id | select_type | table | type | possible_keys | keys | key_len | ref | rows | Extra =>

1 | SIMPLE | call_data_report | ALL | ani_idx | NULL | NULL | NULL | 2995289|Using where

Does this mean it is still not using index?
Comment: That's what it means. I don't know why it's not using the index.
Comment: whether there will be any issue if these two fields are varchar type?
Comment: If it's varchar, try quoting the value: `WHERE ANI = '12345'`
Comment: I think I missed the quote part. Thank you. Explain output is indicating that it is using index now.
Answer: In your case you could try using two single column index ..
create index ani_idx1 on call_data_report(ANI);

create index ani_idx2 on call_data_report(DNIS);

because usinge OR the second key of your composite  index ani_idx DNIS is not used  ..

MySQL Index on multiple columns


C++11: The mutable lambda doesn't seem to change the variable?

Question: I've got a quick test below:
#include<iostream>
using namespace std;
int main(){
    int i=2;
    auto f=[=]()mutable{++i;};
    f();
    f();
    cout<<i<<endl;
    return 0;
}

But the result it still prints "2". Why i is not modified inside a mutable lambda? I'm using clang --std=c++1z.
Thanks!
Answer: You use [=] for your capture which means the lambda gets a copy of i.  This copy is independent from the i in main.
What you need to do is capture by reference [&] in order to apply the changes to the i in main.
Comment: It might help to illustrate the difference if the lambda printed out it's own copy of `i`. You would then see that it's value is different from `int i` from the scope of `main`.
Answer: int i=2;
auto f=[=]()mutable{++i;};
f();
f();
std::cout<<i<<std::endl;

this prints 2.
int i=2;
auto f=[&](){++i;};
f();
f();
std::cout<<i<<std::endl;

this prints 4.
int i=2;
auto f=[=]()mutable{++i; std::cout << i << std::endl;};
f();
f();
std::cout<<i<<std::endl;

this prints 3 4 2.
= copies captured data into the lambda.
If mutable the copies can be modified.
& references captured data in the lambda.
Modifying things through references is legal.
[=] is the same as [i], and [&] is the same as [&i] in this context (you can explicitly list captures, or let them be captured implicitly by listing none and using = or &).
Answer: [=] means you're capturing i by value. Even the mutable lambda could modify it but it's just a copy inside the lambda, then any modification on it would have nothing to do with the original variable.
You might want capture-by-reference, and then mutable is not needed again. e.g.
auto f = [&i]() {++i;};


How is the bayesian framework better in interpretation when we usually use uninformative or subjective priors?

Question: It is often argued that the bayesian framework has a big advantage in interpretation (over frequentist), because it computes the probability of a parameter given the data - $p(\theta|x)$ instead of $p(x|\theta)$ as in the frequentist framework. So far so good.
But, the whole equation it is based on:
$p(\theta|x) = {p(x|\theta) . p(\theta) \over p(x)}$
looks to me little suspicious for 2 reasons:

In many papers, usualy uninformative priors (uniform distributions) are used and then just $p(\theta|x) = p(x|\theta)$, so bayesians get the same result as frequentists get - so how is then bayesian framework better in interpretation, when bayesian posterior and frequentists likelihood are the same distributions? It just yields the same result.
When using informative priors, you get different results, but the bayesian is affected by the subjective prior, so the whole $p(\theta|x)$ has the subjective tinge too.

In other words, the whole argument of $p(\theta|x)$ being better in interpretation than $p(x|\theta)$ builds on a presumption that $p(\theta)$ is kind of "real", which normally is not, it is just a starting point we somehow choose to make the MCMC run, a presumption, but it is not a description of reality (it can't be defined I think).
So how can we argue that bayesian is better in interpretation?
Comment: (1) looks suspect because its conclusion is incorrect: Bayesian results with uninformative priors are *not* necessarily the same as frequentist conclusions. In fact, in [many cases](http://en.wikipedia.org/wiki/Prior_probability#Uninformative_priors) there appears to be no agreement about what an "uninformative prior" even is!  (2) also is debatable because it implicitly assumes that every assumption made in a frequentist analysis is not subjective--but that's not the case. Finally, what exactly do you mean by "better in interpretation"? Your question is ambiguous without a definition of that.
Comment: In addition to whuber's comment I would like to say, there is **no** general reason why Bayes is better than frequentist, hence the argument. Sometimes Bayes gives meaningful results and sometimes frequentist way is better. However, in the applied field, there should be no reason why one should get very different results. From a philosophical perspective, Bayes is definitely strong, but as we all know, theory & practice differ, sometimes drastically. Also, I am a bit concerned about your first paragraph. It appears to me that you are a committed Bayesian (there is nothing wrong with it.).
Comment: Should the title not be `uninformative or *objective* priors` ?  The `subjective` priors are exactly *informative* priors.
Answer: To give a more narrow response than the excellent ones that have already been posted, and focus on the advantage in interpretation - the Bayesian interpretation of a, e.g.,  "95% credible interval" is that the probability that the true parameter value lies within the interval equals 95%.  One of the two common frequentist interpretations of a, e.g., "95% confidence interval", even if numerically the two are identical, is that in the long run, if we were to perform the procedure many many times, the frequency with which the interval would cover the real value would converge to 95%.  The former is intuitive, the latter is not.  Try explaining to a manager some time that you can't say "The probability that our solar panels will degrade by less than 20% over 25 years is 95%", but must instead say "If the true degradation rate was 20% over 25 years, and we could somehow repeat our sampling but with different results blah blah parallel identical universes blah, the long run frequency of times that the one-sided confidence interval I would calculate would lie entirely below 20%/25 years would be 5%", or whatever the equivalent frequentist statement would be.
An alternative frequentist interpretation would be "Before the data was generated, there was a 5% chance the interval I would calculate using the procedure I settled on would fall entirely below the true parameter value.  However, now that we've collected the data, we can't make any such statement, because we're not subjectivists and the probability is either 0 or 1, depending upon whether it does or does not lie entirely below the true parameter value."  That'll help with the auditors and when calculating a warranty reserve.  (I actually find this definition reasonable, albeit not usually useful; it's also not easy to understand intuitively, and especially not if you're not a statistician.)
Neither frequentist interpretation is intuitive.  The Bayesian version is.  Hence the "big advantage in interpretation" held by the Bayesian approach.
Comment: Also, by definition, you'll have to do more explaining in the bayesian case, since you do not only have "what the data tells us" but also what information the prior contains! Bayesians tend to make a long frequentist explanation, but they do not go into explaining what prior they've chosen, why they have chosen a prior and specifically why that prior.
Comment: Well you may not want exactly the previous posterior for your new prior, in our case because of ongoing minor design changes and our knowledge that the mfg. process was evolving too making our prior not 100% informative for future data.  There may also be run-time considerations.  But your point is generally a good one,  it seems to me.
Comment: My problem with the anti frequentist argument is that it tries too much to describe the procedure as an answer. Try the same experiment for yourself in interpretation, but as to what conclusion to draw from the results.

How exactly would you **act** differently based on hearing the results given by a frequentist and a Bayesian? In actuality, you're still going to be acting the same when you understand both. There's no need to go to the level of the procedure to explain that "the best is to act so and so based on the confidence given by the data".
Comment: Well, I'll partially disagree with your last point.  As an example, when i was doing reliability analysis on very, very expensive pieces of equipment in my previous job, we treated the results of our previous reliability analysis as a prior for our new one, downweighted in terms of "equivalent sample size" to take into account the nonstationarity of the real world and smallish changes in design etc.  And, really, Bayesian statistics is all about updating your prior with data; classical statistics doesn't "update", so you only get the same results if your prior is flat, with some exceptions.
Comment: I would just merge the datasets and perform another analysis... no need to come up with a prior. There is no better prior than actual prior data: you get a "real" data-based posterior.
Answer: In my opinion, the reason that Bayesian statistics are "better" for intepretation is nothing to do with the priors, but is due to the definition of a probability.  The Bayesian definition (the relative plausibility of the truth of some proposition) is more closely in accord with our everyday usage of the word than is the frequentist definition (the long run frequency with which something occurrs).  In most practical situations $p(\theta|x)$ is what we actually want to know, not $p(x|\theta)$, and the difficulty arises with frequentist statistics due to a tendency to interpret the results in a frequentist calculation as if it were a Bayesian one, i.e. $p(x|\theta)$ as if it were $p(\theta|x)$ (for example the p-value fallacy, or interpreting a confidence interval as if it were a credible interval).
Note that informative priors are not necessarily subjective, for instance I would not consider it subjective knowledge to assert that prior knowledge of some physical system should be independent of the units of measurement (as they are essentially arbitrary), leading to the idea of transformation groups and "minimally informative" priors.
The flip side of ignoring subjective knowledge is that your system may be sub-optimal because you are ignoring expert knowledge, so subjectivity is not necessarily a bad thing.  For instance in the usual "infer the bias of a coin" problem, often used as a motivating example, you will learn relatively slowly with a uniform prior as the data comes in.  But are all amounts of bias being equally likely a reasonable assumption?  No, it is easy to make a slightly biased coin, or one that is completely biased (two heads or two tals), so if we build that assummption into our analysis, via a subjective prior, we will need less data to identify what the bias actually is.
Frequentist analyses also often contain subjective elements (for instance the decision to reject the null hypothesis if the p-value is less than 0.05, there is no logical compulsion to do so, it is merely a tradition that has proven useful). The advantage of the Bayesian approach is that the subjectivity is made explicit in the calculation, rather than leaving it implicit.
At the end of the day, it is a matter of "horses for courses", you should have both sets of tools in your toolbox, and be prepared to use the best tool for the task at hand.
Having said which, Bayesian $\gg$ frequentist !!! ;oP
Answer: The Bayesian framework has a big advantage over frequentist because it does not depend on having a "crystal ball" in terms of knowing the correct distributional assumptions to make.  Bayesian methods depend on using what information you have, and knowing how to encode that information into a probability distribution.
Using Bayesian methods is basically using probability theory in its full power.  Bayes theorem is nothing but a restatement of the classic product rule of probability theory:
$$p(\theta x|I)=p(\theta|I)p(x|\theta I)=p(x|I)p(\theta|xI)$$
So long as $p(x|I)\neq 0$ (i.e. the prior information didn't say what was observed was impossible) we can divide by it, and arrive at bayes theorm.  I have used $I$ to denote the prior information, which is always present - you can't assign a probability distribution without information.
Now, if you think that Bayes theorem is suspect, then logically, you must also think that the product rule is also suspect.  You can find a deductive argument here, which derives the product and sum rules, similar to Cox's theorem.  A more explicit list of the assumptions required can be found here.
As far as I know, frequentist inference is not based on a set of foundations within a logical framework.  Because it uses the Kolmogorov axioms of probability, there does not seem to be any connection between probability theory and statistical inference.  There are not any axioms for frequentist inference which lead to a procedure that is to be followed.  There are principles and methods (maximum likelihood, confidence intervals, p-values, etc.), and they work well, but they tend to be isolated and specialised to particular problems.  I think frequentist methods are best left vague in their foundations, at least in terms of a strict logical framework.
For point $1$, getting the same result is somewhat irrelevant, from the perspective of interpretation.  Two procedures may lead to the same result, but this need not mean that they are equivalent.  If I was to just guess $\theta$, and happened to guess the maximum likelihood estimate (MLE), this would not mean that my guessing is just as good as MLE.
For point $2$, why should you be worried that people with different information will come to different conclusions?  Someone with a phd in mathematics would, and should, come to different conclusions to someone with high school level mathematics.  They have different amounts of information - why would we expect them to agree?  When you are presented knew information, you tend to change your mind.  How much depends on what kind of information it was.  Bayes theorem contains this feature, as it should.
Using a uniform prior is often a convenient approximation to make when the likelihood is sharp compared to the prior.  It is not worth the effort sometimes, to go through and properly set up a prior.  Similarly, don't make the mistake of confusing Bayesian statistics with MCMC.  MCMC is just an algorithm for integration, same as guassian quadratre, and in a similar class to the Laplace approximation.  It is a bit more useful than quadratre because you can re-use the algorithm's output to do all your integrals (posterior means and variances are integrals), and a bit more general that Laplace because you don't need a big sample, or a well rounded peak in the posterior (Laplace is quicker though).
Answer: I have typically seen the uniform prior used in either "instructive" type examples, or in cases in which truly nothing is known about a particular hyperparameter. Typically, I see uninformed priors that provide little information about what the solution will be, but which encode mathematically what a good solution probably looks like. For example, one typically sees a Gaussian prior ($\mu=0$) placed over a regression coefficient, encoding the knowledge that all things being equal, we prefer solutions in which the coefficients have lower magnitudes. This is to avoid overfitting a data set, by finding solutions that do maximize the objective function but which don't make sense in the particular context of our problem. In a sense, they provide a way to give the statistical model some "clues" about a particular domain.
However, this isn't (in my opinion) the most important aspect of Bayesian methodologies. Bayesian methods are generative, in that they provide a complete "story" for how the data came into existence. Thus, they aren't simply pattern finders, but rather they are able to take into account the full reality of the situation at hand. For example, consider LDA (latent Dirichlet allocation), which provides a full generative story for how a text document comes to be, that goes something like this:

Select some mix of topics based on the likelihood of particular topics co-occurring; and
Select some set of words from the vocabulary, conditioned based on the selected topics.

Thus, the model is fit based on a very specific understanding of the objects in the domain (here, text documents) and how they got created; therefore, the information we get back is tailored directly to our problem domain (likelihoods of words given topics, likelihoods of topics being mentioned together, likelihoods of documents containing topics and to what extent, etc.). The fact that Bayes Theorem is required to do this is almost secondary, hence the little joke, "Bayes wouldn't be a Bayesian, and Christ wouldn't be a Christian."
In short, Bayesian models are all about rigorously modeling the domain objects using probability distributions; therefore, we are able to encode knowledge that wouldn't otherwise be available with a simple discriminative technique.


On two different definitions of complex integral

Question: I'm studying complex analysis on professor Tao's notes. I need to prove that the complex integral defined as such:

*Let $\gamma : [a,b] \to \mathbb{C}$ and $f: \gamma([a,b]) \to \mathbb{C}$ be complex functions. We define $\int_\gamma f$, if it exist, as the number such that
  for every $\epsilon \gt 0$ there exist $\delta$ such that, if $a = x_0 \lt x_1 \lt \cdots \lt x_n = b$ determines a partition of $[a,b]$ , $\max_{1 \le i \le n}| x_i - x_{i-1}| < \delta$ and $x_{i-1} \le \xi_i \le x_i$, then $\displaystyle \left|\sum_{i=1}^n f(\gamma(\xi_i))(\gamma(x_i) - \gamma(x_{i-1})) - \int_\gamma\right| \lt \epsilon$ *

is the same as the standard one, when $f$ is continous and $\gamma$ rectifiable and continously differentiable, in the sense that: $$ \int_\gamma f = \int_a^b\Re[f(\gamma(t))\gamma'(t)]\,dt + i \int_a^b\Im[f(\gamma(t))\gamma'(t)]\,dt$$
(it can be proven that $\int_\gamma f$ exists whenever $f$ is continous and $\gamma$ is rectifiable)

I tought I might show that the complex riemann sums of the left side are arbitrarily close to real ones of the left side, then use the triangular inequality to show the equality above.
If $a = x_0 \lt x_1 \lt \cdots \lt x_n = b$ determines a partition of $[a,b]$, with $1 \le \xi_{i-1} \le x_i$ for $1 \le i \le n$ and $\max_{1 \le i \le n}| x_i - x_{i-1}| < \delta$ for an appropriate $\delta$, we have
$$
\left| \sum_{i=1}^n f(\gamma(\xi_i))(\gamma(x_i) - \gamma(x_{i-1})) - \sum_{i=1}^n \Re[f(\gamma(\xi_i))\gamma(\xi_i)](x_i - x_{i-1}) -
i\sum_{i=1}^n \Im[f(\gamma(\xi_i))\gamma(\xi_i)](x_i - x_{i-1}) \right| =
$$
$$
\left| \sum_{i=1}^n f(\gamma(\xi_i))(\gamma(x_i) - \gamma(x_{i-1})) -
\sum_{i=1}^n \Re[f(\gamma(\xi_i))\gamma(\xi_i)](x_i - x_{i-1}) - i\Im[f(\gamma(\xi_i))\gamma(\xi_i)](x_i - x_{i-1})
\right| =
$$
$$
\left|\sum_{i=1}^n f(\gamma(\xi_i))(\gamma(x_i) - \gamma(x_{i-1})) -
\sum_{i=1}^n f(\gamma(\xi_i))\gamma(\xi_i)](x_i - x_{i-1})\right| =
$$
$$
\left|\sum_{i=1}^n f(\gamma(\xi_i))[(\gamma(x_i) - \gamma(x_{i-1})) -
\gamma(\xi_i)(x_i - x_{i-1})]\right|
$$
But then i don't know what to do, since there does not exist a mean value theorem for complex numbers. How can i proceed? Or should I drop that and try a different method?
Comment: Sorry for the bad formatting. Feel free to edit.
Answer: There is no mean value theorem, but since $\gamma'$ is continuous you have
$$
\gamma'(\xi)-\gamma'(x_i)=\text{Error}
$$
with $Error\to 0$ as the partition is refined. This error does not contribute in the limit you have because $Error\times (x_i-x_{i-1})$ goes to zero faster than the diameter of the partition. Then, you can safely replace $\gamma'(\xi)$ by $\gamma'(x_{i-1})$ in your last formula and, by the Peano form of the remainder in Taylor's expansion, the expression in brackets also goes to zero faster than the diameter of the partition, thus giving zero in the limit for the sum.
I can give more details if you need them.


How to change the value of a user field through Restfull?

Question: I can't change the value of field_motherid field through restfall. GET running, PUT disabled, PATCH enabled and configured. When I do GET there is no user field.
Answer: Assuming the user rest resource is enabled and PATCH requests are configured, also that the requesting user is authenticated to update the user, then:
send a PATCH request to: https://example.com/user/$uid?_format=json
Where $uid is the user id to update (e.g 12)
The request body should look something like this (json format):
{ "field_motherid":
  [
    {"value": "new_value"}
  ]
}


Questions about current economic policy

Question: Is this question on topic? Edit: The question has since been deleted, so I will rephrase.
Is a question about what a country's current economic policy is in a certain area on topic?

Such a question is not about the theory behind or the likely effects of a certain policy. It is maybe a reference request. Is that still economics? An example:

Q: What is the current VAT in country X?  A: It is 12%.

I don't think this
    had any economic content.
Answer: I want to say off-topic because the VAT question especially is so utterly dull. But I also hesitate to suggest we introduce a blanket ban on these kinds of 'matter of fact' questions because

it's hard to see where an objective line is to be drawn.
there's an argument to be made that economists are the best people to ask about some of these things (not VAT, perhaps, but slightly richer questions like the one you linked to).

Perhaps one way forward would be to say that such questions are on-topic, and let the market decide through people's decisions on whether to answer and how to vote.
But I'm curious to hear the opinion of others.
Answer: I would consider the now-deleted question as squarely on topic here (specialized literature request), while the VAT-question example certainly off-topic.
The VAT question is  a "bored to google - let's put economics.se to do it for me", since it just asks for a datum (or two, it doesn't matter).
The first, about EU policy, although ostensibly "purely factual" also, it refers to a complex matter for which most probably no "informative brochure/executive summary" exists, but only studies and research papers by experts who have gathered together and studied relevant EU official documents, synthesized them, analyzed them, and usually expressed opinions on them... which is applied macroeconomics and/or political economy. Such studies are usually not in the most public places even on the Internet, while it is possible that a member of the economics.se community could usefully guide the OP about where to find them, adding in the process useful content/resources here.
I believe @Ubiquitous is right: on this one, the line is not easy to be drawn a priori, and become "off-topic alert/on-topic guidance". Perhaps the per case close/downvote mechanism is the best approach.

Questions about current economic policy


Using different MailServer for special Users in the same domain

Question: I'm new to this topic, so please have forbearance, if this is a dumb question.
At the Moment, we use GMail for all Mailaddresses. To save some money, the idea is, to use an own mailserver for the majority of the addresses, because they are only used for "inside-communication". So 100% Uptime is not important.
But we've got some Mailaddresses, that are more sensitiv. Like our Sales-Team or the Managers. Therefor i want to keep these accounts at Google.
So internal Mailserver for email@example.com and email@example.com. But the GoogleMailServer for email@example.com.
Is this possible, without using a new Subdomain? I want to keep the existing addresses.
Answer: It is not possible without subdomain - all mailboxes @example.com have to be on same server. You can define new MX records set in DNS for subdomain (ie. company.example.com) and point it to your mailserver. Mailboxes will then change to email@example.com instead of firstname.lastname@example.com. It will looks like this:
@ IN MX 10 first.gmail-server.com
@ IN MX 20 second.gmail-server.com
company IN MX 10 your.mailserver.com

Comment: `all mailboxes @example.com have to be on same server` . This is just flat-out wrong. Having a mail gateway that forwards incoming mails to different servers is quite easy. It's not necessary useful in this setup, but clearly possible.
Comment: Thank you! i was guessing, i need a subdomain. i also read, that it is possible to have more than one mailserver for a domain. Working as kind of fallback / load-balancing. But i hopped to choose the mailserver, depending on the receiver of the mail, like firstname.lastname@example.com -> MailServer_GMail and firstname.lastname@example.com -> MailServer_Inhouse.
Comment: ok, mail gateway is way how to do it. But it has many not-so-good-sideeffects:

    1) You have to choose provider who has HA setup of gateways or manage HA setup of it by yourself
    2) Mail gateway is another point of failure, which is not necessary
    3) i think when @ChrisJay have ability to run mail gateway with low risk, he can also run whole mailserver by himself and doesn't need to use gmail.

So my answer is maybe not perfect in all way, but it absolutelly OK in scope of question.


Como parar uma Thread por determinado tempo, sem usar um Timer?

Question: Explicação:
Seguinte, eu tenho uma TThread executando paralela à Main Thread. E tenho uma rotina pra dar um fade na imagem. Bom, o importante é que eu realizo esse fade em um determinado tempo em milissegundos, então eu fiz a rotina baseada em um TTimer.
Problema:
Quando eu executo o comando do fade, por causa do timer a minha thread segue a execução independente do fade ter ou não encerrado. Porém, o que me impede de dar dois ou mais fades sequenciais.
Então o que eu preciso é de uma maneira de deixar a thread aguardando meu comando terminar.
Eu pensei em usar um loop simples para executar o fade, mas como eu poderia medir o tempo sem o timer? Alguém tem alguma ideia?
Comment: @PauloRoberto por que puseste as palavras como código?
Comment: @PauloRoberto ao meu ver, as palavras fade deveriam ser trocadas por efeito de aparecer/desaparecer/esmaecimento. Não estão relacionadas ao código de forma alguma.
Comment: Porque relacionam à ações que envolvem código, são termos em inglês utilizados para determinado feito, pedem destaque. Objetivo é facilitar o entendimento.
Comment: Termos em inglês devem ser redigidos em itálico. Não em código.
Comment: Porque deveriam? Itálico não implicaria praticamente nenhuma diferença do resto do texto. - Porém comentários como estes redigidos por mim e por você não estão ajudando no entendimento da pergunta, devem ser posteriormente excluídos.
Comment: Qual o problema de você criar a thread ou iniciar sua execução **só** depois do efeito acabar?
Comment: Acho que me expliquei mal. O efeito é chamado no meio da thread.
Answer: Você pode utilizar o GetTickCount que te retorna um número cardinal contendo o tempo em milissegundos desde que o sistema está ligado. Depois, quando chamar de novo, é só checar a diferença.
Dois pontos importantes:
1 - Quando o sistema fica ligado por 49,7 dias, o cardinal reinicia.
2 - Quando o computador hiberna, o valor também fica armazenado.
Então é só você implementar uma função:
function VerificarTimeOut(const TickCountInicial, TempoEsperado: Cardinal): Boolean
var
  TickCountAtual: Cardinal;
begin
  TickCountAtual := GetTickCount;
  if TickCountInicial <= TickCountAtual then
    Result := (TickCountAtual - TickCountInicial) >= TempoEsperado
  else
    Result := ((MAXCARDINAL - TickCountInicial) + TickCountAtual) >= TempoEsperado;
end;

Depois na thread você faz:
procedure EsperaAte(const TempoEspera: Cardinal);
var
  TickCountParada: Cardinal;
begin
  TickCountParada := GetTickCount;
  while not VerificarTimeOut(TickCountParada, TempoEspera) do
    Sleep(10);
end;

Obs: Não coloque um sleep muito grande pois, se a thread receber um sinal de parada ou término ela não vai responder se estiver em sleep


Dark+ Theme in VSCode changes after I install Dart extension

Question: I am trying to use Dark+ (default theme) theme in VSCode. Every time I try to use the theme, theme colors change to something different for variables, and the  @override. Both become light-blue in color (as in the picture.)
I have searched and tried everything, including removing and re-installing VSCode itself (and lost my other settings.json on the way!) My question is how to use the Dark+ theme along with the Dart extension?
I use the latest versions of both Flutter and Dart on a Linux (LinuxMint) machine.
Answer: After extensive search, I could find the solution that may help others who may face such a problem.
add
"editor.semanticHighlighting.enabled": false,
to your settings.json file.


How to create a Hook_Schema for Fieldset Form?

Question: i have a form i would like to have the values submitted into a table in mysql database using hook_schema in a .install file. problem is i have no idea how to properly write it out being new to php  and all. i basically have a custom form with over 50 total field divided up into 3 different fieldsets displayed to user depending on checkbosed clicked. what is the best way to write a hook_schema to upload the submission values from my form into my database?
Answer: is your schema already defined for a table in MySQL somewhere, did you already make it in like phpmyadmin? ... if so, the Schema module will show you the exact PHP needed for hook_schema
I recommend:

make a table in your drupal database using something like Navicat, phpmyadmin, mysql admin ... whatever. The table columns are your form field inputs and at least additionally a primary key.
install Schema module and goto admin/structure/schema/inspect. Copy + Paste + Profit
// in yourmodule.install
function yourmodule_schema() {
  // ... paste the $schema['your_table'] textarea stuff Schema page auto-generated for you.
  return $schema;
}

Comment: why is my code ugly :P grrrr
Comment: It was inside a list so it needs 8 spaces not 4 ;)
Comment: No its not already defined i have to define it im going to create the table and download schema to see if i can get it to work thanks :)
Comment: @Clive I thought i put a newline or two to get out of the list .... hmmm ... thanks
Comment: Come to think of it you did, I'm not sure why it didn't break out of the list...