BigQuery SQL - how to pivot the top 3 results into columns

Question: Long time lurker first time poster...
I have a flat table like below and I want to bring back the top 3 finishers by event into separate columns.
with races as (
select "200M" as race, "johnson" as name,23.5 as finishtime
union all
select "200M" as race, "smith" as name,24.1 as finishtime
union all
select "200M" as race, "anderson" as name,23.9 as finishtime
union all
select "200M" as race, "jackson" as name,24.9 as finishtime
union all
select "400M" as race, "johnson" as name,47.1 as finishtime
union all
select "400M" as race, "alexander" as name,46.9 as finishtime
union all
select "400M" as race, "wise" as name,47.2 as finishtime
union all
select "400M" as race, "thompson" as name,46.8 as finishtime
    )

    select * from races

I would like the output to basically look like this:
Race  |  1st Place  |  2nd Place  | 3rd Place
200M  |  johnson    |  anderson   | smith
400M  |  thompson   |  alexander  | johnson

I didn't put a tie into the data above but I will have some of those too...
Thanks in advance!
Answer: Consider below
select * from (
  select race, name,
    row_number() over(partition by race order by finishtime) pos
  from races
)
pivot (any_value(name) as place for pos in (1,2,3))

if applied to sample data in your question - output is
Comment: You made that too easy!  Thanks Mikhail.
Comment: so, did this worked for you?


Chamando função com onclick

Question: Galera eu não consigo chamar uma função usando o onclick, chamando ela direto da tag html vem normal mas se eu chamar de forma não obstrutiva sem chance já li varios docs tentei n maneiras e nada alguem pode dar uma luz.
document.getElementById("btSoyouzm").onclick=function(){buscaImagem()};

function buscaImagem(){
        alert("teste do onclick")
}

Comment: Funciona bem para mim... http://jsfiddle.net/yhfvY/ Pode re-criar o problema no jsFiddle?
Comment: @MatheusBessa isso funciona, porém não queria marcar no html.
Comment: Tentou `window.onload`?
Comment: Não seria isso:   ?
Comment: @Sergio funciona =/, agora porque que na pagina não funciona ja tirei e coloquei onload mil vezes.
Comment: @GuilhermeNascimento já tentei com e sem window.onload
Comment: @HeltonSS, coloque o código no fundo da página. Antes do ``. Se não funcionar precisa colocar mais código aqui ou seguir uma das respostas abaixo.
Comment: @Sergio coloquei o código no final da página como disse e todas respostas funcionaram... não entendi bem o que aconteceu mas vou buscar estudar esse erro, se alguém tiver uma boa explicação, geralmente so colocava no final da página quando estava para subir o arquivo.
Comment: @HeltonSS, se funcionou no final da página então é porque falta `window.onload = function(){ /* o seu codigo aqui */};` Pode testar com isso?
Comment: @Sergio por incrivel que pareça o codigo todo o momento estava com o window.onload vou pesquisar se alguém já teve tal erro. grato pela atenção de todos.
Comment: Dê um exemplo do problema usando o [jsfiddle](http://jsfiddle.net)
Answer: Tenta assim caro amigo
document.getElementById("btSoyouzm").addEventListener("click", buscaImagem, false);

function buscaImagem(){
        alert("teste do onclick")
}

Documentação : addEventListener
Comment: Porque o downvoter? o que tem de errado com a resposta?
Comment: Tá certo a resposta do @Silvio Andorinha!
Comment: @SilvioAndorinha tenho o seguinte retorno do browser "add event not is defined";
Comment: @HeltonSS qual browser você está usando?
Comment: @HeltonSS sugiro uma implementação cross-browser como na minha resposta :D
Comment: @SilvioAndorinha cara para os teste eu sempre uso o firefox e o chrome.
Comment: Era para ter funcionado porque o `addEventListener` funciona no chrome e no filefox
Answer: Para implementar um evento OnClick dinamicamente você precisa adicionar esse evento ao objeto DOM com o addEventListener como na resposta do @SilvioAndorinha, entretanto essa implementação é diferente em outros navegadores nesse caso você pode utilizar uma função para fazer está implementação cross-browser.
Sua Função
function buscaImagem(){
        alert("teste do onclick")
}

Javascript addEvent cross-browser
var addEvent = function(elem, type, eventHandle) {
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, eventHandle );
    } else {
        elem["on"+type]=eventHandle;
    }
};

addEvent(document.getElementById("btSoyouzm"), "click", function(){
  buscaImagem();
});

ou
addEvent(document.getElementById("btSoyouzm"), "click",buscaImagem);

Comment: cara eu ja havia tentado sua resposta e também não deu resultado a unica diferença é que não deu erro no console.
Comment: Aqui esta o teste http://jsfiddle.net/vTv8T/
Comment: Galera vou testar em outra maquina não tem cabimento o que esta acontecendo, prometo dar o feedback depois.

Chamando função com onclick


create objects dynamically according database values

Question: I have a  Flex project. I want to dynamically create mx.controls.Image objects and add them to the display. However, the number of images and it properties deponds on the value stored in a database. Hence, I have to connect to the database,read the values for data table, then  create objects  dynamically according the values.
Then,  I wonder if this is possible and how to do this.
Thanks in advance.
Felix
Comment: You work in Flex Air? In this version is posible. The BD images is encoding? Or only have the reference path for this.
Answer: Just try declaring a variable as *.
Like var any:*; And check always for null. So it will take any type of value.
Hope it will help.


Continuity and limit

Question: $f: (0,\infty) \rightarrow \mathbb{R}$ is continuous and $f(x) \le f(nx) \  \ \forall{{x>0},{n\in\mathbb{N}}} $
Prove that f has limit (may be infinity)
Don't know what to do maybe something with Darboux property.
Comment: $f$ has limit when $x$ tends to...
Comment: I haven't specified in the exercise, assume that $x \rightarrow \infty$
Answer: $\textbf{Lemma}$: Let $0<a<b$. Then there exist $N>0$ such that $(N,\infty)\subseteq\cup_{n=1}^\infty (na,nb)$.
$\textbf{Proof}:$ Let $k_0$ be big enough such that $\frac{k+1}{k}<\frac{b}{a}$ for all $k\geq k_0$. Then $(ka,kb)$ and $((k+1)a,(k+1)b)$ have no trivial intersection for all $k\geq k_0$. Choose $N=k_0$.
Now suppose that there exist two sequences $\{x_n\}$ and $\{y_n\}$ such that $\lim x_n=\lim y_n=\infty$ and $\lim f(x_n)=x<y=\lim f(y_n)$ for some $x,y\in [-\infty,+\infty]$. Choose $x<w<y$ and let $n_0$ be such that $f(x_n)<w$ and $f(y_n)>w$ for all $n\geq n_0$. Let $a=y_{n_0}$ and $b=y_{n_0}+\delta$ for some $\delta>0$ such that $f(z)>w$ for all $z\in (y_{n_0},y_{n_0}+\delta)$. Using the lemma above we conclude that there exists $N$ such that $(N,\infty)\in \cup_{n=1}^\infty (na,nb)$ and this with the fact that $f(z)\leq f(nz)$ for all $n$ and for all $z$ imply that $f(z)>w$ for all $w>N$ which contradicts the fact that $f(x_n)<w$ for all $n>n_0$.

Continuity and limit


OpenBSD pf - implementing the equivalent of an iptables DNAT

Question: Short version
Server A (OpenBSD 4.7) connects to server B (Windows). IP of server B changes. Server A should be able to connect to server B to both the old and new IP. We cannot configure multiple IPs on server B.
Long version
We have an OpenBSD server acting as an access point (ssh + authpf rules) where external clients connect and then open a connection to a service on another internal server. The internal server IP is going to change.
To give us more time to reconfigure all clients to use the new IP address, I thought we can implement the equivalent of a DNAT on the OpenBSD box. If this was a Linux box, I could use the following DNAT rule which lets me connect out from the box itself to the remote service on either the real IP (10.68.32.215) or the new IP.
$ sudo iptables -t nat -A OUTPUT -d 10.68.99.99 -j DNAT --to-dest 10.68.32.215
$ ssh-keyscan -t rsa 10.68.32.215
# 10.68.32.215 SSH-2.0-OpenSSH_4.3
10.68.32.215 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAy/GCd47aaRkBOu72v9Ysqk48Ngd6budStvdwnvMOTLiYoz6M81cTq7SskWctXx57cz6Ijnv1sbzcmDpFMUsN5vHk+6NxfrLzO0M1zh7UezY54FakgaavSdCiy15vGw/Lifntp5kMKkjgC5o42O+RUVw5iCpR8nsu/2/kR2smcVR1G3R8EunjCZWEptOCHz3Iup7FTMd4Pw/xmt+8u+5ZyHKu+uaLWQl6I12rzLiQJNyMLVdhba54FGiJDFUfcXtgM7cFli6xlrE3dnbboQE/7/cuj/N11QwTvHuU07NtrubefZE1VahWb146ph31blsW5NSiyFwL2I7rxFFoPQMbuQ==
$ ssh-keyscan -t rsa 10.68.99.99
# 10.68.99.99 SSH-2.0-OpenSSH_4.3
10.68.99.99 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAy/GCd47aaRkBOu72v9Ysqk48Ngd6budStvdwnvMOTLiYoz6M81cTq7SskWctXx57cz6Ijnv1sbzcmDpFMUsN5vHk+6NxfrLzO0M1zh7UezY54FakgaavSdCiy15vGw/Lifntp5kMKkjgC5o42O+RUVw5iCpR8nsu/2/kR2smcVR1G3R8EunjCZWEptOCHz3Iup7FTMd4Pw/xmt+8u+5ZyHKu+uaLWQl6I12rzLiQJNyMLVdhba54FGiJDFUfcXtgM7cFli6xlrE3dnbboQE/7/cuj/N11QwTvHuU07NtrubefZE1VahWb146ph31blsW5NSiyFwL2I7rxFFoPQMbuQ==

Our version of OpenBSD is 4.7, but we can upgrade if necessary.
If this DNAT is not possible we can probably do a NAT on a firewall along the way.
The closest I was able to accomplish on a test box is:
pass out on em1 inet proto icmp from any to 10.68.31.99 nat-to 10.68.31.247

Unfortunately, pfctl -s state tells me that nat-to translates the source IP, while I need to translate the destination.
$ sudo pfctl -s state
all icmp 10.68.31.247:7263 (10.68.30.199:13437) -> 10.68.31.99:8       0:0

I also found lots of mentions about rules that start with rdr and include the -> symbol to express the translation, but it looks like this syntax has been obsoleted in 4.7 and I cannot get anything similar to work. Attempts to implement a new-syntax redirect rule fail with:
$ echo match out on em1 to 10.68.31.99 rdr-to 10.68.31.247 | sudo pfctl -f -
stdin:1: rdr-to can only be used inbound

Of course, since I am trying to redirect outgoing traffic, modifying the above rule to "pass in" does not work either.
Current status
Ended up applying a NAT on a firewall between the two servers. Did the trick, though from academic interest, I am still curious if this is doable in OpenBSD.
Comment: You have to set up an alias IP on the OpenBSD box son that the box receives the traffic for this IP.
I think otherwise the IP cannot be bound to a MAC address. Thereby no PC can answer your request.
Comment: The OpenBSD box does not need to receive the traffic for this IP - I am only interested in doing the NAT for locally originated connections. In short, what we are doing is: `ssh -L1234:fake-ip:6789 openbsd-box`, should work, as well as `ssh -L1234:real-ip:6789 openbsd-box`.
Comment: Sure but you know that someone has to answer for the ARP requests. If no PC has this particular IP then there will be no routing and the request can't be rerouted be the OpenBSD box. The IP HAS to be in the network somewhere or oyu have to define a static route.
Comment: That's why I am looking for a NAT that is going to translate the fake IP to a real one. Keep in mind that what I am looking for is doable with `iptables` on Linux.
Comment: I don't know why it works with iptables. Would you ,for the sake of science, try if the rules work when you add an alias for the old ip on any interface?
Answer: I'm not totally sure if that's what you want but I use something likt this to redirect traffic to another IP.
rdr pass on $ext_if proto icmp from any to $OLD_IP -> $NEW_IP

