Fret Buzz on specific areas

Question: I have a Jackson Ke5Fr Kelly, I mainly used it on .09 string gauge with standadd tuning but last couple of months it was .10's in Whole-Step Down tuning. Now, I turned back to .09's and standard tuning but there are buzzes different places like, 12th,13th and 14th frets at high E and 9th at A and like 17th at B etc. small areas covering 1-3 frets.
I used "string as a straight edge" method and checked for bows at neck and it seems straight, string doesn't touch anywhere, neither they are too high. Tried to work out with bridge action, it didn't do much either, except maybe in extreme action it helped but almost at a unplayable height. What is causing this? Would it change after I use the strings a little bit more? I am really worried about it.
PS it happens with medium to high pick dynamics and a little bit on lower dynamics.
Comment: Since the string gauge is thicker I think you're just not fretting them hard enough. It's harder to do further up the neck. You have yet to perfect the pressure that needs to be applied on different parts of the fretboard so work on that :)
Comment: You get it wrong, it buzzes on thinner set. I was using 10s for last couple of months, now using 9s. I have been playing for almost 10 years I do not think strength or pick dynamics are the issue here.
Answer: Most fret buzzing is a result of the vibrating string contacting another fret as it vibrates in an oscillating arc.  There are several things that commonly cause this to happen.
Neck does not have enough relief or has a back bow.  The vibrating/oscillating string must clear all the frets between where it is fretted and the bridge.  If the neck is perfectly straight or back bowed, the string is likely to contact one of the frets between the fret you are pressing it against and the bridge. To correct this, tighten the truss rod until there is a slight relief in the neck to provide more clearance on the downstream frets when you fret a note.
To check the amount of relief, you can use one finger to press the string down against the first fret and another to press against one of the frets near where the neck joins the body and see how much clearance you have above the frets in between these two points.  If the string is touching any of the frets between the two you are holding it down on, you do not have sufficient relief. Pressing the string against frets on opposing ends of the fretboard, takes your bridge height adjustment out of the equation for this test.
Even if the strings are not touching any frets in this test, you still may not have enough relief if they are too close to one or more frets.  The string oscillates in an arc when you play it.  The harder you pick the string, the wider the arc.  Also, different gauge strings will have different oscillation patterns due to the tension required to bring them in tune. Less tension generally means a wider oscillation arc and therefore more relief is needed.
Check the relief on both the bass and treble side of the neck.  if there is relief on one side and a back bow on the other, that is a sign of a twisted neck  and a serious problem.
If the relief is sufficient, try adjusting the bridge height.  Your guitar is likely to have a bridge height adjustment for each string.  You mentioned in your question that you have made this adjustment.  Try it again after you are sure you have enough relief after truss rod adjustment.
Another less common but potential area where strings can end up too close to the frets is in the nut. Smaller diameter strings may sit farther down in the slot and the slot can deepen with wear and cause the strings to sit closer to the fret.  Nuts are not generally adjustably (temporary fixes with super glue notwithstanding) so if your nut slots become worn too deep, you will need to replace the nut.
Another common cause of fret buzz - is groves in some frets.  Steel strings against nickle frets will eventually cut grooves in the frets where the strings contact the frets.  This happens primarily on the unwound plain steel strings.  Also, bending strings when playing solos can act like a file and file the frets down so they lose height relative to the other frets.  If you get a buzz when playing notes on certain frets, check to see if that fret is worn or grooved under the offending string.  You can see the condition of the frets more easily if you use a magnifying glass.
One other thing than can cause fret buzz - is one or more frets may be too high, relative to the other frets.  This can happen if the fret works itself loose in the fret slot or was not seated correctly when installed.
You can check for high or uneven frets with a straightedge such as a ruler.  You need a straightedge long enough to cover at least 5 or more frets at a time - but not too long.  Place the straightedge against the frets at various places on the fretboard and on various frets.  The straightedge should evenly contact at least 5 frets at a time without rocking or see sawing.  As you slide the straightedge from the nut towards the body, if you encounter a fret that acts like a fulcrum and allows you to rock the straightedge from lower frets to higher frets like a see saw, then you have found a high fret which may need to be repaired.
Repairing a high fret may mean properly seating it in the groove on the fretboard by tapping it in (with the neck properly braced and possibly heating just the fret to soften any glue), and/or filing it with the correct size fret file and crowning it with the proper tool.  This type repair should be made by a professional.
If some of the frets are grooved or worn more than others, or if several frets are too high, it might be time for a fret job.  If uneven height frets are the main problem - a qualified luthier or guitar repair technician, using the proper fret files and fret levels, can file all the frets down and crown and level them so that all buzzing is eliminated.  Many well played guitars will need a fret job at some point in time and perhaps regularly (if played often enough).
Hopefully you will be able to determine the cause of your fret buzzing, and if it's any of the things mentioned above (besides an unlikely twisted neck) you should be able to solve the problem.
Good luck!
Comment: Thanks Cowboy :D, I'll check for grooves, action and relief again. And do you know how fast heat affects neck. Like being 5-10 minutes touching a radiatior could have made this. Because, it seems to me happened overnight and my genius dad leaned my axe on a heat radiator, very clever of him, luckily I found it right away but, still it was there like 5-10 mins.
Comment: @River  Hmmmm.  Leaning a guitar neck on a heat radiator is NOT a good idea.  But I'm sure your Dad did not know any better so cut him some slack - we all have those moments when we learn from our mistakes.  It's hard to say that damage occurred. But heat can do several things.  It can dry out the neck and cause it to warp or move,  It can shrink the wood in the fingerboard and cause the frets to come loose.  Check to see if the fingerboard is cupped.  Re-hydrating with humidifier might help but I recommend that you take your instrument to a professional for evaluation.
Answer: If you're getting buzz only at certain frets and on certain strings then the problem is probably that your frets aren't level.  This can happen because of fret wear, because the frets weren't properly leveled when the guitar was made, or because the neck has changed shape slightly over time.
You can diagnose the problem by using a short straightedge that covers the length of three frets.  You center it over one fret and see if the straightedge "rocks" a little, indicating a high fret.  You do this test with the strings on and at normal tension.  Stewart MacDonald and others make special straightedges for this purpose.
To fix the problem you can attempt to lightly file and recrown individual frets, but this takes skill and I don't advise you do it yourself.  You can easily end up over-filing frets and wrecking your neck.
Adjusting the truss rod is not usually the solution for your problem.  However, you can check to see if your neck relief is about right this way:  hold your high E string lightly to the fret at the first fret and the fret where the neck meets the body.  Look at the vertical distance between the string and the 12th fret.  Normally you expect it to be "almost touching" -- so that the distance is about as much as the width of your high E string.
Answer: Certain frets may be sticking out and they may need to be leveled off a little bit. I had the same problem in one or two spots on my bass and I took it to a shop where the guy leveled off those frets and no more problems.
Comment: Can it be detected by eyes? They look normal to me, but I don't know nothing about setting up guitars.
Comment: A rather vague answer, but, there's a way of detecting it. I can't specifically remember, but if you're like me and you're not familiar with how to do it, then definitely take it to a setup and repair person.
Comment: The worst thing is there is none around in my region.
Comment: There are videos on YouTube. One channel that I like is called Dave's world of guitar repairs and fun stuff. He shows you how to do it but, myself I would hesitate. If you have no other choice, then I suppose you might have to do it yourself. Its up to you, of course.
Comment: Thx, I'll check it out but still not sure what is the cause.

Fret Buzz on specific areas


tweaking django rest framework template

Question: I'm trying to tweak the login function of the code here -
{% block userlinks %}
    {% if user.is_authenticated %}
        {% optional_logout request user %}
    {% else %}
        {% optional_login request %}
    {% endif %}
{% endblock %}

I want to have it, when logged in, to also display a value before "logout" as "dashboard" and have that reference another URL that's represented in django.
so it would look like this in the dropdown -
USER -
    - dashboard
    - logout

I thought it would be a matter of adding a line in the code like so -
{% block userlinks %}
    {% if user.is_authenticated %}
        Dashboard
        {% optional_logout request user %}
    {% else %}
        {% optional_login request %}
    {% endif %}
{% endblock %}

This ends up making a separate value in the nav-bar however which I don't want.  How do I get it inline?
Answer: Below is the code that should work for you:
{% block userlinks %}
    {% if user.is_authenticated %}

                {{ user }}

Dashboard

{% optional_logout request %}

    {% else %}

{% optional_login request %}

    {% endif %}
{% endblock %}

Please give me a feedback.
EDIT:
The link should be in a list item. I added the
 tags.
Comment: you put me in the right direction.  I had to do some reverse engineering to get it and had to make a custom template tag using the code in the rest_framework templatetags.
Answer: /myapp/templatetags/internal_extras.py
from __future__ import unicode_literals, absolute_import
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import QueryDict
from django.utils import six
from django.utils.encoding import iri_to_uri
from django.utils.html import escape
from django.utils.safestring import SafeData, mark_safe
from django.utils.html import smart_urlquote
from rest_framework.compat import urlparse, force_text
import re

register = template.Library()

@register.simple_tag
def my_logout(request, user):
    """
    Include a logout snippet if REST framework's logout view is in the URLconf.
    """
    try:
        logout_url = reverse('rest_framework:logout')
    except NoReverseMatch:
        return '
{user}
'.format(user=user)

    snippet = """

            {user}

Dashboard

Log out

"""

    return snippet.format(user=user, href=logout_url, next=escape(request.path))

Then in my HTML I had the following -
{% load internal_extras %}

{% if user.is_authenticated %}
    {% my_logout request user %}
{% else %}
    {% optional_login request %}

That did it.

tweaking django rest framework template


Storing data in a session, can only seem to store 1 piece of data at a time

