text:
Q: Explaining Mean, Median, Mode in Layman's Terms How would you explain the concept of mean, median, and mode of a list of numbers and why they are important to somebody with only basic arithmetic skills? Let's not mention skewness, CLT, central tendency, their
statistical properties, etc.
I have explained to somebody that mean is just a quick and dirty way to "summarize" a list of numbers. But looking back, this is hardly illuminating.
Any thoughts or real world examples?

A: Thank you for this simple-yet-profound question about the fundamental statistical concepts of mean, median, and mode. There are some wonderful methods /demonstrations available for explaining and grasping an intuitive -- rather than arithmetic -- understanding of these concepts, but unfortunately they are not widely known (or taught in school, to my knowledge).
Mean:
1. Balance Point: Mean as the fulcrum
The best way to understand the concept of mean it to think of it as the balance point on a uniform rod. Imagine a series of data points, such as {1,1,1,3,3,6,7,10}. If each of these points are marked on a uniform rod and equal weights are placed at each point (as shown below) then the fulcrum must be placed at the mean of the data for the rod to balance.

This visual demonstration also leads to an arithmetic interpretation. The arithmetic rationale for this is that in order for the fulcrum to balance, the total negative deviation from the mean (on the left side of the fulcrum) must equal to the total positive deviation from the mean (on the right side). Hence, the mean acts as the balancing point in a distribution.
This visual allows an immediate understanding of the mean as it relates to the distribution of the data points. Other property of the mean that becomes readily apparent from this demonstration is the fact that the mean will always be between the min and the max values in the distribution. Also, the effect of outliers can be easily understood – that a presence of outliers would shift the balancing point, and hence, impact the mean.
2. Redistribution (fair share) value
Another interesting way to understand the mean is to think of it as a redistribution value. This interpretation does require some understanding of the arithmetic behind the calculation of the mean, but it utilizes an anthropomorphic quality – namely, the socialist concept of redistribution – to intuitively grasp the concept of the mean.
The calculation of the mean involves summing up all values in a distribution (set of values) and dividing the sum by the number of data points in the distribution.
$$
\bar{x} = (\sum_{i=1}^n{x_i})/n
$$
One way to understand the rationale behind this calculation is to think of each data point as apples (or some other fungible item). Using the same example as before, we have eight people in our sample: {1,1,1,3,3,6,7,10}. The first person has one apple, the second person has one apple, and so on. Now, if one wants to redistribute the number of apples such that it is "fair" to everyone, you can use the mean of the distribution to do this. In other words, you can give four apples (i.e., the mean value) to everyone for the distribution to be fair/equal. This demonstration provides an intuitive explanation for the formula above: dividing the sum of a distribution by the number of data points is equivalent to partitioning the whole of the distribution equally to all of the data points.
3. Visual Mnemonics
These following visual mnemonics provide the interpretation of the mean in a unique way:

This is a mnemonic for the leveling value interpretation of the mean. The height of the A's crossbar is the mean of the heights of the four letters.

And this is another mnemonic for the balance point interpretation of the mean. The position of the fulcrum is roughly the mean of the positions of the M, E, and doubled N.
Median
Once the interpretation of mean as the balancing point on a rod is understood, the median can be demonstrated by an extension of the same idea: the balancing point on a necklace.
Replace the rod with a string, but keep the data markings and weights. Then at the ends, attach a second string, longer than the first, to form a loop [like a necklace], and drape the loop over a well-lubricated pulley.