The syntax is not tested but might work
Something similar works on FreeBSD

Edit
After a look into the OpenBSD manpages this syntax might work:
pass in on $ext_if proto icmp from any to $OLD_IP rdr-to $NEW_IP

Comment: This is what I am referring to in my question when I say "rdr rules that include the -> symbol". Unfortunately OpenBSD 4.7 does not seem to support this syntax anymore. I simply get `/etc/pf.conf:19: syntax error` with your example.
Comment: Okay I took a quick look into the OpenBSD manpages. And will edit my post.
Comment: Thanks, but it doesn't seem to be doing the trick for me. I am trying to redirect packets that originate locally on the machine. So when I am on the OpenBSD machine itself, I expect to apply the rule and then be able to ping both OLD_IP and NEW_IP. I updated my question to clarify more what I am trying.
Comment: This is what the rule should do. It should redirect the ICMP packages sent to the old IP to the new IP. It does not touch the new IP.
Comment: Well, not working:

`sudo pfctl -s rules`

`pass in on em0 proto icmp from any to 10.68.99.99 rdr-to 10.68.32.215 `

`ping -c1 10.68.32.215` - works

`ping -c1 10.68.99.99` - nothing
Comment: Migh be a dumb question but is the IP 10.68.99.99 still configured on the server thet implements the firewall?
Comment: 10.68.99.99 is an IP I made up. I edited my question to show a working iptables example with a made up IP.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3829/discussion-between-cperrin88-and-chutz)
Answer: I don't think pf can do this. pf has 4 ways to alter packets:

A packet filter rule with a route-to (and reply-to) option

This only alters the packet's route and not the actual destination

A nat rule

This only alters an outgoing packet's source address/port

A binat rule

