Mixed 3:5 rhythm with ordinary notes

Question: I've got this rhythm which has a 3:5 bit (the three notes in the top go against the first five in the bottom - the final rest in each bar is in-line to make up the bar of 6/8) and I've sketched out what I want (see below). The two staves should be the same. The two F notes should be the same note, how should this be notated correctly? The top F correctly notates the start of the F and the bottom F correctly notates the end / start of the E. I'm not sure how to notate them together on the same line.

Any guidance is appreciated, thank you.
EDIT: Hopefully this makes the intended rhythm clearer.
Comment: Can you please add clarification where the 5 in the 3:5 comes in? The bottom clef shows a total of 6 eight notes, so it's hard to know what 5 refers to.
Even better, can you play the rhythm and a link to it?
Comment: Right, the sixth quaver rest is there to show they are in-line. The three quavers in the triplet go against the first five quavers shown on the bottom clef.
Comment: This doesn't make sense. If the start of the E in the lower clef is correct, then the triplet can only be taking up 4 eight notes, or am I missing something?
Comment: You're missing that the tuplet is 3:5 as I've stated several times. It's three notes in the space of five. The three notes on top take the same time as the five notes on bottom. The the first five quaver notes / rests on the bottom staff take the same time as the first three notes / rests on the top staff. I'm not sure how I can express that idea any clearer.
Comment: First, the durations should be quarters. Tuplet notation can be thought of as squeezing more notes into the original duration, and 3 eighth notes already don't fill out the 5/8 duration.  So I would argue that in the top stave of your second image, change the durations to 3 quarter notes and mark them as a triplet.
Comment: I don't think you understand what tuplets are. It's common to write duplets for example as two quavers in the space as 3. Also your last comment, does nothing to actually answer the question, and you've had difficulty understanding the question. If you don't understand the question, that's fine, but don't start espousing patently wrong notation.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110242/discussion-between-user3235-and-ashiataka).
Answer: Maths. I removed the final quaver rest from your example, because it occurs in both voices. This left a bar of 5/8 and I divided that into 15. Each quaver is subdivided into triplet semiquavers.

The lower voice contains five quaver Fs.
And in the upper voice, as each quaver is divided into a triplet semiquavers the first C is three triplet semiquavers tied to two triplet semiquavers, total note length = 5 triplet semiquavers. And so on.
I think it would be very hard to perform this. This second example combines the upper and lower voice rhythms from your two snippets:

And finally I've put your last quaver back in, and changed the time signature back to 6/8:
Comment: That's perfect, thank you. The last example is what I needed. Thanks for the method too, that makes a lot of sense.
Answer: As someone who might have to play these parts, I'm strongly in favor of writing with a simple  2/4 or 4/4 time signature, and marking the upper part as triplets and the lower part as quintuplets. (either single-beat or two-beat extent as you prefer)
It does not bother us performers to see triplets and quints marked, and after a bar or two you can write "simile" and skip the markings if you desire.
Writing in eighth plus sixteenth groups marked as "triplet" is ugly.  And 5/8 is typically treated as   3 + 2 rhythm, so not what it appears you wanted.
Comment: Thanks for the note, but I wouldn't worry, nobody actually plays my music - I should be so lucky! The piece is actually in 11/8, and this is the only section that isn't straight quavers / crotchets. I just simplified the problem area for my question.
Comment: @Ashiataka  If you truly have no "sub-divisions" of your 11/8, e.g., 6/8 - 5/8 ,  then I still think you're better off marking  triplets that spread over 5 beats, even tho' that's insane to try to play in strict time.
Comment: The bars are subdivided usually into 4,4,3. I'm not sure how your solution would work though because it's just the one note that uses the tuplet construction. See the last example in the accepted answer.

Mixed 3:5 rhythm with ordinary notes


How to configure dhclient on CentOS to get IP from a specific DHCP server

Question: I have a situation where I am able to launch CentOS 6.6 images on a subnet such that the VM instances get their IP addresses from the virtual gateway of the subnet. Now this gateway has gone wonky and I don't have the access to fix it, so I have set up my own DHCP server on this subnet.
So now there are 2 DHCP servers on this subnet and my VMs are getting random IP addresses, sometimes from one DHCP server and sometimes from the other. My question is that how I can configure the dhcp client on my VMs so that they make DHCP requests to only my DHCP server rather than the faulty one? man dhcp.conf has not been very helpful.
Answer: On CentOS 7 this can be achieved by creating the file /etc/dhcp/dhclient.conf and adding a line like
reject 192.168.56.0/24;

to reject DHCP offers from one server or the other (or in this example, from all DHCP servers on a specific subnet).
To filter DHCP offers only on a specific interface, place the reject directive inside an interface block:
interface "eth0" {
    reject 192.168.56.0/24;
}

Note the interface name (here, eth0) must be placed in quotation marks, unlike the example shown in the man page for dhclient.conf.
In all cases, run systemctl restart network.service as the superuser for changes to take effect.

On CentOS 6.7 the same instructions work, however

Each interface uses a separate configuration file for dhclient. In the above example, the file to which the reject rule would be added would be /etc/dhcp/dhclient-eth0.conf (and there would clearly be no need to use an interface block).
The command to reinitialize the system's network interfaces is service network restart, which again must be invoked as the superuser.
Comment: Can I `reject` an IP address instead of a whole subnet? So for instance, will `reject 10.1.1.1;` work if 10.1.1.1 is the IP address of the faulty DHCP server?
Comment: Yes, you can specify an individual IP address like you show, as well as multiple IP addresses and ranges separated by commas. `man dhclient.conf` has more details and examples.
Comment: I tried the `reject IP_Address` option in the dhclient.conf file but it still allocated the IP from the rejected DHCP server. Any ideas what is wrong?
Comment: Not off the top of my head. Are there any clues in the system log? Note I've tested this only on CentOS 7.
Comment: I am also using CentOS 7. Do you know which file has the relevant DHCP logs?
Comment: Ah. In that case, try running either `journalctl -e` (or `journalctl -xe`, for more detail) or `systemctl status network` and check for error messages about DHCP.
Comment: Sorry I gave you the wrong CentOS version, its 6.7, not 7. I couldn't find any of the tools you mentioned in that.
Comment: I've tested this on CentOS 6.7 and updated my answer. Check `/var/log/messages` for information from dhclient.
Answer: DHCP works via a multicast request for an IP address. Which gets an IP address from the first DHCP server to respond. There is no way that I know of to force the client to get a DHCP address from a specific server.
In fact, running two DHCP servers that are not aware of each other is asking for the type of trouble you are running into. You need to get the faulty one shut down or fixed.
Comment: `DHCP works via a multicast request for an IP address` - DHCP actually uses UDP broadcasts to the Layer 2 broadcast address 255.255.255.255. It doesn't use multicast.
Comment: I cannot get the faulty one to be shutdown or fixed, its controlled by another team which are ... lets say busy.

But there is an option in the dhclient command (-s), that lets you specify a specific dhcp server manually. Usually in Linux, if you have a command-line option, there is a reciprocal configuration file option as well. I just cannot find what to put in the `dhcp.conf` file to get the same result as running the `dhclient -s` command manually.
Comment: -1: Does not answer the OP question and there is a way to ignore specific dhcp servers. It is common for gateway servers to run a dhcpd service on downstream interfaces, and get their upstream configurations from a dhcp service running on an upstream server. In this case you need to have a way to tell the upstream interface to ignore the dhcp server that it itself is running. Furthermore, it is common in development environments to have multiple differently purposed dhcp servers running on a local network and the clients decide which one they listen to depending on the developer needs needs.


Nested Tag inside URL tag in Django Template

Question: I have a list of items in my template which produce a table of hrefs. Now I want to send back the item.name to the appropirate view function based on the clicked item. The code should look something like this:
{% for item in myList %}

 {{ item.name }}

{% endfor %}

And the problem is the created nested tag and the {{ item.name }} inside the view arg which doesn't work. Any ideas?
Answer: {% url myView item.name %} should work, if the url pattern expects a positional argument! See the documentation of the url template tag!


create ArrayList with method and parameter is ArrayList's name

Question: my question is simple, but haven't found answer anywhere, how can I create array like this:
public ArrayList<ArrayList<String>> result_of_query_into_array(
        ArrayList<String> nameofArray) {

    nameofArray = new ArrayList<String>();

    try {
        while (result.next()) {

            nameofArray.add(result.getString("nombre_estadio"));
            nameofArray.add(result.getString("ciudad"));
            nameofArray.add(result.getString("capacidad"));
            nameofArray.add(result.getString("temperatura"));
            nameofArray.add(result.getString("equipos"));

        }
    } catch (SQLException e) {

        JOptionPane.showMessageDialog(null,
                "Error en result.next().print..: " + e);
    }

    ARRAY_PRINCIPAL_MULTIDIMENSIONAL.add(nameofArray);

    JOptionPane.showMessageDialog(null, "got all rows  from table  ");

    return ARRAY_PRINCIPAL_MULTIDIMENSIONAL;

}

so when i use this method i have to do this :
ArrayList<String> myArray = new ArrayList<String>();

obj.result_ofquery_into_array(myArray);

is  it posible   to just  do something like :
obj.result_of_query_into_array(myarrayWithoutInstantiatingOutside);

when i put just the name of the array i get an error :
myarrayWithoutInstantiatingOutside cannot be resolved to a variable

please help,  thanks
Comment: Why can't you instantiate outside not within ?
Answer: Because when you are passing a variable as an argument, you are in fact passing the reference of an object, which is then used. When not initializing a variable, you are passing and empty reference, which cannot be resolved. In your example, the correct way of doing this, since anyway you are overwriting the value of the variable, would be :
public ArrayList<ArrayList<String>> result_of_query_into_array() {

    ArrayList<String> nameOfArray = new ArrayList<String>();

    // Logic...

    return nameOfArray;

}

And then just do :
myarrayWithoutInstantiatingOutside = obj.result_of_query_into_array();

Then, you are instantiating the object inside the method, and then returning the reference.
Variables
You have to see variables as simple adresses. Let's take, for example, a house on a street.
123 StackOverflow street
Now, this address, for you, might be your friend's address :
Adress myFriendAddress = 123 StackOverflow street
But for someone else, it might be his boss's address :
Adress myBossAddress = 123 StackOverflow street
The physical position of the house is the same, but the reference is different. It is the same way with objects and variables. The object has a memory address which is the physical position of the object in your memory.
Comment: well yes,  actually i haven't thought of it that way and it does make sence,  thanks,  but   lets  say  i want this to be the way  i create  eg:   a new  player,   but  this would be comming from `JTextField PLAYER = new JTextField(nameofplayer);`,  and name of player would be then  used  to create the    array, something like :

    `result_of_query_into_array( PLAYER )`  in which case player would be created,

ps:   just creating it out of my head something like a  WHAT IF ...

@Gladhus


Show a message after file_transfer is executed

Question: I am using file_transfer to send a download to the http client.
The problem is that file_transfer executes drupal_exit so that no more code is executed after it.
How do you show a message or redirect to another page after sending a file_transfer ?
Answer: By default, you can't - when someone clicks a link to a file that's force-downloaded, it happens as a separate request/process entirely. For security reasons your web site will not be able to tell when/if that download has completed.
I think the easiest thing you can do is implement some javascript on the download link, which auto-refreshes the page as soon as you've clicked it, and while the file is still downloading. You could use a query string or similar to note that a message should be displayed or that a redirect should happen.
If you need something more complicated, you might be able to implement an AJAX-based polling mechanism, which contacts the server and checks the connection status for that file. It's not a trivial task though, and I think you'd need to change the file_transfer module quite a bit to implement that. It also might require some advanced server configuration. All beyond the scope of Drupal, so I'd advise getting a solution working independently first, and only then worry about getting it inside Drupal.
There are some ideas here, and related logic here