Suppose, initially, that the weights are distinct. The pulley and loop balance when the same number of weights are to each side. In other words, the loop 'balances' when the median is the lowest point.
Notice that if one of the weights is slid way up the loop creating an outlier, the loop doesn't move. This demonstrates, physically, the principle that the median is unaffected by outliers.
Mode
The mode is probably the easiest concept to understand as it involves the most basic mathematical operation: counting. The fact that it's equal to the most frequently occurring data point leads to an acronym: "Most-often Occurring Data Element".
The mode can also be thought of the most typical value in a set. (Although, a deeper understanding of 'typical' would lead to the representative, or average value. However, it's appropriate to equate 'typical' with the mode based on the very literal meaning of the word 'typical'.)

Sources:

*

*The Median is a balance point -- Lynch, The College Mathematics Journal (2009)

*Making Statistics Memorable: New Mnemonics and Motivations -- Lesser, Statistical Education, JSM (2011)

*On the Use of Mnemonics for Teaching Statistics -- Lesser, Model Assisted
Statistics and Applications, 6(2), 151-160 (2011)

*What does the mean mean? – Watier, Lamontagne and Chartier, Journal of Statistics Education, Volume 19, Number 2 (2011)

*Typical? Children's and Teachers' Ideas About Average – Russell and Mokros, ICOTS 3 (1990)
OVERALL REFERENCE:  http://jse.amstat.org/v22n3/lesser.pdf

A: I have to wonder whether your criteria are achievable as you seem to want maximal effectiveness and explanatory power with minimal materials. But a simple example such as
1
   1
   2
   2
   2
   3
   3
   4
   5
   6
   15
allows immediate calculation of the mode (2), the median (3) and the mean (44/11) = 4 and thus shows that they can be different.
You could then explain that the ideas of the most common value, the value in the middle and the mean are different. And introduce complications by

*

*changing values to show the mode can be ambiguous

*using an example with an even number of values to explain the convention for calculating the median

*varying values in the tails to emphasise what happens to the mean, and why and why not that may be desirable.

*using simpler examples in which two or three of mean, median, mode coincide.
I have not mentioned central tendency in my teaching except to say that it's a term in various literatures. I prefer to talk about level and how it may be quantified. Conversely, I don't think any serious data analysis is possible unless people have a minimal feeling for skewness as more usual than symmetry.

A: This is how I explain them:
The (arithmetic) mean is the point that takes the entire data set into account, and settles somewhere "in the middle." Have them think of a point cloud, or a blob, in space: the mean is the center of mass of that point cloud.
The median is the point that has "the same number of points on all sides" (where obviously the concept of a "side" isn't well-defined in 2+ dimensions). This represents another kind of "middle," and in fact a more intuitive kind in some sense. Thinking of that same blob in space, it is clear that if the blob is lopsided then the mean will be shifted. But this lopsidedness can be achieved in one of two ways: either you add more points in one area, or you increase the dispersion of points in that area. If you increase the dispersion of points in one area without increasing the number of points, then the median still has the same number of points "on all sides" and will not shift commensurate with the mean.
You can demonstrate this with two very trivial "blobs": $y = (1, 2, 3, 4, 5)$ and $y' = (1, 2, 3, 4, 99)$. $\operatorname{mean}(y) = \operatorname{median}(y)$, whereas $\operatorname{mean}(y') > \operatorname{median}(y')$. But I recommend starting with the geometric/visual "blob-based" explanation first: in my experience it's easier to start with a hand-waving graphical demonstration, then move to concrete toy examples. I find that most people (myself included) aren't naturally number-oriented, and starting with a numerical explanation is a recipe for confusion. You can always go back and teach more precise definitions later.
The mode is the point that, if points are randomly sampled from that blob, is most likely to appear (recognizing that this is a fudge for continuous data). This can be, but doesn't have to be, located near the mean or median.
Once you've explained these concepts, then you can move onto a more "statistical-looking" demo:

The solid line is the mean. The dashed line is the median. The dotted line is the mode. The mean represents the positions of the data points along the x axis, while the median reflects only the number of data points on either side. The mode is just the point of greatest probability, which is different from both the mean and the median.
R code:
set.seed(47730)
y <- rgamma(100, 2, 2)
d <- density(y)
plot(d)
rug(y)
abline(v = mean(y), lty = 1)
abline(v = median(y), lty = 2)
abline(v = d$x[which.max(d$y)], lty = 3)

A: The "mean", "median" and "mode" are "central tendency", aka "most likely outcome" in different domains.  They are all "best bets" in different "games".
Probability and Statistics is a field that was, in part, built by gamblers (link, link) .  When you go to the horse races, or the poker table, you want to know some science that helps you win.  They did too, and wrote about it, so you don't have to invent it yourself.
In a horse race, you want to pick a winner.  You don't have future information, but you do know some past information.  You know how fast each horse ran in the past few races.  If you want to make an estimate of how fast they are likely to run in their next race, you can compute and compare the mean, aka the average, race-times.
Another central tendency is the "median" - which is the center of a sorted list.  What if I put a horrible typo on your list of race times, and the value was 1000x longer than all the others.  It would mess up your estimate. You might not bet on the winning horse.  How do you address that?  You could manually look for that one value, or you might use the "median".
What if you are playing cards, like "blackjack", and you are trying to figure out if you need another card given the previous cards.  The card you are looking for is not a 3.14 because cards numbers are integer values.  How do you figure out what your best bet is when "average" or median is not meaningful?  In this case, you want to bet on the "mode" - the most likely card to come out of the dealers stack.
In all three cases, the central tendency is just another way of saying "best bet".
If you want to account not only for central tendency in your betting, that is to say if you want to bet so that you are able to reduce the impacts of a loss while maximizing winnings, then you must look at "tendencies of variation".  Things like standard deviation, inter-quantile-ranges, or alternative modes and their frequencies, are all used to minimize the maximum losses while maximizing the likely winnings.

A: I think it's useful to explain this concept when considering multiple means, medians, and modes. These values don't exist by themselves in a vacuum.
For example, here's how I would explain mean.
Let's say you have 2 crates of watermelons (crate 1 and 2). It's sealed off so you can't see the watermelons inside and thus you don't know their sizes. However,
you do know the total weights of the watermelons in each crate and each contains the same number of watermelons. From that, you can compute the mean
weights of each crate of watermelons (M1 and M2).
Now that you have two different mean values M1 and M2, you can do a rough comparison of the individual contents.  If M1 > M2, then a randomly selected watermelons from crate 1 may probably be heavier than one picked from
crate 2.
Of course, I would love comments on this perspective.


text:
Q: Why is this C function crashing at fclose? Please help me understand why this function throws an exception when it reaches fclose :

void receive_file(int socket, char *save_to, int file_size) {
    FILE *handle = fopen(save_to,"wb");
    if(handle != NULL) {
        int SIZE = 1024;
        char buffer[SIZE];
        memset(buffer,0,SIZE);
        int read_so_far = 0;
        int read_now = 0;
        int reading_unit = (file_size < SIZE) ? file_size : SIZE;
        do {
            read_now = read(socket,buffer,reading_unit);
            fwrite(buffer,read_now,1,handle);
            read_so_far += read_now;
            if(read_so_far >= file_size) {
                break;
            }
            memset(buffer, 0, sizeof(buffer));
        } while (1);
        read_now = 0;
        fclose(handle);
    }
    else {
        extern int errno;
        printf("error creating file");
        printf(" error code : %d",errno);
        exit(-1);
    }
}

Eclipse CDT exists with the following error :
Single stepping until exit from function __kernel_vsyscall,
which has no line number information.
The purpose of this function is to receive a file through a socket.
EDIT: I'm using CentOS 5.3. The thing is, the file is created and written. Even the MD5 is correct. I don't understand why it's failing at fclose.
EDIT2: here is a stack trace I managed to get :

*** glibc detected *** /home/linuser/workspace/proj/Debug/proj: free(): invalid next size (normal): 0x096a0068 ***
======= Backtrace: =========
/lib/libc.so.6[0x4fb0f1]
/lib/libc.so.6(cfree+0x90)[0x4febc0]
/lib/libc.so.6(fclose+0x136)[0x4e9c56]
/home/linuser/workspace/proj/Debug/proj[0x8048cd8]
/home/linuser/workspace/proj/Debug/proj[0x80492d6]
/home/linuser/workspace/proj/Debug/proj[0x804963d]
/lib/libc.so.6(__libc_start_main+0xdc)[0x4a7e8c]
/home/linuser/workspace/proj/Debug/proj[0x8048901]
======= Memory map: ========
001ff000-00200000 r-xp 001ff000 00:00 0          [vdso]
0046f000-00489000 r-xp 00000000 08:06 1280361    /lib/ld-2.5.so
00489000-0048a000 r-xp 00019000 08:06 1280361    /lib/ld-2.5.so
0048a000-0048b000 rwxp 0001a000 08:06 1280361    /lib/ld-2.5.so
00492000-005d0000 r-xp 00000000 08:06 1280362    /lib/libc-2.5.so
005d0000-005d2000 r-xp 0013e000 08:06 1280362    /lib/libc-2.5.so
005d2000-005d3000 rwxp 00140000 08:06 1280362    /lib/libc-2.5.so
005d3000-005d6000 rwxp 005d3000 00:00 0
005d8000-005fd000 r-xp 00000000 08:06 1280369    /lib/libm-2.5.so
005fd000-005fe000 r-xp 00024000 08:06 1280369    /lib/libm-2.5.so
005fe000-005ff000 rwxp 00025000 08:06 1280369    /lib/libm-2.5.so
009b2000-009bd000 r-xp 00000000 08:06 1280372    /lib/libgcc_s-4.1.2-20080825.so.1
009bd000-009be000 rwxp 0000a000 08:06 1280372    /lib/libgcc_s-4.1.2-20080825.so.1
009c5000-00aa5000 r-xp 00000000 08:06 5465873    /usr/lib/libstdc++.so.6.0.8
00aa5000-00aa9000 r-xp 000df000 08:06 5465873    /usr/lib/libstdc++.so.6.0.8
00aa9000-00aaa000 rwxp 000e3000 08:06 5465873    /usr/lib/libstdc++.so.6.0.8
00aaa000-00ab0000 rwxp 00aaa000 00:00 0
08048000-0804a000 r-xp 00000000 08:06 4884214    /home/linuser/workspace/proj/Debug/proj
0804a000-0804b000 rw-p 00001000 08:06 4884214    /home/linuser/workspace/proj/Debug/proj
096a0000-096c1000 rw-p 096a0000 00:00 0          [heap]
b7e00000-b7e21000 rw-p b7e00000 00:00 0
b7e21000-b7f00000 ---p b7e21000 00:00 0
b7f99000-b7f9a000 rw-p b7f99000 00:00 0
b7faa000-b7fac000 rw-p b7faa000 00:00 0
bfa82000-bfa97000 rw-p bffea000 00:00 0          [stack]

and here is the "updated" version of the function :

void rec_file(int socket,char *path,int size)
{
    FILE *handle = fopen(path,"wb");
    char buffer[4096];
    int total_read = 0;
    if(handle != NULL)
    {
        while(1)
        {
            int bytes_read = recv(socket,buffer,4096,0);
            total_read    += bytes_read;
            if(bytes_read != -1)
            {
                fwrite(buffer,bytes_read,1,handle);
            }
            else
            {
                printf("read error ");
                exit(-1);
            }
            if(total_read >= size)
            {
                break;
            }
        }
        fclose(handle);
    }
    else
    {
        printf("error receiving file");
        exit(-1);
    }
}

maybe this is cleaner? However, I still receive the same fclose exception.
EDIT3:
I commented out everything and I only left the following code, which sadly, still throws the exception at fclose :

void nrec(int sock,char* path,int size)
{
    FILE *handle = fopen(path,"wb");
    if(handle == NULL)
    {
        printf ("error opening file");
        return;
    }
    fclose(handle);
}

A: *

*fclose() returns a value: 0 if the file is closed successfully, EOF if not.  Consider modifying your code to ...
if (fclose(handle)) { printf("error closing file."); exit(-1); }

*As everyone else points out, check read() for error.

*If the crash is happening after the fclose returns 0 (success), and all the read()s were successful, then perhaps the trouble is elsewhere.  Maybe it's the VLA.  Consider changing the buffer code to a file static or a malloc / free.

*If the caller was mistaken about the file size, say, and claimed the file was 500 bytes when in fact it is only 480, will your code keep reading the socket forever?

A: This code seems very ... uncertain about itself. Lot of needless assignments, memset() calls, complicated logic.
There's no point in limiting the amount you try to read. Always read as much as you have buffer space for; if there's less data available, you will get less.
It also doesn't properly handle errors. If read() fails, it can return -1, in which case Bad Things(TM) will happen all over the place.
My advice would be to clean it up, think about return values from I/O functions and check them better, then try again.
Failing that, if you're in Linux, run it through Valgrind to get help tracking down the crash.

A: Not sure specifically, but you do know that read() can return a negative on error, right?

A: You didn't check whether you got an error indication from the read() call.  If you get a  -1 from read(), you then pass it, unchecked, to fwrite(), which takes a size_t as its argument.  When your int value is converted to size_t (or treated as size_t), it becomes a rather large number (4 GB - 1 on a 32-bit system).  So, fwrite() does as you command - tries to write a lot of data from places it is not supposed to.

A: You need to test the return value of read() - it may return an error code, such as -1, as well as the number of bytes read.
Edit: In your new code you should test that the return value from recv() is >= 0, not that it is not -1. You should alse break if it returns zero.

A: The code in edit3 looks reasonable. I suspect you've probably stomped over some memory somewhere else and are reaping the problem at this point in your application.
Do you have bounds checkers, purify etc that you could run to check for buffer overruns, using a free'd memory block etc.

A: Are you sure you haven't corrupted the heap elsewhere, before getting to this function? Try running your program under valgrind.

A: If your "EDIT3" version of the code is still crashing, then the problem lies elsewhere in your code.  If you have made a mistake in another part of your program (for example, freeing something twice, dereferencing a pointer that wasn't pointing where you thought it was), then the resulting corruption can go unseen until later (such as when you reach fclose()).

A: Could it be because you are writing more bytes into the file than file_size ? Using the current logic if you have file_size as 1025 then you will end up in writing 2048 bytes to the file. I believe, you should recalculate the reading_unit inside the while loop.

A: I am unsure how the compiler will interpret these two lines
int SIZE = 1024;
char buffer[SIZE];

You are using a variable to size buffer rather than a constant. I am unsure whether this will behave as you expect. Could you try the following instead.
#define SIZE (1024)
char buffer[SIZE];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple hover effect I am a novice.. I want to hover on the bottle and have the bottle rotate.  At the same time I want to show the pouring and puddling animation.  I don't know how I can get multiple animation to start with a single hover.  Here is the CSS for it:
/*CSS ANIMATION*/

@-webkit-keyframes bottle {
0% {
    height: 67px;
}
7% {
    height: 67px;
}
95% {
    height: 0px;
}
100% {
    height: 0;
}
}

@-moz-keyframes bottle {
0% {
    height: 67px;
}
7% {
    height: 67px;
}
95% {
    height: 0px;
}
100% {
    height: 0;
}
 }

#bottle {
position: absolute;
top: 1055px;
right: 490px;
-webkit-transition: all .2s linear;
}

#bottle:hover {
-moz-transform: rotate(165deg);
-webkit-transform: rotate(165deg);
transform: rotate(165deg);
-webkit-transition: all .2s linear;
}

@-webkit-keyframes pour {
0% {
    background-position: 0 0;
    height: 0;
}
5% {
    background-position: 0 0;
    height: 0;
}
10% {
    background-position: 0 0;
    height: 75px;
    width: 4px;
}
95% {
    background-position: 0 0;
    height: 120px;
    width: 4px;
}
100% {
    background-position: 0 0;
    height: 170px;
    width: 4px;
}
}

@-webkit-keyframes puddle {
10% {
    height: 30px;
}
15% {
    height: 30px;
}
98% {
    height: 50px;
}
100% {
    height: 0;
}
}

#pour {
position: relative;
right: -55px;
top: -25px;

}

#puddle {
position: relative;
top: -50px;
opacity: 1;
right: -20px;
}

#contents1:hover {
-moz-animation: bottle 5s linear 1 forwards;
-webkit-animation: bottle 5s linear 1 forwards;
animation: bottle 5s linear 1 forwards;
}

#contents2:hover {
display: block;
-moz-animation: pour 2s linear 1;
-webkit-animation: pour 2s linear 1;
animation: pour 2s linear 1;
}

#contents3:hover {
-moz-animation: puddle 10s linear 1;
-webkit-animation: puddle 10s linear 1;
animation: puddle 10s linear 1;
}

Now I need to know how to connect contents2:hover and contents3:hover with the bottle:hover.  I mean just by hovering over the bottle, how can I set contents2 and contents3 in motion?
As you guys have requested i ve uploaded everything to JSFiddle.. This is the link http://jsfiddle.net/shettyrahul8june/8tkKK/2/
And for fullscreen jsfiddle.net/shettyrahul8june/8tkKK/2/embedded/result/
For some reasons the bottle.png is not being displayed in the editors link but works fine in fullscreen.. This is the link for the image s26.postimg.org/s07bc6gvp/bottle.png .... All i want is to the bottle to rotate and pour the liquid and then comes the puddle.. All should happen with single bottle hover.. I'm not simply relying on people.. I've worked hard but couldn't get it right.. Also if someone could put light on how to maintain the resolution of the webpage, it'd be a great help.. Hope i am precise.. Please do help because many are searching for this and this could be their ultimate stop..

A: You are looking for Tilde ~ selector in CSS
Working Demo and Source
CSS
#bottle:hover ~ #pour {
    display: block;
    -moz-animation: pour 2s linear 1;
    -webkit-animation: pour 2s linear 1;
    animation: pour 2s linear 1;
}
#bottle:hover ~ #puddle {
    -moz-animation: puddle 10s linear 1;
    -webkit-animation: puddle 10s linear 1;
    animation: puddle 10s linear 1;
}


text:
Q: Comparing HttpContext.User.Identity.Name I am trying this:
string username = httpContext.User.Identity.Name.ToString();
if (u.Equals(username))
{
    authorise = true;
}

the domain name and the username are exactly the same, letter for letter, backslash for backslash, capitals for capitals etc.. but the variable authorise is still false. Not sure why. I am beginning to wonder whether there is a way that is considered better practice for doing this.