Question: I am trying to allow the user to create a shortlist, however I add one thing the shortlist, and it overwrites the whatever else is in there, what am I doing wrong?
function validate_add_cart_item($id){

    $this->db->select('candidates.candidate_id, candidates.first_name, candidates.surname, candidates.DOB, candidates.talent, candidates.location, candidates.availability_order, candidates.availability, candidates.availability_comments, candidate_assets.url, candidate_assets.asset_size')
    ->from('candidates')
    ->join('candidate_assets', 'candidate_assets.candidates_candidate_id = candidates.candidate_id', 'left')
    ->where('candidate_assets.asset_size', 'small')
    ->where('candidate_assets.asset_type', 'image')
    ->where('candidates.candidate_id', (int)$id)
    ->limit(1)
    ->order_by('candidates.availability_order', 'DESC');

    $query = $this->db->get();

    //die($this->db->last_query());
    // Check if a row has been found
    if($query->num_rows > 0 ){
        foreach ($query->result() as $row)
        {
            $data = array(
                'id'      => $id,
                'name'    => $row->first_name." ".$row->surname,
                'location' => $row->location,
                'talent' => $row->talent,
                'image'  => $row->url
            );

            $this->session->set_userdata('shortlist', array($data));
            return TRUE;
        }

    // Nothing found! Return FALSE!
    } else {
        return FALSE;
    }

Answer: $this->session->set_userdata('shortlist', array($data));

doesn't append $data to shortlist but overwrites it with an array that has one element: the current data in $data.
You probably (untested) want:
if($query->num_rows > 0 ) {
    $data = array();
    foreach ($query->result() as $row)
    {
        // append the new "record" to the array $data
        $data[] = array(
            'id'      => $id,
            'name'    => $row->first_name." ".$row->surname,
            'location' => $row->location,
            'talent' => $row->talent,
            'image'  => $row->url
        );
    }
    $this->session->set_userdata('shortlist', $data);
    return TRUE;
}
else {
    ...

Comment: I have tried this but it still overwrites the shortlist in the session if I ma adding people 1 by 1
Answer:    foreach(...){
      // ...
     $this->session->set_userdata('shortlist', array($data));
   }

You are overwriting your previous userdata several times. Instead of this you should create an array, and call set_userdata once.
  $udata = array();
  foreach(...){
    // ...
    $udata []= $data;
  }
  $this->session->set_userdata('shortlist', $udata);

edit:
And your query returns only one row, you probably want to update your array, not overwrite it, so something like this:
  $udata = $this->session->get_userdata('shortlist');
  foreach(...){
    // ...
    $udata []= $data;
  }
  $this->session->set_userdata('shortlist', $udata);

Comment: Be aware that the session data is stored in a cookie and can only contain a very limited amount of data.


Exception thrown starting SOLR in Sunspot gem

Question: I just installed sunspot gem (latest version) including the embedded solr into my application. When I run "rake sunspot:solr:start" it says the server started, but then I can't connect and I think it dies quietly - I cannot find the log file for it.
So my first question is:  Where is the solr log file supposed to be? I checked my app log directory and there was no log there other than the standard development log.
So I did some searching, and ran rake sunspot:solr:run - it throws this error:
<code>java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.arrayFormat(Ljava/lang/String;[Ljava/lang/Object;)Lorg/slf4j/helpers/FormattingTuple
</code>
So I did some more searching and everything indicates a classpath issue, but I can't figure out how to fix it, or why it's happening.
Here's the questions that are related:
Exception thrown while using logback/slf4j
Exception thrown while using logback/slf4j/java
I don't have any other entries on the classpath:

$ java -version java version "1.7.0_45" Java(TM) SE Runtime
  Environment (build 1.7.0_45-b18) Java HotSpot(TM) 64-Bit Server VM
  (build 24.45-b08, mixed mode)

<code>$ echo $CLASSPATH
</code>
Prints nothing
and trying to run solr directly didn't give me any more information on where the problem lies:
<code>$ java -jar start.jar -verbose:CLASS --dry-run
/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/bin/java -verbose:CLASS -Djetty.home=/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr -cp /Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-xml-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/servlet-api-3.0.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-http-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-continuation-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-server-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-security-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-servlet-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-webapp-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-deploy-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-util-8.1.8.v20121106.jar:/Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/lib/jetty-io-8.1.8.v20121106.jar org.eclipse.jetty.xml.XmlConfiguration /var/folders/dm/f2j60c396xl3s7y0jt_mgmvw0000gn/T/start1361372392858055131.properties /Users//.rvm/gems/ruby-2.0.0-p247/gems/sunspot_solr-2.1.0/solr/etc/jetty.xml
</code>
Could anyone suggest how to recover from this error?
Answer: I found the issue, and it was indeed a classpath problem. Luckily I had an older version of SOLR where it was reporting slf4j was bound twice (but still starting).
So this lead me to where the JAR's were, so I've moved these JAR's out of /Library/Java/Extensions directory which had a copy of them (as well as the lib directory for SOLR I think).


Identity for complex inner product spaces

Question: Suppose $V$ is a complex inner product space. I want to prove that for any $x,y \in V$, we have the following identities:
$\langle x, y\rangle = \frac{1}{2\pi} \int_{0}^{2\pi}  \|x + e^{it}y\|^2  e^{it}dt$
$\langle x, y\rangle = \frac{1}{N} \sum_{k=1}^{N}  \|x + e^\frac{2\pi ik}{N}y\|^2 e^\frac{2\pi ik}{N},$ where $N \geq 3.$
I tried to use the polarization identity (and I still thnk is is the way to approach the problem), but I couldn't figure out the trick, so help would be highly appreciated.
Comment: This must be a typo (missing $i$ in the exponents). And there's a typo in the first identity ($dx$ instead of $dt$).
Comment: Just a minor thing: the first identity you wrote should be $||x+e^{it}y||^2=||x||^2+||y||^2+e^{-it}\langle x,y\rangle + e^{it}\overline{\langle x,y\rangle}$
Comment: Thank you, this one solves the integral form. In the "discrete" case, we would get  $∥x+e^\frac{2πk}{N}y∥^2=∥x∥^2 + ∥y∥^2 + 2e^\frac{2πk}{N}$ and I cannot see how this would yield the required result.
Comment: You are right about both, My typo was $dx$ instead of $dt$, and the missing $i$ typo was already in the exercise I got (but I can see how this fixes the exercise and the solution is then straightforward). Also, I can see why this fails for $N=2$. Thanks!
Comment: Oops, my bad :)
Answer: \begin{align}
&\frac{1}{N} \sum_{k=1}^{N}\|x + e^\frac{2\pi ik}{N}y\|^2 e^\frac{2\pi ik}{N}\\
&=\frac{1}{N} \sum_{k=1}^{N}\left(\|x\|^2+\|e^\frac{2\pi ik}{N}y\|^2+\langle x, e^\frac{2\pi ik}{N} y\rangle+\langle e^\frac{2\pi ik}{N} y,x\rangle\right)e^\frac{2\pi ik}{N}\\
&=\frac{1}{N} \sum_{k=1}^{N}(\|x\|^2+\|y\|^2)e^\frac{2\pi ik}{N}+\frac1N\sum_{k=1}^{N}\langle x, y\rangle e^\frac{-2\pi ik}{N}e^\frac{2\pi ik}{N}+\frac1N\sum_{k=1}^{N}\langle y, x\rangle e^\frac{2\pi ik}{N}e^\frac{2\pi ik}{N}\\
&=0+\frac1N\sum_{k=1}^{N}\langle x, y\rangle+0\\
&=\langle x, y\rangle
\end{align}
Some observations:

The sum identity is a generalization of polarization identity in complex Hilbert space ($n=4$).
$$\langle x,y\rangle ={\frac {1}{4}}\left(\|x+y\|^{2}-\|x-y\|^{2}+i\|x+iy\|^{2}-i\|x-iy\|^{2}\right)$$
$\{\frac{2\pi k}n:k,1,\dots,N\}$ is a partition of $[0,2\pi]$, so the sum is a Riemann sum of the integral.
$$\frac{1}{N} \sum_{k=1}^{N}  \|x + e^\frac{2\pi ik}{N}y\|^2 e^\frac{2\pi ik}{N}\longrightarrow\frac{1}{2\pi} \int_{0}^{2\pi}  \|x + e^{it}y\|^2  e^{it}dt$$
The integral is path integral of $\|x+zy\|^2$ on the circle $|z|=1$.
$$\int_{0}^{2\pi} \|x + e^{it}y\|^2  ie^{it}dt=\oint_{|z|=1} \|x + zy\|^2  dz$$


Twitter abraham twitteroauth constantly asking for permission

Question: I'm using the abraham / twitteroauth to allow users to login through via their Twitter accounts. At the moment I can create the link, have them go to the link, authorize permission for the app to use their details, return to the site and save their user_id and access tokens as expected.
This is fine and works well, however when a user then logs out (clears sessions, cookies, etc) and then clicks the "sign in with Twitter" button, it then asks them for their permission again even though the app is already registered in their apps and has that permission. Should it not just sign them in again?
Login link generation using Code Igniter so ignore syntax
$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);

$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => RETURN_WEBSITE_URL));

$twitterOauth = array(
    "oauth_token" => $request_token['oauth_token'],
    "oauth_token_secret" => $request_token['oauth_token_secret'],
);

$this->session->set_userdata($twitterOauth);
$this->twitterLoginUrl = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));

Return function
$request_token = [];
$request_token['oauth_token'] = $this->session->userdata('oauth_token');;
$request_token['oauth_token_secret'] = $this->session->userdata('oauth_token_secret');;

if (isset($_REQUEST['oauth_token']) && $request_token['oauth_token'] !== $_REQUEST['oauth_token']) {
    die("This isn't right.");
}

$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));

What am I doing incorrectly?
Answer: Twitter API supports two sign in flows. 3-legged authorization and Sign in with Twitter. The main difference between them is Sign in with Twitter will automatically redirect back to the application if the user has previously authorized the application.
The technical difference is that 3-legged uses GET oauth/authorize while Sign in with Twitter uses GET oauth/authenticate.
Your code implements GET oauth/authorize so yes it is expected that the users have to authorize every time. If you do not want returning users to authorize you have to switch to GET oauth/authenticate.


Cannot import matplotlib.pyplot in python 3

Question: I followed the instructions to install matplotlib for python 3 from here: How to install matplotlib with Python3.2
But I get an ImportError, which I have not been able to resolve, when importing pyplot:
>>> import matplotlib
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python3.2/dist-packages/matplotlib-1.4.x-py3.2-linux-i686.egg/matplotlib/pyplot.py", line 98, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
 File "/usr/local/lib/python3.2/dist-packages/matplotlib-1.4.x-py3.2-linux-i686.egg/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
 File "/usr/local/lib/python3.2/dist-packages/matplotlib-1.4.x-py3.2-linux-i686.egg/matplotlib/backends/backend_gtk3agg.py", line 1, in <module>
   import cairo
ImportError: No module named cairo

I have tried matplotlib.use('Agg') and matplotlib.use('GTK') before import pyplot, but they don't make a difference.
Any help would be much appreciated, thanks.
Edit:

This shows that I have all the required dependencies.
jack@hostname:~/installs/matplotlib$ sudo python3 setup.py --keywords
============================================================================
Edit setup.cfg to change the build options

BUILDING MATPLOTLIB
        matplotlib: yes [1.4.x]
            python: yes [3.2.3 (default, Apr 10 2013, 05:29:11)  [GCC
                    4.6.3]]
          platform: yes [linux2]

REQUIRED DEPENDENCIES AND EXTENSIONS
             numpy: yes [version 1.6.1]
          dateutil: yes [using dateutil version 2.1]
           tornado: yes [using tornado version 3.1]
         pyparsing: yes [using pyparsing version 2.0.0]
             pycxx: yes [Official versions of PyCXX are not compatible
                    with Python 3.x.  Using local copy]
            libagg: yes [pkg-config information for 'libagg' could not
                    be found. Using local copy.]
          freetype: yes [version 14.0.8]
               png: yes [version 1.2.46]

OPTIONAL SUBPACKAGES
       sample_data: yes [installing]
          toolkits: yes [installing]
             tests: yes [using nose version 1.3.0]

OPTIONAL BACKEND EXTENSIONS
            macosx: no  [Mac OS-X only]
            qt4agg: no  [PyQt4 not found]
           gtk3agg: yes [gtk3agg backend does not work on Python 3]
         gtk3cairo: no  [Requires cairo to be installed.]
            gtkagg: no  [Requires pygtk]
             tkagg: yes [version version not identified]
             wxagg: no  [requires wxPython]
               gtk: no  [Requires pygtk]
               agg: yes [installing]
             cairo: no  [cairo not found]
         windowing: no  [Microsoft Windows only]

OPTIONAL LATEX DEPENDENCIES
            dvipng: yes [version 1.14]
       ghostscript: yes [version 9.05]
             latex: yes [version 3.1415926]
           pdftops: yes [version 0.18.4]