Juniper EX BGP with Default Routes

Question: I'm new to BGP - so this is certainly a learning exercise. I'm moving away from PA space provided on 2 routed uplinks to having my own IP space and multi-homing my transit.
To begin with, there will only be a single transit provider - and they have provided 2 RJ45 cable drops with a different /30 VLAN on each - to go to each of my Juniper EX3200 switches.
I only intend to take default routes for now - and in the mean time, I need to continue to use the routed uplinks and PA space - whilst maintaining another routing table for the new BGP gateway/network.
There is 2x uplinks (ge-0/0/0 and ge-0/0/1) on which my WAN glue block VLAN resides (vlan4000). VRRP runs on this VLAN and all my IP's are routed from my provider to this virtual IP. Then internal routes are direct over VLAN L3 interfaces. The gateway IP (ie. my provider's router virtual IP) in vlan4000 acts as my default route.
So I'm aware that I'll likely need to run two routing tables (VRFs) to separate the BGP IPs from the "other" IPs - and maybe do some filter based forwarding for selecting the right gateway.
I've been doing some fairly extensive reading of both,

http://www.juniper.net/us/en/training/certification/JNCIA_studyguide.pdf
http://www.juniper.net/us/en/training/certification/JNCIS_studyguide.pdf

To get a good understanding of the config required.

From my (limited) understanding thus far, I think I  need to ...

Bring up a BGP session with my transit provider
Announce my IP block over my ASN
Route the BGP IP block over that specific interface
Form some kind of failure/HA between the two EX3200's so that a single failure doesn't drop the BGP session.

What I'm essentially unsure of is how the two EX3200's bring up their BGP sessions. As each have their own IPs (router-ids) in two separate VLANs - this looks to be two separate BGP sessions - and I'll need to conditionally route between each BGP default gateway if either goes down?
Has anyone got any example configurations of where to begin?
Comment: Are you using this same EX switch for your external routing today?
Comment: Yes. So currently, there is 2x Uplinks that have routed PA space from my provider. So I've got a glue block, from which the gateway is used for the default route (`0.0.0.0/0 next-hop x.x.x.x`). So I'm aware that I'll likely need to run two routing tables (VRFs) to separate the BGP IPs from the "other" IPs - and maybe do some filter based forwarding for selecting the right gateway.
Answer: EX switches can do VRF-Lite to support multiple routing tables. To start you can look at this KB article from Juniper:
http://kb.juniper.net/InfoCenter/index?page=content&id=KB14926
What you need is BGP support for the VRF/virtual-router. For this you need the AFL license on the EX switches. Here is a software feature table for the EX series, which is always useful:
http://www.juniper.net/techpubs/en_US/junos10.2/topics/concept/ex-series-software-features-overview.html#layer-3-protocols-features-by-platform-table
If you've installed the license you can configure a routing-instance and the BGP protocol under it:
routing-instances {
test {
    instance-type virtual-router;
    protocols {
        bgp {
            local-as 65565;
        }
    }
}

eBGP (external BGP, to your provider) sessions are normally made between interface IPs. So you configure your IP in the /30 on an interface(repeat for second uplink on the other switch) and establish the BGP session to the IP of the provider router. Ask your provider to announce you a default route.
You should connect your two switches and speak iBGP (internal BGP) between them so that they both get the routing information from each other.
If one uplink fails or the BGP session drops your switch will automatically switch to the other uplink.
General information regarding BGP on EX switches is here:
http://www.juniper.net/techpubs/en_US/junos10.4/information-products/pathway-pages/ex-series/bgp.html
This is just a short answer. Please be aware that BGP routing is a very broad topic and it's easy to wreak havoc not only in your network but in your providers network or in an extreme case even worldwide. I would advise getting professional help for the initial setup.
Comment: Thanks Sebastian. I realised I asked a fairly open-ended question (knowing the full extent of BGP). Some of the key questions as to how the two devices need to communicate have been answered (ie. I wasn't sure if iBGP was required, turns out it is). I already read the ~60 pages of BGP guidance in the JNCIE/JNCIS papers - but that's barely a fraction of what I'd need to know in production. FYI. I'm currently looking for a consultant to assist - but I'd like to understand the fundamentals myself at least.
Comment: Sure, nothing wrong with learning how it all works. :) I recommend a few books. "Routing TCP/IP 1+2" from Cisco. Has lots of fundamentals even when you use Juniper. Also "Interconnections 2 ed." from Radia Perlman regarding Layer 2
Answer: Thanks @Sebastian for putting me on the right track. I wanted to follow up on this with what I've learnt/implemented so far with a single EX3200 in a lab. This is a working configuration.
The only bit I'm missing from my original requests was how the high-availability will work for the default gateway on the BGP connection - but I think iBGP will fit that bill.
I might add another routing instance to mimic a second switch - then run a physical trunk between interfaces assigned to each instance. Then bring up eBGP and iBGP on both.

I set up two routing instances, to isolate the two networks (PA IPs and BGP IPs) and gateways.
vlan.10 and vlan.20 served as the BGP uplinks, vlan.3999 is for the /22 IPs we're announcing over our ASN.
vlan.30 is an existing /24 of PA space - with a static route to the main gateway on vlan.40
You can see that the BGP instance was configured specifically on that routing instance - so its not shared amongst the other routing table.
routing-instances {
  transit-bgp {
    instance-type virtual-router;
    interface vlan.10;
    interface vlan.20;
    interface vlan.3999;
    routing-options {
      router-id x.x.x.50;
      autonomous-system xxxxx;
    }
    protocols {
      bgp {
        group bgp1 {
          type external;
          peer-as xxxxx;
          neighbor x.x.x.109 {
            import import-route-transit1;
            export export-route;
          }
        }
        group bgp2 {
          type external;
          peer-as xxxxx;
          neighbor x.x.x.113 {
            import import-route-transit2;
            export export-route;
          }
        }
      }
    }
  }
  transit-pa {
    instance-type virtual-router;
    interface vlan.30;
    interface vlan.40;
    routing-options {
      static {
        route 0.0.0.0/0 next-hop x.x.x.1;
      }
    }
  }
}

So the vlans were assigned as follows
vlans {
  bgp1 {
    vlan-id 10;
    l3-interface vlan.10;
  }
  bgp2 {
    vlan-id 20;
    l3-interface vlan.20;
  }
  liveips {
    vlan-id 3999;
    l3-interface vlan.3999;
  }
  routedips {
    vlan-id 30;
    l3-interface vlan.30;
  }
  routedgw {
    vlan-id 40;
    l3-interface vlan.40;
  }
}

Then to make sure that the two BGP links were preferenced (should one fail), policies were set up to alter the local-preference. A policy was also created to export specific routes to be advertised over BGP.
policy-options {
  policy-statement export-route {
    term local-routes {
      from {
        route-filter x.x.x.0/22 exact;
      }
      then accept;
    }
  }
  policy-statement import-route-transit1 {
    term default {
      then {
        local-preference 220;
        next policy;
      }
    }
  }
  policy-statement import-route-transit2 {
    term default {
      then {
        local-preference 200;
        next policy;
      }
    }
  }
}

At this point - everything was perfect and both routing tables worked in harmony - but completely isolated. Ie. there was no routes shared/leaked between each other. So I set up some filter based forwarding to allow routes to be distributed.
First, I used an input filter on the vlan interface
interfaces {
  vlan {
    unit 10 {
      family inet {
        address x.x.x.110/30;
      }
    }
    unit 20 {
      family inet {
        address x.x.x.114/30;
      }
    }
    unit 30 {
      family inet {
        filter {
          input transit-pa-int;
        }
        address x.x.x.50/24;
      }
    }
    unit 30 {
      family inet {
        address x.x.x.1/24;
      }
    }
    unit 3999 {
      family inet {
        filter {
          input transit-bgp-int;
        }
        address x.x.x.1/22;
      }
    }
  }
}

Which used the following firewall rules
firewall {
  family inet {
    filter transit-pa-int {
      term one {
        from {
          destination-address {
            x.x.x.0/22;
          }
        }
        then {
          routing-instance transit-bgp;
        }
      }
      term default {
        then {
          routing-instance transit-pa;
        }
      }
    }
    filter transit-bgp-int {
      term one {
        condition {
          destination-address {
            x.x.x.0/24;
          }
        }
        then {
          routing-instance transit-pa;
        }
      }
      term default {
        then {
          routing-instance transit-bgp;
        }
      }
    }
  }
}

Juniper EX BGP with Default Routes


Difficulty on deciding when to use grace notes

Question: Writing down exact lengths this is what a piece of my melody (4/8) looks like:

I assume this is a text book case of it being better to use a grace note like this:

I'm having a bit of a hard time on deciding when exactly to use grace notes.
For instance, this:

My intuition is to leave it as it is, since it occurs in between beats (as it should) But then it seems odd to have fixed-length notation in some instances and grace notes in others for the same kind of embellishments in the same score.
Comment: Grace notes are often subject to "interpretation" by the performer.  It seems that you have an exact requirement so writing the rhythm that you want played would be more appropriate in my mind.
Answer: Grace notes are usually used as Acciaccaturas. So, you'd use them when the notes are not melodically and harmonically essential. They are ornaments, that add a little flavour to your melody. Basically, if you remove them from the melody, the sum of it would be the same.
Also, this:

Is not so easily readable by someone not so experienced. I'd suggest to use something less confusing, unless you are aiming this to be read by someone on a high level of sight reading.
Comment: What would be less confusing, if I want to maintain the rhythm as-is? Split the note and use ties?
Comment: The least confusing would be the grace note.After that ties, yeah. A double dotted note is not commonly used
Comment: Regarding the ties, w/o appoggiatura: To me the double dot is more easily read, it communicates to me to maintain the note for the rest of the measure, no?
Answer: Grace notes and phrases do not as a rule carry harmonic/melodic/rhythmic meaning.  Any accented note that is off-beat is not a grace note.   Notes that are on-beat may be appoggiaturas (a particular kind of grace note asking for harmonic resolution, not stricken through and usually written with "at least" its nominal duration): they are a bit of the odd man out since they eat into the note value of the following rather than the preceding note, serve harmonic function, and it's actually the following, usually "in-harmony" main note that is unaccented and may even have a fuzzy/shifted starting point.
Appoggiaturas are not much in fashion these days.  Their main place is in solo pieces or voices or chamber music where the execution typically relies on single players.
So as a rule of thumb (and putting appoggiaturas aside): if the timing of the following note is more important (and likely accented) than the timing of your current note, a grace note might be appropriate.  If the pitch of the following note is the same, a grace note is almost never used.  In a similar vein, if a particular articulation is prescribed (other than just using a legato slur, typically including the following note), grace notes are more often than not replaced with regular notes.
There are no completely reliable hard rules like in many musical issues.


How to convert currency dynamically on Product Page?

Question: I am using drupal 7 and commerce modules. I want a dynamic currency converter on product display page or cart page (priority is product display page). Suppose Product A is displayed with price 1 USD and user is from India or some other country then I want to give the user an option to change the currency before adding product to cart. If the user selects INR then the 1 USD will be converted to INR which makes it 67 and payment will be made in INR. How can I achieve this kind of functionality in Drupal ?
Suggestions are welcomed.
Thanks
Comment: Please follow http://drupal.stackexchange.com/questions/158322/country-based-product-price-should-be-changed-in-commerce-kickstart i guess this question is similar to the question asked in the link
Comment: Thank you Shilpa for replying. commerce_multicurrency was the solution.
Comment: So should i post this as an answer
Answer: You can use  Commerce Multicurrency module for INR price field in the products content types.
Answer: See my answer there https://drupal.stackexchange.com/a/275805/14465 for a step by step solution. It include a way to automaticaly change currency based on the user IP.


Site travando em páginas especificas

Question: Tenho poucas funções nesse site, mas acredito que algum jQuery está fazendo a seguinte página travar.
Os scripts, basicamente são:

O que pode estar gerando esse travamento? Até mesmo o inspecionar elemento demora para abrir.
Comment: Você tem o link do site?
Comment: @MoisesGama está ali no link "página". Mas para facilitar: http://www.congressoconsulfarma.com/Web/cursos/09
Answer: Realmente seu site esta mal desenvolvido, faltam abrir e fecharr tags, colocar as coisas nos lugares certos e o erro não tem nada a ver com jquery, tem a ver com boas práticas de desenvolvimento que você não esta seguindo.
Avaliei seu site com esta incrível ferramenta do google (PageSpeed Insights) , de 0 a 100, o google da nota 9 (mobile) e 11 (desktop) para esta pagina em questão, que você colocou o link ai, isso é horrível para o usuário pois gasta muita banda da internet dele.
Faça algumas coisas básicas:

Coloque os scripts e jquerys no final da pagina, antes de .
Utilize o minimo possivel de scripts jquery, ou coloque todos eles em um unico arquivo minificado e inclua-os na pagina.
Comprima seus scripts e se possível o html.
Trabalhe as imagens, estão pesadas demais.
veja com o F12 as coisas que estão faltando na pagina, isso atrasa o carregamento do site,ja que até ele ver que não existem, ele continua chamando elas, como o none.js, icon e mais coisas em sua pagina.

Você chama 02 vezes os mesmos scripts e nenhum é .min chama todos sem compactação, isso não é bom, note que bootstrap.js é chamado 02 vezes, só nesta pagina.

<link href="/Content/css/bootstrap.css" rel="stylesheet" />
<link href="/Content/css/business-casual.css" rel="stylesheet" />
<link href="/Content/css/quadradoCursos.css" rel="stylesheet" />
<link href="/Content/css/theme.css" rel="stylesheet" />
<link href="/Content/css/style.css" rel="stylesheet" />
<link href="/Content/css/socialIcons.css" rel="stylesheet" />
<link href="/Content/css/palestrantes.css" rel="stylesheet" />
<link href="/Content/js/bootstrap.js" rel="stylesheet" />

Por favor, reveja todo o código e abra e feche as tags corretamente, utilize arquivos .min do jquery e bootstrap e explore mais o potencial do bootstrap que deixara seu site leve e com excelente usabilidade!
Comment: não precisa bater tanto no menino. Eu ia responde mas sua resposta está ótima, só esqueceu de falar da semântica do código, o a `tag` `body` e `html` não foram abertas, o `footer` estão fora do fechamento do `body` (que nem sei porque está fechando se não está abrindo onde deveria) e todo o resto. Se fosse validar no W3C jessuis.
Comment: @MoisesGama desculpe, acho que peguei pesado, não tive a intenção de chatear ninguém, mas a gente que desenvolve pega paixão pela coisa, que da até raiva (do código e não da pessoa) quando vemos algo assim.
Comment: @MaiconCarraro Ela é tão F0d4 que até lhe da os arquivos compactados para você usar caso ache necessário, não me vejo sem esta ferramenta kkkkkkk E tem uma extensão dela para o Chrome tbm que faz o mesmo trampo e tem o mesmo nome.
Comment: Agradeço a critica de todos. Não, não estou começando e essa aplicação não é minha, eu estou dando manutenção.
Comment: sei como é sou igual, mas pelo visto ele está começando e ser desmotivado é muito ruim. Mas na boa entendo como se sente. Abs.
Comment: @MoisesGama vc esta certo, vou editara resposta!
Comment: Desconhecia essa ferramenta do Google vou até adicionar nos favoritos :)
Answer: A resposta do Paulo Roberto está impecável; você deve dar +1, aceitá-la e seguir os conselhos dela.
Tendo dito isso, parte do problema (que o PageSpeed Insights não tem como pegar porque ele não faz OCR) é que você está usando imagens pra representar o que é, fundamentalmente, texto. Você deveria fortemente cogitar a possibilidade de colocar essas imagens como texto na página: assim você reduz o tamanho da sua página e não precisa repetir o conteúdo da imagem no alt="…" só pro Google te indexar.
Se o seu cliente fizer questão de uma fonte bonitinha no banner de cada curso, você pode usar uma webfont — Typekit, Fonts.com têm várias opções a preços acessíveis, e se o cliente não liberar a verba, você pode escolher uma fonte do Google Web Fonts.
Answer: Apesar de todos os comentários válidos a respeito da forma com quem o site foi desenvolvido, o problema não era esse.
O site havia sofrido um SQL Injection.