A: This maybe a mismatch of some kind.  I would write a unit test to verify your assumptions here.
The backslashes may be escaped differently.  You could try matching without these.
function string CleanAndTrim(string user){
    var cleaned = user.Replace(@"\", "");
    cleaned = user.Replace(@"/", "")
    return cleaned.ToLower().Trim();
}

if(CleanAndTrim(u)==CleanAndTrim(username){
  authorise = true;
}

A: Why are you calling .ToString() on a string?  And why are you using an if-statement to set a boolean value?  -- Assign the boolean directly. Try this:
string username = httpContext.User.Identity.Name;
authorise = u.Equals(username);

I wouldn't worry about best practices right now, as you need to get the basics down first.


text:
Q: Can I make git print x.y.z style tag names in a sensible order? Consider this list of version numbers:
0.3.0
0.3.1
...
0.3.8
0.3.9
0.3.10
0.3.11

git tag would print them in the following order:
0.3.0
0.3.1
0.3.10
0.3.11
0.3.2
...

I there any way to make git tag print them in 'numeric' order as opposed to alphabetical order? Or a workaround - perhaps a program I can pipe the output through to order them how I want?

A: Easier solution:
serv ~: echo -e "1.1.1\n1.3.2\n1.1.10\n1.1.2" | sort -V
1.1.1
1.1.2
1.1.10
1.3.2

Breakdown of the sort options being used here:

*

*-V sort by version

A: You will soon (with Git 1.9.x/2.0, Q2 2014) be able to use git only for getting the right sorted output:
See commit b6de0c6, from commit 9ef176b, authored by Nguyễn Thái Ngọc Duy (pclouds):
 --sort=<type>

Sort in a specific order.
  Supported type is:

*

*"refname" (lexicographic order),

*"version:refname" or "v:refname" (tag names are treated as versions).

  Prepend "-" to reverse sort order.

In your case:
 git tag -l --sort=version:refname

A few test cases:
git tag foo1.3 &&
git tag foo1.6 &&
git tag foo1.10

Here is what you would get:
# lexical sort
git tag -l --sort=refname "foo*"
foo1.10
foo1.3
foo1.6

# version sort
git tag -l --sort=version:refname "foo*" >actual &&
foo1.3
foo1.6
foo1.10

# reverse version sort
git tag -l --sort=-version:refname "foo*" >actual &&
foo1.10
foo1.6
foo1.3

# reverse lexical sort
git tag -l --sort=-refname "foo*" >actual &&
foo1.6
foo1.3
foo1.10

A: serv ~: echo -e "1.1.1\n1.3.2\n1.1.10\n1.1.2" | sort -n -t. -k1,1 -k2,2 -k3,3
1.1.1
1.1.2
1.1.10
1.3.2

Breakdown of the sort options being used here:

*

*-n - sort using numerical string order (thus 10 comes after 1)

*-t. - use periods as field separators

*-k1,1 define a sort key on the first field (and only the first field)

*-k2,2 define a sort key on the second field (and only the second field)

*-k3,3 define a sort key on the third field (and only the third field)


text:
Q: How to I append a LD_LIBRARY_PATH to bashrc I'm trying to configure this python package called project, one of the last installation steps requires me to install the libsdf library which I did without issue.
export LD_LIBRARY_PATH=$(pwd)/project/external/pysdf/build/:${LD_LIBRARY_PATH}

cd ./project/external/pysdf/

python setup.py install

I can then call my project .py scripts which use libsdf with no issue as long as I run them through the terminal. Whenever I try to run the same script which worked in a terminal, through an IDE such as VScode, spyder or jupyter I get this error 'Error importing pysdf. Make sure libsdf.so is in LD_LIBRARY_PATH and pysdf is installed'. I'm guessing this is because I haven't defined LD_LIBRARY_PATH globally through the .bashrc.
I tried to correct this but I'm unsure how the LD_LIBRARY_PATH should look as I cant get it working.
I've tried the following:
echo 'export LD_LIBRARY_PATH=/u/myusrname/code/projectv15/project/external/pysdf/build/:${LD_LIBRARY_PATH}' >> ~/.bashrc

where I used the absolute path to /pysdf/build/ where libsdf.so is found.
Can anyone tell me how I set the LD_LIBRARY_PATH in bash correctly.


text:
Q: How can a nested switch be avoided in Flutter/Dart? I'm looking down the barrel of a nested switch statement. I would really like to avoid this rats nest. I know in other languages there are other funky ways of avoiding this, like so, how about Dart?
My data structure is quite complex compared to this, so here is something simple & similar.
enum DayOfWeek {
sun,
mon,
tues,
wed,
thurs,
fri,
sat,
}

enum WeekOfMonth {
/// 1-7
first,
/// 8-14
second,
/// 15-21
third,
/// 22-28
fourth,
/// 29-31
fifth,
}

switch (dayOfWeek) {
  case sun:
    switch (weekOfMonth) {
      case first:

      case second:

      case third:

      case fourth:

      case fifth:

    }

  case mon:

    ...

  case tues:

  case wed:

  case thurs:

  case fri:

  case sat:
}

A: You will always have some sort of nesting, unless there is a logic on what you want to return - e.g. if 1st week, always return 'abc'...
I found recently that a simple way to achieve this is to use a Map instead of case statement.
Not saying I would always recommend this, but this is an approach you might use in some cases.
In a Map you simply store your return values like this
enum DayOfWeek {
sun,
mon,
tues,
wed,
thurs,
fri,
sat,
}

enum WeekOfMonth {
/// 1-7
first,
/// 8-14
second,
/// 15-21
third,
/// 22-28
fourth,
/// 29-31
fifth,
}

String? f(DayOfWeek dayOfWeek, WeekOfMonth weekOfMonth) {

  var ret = <DayOfWeek, Map<WeekOfMonth, String>> {
    DayOfWeek.sun: {
          WeekOfMonth.first: "Sun - 1st",
          WeekOfMonth.second: "Sun - 2nd",
          WeekOfMonth.third: "Sun - 3rd",
          WeekOfMonth.fourth: "Sun - 4th",
          WeekOfMonth.fifth: "Sun - 5th",
         },
     DayOfWeek.mon: {
        WeekOfMonth.first: "Mon - 1st",
        WeekOfMonth.second: "Mon - 2nd",
        WeekOfMonth.third: "Mon - 3rd",
        WeekOfMonth.fourth: "Mon - 4th",
        WeekOfMonth.fifth: "Mon - 5th",
       },
       DayOfWeek.tues: {
        WeekOfMonth.first: "Tues - 1st",
        WeekOfMonth.second: "Tues - 2nd",
        WeekOfMonth.third: "Tues - 3rd",
        WeekOfMonth.fourth: "Tues - 4th",
        WeekOfMonth.fifth: "Tues - 5th",
       },
       DayOfWeek.wed: {
        WeekOfMonth.first: "Wed - 1st",
        WeekOfMonth.second: "Wed - 2nd",
        WeekOfMonth.third: "Wed - 3rd",
        WeekOfMonth.fourth: "Wed - 4th",
        WeekOfMonth.fifth: "Wed - 5th",
       },
       DayOfWeek.thurs: {
        WeekOfMonth.first: "Thurs - 1st",
        WeekOfMonth.second: "Thurs - 2nd",
        WeekOfMonth.third: "Thurs - 3rd",
        WeekOfMonth.fourth: "Thurs - 4th",
        WeekOfMonth.fifth: "Thurs - 5th",
       },
       DayOfWeek.fri: {
        WeekOfMonth.first: "Fri - 1st",
        WeekOfMonth.second: "Fri - 2nd",
        WeekOfMonth.third: "Fri - 3rd",
        WeekOfMonth.fourth: "Fri - 4th",
        WeekOfMonth.fifth: "Fri - 5th",
       },
       DayOfWeek.sat: {
        WeekOfMonth.first: "Sat - 1st",
        WeekOfMonth.second: "Sat - 2nd",
        WeekOfMonth.third: "Sat - 3rd",
        WeekOfMonth.fourth: "Sat - 4th",
        WeekOfMonth.fifth: "Sat - 5th",
       },
  };

  return ret[dayOfWeek]![weekOfMonth];

}

void main() {
  print(f(DayOfWeek.wed, WeekOfMonth.third));
}


text:
Q: Why do we have to copy all files into dedicated folder when doing unit tests? I'm using Mocha Library and the Library by default use a Test folder. So, I have to copy the code I written in production into Test folder when doing Unit Tests with Mocha.
Anyone can think reason behind this method? Is it appropriate?
I'm just a hobbyist, haven't done programming for large companies. I also avoided unit tests thru Mocha for years but it seems it's right time for me to actually start to use Mocha to remove manual testing pain.
EDIT: Actually, I can import the code directly from Production but the practice among examples I witnessed is to use dedicated folder for Unit Tests, I looking to understand reasons behind this practice.

A: It's normal to keep tests in a separate directory because they are not part of the code that would be deployed. But it's also standard practice to import the code you want to test into the test code, without copying any code around.
For illustration, I opened up a random test from Mocha.JS' own test suite, and it does this:
var Mocha = require('../../lib/mocha');


text:
Q: Batch file issues I have a batch file that removes all attributes to .jpg files and then deletes the jpg(s) in that directory.  Great for ripped music.  I have many directories in my MY MUSIC folder.  I'd like to put my DelHiddenJpg.bat in MY MUSIC directory and run it and have it preform those commands in all the subdirectories. This is what is in the DelHiddenJpg.bat
attrib -S -H *.jpg
Del *.jpg

Is there anyway to do this without having to drop DelHiddenJpg.bat in every subdirectory?

A: attrib /S does subdirectories recursively.
del /S also also does subdirectories recursively.
So if you want to sit in the "My Music" directory and do a recursive delete you can do
attrib /S -S -H *.jpg
del /S *.jpg

There is also del /F - force delete - which may allow you to delete without changing the attribs first.
Also check del /Q - Quiet mode - this suppresses the Delete (Y/N) question.
By the way, attrib -S (different from attrib /S), removes the System attrib - not sure why your jpgs will have the system attribute set.
On the other hand, if I have misunderstood your question and you don't want to do a recursive delete, but want to just do one directory at a time, but do not want to have a copy of the batch file in each subdirectory, then this is what you can do.

*

*your batch file should have your original commands (without the /S)

*keep the batch file in any particular directory (for eg . in c:\bin or c\batch) and add this directory to your path - you can do this from Control Panel->System if you want it to be  automatically set for any new command window which is opened.

*Whichever directory you want to run it in, just cd to that directory and run DelHiddenJpg - it will be picked up from the path.


text:
Q: Would it be possible to print the file used to redirect STDERR? Would it be possible to print the filename used to redirect STDERR, given the sample command below:
command.sh 2>file.err

Code in command.sh:
#!/bin/sh
ls -l non_existing_file.txt
echo "STDERR file is: $stderrFilename" # variable should print file.err

A: It's a little risky, but you could try parsing AIX's procfiles output. It involves capturing the major and minor numbers of the stderr device, along with the inode number, then looking for the corresponding device, its mountpoint, and then using find to look for the file with the given inode number:
#!/bin/sh
dev=$(procfiles $$ | awk '$1 == "2:" { print substr($4, 5) }')
inode=$(procfiles $$ | awk '$1 == "2:" { print substr($5, 5) }')

major=${dev%%,*}
minor=${dev##*,}

if [ "$major}" -eq 0 ]
then
  echo I give up, the major number is zero
  exit 1
fi

for file in /dev/*
do
  [ -b "$file" ] || continue
  if istat "$file" | grep -q "^Major Device ${major}.*Minor Device ${minor}$"
  then
    break
  fi
done

fs=$(mount | awk '$1 == "'"${file}"'" { print $2 }')
stderrFilename=$(find "$fs" -inum "$inode")

A: I made a solution using history. Not sure if there is an easier way to do this ( or a proper one).
#!/bin/sh
stderrfname=`history | tail -1 | awk '{ print $3 }' | sed "s/.*>//"`
echo "STDERR file is: $stderrfname"


text:
Q: D2PAK 2-pin NMOS? I was looking up high-voltage NMOSs on DigiKey and found this entry for model STB12NM60N. However, it appears to be a two-pin NMOS (at least, I'm not sure how that tab connects to anything). Based on the pin numbering, as far as I can understand it looks like the NMOS has a gate and source terminal but no drain. I couldn't find anything after looking through the datasheet, and the only other article I've found on D2PAK SMD components just had the tab route internally to another external pin - a different situation to the STB12NM60N which just doesn't have a drain terminal.
My question is two-fold: (a) Does the STB12NM60N have a drain terminal (i.e., all three drain, gate, and source terminals), and (b) how can I route traces to the drain terminal? Thank you!

A: The tab is the drain terminal.
Route the tab as best in your application.

A: The tab/pad is a pin. Same as pin 2 (the cut pin) Not your fault. Datasheet unclear. Can't know without experience. The tab is not always electrically connected though, especially if there is a functional pin elsewhere so all functionality is covered without the tab. Then it could go either way. Electrically isolated tabs are more likely in through-hole and less likely in SMD. But in this case you need three pins and pin 2 is cut so the tab must serve the function of pin 2.

A: I guess it helps to know that D2PAK is a mechanically modified TO-220, where the middle pin and the screw hole tab are internally connected. When using a TO-220, you would use an isolating, heat conducting shim between the tab and a heat sink, and fasten it with a plastic screw or a clip.
However, for SMD, the copper in the PCB is in fact the heat sink, so all of that stuff became obsolete. So the screw hole was removed by shortening the tab, and the middle pin could be cut short, leaving a 3 pad SMD device.
I2PAK (TO-262) is an interim step which can only be fastened to heat sink with a clip rather than screw.
So TO220 became TO-262 by filing down the screw hole part of the heat sink tab, TO-262 became TO-263 (D2PAK) by bending the pins, for SMD use. In this case, the middle pin became then obsolete (but there are other D2PAK devices where this isn't the case).
So yes, it has a drain terminal, it's the rather large third SMD terminal.
And knowing this, routing to it should be fairly obvious, with one caveat. The drain terminal should be well connected to plenty of copper in the PCB, for cooling.
Easy to do it it's connected by vias to an inner supply layer (think half bridge driver), easy to forget if not.


text:
Q: How do I build a link_to tag that takes a string ID instead of a numeric id? I have a routes question concerning Rails 5.  I have this in my config/routes.rb file
  resources :votes

The "show" method in my VotesController can take an ID of either a numeric or string form.
  def show
    id = params[:id]
    if id.present?
      # If they entered a name
      if id.to_i == 0
        name = id.gsub "_", " "
        @person = Person.find_by_name(name)
      else
        @person = Person.find_by_id(id)
      end

I used to be able to construct this link_to to link to the method to generate a link with a numeric ID ...
<%= link_to person.name, vote_path(person), :class => 'unvotedPersonLink' %>

However, I would like to generate a link with a string value for the ID, as defined by a method in my model called "person.seo_name".  So I tried this
<%= link_to person.name, vote_path(:id => person.seo_name), :class => 'unvotedPersonLink' %>

but got the error
No route matches {:action=>"show", :controller=>"votes", :id=>nil} missing required keys: [:id]

How can I build my link_to tag so that it passes in my desired "string" parameter instead of a numeric one?

A: You can pass in whatever you want. If the error is telling you that the ID you're passing is nil, then your seo_name attribute for the Person you're using is nil.
As long as vote_path is expecting an ID, which you can check via rake routes | grep vote, then this will work fine for you as far as generating a link goes:
<%= link_to person.name, vote_path(person.seo_name) %>

But keep in mind that it'll require you to make the necessary adjustments in your controller to search your persons table based on the seo_name column, instead of id.

Also, I highly recommend that you utilize a gem called friendly_id for what you're trying to accomplish. It'll make things a lot cleaner and DRYer, as you can use it easily in any model. And you can easily use either the ID or a URL-friendly slug to query your table, simply by adding friendly to the query:
Person.friendly.find(1)

# OR #

Person.friendly.find('this-is-a-url-friendly-string')

A: In your view
<%= link_to person.name, vote_path(person), :class => 'unvotedPersonLink' %>

or
<%= link_to person.name, vote_path(id: person.seo_name), :class => 'unvotedPersonLink' %>

in your controller
@person = Person.find_by(id: params[:id]) || Person.find_by(name: params[:id])

make sure seo_name method is not returning nil

A: The exception is coming from vote_path, so we can focus on that and not worry about link_to or the controller.
When I'm having route problems like this, the first thing I do is run rake routes (or nowadays rails routes) to make sure I've got the right name. Second I play around in the console with the app variable. For example:
> app.vote_path(1)
 => "/votes/1"
> app.vote_path(id: 1)
 => "/votes/1"
> app.vote_path("foo")
 => "/votes/foo"
> app.vote_path(id: "foo")
 => "/votes/foo"
> app.vote_path(nil)
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"votes", :id=>nil}, possible unmatched constraints: [:id]
> app.vote_path(id: nil)
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"votes", :id=>nil}, possible unmatched constraints: [:id]

You say elsewhere you've checked already that person.seo_name is not returning nil, but I would check again, but it really looks like that's the problem. Try this:
p = Person.find 5   # or whatever is the numeric id
app.vote_path(p.seo_name)

A: The params can contain any information, but you have to process them in the controller based on your need. By default, the routes requires to have an params called :id. If you want other name to be used in your route you can override the default resource identifier :id
Check the rails routing
Make sure the person.seo_name is not returning nil. So, you can use before_save callback in Person model. There, you can set the seo_name field with specific data.
class Subscription < ActiveRecord::Base
   before_save :populate_seo_name, on: :create

   private
     def populate_seo_name
       self.seo_name = ...
     end
end

A: This has been answered in the past https://stackoverflow.com/a/26600064/4652075.
You are passing a string to a field that is expecting an integer and it is being rendered null. You should be passing a string value to a field that is expecting a string. If your "votes" model is generated by ActiveRecord then it is likely an integer.
In your case:
class Person < ApplicationRecord
  def to_param
    identifier
  end

  # or
  alias_method :to_param, :identifier
end

class VotesController < ApplicationController
  before_action :set_voter

  def show end;

  private

  def set_voter
    if !params[:id]?
      @person = Person.find_by(identifier: params[:seo_name])
    else
      @person = Person.find(params[:id])
    end
  end
end

# in the view
<%= link_to person.name, votes_path(identifier: person.seo_name), class: "whatever" %>

Should work.


text:
Q: Google App Engine Saves and Avoiding Fetching Stale Data I've been using App Engine for a few years and one problem that seems to pop up again and again with HDR is the fact that when you update data on one screen, you will sometimes retrieve the old data on the read-only version of that screen if the read-only request is made within a second or two of the update. I know that this has been talked about here and here. I know what the problem is but I'm wondering what the proper solution might be? Here's an example of where I could have stale data.
Say you build a shopping list app.
Entity 1: ShoppingList
Entity 2: ShoppingListItem

The ShoppingList entity has a field on it that keeps a total of the amount items in the list. Entity number two is your ShoppingListItem. When you add or delete a ShoppingListItem, you need to update the total on the ShoppingList. You have two ways to update the total.

*

*Query database and count the number of items in the ShoppingListItem table.

*Auto-increment the cached total field +/- 1 without ever counting the database.

With both solutions, you end up with with stale data. #1 could be out of date because the original save  of the add/delete may not have propagated yet. Therefore the query would miss the new record. #2 will have stale data when you either add or remove multiple items in quick succession. The total is updated for save 1 but on save 2, save 1 may still be propagating and the query for the ShoppingList total for save 2 will still reflect the original state before save 1.
So my question is, what is the proper way to fix this? To me it seems like you have two choices:

*

*Always work off of a memcached entity when using cached totals. Saves will not clear the memcache but instead inject the updated entity directly back into it. That keeps memcache up-to-date. This will of course mean that queries that do not hit memcache (like getting a list of all ShoppingList entities) may still return stale data. But at least when all of the saves are done, the cached total in the database will be correct.

*Deal with the fact that you are going to have stale data but then figure out a way to clean it up sometime in the future. Either schedule a TaskQueue to requery that ShoppingList and update the total in 10-30 seconds or have a scheduled a Cron Job that runs every 30 seconds and looks for all ShoppingList entities that have been updated.

I'm leaning towards solution #1. Thoughts?

A: Option 3 is to give https://developers.google.com/appengine/docs/java/datastore/structuring_for_strong_consistency and https://developers.google.com/appengine/docs/java/datastore/structuring_for_strong_consistency a careful read. What you're encountering is a classic manifestation of "Eventual Consistency". Pay particular attention to Entity Groups and ancestor queries.

A: I think in most cases @david-w-smith's answer is correct. However, I mentioned in my comment to his answer, there is a big limitation to using Entity Groups. That limit is that the Entity Group can only handle one write per second. That's probably fine for applications with just a few users but would not be acceptable for say, a social network.
As was also suggested by the Google documentation (https://developers.google.com/appengine/docs/java/datastore/structuring_for_strong_consistency), I have implemented a rather extreme implementation of caching using memcache. All shoppingList query results are stored in the cache and when the list is either updated, added, or deleted I also update the status  of the query results in the cache. I worry about the natural complexity of maintaining two copies of the data (database and memcache) but that's what UnitTests are for. Right?


text:
Q: separar colunas e retirar a letra t
dados<-read.table("especies identificadas.txt",header=T,sep=",")
  dados
     species.......................com......sem

1              C. maculata\t               1\t3
2           C. sanguinea\t               26\t39
3             E. connexa\t               20\t14
4              H. axyridis\t               2\t7
5          H. convergens\t               12\t37
6        T. bisquinquepustulata         74\t87
7             H. festiva\t               65\t39
8           S. rubicundus\t               50\t3
9         S. demerarensis\t               10\t7
10              S. loewii\t               4\t11
11           D. agapitus  \t               2\t3
12           D. seminulus\t               15\t0
13          Sticholotidini\t               1\t0

A: Tenta modificar o separador. No seu caso, pela saída, a vírgula não é o separador das colunas.
dados<-read.table("especies identificadas.txt",header=T,sep="\t")

A: O problema é que ao colocar o "\t" como parâmetro da função o R reconhece ele como um símbolo de tabulação (o popular "Tab" do teclado) e por isso não reconhece seu separador. Entretanto, ao digitar "\\t" (para que ele reconheça o metacaractere como texto)  o read.table não aceita, pois o separador só pode ser um caractere. Fiz uma modificação no seu arquivo (se é possível fazer) substituir o "\t", por "|" e usei o código:
dados <- read.table("especies_identificadas.txt", header = F, sep = "|")


text:
Q: Breaking nested while loops with boolean So my program tries to find Pythagorean Triplet, where a^2 + b^2 = c^2 AND a+b+c=1000. So everything works well, but program finds the answer quite early in the program runtime, so I would like to break somehow out of all the loops. I am trying simple boolean method, but for some reason my cycle stops after 1 second. If I remove exit = True then everything works (but no break obviously).
P.s. it's also same problem if I use simple 0 or 1 integers to check that.
Can anyone give me ideas why this is not working?
i = 0
j = 0
k = 0
exit = False
while (i < 999 and exit == False):
    while (j < 999 and exit == False):
        while (k < 999 and exit == False):
            if i*i + j*j == k*k:
                if i + j + k == 1000:
                    exit = True
                    ii = i
                    jj = j
                    kk = k
            k += 1
        j += 1
        k = 1
    i += 1
    j = 1
i = 1
print('result: %d^2 + %d^2 = %d^2' % (ii, jj, kk))

A: The specific problem you have is simply that your code does meet the criteria you set, when
ii == 0
jj == 500
kk == 500

If you don't want this trivial solution, you should initialise to 1 at the start (or, better, spot the trivial opportunity to factor out duplication and set e.g. j = 1 in only one place).

A: Make it a Generator Function:
>>> def pythagorean_triangles(target):
...     for a in range(1, target):
...         for b in range(1, target):
...             for c in range(1, target):
...                 if a ** 2 + b ** 2 == c ** 2 and a + b + c == target:
...                     yield a, b, c
...
>>> triangles = pythagorean_triangles(1000)
>>> next(triangles)
(200, 375, 425)

A: Functions are a great way to do this early exit logic. I've also switched your loops to use the xrange() builtin, which cleans up some of your surrounding logic.
def triplet():
    for i in xrange(1000):
        for j in xrange(1000):
            for k in xrange(1000):
                if i*i + j*j == k*k:
                    if i + j + k == 1000:
                        return (i, j, k)

i, j, k = triplet()
print('result: %d^2 + %d^2 = %d^2' % (i, j, k))

Note that from here, there's a number of optimizations that you can make.

*

*Like that given an i and j, you only need to test one k, that is k == 1000 - i - j.

*Like that if you've tested i == 1 and j == 2, you don't need to test i == 2 and j == 1. They will have the same result.

Additionally, if you wanted to skip 0 in the loop, you could do xrange(1, 1000). xrange() allows you to pass a start and an end position.

A: Why not simply using a pythonic way to solve the problem:
[(a,b,c) for a,b,c in itertools.product(range(0,999), repeat=3) if (a**2 + b**2 == c**2) and (a + b + c == 1000)]

A: You have already been suggested how to refactor the code to avoid the need to break loops in the first place, and personally I would use a generator function solution of @pillmuncher (if still considering the use of loops at all).
Here is just an example of how you can break a loop without using a boolean flag:
i = 1
while i < 999:
    j = 1
    while j < 999:
        k = 1
        while k < 999:
            if i*i + j*j == k*k and i + j + k == 1000:
                ii, jj, kk = i, j, k
            else:
                k += 1
                continue
            break
        else:
            j += 1
            continue
        break
    else:
        i += 1
        continue
    break
print('result: %d^2 + %d^2 = %d^2' % (ii, jj, kk))

Or, using more neat for ... in range(...) (or better xrange in Python 2) loop:
for i in range(1, 999):
    for j in range(1, 999):
        for k in range(1, 999):
            if i*i + j*j == k*k and i + j + k == 1000:
                ii, jj, kk = i, j, k
            else:
                continue
            break
        else:
            continue
        break
    else:
        continue
    break
print('result: %d^2 + %d^2 = %d^2' % (ii, jj, kk))


text:
Q: Golang: Interrupting infinite polling having time.Sleep I am using the following simple polling mechanism:
    func poll() {

        for {
            if a {
                device1()
                time.Sleep(time.Second * 10)
            } else {
                sensor1()
                time.Sleep(time.Second * 10)
            }
        }
    }

I need to poll the device1 only if "a" is true otherwise poll the sensor1. Now here "a" will be set to true by clicking the button on UI which will be a random act.
But because of time.Sleep, delay get introduced while checking the condition.
Is there any way to immediately stop time.Sleep when I get the value for "a"?
what are the possible ways to implement such interrupts while polling in golang?

A: You cannot interrupt a time.Sleep().
Instead if you need to listen to other "events" while waiting for something, you should use channels and the select statements. A select is similar to a switch, but with the cases all referring to communication operations.
The good thing of select is that you may list multiple cases, all refering to comm. ops (e.g. channel receives or sends), and whichever operation can proceed will be chosen (choosing one randomly if multiple can proceed). If none can proceed, it will block (wait) until one of the comm. ops can proceed (unless there's a default).
A "timeout" event may be realized using time.After(), or a series of "continuous" timeout events (ticks or heartbeats) using time.Ticker.
You should change your button handler to send a value (the button state) on a channel, so receiving from this channel can be added to the select inside poll(), and processed "immediately" (without waiting for a timeout or the next tick event).
See this example:
func poll(buttonCh <-chan bool) {
    isDevice := false

    read := func() {
        if isDevice {
            device1()
        } else {
            sensor1()
        }
    }

    ticker := time.NewTicker(1 * time.Second)
    defer func() { ticker.Stop() }()

    for {
        select {
        case isDevice = <-buttonCh:
        case <-ticker.C:
            read()
        }
    }
}

func device1() { log.Println("reading device1") }
func sensor1() { log.Println("reading sensor1") }

Testing it:
buttonCh := make(chan bool)

// simulate a click after 2.5 seconds:
go func() {
    time.Sleep(2500 * time.Millisecond)
    buttonCh <- true
}()

go poll(buttonCh)
time.Sleep(5500 * time.Millisecond)

Output (try it on the Go Playground):
2009/11/10 23:00:01 reading sensor1
2009/11/10 23:00:02 reading sensor1
2009/11/10 23:00:03 reading device1
2009/11/10 23:00:04 reading device1
2009/11/10 23:00:05 reading device1

This solution makes it easy to add any number of event sources without changing anything. For example if you want to add a "shutdown" event and a "read-now" event to the above solution, this is how it would look like:
for {
    select {
    case isDevice = <-buttonCh:
    case <-ticker.C:
        read()
    case <-readNowCh:
        read()
    case <-shutdownCh:
        return
    }
}

Where shutdownCh is a channel with any element type, and to signal shutdown, you do that by closing it:
var shutdownCh = make(chan struct{})

// Somewhere in your app:
close(shutdownCh)

Closing the channel has the advantage that you may have any number of goroutines "monitoring" it, all will receive the shutdown (this is like broadcasting). Receive from a closed channel can proceed immediately, yielding the zero-value of the channel's element type.
To issue an "immediate read" action, you would send a value on readNowCh.


text:
Q: How to grant a java tool write permission to /var/log? I'm running a java tool as a command line app using cronjob:
java -jar /var/java/-myfile.jar
By default I'm using logback and write to /var/log/mylogfile.log.
Problem: the user running the jar has no permissions to write to the /var/log/ folder.
That folder has only permissions to `root syslog'.
Question: should I run the jar as sudo? Or should I give the running user write permissions to that folder? If yes, how?

A:
Should I run the jar as sudo?

No. Far too dangerous since you could then change about anything to the system and a single misplaced space could remove your whole system.

Or should I give the running user write permissions to that folder? If yes, how?

Yes.  The 2 main commands are to change write permissions and change the USER of your log file:
   sudo chmod 664 /var/log/{yourdir}/mylogfile.log
   sudo chown $USER:$USER /var/log/{yourdir}/mylogfile.log

where $USER is your current active user and {yourdir}/ is a directory you defined (mysql and apache for instance use their own directory in /var/log/ instead of filling up /var/log/). It is a slightly better method.


text:
Q: Resize Corner takes a lot of space in GNOME The resize corner takes a lot of space. At least half an inch of space in all four sides of any window of a program. How should I scale it down.
I'm on Ubuntu 20.04 LTS.

A: The problem was caused due to a bad scripted theme.


text:
Q: Name clash between scope function and instance method I have the following interface, and code which uses that interface
interface Degenerate {
  fun run(action: Runnable)
}

// elsewhere...
fun consumerOfDegenerate(instance: Degenerate) {
  instance.run {
    // I want to call instance::run
    // but instead it is calling the scope function

IntelliJ gives the following warning message

Candidate resolution will be changed soon, please use fully qualified name to invoke the following closer candidate explicitly:
public abstract fun run(action: Runnable): Unit defined in com.acme.Degenerate

but I can't figure out the syntax to actually do that.

A: I'm not sure what "fully qualified name" (in the context of a function name) means in the warning message, but specifying the parameter name would work:
instance.run(action = {
    ...
})

The scope function run has the parameter name block, which is different from your run method.
If the parameter names also happen to be the same, you can create a Runnable explicitly, since the scope function run takes a () -> Unit instead:
instance.run(Runnable {
    ...
})


text:
Q: Finding $\lim_{n \to \infty} \int_{(0,\infty)} \frac{n \sin (x/n)}{x(1+x^2)}dx$ via DCT I am trying to find $\lim_{n \to \infty} \int_{(0,\infty)} \frac{n \sin (x/n)}{x(1+x^2)}dx$ by applying the Dominated Convergence Theorem for Lebesgue Integrals.
First, considering $(f_n): f_n=\frac{n \sin (x/n)}{x(1+x^2)}=\frac{\sin(x/n)}{(x/n)} \frac{1}{1+x^2},$ it then follows that $\lim_{n \to \infty}\frac{\sin(x/n)}{(x/n)}\frac{1}{1+x^2}=\frac{1}{1+x^2}\lim_{n \to \infty}\frac{\sin(x/n)}{(x/n)}$. And thus substituting with $u=\frac{x}{n}$, we get that as $n \to \infty$, $u \to 0$. Obviously, $\lim_{u \to 0} \frac{\sin u }{u}=1 \Rightarrow \lim_{n \to \infty} f_n = \frac{1}{1+x^2}=f(x).$ Hence $f_n$ converges pointwise to $f$.
Then the requirement is that $(f_n)$ is in $L_1$. I go on to argue that since on $(0,\infty)$ both $\frac{\sin(x/n)}{(x/n)}$ and $\frac{1}{1+x^2}$ are continuous, then both functions are measurable. And because the measurable functions form an algebra, then $f_n$, their product, is also measurable. How do we argue however that they are Lebesgue integrable? I know, for example, that the Lebesgue integral $\int_{(0,\infty)}\frac{\sin x}{x}$ does not exist.
Also, I reckon we are going to use $g(x)=\frac{1}{1+x^2} \in L_1$ to dominate $f_n$ such that $|f_n|\leq g$ for all $n$. I argue as follows: on $(0,\infty)$ we have $|\sin (x/n)|\leq|x/n|$ for any $n$. Hence $|f_n|=\left|\frac{\sin(x/n)}{(x/n)}\frac{1}{1+x^2} \right|\leq \frac{1}{1+x^2}$. So, once again we get to the question of the function being in $L_1$.
Finally, it is straightforward to apply DCT and get $\lim_{n \to \infty}\int f_n= \int f=\left.\tan^{-1}(x)\right|^{\infty}_{0}=\frac{\pi}{2}$. However, application of the Riemann integral bothers me somewhat, as we know that for the bounded Riemann integrable function, the proper Riemann integral is equivalent to the Lebesgue version. Does this application hold?

A: It is not necessary to check that each $f_n$ is Lebesgue integrable. To apply Dominated Convergence, you only need to check that $g$ is Lebesgue integrable. [Anyway, once you have checked that $g$ is Lebesgue integrable, it follows immediately from your inequality $|f_n| \leq |g|$ that each $f_n$ is also Lebesgue integrable.]
So how do you show that $g$ itself is Lebesgue integrable? Perhaps you could first verify that $|g|\chi_{(0,N)}$ is Lebesgue integrable for each $N \in \mathbb N$. [As you correctly pointed out, the Lebesgue integral of $|g|\chi_{(0,N)}$ is equal to the Riemann integral of $|g|$ on the interval $(0,N)$.] Then apply Monotone convergence to deduce that $|g|$ is Lebesgue integrable (with integral equal to $\pi / 2$).


text:
Q: position: absolute; in my hero image doesn´t let me add more content Link to the site is
I have an image with size cover as soon as you enter the page. In order to make it available in every browser (I was having troubles with Opera mini and Android browser) I added this code to the div element:
 .portada{
    width: 100%;
    height: 100%;
    position: fixed;
    padding: 20px 10px 60px 10px;
    height: 100vh;
    top: 0;
    left: 0;
    z-index: 0;
      background: url(../img/nike.jpg) no-repeat center center;
    /* background-attachment: fixed; removed for Android */
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    overflow: hidden;
}

However, now, because of the position: fixed; when I keep adding content into my page, bellow that section, it displays under the picture and I can´t see it. It is destroying my page. And as soon as I take out the position: fixed; code, it goes back to not displaying the image full screen in Opera and old Android browser.
I want to be able to create more content and scroll down the page.
I have tried with position:relative; but it goes back to not working on Opera mini. It displays the image full width but with minimum height.
Any help? Thanks!

A: I think I finally found the solution. I added to the .portada class  min-height: 300px; and now at least in those browsers the image is a little bit bigger and it does the job. I also took out the width and height properties so the final code of the class is:
 .portada{
position: relative;
min-height: 300px;
z-index: -1;
padding: 20px 10px 60px 10px;
height: 100vh;
  background: url(../img/nike.jpg) no-repeat center center;
/* background-attachment: fixed; removed for Android */
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
overflow: hidden;

}
Looks like it works good in every browser I can test.

A: This is because you display your image as a background and your div.portdata is empty. Try inserting the image using img html tag.


text:
Q: Java read huge file ( ~100GB ) efficiently I would like to read a huge binary file ( ~100GB ) efficiently in Java.  I have to process each line of it . The line processing will be in separate threads. I don't want to load the whole file into memory. Does reading in chunks work? What will be the optimum buffer size? Any formula for that?

A: If this is a binary file, then reading in "lines" does not make a lot of sense.
If the file is really binary, then use a BufferedInputStream and read bytes one at a time into byte[].  When you get to the byte that marks your end of "line", add the byte[] and the count of bytes in the line to a queue for you worker threads to process.
And repeat.
Tips:

*

*Use a bounded buffer in case you can read lines faster than you can process them.

*Recycle the byte[] objects to reduce garbage generation.

If the file is (really) text, then you could use BufferedReader and the readLine() method instead of calling read().

The above will give you reasonable performance.  Depending on how much work has to be done to process each line, it may be good enough that there is no point optimizing the file reading.  You can check this by profiling.
If you profiling tells you that reading is the bottle-neck, then consider using NIO with ByteBuffer or CharBuffer.  It is more complicated but potentially faster than read() or readLine().

Does reading in chunks work?

BufferedReader or BufferedInputStream both read in chunks, under the covers.

What will be the optimum buffer size?

That's probably not that important what the buffer size is. I'd make it a few KB or tens of KB.

Any formula for that?

No there isn't a formula for an optimum buffer size.  It will depend on variables that you can't quantify.

A: Java 8, streaming
Stream<String> lines = Files.lines(Paths.get("c:\myfile.txt"));
lines.forEach(l -> {
  // Do anything line by line
});


text:
Q: Difference between 'sale agreement' and 'agreement for sale' Can we use the term "sale agreement" so as to denote an "agreement for sale"?
An "agreement for sale" is in essentially a contract to sell a property in future.

A: Standard terms in U.S. business practice are a sales agreement and an agreement of sale, with both meaning a formal contract for one party to sell and the other to buy. You can look both terms up on a search engine and find lots of references. Under the Statute of Frauds, certain contracts of sale must be formalized in writing to be enforceable. The huge majority of sales, however, occur without any written contract. For example, purchases at a supermarket involve no written contract.
The terms that you references, sale agreement and agreement for sale, are not standard phrases in business practice in Pennsylvania.

A: An 'agreement for sale' is the condition one has to accept before he/she buys or sale. While 'sale agreement' in most cases appears in form of document to claim the ownership of a particular property.


text:
Q: UIPickerView Wrap Around Swift 2 I need help creating an UIPickerView to wrap around the options. So instead of the picker looking like this:

I want it to look like this (without the "min"):

I looked everywhere, but I can't find a way to do it with Swift 2.0
Thanks!

A: Here is an explanation that makes for quicker use:
Goal:
Make your UIPickerView larger than the user will ever try to scroll
Steps:
(1) Extend your picker in size
func pickerView(numberOfRowsInComponent) -> Int {
    return 10_000;
}

(2) Access by Modulus
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return data[row%data.count];
}

(3) Init to Middle (after init)
picker.selectRow((10_000/2), inComponent: 0, animated: false);

A: You can return a very large number in
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
and select the middle row while initialzing with
selectRow(COUNT/2, inComponent: 0, animated: true)
See this code sample


text:
Q: Dificuldade com PDO Estou iniciando com o uso de PDO e estou com uma dúvida que não consegui resolver. Faço o select abaixo que irá me retornar 2 horários:
$sqlSaida = 'SELECT horario
               FROM HORARIOS
              WHERE COD = :codsaida
              UNION
             SELECT horario
               FROM HORARIOS
              WHERE COD = :codretorno;';

$resSaida = $conexao->prepare($sqlSaida);

$resSaida->execute(array(
    ':codsaida' => $codsaida,
    ':codretorno' => $codretorno
));

$saidas = $resSaida->fetchAll();

Mas não consigo armazenar os resultados, abaixo consigo exibir ambos, mas como poderia armazenar eles em variaveis diferentes?
foreach ($saidas as $saida) {
 echo $saida['horario'];
}

A: Cria um array.
    $arrData = [];
    $x = 0;
    foreach ($saidas as $saida) {
       $arrData[$x]['horario'] = $saida['horario'];
       $arrData[$x]['retorno'] = $saida['retorno'];
       $x++;
    }

    echo "<pre>";
    print_r($arrData['horario']);
    echo "</pre>";


text:
Q: Is there a nice html5 2D graphics library that can be used nicely with Three.js? I'm using Three.js to create some 3D graphics using webgl in a canvas element. Is there a nice library to draw 2D elements over the top of the 3D graphics. Something like the HUD of a 3D game. I want to draw some images or text on the screen over the 3D stuff. Any ideas? Can it be done with Three.js?

A: You'll notice in his examples that when he overlays 2D objects he just uses other HTML elements: http://mrdoob.github.com/three.js/examples/webgl_multiple_canvases_grid.html
It may be worth doing the same for yourself, where an entirely separate 2D canvas on top of the 3D one controls the HUD. There are some mouse-event related problems with that approach though, so it depends more precisely on what you need.


text:
Q: This acts on inner Class I have a Class, which contains inner class.
I want to send value, which equals to the top class, but "this" sends the value of inner class. What can I do?
package Controller;
public class MessageFrameListener{
private MessageFrame mf;
private User us;
private Contact cn;
private Timer timer;
private Running run;
private ListFrame lf;

public MessageFrameListener(ListFrame l_f, MessageFrame m_f, User u_s, Contact c_n, Running r_n){
    run = r_n;
    mf = m_f;
    us = u_s;
    cn = c_n;
    lf = l_f;
    m_f.addButtonListener(new SButtonListener());
    m_f.addWinListener(new FrameListener());

    timer = new Timer(500,new timerListener());
    timer.start();
}

public class FrameListener implements WindowListener{

    @Override
    public void windowClosing(WindowEvent e) {
        timer.stop();
        timer = null;
        mf.close();
        lf.removeMFL(this));
    }
}
}