This only alters an outgoing packet's source address/port and an incoming packet's destination address/port.
(Since rdr is stateful, I don't understand why binat exists.)

A rdr rule

This only alters an incoming packet's destination address/port

I was trying to redirect outgoing packets with destination 10.193.130.31.56862 to 10.0.0.30.56862. I was able to do this on linux with iptables:
sudo iptables -t nat -A OUTPUT -d 10.193.130.31 -p tcp --dport 56862 -j DNAT --to-destination 10.0.0.30

I tried to do the same on macOS by adding to my /etc/pf.conf:
nat pass log (all) on en6 inet proto tcp from any to 10.193.130.31 port 56862 -> 10.0.0.30 port 56862

where en6 is my external network interface.
I then added a logging interface with:
sudo ifconfig pflog0 create

Finally, I reloaded my pf rules with:
sudo pfctl -vf /etc/pf.conf

And started pf with:
sudo pfctl -e

And then my packets with tcpdump:
sudo tcpdump 'tcp port 56862' -vv -lnttti en6

I created a test connection with:
nc -v 10.193.130.31 56862

And I saw the following output in tcpdump:
00:00:00.000000 rule 1/0(match): nat out on en6: (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 64)
  10.0.0.30.56862 > 10.193.130.31.56862: Flags [SEW], cksum 0x9730 (incorrect -> 0xd1e3), seq 3809148311, win 65535, options [mss 8961,nop,wscale 9,nop,nop,TS val 2314373431 ecr 0,sackOK,eol], length 0

Which indicates that my source was changed to 10.0.0.30:56862, but not my destination.
When I ran similar tests with an rdr rule, I got no output (because I had no incoming packets):
rdr pass inet proto tcp from any to 10.193.130.31 port 56862 -> 10.0.0.30 port 56862


How can I count the number of events in a given interval?

Question: I need to know how frequency different events occur. For example how many HTTP requests have occurred in the last 15 minutes. Because there can be a large count of events (millions) this must be use a limited amount of memory.
It there any util class in Java that can do this?
How can I implement this self in Java?
Theoretical usage code can look like:
FrequencyCounter counter = new FrequencyCounter( 15, TimeUnit.Minutes );
...
counter.add();
...
int count = counter.getCount();

Edit: It must be a real time value which can changed thousand times the minute and will be query thousands times the minute. That a database or file based solution are not possible.
Comment: Do you have any other limitations? (Concurrency wise?)
Comment: If your applications output some logs and I am sure it does, why don't you have another process (that could actually be located on another server, as long as it as access to the log files) analyse those logs to extract this information? If you do not need to have this information in real time you could imagine to trigger a kind of batch job that would do the computation one time per day, or a couple of times per day when the load is not high (e.g. during the night etc)
Comment: You could have a counter that resets at midnight and enter the number of requests each minute in a db. Then all you need to count is the fraction of the minute at the start and end of the interval the rest can be calculated. This could be optimized further by storing the count every x seconds too and you can calculate the count with minutes and the smaller interval, so you only have to count x seconds.
Comment: @Allan it must be real time. Sorry that I forget to write it.
Comment: @GalAbra Yes, concurrency / thread safe is needed. But I think a synchronized should solve this. It must not be high concurrency.
Comment: You mean how many events occur in the **next** 15 minutes or occur**ed** in the last 15 minutes?
Comment: @maraca I want the events from the past and not from the future. I have fix the grammatical error in the text. Sorry for my bad English.
Answer: Here is my implementation of such a counter. The memory usage with the default precision is fewer as 100 bytes. The memory usage is independent of the event count.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A counter that counts events within the past time interval. All events that occurred before this interval will be
 * removed from the counter.
 */
public class FrequencyCounter {

    private final long          monitoringInterval;

    private final int[]         details;

    private final AtomicInteger currentCount = new AtomicInteger();

    private long                startInterval;

    private int                 total;

    /**
     * Create a new instance of the counter for the given interval.
     *
     * @param interval the time to monitor/count the events.
     * @param unit the time unit of the {@code interval} argument
     */
    FrequencyCounter( long interval, TimeUnit unit ) {
        this( interval, unit, 16 );
    }

    /**
     * Create a new instance of the counter for the given interval.
     *
     * @param interval the time to monitor/count the events.
     * @param unit the time unit of the {@code interval} argument
     * @param precision the count of time slices for the for the measurement
     */
    FrequencyCounter( long interval, TimeUnit unit, int precision ) {
        monitoringInterval = unit.toMillis( interval );
        if( monitoringInterval <= 0 ) {
            throw new IllegalArgumentException( "Interval mus be a positive value:" + interval );
        }
        details = new int[precision];
        startInterval = System.currentTimeMillis() - monitoringInterval;
    }

    /**
     * Count a single event.
     */
    public void increment() {
        checkInterval( System.currentTimeMillis() );
        currentCount.incrementAndGet();
    }

    /**
     * Get the current value of the counter.
     *
     * @return the counter value
     */
    public int getCount() {
        long currentTime = System.currentTimeMillis();
        checkInterval( currentTime );
        long diff = currentTime - startInterval - monitoringInterval;

        double partFactor = (diff * details.length / (double)monitoringInterval);
        int part = (int)(details[0] * partFactor);
        return total + currentCount.get() - part;
    }

    /**
     * Check the interval of the detail counters and move the interval if needed.
     *
     * @param time the current time
     */
    private void checkInterval( final long time ) {
        if( (time - startInterval - monitoringInterval) > monitoringInterval / details.length ) {
            synchronized( details ) {
                long detailInterval = monitoringInterval / details.length;
                while( (time - startInterval - monitoringInterval) > detailInterval ) {
                    int currentValue = currentCount.getAndSet( 0 );
                    if( (total | currentValue) == 0 ) {
                        // for the case that the counter was not used for a long time
                        startInterval = time - monitoringInterval;
                        return;
                    }
                    int size = details.length - 1;
                    total += currentValue - details[0];
                    System.arraycopy( details, 1, details, 0, size );
                    details[size] = currentValue;
                    startInterval += detailInterval;
                }
            }
        }
    }
}

Answer: The best way I can think to implement this is using another "time counting" thread.
If you're concerned about the amount of memory, you can add a threshold for the size of eventsCounter (Integer.MAX_VALUE seems like the natural choice).
Here's an example for an implementation, that is also thread-safe:
public class FrequencyCounter {

    private AtomicInteger eventsCounter = new AtomicInteger(0);
    private int timeCounter;
    private boolean active;

    public FrequencyCounter(int timeInSeconds) {
        timeCounter = timeInSeconds;
        active = true;
    }

    // Call this method whenever an interesting event occurs
    public int add() {
        if(active) {
            int current;
            do {
                current = eventsCounter.get();
            } while (eventsCounter.compareAndSet(current, current + 1));

            return current + 1;
        }
        else return -1;
    }

    // Get current number of events
    public int getCount() {
        return eventsCounter.get();
    }

    // Start the FrequencyCounter
    public void run() {
        Thread timer = new Thread(() -> {
            while(timeCounter > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                timeCounter --;
            }
            active = false;
        });
        timer.start();
    }
}

Answer: How about a scheduled executor service.
class TimedValue{
    int startValue;
    int finishedValue;
    TimedValue(int start){
         startValue = start;
    }
}

List<TimedValue> intervals = new CopyOnWriteArrayList<>();

//then when starting a measurement.
TimeValue value = new TimedValue();

//set the start value.
Callable<TimedValue> callable = ()->{
    //performs the task.

    value.setValueAtFinish(getCount());
    return value;
}

ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

ScheduledFuture<TimedValue> future = executor.schedule(
                                       callable,
                                       TimeUnit.MINUTES,
                                       15);

executor.schedule(()->itervals.add(
                        future.get(),
                        TimeUnit.MINUTES,
                        future.getDelay(TimeUnit.MINUTES
                      );

This is a bit of a complicated method.
I would probably just have a List<LoggedValues> and accumulate values in that list at a fixed rate. Then it could be inspected whenever you want to know an intervals.


PhoneGap onDeviceReady won't fire up on iPhone

Question: I've got a PhoneGap app that won't run the "deviceready" event on an iPhone but WILL run it on Android.
Any ideas why is this? or how to fix it?
(PhoneGap ver 1.0)
The code is :
<code>function onBodyLoad()
{
     if (typeof navigator.device == "undefined"){
          document.addEventListener("deviceready", onDeviceReady, false);
     } else {
         onDeviceReady();
     }
}

<body onload="onBodyLoad()">
</code>
Thanks!
Comment: OK. Found it - the PhoneGap framework didn't fire up because of a compiler thingy. the jQuery part did fire and thus the app seemed fine, but all the PhoneGap part didn't and thus I couldn't use the deviceready.
Answer: Did you just copy your www folder from one to the other? Android and iOS use their own phonegap-1.0.0.js file. Make sure you are using the correct js file for the platform.
Comment: you were right! I used the JS from android for the iPhone. That DIDN'T work :)
Comment: Wasn't obvious for me as well.
Comment: Boos thanks...u solved my problem i had wasted lots of my time but your post save my time that i could west due to this little mistake
Comment: Is it possible to load the www folder reference from the server rather than keeping it locally ,so we have the regular updates.Is so,will it be possible to get the control over the native features like camera,calender in iphone.


Day Wise Searching in select query in mysql

Question: i have a date field in my table in mysql . I want fetch record in a such a way that it gives record in the following manner from today to previous year.
id-->day-->counter
That means i want per day wise counter. In past year how many records were inserted in each day (sunday,monday,etc).
plz help
Thank You
Comment: This doesn't sound very hard.  What have you tried?
Answer: SELECT DAY(dateField) AS dateDay, COUNT(*) AS numberOfDays
  FROM dateTable
    WHERE dateField BETWEEN TIMESTAMPADD(YEAR, -1, NOW()) AND NOW()
    GROUP BY dateDay

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_day
The DAY function can be replaced with DATE to get a full date, TO_DAYS to get a day number from the year 0, WEEKDAY to get Monday - Sunday, etc.
EDIT: To show by WEEKDAY, use DAYNAME function (DAYNAME(dateField))
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_dayname
Comment: Nice one Jeff....but if i want to show result as sunday monday wise then what will i do...
Answer: Use previous year in where clause and count the occurrences grouped by dayname in each of year. And you can order the result on weekday numbers.
Exampe:
select   year( date ) as year
       , dayname( date ) as day
       , count( date ) as counter
  from table_name
 where
       date between ( curdate() - interval 1 year ) and curdate()
       -- or the following, to match all from prev year
       -- year( date ) >= year( curdate() - interval 1 year )
 group by 1, 2 -- year and dayname
 order by year
          , field( weekday( date ), 6, 0, 1, 2 ,3 ,4, 5 ) -- sun to sat


Need help showing that the intervals $[a,b]+[c,d]=[a+c,b+d]$

Question: Let $A$ and $B$ be sets. Define $$A+B=\{x+y\mid x\in A,\ y\in B\}$$
Prove: $[a,b]+[c,d]=[a+c,b+d]$. Im pretty sure that I have the forward containment but I need help showing that $$[a+c,b+d]\subset[a,b]+[c,d].$$ Any help would be greatly appreciated.
Comment: Are $[a,b]$ supposed to be $\{x| a \le x \le b\}$?
Comment: @fleablood yeah they are just arbitrary intervals in $\mathbb{R}$.
Answer: If $x \in [a+c,b+d]$ then $a+c \le x \le b+d$.
$a \le x-c \le b+(d-c)$
Let $k = \min (x-c, b)$ so $a \le x-c\le k$ so $a \le k$ and $k \le b$ so $k\in [a,b]$.
Let $j = x-k$.  If $k = x-c$ then $j = c \in [c,d]$.  If $k = b$ then $j=x-b$ and $a+c \le x \le b+d$ so $a+c-b \le x-b=j < d$ ane $k \le x-c$ so $j= x-k \ge x-(x-c)= c$ so $j \in [c,d]$.
As $x = k+ j$ and $k \in [a,b]$ and $j\in [c,d]$ so $x \in [a,b] +[c,d]$.


Multihomed VM workgroup attached to domain clients, resolution issues

Question: hopefully someone here can help me out with this nightmare:
I have a corporate network with ADDS, let's make believe this is a 192.168.10.x network.
I have a server that runs 3 VMs (one APP server, one SQL server and one web server) that are not connected to the corporate domain, but all the clients for these services are on the network domain.  Each VM has 3 NICs (one required admin network between the VMs 192.168.100.x, one network to manage an ISILON storage solution 192.168.101.x, and the network that connects to the corporate domain 192.168.10.x).
I currently have no issues getting to these machines using their 10.x IP addresses.  I can also get to them "sometimes" using their hostname.  The issue is that the hostname I use will round-robin between the 3 different IP addresses assigned to each VM (100.x, 101.x and 10.x).  I've gone in to the IPV4 settings for each NIC on the 100 networks and turned off the DNS option and the NetBios over TCPIP, but this problem still persists.
My question is:  Is there a way to ensure that everytime a hostname like 'vmserver1' is used, it is correctly resolved to 192.168.10.x instead of 100.x or 101.x?  As you can guess, if it resolves to 100.x or 101.x, I get no reply on the corporate domain.
My thanks for your help!!
Answer: DNS registration with multiple NIC:

To disable DNS dynamic update for all names on the computer, clear the
  Register this connection's addresses in DNS and the Use this
  connection's DNS suffix in DNS registration check boxes on the DNS tab
  for all connections in Network Connections.

From: https://support.microsoft.com/en-us/kb/305553#6
For multiple IP per NIC :
Please use the command; netsh int ipv4 add address "Local Area Network" skipassource=true

After you install this hotfix, you can assign IP addresses that will
  not be registered for outgoing traffic on the DNS servers by using a
  new flag of the netsh command. This new flag is the skipassource flag.
Note You can create IP version 4 (IPv4) addresses and IP version 6
  (IPv6) addresses by using the netsh command together with the new
  skipassource flag.
For example, the following command creates an IPv4 address that is not
  registered for outgoing traffic on the DNS servers:
Netsh int ipv4 add address
  skipassource=true

Please check https://support.microsoft.com/en-us/kb/2386184 & https://support.microsoft.com/en-us/kb/2554859
If both method fail please do static A entry in your DNS.
Comment: I mentioned above that I had already done the "Clear the register this connection's address in DNS", and the multiple IP per NIC doesn't apply to my situation.  I'm guessing the problem here is that my machines aren't on the domain, and it's the domain's DNS server that's causing the resolution issues.  Since I don't have admin rights to the domain, I'll have to go a step higher I guess.  Thanks anyways for the effort!


windows 2008 r2 internet sharing via network bridge

Question: I have 2 PCs running windows, namely A and B.
A has 2 network adapters A-NIC1 and A-NIC2
B has 1 network adapter B-NIC1.
A-NIC1 is connected to the company network and it can access the internet, The IP address is something like "192.168.1.XXX".
I want to connect B-NIC1 to A-NIC2 using a straight RJ-45 lan cable and do some network configuration in windows 2008 R2 running on the PC A. I hope the PC B can access the internet via this lan cable connection to the PC A.
Is it possible to achieve my goal in this way?
If yes, how to setup the windows 2008 network? I prefer using network bridge instead of NAT?
If no, what are other method (without adding routers or other equipments)?
Comment: Can you assign PC B an IP address inside the 192.168.1.xxx LAN? If so, just bridge the two network interfaces on PC A.
Answer: Yes, you select both A-NIC1 and A-NIC2 right click and select bridge networks. you then just conncet A-NIC2 to your B-NIC1.
Mind though that normally you should use a cross over cable instead of a straight one. It might work if your network cards have autosensing.
Comment: After selecting bridge network include both A-NIC1 and A-NIC2, the "network bridge" has no internet access. It shows "unidentified network". When connect B-NIC1 to A-NIC2, there is no internet connection.
Comment: Well there is a utp cable in A-NIC1 right that can connect to internet?
Comment: yes, A-NIC1 is connected to the internet but when I bridge A-NIC1 and A-NIC2 together, the A-NIC1 lost internet connection.
Comment: Did you configure the IP's?
Comment: the PC A IP is assigned by DHCP (192.168.1.6), the PC B IP is assigned manually with a non-conflicting IP (192.168.1.10) on the network. The router is able to assign IP address from 192.168.1.2 to 192.168.1.100.
Comment: so if you have Ip's and a gateway from your DHCP server I don't see a reason why you would not have internet connectivity?
Answer: leave A-NIC1 IP assigned by DHCP and assign B-NIC1 IP manually to something outside the router's range for DHCP, then bridge A-NIC1 and A-NIC2. if the range is 192.168.0.2-100, then PC B should be 192.168.0.101-254 assuming the subnetmask is 255.255.255.0 (network is 192.168.1.0/24).


Additive forecast errors across uneven time steps?

Question: Assume that I have some stochastic dynamical model of the form:
$$x_{t+1}=M(x_t)+\epsilon$$
where $M:x\rightarrow x$ is a deterministic function, the subscript $t$ denotes a certain time step, and $\epsilon$ is a realization of some Gaussian noise $\mathcal{N(\mu=0, \sigma)}$ with zero mean and some standard deviation. If I propagate this model in equal time steps $\Delta t$, then I am adding a steady amount of random noise to the forecast over time. That's great.
Now, let's complicate matters. Assume that instead of propagating in steady time steps, I am using some scheme which adjusts the time steps individually. As a consequence, the time between two steps is no longer uniform. To ensure that I am still adding a constant amount of noise over time, I suspect that I would have to adjust the standard deviation $\sigma$ to reflect the length of the individual time step. Is there a general rule to scale additive Gaussian noise for such uneven time steps?
I suspect this might be a relatively common question, but my search on this site and beyond has come up dry. Perhaps I have been looking for the wrong terms. I would appreciate any answers or references to other questions which answered this conundrum.
Answer: The state equation may be seen as the simplest possible discretisation (namely the Euler-Maryuama scheme) of the stochastic differential equation governing "nature". Similar to simulations of Brownian motion, the variance (or covariance matrix) of $\varepsilon$ should scale with $\Delta t$.
Notably, this has the nice consequence that the variance of a sum of errors for
many smaller time steps is the same as the variance of the error for the original time step.


AlamoFire does not respect timeout interval

Question: class APIClient {
    var user = User()
    let alamoFireManager : Alamofire.Manager?
    let center = NSNotificationCenter.defaultCenter()

    init(){
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 4 // seconds
        configuration.timeoutIntervalForResource = 4
        self.alamoFireManager = Alamofire.Manager(configuration: configuration)
    }

    func test(){
        //This does not respect the 4 second time out. Why?
        self.alamoFireManager!.request(.POST, CONSTANTS.APIEndpoint+"/test", parameters: parameters).responseJSON {
                        (req, res, json, error)  in
                        if let json = self.handleAPIResponse(req, res: res, json_data: json, error: error){
                        }
                    }
    }

Comment: Set a breakpoint at the `test` function and print the `self.alamoFireManager!.session.configuration.timeoutIntervalForRequest`
Comment: Are you assuming that the first time you call the method test(), it should have a 4 second delay?
Comment: The delay is for the http request not for the complete test method. For example the timeout dose not apply to your handleAPIResponse call.
Comment: What is the use of 'center' object you created?
Answer: Are you sure that the 4 seconds timeout is not enforced? I have created an experiment:
    let center = NSNotificationCenter.defaultCenter()
    var alamoFireManager : Alamofire.Manager?

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.Manager(configuration: configuration)

    self.alamoFireManager!.request(.POST, "http://oznet.go.ro/iDorMobile/ConfigServer/api.php/timeout/2", parameters: nil).responseJSON {
        (req, res, json, error)  in
        println("First json \(json)")
        println("First error \(error)")
    }

    self.alamoFireManager!.request(.POST, "http://oznet.go.ro/iDorMobile/ConfigServer/api.php/timeout/6", parameters: nil).responseJSON {
        (req, res, json, error)  in
        println("Second \(json)")
        println("Second \(error)")
    }

and the console output i got:
First json Optional({
    name = timeoutTest;
    value = 2;
})
First error nil
Second nil
Second Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7f91dc8223e0 {NSErrorFailingURLKey=http://oznet.go.ro/iDorMobile/ConfigServer/api.php/timeout/6, NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=http://oznet.go.ro/iDorMobile/ConfigServer/api.php/timeout/6})

The URLs from my example are currently down, i will try to put them back online. You can use the urls from the example to test. By setting a different number at the end you can modify the timeout (in seconds).
I have used the cocoapods last version of Alamofire.
Comment: Swift 3 / April 2017: should be `Alamofire.SessionManager`, and `URLSessionConfiguration.default`
Answer: You need create a global variable for the request manager:
var alamoFireManager = Alamofire.Manager.sharedInstance

And after configure the custom parameters:
 let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.Manager(configuration: configuration)

Answer: Here's the Swift 3.0 / Alamofire 4.0 code to get an alamofireManager that has a 5 second timeout:
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForResource = 5 // seconds

    let alamofireManager = Alamofire.SessionManager(configuration: configuration)

Comment: In case of Alamofire 4.0 Alamofire.Manager has been changed to Alamofire.SessionManager as indicated by @Jamie
Answer: I guess this one works for you, note that you have to declare instance of Alamofire.Manager outside the function, please see below code
//Declare it out side the function
var alamoFireManager : Alamofire.Manager!

func callUrl() {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForResource = 10800 // seconds
    configuration.timeoutIntervalForRequest = 10800 // seconds

    alamoFireManager = Alamofire.Manager(configuration: configuration)

    alamoFireManager.request(.POST, url, parameters: dir as? [String : AnyObject], encoding: .JSON, headers: [ "Content-Type": "application/json"])
        .responseJSON { response in
    }
}

hope this helps you
Comment: i can confirm that this will not work if the instance of alamofire manager is declared inside the function.
Answer:  init(){
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForResource = 4
    configuration.timeoutIntervalForRequest = 4
    self.alamoFireManager = Alamofire.Manager(configuration: configuration)
    self.alamoFireManager!.request(.POST, CONSTANTS.APIEndpoint+"/test", parameters: parameters).responseJSON {
                    (req, res, json, error)  in
                    if let json = self.handleAPIResponse(req, res: res, json_data: json, error: error){
                    }
                }
}

Use self.alamoFireManager!.request in the same init function , timeout delay is only for the request not for the whole function. may be it can help.
Answer: I got NSURLErrorDomain when I used above method .
This is my code (swift 3.2/Alamofire 4.4)
    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 4

    manager.request(.POST, CONSTANTS.APIEndpoint+"/test", parameters: parameters).responseJSON {
                    (req, res, json, error)  in
                    if let json = self.handleAPIResponse(req, res: res, json_data: json, error: error){
                    }


If $X_i$ are i.i.d. and $Y_i$ are i.i.d, are $Z_i$ = $X_iY_i$ i.i.d?

Question: Clearly $X_iY_i$ have the same distribution, but are they independent, given that there can be a dependent relationship between the $X_i$ and the $Y_i$?
Answer: The $Z_i$ are not necessarily independent. For example, suppose $Y_i = X_{i-1}$. Then $Z_i = X_i X_{i-1}$ and $Z_{i+1} = X_{i+1} X_i$ both depend on $X_i$
Comment: I don't think this by itself answers the question. Consider sequence of constant functions. They are independent and your argument fails. The answer to the question should be of the lines "not necesserally, here is a counter example" because it clearly can be true, but it is not always true.


Jordan Normal Form Question

Question: I'm trying to properly get to know the Jordan normal form Theorem, and am confused as to why this proposition holds. I have read that if A is a matrix in Jordan normal form and $T:V\rightarrow V$ then $$\dim\ker(T-\lambda I)^r-\dim\ker(T-\lambda I)^{r-1}$$ is the number of Jordan blocks $J_m(\lambda)$ of A with $m\geq r$.
I am not sure why this holds, can anyone explain this for me?
Comment: I suppose you meant $\;A\;$ is the JCF of $\;T\;$ ...right?
Comment: Yes, that's correct!
Answer: Suppose $J$ is a Jordan block of size $m$, then $\dim \ker(J-\lambda I)^r = \min (m,r)$.
Hence, if we set $r=1,2,...$, we get the dimensions
$1,2,...,m-1,m,m,...$.
If we look at $\min(m,r-1)$ we get the numbers $0,1,...,m-2,m-1,m,...$
Hence $\min (m,r) - \min (m,r-1) $ gives the numbers $1,1,...,1,1,0,...$ where
the transition to $0$ occurs at $r=m+1$.
Hence $\min (m,r) - \min (m,r-1) =1$ iff $r \le m$.
Summing over the blocks corresponding to $\lambda$ gives the desired result.

Jordan Normal Form Question


Hibernate JPA Parent-Child mapping

Question: I have a parent table i.e. audit_log(parent) which contains a single column id. For a given id in audit_log, I have a list of vendor ID's. I am storing them in separate table audit_log_vendorid(child table). I want the child table to get the id from the parent table as one of the columns(parent_id). Here's the table schema.
audit_log
+-------+------------+------+-----+---------+-------+
| Field | Type       | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id    | bigint(19) | NO   | PRI | NULL    |       |
+-------+------------+------+-----+---------+-------+

audit_log_vendorid
+-----------+------------+------+-----+---------+----------------+
| Field     | Type       | Null | Key | Default | Extra          |
+-----------+------------+------+-----+---------+----------------+
| id        | bigint(19) | NO   | PRI | NULL    | auto_increment |
| vendor_id | bigint(19) | NO   |     | NULL    |                |
| parent_id | bigint(19) | NO   |     | NULL    |                |
+-----------+------------+------+-----+---------+----------------+

I'have defined my hibernate classes as follows
@Entity
@Table(name="audit_log")
public class AuditLog  {

private List<AuditVendorPair> vendorIDs;

public AuditLog(List<AuditVendorPair> vendorIds) throws Exception {
    this.vendorIDs = vendorIDs;
}

@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name = "audit_log_vendorid",
   joinColumns = { @JoinColumn(name = "parent_id", referencedColumnName="id") })
public List<AuditVendorPair> getVendors() {
    return vendorIDs;
}

@Id @Column(name="ID")
public Long getId() {
    return super.getId();
}

public void setHostServices(List<AuditVendorPair> vendorIDs){
    this.vendorIDs = vendorIDs;
}

}

My hibernate mapping class for audit_log_vendorid is below. I pass in a vendor id and expect the other two fields to be populated by hibernate. The parent_id field I want from "id" field in audit_log. It's initialized as null as of now causing mysql constraint exception.
@Entity
@Table(name="audit_log_vendorid")
public class AuditVendorPair {

private Long id;
private Long parent_id;
private Long vendor_id;
public AuditVendorPair(Long vendor_id){
    this.vendor_id = vendor_id;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
public Long getId(){
    return id;
}

public void setId(Long id){
    this.id = id;
}

@Column(name="vendor_id")
public Long getVendorID() {
    return vendor_id;
}

public void setVendorID(Long vendor_id){
    this.vendor_id = vendor_id;
}

@Column(name="parent_id")
public Long getParentId() {
    return parent_id;
}

public void setParentId(Long parentID){
    this.parent_id = parentID;
}
}

I am curious to know if my annotations are correct. I basically want the id from the audit_log table to be populated in the parent_id field in audit_log_vendorid table by hibernate.
Answer: No, they're not correct. audit_log_vendorid is not a join table. A join table is a table that is not mapped to an entity, and which contains IDs of two associated entities, mapped to other tables.
You also shouldn't have a parent_id field in the AuditVendorPair. Not only because that doesn't respect the Java naming conventions, but also because it should be replaced by a reference to AuditLog, mapped with ManyToOne.
So, in short, you should have a bidirectional OneToMany association, mapped as explained in the documentation.
Comment: Yes audit_log_vendorid is not a join table. What's the reason of referring to AuditLog, mapped with ManyToOne? I thought unidirectional oneToMany would work. Using the foreign key, are we indicating to hibernate that it needs to fetch value for parent_id from the referenced column? Would things change if my primary key in audit_log table is more than the ID ?
Comment: You can use a unidirectional OneToMany, but then the parent_id column in audit_log_vendorid would be handled by the OneToMany association (you would need `@JoinColumn("parent_id")`), and should not be mapped a second time in the AuditVendorPair entity. If you need to access the parent from the AuditVendorPair entity, then it should be bidirectional.
Answer: I think you are overlooking a key concept in JPA, which is entities are objects, so you would never have an entity referring to it's parent using the ID directly, you would refer to the object (JPA will use the id when querying the DB)
@Entity
@Table(name="audit_log")
public class AuditLog  {

    @OneToMany(cascade= CascadeType.ALL, mappedBy = "auditLog")
    private Collection<AuditVendorPair> vendorIDs;

    @Id @Column(name="id")
    private Long id;

    public AuditLog() {
    }

    public Collection<AuditVendorPair> getVendors() {
        if (vendorIDs == null) {
            vendorIDs = new ArrayList<>();
        }
        return vendorIDs;
    }

    public long getId() {
        return id;
    }
}

and
@Entity
@Table(name = "audit_log_vendorid")
public class AuditVendorPair {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @JoinColumn(nullable = false, name = "parent_id")
    @ManyToOne(optional = false)
    private AuditLog auditLog;

    @Column(name = "vendor_id")
    private Long vendorId;

    public AuditVendorPair() {
    }

    public long getVendorId() {
        return vendorId;
    }

    public void setVendorId(long vendorId) {
        this.vendorId = vendorId;
    }

    public AuditLog getAuditLog() {
        return auditLog;
    }

    public void setAuditLog(AuditLog auditLog) {
        this.auditLog = auditLog;
    }
}

AuditVendorPair is referring to AuditLog using the Entity, and since this is an entity relation, you have to use @JoinColumn to specify the name.
Some best practices for JPA/Hibernate

No args constructor is required by the spec.
Don't have a setter for the primary key, unless you generate it in code.
You can't use primitives for fields. However if the database enforces NOT NULL, you should use primitive long in getters and setters, so your IDE can warn you about NPE, instead of waiting for your tests to fail.
Use Collection not List, as list implies order.
Done use underscores in field names, but use them when specifying the name of the column.
Notice the null check and collection creation in getVendors(), this is to avoid NPE when the object is first created. This means that you can use the same logic for adding a AuditVendorPair regardless if the AuditLog has just been created, or if it is loaded from the DB. It also means I don't create a setVendors() unless I need to replace the entire list, which is rarely the case, and when it is, you typically need to explicitly delete every entity in the list.
Comment: Thanks for the information. I get the following when I try and persist the AuditLog:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'audit_id' cannot be null
Do I need to add foreign key reference from child parent_id to parent id column?
Answer: It sounds like you should read a little more about the principles behind JPA.
Here is a 'raw' JPA example of what the code will look like, if you use Spring-data and autowire @PersistanceUnit you don't need to manager the entityManager youself.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU-Name");
EntityManager em = emf.createEntityManager();

try {
    long primaryKey = 1L; // comes from somewhere else
    long vendorId = 1L;   // comes from somewhere
    AuditLog log = em.find(AuditLog.class, primaryKey); // loaded from DB

    AuditVendorPair pair = new AuditVendorPair();
    pair.setAuditLog(log);
    pair.setVendorId(vendorId);
    em.getTransaction().begin();
    em.persist(pair);
    em.getTransaction().commit();
} finally {
    em.close();
}

You have to connect the entities in code, and any existing entities have to be loaded from the database. If you are storing a new AuditVendorPair, you first have to load the AuditLog object, and then set it on the newly created AuditVendorPair. Typically Vendor will also be an Entity, so it will also have to be looked up.
Note: The example above does not maintain the two-way relationship between AuditLog and AuditVendorPair, since AuditVendorPair is not added to the collections of vendors on AuditLog. Since the column defining the relation is on AuditVendorPair (which is stored) this is not an issue, because next time you load the AuditLog instance from the DB the AuditVendorPair will be part of the vendor collection. However if you use the AuditLog after the persistence context is closed, you may want to maintain the two-way relation.
Note: the example above assumes that you get requests with primary keys. In general you should never expose primary keys in any front-end, in our systems we generate a unique field (UUID) for every entity that is exposed in a UI.

Hibernate JPA Parent-Child mapping


Power analysis for binomial test via simulation

Question: Suppose a gene is mutated in 30% of the samples.
I want plot the number of samples required to see 30% of them mutated at various level of power.
I want to do this through a simulation so I generated different sample sizes and for each sample size I generated a 1000 trials of simulated number of mutated samples based on p.
p = 0.3
# from sample size 1:100, I generated 1000 binomial random variable
for (n in 1:100) {
  k = rbinom(1000, n, p)
}

How do I construct the power analysis after I have generated some simulated data?
Comment: Did you want to run some test? Eg, to show that the observed proportion is <.5? Or did you want to get a 95% CI of a given width & that would include .3 95% of the time?
Comment: i think my null p0=.01 which a sample will be mutated in a gene in a background model, and my p1=.3
Comment: What language is that? Is it supposed to be `R`?
Comment: Yes. it's R. "The first step is to identify a threshold c for the number of successes such that the probability to get at least c successes in a sample of size n is very low under the null hypothesis " I'm not sure how to determine my threshold c for my case.
Comment: I want to see how many samples would I need to see 30% samples mutated at 80% power.
Comment: What does that mean? Do you want to run a binomial test against a null of .5?
Comment: i think my problem is quite similar to this [question](http://stats.stackexchange.com/questions/38439/power-analysis-for-binomial-data-when-the-null-hypothesis-is-that-p-0) except my P0 is .01, so the minimum number of success to reject null should be some number greater than 1 i think.
Answer: You may be able to figure out everything you need to know from my answer here: Simulation of logistic regression power analysis - designed experiments, which is quite comprehensive.
The basic procedure for simulating a power analysis is to:

Simulate data according to your preferred scenario (the alternative hypothesis).
Run the test you intend to use.
Do this many times, and see what percentage of the time your results are significant.
If you want to solve for the required $N$ to achieve a given power, do the above with different $N$s and find the one that yields the power you want.

In your case, you need to apply the binomial test with the null proportion set to $.01$.
Here's an example in R (note that your code had errors):
set.seed(8063)
p = 0.3
# from sample size 1:100, I generated 1000 binomial random variable
k = matrix(NA, nrow=1000, ncol=100)
for(n in 1:100){
  k[,n] = rbinom(1000, n, p)
}

p.mat  = matrix(NA, nrow=1000, ncol=100)
for(i in 1:1000){
  for(n in 1:100){
    p.mat[i,n] = binom.test(x=k[i,n], n=n, p=0.01)$p.value
  }
}
power = c()
power = apply(p.mat, 2, FUN=function(x){ mean(x<.05) })
min(which(power>.8))
# [1] 5
power[4]
# [1] 0.763
power[5]
# [1] 0.82

Brute force search:
tl = NULL
tl[paste("n", 1:10, sep="")] = list(NULL)
pl = tl
for(n in 1:10){
  tl[[n]] = 0:n
  for(h in 0:n){
    pl[[n]][h+1] = binom.test(tl[[n]][h+1], n, 0.01, "g")$p.value
  }
}
msig = lapply(pl, function(x){ min(which(x<.05))-1 })
pow = c()
for(n in 1:10){
  pow[n] = 1-sum(dbinom(0:(msig[[n]]-1), n, .3))
}
names(pow) = paste("n", 1:10, sep=" = ")
min(which(pow>.8))
# [1] 5
pow[4:5]
#   n = 4   n = 5
# 0.75990 0.83193

Comment: Wouldnt it be binom.test(x=k[i,n], n=n, p=0.01, alternative="greater") in my case?
Comment: @kylelyk02, you could do that if you wanted.
Comment: i noticed that the power flucuate when sample is low, would it be safer to say power > .8 at power[9] instead of           power[5]?
Comment: @kylelyk02, I don't follow that comment, but it occurs to me that your situation is so simple it can easily be found analytically by brute force search. I updated by answer. Note that the analytical results agree very closely w/ the original simulation.
Comment: here's what i meant by [power fluctuate](http://imgur.com/1GEiwua). As you can see there are occasional dips in the power as sample size increases.
Comment: @kylelyk02, did you get that from expanding on the simulation? Notice that the analytical solution found by brute force search also yields n=5 as where you get 80% power for your scenario.
Comment: yes i generated that from the simulation and plotted the power at each sample size.
Comment: @kylelyk02, it could be anything. It might be due to the discontinuous nature of counts, or something in the code, or would be smoothed out by more iterations. But at any rate, you can get your answer from the search of the analytical solution.
Comment: Thank you very much for your thorough answer. I learnt a  lot.
Comment: @gung-ReinstateMonica How do I run this test when there is uncertainty about `p`.
In a binomial scenario, `p = number of successes/number of trials`. What if the number of trials(and number of  successes) keep increasing? How do we incorporate those uncertainties into the simulation
Comment: @dpk, when you simulate, you decide what `p` you are interested in up front. It doesn't change, because it's the value that you are theoretically interested in, not an empirical value.


Recreate FRM files ( structure files )

Question: I was moving files around and for some reason all frm files are now empty, how can I recreate them ? most of the tables are myisam but a few are innodb.
Comment: Do you have a backup?
Comment: Even if you only have the table definitions, you could re-create them
Answer: MyISAM tables are gone, InnoDB - you can recover from the dictionary
Comment: how can they be gone if all data is still there ?
Comment: We are talking about table structure, ain't we?
Comment: sure, but is it really this faulty, I mean, if you lose a 10k file all your data is gone
Comment: I saw some research paper on recovery frm files from a raw disk image. It's based on signatures lookup. Authors claim to implement it in a tool , but I never tested it. http://www.jofcis.com/publishedpapers/2015_11_15_5415_5423.pdf
Comment: And yes, MyISAM is fragile. All important data should be in innodb

Recreate FRM files ( structure files )


Expected value of X given X+Y=s?

Question: Question:
Given $X\sim N(\mu_X, \sigma_X^2)$ and $Y\sim N(\mu_Y, \sigma_Y^2)$ are independent, and you know $X+Y=s$. What is the expected value of $X$?
I encountered this during an interview. My thoughts were to use conditional expectation $E(X|Z=s)$ where $Z\sim N(\mu_X+\mu_Y, \sigma_X^2+\sigma_Y^2)$. However, it involves a lot of calculations, which I don't think would be an interview question. Could anyone suggest?
Comment: (1) Find the joint distribution of $(X, X+Y).$ (2) Use your understanding of univariate ordinary least square regression.
Comment: I took an approach similar to the one suggested by @whuber in my answer where I replaced (2) with your understanding/knowledge of a property, the conditional expectation, of bivariate normal distributions. Arguably, for your question this is equivalent to knowing how to express the so-called population regression function  in the simple linear regression model (i.e., the conditional expectation of the dependent variable $X$ given the intercept and regressor $\left(X+Y\right)$) in terms of $\mathrm{Cov}(X,X+Y)$, $\mathbb E(X)$, $\mathbb E(X+Y)$, and $\mathbb V(X+Y)$.
Comment: related: https://stats.stackexchange.com/questions/9071/intuitive-explanation-of-contribution-to-sum-of-two-normally-distributed-random
Answer: Since $X$ and $Y$ are both univariate normal and independent, we know that all linear combinations of $X$ and $X+Y$ are univariate normal. Thus, $\left(X,X+Y\right)^\top$ is bivariate normal and we have
$$
X+Y \sim \mathcal N\left(\mu_X+\mu_Y, \sigma_X^2+\sigma_Y^2\right), \\
\mathrm{Cov}\left(X,X+Y\right)=\mathrm{Cov}\left(X,X\right)+\mathrm{Cov}\left(X,Y\right)=\sigma_X^2, \\
\begin{pmatrix}
X\\
X+Y\\
\end{pmatrix} \sim \mathcal N\left(\begin{pmatrix}
                             \mu_X\\
                             \mu_X+\mu_Y
                             \end{pmatrix},
                        \begin{pmatrix}
                        \sigma_X^2 & \sigma_X^2\\
                        \sigma_X^2 & \sigma_X^2+\sigma_Y^2
                        \end{pmatrix}\right).
$$
The well-known formula for the conditional expectation in the bivariate normal case then yields
$$
\mathbb E\left(X|X+Y=s\right) = \mu_X+\frac{\sigma_X^2}{\sigma_X^2+\sigma_Y^2}\left(s-\left(\mu_X+\mu_Y\right)\right).
$$

Expected value of X given X+Y=s?


How can I use a for loop for an Assembly MIPS instruction?

Question: So I have been busy with assembly lately, and I am stuck with using a for loop. I have searched through the internet, but I don't understand any of it. I have to loop SLL  $1,$1,4 # sll operation for X amount of times. How can I do this?
#generated assembly code for SIMPL
@include "Mips.wasm"
.data   MyRegisters:    REGISTERS
0:  WORD    zero    0
1:  WORD    temp    0
2:  WORD     0
3:  WORD     0
4:  WORD     0
5:  WORD     0
6:  WORD     0
7:  WORD     0
8:  WORD     0
9:  WORD     0
10: WORD     0
29: WORD    sp      0
31: WORD    ra
.data   MyMemory:   DATAMEM
50: WORD stack  # start of stack
0:  WORD    a       0
1:  WORD    b       0
2:  WORD    result  0
.code   MyCode: MIPS,MyMemory
    J       INIT
L1: # main
    LUI     $1     , 1          # storing numeric into reg
    ORI     $1     , $1     , 0
    SW      $1     , a      , $0        # assignment of var
    # expr;
    LUI     $1     , 0          # storing numeric into reg
    ORI     $1     , $1     , 1000
    SW      $1     , b      , $0        # assignment of var
    # expr;
    LW      $1     , b      , $0        # storing var into reg
    LW      $2     , b      , $0        # storing var into reg
    SLL     $1     , $1     , 4         # sll operation
    SW      $1     , result , $0        # assignment of var
    # expr;
    LUI     $1     , 0          # storing numeric into reg
    ORI     $1     , $1     , 1
    #return int value   # stack ret value
    JR      $31     # return
INIT:   # Start of our program
    J       L1      # jump to the main code
END:

Comment: I assume you know conditional branches? Write some pseudocode or draw a flowchart.
Comment: Oh, it sounded like I have some assembly knowledge. I actually am a beginner. I just don't know how to implement the code for it.
Comment: You can see an [example here](http://stackoverflow.com/a/13655852/547981) (see _iteration type 2_).
Answer: There are no loops in assembler, that's a C (or similar language) concept.
Instead, there are conditional branch instructions used to jump based on a test.
 li    $t0, 10
 li    $t1, 0
 loop:
 addi  $t1, $t1, 1
 bne   $t1, $t0, loop

This would roughly correspond to a C "for" of:
for( int n = 0; n < 10; ++n ) {}

Where other code MIPS code doing actual work (that which would appear in the brackets in C) would be situated between the loop: label and the addi instruction.
Comment: `addi  $t1, $t1, 1` <-- shouldn't that be `addi  $t1, $t1, -1` ?
Comment: $t1 starts at zero, and increments until 10, so it should be addition not subtraction. If it were -1 instead, the loop would run until the integer wraps around, iterating billions of times on a 32 bit device. If you're thinking in terms of the link sample above, that example starts the counter at 3, and loops from there TO zero, non inclusive.


CSS menu aligns to left but when floating to right, the order of menu items are reversed

Question: I know others have asked this question and I'm not able to wrap my head around those solutions due to the complexity of the CSS being used and I have submenus within. This was made by an online menu CSS generator. This is the page that I'm building:
http://sandboxisle.com/home-page-main/
#menu {
    background: #00338D;
    color: #FFF;
    height: 45px;
    padding-left: 18px;
    border-radius: 10px;
}
#menu ul, #menu li {
    margin: 0 auto;
    padding: 0;
    list-style: none;
}
#menu ul {
    width: 100%;
}
#menu li {
    float: left;
    display: inline;
    position: relative;
}
#menu a {
    display: block;
    line-height: 45px;
    padding: 0 14px;
    text-decoration: none;
    color: #EBB700;
    font-size: 16px;
}
#menu a.dropdown-arrow:after {
    content: "\25BE";
    margin-left: 5px;
}
#menu li a:hover {
    color: #FFFFFF;
    background: #00338D;
}
#menu input {
    display: none;
    margin: 0;
    padding: 0;
    height: 45px;
    width: 100%;
    opacity: 0;
    cursor: pointer
}
#menu label {
    display: none;
    line-height: 45px;
    text-align: center;
    position: absolute;
    left: 35px
}
#menu label:before {
    font-size: 1.6em;
    content: "\2261";
    margin-left: 20px;
}
#menu ul.sub-menus{
    height: auto;
    overflow: hidden;
    width: 250px;
    background: #766A62;
    position: absolute;
    z-index: 99;
    display: none;
}
#menu ul.sub-menus li {
    display: block;
    width: 100%;
}
#menu ul.sub-menus a {
    color: #EBB700;
    font-size: 16px;
}
#menu li:hover ul.sub-menus {
    display: block
}
#menu ul.sub-menus a:hover{
    background: #766A62;
    color: #ffffff;
}
@media screen and (max-width: 800px){
    #menu {position:relative}
    #menu ul {background:#766A62;position:absolute;top:100%;right:0;left:0;z-index:3;height:auto;display:none}
    #menu ul.sub-menus {width:100%;position:static;}
    #menu ul.sub-menus a {padding-left:30px;}
    #menu li {display:block;float:none;width:auto;}
    #menu input, #menu label {position:absolute;top:0;left:0;display:block}
    #menu input {z-index:4}
    #menu input:checked + label {color:white}
    #menu input:checked + label:before {content:"\00d7"}
    #menu input:checked ~ ul {display:block}
}