Site travando em páginas especificas


Como pegar a data de amanha com JavaScript?

Question: Olá.
Tenho esse código:

var datas = new Date();
console.log(datas.toLocaleDateString());

Ele me retorna: 22/05/2017

Tem como fazer com que ele retorne sempre com um dia a mais? assim: 23/05/2017
Answer: Assim:
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);


Filter "exposed filter" data based on another "exposed filter"

Question: I have to exposed filters from 2 vocabularies, filtering results for a page. I'm using views module for this
Is there a way to create a bridge between them ? For example when I select something from the first filter the data from the 2'nd filter will change based on what I selected on first filter, and backwards.
If i'm thinking well there is no way to create a direct connection between those 2 filters (vocabularies), we have to use what they have in common, the content. So i'm guessing I need to get vocaluray 1 terms from the content after filter 2 has selected something.

Filter 2 -> generate content -> generate filter 1 data again

Is there a way to do this without "hardcoding" ? Thanks
Answer: Try the Hierarchical Select module for that

This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
Comment: I'm using 2 different vocabularies, from what I know this module is to display terms from a vocabulary not combining 2 or more vocabularies.
Comment: Try views_selective_filters module https://www.drupal.org/project/views_selective_filters


Do I need to uses always the last targetSdkVersion?

Question: Simple question: In Eclipse "New Android project" command always tries to uses last available sdk. Is it always a good idea?
UPDATE:
I try to explain. Now in Eclipse, "New project" produces a manifest with:
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

So, target to the last Android (Jelly Bean, 4.2.x) but it can run also on Froyo (2.2). It's ok for me. What could I do very wrong with this choice?
UPDATE
Is it ok if I set android:minSdkVersion="8" + android:targetSdkVersion="17" and the build target to 2.2 to be sure my app will run on older devices (no NoSuchMethodError exception)?
Comment: Read this description on what "target sdk version" means: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
For this it follows that you tested your app on this sdk version and verified it works ok. So device do not need to emulate older sdk for you.
Comment: I meant that probably you don't always want last version in that place. I.e. if you create new project (writing app from scratch) - this is probably the good way to start. Otherwise lets imagine your app accesses some device features and you tested it on device with API level 18. Then you see that API Level 20 is available and just change this target version. After this some features might not work on newer devices, however, if you leave target sdk on 18, new devices will emulate it for you and everything will work just fine.
Comment: It depends on what devices do you want to target
Comment: @tuxSlayer Yes, thanks, a lot of time passed since I wrote this question. Now I always target the last sdk version
Answer:
What could I do very wrong with this choice?

There is nothing wrong with this choice, which is why the build tools default to it.
Setting the targetSdkVersion opts you into specific behaviors that you might not get with an older targetSdkVersion. You can see some of what you get by reading the documentation for Build.VERSION_CODES.
Comment: @Seraphim: I would not recommend that approach. Lint will tell you when there are classes and methods that you are using that exceed your `minSdkVersion`. With ~40% of Android devices running Android 3.0+, you should be starting to use capabilities that are newer than Android 2.2, just conditionally (e.g., via `Build.VERSION.SDK_INT`). In those cases, you should set your build target to be the version of Android that has all the classes and methods that are you trying to use.
Comment: @Seraphim: Possibly. Make sure you are on a current version of the SDK tools (and the ADT plugin for Eclipse, if you use Eclipse). You may need to manually run Lint, though usually it automatically runs when you save the file.
Comment: Previously, targetSdk was 8, and now (with 17) I get NetworkOnMainThreadException exception. Changing the target helped me to discover those "bad" lines.
Comment: Is it ok if I set android:minSdkVersion="8"
    android:targetSdkVersion="17" and the build target to 2.2 to be sure my app will run on older devices?
Comment: Really? I tried but with getfragmentmanager() and a Emulator with 2.2 no lint error/warning but in runtime I get an "NoSuchMethodError" exception. Do you think it's a lint problem?
Comment: Please, could you make an example of a method that will surely produce a Lint warning in my case?
Comment: @Seraphim: Since I do not know what your "case" is, I have no way to answer that.
Comment: Ok, forget it. Now I understand what you've told me: minSdkVersion="8", targetSdkVersion="17" and the build target as max as I can "manage". Ok learned something interesting today. For example, using DreamService (API 17): If I keep the build target lower than 17 I get the Lint warning.
Answer: If you want to develop applications for an older version, it is not a good idea. You can always check what the most used version is and make your application against that version. In some cases it is needed to use the latest version because some functionality is not yet implemented in an older version.
Answer: You can read more about it here: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
But you should almost always have target as the latest and then change minimum to the oldest you want.


Solve the equation -

Question:
Solve  $$ 3-\frac{4}{9^x}-\frac{4}{81^x}=0 $$

I had this question for an exam today and I want to find out if my answer was correct.
Comment: If you have an answer that you want to be checked, please write it in your question to enable us to judge if it is correct.
Comment: Did you get $x=\frac{\log{2}}{2\log{3}}$, because that's what I got.
Comment: @YagnaPatel I didn't get that answer but I had a feeling I did it wrong anyways.
Answer: Substitute $t = 2 / 9^x$, then you get simple quadratic: $t^2 + 2t - 3 = 0$ ...
UPDATE: I want to update my answer regarding the solution of the equation:
The question does not specify if only real solutions are required. If that is the case there is a single solution: $ \ln2 / \ln9 $. However, this is not the only solution as the quadratic has one more root (-3) which will result in complex (infinitely many) solutions, i.e.:
$$ 9^x = - \frac 2 3 $$ or
$$ x = \frac{ln (-1) + ln(2/3)}{ln9} $$
$ ln(-1)=(2k+1)\pi i$ for $ k \in \mathbb{Z}  $, which give us infinitely many solutions to the equation:
$$ x=\frac{ln(2/3)}{ln9} + i \frac{(2k+1) \pi}{ln9} $$
Comment: I did $y=9^{-x}$, but anyway this is the easiest approach to this problem.
Answer: So if we let the common denominator be $81^x$, we would get this:
$$\frac{81^x\times 3 - 4\times9^x - 4}{81^x} = 0$$
Use the quadratic formula on the numerator while letting $y = 9^x$, and we get
$$y = 9^x =  \frac{2\pm 4}{3}$$
So $$x = \frac{\ln 2}{\ln 9}$$
since $\ln \frac{-2}{3}$ does not exist.
Comment: you did the quadratic formula wrong... also, why the aversion to base-9 logs?
Comment: @MichaelChirico Maybe. It's about the method, not about the actual numbers. If you have the numbers, please consider editing the question with the right numbers. :)
Comment: that's why i didn't downvote. just letting you know since you got a different answer than did i.
Comment: @MichaelChirico I checked, and I have the right numbers I believe.
Comment: discriminant is 16+48. where'd you get 40?
Comment: @MichaelChirico It's $4ac$ not $2ac$, sorry my bad