So, this line
        lf.removeMFL(this));

sends "FrameListener" by this, but I want to send "MessageFrameListener"

A: Use the qualified this:
MessageFrameListener.this

A: Use:

   lf.removeMFL(MessageFrameListener.this);

A: Within the inner class itself, you can use
MessageFrameListener.this;

You can also add a method to the outer class
public MessageFrameListener getInstance() {
    return this;
}


text:
Q: Windows Forms Touch Screen App Not Picking Up Button Click I have written a .net application using vb which emulates a keyboard, each button (I've tried with both native windows form buttons and devexpress simple buttons) on the form when clicked appends its text property to a label control. This works absolutely find on 3 of the 4 touch screens I have, however, the fourth screen is very intermitant in whether it will collect the touch.
Windows seemingly has registered the touch but the application does not acknowledge it (again this happens randomly on 1 hardware vendors device - a seperate model from the same hardware vendor works fine).
To make matters more confusing for me, the windows keyboard and native windows applications seem to work without issue on the same device. All devices tested are running Windows 10 LSBT.
I've even gone to the point where I am registering several events to prove that they are being picked up, and comparing the touch results to those of a stylus being used in its place (which incidentally works perfectly with no issues).
I've had a look at all touch options in windows, again with no real success and after now spending the entire week on this have pretty much run out of ideas.
Any tips / suggestions / straws to clutch onto at this point would be gratefully recieved,
Thanks
Chris

A: In the end between myself and a colleague we both went down the route of capturing gestures and manipulating to suit our needs.


text:
Q: How to Bubble sort in C an array of type struct using temporary int (tmp)? I get error from the compiler because I can't assign an integrer type tmp to a struct type. I try to bubble sort array of struct type. The code is bigger than this but I think this is enough to provide all the info you need.
struct varor{
     int varunummer;
     char namn[WORDLENGTH];
     int lagersaldo;
 };
 typedef struct varor Vara;

 void sorteraVaror(Vara reg[]){
         int i,j, tmp;
         for(i=0; i< MAX-1; i++){
             for(j=0; j<MAX-1; j++){
                 if(reg[j].varunummer>reg[j+1].varunummer){
                 tmp=reg[j].varunummer;
                 reg[j].varunummer=reg[j+1].varunummer;
                 reg[j+1].varunummer=tmp;
                 }
             }
         }
 }

A: As @vladfrommoscow points out, and in other words; tmp must be of the same type as the structs in the array.


text:
Q: If Sauron wins eventually without the Ring, why weren't Elrond/Gandalf in panic mode before Frodo showed up? Sort of a follow-up question to Why did the Council of Elrond debate hiding or sending the Ring away, if Sauron wins eventually in that scenario?
If Sauron wins eventually even without finding the Ring, then it seems the situation was already critical by the time Frodo brought the Ring to Rivendell, and would be even more critical if Frodo had not showed up. In that sense, it was a major stroke of good fortune for Frodo to show up when he did - it gives them the option to send it to Mt. Doom.
From the answer to the question above, even though many of the attendees at the Council of Sauron didn't know how bad the military situation was, Elrond/Gandalf (and maybe Aragorn) did know. Why weren't they in panic mode then? One might've expected Frodo not to have arrived at an idyllic Rivendell, but one that was preparing for war - either by preparing help for Gondor, sending envoys to warn Erebor and other potential allies & ask for help, or commission searches for the Ring, etc., before Frodo ever arrived.

A: @alexg's analysis is excellent and I have upvoted it.  I'd like to add one point:
People -- and Elves, too -- are really, really bad at sustaining an emergency over centuries. Gondor (or maybe possibly all of humanity on Middle Earth) can sustain a high alert against Sauron for a few months or even, maybe possibly, a few years, but not longer.
Sauron is a threat, but a very, very distant one. I live in Massachusetts, and let's say that I know that Quebec is a volcanic wasteland and was taught in history class that three thousand years ago (about the time Homer wrote the Iliad) we fought a war with the Dark Power of Quebec and defeated him, but did not destroy him. Would we still be maintaining a huge army just in case?  Or would we shrug and sweep the occasional ash from Mt. Le Doom off our walkways? (Consider how people on our own Earth responded to various actual aggressors. "Herr Hitler? Mr. Putin? They're all talk. We can work with them." )
Or consider how people living in a much more unmistakable threat -- all those Neapolitans living on the slopes of Vesuvius, for example or the Californians living on the San Andreas -- handle the very real risk of geological destruction. They shrug. Maybe they take a few precautions. But they go right on living their lives there.
It must have been very, very frustrating to be Gandalf or Elrond trying to persuade generation after generation of Men that preparing for an eventual return of Sauron was more important that dealing with their clear and present troubles.
Added: Note, BTW, that Tolkien had direct, personal experience of this right when he was writing LotR in an England at war with Germany which had largely ignored Sir Gandalf Churchill's repeated warnings.

A: Further to existing answers, while the long-term prospects were indeed grim, over the few decades before the Council, the free peoples had actually had a long string of local victories - the storming of Dol Guldur, the death of Smaug, the Battle of Five Armies, the Thorongil campaigns in the South, the re-establishment of a Gondorian garrison in east-bank Osgiliath, the Rangers increasingly securing the Bree-land.  That winning streak only really came to an end with Sauron's counter-attack on Osgiliath, which happened after Gandalf had conclusively identified the ring.
Contrast with the rather worse situation at the start of The Hobbit, when Gandalf was concerned about the possibility of an imminent attack on Rivendell by an army from Rhûn, given cover for the crossing of Rhovanion by Smaug.  One could interpret Gandalf and Elrond's encouragement of the quest of Erebor in that circumstance as a sign of panic.

A: We can start the clock even further back. It would have been sensible, after Sauron's defeat at the War of the Last Alliance, to take military measures so that his forces could not use Mordor as a base. Although the inner part of Mordor is hard to occupy for non-orcs, a system of perimeter fortresses and patrols could be established. This is actually what happened, but it failed; Gondor was led to withdraw due to other circumstances, and places like Minas Ithil fell under the enemy's control.
It might have been sensible, at this point, to counterattack. This is also what happened, but regrettably King Eärnur of Gondor did not return - the line of kings in the south was broken and Gondor was net worse off than before.
Knowing about the Ring, it might have been sensible to look for it. They actually did, and Saruman kept looking even after discouraging others.
If you are playing the long game, you might think to build up an immensely powerful military force over a period of centuries. The most obvious precursor is the mighty kingdom of Numenor, and that didn't go very well. Elrond would be skeptical, even aside from the fact that becoming the immortal shadow ruler of a warlike nation is really more of a Sauron move.
In summary, they have tried a lot of the most sensible ideas. But in the long term, the problem is that Sauron keeps coming back, and they can never sustain the military strength necessary to defeat his forces absolutely. In Elrond's lifetime, various kingdoms have risen and dwindled. As he says, "I have seen three ages in the West of the world, and many defeats, and many fruitless victories."
Thus, the strategic situation for the bulk of the Third Age is one where the goodies are essentially under siege, and occasionally have larger wars that are very costly but inconclusive. No war to date has stopped orcs from eventually reoccupying Gundabad, and Gondor has been in a long stalemate of trying to contain Mordor while lacking the strength to attack it properly. Rivendell may be idyllic internally, but it is still the Last Homely House, set in the midst of a wild landscape crawling with danger. The Shire is at peace, but only thanks to the continual efforts of the Rangers who hold back threats from the North.
So at the point the main narrative begins, the status quo is the assumption that the goodies are mainly trying to survive, and have never inflicted a military defeat on the enemy that lasted in the long run. Elrond is personally familiar with all of this, even if not all of his allies share the same view. For example, Galdor asks whether the Grey Havens could withstand Sauron indefinitely - it's not obvious to him that they can't. Boromir is more confident in Gondor's strength, but Elrond is bitterly aware that over enough centuries, it cannot be sustained. Given the waning strength of the Elves, and the fact that Sauron just keeps coming back, he fears that even a military victory would only mean that the next time Sauron returns, he will face less opposition, and so can grind out a win in the very long term. This is not a cause for panic, because it's a strategic question for the millennia, but it does shape Elrond's thinking.
One of the main things that Elrond and Gandalf are doing at the Council is to bring everyone else around to their point of view. The hobbits note that Gandalf, in particular, has been privately lobbying everyone else about the threat posed by Mordor. They have already been engaged in low-level warfare for centuries, but the situation has recently come to a head. Elrond and Gandalf are too experienced to panic, but they are making essentially the correct choices given the new strategic reality. The Ring has been found and Sauron knows it. They have the chance to inflict a final defeat on him. They are actively pursuing a decisive course of action, using what strength they have.


text:
Q: socket.io Sending a dictionary in Swift does not work I am having an issue sending dictionaries over socket.io. From what I have read, dictionaries are natively supported and there is no need to first encode to a JSON. I have setup code like so:
func configureSockets() {
        // Create a default manager object
        socket = manager.defaultSocket

        socket.on(clientEvent: .connect, callback: {data, ack in
            print("SOCKETS.IO CONNECTED")
        })

        socket.on(clientEvent: .disconnect, callback: {data, ack in
            print("SOCKETS.IO DISCONNECTED")
        })

        socket.onAny({(event) in
            print("any event!!")
        })

        socket.on("chat message", callback: {data, ack in
            print("GOT A CHAT MESSAGE!")
        })

        // Connect to the server
        socket.connect()
    }

The setup is done in viewDidLoad. I emit the message like so:
socket.emit("chat message", ["name": "Bob"])

I get nothing back at all when I send a dictionary like above. However sending a string works e.g:
socket.emit("chat message", "Hello World!")

Any ideas what I am doing wrong here? Would really appreciate some feedback. Thanks.


text:
Q: jQuery DataTables requested unknown parameter I've having a hard time figuring out why this doesn't work... So the jsfiddle will work.
jsfiddle working
Now the jsfiddle works because I have created a var exactly to what console.log(data) in the code below produces.
$(document).ready(function () {
    $("#<%= ddlProduct.ClientID %>").change(function (e) {
        var P_ID = $("#<%= ddlProduct.ClientID %>").val();
        $.ajax({
            headers: {
                Accept: "*/*"
            },
            type: "POST",
            url: "../service/product.asmx/GetProduct",
            data: '{"jsondata" : {"P_ID" : "' + P_ID + '"}}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg, status, metaData) {
                var data = msg.d.P_ID;
                buildMyDatatable(data);
            },
            error: function (ex, status) {
                //alert(ex.responseText);
                alert("error");
            }
        });
    });

    function buildMyDatatable(data) {
        console.log(data);
        $("#table_id").dataTable().fnDestroy();
        $('#table_id').dataTable({
            "bProcessing": true,
            "aoColumns": [
                    { mData: "Q_ID"},
                    { mData: "Business" },
                    { mData: "Product" },
                    { mData: "QuestionType" },
                    { mData: "Question" },
                    { mData: "Answer" },
                    { mData: "AskBy" },
                    { mData: "AnsBy" },
                    { mData: "AnsByEmail" },
                    { mData: "DateAsk" },
                    { mData: "DateAns" }
                ],
                "aaData": data,
        });
    }
});