Here's my HTML

  <input type='checkbox' id='responsive-menu' onclick='updatemenu()'>

Calendar

News

For Members

Orientation

Leadership Building

Newsletters

Resource

Service Documents

District 50 Clubs Directory

Awards & Contests

D50 Resource

Club Resource

LCIF Resource

Answer: Please check the code below:

#menu {
  background: #00338d;
  color: #fff;
  height: 45px;
  padding-left: 18px;
  border-radius: 10px;
}

#menu ul {
  margin: 0;
  padding: 0;
}
#menu li {
  padding: 0;
  list-style: none;
}

#menu .navbar {
  display: flex;
  justify-content: end;
  width: 1170px;
  margin: 0 auto;
}
#menu li {
  float: left;
  display: inline;
  position: relative;
}
#menu a {
  display: block;
  line-height: 45px;
  padding: 0 14px;
  text-decoration: none;
  color: #ebb700;
  font-size: 16px;
}
#menu a.dropdown-arrow:after {
  content: "\25BE";
  margin-left: 5px;
}
#menu li a:hover {
  color: #ffffff;
  background: #00338d;
}
#menu input {
  display: none;
  margin: 0;
  padding: 0;
  height: 45px;
  width: 100%;
  opacity: 0;
  cursor: pointer;
}
#menu label {
  display: none;
  line-height: 45px;
  text-align: center;
  position: absolute;
  left: 35px;
}
#menu label:before {
  font-size: 1.6em;
  content: "\2261";
  margin-left: 20px;
}
#menu ul.sub-menus {
  height: auto;
  overflow: hidden;
  width: 250px;
  background: #766a62;
  position: absolute;
  z-index: 99;
  display: none;
}
#menu ul.sub-menus li {
  display: block;
  width: 100%;
}
#menu ul.sub-menus a {
  color: #ebb700;
  font-size: 16px;
}
#menu li:hover ul.sub-menus {
  display: block;
}
#menu ul.sub-menus a:hover {
  background: #766a62;
  color: #ffffff;
}
@media screen and (max-width: 800px) {
  #menu {
    position: relative;
  }
  #menu ul {
    background: #766a62;
    position: absolute;
    top: 100%;
    right: 0;
    left: 0;
    z-index: 3;
    height: auto;
    display: none;
  }
  #menu ul.sub-menus {
    width: 100%;
    position: static;
  }
  #menu ul.sub-menus a {
    padding-left: 30px;
  }
  #menu li {
    display: block;
    float: none;
    width: auto;
  }
  #menu input,
  #menu label {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
  }
  #menu input {
    z-index: 4;
  }
  #menu input:checked + label {
    color: white;
  }
  #menu input:checked + label:before {
    content: "\00d7";
  }
  #menu input:checked ~ ul {
    display: block;
  }
}

      <input
        type="checkbox"
        id="responsive-menu"
        onclick="updatemenu()"
      />