Solve the equation -


Pearson correlation with missing values

Question: I am trying to correlate dendrochronological data with climate data. The first one is acquired directly from trees, the second one from various stations from around the world. According to the formula of Pearson correlation, two sets of values must be of the same size. But the climate data is not always complete - e.g. temperature might have not been collected on a given day 100 years ago.
What should I do in such a situation?
I had two ideas. Interpolate missing values or omit the incomplete pair. I don't want to do the first one as it artificially creates values which might not be true. But can I do the second one?
I am not a mathematician and I'm not sure whether it is a viable option. Also, if you had any sources to back your answers up, I'd appreciate it as well.
Comment: Interpolation might make sense otherwise, but can't help you gauge the strength of relationships between known data. Your best option is to use pairs for which both variables are known. (It's not obvious from what you say that Pearson correlation makes sense any way, but that's a different question.)
Comment: I'd just like to emphasize and expand @NickCox final sentence: Correlation of time series data is often problematic or spurious.  All sorts of time series can be correlated due to some other cause.
Answer: Imputation (what you are calling interpolation) is widely used to handle missing data. You will obtain good estimates of Pearson correlation using (flexible) mean imputation. However, to estimate standard errors you will have to use multiple imputation. Omitting incomplete pairs is called a complete case analysis, and while inefficient, can work decently well. One must assume that the nature of the missingness doesn't depend on unmeasured values, like the outcome itself, for these approaches to be valid.
Comment: Contrary to this, a contrast between interpolation and imputation is both clear and worth preserving. Interpolation is centuries old and  historically was often focused on getting finer detail from mathematical tables (e.g. of logarithms).  In a time series, interpolation uses only nearby values on the same variable, and can use e.g. linear, cubic, cubic spline methods (not at all a complete list). As I understand it, imputation usually (always?) uses relationships between variables to make predictions of what is missing, and typically (always?) does not use time or space ordering at all.
Comment: @NickCox interestingly, air pollution modeling is an area where I've seen both principals applied. The goal is to predict individual level exposure to PM10 (or PM2.5) which is subject to seasonal variability and other exogenous time-varying or static trends. A flexible Kalman Filter is fitted capable of providing mean-level and individual level predictions over time. Most imputation techniques benefit from using simple panel data where the only assumed covariate structure is an exchangeable one, and even that is not turnkey as far as providing good predictions. Subtle and relevant point +1.
Comment: Indeed. The principles are not exclusive. Oddly, I come across many fairly well trained statistically-minded people who have never heard of interpolation, beyond knowing from childhood, that you can join up the dots, whereas they are often very clued up on imputation (which has usually been oversold to them). Part of the explanation may lie in a decades-long division of teaching whereby interpolation is regarded as part of numerical analysis. (It was not always so, as witness older books on combination of observations.)  Interpolation isn't magic either to repair broken data.

Pearson correlation with missing values


How to put your android application on Android Market for free?

Question: I am very new to the Android Market. I want to put my application up for free.
Is there any possibility for free "upload" (I saw you must pay 25$). This is for school project and I will not pay that money, too much for me <code>:D</code>
If there is no possibility for that, if there is someone out there with account, that I will send app to him and he will put it on Android Market.
Answer: No that is not possible, if you want to publish on Google Play you have to get that Publisher Account which costs 25$. This fee is mainly to prevent people from spamming the market.
Alternatively you could look at publishing your application on other non-official "markets", most of them will let you do so for free. You will not get as much exposure, but if you're seeking a free way to get your application out there, that's the only way I know of doing so.
Comment: Yes, try Amazon, AppBrain, or just email the APK to your friends and have them install it manually, or host the APK file on a website and send the link for people to install manually (but they have to click that special check box - which you'll show them how).


Qual é o significado da palavra "cout" no C/C++?

Question: Bem, é muito comum nas linguagens de programação haver palavras-chaves responsáveis para impressão da saída de dados.
Algumas são clássicas como echo, print, printf e write, etc.
Porém no C/C++ temos o cout. Para mim, essa palavra não faz sentido  estar relacionado a impressão de dados(falo em uma tradução, por exemplo). Inclusive não achei uma tradução para essa palavra.
Por exemplo:
int main()
{
   cout << "Imprimindo o famoso HELLO WORLD!!!\n";

   return 0;
}

Qual é o significado da palavra cout afinal de contas?
Comment: `fopen()` também não é tão obvio assim hehe.
Comment: @rray `f` => file.
Comment: Em C o identificador `cout` não está reservado. Podes usá-lo para o que quiseres, por exemplo: `int cout = 42;` ou `struct cout { double cin; };` ...
Answer: O cout não é uma palavra-chave da linguagem, é um objeto da biblioteca padrão e só pode ser usada através do namespace std e inclusão do header iostream.
O significado seria console output. Assim como cin seria console input. Ambos são streams de entrada e saída de dados pelo console.
Há quem considere que o "c" seria character. Pelo menos é o que diz o criador da linguagem. É esquisito mas faz algum sentido porque no fundo tudo que é enviado para o stream acaba sendo convertido para caracteres que vão para o console (ao contrário do que as pensam outros tipos não são impressos, só uma string, por isso todo tipo precisa poder ser convertido para string de alguma forma, mesmo sem criar um objeto novo).
Coloquei no GitHub para referência futura.
Comment: Ah, tá explicado. E eu que achei que era porque não podia usar só `out` por talvez já ser reservado. :)
Comment: Só uma pequena correção, `std::cout` não é uma função mas sim um objeto global.
Comment: +1 simples e direto :D


three dimensional planar geometry (analytical geometry of planes )

Question: A plane meets a set of three mutually perpendicular planes in the sides
of a triangle whose angles are A, B, C. Show that the first plane makes with
the other three planes angles, the squares of whoso cosines are
cot B cot C, cot C cot A, cot A cot B
I am looking for a more simpler approach where analytical geometry concepts can be used. I have no knowledge of the properties of triangles, except the definitions of sine, consine etc
Answer: Assume that $A=(a,0,0), B=(0,b,0), C=(0,0,c)$ with $a,b,c>0$. The equation of the plane $\pi$ through $A,B,C$ is clearly $\frac{x}{a}+\frac{y}{b}+\frac{z}{c}=1$, hence $\pi$ is orthogonal to the vector $\left(\frac{1}{a},\frac{1}{b},\frac{1}{c}\right)$. The side lengths of $ABC$ are $AB=\sqrt{a^2+b^2},AC=\sqrt{a^2+c^2}$ and $BC=\sqrt{b^2+c^2}$, corresponding to the following planar configuration (it is useful to recall that the height through $A$ is the locus of points $P$ such that $PB^2-PC^2=AB^2-AC^2$):

Unfolded trirectangular tetrahedron. Red segment $=a$, Blue segment $=b$, Green segment $=c$.
Let $H$ be the orthocenter of $ABC$, $H_A H_B H_C$ the orthic triangle and $V_A,V_B,V_C$ the points on the heights "seeing" the sides of $ABC$ under a right angle. The cosine of the angle between $\pi$ and $OAB$ equals $\frac{HH_C}{H_C V_C}$. Your 3d-problem is now a 2d-problem. Can you finish it? Consider that:
$$ \cot B\cot C =\left(\frac{b c}{2\Delta}\right)^2. $$


How does a menu item get hidden with the Domain module?

Question: I have a node that is restricted to site dev2. In my menu, I have a link to that node. On dev1 site, the link doesn't show up.
I have created a hook for node_access that returns NODE_ACCESS_ALLOW  for the view operation. Shouldn't it show up in the menu for both sites even though it is restricted to dev2 by the Domain module?
Comment: devel_access might help you.
Comment: I am a little bit confused by your question. "Shouldn't it show up in both sites"? You restricted the link to dev2 w/ the domain module...so no, in theory it should not. I guess I don't understand what you are trying to ask. Are you asking how does the Domain module work?
Answer: I did a project this summer that used Domain Access to split a site into desktop and mobile versions of the website.  The client wanted to be able to target pieces of content for the desktop, mobile, or both.
If a piece of content is in a menu, the the domain rules will decide if that piece of content is available, which is what you are seeing.  This is done with the standard node_access methods, which grant permissions rather than take them away.
I think you have a two options here.
I think proper thing you should do it to send the node to all or multiple affiliates, which should be an option when you edit the node.
If you want to go the node_access route, then I suspect you need to clear caches and also rebuild the node permissions.  I totally forget where this option is in the UI, but you essentially need to call node_access_rebuild.  The easiest way is probably with drush
<code>drush php-eval 'node_access_rebuild();'
</code>
Just keep in mind that the link will appear in the menu, but the node will also be viewable.  The two go hand in hand.
Comment: Out of curiosity, did you end up having to rebuild node permissions?


JDBC PreparedStatement pooling for Scala

Question: I am using a JDBC driver for Microsoft SQL Server 2012 (sqljdbc_4.0) and although the Connection instances are thread-safe, the Statement instances do not appear to be (particularly PreparedStatement).
I am using Scala .par.foreach method calls on some collections that then execute PreparedStatement instances. I am currently creating new PreparedStatement instances inside the closure of the .foreach to process each item, since they are not thread-safe.
Each of the PreparedStatement queries is the same, with different values substituted for the question-mark parameters (?). I am wondering if there is any way to create a pool of PreparedStatement instances equal in size to the number of threads used by the parallel collection, and then just reuse a free one for each iteration of the .foreach closure, returning them to the pool after reuse.
Answer: Although the Connection is thread safe the idiomatic way to do this would be to use a pool of connections and have each thread use a separate connection.
This will cause less contention between threads over the connection and the underlying transport.  It will also better allow the database on the other end to use different worker threads for each connection as well.  You gain throughput at cost of client side memory, with the caveat that you can still experience contention at the database level over the actual data if you're doing updates at the same time.
You could try BoneCP, c3p0 or DBCP for pooling, all three are widely used.  They allow you to configure statement pooling as well to save on the cost of re-preparing them.


Inequality: $(a^3+3b^2+5)(b^3+3c^2+5)(c^3+3a^2+5) \ge 27(a+b+c)^3$

Question: Proving inequality for positive real $a,b,c > 0$: $$ (a^3+3b^2+5)(b^3+3c^2+5)(c^3+3a^2+5) \ge 27(a+b+c)^3$$
Answer: Use AM-GM inequality we have $$a^3+2=a^3+1+1\ge 3a$$
so
$$a^3+3b^2+5\ge 3a+3b^2+3=3(a+b^2+1)$$
so
$$LHS\ge 27(a+b^2+1)(1+b+c^2)(a^2+1+c)$$
Use Holder inequality we have
$$(a+b^2+1)(1+b+c^2)(a^2+1+c)\ge (a+b+c)^3$$
By done!