My question is, why does var data = server.hardcoded.response work vs it not working when using the actual ajax response?
When using the ajax response I get this error.
DataTables warning (table id = 'table_id'): Requested unknown parameter 'Q_ID' from the data source for row 0

A: I have solved the problem.
var data = $.parseJSON(data);

inherently JavaScript was passing it as a string and not an object.


text:
Q: CSS3 Transition with Varying Ease Not Working I have tried comparing the code to a few sources, including the tutorial I followed to make it and my transitions aren't working, it's just jumping from its starting state the end with no animation.
Thank you in advance.
HTML:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<link rel="stylesheet" type="text/css" href="style.css" />

no

one

two

three

four

five

minustwo

CSS:
div {
width: 300px;
margin: 5px 0;
padding: 5px;
color: white;
background-color: #ED8029;
text-align: left;
border-radius: 5px;
}

div:hover  {
width: 700px;
}

div.no {
-webkit-transition: 3s linear;
-moz-transition: 3s linear;
-o-transition:  3s linear;
-ms-transition: 3s linear;
transition: 3s linear 2s;
}

div.one {
-webkit-transition: 3s linear 1s;
-moz-transition: 3s linear 1s;
-o-transition: 3s linear 1s;
-ms-transition: 3s linear 1s;
transition: 3s linear 1s;
}