Calendar

News

          For Members

Orientation

Leadership Building

Newsletters

          Resource

Service Documents

              District 50 Clubs Directory

Awards & Contests

D50 Resource

Club Resource

LCIF Resource

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Ancora e link no mesmo href sem perder efeito

Question: Estou com um problema, tenho um arquivo javascript que faz o scroll ficar suave quando clica em uma âncora, porém preciso que esse href contenha a âncora mas também contenha o link para quando estiver em outra página voltar para a que eu quero, ja tentei fazer algo como href="index.php#header" mas quando faço isso o efeito de scroll suave some, eu queria fazer quando ele estiver na página index.php ele ficar com o scroll suave na âncora e quando estiver em outra página ele servir como um link para a index.php.

/****JAVASCRIPT **********/
jQuery.easing.jswing = jQuery.easing.swing;
jQuery.extend(jQuery.easing, {
    def: "easeOutQuad",
    swing: function(e, f, a, h, g) {
        return jQuery.easing[jQuery.easing.def](e, f, a, h, g)
    },
    easeInQuad: function(e, f, a, h, g) {
        return h * (f /= g) * f + a
    },
    easeOutQuad: function(e, f, a, h, g) {
        return -h * (f /= g) * (f - 2) + a
    },
    easeInOutQuad: function(e, f, a, h, g) {
        if ((f /= g / 2) < 1) {
            return h / 2 * f * f + a
        }
        return -h / 2 * ((--f) * (f - 2) - 1) + a
    },
    easeInCubic: function(e, f, a, h, g) {
        return h * (f /= g) * f * f + a
    },
    easeOutCubic: function(e, f, a, h, g) {
        return h * ((f = f / g - 1) * f * f + 1) + a
    },
    easeInOutCubic: function(e, f, a, h, g) {
        if ((f /= g / 2) < 1) {
            return h / 2 * f * f * f + a
        }
        return h / 2 * ((f -= 2) * f * f + 2) + a
    },
    easeInQuart: function(e, f, a, h, g) {
        return h * (f /= g) * f * f * f + a
    },
    easeOutQuart: function(e, f, a, h, g) {
        return -h * ((f = f / g - 1) * f * f * f - 1) + a
    },
    easeInOutQuart: function(e, f, a, h, g) {
        if ((f /= g / 2) < 1) {
            return h / 2 * f * f * f * f + a
        }
        return -h / 2 * ((f -= 2) * f * f * f - 2) + a
    },
    easeInQuint: function(e, f, a, h, g) {
        return h * (f /= g) * f * f * f * f + a
    },
    easeOutQuint: function(e, f, a, h, g) {
        return h * ((f = f / g - 1) * f * f * f * f + 1) + a
    },
    easeInOutQuint: function(e, f, a, h, g) {
        if ((f /= g / 2) < 1) {
            return h / 2 * f * f * f * f * f + a
        }
        return h / 2 * ((f -= 2) * f * f * f * f + 2) + a
    },
    easeInSine: function(e, f, a, h, g) {
        return -h * Math.cos(f / g * (Math.PI / 2)) + h + a
    },
    easeOutSine: function(e, f, a, h, g) {
        return h * Math.sin(f / g * (Math.PI / 2)) + a
    },
    easeInOutSine: function(e, f, a, h, g) {
        return -h / 2 * (Math.cos(Math.PI * f / g) - 1) + a
    },
    easeInExpo: function(e, f, a, h, g) {
        return (f == 0) ? a : h * Math.pow(2, 10 * (f / g - 1)) + a
    },
    easeOutExpo: function(e, f, a, h, g) {
        return (f == g) ? a + h : h * (-Math.pow(2, -10 * f / g) + 1) + a
    },
    easeInOutExpo: function(e, f, a, h, g) {
        if (f == 0) {
            return a
        }
        if (f == g) {
            return a + h
        }
        if ((f /= g / 2) < 1) {
            return h / 2 * Math.pow(2, 10 * (f - 1)) + a
        }
        return h / 2 * (-Math.pow(2, -10 * --f) + 2) + a
    },
    easeInCirc: function(e, f, a, h, g) {
        return -h * (Math.sqrt(1 - (f /= g) * f) - 1) + a
    },
    easeOutCirc: function(e, f, a, h, g) {
        return h * Math.sqrt(1 - (f = f / g - 1) * f) + a
    },
    easeInOutCirc: function(e, f, a, h, g) {
        if ((f /= g / 2) < 1) {
            return -h / 2 * (Math.sqrt(1 - f * f) - 1) + a
        }
        return h / 2 * (Math.sqrt(1 - (f -= 2) * f) + 1) + a
    },
    easeInElastic: function(f, h, e, l, k) {
        var i = 1.70158;
        var j = 0;
        var g = l;
        if (h == 0) {
            return e
        }
        if ((h /= k) == 1) {
            return e + l
        }
        if (!j) {
            j = k * 0.3
        }
        if (g < Math.abs(l)) {
            g = l;
            var i = j / 4
        } else {
            var i = j / (2 * Math.PI) * Math.asin(l / g)
        }
        return -(g * Math.pow(2, 10 * (h -= 1)) * Math.sin((h * k - i) * (2 * Math.PI) / j)) + e
    },
    easeOutElastic: function(f, h, e, l, k) {
        var i = 1.70158;
        var j = 0;
        var g = l;
        if (h == 0) {
            return e
        }
        if ((h /= k) == 1) {
            return e + l
        }
        if (!j) {
            j = k * 0.3
        }
        if (g < Math.abs(l)) {
            g = l;
            var i = j / 4
        } else {
            var i = j / (2 * Math.PI) * Math.asin(l / g)
        }
        return g * Math.pow(2, -10 * h) * Math.sin((h * k - i) * (2 * Math.PI) / j) + l + e
    },
    easeInOutElastic: function(f, h, e, l, k) {
        var i = 1.70158;
        var j = 0;
        var g = l;
        if (h == 0) {
            return e
        }
        if ((h /= k / 2) == 2) {
            return e + l
        }
        if (!j) {
            j = k * (0.3 * 1.5)
        }
        if (g < Math.abs(l)) {
            g = l;
            var i = j / 4
        } else {
            var i = j / (2 * Math.PI) * Math.asin(l / g)
        }
        if (h < 1) {
            return -0.5 * (g * Math.pow(2, 10 * (h -= 1)) * Math.sin((h * k - i) * (2 * Math.PI) / j)) + e
        }
        return g * Math.pow(2, -10 * (h -= 1)) * Math.sin((h * k - i) * (2 * Math.PI) / j) * 0.5 + l + e
    },
    easeInBack: function(e, f, a, i, h, g) {
        if (g == undefined) {
            g = 1.70158
        }
        return i * (f /= h) * f * ((g + 1) * f - g) + a
    },
    easeOutBack: function(e, f, a, i, h, g) {
        if (g == undefined) {
            g = 1.70158
        }
        return i * ((f = f / h - 1) * f * ((g + 1) * f + g) + 1) + a
    },
    easeInOutBack: function(e, f, a, i, h, g) {
        if (g == undefined) {
            g = 1.70158
        }
        if ((f /= h / 2) < 1) {
            return i / 2 * (f * f * (((g *= (1.525)) + 1) * f - g)) + a
        }
        return i / 2 * ((f -= 2) * f * (((g *= (1.525)) + 1) * f + g) + 2) + a
    },
    easeInBounce: function(e, f, a, h, g) {
        return h - jQuery.easing.easeOutBounce(e, g - f, 0, h, g) + a
    },
    easeOutBounce: function(e, f, a, h, g) {
        if ((f /= g) < (1 / 2.75)) {
            return h * (7.5625 * f * f) + a
        } else {
            if (f < (2 / 2.75)) {
                return h * (7.5625 * (f -= (1.5 / 2.75)) * f + 0.75) + a
            } else {
                if (f < (2.5 / 2.75)) {
                    return h * (7.5625 * (f -= (2.25 / 2.75)) * f + 0.9375) + a
                } else {
                    return h * (7.5625 * (f -= (2.625 / 2.75)) * f + 0.984375) + a
                }
            }
        }
    },
    easeInOutBounce: function(e, f, a, h, g) {
        if (f < g / 2) {
            return jQuery.easing.easeInBounce(e, f * 2, 0, h, g) * 0.5 + a
        }
        return jQuery.easing.easeOutBounce(e, f * 2 - g, 0, h, g) * 0.5 + h * 0.5 + a
    }
});

                                Sales

                                Acquisition

                                Lettings

                                Commercial