How can we apply Algebra in our life??

Question: We all know that Math is the science's mother and it's applied in all areas,
I have an idea about where functions and geometry calculus ans stats are applied (in economic, banks, building ...), but I have no idea where can we apply algebra in real life, I mean like groups, rings and polinomials, I try to think where it could be usefull but I i find nothing.
I was thinking that if I am studying groups and rings only to teach people those notions which will also teach other's then it has no sence !!!!!!!!
any body give me some uses of groups and rings in the daily life
thanks
Comment: Have you already search for some anwsers of your question on this website ? I think this is a duplicate question see [this](http://math.stackexchange.com/questions/966917/do-we-use-abstract-algebra-in-real-life)  and  [this](http://math.stackexchange.com/questions/65300/real-world-uses-of-algebraic-structures) , [this](http://math.stackexchange.com/questions/324253/are-there-real-world-applications-of-finite-group-theory) , [this](http://math.stackexchange.com/questions/83837/what-is-a-real-world-application-of-polynomial-factoring) for example
Comment: Yeah they probably said the same things about Maxwell's equations.
Comment: @Nizar they are talking about graphs but what i wanted to know is about groups and rings which don't use graphs or calculis
Comment: I use the Abel-Ruffini-Theorem occasionally to point out that numerics have a fundamental value (apart from speed)
Answer: I think it depends on your life. A very few people (in the big picture) actively use abstract algebra day to day. When we teach the subject, we're trying to train those people.
As a (somewhat) practical matter, X-ray crystallography depends pretty heavily on group theory, as I recall, and it's used to do all sorts of science that have an impact on your daily life.
But you might as well ask "How do we apply biochemistry in daily life?" The answer is "not at all, but it has a huge impact nonetheless, since most medicines depend on it." So all you really need is for a few people to apply biochem well, and the fact that the rest of us don't do so is actually a good thing: it shows that specialization has worked. Kinda like being an airline pilot. I can't fly a 747, and chances are that you can't either, but that's no reason to stop training pilots. :)
Why should you study abstract algebra? Well, that's a choice you're making, perhaps to enjoy understanding something that some people find inherently beautiful or at least intriguing, or perhaps to train to be one of those people whose daily life's work does depend on knowing that stuff.
Comment: to be fair: there is the tiny, subtle difference that your life depends upon your own biochemistry (granted, you do not have to understand it)
Answer: Not always is pure maths used in daily life.You may read the book-A Mathematician's Apology by G.H. Hardy which talks on this issue.He says that there are certain branches of mathematics which are also called pure maths is where the real beauty of mathematics lies but they are not used in our daily lives.They help to change the view you have towards the world and your perception.
You may find the book interesting but this book has also been criticised a lot by some people.Some complex branches of number theory do have application in Information Technology that affects out daily life.For eg. use in e-mails.
Comment: Well, Hardy said, "No one has yet discovered any warlike purpose to be served by the theory of numbers or relativity, and it seems unlikely that anyone will do so for many years."  As the [Wikipedia article notes](https://en.wikipedia.org/wiki/A_Mathematician's_Apology), "Since then number theory was used to crack German enigma codes and much later, figure prominently in public-key cryptography."
Comment: Note that what area of maths are "useless" is highly depedent on evolution of global science. Prime factorization was once just a little game without real world implication... Things like category theoryhave applications in datamining, something totally unconceivable 50 years ago
Comment: @Tryss I think the word you're looking for is [inconceivable](https://youtu.be/Z3sLhnDJJn0). :)
Comment: @SpamIAm : thanks ! English is not my native language, so sometimes I write funny stuff.

How can we apply Algebra in our life??


different results using R or Libre Office calc

Question: I have this set of data
x       y
0.5 306.3
1   622.3
2   1230.1
3   2017.7
4   2589
5   3175.4
6   3751.9
9   5585.7
12  7388.8
15  9218.8
20  12042.8
25  15056.5
30  18081.2
45  27095.3
60  35609.2
80  47263.1

When I plot x vs y with R I obtain an almost linear plot, when I plot them with Libre Office Calc I obtain a parabolic plot.
How is that possible?
Which one is the right one?
Comment: Excuse me, why did you delete the plot I went to the trouble of including for illustration? It was nothing other than a cleaner, larger (i.e. non-screenshot) version of the same plot you linked to in comments. Why remove it? If you included a link to the plot, you intended it to be seen. I made it easier to be seen, and in the correct context (in your question). What's up?
Comment: Sorry my mistakes, it's my first time with this forum and I still do not know how does it works.
Comment: Okay; I put it in my answer instead, so at least people can see it.
Answer: From the look of your link below, you obtained this plot:

It looks like you're just plotting y vs its index in Libre Office Calc.
Let's look at the difference - first in R:
R gives (using plot(x,y)):

But if you plot y vs its index and plot lines (plot(y, type="l", col=4)), you get:

If you don't tell Libre Office Calc to do a scatter plot, by default it does a barplot of the series. Instead you seem to have got it to do a line plot of just the $y$ series. You can, for example, get that (the top plot in my answer) by selecting the $y$ column and then Insert, Chart and then choosing Line and then clicking on the third plot, "Lines only".
Libre Office Calc will produce the correct plot if you tell it the right things:

You can do this as follows:
Select both data columns. Insert then Chart
The Chart Wizard window should pop up (if you're using a recent version, anyway, mine were done in 220.127.116.11).
Choose the XY (Scatter) option.
Click Finish (or choose one of the related plots there, like the line-and-points or the line-only plot and then click Finish).
Comment: Yes you do have the index of the $y$ points, it's just not *telling* you that you do.
Comment: My r plot is look like your. But my libre office plot is this one    https://docs.google.com/file/d/0B3FIuCA5bZUaakNtNDhrWE5Vc1k/edit?usp=sharing On the x axes i do not have the index
Comment: thanks probability I'm making some mistakes with libre office is the first time I use it.  Thanks for help
Answer: Just to reiterate what was mentioned above:
To have your provided values along the x-axis, you must choose "XY Scatter", and NOT Line graph or anything else...
So highlight your two columns of data, choose Insert -> graph -> XY Scatter, and it should create a "data range" for your "x axis". The "x axis" data range field does NOT appear and is not create-able (that I can tell) when you select a line graph...


Up-down strumming when playing fingerstyle

Question: I'm trying to learn never dying Nothing Else matters by Metallica and got to the part where I need to strum C, A and D chords:

If I had a pick in my hands, it would go like nothing - down-down-up-up and so on. But since this song is played fingestyle, how to pass through this part? I've tried to throw my fingers up and down, but it just sounds very crappy, especially when fingers go up. Also I should mention the fact, that I have very short fingernails.
As usual any explanation and a link to video lessons will be very appreciated.
Comment: No fingernails at all, or very short ones?
Comment: @Neil Fein I mean I have them, but they are cut very short (I cant afford longer ones because of the sports)
Comment: FWIW you don't necessarily need to play this song finger style. It was the first song I successfully taught myself, and I didn't even know what finger style was. However knowing about it now definitely makes the song easier to play :D.
Answer: When I play this, or other parts like it..going from finger picking to a strum,  I just put my thumb and first finger together, LIKE I'm holding a pick and just use my fingertips.  I have short nails too, but there's enough to get a good sounding strum.  Or I kind of drag all my fingertips, nails touching the strings.
Comment: If you go further and put all the fingertips together, you can lead with the middle or ring for tonal variation (or if the index nail is too short).
Answer: You might want to check out the rasgueado technique.  You don't really need nails to do it and if you take the time to learn it correctly, it will also improve your single note strokes.  Here is a video of someone demonstrating.
http://www.youtube.com/watch?v=r43WrKA6ppI
Answer: Rasgueado works for a lot of metal. I do a fair bit on some of our songs where we kill the distortion but want to keep some power in the rhythm. It sounds much fatter, while keeping sharp attack, as all five nails can hit the strings in very quick succession.
It also can give really fast strums, which may be difficult using other techniques.
Answer: Even with very short fingernails, there'll still be a difference between your upstroke and your downstroke. The sides of your fingernails striking the strings will make your downstroke more percussive than your upstroke, which will produce a tone that's a little softer than the upstroke. Neither will produce as crisp a sound as a pick.
With no pick, I usually start strumming on the downstroke where I want to start with a bang. If I want to start softly (as in, for example, the opening chords of "Mood for a Day" by Steve Howe), I'll either start strumming on the upstroke or strum the strings with the side of my thumb.
It's also worth noting that if you want to use a pick for this part, you have several options including pick-holders mounted on a mic stand or the headstock of the guitar.
Answer: There are many ways you can strum when fingerpicking. I guess you are not using your nails but your fingers when playing the rest of the song so in that case you will want some mellowsounding strums. Use your middle and ring finger for the downstrum and your index finger for your upstrum.
As for the video lesson this should be sufficient..
If you want to play more like basic rock type chording so it would sound like a pick then put your index  finger together with your thumb (sort of like when your holding a pick) and use the index finger nail for the downstroke and your thumbnail for the upstroke...
There are many ways to strum and you can choose which ever feels right for you and suits the feel of the song you are playing.
Answer: Just use the side of your thumb and hold your fingers together, kind of like slapping a bass.


Data Type Classification in Statistics

Question: It is my understanding that in statistics one has 4 basic data types:
nominal, ordinal, ratio, and interval.
I see cases where people refer to "count data" (which is a random variable whose range is the set of whole numbers, such as the number of accidents in a week or the number of passengers on a plane), which brings me to my question: is "count data" is really data. It seems to me that it is a statistic computed from nominal data for two reasons. First, it doesn't seem to fall into one of the four data type categories. Secondly, it is obtained not from a measurement or recording of single events but rather from an arithmetic operation (i.e. addition). So for example, the number of passengers in a plane is a statistic whch would be computed from the nominal data associated with each seat in the plane ("1" = occupied, "0" = unoccupied).
Matt
Comment: Tangential, but "count data" need not be a random variable. Counting the entries in a spreadsheet or database (based on attribute values of the contained data), whereas stochastic models (ie, randomness) are extraneous to the data.
Answer: Certainly count data is data.  The list of what you call four basic data types is not intended to be an enumeration of "data types".  It is a list of what are called "levels of measurement".  My sixth-grade teacher frequently iterated the assertion "Measurement is approximation; counting is exact."  That would exclude count data from a list of "levels of measurement".  The term "levels of measurement" seems to come from the discipline of psychophysics.  It gets taught in statistics courses with very little if any of the theory that it emerged from, and usually without even citing any sources where one could read more about it. See "On the Theory of Scales of Measurement" by S. S. Stevens, Science, volume 103, number 2684, pages 677--680, June 7, 1946.
Comment: I still have some difficulties making sense of these distinctions. On pg 678 in the article by Stevens, we read "the only statistic relevant to nominal scales of type A is the number of cases, e.g. the number of players assigned numerals", which seems to be exactly what I was saying earlier (counts are statistics). Secondly, it seems the statements "nominal is a level of measurement" and that "measurements are approximations" are not totally consistent. If a nominal variable has 2 categories where a subject is either unambiguously in one category or the other, there is no approximation.
Comment: @MattBrenneman, +1 (also to M.H.). Fyi, there are other inconsistencies as well as increasingly subtleties in theories of scaling. But I think what you are asking about: *data* vs. *measurement* may be a false dichotomy. A statistic, being the image of input data produced by an estimator, is also data (eg, your FICO score based on your credit record data is data to banks).
Comment: @MattBrenneman : I don't think "nominal is a level of measurement" and "measurements are approximations" necessarily conflict with each other.  For example, I once attended a talk by [Stephen Fienberg](http://en.wikipedia.org/wiki/Stephen_Fienberg), the famous categorical data analyst, in which he mentioned a survey he designed of Jews living in the Pittsburgh area.  The survey began with questions to ascertain whether a person should be considered Jewish.  He was empatically unwilling to trust their assertions about this.  There are uncertainties aobut the boundaries between categories.

Data Type Classification in Statistics


Prove or name this identity: the number of factors of $p$ in $\binom{n}{k}$ is $(s_p(k)+s_p(n-k)-s_p(n))/(p-1)$

Question: you can count the number of factors of $p$ that are in $\binom{n}{k}$ for prime $p$. Let $s_p(n)$ be the sum of the digits of $n$ in base $p$.  Then, the number of factors of $p$ in $\binom{n}{k}$ is $(s_p(k)+s_p(n-k)-s_p(n))/(p-1)$.
Comment: I have heard this result attributed to Kronecker. You can prove it by computing the power of $p$ dividing a factorial.
Answer: It's a  corollary of Legendre's 1808 theorem that power of the prime $p$ that divides $n!$ is
$$  [n/p] + [n/p^2] + [n/p^3] +\: \cdots\ =\ \frac{n-s_p(n)}{p-1}$$
For this and much more see  Andrew Granville's very interesting survey The Arithmetic Properties of Binomial Coefficients.
A full answer is here.
Comment: Which chapter can i find my problem?
Comment: Math Gems - How do you prove the theorem you stated?
Comment: @Victor See also [this prior question.](http://math.stackexchange.com/questions/20737/prime-powers-that-divide-a-factorial) Also googling "power of prime divid factorial" finds many proofs. But you'll learn better if you discover it yourself - it's not hard.


Git - get last commit made on branch

Question: I have a git branch, branch-1, whose last commit hash is 123456. I also have a git branch branch-2 whose last commit is 7890ab and was made after 123456. Both of these branches are based off of dev.
I then merge branch-2 into dev and pull dev into branch-1. Running git log on branch-1 shows the last 3 commits as:

A merge commit for pulling dev into branch-1

7890ab

123456

Is there a command I can run that will retrieve the last commit made on branch branch-1 -- that is, 123456? I've tried running git log --no-merges --max-count=1, which excludes the merge commit, but retrieves 7890ab because it's not a "merge commit" even though it was retrieved from a separate branch.
Thank you.
Comment: Side Note, you emphasized the word "*made* on branch `branch-1`" to convey the meaning of your question, which I think is clear, but note that in Git that meaning doesn't really exist. In other words, you are interested in knowing what was the last commit "made" while `branch-1` was checked out, but imagine the scenario where you were detached when you made that commit, and then created a new branch pointing to that new commit after the fact. In that case, no commit was ever "made" on that branch, and no one could possibly ever know that (or care), except for you.
Comment: The tip of the reflog for that branch?
Comment: Wait, if you pull dev while you are on branch-1 then the last commit made on branch-1 will whatever commit results from that. I think. But you can use the reflog to figure where the branch was n steps before that pull.
Comment: Why do you wish to do this? From the POV of the Git history (e.g. on a fresh clone), this is not possible. Though, as @Guildenstern points out the machine that committed to `branch-1` may have extra information in the reflogs.
Answer: I was able to solve this by using the first-parent flag on git log. From the git log documentation:

When finding commits to include, follow only the first parent commit
upon seeing a merge commit. This option can give a better overview
when viewing the evolution of a particular topic branch, because
merges into a topic branch tend to be only about adjusting to updated
upstream from time to time, and this option allows you to ignore the
individual commits brought in to your history by such a merge.

This resulted in a log that just showed the original 123456 commit and a merge commit, but I was able to filter out the merge commit by description (e.g. filter out any commit with description "Merge branch x into target"

Git - get last commit made on branch


xpath to YouTube Subscribers is not working

Question: I am working on a sheet to get the Subscriber Count of a Youtube Channel. The problem is the old paths are not working anymore and the new one does not seem to return anything.
Here is what I have tried:
"http://www.youtube.com/weargenius","//*[@id=\"c4-primary-header-contents\"]/div/div/div[2]/div/span/span[1]"
=IMPORTXML(I4,"//yt-formatted-string")
=IMPORTXML(I4,"//div[@class='style-scope ytd-c4-tabbed-header-renderer']")
=VALUE(INDEX(REGEXEXTRACT(LOWER(INDEX(REGEXEXTRACT(INDEX(IMPORTXML(A1,"//div[@class='primary-header-actions']"),1,1),"(Unsubscribe)([0-9kmKM.]+)"),1,2)),"([0-9,.]+)([km]?)"),,1) * SWITCH(INDEX(REGEXEXTRACT(LOWER(INDEX(REGEXEXTRACT(INDEX(IMPORTXML(A1,"//div[@class='primary-header-actions']"),1,1),"(Unsubscribe)([0-9kmKM.]+)"),1,2)),"([0-9,.]+)([km]?)"),,2),"k",1000,"m",1000000,1))

and many more solutions that did not work.
What I would like to accomplish is that we can get the subscriber account using google sheets from youtube profile page.
Comment: I4 is the link to any channel, fyi.
Answer: Use :
=IMPORTXML(I4;"//span[contains(@class,'subscriber')]")

Comment: Replace ";" with ","  since I'm based in Europe. EDIT : Nice !
Comment: Worked! Thank you!!
Answer: try:
=IFERROR(MID(QUERY(IMPORTXML("https://www.youtube.com/channel/"&A1,
 "//div[@class='primary-header-actions']"), "select Col1"), 31, 20), )

=IFERROR(MID(QUERY(IMPORTXML("https://www.youtube.com/channel/UCH58d6dGp6b0hisvkCh7sNg",
 "//div[@class='primary-header-actions']"), "select Col1"), 31, 20), )

https://stackoverflow.com/a/55064665/5632629


UIPickerView freezes UI when reloaded

Question: The ui of my app freezes when the index of the UIPickerView gets to 1 or the number of elements is 2. Im really confused because this was working then all the sudden its broken. Ive done some research and found it may be something to do with a thread. Can someone help me solve the issue with the UIPickerView?
// class implements UIPickerViewDelegate, UIPickerViewDataSource, UIGestureRecognizerDelegate

     @IBOutlet weak var planetPickerView: UIView!
     var planetPicker: UIPickerView!

View did load:
override func viewDidLoad() {
     super.viewDidLoad()
     //Other code not important
     configurePlanetPicker()
}

UIPickerView implementation: (skyBalls is an array of classes whit various data as getters)
 func configurePlanetPicker() {
        planetPicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: planetPickerView.frame.width, height: 70))
        planetPicker.delegate = self
        planetPicker.dataSource = self
        planetPicker.transform = CGAffineTransform(rotationAngle: CGFloat(-90 * (Double.pi/180)))
        planetPicker.frame = CGRect(x: -100, y: 0, width: planetPickerView.frame.width + 200, height: 70)
        planetPicker.showsSelectionIndicator = false
        planetPickerView.backgroundColor = .clear
        let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
        tap.delegate = self
        planetPicker.addGestureRecognizer(tap)
        planetPickerView.addSubview(planetPicker)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return skyBalls.count }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))

        let image = UIImageView(frame: CGRect(x: 15, y: 10, width: 40, height: 40))
        image.image = UIImage(named: "\(skyBalls[row].getImage().split(separator: ".")[0])")
        image.contentMode = .scaleAspectFit
        mainView.addSubview(image)

        let titleLbl = UILabel(frame: CGRect(x: 0, y: 50, width: 70, height: 20))
        titleLbl.text = skyBalls[row].getName()
        titleLbl.textColor = .white
        titleLbl.textAlignment = .center
        titleLbl.adjustsFontSizeToFitWidth = true
        mainView.addSubview(titleLbl)

        mainView.transform = CGAffineTransform(rotationAngle: 90 * CGFloat((Double.pi/180)))
        return mainView
    }

    @objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
        if tapRecognizer.state == .ended {
            let rowHeight = planetPicker.rowSize(forComponent: 0).height
            let selectedRowFrame = planetPicker.bounds.insetBy(dx: 0, dy: (planetPicker.frame.height - rowHeight) / 2)
            let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: planetPicker))
            if userTappedOnSelectedRow {
                let selectedRow = planetPicker.selectedRow(inComponent: 0)
                upgradePlanetName = skyBalls[selectedRow].getName()
                let settings = UIStoryboard(name: "PlanetUpgrade", bundle: .main).instantiateViewController(withIdentifier: "Upgrade") as! UpgradeViewController
                self.present(settings, animated: false)
            }
        }
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