div.two {
-webkit-transition: 3s linear 2s;
-moz-transition: 3s linear 2s;
-o-transition: 3s linear 2s;
-ms-transition: 3s linear 2s;
transition: 3s linear 2s;
}

div.three {
-webkit-transition: 3s linear 3s;
-moz-transition: 3s linear 3s;
-o-transition: 3s linear 3s;
-ms-transition: 3s linear 3s;
transition: 3s linear 3s;
}

div.four {
-webkit-transition: 3s linear 4s;
-moz-transition: 3s linear 4s;
-o-transition: 3s linear 4s;
-ms-transition: 3s linear 4s;
transition: 3s linear 4s;
}

div.five {
-webkit-transition: 3s linear 5s;
-moz-transition: 3s linear 5s;
-o-transition: 3s linear 5s;
-ms-transition: 3s linear 5s;
transition: 3s linear 5s;
}

div.minustwo {
-webkit-transition: 3s linear -2s;
-moz-transition: 3s linear -2s;
-o-transition: 3s linear -2s;
-ms-transition: 3s linear -2s;
transition: 3s linear -2s;
}

A: When you specify a transition, you need to specify the property you're trying to animate. So, for example, you should write something like:
div.no {
-webkit-transition: all 3s linear;
-moz-transition: all 3s linear;
-o-transition: all 3s linear;
-ms-transition: all 3s linear;
transition: all 2s linear;
}