Comment: How did you install matplotlib?  With a package manager such as apt-get, or from setup.py?
Comment: You probably haven't installed [pycairo](https://pypi.python.org/pypi/pycairo)
Comment: "...they don't make a difference" because you still get *an* `ImportError` or *this particular* `ImportError`?
Comment: @KenHill I cloned from Github, then did 'sudo python3 setup.py build', then 'sudo python3 setup.py install'
Comment: @mata I installed python-cairo, then rebuilt and reinstalled Is that the same?
Comment: @BrianCain It's always this particular ImportError with 'cairo'.
Comment: @jackyu - you mean you compiled pycairo yourself, or did you install the package `python-cairo` using your distro's package system? The latter probably won't work, you also need to compile it yourself.
Comment: @mata How do I make pycairo visible to matplotlib installation?  I have cloned pycairo from github (git clone git://git.cairographics.org/git/pycairo) and installed it via 'python3 setup.py install', but matplotlib still doesn't see it (please see Edit above).
Comment: and pycairo installed without error (can you import cairo in python)? check that it was installed to a directory on `sys.path`, and check the access permissions, installing stuff using sudo sometimes messes these up, maybe you need to chmod it to 0755...
Comment: 'import cairo' throws no errors, but confusingly 'print(cairo)' points to '__init__.py' inside a directory created by the installation of 'python3-cairo'. The installation of 'pycairo' doesn't seem to create a 'pycairo' directory.
Answer: Problem Cause In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There is Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
I resolve this issue following ways I assume you have installed the pip matplotlib, there is a directory in you root called ~ /. matplotlib. Create a file called matplotlibrc there and following code
~ / .matplotlib / Matplotlibrc
backend: TkAgg


Left/Right Limit Proof

Question: Using a limit from the left and limit from the right argument, how can I see whether a limit exists for the following:
$$\lim_{x \rightarrow 0} \frac{\sin(x)}{|x|}$$
I think this limit does not exist by this argument, but how would I demonstrate that?
Comment: What do you think the limits from the left and right are?
Comment: I think -1 from the left and 1 from the right. Is it simple enough to say those are unequal, thus a limit DNE?
Comment: @PaulGerard Yes. If the limit exists, it has to be unique.
Comment: Those are right, and yes, it is. The key here is that $\sin x$ is very close to $x$ when $x$ is near $0$, so the fraction is very much like $\dfrac{x}{|x|}$.
Comment: ah i see, thanks again!
Answer: $$\lim_{x\to 0^+}\frac{\sin x}{|x|}=\lim_{x\to 0^+}\frac{\sin x}{x}=1$$
$$\lim_{x\to 0^-}\frac{\sin x}{|x|}=\lim_{x\to 0^-}\frac{\sin x}{-x}=-1$$
The above, of course, based in
$$\lim_{x\to 0}\frac{\sin x}{ x}=1$$

Left/Right Limit Proof


Criar um meio para não repetir meu código

Question: Como posso criar um meio de simplificar o código abaixo para que não se repitam algumas coisas?
Gostaria que o meu código "Gera usuário" não se repetisse ao longo do IF.
Como devo proceder?
if (txtNome.Text == ""){
    MessageBox.Show("Digite o nome do usuário.", "Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    txtNome.Focus();
}else if (txtEmail.Text == ""){
    MessageBox.Show("Digite o seu endereço de e-mail.", "Mail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    txtEmail.Focus();
}else if (txtSenha.Text == ""){
    MessageBox.Show("Digite a sua senha.", "Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    txtSenha.Focus();
}else if (RdAdministrador.Checked == true){
    string resposta="xxxxx";
    string res = Interaction.InputBox("Você é realmente um administrador?\nDigite a resposta para a pergunta secreta.", "Pergunta Secreta");
    if (res == resposta){
        MessageBox.Show("Acesso concedido!");
        //Gera usuário ********************************************************************************************
        int i = txtNome.Text.LastIndexOf(" "); //Carrega na variavel o valor do ultimo espaço para pegar sobrenome.

        string nome = txtNome.Text.Substring(0, 1); //Carrega primeira letra do nome digitado.

        string sobrenome = txtNome.Text.Substring(i + 1); //Carrega ultimo sobrenome completo.

        Random GeraRandom = new Random(); //Gera numero randomico para adicionar ao usuário.
        int numero = GeraRandom.Next(1, 99);

        txtUsuario.Text = sobrenome + nome + numero;
        //**********************************************************************************************************
    }else{
        MessageBox.Show("Acesso negado, Adeus!", "Good-bye", MessageBoxButtons.OK,MessageBoxIcon.Stop);
    }
}else{
    //Gera usuário ********************************************************************************************
    int i = txtNome.Text.LastIndexOf(" "); //Carrega na variavel o valor do ultimo espaço para pegar sobrenome.

    string nome = txtNome.Text.Substring(0, 1); //Carrega primeira letra do nome digitado.

    string sobrenome = txtNome.Text.Substring(i + 1); //Carrega ultimo sobrenome completo.

    Random GeraRandom = new Random(); //Gera numero randomico para adicionar ao usuário.
    int numero = GeraRandom.Next(1, 99);

    txtUsuario.Text = sobrenome + nome + numero;
    //**
}

Answer: Crie classes.
Faça programação-orientada-a-objetos, criando classes com métodos, funções, variáveis, etc...
Você pode criar uma classe "gerador_de_usuario" e dentro dela botar uma função gerar_usuário(string nome, string email, string senha), assim ficará mais organizado.
Answer: Você poderia criar uma função gerar_usuario() e dentro desta função colocar o código de criar usuários e depois só chamar a função onde você precisar.
Comment: Gerei uma função public void GeraUsuário () e funcionou. Era fácil assim e eu não me lembrava... obrigado Flavio!!!
Answer: Sugestão:
Faça as validações na model.
No seu código, você precisará apenas de um try catch.
Exemplo:
Modelo
if(String.IsNullOrEmpty(this.Name)){throw new Exception("O nome é obrigatório")}

Já no código apresentado:
try{...}catch(Exception ex){...}


Determining the direction of a significant Spearman's Rho Correlation

Question: I have conducted Spearman's Rho tests with two ordinal variables (one with 4 possible answers and the other with 6). I have obtained a statistically significant correlation between the two. My question is, how can I graphically (or some other way) determine which answer of each correlate together - as a scatterplot would not work with my data (since it is not scale).
Answer: Let's create some toy data in R:
> set.seed(1)
> nn <- 60
> xx <- floor(4*runif(nn))+1
> yy <- pmin(6,pmax(1,xx+rnorm(nn,0,3)))
>
> Q1 <- ordered(letters[xx],levels=letters[1:4])
> Q2 <- ordered(LETTERS[yy],levels=LETTERS[1:6])

Here is a Spearman's rho correlation test:
> cor.test(as.numeric(Q1),as.numeric(Q2),method="spearman")

        Spearman's rank correlation rho

data:  as.numeric(Q1) and as.numeric(Q2)
S = 24468, p-value = 0.01264
alternative hypothesis: true rho is not equal to 0
sample estimates:
      rho
0.3201582

Warnmeldung:
In cor.test.default(as.numeric(Q1), as.numeric(Q2), method = "spearman") :
  Kann exakten p-Wert bei Bindungen nicht berechnen

Now, one way of understanding this would be a simple incidence table:
> table(Q1,Q2)
   Q2
Q1   A  B  C  D  E  F
  a 10  1  1  0  1  0
  b  6  2  1  1  2  5
  c  4  3  3  4  1  1
  d  3  2  2  1  4  2

Alternatively, you can certainly plot your data. Simply transform them to the underlying integers and add a little jittering:
> delta <- 0.2
> plot(as.numeric(Q1)+runif(nn,-delta,delta),as.numeric(Q2)+runif(nn,-delta,delta),pch=19,xlab="Q1",ylab="Q2",xaxt="n",yaxt="n")
> axis(1,1:4,levels(Q1))
> axis(2,1:6,levels(Q2),las=2)

Alternatively, create a sunflowerplot:
sunflowerplot(Q1,Q2,xaxt="n",yaxt="n")
axis(1,1:4,levels(Q1))
axis(2,1:6,levels(Q2),las=2)

(To be honest, I'm not too keen on the default sunflowerplot, but you can customize the colors and the widths of the segments rather well, see ?sunflowerplot.)
Comment: Possibly. I have zero idea about SPSS. Maybe someone will come along and add an SPSS answer, or you could post a question [at StackOverflow in the "SPSS" tag](http://stackoverflow.com/questions/tagged/spss), pointing back to this thread.
Comment: Thanks for this, but would I be able to do this in spss?
Answer: Sometimes people overlook the convenient way in which a Chi-square procedure can answer questions like this.  Specifically, each of your 24 cells' Chi-square residuals -- or better yet, standardized residuals -- will tell to what extent the count of observations in that cell is disproportionate, given the entire bivariate distribution.  In SPSS:
cross Q1 by Q2 / stat chi /cells count sresid.

Standardized residuals beyond +/- 2 are typically the ones that signal notably disproportionate counts (although this is only a rule of thumb).  You'll probably be most interested in values >2 since you want to know which pairs of answers tend to co-occur.


Find $x>0$ for which the integral value $\int_0^{\sqrt {x}} \sin (\frac{2\pi t}{t+2}) dt$ is the largest

Question:
Find $x>0$ for which the integral value of $$\int_0^{\sqrt {x}} \sin \left(\frac{2\pi t}{t+2}\right) dt$$ is the largest.

 My try:
Let: $$f(x)=\int_0^{\sqrt {x}} \sin \left(\frac{2\pi t}{t+2}\right) dt$$ and $$F'(t)=\sin \left(\frac{2\pi t}{t+2}\right) dt$$
Then: $$f(x)=F(\sqrt {x})-F(0)$$
$$f'(x)=\frac{F'(\sqrt {x})}{2\sqrt {x}}-F'(0)\cdot 0=\frac{F'(x)}{2\sqrt {x}}=\frac{\sin \left(\frac{2\pi \sqrt {x}}{\sqrt {x}+2}\right)}{2\sqrt {x}}$$In this moment I am wanting to find $x$ for which $f'(x)=0$ and $f'$ changes the sign because it is a maximum for $f$. However I have a sine and I don't know how to do it in the simplest way, because the study of all ranges of sine variation is a terrible calculation. Can you help me?
Comment: In the last expression, replace $\sqrt{x}$ by $y$, say, and analyse the corresponding function of $y$ in $(0,\infty)$. It looks doable.
Comment: @ViktorGlombik yes, but when I calculate only $f'(x)=0$ I don't know if in this $x$ is maximum or minimum
Comment: I am getting infinite values.
Comment: @AjayMishra [WolframAlpha says otherwise](https://www.wolframalpha.com/input/?i=extrema+Si(2+π+(sqrt(x)+%2B+2))+-+Si(4+π)+from+x+%3D+0+to+100).
Comment: I didn't get that at all.
Answer: Given function, $$ f(x) = \int_0^{\sqrt{x}} \sin\bigg( \cfrac{2 \pi t}{t + 2} \bigg) dt $$
On differentiating, $$f'(x) = \cfrac{1}{2 \sqrt{x} }  \sin\bigg( \cfrac{2 \pi \sqrt{x}}{\sqrt{x} + 2} \bigg)$$For stationary points, $f'(x) = 0$. Here, in order to satisfy the condition, $$x = \bigg( \cfrac{2n}{2-n} \bigg)^2 $$
Where $ n \ne 0 $ and $ \in \mathbb I$ . But, remember at these values of $x$, there is stationary points, in order to find the maxima you can plug these values in $f'(x)$ and use first derivative test to find that. Can you do this from now?
Answer: You did almost half of the solution
After using $f'(x)=0$ we get
$$\sin \bigg(\frac{2\pi \sqrt x}{\sqrt x +2}\bigg)=0$$
Which yields
$$\frac{2\pi \sqrt x}{\sqrt x +2}=n\pi$$
or
$$2\sqrt x=n(\sqrt x+2)$$
By rearranging one can see that $x$ must be an integer in order to satisfy above equality because $n$ is integer
And this equation satisfies only when
$$x=0,4$$ for some $n\in Z$
But as $x>0$
Thus,
The only solution is
$$x=\boxed{4}$$
Comment: Where it was stated that $x$ must be integer?
Comment: It is not stated it's obtained in the solution because n is integer , so if you take any integral values of X which is not perfect square then equations won't satisfy


What is the reference edf for generalized additive models?

Question: From the summary of my fitted generalized additve model (gam) I see two edfs. The first edf is the model edf and second is the reference edf.
However, for AIC estimation, the reference edf is used. But what is the reason behind that?
As model is estimated using the edf, why are we using reference edf?
This is a sample R code:
set.seed(123)
library(mgcv)
x1=runif(100)
x2=runif(100)
y=exp(x1*pi) + x2^3 + rnorm(100)
M = gam(y~s(x1)+s(x2), method="REML")
summary(M)
  # AIC that takes the reference edf as edf!
-2*logLik.gam(M) + 2*(sum(M$edf2)+1) == AIC(M)
[1] TRUE

```

Answer: It's effective degrees of freedom for the smooth that is used in the test of the null hypothesis $\text{H}_0: f_j(x_{ji}) = \mathbf{0}$ (that the function is a constant 0 function).
There are at least three definitions of the effective degrees of freedom for a smooth term (see $edf, $edf1, and $edf2 components in a fitted GAM object). These represent different views on the complexity of the smooth, with the reference EDF being one view that is useful in tests (I believe this is $edf1). $edf2 is an EDF that is corrected for having estimated the smoothing parameters, and $edf is the standard definition of EDF.


mysql join two tables, count and sum alias

Question: I have query
SELECT p. * , COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id )
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30

It returns me this data which is correct
 id poll_id caption voteCount
 1  1   32  1
 2  1   256 1
 3  1   512 0

Now I need to count that alias voteCount, so for this example it would be 1+1+0=2.. And return it as another alias. How could I do it? I must use only 1 query, and I do not have rights to edit database. I have tried examples from
MySQL Join two tables count and sum from second table
MySQL query, COUNT and SUM with two joined tables
and couple more
but no luck..
Answer: Wrap another query around it?
SELECT id, poll_id, SUM(voteCount) AS votecount
FROM ( ... your query here ... ) As subquery
GROUP BY poll_id

Comment: Thanks this works but I need to get other results too. I have accepted M Khalid Junaid answer as it's perfect for me.
Answer: You can use a cross join to your same query by calculation sum of the count column
SELECT t1.*,t2.totalvoteCount FROM (
SELECT p. * , COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id )
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30
) t1
CROSS JOIN (
SELECT SUM(voteCount) totalvoteCount
FROM (
SELECT  p.id,COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id )
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30
) t
) t2

Output would be as follows
id poll_id caption voteCount   totalvoteCount
 1  1       32          1        2
 2  1       256         1        2
 3  1       512         0        2

Answer: In your example voteCount represents the count for each group. If you want the count across all groups then you can omit the group by clause (which is legal if your select only consists of a count).
SELECT COUNT(r.poll_option_id)
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON (r.poll_option_id = p.id)
WHERE p.poll_id =1

Or
SELECT p. * , COUNT( r.poll_option_id ) AS voteCount,
    (SELECT COUNT(r.poll_option_id)
    FROM poll_options AS p
    LEFT JOIN poll_responses AS r ON (r.poll_option_id = p.id)
    WHERE p.poll_id =1) totalVoteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id )
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30


Tamanho de vetor em C

Question: Sou novo na linguagem C e estou obtendo problemas para determinar o tamanho de vetores do tipo struct.
Exemplo. Tenho uma estrutura do tipo categoria com três tipos de variáveis 1 int e 2 char.
#include <stdio.h>
#include <stdlib.h>

struct categoria_st{
    char nome_categ[25];
    int num_subcateg;
    char subcateg_st
};

Agora, eu pretendo criar um vetor dinâmico do tipo struct categorias_st através de uma pergunta dentro da função main. Pensei em algo do tipo:
int main(){
struct categoria_st cat;
int n_categ;

   printf("Quantas categorias queres adicionar?\n");
    scanf("%d", &n_categ);
    return 0;

}

Contudo, eu não sei como realizar isso na linguagem C.
Answer: #include <stdio.h>
#include <stdlib.h>

struct categoria_st{
  char nome_categ[25];
  int num_subcateg;
  char subcateg_st;
}

int main(){
  int n_categ;
  //primeiro pedir ao utilizador o numero de categorias
  printf("Quantas categorias queres adicionar?\n");
  scanf("%d", &n_categ);

  //neste momento já podes declarar a variável do tipo da estrutura definida
  //com o valor pretendido pelo utilizador
  struct categoria_st category[n_categ];

  return 0;

}

Inicialmente é criada uma estrutura chamada categoria_st, constituída por 3 variáveis nome_categ, num_subcateg, subcateg_st.
No main é declarada uma variável n_categ do tipo inteiro para guardar o tamanho das categorias a inserir.
Esse valor é guardado no endereço da variável n_categ através do scanf().
De seguida é então declarado um array da estrutura chamada category com o tamanho inserido pelo utilizador.
Comment: poderia explicar o que seu código faz? como ele responde a pergunta? textos ajudam na compreensão.
Comment: Tentei explicar melhor em texto o que tinha no código por comentários... Penso que aqui o que o utilizador pretendia era inicializar um array da estrutura definida inicialmente com um tamanho indicado por o utilizador, e foi isso que coloquei no código... @ErlonCharles
Comment: Alguns pontos a mais são pertinentes para melhorar esta resposta: (i) Arrays de tamanho variável (VLAs, em inglês), só são obrigatórias na especificação de [C99](https://www.dii.uchile.cl/~daespino/files/Iso_C_1999_definition.pdf). Em especificações mais antigas não há previsão para isso na linguagem e, em especificações mais novas, essa funcionalidade é **opcional**. Isso significa que os compiladores podem deixar de aceitar esse comportamento, se hoje o aceitam; (ii) há, também, como resolver o problema utilizando alocação dinâmica de memória, que é a solução mais utilizada
Answer:
Não sou a melhor pessoa para responder, mas estou aprendendo com isso.

Abaixo passo a passo de um exemplo que estava testando no repl.it
Primeiro criamos a struct aqui o identificador é s_produtos
struct s_produtos
{
  int codigo;
  char nome[20];
};

Definimos duas variáveis do tipo int
// Recebera o valor informado pelo usuário
int qnt = 0;
// A cada loop guardara a posição no qual sera adicionado
// o produto
int posicao = 0;

Lê a entrada do teclado e armazena o valor informado em qnt
printf("Quantas produtos deseja adicionar?:");
scanf(" %d", &qnt);

Criamos a variável protudos do tipo s_produtos e definimos seu tamanho com o valor de qnt
struct s_produtos produtos[qnt];

Fazemos o loop e é pedido ao usuário informar os dados.
for(posicao; posicao < qnt; posicao++) {
  printf("\n");
  printf("Informe o código:");
  scanf("%d", &produtos[posicao].codigo);
  flush_in();// Limpa o teclado
  printf("Informe o nome:");
  // Usei gets pois scanf para no espaço e não pega a linha toda, ex:
  // Leite em Pó
  // Só retorna: Leite
  gets(produtos[posicao].nome);

}

A função flush_in encontrei no SOpt pois scanf(" %d", &produtos[posicao].codigo); não estava funcionando.
void flush_in() {
    int ch;
    do {
        ch = fgetc(stdin)
    } while (ch != EOF && ch != '\n');
}

Abaixo exibimos os registros na tela
// Armazena o tamanho total do vetor
int total = sizeof(produtos)/sizeof(produtos[0]);
printf("\n\n");
printf("+--------- PRODUTOS ---------+\n");
for(int i = 0; i < total; i++) {
  printf("%d - %s\n", produtos[i].codigo, produtos[i].nome);
}
printf("+----------------------------+\n");

Podes ver funcionando em repl.it.

Referência

Limpeza do buffer do teclado após scanf
Answer: Acredito que as soluções anteriormente propostas funcionem nos maiores compiladores atualmente (testei apenas com gcc 11.2.0), mas VLAs (Variable-Length Arrays, em tradução livre Vetores de Tamanho Variável) só são obrigatórios na especificação C99. Seu suporte desde C11 é opcional e, portanto, pode haver compiladores que não implementam essa funcionalidade e mesmo os que o fazem podem deixar de fazer.
Uma solução diferente daquelas e que deve funcionar em qualquer compilador C é a que utiliza alocação dinâmica de memória. Ela se baseia em, como o nome sugere, reservar novos espaços na memória (heap), à medida que necessário.
Segue o código exemplo:
#include <stdio.h>
#include <stdlib.h> // malloc / calloc

// É sempre válido definir um limite para a quantidade de elementos que você
// quer armazenar em memória, especialmente quando esse valor vem do usuário,
// de forma a evitar potenciais problemas devido ao mal gerenciamento de
// memória. Para mais informações: https://pt.wikipedia.org/wiki/Aloca%C3%A7%C3%A3o_din%C3%A2mica_de_mem%C3%B3ria_em_C#Problemas
#define MAX_N_CATEG 10

// Usamos `typedef` para dar um nome ao nosso tipo `struct categoria_st`. Por
// acaso eu defini esse nome como `categoria_st`, mas poderia ter usado qualquer
// outro que não fosse uma palavra reservada da linguagem
typedef struct categoria_st {
  char nome_categ[25];
  int num_subcateg;
  char subcateg_st;
} categoria_st;

int main() {
  int n_categ = 0;
  categoria_st *cat; // Ponteiro para `categoria_st`

  // Para evitar problemas, garantimos que `n_categ`:
  //   - É positivo
  //   - É menor ou igual que `MAX_N_CATEG`
  while (n_categ <= 0 || n_categ > MAX_N_CATEG) {
    printf("Quantas categorias queres adicionar? Escolha um valor entre 1 e %d (0 para sair)\n", MAX_N_CATEG);
    scanf("%d", &n_categ);

    // Damos ao usuário uma forma de sair do programa sem prosseguir
    if (n_categ == 0) {
      return 0;
    }
  }

  // Esta é a segunda linha mais relevante do código. Aqui acontece a alocação
  // dinâmica de memória. A função `calloc` pede ao Sistema Operacional uma
  // quantidade de memória livre com espaço suficiente para armazenar `n_categ`
  // elementos do tipo `categoria_st`. Após recebida essa memória, ela é
  // inicializada com `0`. Podemos entender essa segunda etapa como uma
  // "limpeza" do conteúdo anterior naquele espaço de memória que, para o nosso
  // programa, era "lixo" (desnecessário, não fazia sentido).
  //
  // Outro ponto importante é o início da expressão do lado direito da
  // atribuição, `(categoria_st *)`. Esta expressão é usada para fazer uma
  // conversão explícita de tipos. A função `calloc` retorna o tipo `void *`,
  // um ponteiro para `void`. Em poucas palavras, um ponteiro para `void` é,
  // essencialmente, um ponteiro para um endereço de memória específico, sem
  // informação de tipo, e que pode ser atribuído a qualquer tipo de ponteiro.
  // Ao realizar a conversão explícita estamos tirando qualquer margem de dúvida
  // do compilador sobre nossa intenção com essa atribuição: nós queremos um
  // ponteiro para uma região da memória que vai armazenar dados do tipo
  // `categoria_st`.
  //
  // Uma opção diferente seria usar a função `malloc`, com sintaxe similar:
  //   cat = (categoria_st *)malloc(n_categ * sizeof(categoria_st));
  // Note que para a função `malloc` é passado apenas um argumento com o tamanho
  // total de memória desejado. Outra diferença é que a função `malloc` não
  // "limpa" a memória reservada para a nossa variável.
  cat = (categoria_st *)calloc(n_categ, sizeof(categoria_st));

  // Checamos se a memória foi armazenada e entregue ao nosso programa com
  // sucesso. Caso contrário, `cat` terá o valor `NULL`, uma macro definida
  // em diversos cabeçalhos da linguagem, entre eles `stdio.h` e `stdlib.h`,
  // cujo valor, em C, é, normalmente, `((void *)0)` ou `0`. De qualquer forma,
  // seu valor é avaliado como `falso`.
  // Para mais informações sobre `NULL`: https://en.cppreference.com/w/c/types/NULL
  if (!cat) {
    printf("Houve um erro ao reservar memória para as categorias.\n");
    return 1;
  }

  // Aqui vem sua lógica. Você pode usar o operador `[]` pra acessar "posições"
  // diferentes dentro de `cat` de forma análoga a um vetor.
  //
  // Em https://pt.stackoverflow.com/a/91368/76558 há uma comparação bem
  // completa sobre ponteiros e vetores, expondo semelhanças e diferenças.
  for (int i = 0; i < n_categ; ++i) {
    cat[i].num_subcateg = i;
  }

  // Esta é **a linha mais relevante do código**. Um erro muito comum e um
  // grande causador de problemas em códigos com alocação dinâmica de memória
  // é não liberar a memória anteriormente reservada. No limite, isso pode levar
  // a uma falha por falta de memória disponível para o programa ou mesmo a
  // falta de memória para o Sistema Operacional, dependendo do tipo de programa
  // em questão. Liberar memória reservada é imprescindível.
  //
  // Neste caso, como sabemos que, se o programa chegar aqui, `cat` estará
  // apontando para um bloco válido de memória, não inclui a validação. Porém,
  // é boa prática checar se o seu ponteiro aponta para um bloco de memória
  // válido antes de liberá-lo. Isso pode ser feito com:
  //
  //   if (cat) {
  //     free(cat);
  //   }
  //
  // Outro ponto importante é não liberar o mesmo bloco de memória duas vezes.
  // Isso levará a um erro em tempo de execução.
  free(cat);

  return 0;
}

Incluí a maior parte da explicação como comentário no código, mas vou deixar as fontes inclusas aqui para mais fácil referência:

Informações gerais sobre alocação dinâmica de memória em C
Informações sobre NULL em C
Vetores vs Ponteiros em C

Tamanho de vetor em C


Data augmentation step in Krizhevsky et al. paper

Question: In the paper Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "Imagenet classification with deep convolutional neural networks." Advances in neural information processing systems. 2012., section 4.1, the authors describe their data  augmentation process. They say they  increased the size of the training set by a factor of 2048. Does this mean they trained on a total of 2048 × 1.2 millions images?
Moreover, I don't quite follow this:

At test time, the network makes a prediction by extracting five 224 ×
  224 patches (the four corner patches and the center patch) as well as
  their horizontal reflections (hence ten patches in all), and averaging
  the predictions made by the network's softmax layer on the ten
  patches.

What do they mean they extracted five 224 × 224 patches (corner, center and horizontal)? And why does it result in ten patches in total?
Thank you!
Answer:
They say they increased the size of the training set by a factor of 2048. Does this mean they trained on a total of 2024 X 1.2 millions images?

Yes, in the paper:

The first form of data augmentation consists of generating image translations and horizontal reflections. We do this by extracting random 224x224 patches (and their horizontal reflections) from the 256x256 images and training our network on these extracted patches

They are generating those extra patches 'on the fly' from the original images, said here:

In our implementation, the transformed images are generated in Python code on the CPU while the GPU is training on the previous batch of images. So these data augmentation schemes are, in effect, computationally free.

What do they mean they extracted five 224 × 224 patches (corner, center and horizontal)? And why does it result in ten patches in total?

The original images have size 256x256, so they are getting a patch by cropping the original picture on the upper left corner with a size 224x224. Same thing for upper right, lower left, lower right and center. So that's making 5 patches. And for each of those patch they are mirroring the picture, so they get 5 more patches. Total 10, and then they take the average prediction.
Comment: Thank you! To clarify, in testing to predict 1 image,  it will average over 10 patches of size 224X224.
Comment: Yes, that's correct
Answer: I think they've trained only on 1.2M images. Here is why:
Even if they could get 0.001s per forward and backward pass (with 1 Titan X and cuDNN), it would take this much time to train on 2048*1.28M images for 90 epochs with mini-batch SGD:
0.001*2048*1280000*90/60/60/24 = ~ 2730 days = ~ 7.5 years
Comment: This is an interesting observation. In your opinion, what do the authors mean with the 2048 factor.
Comment: Good question - for them.
Comment: Now in 2018, I went with the same problem, it would take many years to complete the training. The reason I'm here now is to verify that and this does help. Thank you
Answer: They are actually training on 1.2 million * 2048 training images.

We do this by extracting random 224 × 224 patches (and their horizontal reflections) from the
  256×256 images

For each training image of size 256x256, if you extract patches of size 224x224, you can get up to 1024 224x224 patches from the image ((256-224)*(256-224)). And for each such patch you take a horizontal reflection. In total 2048 patches from a single image.


werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'articles' with values ['page']. Did you mean 'static' instead?

Question: I have issues with a Jinja Template im trying to work on and need some advice, I keep gettign the error
werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'articles' with values ['page']. Did you mean 'static' instead?
here is the jinja template:

                    {% if blogs.has_prev %}

                            Previous

                    {% endif %}

                    {% for page_num in blogs.iter_pages() %}
                        {% if page_num %}
                            {% if page_num != blogs.page %}

                                    {{ page_num }}

                            {% else %}

                                    {{ page_num }}

                            {% endif %}
                        {% else %}

                                …

                        {% endif %}
                    {% endfor %}

                    {% if blogs.has_next %}

                            Next

                    {% endif %}

and here is the flask route im pulling from:
@blogs_blueprint.route("/articles", methods=["GET"])
@blogs_blueprint.route("/articles/<int:page>", methods=["GET"])
def articles(page=1):
   per_page = 6
   blog_list = Blog.query.order_by(desc(Blog.date_created)).paginate(page=page, per_page=per_page, error_out=False)
   current_year = datetime.now().year
   return render_template("articles.html", blogs=blog_list, year=current_year)
   ```

Answer: Usually an error like that occurs when the flask app doesn't know about that route.
If you have a blueprint you have to remember to register it with your flask app
from . import blog # assuming the blueprint is in blog.py
app.register_blueprint(blog.blogs_blueprint)


ICalendar and Outlook opeing as node For Add to Cal Module Even After Clearing Caches

Question: I installed the Add to cal module and enabled it.
Created a View using with fields or Event Date,Location and Title.
Thus when I added Event Date fields to the View and While Configuring i Choosed Formatter to Add to Cal.
The Add to Cal Works fine For Google and Yahoo calendar But When I choose The ICalendar or Outlook Option , corresponding node file gets open eg:- [website name]/node/207/field_date1/addtocal.ics but doesnt downloads the ics file.
I tried Clearing the Cache Varnish Cache as it hosted on the Acquia.com and also the Performance cache but that seems to not work.
Answer: I'm a maintainer of the Add To Cal module. It turns out that this is in fact a bug, which we're patching right now.
Until the patch is released, you can fix the issue by downloading and enabling the Entity module on your site. The patch will add this as a dependency to Add To Cal.
Here's the issue on drupal.org: https://www.drupal.org/node/1744684#comment-9056553
EDIT: The 1.x-dev version now includes this bug fix, and it will be included in the beta4 release.
Answer: Loking at the above problem, I thought maybe that's Add to Cal module problem, but it was poor configuration problem from my side. I reviewed the configuration and then tried following :

Go to Your content type (in my case Event).
Then choose manage display tab.
Choose the date field and change the formatter to Add to Cal
Use subsequent available fields to be inserted into the XXX.ical file which gets downloaded.

thanks..!


Baseline values unequal across two treatments in a repeated measures design. A question about controlling for baseline values in lme

Question: I have data on a repeated measures study with measurements on various outcomes taken at 0,6 and 12 weeks. An issue I have run into is that baseline values for various outcomes are not similar between treatments
even though individuals were randomly assigned to the two treatment groups. I made a mistake earlier where I did not randomize based on outcomes, whats done is done.
I realize that mixed effects model or an ANCOVA can allow for analysis in-spite of baseline differences. I have used mixed effect model to analyze my data.
Here is my question: as I understand, in a mixed effect model the use of random intercept for each participant in the study (time | subject) takes care of different baseline values of outcome for a given set of participants.
This is what my main effect model looks like
<code>outcome_a ~ age + sex + treatment + time + time * treatment + (time | subject)
</code>
Where 'outcome_a' has a higher mean baseline value in treatment 'a' as compared to treatment 'b'
What I am wondering is, is there way to have a random intercepts set in such a way that outcome_a random intercepts are set higher just for treatment 'a' as compared to treatment 'b' random intercepts.
Would this account for
a) differences in baseline across groups (treatment 'a' having higher mean value for outcomes as compared to treatment 'b'), and as well as
b) general differences in baseline within all participants?
And if yes, how would one go about setting up such a model?
I hope I am clear with this, please let me know if there are any questions.
Comment: If you just want a random intercept, then `(1 | subject)` already takes care of that. `(time | subject)` is like saying there is a baseline effect *and* subjects responds differently to the effect of time. As for random intercepts 'set higher' for one treatment than the other, how does this differ from a fixed effect for `treatment`?
Comment: @FransRodenburg I see. I understand this better now. Thanks.
Answer: Check the paper by Stephen Senn on baseline imbalances between treatments.
Moreover, because you have the main effect of treatment in your model, you already account for treatment differences at baseline. That is, that the outcome has a different mean for treatment 'a' and for treatment 'b' at baseline.


Instance States and media player

Question: I'm writing a simple app where activity A has a song playing. When a button is pressed, the media player pauses and activity B opens. When the user goes back to activity A, the mediaplayer is supposed to resume (from where it left off). My question is, what happens when you press the back button on activity B? I know activity B will be killed but is onResume from activity A loaded? Where do I give instruction to resume?
Comment: yes `onResume()` in Activity A will be called. As weill `onStart()` in Activity A
Answer: onResume  method will be called when a activity is resumed.

It seems you have to read Activity Lifecycle before any kind of android programming
Comment: I have mediaplayer.start(); in my onResume function and nothing happens when I hit the back button from activity b.  Why is this?
Answer: My code looks as follows
public class Homework extends Activity {

final MediaPlayer mediaplayer = new MediaPlayer();
int media_length;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_homework);

    setContentView(R.layout.activity_homework);
    AssetFileDescriptor afd;
    try {
        afd = getAssets().openFd("rev.mp3");
        mediaplayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
        mediaplayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mediaplayer.start();
    Button next = (Button) findViewById(R.id.homeworkContinue);
    final Intent openCloser = new Intent(this, EndActivity.class);
    next.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            mediaplayer.pause();
            media_length = mediaplayer.getCurrentPosition();
            startActivity(openCloser);

        }

    });
}