I do reload the UIPickerView upon a button press that increases the size of the skyBalls array:
planetPicker.reloadAllComponents()

BUT the problem still occurs if planetPicker.reloadAllComponents() is entirely removed in all forms from the project.
I have tried restating my mac, iphone, and xcode, as well as deleting derived data. I cleaned the build folder and nothing seems to fix the issue.
Thank you in advance.
Comment: could you please highlight the line which has an issue? or what is the exact problem please share more about the issue.
Comment: @emrcftci sure thing. All of the buttons and views freeze when the app loads the second element in the picker view. It doesn't seem to crash but just sit there as the phone gets hot. I'm not quite sure what line has the issue. I tried to comment out the viewForRow method and replace it with a standard array of numbers and the issue still happened
Comment: what is the detail of `.getName()` function?
Comment: @emrcftci it returns a string of the planet name. So the first index would be "Sun".
Comment: please check @MoumenAlisawe 's answer
Comment: @emrcftci even with the entirety of the `planetPickerView.reloadComponents()`removed from the project it still freezes. It's not just when it reloads.
Comment: if you've removed the reload line, when UI freezes? Maybe you should share more detail about your issue. I saw things you've done inside of the `viewForRow` function, maybe these causes your problem.
Comment: @emrcftci well the UI freezes either way if the reload line is there or not. I've tried removing the entire `viewForRow` method and replacing it with the `titleForRow` method to test is it was the views. I still had the same result. I have stored restarting every device, Xcode, and deleted all the derived data. Nothing works.
Answer: Ok so I found out that it wasn't the UIpickerView's fault at all.
So after looking around I tried this:

1) Open "Breakpoint navigator"
2) tap '+' button and choose the "Exception Breakpoint" option

it then took me to the root of the problem witch was an array index out of bounds that for some reason wasn't crashing the app.
Answer: when you have to update your view
you must call .reloadAllComponents() always on the main thread  DispatchQueue.main.async should resolve the problem .
DispatchQueue.main.async {
    self.planetPickerView.reloadAllComponents()
}

UIPickerView freezes UI when reloaded


Nascer e por do sol em R

Question: Estou tentando criar um script que mostre o nascer e o por do sol com as latitudes definidas, mas o horário não está compatível. OBS: essa latitude corresponde ao horário de são paulo.
library(maptools)

library(dplyr)