+44 020 7938  3777

firstname.lastname@example.com

";

            <button type="button" class="btnMobile" href="tel:+4402079383777">+44 020 7938 3777</button>

            <button type="button" class="btnMobile" href="mailto:email@example.com">email@example.com</button>

            Proactive Property People <button style='display: ;' id='btnOpen' onclick='modalOpen();'>VALUATIONENQUIRY<svg width='50' height='50' id='btnSvg'><circle style='margin-bottom: 31px;' cx='18' cy='18' r='18' stroke-width='0' fill='white' />Sorry, your browser does not support inline SVG.</svg> </button>

Answer: Simples. Inclua o arquivo que contém a função do Scroll somente na index que é onde você quer o efeito, nas outras deixe apenas o comportamento nativo cuidar do trabalho (redirecionar para a âncora da página index).


Display children of taxonomy term in parent taxonomy page

Question: i would like to print the children of taxonomy term in its parent taxonomy page.
For example there is a news portal and under Sports taxonomy term page i would like to print the children of Sports term:
SPORTS
football #basketball #tennis ...
and then the latest nodes...
How can i achieve this?
Comment: Thanks for the replies but you are proposing to make a block in a different region of th page and print the child-terms using views.
I would like to print the terms under h1.title of the page term and before the nodes.
Answer:
Create a view of taxonomy terms
Create a block display for the view
Add a contextual filter for vocabulary ID
Make the block show up on all vocabulary pages in the block settings.
Comment: This is a good solution if you're OK with using a Block to display the children.
Comment: Well yes it's not a good solution for someone who hates the Block module I suppose.
Comment: I love Blocks. They are very handy to drop into regions, and this works especially well with responsive themes. I've struggled with Panels playing nice with responsive themes, so I've been using blocks much more these days.
Comment: I tried but i get server error 500 when i create such block. I keep searching for the error.
Comment: When exactly does the server error happen? What's in the Apache log?
Answer: It's really easy to achieve this using the Views module.
Just install the views module and add a new view page fetching the taxonomy terms.
The procedure is pretty straightforward if you know how to use Views.
Answer: Use Panels for this, and the Views content panes sub module that comes with it. Download and enable the module (and the sub module) as usual, then...