public void onResume(Bundle savedInstanceState){
    super.onResume();
    mediaplayer.seekTo(media_length);
    mediaplayer.start();
}

}
Comment: what is the provblem you are facing?
Comment: Basically when I hit the back button from activity b it loads back into this activity and doesn't play anything.

Instance States and media player


ANOVA for non-normal heterogenous unequally replicated data

Question: I need some advice on how to proceed with my data analysis. I have 3 groups (Archaea, Bacteria and Eukarya). Each group has unequal number of individual species (70, 651, and 244 respectively). Each specie was given 7 different treatments (A, B, C, D, E, F, and G) and I counted the number of domains (you can call it 'y').
Now the problems are: Counts for treatment A are extremely high compared to counts of other treatments. Treatment G has the lowest counts. Other treatments have more or less similar counts. Data is non-normal, does not have homogenous variances, unequally replicated and any help would be appreciated.

Which test should I use?
Any transformation?
Comment: Please tell us what you are trying to find out. What is your research question(s)? What hypotheses?
Answer: Some of your questions about how to respond to violations of anova assumptions may be answered by this flow chart .
However, more important may be that you look into multi-level modeling, a.k.a. hierarchical linear modeling or nested modeling.  This is because you have species nested within groups.
Answer: One option is to use a permutation test.  If you are testing whether the treatments have an effect then you could permute observations within each species and compare the resulting statistic of interest from the various permutations to the original data.  Note that this is testing that within each species the distribution (shape, mean, and variance) is identical between the treatments, but could differ between species.  If your hypothesis is different than this (as Peter mentioned we need details to be of more help) then you would need a different test.