dateInt <- c("2017-10-11","2017-10-01")

  lon <- -46.6821862
  lat <- -23.5977319
  timezone <- 'UTC+3'
  date <- dateInt[2]

  if (length(dateInt)==1) {
    span <- 1
  }else {
    span <- difftime(strptime(dateInt[1], format = "%Y-%m-%d")
                 ,strptime(dateInt[2], format = "%Y-%m-%d"),units="days")

    span <- as.numeric(span)
    span <- span
  }

  lon.lat <- matrix(c(lon, lat), nrow=1)

  day <- as.POSIXct(date, tz=timezone)
  sequence <- seq(from=day, length.out=span , by="days")

  #Getting datas
  sunrise <- sunriset(lon.lat, sequence, direction="sunrise", POSIXct.out=TRUE)
  sunset <- sunriset(lon.lat, sequence, direction="sunset", POSIXct.out=TRUE)
  solar_noon <- solarnoon(lon.lat, sequence, POSIXct.out=TRUE)
  day_length <- round(as.numeric(sunset$time-sunrise$time),2)

  r <- data.frame(Data=as.Date(sunrise$time),
              Nascer=format(sunrise$time, "%H:%M"),
              `Meio Dia`=format(solar_noon$time, "%H:%M"),
              Pôr=format(sunset$time, "%H:%M"),
              `Duração(Horas)` = day_length)

  #sorting dataframe by Data
  r <- r[order(r, decreasing = TRUE),]

  r <- data.frame(lapply(r, as.character), stringsAsFactors=FALSE)

  #Removing N/A
  r <- na.omit(r)

  r

Comment: Por que o horário não está compatível? Que hora deveria aparecer?
Comment: Sp é UTC -3, mas para o horário ficar realmente parecido, tenho que colocar UTC+3, mesmo assim, há o atraso entorno de 30 minutos.
Answer: library(suncalc)
library(dplyr)
lon <- -46.6821862
lat <- -23.5977319
timezone <- base::grep("Brazil", base::OlsonNames(), value = T)
# tz de SP = timezone[3]
# Sys.Date() = data de hoje
df <- data.frame(date = seq.Date(Sys.Date()-30, # Data de inicio
                                 Sys.Date(),    # Data final
                                 by = 1),       # Passo
                 lat = rep(lat, 31),  # 30+1
                 lon = rep(lon, 31))

df2 <- suncalc::getSunlightTimes(data = df,
                                 keep = c("sunrise", "sunset"),
                                 tz   = timezone[3]) %>%
  dplyr::rename("Nascer do sol" = sunrise,
                "Pôr do sol"    = sunset)

__
> df2
         date       lat       lon       Nascer do sol          Pôr do sol
1  2019-03-30 -23.59773 -46.68219 2019-03-30 06:15:15 2019-03-30 18:09:38
2  2019-03-31 -23.59773 -46.68219 2019-03-31 06:15:37 2019-03-31 18:08:39
3  2019-04-01 -23.59773 -46.68219 2019-04-01 06:15:59 2019-04-01 18:07:39
4  2019-04-02 -23.59773 -46.68219 2019-04-02 06:16:21 2019-04-02 18:06:40
5  2019-04-03 -23.59773 -46.68219 2019-04-03 06:16:44 2019-04-03 18:05:42
6  2019-04-04 -23.59773 -46.68219 2019-04-04 06:17:06 2019-04-04 18:04:43
7  2019-04-05 -23.59773 -46.68219 2019-04-05 06:17:28 2019-04-05 18:03:45
8  2019-04-06 -23.59773 -46.68219 2019-04-06 06:17:51 2019-04-06 18:02:48
9  2019-04-07 -23.59773 -46.68219 2019-04-07 06:18:13 2019-04-07 18:01:50
...

Nascer e por do sol em R


Custom sbt configuration with Intellij auto import

Question: I can't get the embedded sbt plugin (with auto import enabled) in Intellij (13.1) to recognize custom sbt configurations. I have the follow setup in my sbt build file:
<code>  lazy val EndToEndTest = config("e2e") extend (Test)

  private lazy val e2eSettings =
     inConfig(EndToEndTest)(Defaults.testSettings)

  lazy val root: Project = Project(
    id = "root",
    base = file(".")
  )
   .configs(EndToEndTest)
   .settings(e2eSettings)
</code>
The code works according to expectations in the sbt console. E.g I can write:
sbt e2e:test (and it will execute tests located in /src/e2e/scala)
The issue is that the directory /src/e2e/scala won't get registered as a source directory in Intellij. This makes it hard to use intellij to manage the tests. I can manually mark the directory as source but it gets reverted every time

I update my sbt files (auto import).
Do a manual update through the sbt tool window

Related:
Using the preconfigured configuration IntegrationTest works as expected but custom once don't.
Answer: According to sbt-idea documentation this can be done in your case by adding
<code>ideaExtraTestConfigurations := Seq(EndToEndTest)
</code>
to your project settings.
Comment: I'm not using the sbt-idea sbt plugin. Intellij comes with sbt support since version 13. Are you saying that Intellij is using the sbt-idea plugin under the hood?


Por que uma Stored Procedure gera resultados diferentes se executados no Workbench e no Java com JDBC

Question: Tenho uma Stored Procedure no MySQL que está funcionando normalmente quando executo a partir do Workbench, porém ao executar esse mesmo procedimento no Java/JBDC estou obtendo valores errados e diferentes dos obtidos no Workbench.
Minha Stored Procedure faz a contagem vários registros de outras tabelas e consolida todos os resultados na tabela destino. A parte do meu procedimento que está apresentando divergência segue abaixo:
CREATE DEFINER=`root`@`%` PROCEDURE `processa_iap`(IN data_movimento DATE)
BEGIN
    DECLARE dia_mov INT;
    DECLARE mes_mov INT;
    DECLARE ano_mov INT;

    SET dia_mov = DAY(data_movimento);
    SET mes_mov = MONTH(data_movimento);
    SET ano_mov = YEAR(data_movimento);

    INSERT INTO IAP_ATINGIDO(MES,ANO,PA,DEB)
    SELECT mes_mov 'MES', ano_mov 'ANO', A.CODPAC, COUNT(A.CODPAC)
        FROM ASSOCIADOS A, (SELECT DISTINCT CC.COD_ASSOC
            FROM CONTAS_CARTAO CC
            WHERE CC.ESTADO_CARTAO='Operativo' AND CC.COD_ASSOC IS NOT NULL
            AND CC.TITULARIDADE='TITULAR'
            AND CC.PRODUTO NOT LIKE '%Poupança%'
            AND CC.PRODUTO NOT LIKE '%Salário%'
            AND CC.PRODUTO NOT LIKE '%BNDES%') C
        WHERE A.COD=C.COD_ASSOC
        GROUP BY A.CODPAC
    ON DUPLICATE KEY UPDATE DEB=VALUES(DEB);
END