Create a view of taxonomy terms
Add a contextual filter for a term id
Go to admin/structure/panels
Enable the Taxonomy term template
Edit the Taxonomy term template
Add a new variant
Add the Taxonomy term view you created earlier to the content, and pass the current page's taxonomy term id context as an argument to the View
Add the Taxonomy term Description content to the Panel
Add the List of related items content to the Panel


Nesting v. interaction in LMM

Question: I have a continuous response variable, a continuous predictor (P1) and a variable (elevation, P2) that could be treated either as continuous or categorical (I guess?). I also have an ID as the random effect. My aim is to find out about the effect of P1 on the response variable, but only in combination with (or taking into consideration) the respective elevation, as the effects of P1 and P2 could otherwise potentially cancel each other out.
Now I am confused as to whether I need an interaction term (P1:P2) in my LMM or whether this calls for some sort of nesting?
I hope I gave enough information, thanks for any advice on the matter!
Answer: Nesting is an issue with experimental design.  You don't have that (at least, not from what you've written).
You might have interaction between P1 and P2.  That would mean that the effect of P1 on the response variable was different at different levels of P2 and, similarly, that the effect of P2 on the response variable was different at different levels of P1.
Comment: So if I understand correctly it's then not possible to determine the "direction" of the interaction, i.e. consider the effect of P1 as entirely dependant on P2?
Comment: Interactions don't really have a direction.

Nesting v. interaction in LMM


Documents are added and then removed immediately after