Jquery Validation and Messages

Question: I'm trying to get an error message to show when my fields are missing input. Once both are filled in I want a success message to show in place of #error.
Not sure why I'm not getting any message currently.

$("input[type='button']").click(function() {
  $("form").validate({
    rules: {
      username: "required"
    },
    messages: {
      username: "please enter a name"
    }
  });
  alert("Submitted");
});

<form>

    Username:
    <input type="text" name="username" id="username">

    Password:
    <input type="password" name="pw" id="pw">

    <input type="button" value="Submit">

</form>
Answer: What about this ?
$("input[type='button']").click(function() {

    if($("#username").val()==""){
        $("#error").html("Please enter a name");
        return;
    }
    if($("#pw").val()==""){
        $("#error").html("Password required");
        return;
    }
    alert("Submitted");
});

Comment: That totally worked! If I want to add the success message would it be an else after the ifs?
Comment: nope.. instead of «alert("Submitted");» : «$("#error").html("Submitted!");»
Comment: NOTE... That I totally skipped what could be defined has field validation ( elem.validate() ) that you didn't show the script. This just checks for empty fields.
Comment: Thanks again ! That works like a charm! I had done this in pure JS but needed to be modified to jQuery for full credit. Total noob with javascript, any tutorials or resources you'd recommend to a beginner?
Comment: Yeah just empty fields for now is fine
Comment: Look for W3C tutorials about jQuery... They are'nt always as complete as we would wish... But for the Basics it's ok.