Código do método Java onde executo a Stored Procedure:
public void processaIAP() throws SQLException {
    try {
        sql = "{CALL processa_iap(?)}";
        CallableStatement cstm = connection.prepareCall(sql);

        Date data = buscaMenorDataImportacoes();
        cstm.setDate(1, data);

        cstm.execute();
        cstm.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

Notei que a diferença apresentada nos resultados entre as duas execuções corresponde com a ausência dos NOT LIKE na cláusula WHERE da subconsulta presente na Stored Procedure, ou seja, é como se quando eu executasse o procedimento no Java ele desconsiderasse as seguintes instruções SQL:
AND CC.PRODUTO NOT LIKE '%Poupança%'
AND CC.PRODUTO NOT LIKE '%Salário%'
AND CC.PRODUTO NOT LIKE '%BNDES%'

Tentei utilizando várias versões do conector MySQL para Java mas o problema persiste. Alguém já se deparou com problema parecido? Alguma solução?
Answer: Não sei o porquê, e se alguém tiver alguma ideia favor contribuir conosco, mas o problema estava na utilização em conjunto do comando de negação NOT e a utilização de algum caractere especial nas strings da consulta. Só descobri através de tentativa e erro. A solução para o meu problema foi a seguinte:
AND CC.PRODUTO NOT LIKE '%Poupan_a%'
AND CC.PRODUTO NOT LIKE '%Sal_rio%'
AND CC.PRODUTO NOT LIKE '%BNDES%'


From Fermat's Theorem to The Chinese Remainder Theorem

Question: Firstly, the question starts with Fermat's Theorem:

$5^{2017}$ (mod 7) (mod 11) (mod 13) = ?

I have computed all of them and the answer is (in order): (5, 3, 5).
Secondly, the question asks to compute the below problem using The Chinese Remainder Theorem:

$5^{2017}$ (mod 1001) = ? (while actually $7*11*13 = 1001$)

What I did is:

mod 7            mod 11            mod 13

$x$ =  $11*13$            $7*13$             $7*11$
$x \equiv 143 \;(\bmod\;7)$
$x \equiv 91 \;(\bmod\; 11)$
$x \equiv 77 \;(\bmod\; 13)$
Therefore:
$x \equiv 3 \;(\bmod\; 7)$
$x \equiv 3 \;(\bmod\; 11)$
$x \equiv 12 \;(\bmod\; 13)$
$x = (B1*X1*C1) + (B2*X2*C2) + (B3*X3*C3)$
Therefore:
$x = (143*3*5) + (91*3*3) + (77*12*5) = 7584$
So, where did I do a mistake?
Comment: Have you thought about what having 5 mod 7 and 5 mod 13 means ?
Comment: Do you know the Chinese remainder theorem?
Answer: 1)  Fermat's little theorem say that if $\gcd(5,p) = 1$ and $p $ is prime that $5^{p-1} \equiv 1 \pmod p$.
So $5^6\equiv 1 \pmod 7$ and $5^{10}\equiv 1 \pmod {11}$ and $5^{13}\equiv 1 \pmod {13}$.
So if $2107 = 6k + r$ then $5^{2017}=5^{6k+r}=(5^6)^k*5^r \equiv 1^k*5^r\equiv 5^r\pmod 7$.
So that this how you solve $5^{2017}\pmod {7}$.  Do the the same for $11,13$.
.....
So now you have $5^{2017}\equiv a \pmod 7$ and $5^{2017}\equiv b \pmod {11}$ and $5^{2017}\equiv c \pmod {11}$.
So the chinese remainder theorem says there is a single unique solution to $5^{2017}\equiv x \pmod {7*11*13}$ that satisfies $x \equiv a \pmod 7$ and $x \equiv b \pmod {11}$ and $c\equiv \pmod 13$.
And the chinese remainder shows you how to find it.
$7j + 13m =1$ has a solution. FInd it.
So $7bj + 11am = N$ will be so that $N\equiv 7bj + 11am \equiv 7bj +11bm \equiv b\pmod {11}$ and $N\equiv 7bj + 11am \equiv 7aj + 11am \equiv a \pmod 7$.
And
$77k + 13p= 1$ also has a solution.  Find it.
So $77ck + 13Np = M$ will be so that $M\equiv 91ck + 13cp \equiv c\pmod{13}$ while $M\equiv 77Nk + 13Np \equiv N \equiv a \pmod 7$ and $M\equiv N\equiv b \pmod {11}$.
So $5^{2017}\equiv M \pmod {1001}$
.....
So you have $5^{2017} \equiv 5 \pmod 7$ and $5^{2017}\equiv 3 \pmod 11$.
I figure that $2*11 - 3*7 = 1$
And so $2*11*5 - 3*7*3 = 47$ and
$47\equiv 2*11*5 - 3*7*3 \equiv 2*11*5- 3*7*5\pmod 7\equiv 5\pmod 7$.
And $47 \equiv 2*11*5 - 3*7*3 \equiv 2*11*3 - 3*7*3 \equiv 3\pmod {11}$.
....
Now do the same thing with  $47\pmod {77}$ and $5\pmod {13}$
Use $6*13 - 77 =1$.
To get $6*13*47 - 5*77 = 3281 = 278+3003 \equiv 278 \pmod{1001}$.
Answer: The mistake is that you forgot to take inverses. We want
$\quad \bmod 7\!:\ \ \ 1/(11\cdot 13)\equiv 1/3\equiv -6/3\equiv \color{#c00}{-2}$
$\quad \bmod 11\!:\,\ 1/(7\cdot 13)\equiv 1/3\equiv 12/3\equiv \color{#0a0}4$
$\quad \bmod 13\!:\!\,\ 1/(7\cdot 11)\equiv 1/(-1)\equiv \color{#90f}{-1}$
so $\,\ x\equiv 5\,\underbrace{(11\cdot 13)(\color{#c00}{-2})}_{\textstyle \equiv 1\pmod{\!7}}\ +\ 3\!\!\!\!\! \underbrace{(7\cdot 13)\,\color{#0a0} 4}_{\textstyle \equiv 1\pmod{\!11}}\!\!\!\! +\ 5\!\!\underbrace{(7\cdot 11)(\color{#90f}{-1})}_{\textstyle \equiv 1\pmod{\!13}}\! = -723 \equiv 278\pmod{\!1001}$

But it is much easier to solve the congruences two-at-a-time as below:
Note $\, x\equiv 5\pmod{\!7\ \&\ 13}\!\iff\! x\equiv 5\pmod{\!91}\,$ so $\,x = \color{#0a0}{5\! +\! 91k}\ $ by CCRT = constant case CRT.
so $\bmod \color{#c00}{11}\!:\,\ 3\equiv x\equiv \color{#0a0}{5 + 91}\,\color{#c00}k\equiv 5+3k\iff 3k\equiv -2\equiv 9\iff \color{#c00}{k\equiv 3}$
Thus we conclude $\,\ x = 5 + 91(\color{#c00}{3\!+\!11n}) =  \bbox[5px,border:1px solid #c00]{278 + 1001n}\ \,$  Took $1$ minute of mental arithmetic.


How to log each instance of a Class into different files with Nlog?

Question: I have a project where I am testing eight pieces of the same equipment at the same time. I need to be able to write to a log for each piece of equipment. I also need to have another log file that has system log messages. In the past I have written my own logging but would like to try Nlog. I wrote a simple test to see if this would work and I am not having much success. What I would like to do is have each instance of TempObject log into its own file. Currently the following code logs into each of the log files:
NLog.Config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="logfile" xsi:type="File" fileName="logfile.txt" />
    <target name="myObj1" xsi:type="File" fileName="myObj1.txt" />
    <target name="myObj2" xsi:type="File" fileName="myObj2.txt" />
    <target name="myObj3" xsi:type="File" fileName="myObj3.txt" />
    <target name="myObj4" xsi:type="File" fileName="myObj4.txt" />
    <target name="console" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
    <logger name="*" minlevel="Info" writeTo="myObj1" />
    <logger name="*" minlevel="Info" writeTo="myObj2" />
    <logger name="*" minlevel="Info" writeTo="myObj3" />
    <logger name="*" minlevel="Info" writeTo="myObj4" />
    <logger name="*" minlevel="Info" writeTo="console" />
  </rules>
</nlog>

MainWindow.xaml.cs
public partial class MainWindow : Window
{
  private static Logger logger = LogManager.GetCurrentClassLogger();

  private TempObject myObj1 = new TempObject(1);
  private TempObject myObj2 = new TempObject(2);
  private TempObject myObj3 = new TempObject(3);
  private TempObject myObj4 = new TempObject(4);

  public MainWindow()
  {
    InitializeComponent();
    logger.Info("this is the first log message");
    myObj1.LogMessage();
    myObj2.LogMessage();
    myObj3.LogMessage();
    myObj4.LogMessage();
    SetUpDisplay();
  }
}

TempObject.cs
public class TempObject
{
  private int myUUT;

  private static Logger logger = LogManager.GetCurrentClassLogger();

  public TempObject(int uutNumber)
  {
    myUUT = uutNumber;
  }

  public void LogMessage()
  {
    logger.Info("UUT" + myUUT);
  }
}

Comment: can you clarify -  using the current code you have given, all instances log into the same logfile.
Comment: Currently for each instance of TempObject the call logger.Info("UUT" + myUUT); will log into each of the following log files: logfile, myObj1, myObj2, myObj3 myObj4.  I would like myObj1 instance of TempObject to log into myObj1 log file only, myObj2 instance  of TempObject to log into myObj2 log file only, myObj3 instance  of TempObject to log into myObj3 log file only, myObj4 instance  of TempObject to log into myObj4 log file only.
Comment: hmm. as Nlog correctly only sets the filename in the config, this may be tedious. you could use the ReconfigExistingLoggers of Nlog, after changing the target, but this you have to call each time you have log statement (but this is manipulating a config file at runtime for wrong reasons)
Answer: I had to change the following in the TempObject and it works.
public class TempObject
{
  private int myUUT;

  private Logger myLogger;

  public TempObject(int uutNumber)
  {
    myUUT = uutNumber;
    string logString = "myObj" + myUUT;
    myLogger = LogManager.GetLogger(logString);
  }

  public void LogMessage(string msg)
  {
    myLogger.Info("UUT" + myUUT+ "|" + msg);
  }
}

and the rules section of the config file to:
<rules>
  <logger name="*" minlevel="Info" writeTo="logfile" />
  <logger name="myObj1" minlevel="Info" writeTo="myObj1" />
  <logger name="myObj2" minlevel="Info" writeTo="myObj2" />
  <logger name="myObj3" minlevel="Info" writeTo="myObj3" />
  <logger name="myObj4" minlevel="Info" writeTo="myObj4" />
  <logger name="*" minlevel="Info" writeTo="console" />
</rules>


Mudar de cor de uma Row quando expirar VB .Net

Question: Tenho uma base de dados com as seguintes tabelas: Data Emissão e Data Expira.
Então eu quero que, quando a data do Data expira for igual ou superior a Data Emissao, a row mude de cor para Vermelho e quando estiver faltando 1 mês para atingir a data mude de cor para Amarelo.

Meus codigos
Private Sub CadastroDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles CadastroDataGridView.CellFormatting
    If Me.CadastroDataGridView.Columns(e.ColumnIndex).Name = "DataGridViewTextBoxColumn15" Then
        If e.Value IsNot Nothing Then
            Dim dgvdate As Date = CDate(e.Value)
            If dgvdate < CDate(Now) Then
                e.CellStyle.BackColor = Color.Red
                e.FormattingApplied = True
            Else
                e.CellStyle.BackColor = Color.Green
                e.FormattingApplied = True
            End If

        End If
        End If
End Sub

Comment: Com as seguintes colunas não tabelas, certo?
Comment: Poste as Tabelas completas...
Comment: Por favor, mostre o seu código, saliente o que importa para a dúvida e diga o que já tentou.
Answer: Não testei, mas deve funcionar:
Dim data_addmes As Date = Date.Now.AddMonth(1)
Dim data_expira As Date = dgvRow.Cells("Data_expira").Value
Dim data_emissa As Data = dgvRow.Cells("Data_Emissao").Value

If data_addmes >= data_expira Then
    dgvRow.DefaultCellStyle.BackColor = Color.Yellow
Else If data_expira >= data_expira Then
   dgvRow.DefaultCellStyle.BackColor = Color.Red
End If

Comment: Poste seu código que poderei melhorar minha resposta


"No 'Access-Control-Allow-Origin' header is present" cakephp

Question: Bom dia pessoal
Estou fazendo uma aplicação com angular e cakePHP.
Estou tentando fazer uma requisição para o backend e a seguinte mensagem aparece no console:

XMLHttpRequest cannot load http://localhost:8765/api/v1/users/client.json?client_id=cliente&client_secret=segredo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

meu controller
.controller('loginCtrl', ['$scope', '$stateParams', '$http', '$location', function ($scope, $stateParams, $http, $location) {

$scope.fazerLogin = function(usuario){
    //console.log(usuario);
    //http://localhost:8765/api/v1/users/client.json?client_id=cliente&client_secret=segredo"
    var url = "";
    var cid = "cliente";
    var cs = "segredo";
    $http.post("http://localhost:8765/api/v1/users/client.json?client_id="+cid+"&client_secret="+cs).success(function(data){
        console.log(data);
    });

}

}])

meu php
<?php
public function beforeFilter()
{

   parent::beforeFilter();
           $this->response->header('Access-Control-Allow-Origin','*');
           $this->response->header('Access-Control-Allow-Methods','*');
           $this->response->header('Access-Control-Allow-Headers','X-Requested-With');
           $this->response->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
           $this->response->header('Access-Control-Max-Age','172800');
}
?>

Onde tenho que fazer o ajuste no meu php?
Answer: Olá!
O servidor não permite fazer requisições para outro domínio, além do atual. Deve-se dar permissão para isso, acrescentando o seguinte cabeçalho:
<?php
    header("Access-Control-Allow-Origin: *");
    ...
    ...
?>

Referência para mais detalhes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Answer: No endpoint do seu serviço adicione:
$this->response->header('Access-Control-Allow-Origin', '*');


scale_color_manual() not working

Question: I am trying to get scale_color_manual() to work in ggplot2 and I am not getting the colors.
I am following the example at this link
My dataset is df given by
structure(list(cond = structure(1:3, .Label = c("A", "B", "C"
), class = "factor"), yval = c(2, 2.5, 1.6)), .Names = c("cond",
"yval"), class = "data.frame", row.names = c(NA, -3L))

If I use the code in the example to make a bar plot, it works
ggplot(df, aes(x=cond, y=yval, fill=cond)) + geom_bar(stat="identity") +
    scale_fill_manual(values=c("red", "blue", "green"))

I changed the code to make a scatter-plot, I don't see the points in color now.
ggplot(df, aes(x=cond, y=yval)) + geom_point() +
    scale_color_manual(values=c("red", "blue", "green"))

This could be trivial, but I am having a hard time finding what I am doing wrong here.
Any help would be much appreciated!!
Thanks
Comment: you have not mapped any variable to colour in the aesthetic
Comment: You are right, thanks!
Answer: As per the commenter above, I need to map color to a variable, the following works
ggplot(df, aes(x=cond, y=yval, color = cond)) + geom_point() +
    scale_color_manual(values=c("red", "blue", "green"))

scale_color_manual() not working


How do I add menu items within a .install file

Question: I'm trying to build an intall profile that implements a number if features. I am running into some issues because although features allows me to require menus, it seems there is no way to also include the links (most of the link are simple aliases to add content or edit views). Is there a way to add menu items from within the install profile?
Answer: You can follow the example from the profiles/standard/standard.install file and use code like this inside your implementation of hook_install():
// Create a Home link in the main menu.
$item = array(
  'link_title' => st('Home'),
  'link_path' => '<front>',
  'menu_name' => 'main-menu',
);
menu_link_save($item);

Comment: Thanks! what if the menu is hierarchical, for instance I have a menu the has an events link, and under the events link is an add events link
Comment: You can pass `plid` as the parent link ID in your `$item`, so save 'Events' first, then save `Add Events` with a `plid` of the first item's `mlid` (menu link id, it's returned from `menu_link_save()`)