Question: Here's my simple template:
<template name="feed">
  {{> crewChat}}

  {{> statusSubmit}}
  {{#each statuses}}
    {{> statusItem}}
  {{/each}}
</template>

In my groupChat.html and groupChat.js files:
<template name="crewChat">

      {{#each messages}}
        {{> crewChatMessage}}
      {{/each}}

  <form class="new-message">
    <textarea id="message" name="content" rows="2"></textarea>

      <input type="submit" value="Submit" class="compact tiny ui primary button">

  </form>

</template>

Template.crewChat.events({
  'submit form': function(e) {
    e.preventDefault();

    var crewMessage = {
      content: e.target.content.value
    }

    Meteor.call('createCrewMessage', crewMessage, function(error, result) {
      if (error)
        return alert(error.reason);
      console.log("Create new crew message.");
      $(e.target.content).val("");
    });
  }
});

Template.crewChat.helpers({
  messages: function() {
    return CrewMessages.find({}, {sort: {submitted: -1}});
  }
});

When I submit a new message, I can see it added using Mongol (and visually for a split second), but it's removed immediately after.
Meteor.methods({
  createCrewMessage: function(crewMessageAttributes) {
    var user = Meteor.user();
    var crewMessage = _.extend(crewMessageAttributes, {
      userId: user._id,
      author: user.profile.firstName,
      submitted: new Date()
    });
    var crewMessageId = CrewMessages.insert(crewMessage);
    return { _id: crewMessageId };
  }
});

Any ideas why this would be happening?
Answer: I had forgotten to subscribe to my published collection.
Meteor.subscribe('crewMessages');


Batch-script implementing 2 ODBC-connections

Question: Thanks for all previous help! I have a question regarding av script.
My computers is all XP, and needs the following when I do my thing :
I have 2 ODBC-connections (towards MS-SQL-DB), which I have a username / password to create a connection to.
Does anyone have any advice on how to accomplish this? Either in a batch-script or otherwise.
Answer: I'll recomend to use Windows Scripting (WSH) or Windows powerShell.
The reason are:

you will probably get more use for
that tecnology in a Windows
enviroment than of python. (I like python but this is true)
It's
included in all Windows Version (the
scripting tecnology).
You can do a lot of things in a easy way... check WMI, services, restarts, manage logs,
files, odbcs, external software, uninstall software...

There's many Web with sample scripts, and a blog of microsoft with a lot of information:
Scripting Web
And they provide a free tool to help you in programming and with a lot of examples:
Scriptomatic 2.0
And now, the Solution.
First of all, you need Mysql ODBC driver installed in the XP
Then, Here's a link of a sample code, that explain how works and that you can configure to your needs.
Example Script
For executing those scripts, simply open a CMD window and use the command: cscript script.vbs
As you can see, the solution is in the same web that told before, there's a huge database and can do anything with them.
Hope this helps.
Comment: Mysql odbc driver? not mssql? Thanks for all the advice. I promise you that I will not go with Python. Windows Powershell or vbs maybe? I have to sit down a weekend to learn vbs. Maybe drink some beer and learn vbs. Or just drink beer. :-)
Comment: if MSSQL database, You didnt have to install the odbc, it's included on Windows, I'm more confortable with Vbscript at the moment, but Powershell is powerful too. Both choices are good. Luck!
Answer: What do you need to do?
If all you have to do is to check if both databases are in good condition then write simple program that checks that. You can use Python with odbc module; it is already included if you use Python from ActiveState: http://www.activestate.com/activepython/downloads
You test script can look like:
import odbc
connection = odbc.odbc('DSN[/username[/password]]')
cursor = connection.cursor()
cursor.execute("SELECT ...")
for txt in cursor.fetchall():
    print(txt[0])

Of course you can use such program from .bat
check_connection.py my_database1/maclovin/passwd
check_connection.py my_database2/maclovin/passwd

and in program use connect string from command line: odbc.odbc(sys.argv[1]) (in such case you must also import sys)


How to group by and merge in java-script object ES5

Question: I have a object like this
{
"User 1":[
{"count":"1","stage":"A","jCount":"10","name":"User 1","stageId":"A1"},
{"count":"8","stage":"B","jCount":"10","name":"User 1","stageId":"B1"},
],

"User 2":[
{"count":"7","stage":"C","jCount":"8","name":"User 2","stageId":"C1"},
{"count":"8","stage":"B","jCount":"8","name":"User 2","stageId":"B1"},
{"count":"9","stage":"A","jCount":"8","name":"User 2","stageId":"A1"},
{"count":"8","stage":"D","jCount":"8","name":"User 2","stageId":"D1"},
],

"User 3":[
{"count":"6","stage":"D","jCount":"6","name":"User 3","stageId":"D1"},
{"count":"8","stage":"B","jCount":"6","name":"User 3","stageId":"B1"},
{"count":"1","stage":"A","jCount":"6","name":"User 3","stageId":"A1"},
],
/* Many more users */
}

I am tring to change my object in this format
[
{
"name":"User 1",
"jCount":10,
"stageIdCountA1":1,
"stageIdCountB1":8,
"stageIdCountC1":0,
"stageIdCountD1":0,
},{
"name":"User 2",
"jCount":8,
"stageIdCountA1":9,
"stageIdCountB1":8,
"stageIdCountC1":7,
"stageIdCountD1":8,
},{
"name":"User 3",
"jCount":6,
"stageIdCountA1":1,
"stageIdCountB1":8,
"stageIdCountC1":0,
"stageIdCountD1":6,
},
/* Many more users */
]

There is max only 4 stages are there A1,B1,C1,D1 and jCount is common in user array of child objects
if there is no stage it should print 0
I tried to do manipulation in angularjs view but its becoming difficult.
Answer: You can use map to map each user object to an item in an array, and reduce inside the map function to turn the array of stages into a single object:

const input={"User 1":[{"count":"1","stage":"A","jCount":"10","name":"User 1","stageId":"A1"},{"count":"8","stage":"B","jCount":"10","name":"User 1","stageId":"B1"},],"User 2":[{"count":"7","stage":"C","jCount":"8","name":"User 2","stageId":"C1"},{"count":"8","stage":"B","jCount":"8","name":"User 2","stageId":"B1"},{"count":"9","stage":"A","jCount":"8","name":"User 2","stageId":"A1"},{"count":"8","stage":"D","jCount":"8","name":"User 2","stageId":"D1"},],"User 3":[{"count":"6","stage":"D","jCount":"6","name":"User 3","stageId":"D1"},{"count":"8","stage":"B","jCount":"6","name":"User 3","stageId":"B1"},{"count":"1","stage":"A","jCount":"6","name":"User 3","stageId":"A1"},],};

const stages = ['A', 'B', 'C', 'D'];
const output = Object.entries(input).map(([name, arr]) => {
  const { jCount } = arr[0];
  const stageCounts = stages.reduce((a, stageName) => {
    const propName = 'stageIdCount' + stageName;
    const foundStage = arr.find(({ stage }) => stageName === stage);
    const count = foundStage ? foundStage.count : 0;
    a[propName] = count;
    return a;
  }, {});
  return { name, jCount, ...stageCounts };
});
console.log(output);

If you can't use spread syntax (which you should - integrate Babel into your build process if at all possible), then replace
return { name, jCount, ...stageCounts };

with
return Object.assign({ name, jCount }, stageCounts);

Comment: @Mrworldwide: `return Object.assign({name, jCount}, stageCounts);`.
Comment: can you tell in ES2015 pls
Comment: @Mrworldwide  Save yourself a life of pain,.. set yourself up a toolchain that transpiles..  Having to worry about ES5, ES6, ES2015, etc etc,. Is not something I can stomach..
Answer: Using ES6 and Object.entries you can do something like:

const obj = {
  'User 1': [
{ count: '1', stage: 'A', jCount: '10', name: 'User 1', stageId: 'A1' },
{ count: '8', stage: 'B', jCount: '10', name: 'User 1', stageId: 'B1' }
  ],

  'User 2': [
{ count: '7', stage: 'C', jCount: '8', name: 'User 2', stageId: 'C1' },
{ count: '8', stage: 'B', jCount: '8', name: 'User 2', stageId: 'B1' },
{ count: '9', stage: 'A', jCount: '8', name: 'User 2', stageId: 'A1' },
{ count: '8', stage: 'D', jCount: '8', name: 'User 2', stageId: 'D1' }
  ],

  'User 3': [
{ count: '6', stage: 'D', jCount: '6', name: 'User 3', stageId: 'D1' },
{ count: '8', stage: 'B', jCount: '6', name: 'User 3', stageId: 'B1' },
{ count: '1', stage: 'A', jCount: '6', name: 'User 3', stageId: 'A1' }
  ]
  /* Many more users */
};

const stages = ['A1', 'B1', 'C1', 'D1'];

const getCount = (stage, user) => {
  const stageItem = obj[user.name].find(s => s.stageId === stage);
  return stageItem ? stageItem.count : 0;
};

const r = Object.entries(obj)
  .map(([name, user]) => ({ name, jCount: user[0].jCount }))
  .map(user => {
const stagesCounts = stages
  .map(stage => ({
    [`stageIdCount${stage}`]: getCount(stage, user)
  }))
  .reduce((acc, stage) => ({ ...acc, ...stage }), {});
return { ...user, ...stagesCounts };
  });

console.log(r);

Update (ES5)

const obj = {
  'User 1': [
    { count: '1', stage: 'A', jCount: '10', name: 'User 1', stageId: 'A1' },
    { count: '8', stage: 'B', jCount: '10', name: 'User 1', stageId: 'B1' }
  ],

  'User 2': [
    { count: '7', stage: 'C', jCount: '8', name: 'User 2', stageId: 'C1' },
    { count: '8', stage: 'B', jCount: '8', name: 'User 2', stageId: 'B1' },
    { count: '9', stage: 'A', jCount: '8', name: 'User 2', stageId: 'A1' },
    { count: '8', stage: 'D', jCount: '8', name: 'User 2', stageId: 'D1' }
  ],

  'User 3': [
    { count: '6', stage: 'D', jCount: '6', name: 'User 3', stageId: 'D1' },
    { count: '8', stage: 'B', jCount: '6', name: 'User 3', stageId: 'B1' },
    { count: '1', stage: 'A', jCount: '6', name: 'User 3', stageId: 'A1' }
  ]
  /* Many more users */
};

const stages = ['A1', 'B1', 'C1', 'D1'];

function getCount(stage, user) {
  const stageItem = obj[user.name].find(s => s.stageId === stage);
  return stageItem ? stageItem.count : 0;
}

function mapStages(user) {
  return stages
    .map(stage => ({
      [`stageIdCount${stage}`]: getCount(stage, user)
    }))
    .reduce((acc, stage) => ({ ...acc, ...stage }), {});
}

const r = Object.entries(obj)
  .map(function(entry) {
    return { name: entry[0], jCount: entry[1][0].jCount };
  })
  .map(function(user) {
    return Object.assign(user, mapStages(user));
  });

console.log(r);
Comment: is their any chance I can achieve it in ES5..?
Comment: Sure @Mrworldwide
Answer: This is how I found my solution:

var obj = {
 'User 1': [
  { count: '1', stage: 'A', jCount: '10', name: 'User 1', stageId: 'A1' },
  { count: '8', stage: 'B', jCount: '10', name: 'User 1', stageId: 'B1' }
 ],

 'User 2': [
  { count: '7', stage: 'C', jCount: '8', name: 'User 2', stageId: 'C1' },
  { count: '8', stage: 'B', jCount: '8', name: 'User 2', stageId: 'B1' },
  { count: '9', stage: 'A', jCount: '8', name: 'User 2', stageId: 'A1' },
  { count: '8', stage: 'D', jCount: '8', name: 'User 2', stageId: 'D1' }
 ],

 'User 3': [
  { count: '6', stage: 'D', jCount: '6', name: 'User 3', stageId: 'D1' },
  { count: '8', stage: 'B', jCount: '6', name: 'User 3', stageId: 'B1' },
  { count: '1', stage: 'A', jCount: '6', name: 'User 3', stageId: 'A1' }
 ]
 /* Many more users */
};

var stages = ['A1', 'B1', 'C1', 'D1'];

function getCount(stage, user) {
 var stageItem = obj[user.name].find(function (s) {
  return s.stageId === stage;
 });
 return stageItem ? stageItem.count : 0;
}

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function mapStages(user) {
 return stages.map(function (stage) {
  return _defineProperty({}, "stageIdCount" + stage, getCount(stage, user));
  }).reduce(function (acc, stage) {
  return _extends({}, acc, stage);
 }, {});
}

var r = Object.entries(obj)
.map(function(entry) {
 return { name: entry[0], jCount: entry[1][0].jCount };
})
.map(function(user) {
 return Object.assign(user, mapStages(user));
});

console.log(r);


Programmatically translate a string in hook_update_N()

Question: Is there a function I can use to perform a string translation in hook_update_N()?
Comment: I think the question is, if it is possible to translate a **specific string** in a hook_update, instead of going in to administration to translate it manually.
Comment: Is there a problem with `t()`? It should work on an installed site, otherwise use `st()` which is designed for installation. If you don't want to make the choice, use `get_t()` to be sure
Answer: Yes, you can check in the locale module how it's done and replicate to use the same queries like this :
/**
 * Translating some pagination strings.
 */
function hook_update_XXXX() {
  $translations = array(
   'last' => array(
     'fr' => 'dernière page',
     'en-en' => 'last',
   ),
   'first' => array(
     'fr' => 'première page',
     'en-en' => 'first',
   ),
 );

 foreach ($translations as $string => $values) {
   $source = db_query('SELECT lid, source, context, textgroup, location FROM {locales_source} WHERE source = :string', array(':string' => $string))->fetchObject();
  if (!$source) {
    watchdog('update_hook', 'Translation of string "%string" failed.', array('%string%' => $string));
    continue;
  }

  foreach ($values as $langcode => $translated) {
    $translation = db_query('SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language', array(':lid' => $source->lid, ':language' => $langcode))->fetchField();
    if (is_string($translation)) {
      db_update('locales_target')
      ->fields(array('translation' => $translated))
      ->condition('lid', $source->lid)
      ->condition('language', $langcode)
      ->execute();
    }
    else {
      db_insert('locales_target')
      ->fields(array(
        'lid' => $source->lid,
        'translation' => $translated,
        'language' => $langcode,
      ))
      ->execute();
      }
    }
  }
}

I'm using such code to update strings in code instead of having to this manually when deploying code. So a simple "drush updb" can do the job for me.
OR as I've found out recently, a faster version exists like this :
/**
 * Translating some strings.
 */
function hook_update_X() {
  $report = array(
    'skips'=> 0,
    'updates'=> 0,
    'deletes'=> 0,
    'additions'=> 0
  );

  // Translate strings.
  _locale_import_one_string_db($report, 'fr', '', 'Your shipping address book is currently empty.', 'Votre carnet d\'adresses de livraison est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
  _locale_import_one_string_db($report, 'fr', '', 'Your billing address book is currently empty.', 'Votre carnet d\'adresses de facturation est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);

  // Clear locale cache.
  cache_clear_all('locale:', 'cache', TRUE);
}

For Drupal 8, please see this answer : https://drupal.stackexchange.com/a/220608/61138


A function continuous in both arguments

Question: Is there a two-arguments function which is not continuous but continuous in each argument?
It seems I have studied something like this, but don't remember.
Comment: @Jossie: I don't understand your notation
Answer: Yes, the map $f:\Bbb R^2\to\Bbb R$ $$(x,y)\mapsto\begin{cases}
\dfrac{xy}{x^2+y^2}, &\text{ if }x\ne0\text{ or }y\ne0\\
0, &\text{ if } x=y=0
\end{cases}$$
Then $y\mapsto f(x,y)$ for a fixed $x$ is continuous. As it is symmetric in $x,y$, the map $x\mapsto f(x,y)$ is continuous, too.
But $f$ is not jointly continuous at $(0,0).$ To see this, let $z_n=\left(\frac1n,\frac1n\right)$. Then $f(z_n)=\frac12$ for each $n$. On the other hand, it converges to $(0,0)$ which has image $0.$
Comment: Is there an example which is associative?
Answer: Consider the function $f: \mathbb{R}^2 \rightarrow \mathbb{R}$,
$$
f(x,y) = \begin{cases}
      \frac{xy}{x^2 + y^2} & (x,y) \neq (0,0) \\
      0 & (x,y) = (0,0) \\
   \end{cases}
$$
This is discontinuous as it is 1/2 arbitrarily close to $(0,0)$ when $x=y$, but it is easily seen to be continuous in each variable.
Comment: Is there an example which is associative?

A function continuous in both arguments


Content type drop down filter types

Question: In the content page, there is a filter that shows the page, and other types of content.
Is there a way for me that will allow me to show only certain types of items in the content type.
Thank you,
Kevin
Answer: You can use Administer views but to quickly achieve this I would use the hook_form_alter.
Do something like this, Although I would recommend you set this restriction to specific role but for this example I am going to ignore roles. Within hook_form_alter you do
if($form['#form_id] == 'node_admin_content') {
   unset($form['filter']['filters']['status']['filters']['type']['#options']['article']);
}

You can change the ['article'] to whatever the machine name of your content type is. use devel to find out what elements the $form variable contains.
Comment: Why not just create a new view or change the existing one via the UI?
Comment: Yes but instead of creating a new view installing the module I suggested on my answer will be easier and works well too.

Content type drop down filter types