Jquery Validation and Messages


One time db scrub with .install file

Question: I need to scrub a production db to replace paths in the body field. Being a production database, it needs to happen in a time-sensitive, well-documented way with the solution frozen in code. I'd assume that a .install file would be the best way to do this.
What would a one time install script look like to search the database for "http://mysite.com" and replace with "https://www.mysite.com" in the default body field?
Answer: I typically do things like this outside of modules, and instead use a drush script.
The script itself, would go something like

Go into maintenance mode
Do an EntityFieldQuery to get my nids.
Loop through each nid, and
Load the node, and make an entity metadata wrapper
Do the search and replace on the fields
Save the node
Exit maintenance mode

Before and after running the script, I usually do a drush sql-dump.  You can even combine all of this into a single script
#!/bin/bash

drush variable-set -y --always-set maintenance_mode 1
drush sql-dump --result-file=~/db/before.sql
drush scr path/to/my/script.php
drush sql-dump --result-file=~/db/after.sql
drush variable-delete -y --exact maintenance_mode

By doing a drush script, you can really ensure that the task runs when you want it to, and you aren't bound by execution time limits.  I also find it easier to debug.
That said, you should just be able to use Pathologic to rewrite the URLs.  Install/enable it, and add it to your text formats, and configure to do the path fixups.
Comment: excellent. Already using pathologic to filter on input for all content going forward, just need to scrub old content.

One time db scrub with .install file


Calculating entropy of a binary matrix

Question: Given a matrix whose entries consist of only 1's and 0's, I would like to come up with a measure of how "ordered" the matrix is, in some sense.  This exact question was posed here:
Measuring entropy/ information/ patterns of a 2d binary matrix
in which the top-rated answer posted by whuber provided what I'm looking for, except that I didn't understand one key detail.  Referring to his answer, he writes: 'Let's measure this randomness with their base-2 entropy. For $a_1$, the sequence of these entropies is $(1.92, 1.5, 1.58, 1.0)$.  Let's call this the "profile" of $a_1$.'
Unfortunately, I've tried but failed to come up with the same entropy values, so I'd appreciate it if I could get some help on how to arrive at those numbers.
Comment: I'd just like to tack on a point of interest; whuber and Cosmo Harrigan have provided excellent answers to this question but I would also encourage you to reframe this as a graph problem. Graph entropy has quite a bit of literature about this and approaches the exact same problem from a different viewpoint: imagine that this matrix defines the connections between nodes. This may make it a little bit easier to understand. For reference, here's a link that discusses this.

http://www.visualab.org/index.php/what-is-an-entropy-of-graph-is-it-related-to-concept-of-entropy-in-information-theory
Comment: Did you find a solution?
Answer: The results you are referring to can be replicated using the following code:
https://github.com/cosmoharrigan/matrix-entropy
This code generates the visualizations and includes the calculation of the "profile" (a list of the entropies) of the set of scaled filtered matrices. Note that the specific entropy values have been updated in the original answer.

Calculating entropy of a binary matrix


nhibernate insert question - have id but not entity object

Question: Using NHibernate I need to insert an entity into a database that has a child entity. Example:
<code>public class Reservation
{
    public int Id { get; set; }
    public Service Service { get; set; }
}

public class Service
{
    public int Id { get; set; }
}
</code>
I need to create a new Reservation and insert it. However, when constructing the Reservation for insertion, I don't have the Service entity, but I do have the Service's Id value. Is there a way to insert my reservation without fetching the Service first?
Answer: You can use NHibernate's Load method.  This will create a proxy for the Service object, but it will not actually hit the database.  See this blog post for the difference between load and get.
Comment: Dude. This is gonna help us so much! We have ReportingQuery to select without Entity. Now we can Update. NICE!


What does this Apache SOLR error mean?

Question: From the log (set as "error"):
SearchApiException while optimizing Solr server local solr server: "0" Status: Request failed: request timed out in SearchApiSolrConnection->checkResponse() (line 541 of /var/www/domainname/sites/all/modules/contrib/search_api_solr/includes/solr_connection.inc).
What does this error message mean?
Comment: Is your solr server up and running?
Comment: Yes. Every 15 minutes 1000 new items are being indexed. So usually the log message every 15 min is: Indexed 1000 items for index ITEM NAME. But then this came up instead. It's not a warning or a notice, it's a "real" error.
Comment: Does this [stackoverflow post](http://stackoverflow.com/questions/19557476/timing-out-a-query-in-solr) help?
Answer: The error means exactly what it says:

Request failed: request timed out

The connection between your Drupal server and Solr server timed out.
If the servers are geographically far from one another, you might consider moving them closer together to reduce latency. Your Solr or Drupal server may also need more resources.
Both are things you'll need to incrementally test (preferably in an identical staging environment) until you've worked out where the bottleneck is and how you can overcome it

What does this Apache SOLR error mean?


If I play C1, F1, G1 - will F1 and G1 together cause dissonance or sound bad(to most people)?

Question: If i play C1, F1, G1 at the same time:
• C1 & F1 = Perfect 4th
• C1 & G1 = Perfect 5th
● What about F1 & G1 at the same time?

Would these sound bad together?  (to most people)
What is their relationship?
Comment: What did you think when you tried it? On what instrument/s?
Comment: Do you really mean octave 1? That's the lowest. If these were played in octave 4 or 5 the sound will be very different.
Answer: Generally speaking C-F-G is known as a "sus4" chord. Historically it would be considered dissonant, but in modern music, especially jazz and rock/pop it's a very standard chord that would not bother the typical listener. In fact, it often has a very pleasing effect.
Playing F and G together, out of context, would most likely be perceived as dissonant.
The relationship between F and G is a "major second". As with the sus4 chord, the interval itself is dissonant by historical definition, but is frequent in more modern music and is not heard as harsh.
There is a caveat to all this. Playing C1-F1-G1 would sound "muddy", at best, on many instruments. When notes that are relatively close together are played simultaneously in a low register, they tend to clash a great deal. However, C4-F4-G4, for example, would have a better sound.

The "to most people" part of the question is unanswerable. What sounds good or bad is influenced by too many factors -- cultural background and exposure to music, especially.


UINavigationBar back button title is hidden when the bar title is too long in iOS7

Question: I have a problem and can't solve it. I'll try to describe the issue, so:
when the title of the UINavigationBar is not so long - the situation is like this:

but if the title of the bar contains more characters - it hides the title of the back button as u can see on the next screenshot:

Is it a standard UINavigationBar behaviour in iOS7? May be there are some ways to solve this? Anyway in iOS6 the situation is much better - there I can't find any problem like this.

Comment: imho - it's okay and try to believe to Apple decisions about user experience. And if back button don't have any property about that - try to use custom back button looks same as default.
Comment: `[[UIBarButtonItem alloc]initWithCustomView:yourView]`
Answer: Simple fix:
Create one view with label and set that view as a title view to the navigation controller
// creating title view
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    // Adding label with custom frame
    UILabel *labelForTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];

    [labelForTitle setCenter:titleView.center];
    [labelForTitle setText:@"sfdfagd ggjhdgfjhadsgfjasgdhfgasdjfgajsdgfjashgdjhfasjdfsadjgfhsadghf"];

    [titleView addSubview:labelForTitle];

     // setting title view for the navigation controller.
    [self.navigationItem setTitleView:titleView];

output will be like this :


Proving An Asymptotic Relation Needed to Answer a Probability Problem

Question: I am working on understanding problem 3.4.13 from Durrett's Probability Theory and Examples. I found a solution online that relies on the following relationship:
$$
\sum\limits_{j=1}^n j^{2-\beta}\sim \frac{n^{3-\beta}}{3-\beta}.
$$
I have no idea how you show something like this.
Could anyone give some help?
Thank you.
Answer: $\sum_{j=1}^n j^{2-\beta}$ is a Riemann sum for $\int_0^n x^{2-\beta} dx$, which is equal to the right side you have given. (Specifically it is the right hand sum with $h=1$.) You can then use the error estimate for the rectangle rule to prove that the difference is of lower order than $n^{3-\beta}$.
Answer: We can approximate sums with integrals. If $f$ is an increasing function, then
$$
\int_{s=a-1}^{b} f(s)\ ds \le \sum_{i=a}^{b} f(i) \le \int_{s=a}^{b+1} f(s)\ ds.
$$
If $f$ is a decreasing function, then
$$
\int_{s=a}^{b+1} f(s)\ ds \le \sum_{i=a}^{b} f(i) \le \int_{s=a-1}^{b} f(s)\ ds.
$$
The notation $\sim$ means that the ratio of the left side and the right side tends to $1$ as $n$ goes to infinity.