Here's some more info on using transitions.


text:
Q: Save superscript symbols in SQL Server I want to save alpha, beta, theta and all super script symbols in SQL Server database through my .Net windows application. And I need to fetch again and want to show on label control. What do I have to do? I am using C#.

A: Store them in a nchar(n) or nvarchar(n) field in sql server. Don't forget the N' ' notation for strings. To represent the characters in you label, you'll need a unicode font.
I think everything else is the same for storing, retrieving and placing string values on a label.


text:
Q: Request method 'PUT' not supported When calling from Resttemplate I have to call a PUT method using Resttemplate. I am able to hit the service from POST Man. But when i try the same request from Java using Resttemplate its throwing error .What could be mistake i am doing.
405 : [{"category":"ACCESS","code":"METHOD_NOT_SUPPORTED","description":"Request method 'PUT' not
supported","httpStatusCode":"405"}]

@Autowired
@Qualifier("orderMasterUpdateClient")
private RestTemplate orderMasterUpdateClient; // Loading the template with credentials and URL

ResponseEntity<SalesOrderDocument> responseEntity = orderMasterUpdateClient.exchange(
                URL,
                HttpMethod.PUT,
                new HttpEntity<>(headers),
                SalesOrderDocument.class, changeRequest);

A: If you want to send changeRequestobject data in the body of the PUT request, I suggest you to use next RestTemplate exchange method call:
String url = "http://host/service";
ChangeRequest changeRequest = new ChangeRequest();
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<ChangeRequest> httpEntity = new HttpEntity<>(changeRequest, httpHeaders);

ResponseEntity<ChangeRequest> response = restTemplate
            .exchange(url, HttpMethod.PUT, httpEntity, ChangeRequest.class);


text:
Q: static initialisation order issue with static/dynamic linking If a c++ application is organised in following manner
//file1.cpp
static Y sgObj = X::getInitObject(0);  //declared in file scope

//file2.cpp
namespace{
   int getInitValue()
   {
      static int val = Y::sObj.initVal();
      return val;
   }
}

namespace X{
   Y getInitObject(int initVal)
   {
      if(initVal < getInitValue())
      {
         cout << "Print some log message" << endl;
      }

      return Y::initMethod(initVal);
   }
}

//file.h
//This class is shipped as static and dynamic library, and application is supposed to link
//them in their executable based on their need
class Y{
public:
int initVal();
static Y initMethod(int val);
static Y sObj;
};

Assuming all the necessary header files are included and we are able to create the executable for this application, does it have initialization issue with the way I am creating the object in file1.cpp when:

*

*statically
  vs

*dynamically linking with the library(corresponding to implementation of class Y) for creating the object sgObj.

Given the class Y's implementation is not exposed to application, we can't change the way its static member sObj is created.
Does it have anything to do with platform / compiler being used?

A: You must either assure that file1.cpp includes <iostream> before the definition of sgObj or you need to construct a local object of type std::ios_base::Init before you use cout during the static initialization:
  if(initVal < getInitValue())
  {
     (void)std::ios_base::Init{};
     cout << "Print some log message" << endl;
  }

Otherwise cout might not be initialized when you reach that line.

Other than that, the order in which Y::sObj and the global sgObj are constructed is indeterminate, assuming Y::sObj is defined in another translation unit not shown, because the order in which dynamic initialization between different translation units happens is indeterminate.
Therefore, if Y::initMethod, which is called from the global initialization of sgObj accesses Y::sObj it might not be initialized yet, causing undefined behavior.
If you want to be able to use the static Y::sObj during static initialization of other non-local static variables, you need to use something like the Meyers singleton pattern:
class Y{
//...
    static Y& sObj {
        static Y instance /* initializer here */;
        return instance;
    }
};

To be used as Y::sObj() instead of Y::sObj.


text:
Q: An internal error occurred during: "Building UI model" i am trying to create new project in eclipse "Spring started Project" but it gives the error An internal error occurred during: "Building UI model".
com/google/common/base/Function
i am new in spring boot ..please solve the problem also shared screenshot here.

A: Please install "TestNG plug-in for Eclipse". It will solve the issue.

A: I found this problem same you. Because your Eclipse and STS version miss match. example I use Eclipse Mar(4.5.x) and download Spring version 3.8.2  this is miss match version.
I have 2 solution

*

*Download Spring Tool suit (STS) at "https://spring.io/tools/sts/legacy"
Please check your Eclipse before download

OR

*you can not download STS at "Eclipse Market Place". because eclipse search new version of STS. (is match for new vesion of Eclipse)
you can download at "Install new software". and I use this Link http://dist.springsource.com/release/TOOLS/update/e4.X/
you can insert version match for your Eclipse at "x"

A: I was also facing same issue. I fixed it by updating all the plugins etc. You need to click on "Check for Updates" in help and proceed further.
I have Eclipse Neon.3 Release (4.6.3). I added STS plugin through Marketplace. (See http://www.adeveloperdiary.com/java/spring-boot/create-spring-boot-application-step-step/)
After that I got the same error while creating new spring starter project.
An internal error occurred during: "Building UI model".
com/google/common/base/Function

After updating all the plugins i am able to creat a new spring starter project.
Regards,
Krishan


text:
Q: How can we do alterate row coloring in SSRS I have a SSRS table where there are three rows . First row is Category and Second Row is Subcategory . These fields are individual fields in database. The third row is the total . I need color formatting like below .
This is the structure of my table in SSRS .
enter image description hereenter image description here

A: For your Category and Total rows, just set the background color property as desired as these will not change.
For you subcategory rows set the background color property to something like
=IIF(RowNumber(Nothing) Mod 2 = 0, "Silver", "#F08080")

CHange the color names or hex values to match your required colours.

A: Alternative is to put the following code in your report (Report Properties -> Code)
Public Function BackColour(Byval line as Decimal) as String

If line = -1
    return "Gainsboro"
End If
If line = -2
    return "LightGrey"
End If
If line = -3
    return "Silver"
End If
If line mod 2 = 0
    return  "#F08080"

Else
    return "White"
End If

End Function

Now if your inner most details group, set the background color to the following :
=code.backcolour(runningvalue(Fields!sub_category_code.Value,countdistinct,nothing))

Hope this gives you the result you are after


text:
Q: How to programmatically mute video How to play a video without sound?
I have tried these options but neither of them worked:
1) Setting the MPMusicPlayerController player to ipodMusicPlayer and disabling the application audio.
musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

2) Forcing the app to run the audio
 NSError *error = nil;
 if ([[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&error]) {
     NSLog(@"Error setting audio session: %@", error);
 }

A: Use this codebase to mute.
NSError *errorFeedBack = nil;

if (![[AVAudioSession sharedInstance] setActive:NO error:&errorFeedBack] )
{
    NSLog(@"Error encountered: %@", [errorFeedBack localizedDescription]);
}


text:
Q: Changing boolean value in pandas dataframe through function i'm super new to coding and trying to change a boolean set in a pandas df from True to False.
I want to select a certain row, based on a name.
My df, df_contacts looks like this:
     name  gender relationship category access          timestamp proof
0    Emma  female         ex-girlfriend   True  1653939064.769388     1
1   Amber  female         ex-girlfriend   True  1653939064.769388     1
2    Mark    male              business  False  1653939064.769388     1
3  Claire  female         ex-girlfriend   True  1653939064.769388     1
4    Sara  female             co-worker  False  1653939064.769388     1
5  Marcus    male                friend  False  1653939064.769388     1
6  George    male          soccer-coach  False  1653939064.769388     1

I want to change the value True, behind Emma's name, into False.
How can i write this function based on user_input, and not on index?
I am stuck on this:
code
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
        if block == 'yes':
            df_contacts.loc[df_contacts["access"] == True, False]
        print(df_contacts)

switch_access(name)

A: This will change it using numpy
import numpy as np
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
        if block.lower() == 'yes':
            condition_list = [df_contacts['category'] == True, df_contacts['category'] == False]
            choice_list = [False, True]
            df_contacts['category'] = np.where(df_contacts['name'] == name, np.select(condition_list, choice_list, df_contacts['category']), df_contacts['category'])
        return df_contacts

df = switch_access('Emma')
df

I also altered your code a little to make it slightly more fault tolerant

A: You can use:
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
        if block == 'yes':
            df_contacts.loc[df_contacts['name'] == name, 'access'] = False
        print(df_contacts)

switch_access('Emma')

Output:
     name  gender relationship category  access     timestamp  proof
0    Emma  female         ex-girlfriend   False  1.653939e+09      1  # True to False
1   Amber  female         ex-girlfriend    True  1.653939e+09      1
2    Mark    male              business   False  1.653939e+09      1
3  Claire  female         ex-girlfriend    True  1.653939e+09      1
4    Sara  female             co-worker   False  1.653939e+09      1
5  Marcus    male                friend   False  1.653939e+09      1
6  George    male          soccer-coach   False  1.653939e+09      1

A: If you want to read the name along with changing the boolean value, you can use this code...
name = input("Enter name of contact: ")
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access(name, block):
    if block.lower() == 'yes':
        if df_contacts.loc[df_contacts["name"] == name]['access'][0] == True:
            df_contacts.loc[df_contacts["name"] == name, 'access'] = False
            print(df_contacts.loc[df_contacts["name"] == name])

switch_access(name, block)

Output
Enter name of contact: Emma
Confirm restricting this contact from seeing your photos? Yes
   name  gender relationship_category  access     timestamp  proof
0  Emma  female         ex-girlfriend   False  1.653939e+09      1


text:
Q: How to encrypt private keys like OpenSSL? When I generate a private Elliptic Curve with OpenSSL, with this command:
openssl ecparam -name secp521r1 -genkey -noout -out key.pem

I get something like this:
-----BEGIN EC PRIVATE KEY-----
MIHbAgEBBEGpyKy6t0i6cEdxETKfsXNmFA4oWLQrM1LaPdfiyGs13+DckCjskukK
NlbQYBb7gKIAAqj4vbmdCjTkoxnuXToqRKAHBgUrgQQAI6GBiQOBhgAEAHRbQ/Ow
rR0fjiLdS+wHgpGX3kIk1IdJwr6m18k8nkta7d6YCho555Tbru+17zrtEMasd5UH
YX8PRRtGaCD29aOzASUXOkwrmth4wLRsDQEe4qWAjATVvbw4LDP9Jz92OFXbEPwR
P3uNunAQ2grnBjNCXN5yF49nyK1lSZxscxv+OCM/
-----END EC PRIVATE KEY-----

which has the same format to what I generate with a mix of NodeJS' Crypto module plus key-encoder:
-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIBevCX7Zvo2G93UtPEl2ibpz71dXdjN/xMbwZBQwHukZJWwuKtJ8Sm
dn21nDV5uEa7mgiBu0X5BVvsN/Wr+TzoAD2gBwYFK4EEACOhgYkDgYYABABaycjM
EduL5R+bBY7T5WF+L314mfm2AZkKDs4EDkYWPupzbfE1qsQkjyPjh/JxMRU6nr9w
xJ7X9jSA6wy0dHNqSQFP+5SHOuJu32Da21qBIKU9Xaoy0CloGfRjEQAbg5N1h4uw
wKdMrY2a34dYn1eEe2YFzHKTFJPzOxyeKsDsFaafng==
-----END EC PRIVATE KEY-----

Now, when I encrypt it with AES256 by using this command
openssl ec -aes256 -in key.pem -out encrypted-key.pem
I get
-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,96218C0F2D6F661750C994B319DD05FB

pdk5WCaaLL8+YU27QjHMRgNkNwgPfgqL2ZNx/73pBDiSekfEKn39XrllE+j0lEA/
jNt1v85bBl4GQR97Br1wYl0WyHRTMlJvyc1f+dRIG+Pyu2gt4bdWaXbuajn0suWG
EGNPKBQJNvY3+J010FQfVI45puC03gKA910ODSE3igNuAtSxoptmbD9DMr/2hj2y
BG1WarSvtX9P/eFw6sLVtou8iAD53lO41SA/ppHAbwuGdFwH9bA/LKlQUEHC3v2J
QJmEdt/1wYO4QLtFulDpNVd7nqGd3yn2/sZ1E5XBJ4E=
-----END EC PRIVATE KEY-----

How can I get a similarly encrypted key with NodeJS' Crypto? or in other words, what's that format and how is it encrypted. With NodeJS' Crypto is trivial to do aes-256-cbc encryption, but I'm not sure how the passphrase is processed (hopefully pbkdf2) and how to reach that format. Is it documented somewhere?