Indo de um ponto para outro

Question: Com os seguintes fatos,
x(p1,d1,c,d,e,f),
y(d1,d2,i,j,k,l),
z(d2,d3,o,p,q,r),

Pensado neles como pontos, gostaria de saber como posso ir de x a z , fazendo o input de p1 e d3.
Tenho, por exemplo:
write('Partida: '),nl,
read(Partida_it),
write('Destino: '),nl,
read(Destino_it),
    viagem(Partida_it,Destino_it,C,D,E,F),nl,
    write(Partida_it),write('<-->'),write(Destino_it),nl,
write('Tipo: '),write(C),nl,
write('Hora de partida: '),write(D),nl,
write('Hora de chegada: '),write(E),nl,
write('Preco: '),write(F),nl,
    fail,

Para o caso de ja existir essa viagem^
viagem(Partida_it,B,C,D,_,P1),nl,
viagem(B,Destino_it,F,_,E,P2),nl,
P is P1+P2,
write(Partida_it),write('<-->'),write(Destino_it),nl,
write('Tipo: '),write(C),write('e'),write(F),nl,
write('Hora de partida: '),write(D),nl,
write('Hora de chegada: '),write(E),nl,
write('Preco: '),write(P),nl,
    fail.

Estou já há umas horas preso neste problema.
Comment: Olá, bem vindo ao StackOverflow em Português! Você poderia fornecer mais detalhes da sua dúvida? Que tipo de problema você está tentando resolver? Onde você travou?
Comment: Olá, obrigado!
Trata-se de uma plataforma de viagens entre varios transportes, tenho várias viagens na base de dados, por exemplo
     viagem(roma,lisboa,aviao,12:00,15:00,300).
     viagem(lisboa,porto,comboio,16:00,18:00,10).
Dando input
write('Partida: '),nl,
read(Partida_it),
write('Destino: '),nl,
read(Destino_it).
Quero que o programa de um output das viagens necessarias para chegar de Roma ao Porto e a soma dos preços
Answer: A sua lógica, em alto nível, seria o seguinte:

Se existe um viagem de Partida a Destino, faça ela e pronto;
Caso contrário, viaje para um ponto X que você ainda não visitou, e depois tente viajar de X para Destino.

Verificar se você já visitou X ou não é importante, caso contrário você pode entrar num loop infinito. Isso pode ser feito salvando os pontos por onde você já passou em uma lista, e ao escolher um destino verificando se esse ponto está ou não na lista.
Em código:
viajar(A, B, _, [viagem(A, B, C, D, E, F)]) :-
    viagem(A, B, C, D, E, F), % Se existe uma viagem direta de A a B
    !.                        % Não precisa procurar mais

viajar(A, B, JaVisitou, [viagem(A, X, C, D, E, F)|Lista]) :-
    viagem(A, X, C, D, E, F),           % Escolhe um destino qualquer
    \+ member(X, JaVisitou),            % Que você ainda não visitou
    viajar(X, B, [X|JaVisitou], Lista). % E tente ir dele até B

O resultado de uma chamada passando Partida e Destino seria uma lista de todas as viagens que têm que ser realizadas:
?- viajar(roma, porto, [roma], Lista).
Lista = [viagem(roma, lisboa, aviao, 12:00, 15:00, 300), viagem(lisboa, porto, comboio, 16:00, 18:00, 10)]

Exemplo no ideone. A partir daí você pode fazer operações nessa lista, tipo imprimir todos os passos:
passos([]).
passos([viagem(A,B,C,D,E,F)|R]) :-
    write(A),write('<-->'),write(B),nl,
    write('Tipo: '),write(C),nl,
    write('Hora de partida: '),write(D),nl,
    write('Hora de chegada: '),write(E),nl,
    write('Preco: '),write(F),nl,
    passo(R).

E calcular o preço total:
preco([], 0).
preco([viagem(_,_,_,_,_,P)|R], Total) :-
    preco(R, X),
    Total is P + X.

Etc. Nota: nos exemplos acima, não usei recursão de cauda, para tornar a resposta mais simples e a lógica bem evidente. Na prática, você deve usar acumuladores em vez de fazer operações adicionais após a chamada recursiva.
Comment: Isso clarificou tudo! Muito obrigado!

Indo de um ponto para outro


Intermittent access to website

Question: Environment:

Active Directory domain with a single domain controller (Windows Server 2003 R2
Standard x64 Edition - Service Pack 2) which is also the DNS
Windows XP Service Pack 3 clients. The client computers have ONLY our internal
DNS server as their DNS address.

Our users have reported that occasionally they cannot visit Southwest Airlines
website www.southwest.com.
After a few days of trying we were able to reproduce the problem in a test user's
login.
When attempting to access the site in Firefox, the status bar says, "Looking up
www.southwest.com" and after a few moments Firefox displays:
Address Not Found
Firefox can't find the server at www.southwest.com
Similar results in Internet Explorer
We tried restarting the browser and the computer, but we still cannot access the
site. Other websites we tested work normally.
We tried accessing the website from another computer and got the same results.
nslookup reveals the following:
C:\Documents and Settings\TestQ>nslookup www.teamdesk.net
Server:  server.domain.local
Address:  172.21.31.206

Name:    www.teamdesk.net
Address:  188.8.131.52

C:\Documents and Settings\TestQ>nslookup www.southwest.com
Server:  server.domain.local
Address:  172.21.31.206

DNS request timed out.
    timeout was 2 seconds.
*** Request to server.domain.local timed-out

C:\Documents and Settings\TestQ>nslookup
Default Server:  server.domain.local
Address:  172.21.31.206

> www.southwest.com
Server:  server.domain.local
Address:  172.21.31.206

DNS request timed out.
    timeout was 2 seconds.
*** Request to server.domain.local timed-out

> set d2
> www.southwest.com
Server:  server.domain.local
Address:  172.21.31.206

------------
SendRequest(), len 51
    HEADER:
        opcode = QUERY, id = 4, rcode = NOERROR
        header flags:  query, want recursion
        questions = 1,  answers = 0,  authority records = 0,  additional = 0

    QUESTIONS:
        www.southwest.com.domain.local, type = A, class = IN

------------
------------
Got answer (119 bytes):
    HEADER:
        opcode = QUERY, id = 4, rcode = NXDOMAIN
        header flags:  response, auth. answer, want recursion, recursion avail.
        questions = 1,  answers = 0,  authority records = 1,  additional = 0

    QUESTIONS:
        www.southwest.com.domain.local, type = A, class = IN
    AUTHORITY RECORDS:
    ->  domain.local
        type = SOA, class = IN, dlen = 41
        ttl = 3600 (1 hour)
        primary name server = server.domain.local
        responsible mail addr = hostmaster
        serial  = 2064
        refresh = 900 (15 mins)
        retry   = 600 (10 mins)
        expire  = 86400 (1 day)
        default TTL = 3600 (1 hour)

------------
------------
SendRequest(), len 35
    HEADER:
        opcode = QUERY, id = 5, rcode = NOERROR
        header flags:  query, want recursion
        questions = 1,  answers = 0,  authority records = 0,  additional = 0

    QUESTIONS:
        www.southwest.com, type = A, class = IN

------------
DNS request timed out.
    timeout was 2 seconds.
timeout (2 secs)
SendRequest failed
*** Request to server.domain.local timed-out

> www.google.com
Server:  server.domain.local
Address:  172.21.31.206

------------
SendRequest(), len 48
    HEADER:
        opcode = QUERY, id = 6, rcode = NOERROR
        header flags:  query, want recursion
        questions = 1,  answers = 0,  authority records = 0,  additional = 0

    QUESTIONS:
        www.google.com.domain.local, type = A, class = IN

------------
------------
Got answer (116 bytes):
    HEADER:
        opcode = QUERY, id = 6, rcode = NXDOMAIN
        header flags:  response, auth. answer, want recursion, recursion avail.
        questions = 1,  answers = 0,  authority records = 1,  additional = 0

    QUESTIONS:
        www.google.com.domain.local, type = A, class = IN
    AUTHORITY RECORDS:
    ->  domain.local
        type = SOA, class = IN, dlen = 41
        ttl = 3600 (1 hour)
        primary name server = server.domain.local
        responsible mail addr = hostmaster
        serial  = 2064
        refresh = 900 (15 mins)
        retry   = 600 (10 mins)
        expire  = 86400 (1 day)
        default TTL = 3600 (1 hour)

------------
------------
SendRequest(), len 32
    HEADER:
        opcode = QUERY, id = 7, rcode = NOERROR
        header flags:  query, want recursion
        questions = 1,  answers = 0,  authority records = 0,  additional = 0

    QUESTIONS:
        www.google.com, type = A, class = IN

------------
------------
Got answer (132 bytes):
    HEADER:
        opcode = QUERY, id = 7, rcode = NOERROR
        header flags:  response, want recursion, recursion avail.
        questions = 1,  answers = 6,  authority records = 0,  additional = 0

    QUESTIONS:
        www.google.com, type = A, class = IN
    ANSWERS:
    ->  www.google.com
        type = CNAME, class = IN, dlen = 8
        canonical name = www.l.google.com
        ttl = 69859 (19 hours 24 mins 19 secs)
    ->  www.l.google.com
        type = A, class = IN, dlen = 4
        internet address = 188.8.131.52
        ttl = 300 (5 mins)
    ->  www.l.google.com
        type = A, class = IN, dlen = 4
        internet address = 188.8.131.52
        ttl = 300 (5 mins)
    ->  www.l.google.com
        type = A, class = IN, dlen = 4
        internet address = 126.96.36.199
        ttl = 300 (5 mins)
    ->  www.l.google.com
        type = A, class = IN, dlen = 4
        internet address = 22.214.171.124
        ttl = 300 (5 mins)
    ->  www.l.google.com
        type = A, class = IN, dlen = 4
        internet address = 22.214.171.124
        ttl = 300 (5 mins)

------------
Non-authoritative answer:
Name:    www.l.google.com
Addresses:  22.214.171.124, 18.104.22.168, 184.108.40.206, 126.96.36.199
            18.104.22.168
Aliases:  www.google.com

How do we further diagnose and resolve this problem?
EDIT
I work with Brad. Thanks for your help so far.
1) The DNS server acts as the resolver. There is no forward lookup other than the root servers via root hints.
2) Under the error state (i.e., when the southwest.com lookups are timing out), nslookup southwest.com ns-1.southwest.com times out looking up the ns-1.southwest.com server. Same thing with ns-2.southwest.com.
3) Under the error state, nslookup southwest.com 184.108.40.206 and nslookup southwest.com 188.8.131.52 (i.e., against the IP addresses of ns-1 and ns-2.southwest.com) both work, returning southwest.com's IP addresses.
4) Under the error state, the cache is unchanged from when things are working normally. That is, dnsmgmt\cached lookups.(root)\com\southwest always shows the following (including the A record for ns-2, which fails (see #2 above)).
Name                        Type                Data
----                        ----                ----
(same as parent folder)     Name Server (NS)    ns-1.southwest.com
(same as parent folder)     Name Server (NS)    ns-2.southwest.com
(same as parent folder)     Host (A)            22.214.171.124
(same as parent folder)     Host (A)            184.108.40.206
ns-2                        Host (A)            188.8.131.52

I suspect we're overlooking something obvious ...
EDIT
(Sorry for the delay. I posted this over 8 hours ago but it never appeared.)
Under the error state,
5) nslookup southwest.com against all *.gtld-servers.net servers succeeded
... QUESTIONS:
    southwest.com, type = A, class = IN
AUTHORITY RECORDS:
->  southwest.com
    type = NS, class = IN, dlen = 7
    nameserver = ns-1.southwest.com
    ttl = 172800 (2 days)
->  southwest.com
    type = NS, class = IN, dlen = 7
    nameserver = ns-2.southwest.com
    ttl = 172800 (2 days)
ADDITIONAL RECORDS:
->  ns-1.southwest.com
    type = A, class = IN, dlen = 4
    internet address = 220.127.116.11
    ttl = 172800 (2 days)
->  ns-2.southwest.com
    type = A, class = IN, dlen = 4
    internet address = 184.108.40.206
    ttl = 172800 (2 days)

------------
Name:    southwest.com
Served by:
- ns-1.southwest.com
          126.96.36.199
          southwest.com
- ns-2.southwest.com
          126.96.36.199
          southwest.com

6) nslookup southwest.com 18.104.22.168 (OpenDNS) succeeded
7) Clearing the cache fixed the problem, but it just returns later.
8) After clearing the cache and doing nslookup southwest.com (which succeeds), the cache now has ns-1's A record (it didn't under the error state, see #4 above)
Name                        Type                Data
----                        ----                ----
(same as parent folder)     Name Server (NS)    ns-1.southwest.com
(same as parent folder)     Name Server (NS)    ns-2.southwest.com
(same as parent folder)     Host (A)            188.8.131.52
(same as parent folder)     Host (A)            18.104.22.168
ns-1                        Host (A)            188.8.131.52
ns-2                        Host (A)            188.8.131.52

9) Note that the DNS server only forwards to the root servers. Can you think of any reason that should cause this problem?
Comment: maybe from your DNS server, try
nslookup www.southwest.com ns-1.southwest.com
and
nslookup www.southwest.com ns-2.southwest.com

This will show if your DNS server can access their DNS servers.
Comment: btw, your DNS server - how it configured - it acts as resolver or it merely forwards requests to your ISP ? - in the latter case, try nslookup www.southwest.com nsX.yourisp.net
Comment: Also, the L root IP is current.
Comment: Since the problems is looking-up nameservers names, now, you may try nslookup southwest.com a.gtld-servers.net ... m.gtld-serves.net. See if all requests answered and return both NS and both A records.
Comment: Is there an A record for ns-1 in the cache ? - might be the cause. Did you try to empty the cache ?
Answer: If you forward DNS to your ISP, try doing an nslookup specifying their servers and see if the problem is on their end. If you are using root hints, make sure that the L root server root hint is using the right IP. I've seen that cause some wonkiness on older AD installs.

Intermittent access to website


Use different fonts in same Excel cell?

Question: Is there any way to change the color and/or font of specific text within an excel cell?  That is, I'd like one part of the cell's displayed value to be red and another part of the same cell's displayed value to be blue (as an example).  Since the displayed values are being calculated as formulas, I'd need some sort of formatting formula that would apply only the stuff inside the formula.  I can't seem to find anything in the text.
Comment: Highlight Cell.  Press Ctrl+1 is your friend.
Comment: Nope, that uses the built-in excel custom formats, and in order for me to specify the condition, I'd need a custom format that evaluates formulas.  Would love to use it but can't.
Answer: If you want to do this based on a formula, you will have to write some VBA. See this example
Comment: Could I use the VBA technique to apply different fonts as well?
Comment: Yes. You can change any attribute. Font name and type, bold, strikethrough, etc. etc. this way. There are many VBA examples available on how to do this.
Answer: No problem. Edit the value in the formula toolbar.
Comment: Oops! Missed the part about it being a calculated value. Conditional formatting is the way to go.
Answer: Take a look at Conditional Formatting in excel.
Comment: I can't use conditional formatting because I want the fonts/colors to apply to specific calculated values within the cell.  I am creating an inline bar graph.  I'd like to format the bar graph using one font and the associated value using a different font.

Use different fonts in same Excel cell?


How to set value for input field and have it update on submission to Ember.js action?

Question: On the handlebars template, I'd like to pre-populate an input field with the value. That I can do by putting value=object.property. Then the user should update the value, and when they click the button activating the action, the value should submit to the Component.
The problem is that no value is getting submitted, not the pre-populated value, or the new value. When I console.log what is getting submitted to the component, the input from the text field is "undefined" and the input from the number field is "NaN".
This is my handlebars template:
{{input type="text" value=object.name valueBinding='newName'}}
{{view App.NumberField min='1' value=object.count valueBinding='newCount'}}
<button {{action updateObjectDetails object}}>Save</button>

The related component it is submitting to:
App.ObjectsDetailsComponent = Ember.Component.extend({
  actions: {
    updateObjectDetails: function(object){
      object.set("name", this.get('newName'))
      object.set("party_size", parseInt(this.get('newCount')))
      object.save();
    }
  }
});

Is there a way to populate the input field with the correct value AND have it submit with the action?
Answer: Ah, got it. The thing is to not try to use the valueBindings, like you might when creating a new object, but to use the actual value, because the actual value is changing. So in the component, it's object.get('name'), not this.get('newName').
Therefore the handlebars should be like this:
{{input type="text" value=object.name}}
{{view App.NumberField min='1' value=object.count}}
<button {{action updateObjectDetails object}}>Save</button>

And the component like this:
App.ObjectsDetailsComponent = Ember.Component.extend({
  actions: {
    updateObjectDetails: function(object){
      object.set("name", object.get('name'))
      object.set("party_size", parseInt(object.get('count')))
      object.save();
    }
  }
});


Jenkins Phing Plugin - Resource Temporarily Unavailable

Question: I have just started getting Jenkins setup with Phing as the build tool. Although I have used Jenkins before, I'm new to Phing.
I have a project setup in Jenkins that has a Mercurial Repository setup and a Phing Build step.
The build.xml file simply archives the existing file, deletes them and copies the new files from the repository.
I have run phing from the terminal and everything works as planned. However, when running from within Jenkins, I'm getting the following in the Console Output:
<code>[workspace] $ /usr/local/pear/bin/phing -buildfile /Users/Shared/Jenkins/Home/jobs/Project/workspace/build.xml "-Dwebroot=/Volumes/Websites/Project/ -Dcheckoutroot=/Users/Shared/Jenkins/Home/jobs/Project/workspace -Drevision=5" -logger phing.listener.DefaultLogger

/usr/local/pear/bin/phing: fork: Resource temporarily unavailable
Build step 'Invoke Phing targets' marked build as failure
</code>
My first thought was that it was permission related, but I've changed Jenkins to run as the same user that I ran Phing manually as and it still got the same issue.
Does anybody have any thoughts as to what might be causing the problem?
I can't find anything related to this error anywhere that isn't related to Cygwin...
The system is running on OS X 10.7.5 with Jenkins 1.518 and Phing 2.5.1
The build.xml file looks like:
<code><?xml version="1.0" encoding="UTF-8"?>
<project name="Project" default="dist">
    <property name="revision" value="old" />
    <property name="webroot" value="/Volumes/Websites/${phing.project.name}" />
    <property name="checkoutroot" value="./" />

    <target name="clean">
        <echo msg="Backing up old site to ${phing.project.name}-${revision}..." />
        <tar destfile="${webroot}/../${phing.project.name}-${revision}.tar.gz" basedir="${webroot}" compression="gzip" />

        <echo msg="Deleting site from ${webroot}..." />
        <delete>
            <fileset dir="${webroot}" />
        </delete>
    </target>

    <target name="dist" depends="clean">
        <echo msg="Copying files to website at ${webroot}..." />

        <copy todir="${webroot}">
            <fileset dir="${checkoutroot}/Website">
                <exclude name="**/.hg/**" />
            </fileset>
        </copy>
    </target>
</project>
</code>
Comment: "Resource temporarily unavailable" generally means out of memory or process limit reached. I am having the exact same issue in Jenkins 1.524 on an MBP running OS X 10.8.4, PHP 5.4.10, and phing 2.5.0 (PHP, pear, and thus phing are installed via MAMP). I see in `top` that every time I start my project build, about 1000 `sh` processes spin up, then I get that error and the job fails. The process spin up explains the error, but I cannot figure out why these processes spin up.
Answer: I've managed to resolve this issue by removing all of the path details in the Phing configuration section within Jenkins.
This makes absolutely no sense to me as to why it's working without these details as I definitely only have one Phing install, so it's not as if it was picking up the wrong one or something.
However, by not specifying anything in the Phing section of the Jenkins project config so it picks up the default path, default build target etc. and this is working flawlessly now!


Como ignorar uma linha de uma consulta no banco de dados?

Question: Estou tentando desenvolver um codigo para criar tabelas dinâmicas com php e mysql, utilizando um banco de dados asterisk. Minha primeira dificuldade é que o registro das ligações são duplicados (ou quadruplicados), caso a ligação seja interna. Por exemplo, se eu usar o comando:
SELECT calldate, src, dst, duration, disposition
FROM cdr
ORDER BY calldate DESC
LIMIT 8;

Esse resultado é obtido:
+---------------------+------+------+----------+-------------+
| calldate            | src  | dst  | duration | disposition |
+---------------------+------+------+----------+-------------+
| 2020-12-15 08:43:27 | 5003 | 5010 |      505 | ANSWERED    |
| 2020-12-15 08:42:32 | 5001 | 5006 |       34 | ANSWERED    |
| 2020-12-15 08:41:42 | 5001 | 5006 |       34 | ANSWERED    |
| 2020-12-15 08:39:15 | 5006 | 5010 |       34 | ANSWERED    |
| 2020-12-15 08:38:26 | 5006 | 5010 |       34 | ANSWERED    |
| 2020-12-15 08:36:30 | 5001 | 5008 |       36 | ANSWERED    |
| 2020-12-15 08:36:06 | 5004 | 5001 |        0 | BUSY        |
| 2020-12-15 08:35:46 | 5004 | 5001 |       20 | BUSY        |
+---------------------+------+------+----------+-------------+
8 rows in set (0.09 sec)

Como posso contornar isso?
Comment: SELECT DISTINCT src, dst, ...
Comment: A tabela que você postou na pergunta não tem registros duplicados. Duplicado seria se todos os dados de um registro (linha) fossem iguais aos de outra linha. Como as _calldates_ são todas diferentes, não está ocorrendo duplicação de registros.
Answer: Você pode utilizar o distinct para distinguir os resultados do select, porém nesse caso acredito que você deseja distinguir apenas pela coluna "disposition", uma vez que é a única duplicada/quadruplicada no exemplo.
Mas acredito que o mais correto seria você realizar uma tratativa na sua tabela para evitar registros duplicados, podendo ser feito com a constraint unique.
Espero ter ajudado, caso não, por favor complemente sua pergunta.
Answer: Tente isso:
SELECT max(calldate) calldateMax, src, dst, duration, disposition
FROM cdr
group by src, dst, duration, disposition
ORDER BY calldateMax DESC