profile with pycallgraph

    Example:
        pycallgraph graphviz -- ./mypythonscript.py

    References:
        http://pycallgraph.slowchop.com/en/master/
195987
def make_call_graph(func, *args, **kwargs):
    
    from pycallgraph import PyCallGraph
    from pycallgraph.output import GraphvizOutput
    with PyCallGraph(output=GraphvizOutput):
        func(*args, **kwargs)
1342574
def thread_view(request, pk):
    '''  '''
    if request.is_ajax():
        if not request.user.is_authenticated():
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")
        try:
            user_profile = UserProfile.objects.get(user=request.user)
        except UserProfile.DoesNotExist:
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")
        try:
            thread = Thread.objects.get(pk=pk)
        except Thread.DoesNotExist:
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")
        follow_form = FollowThreadForm(
            request.POST if "follow_thread" in request.POST else None,
            instance=thread,
            profile=user_profile,
        )
        if follow_form.is_valid():
            following = follow_form.save()
            response = dict(
                following=following,
                num_of_followers=thread.followers.all().count()
            )
            return HttpResponse(json.dumps(response),
                                content_type="application/json")
        raise Http404
    userProfile = UserProfile.objects.get(user=request.user)
    thread = get_object_or_404(Thread, pk=pk)
    messages_list = Message.objects.filter(thread=thread)

    follow_form = FollowThreadForm(
        request.POST if "follow_thread" in request.POST else None,
        instance=thread,
        profile=userProfile,
        )

    if follow_form.is_valid():
        following = follow_form.save()
        if following:
            message = "You are now following this thread."
        else:
            message = "You are no longer following this thread."
        messages.add_message(request, messages.INFO, message)
        return HttpResponseRedirect(reverse("threads:view_thread",
                                            kwargs={"pk": pk}))

    edit_forms, delete_forms = [], []

    for message in messages_list:
        edit_message_form, delete_message_form = None, None
        if message.owner == userProfile or userProfile.user.is_superuser:
            edit_message_form = EditMessageForm(
                request.POST if "edit_message-{0}".format(message.pk) in request.POST else None,
                instance=message,
                prefix="edit-{0}".format(message.pk),
                )
            delete_message_form = DeleteMessageForm(
                request.POST if "delete_message-{0}".format(message.pk) in request.POST else None,
                instance=message,
                )
            if edit_message_form.is_valid():
                edit_message_form.save()
                messages.add_message(request, messages.INFO, "Message updated.")
                return HttpResponseRedirect(reverse("threads:view_thread", kwargs={
                    "pk": pk,
                    }))
            if delete_message_form.is_valid():
                thread = delete_message_form.save()
                messages.add_message(request, messages.INFO, "Message deleted.")
                if thread is None:
                    return HttpResponseRedirect(reverse("threads:list_all_threads"))
                return HttpResponseRedirect(reverse("threads:view_thread", kwargs={
                    "pk": thread.pk,
                    }))

        edit_forms.append(edit_message_form)
        delete_forms.append(delete_message_form)

    edit_thread_form = None
    if thread.owner == userProfile or request.user.is_superuser:
        edit_thread_form = EditThreadForm(
            request.POST if "edit_thread" in request.POST else None,
            instance=thread,
            )

    add_message_form = MessageForm(
        request.POST if "add_message" in request.POST else None,
        profile=userProfile,
        thread=thread,
        )

    if edit_thread_form and edit_thread_form.is_valid():
        thread = edit_thread_form.save()
        return HttpResponseRedirect(reverse("threads:view_thread", kwargs={
            "pk": thread.pk,
            }))
    elif add_message_form.is_valid():
        add_message_form.save()
        return HttpResponseRedirect(reverse('threads:view_thread', kwargs={
            'pk': pk,
            }))
    elif request.method == "POST":
        messages.add_message(request, messages.ERROR, MESSAGES['MESSAGE_ERROR'])


    thread.views += 1
    thread.save()

    following = request.user in thread.followers.all()

    return render_to_response('view_thread.html', {
        'thread': thread,
        'page_name': thread.subject,
        'messages_list': zip(messages_list, edit_forms, delete_forms),
        "add_message_form": add_message_form,
        "edit_thread_form": edit_thread_form,
        "following": following,
        "follow_form": follow_form,
        }, context_instance=RequestContext(request))
956527
def graph(self, name, *args, **kwargs):
        
        return Graph(self, name, *args, **kwargs)
614400
def write_graph(self, filename):
        
        f = open(filename, 'w')
        f.write(self._get_graphviz_data())
        f.close()
752484
def profile(n):
    
    def decorator_with_name(func):
        def func_wrapper(*args, **kwargs):
            with ProfileKV(n):
                return func(*args, **kwargs)
        return func_wrapper
    return decorator_with_name
166465
def _genenare_callmap_sif(self, filepath):
        
        with open(filepath, "wb") as f:
            for src, dst in self.callgraph.edges():
                f.write("%#x\tDirectEdge\t%#x\n" % (src, dst))
838476
def scan_to_graph(python_modules, graph, ignore=tuple()):
    
    def callback(specification, provider):
        graph.register_provider(specification, provider)
    scan(python_modules, callback, ignore=ignore)
782436
def to_call_agraph(self):
        

        A = nx.nx_agraph.to_agraph(self.call_graph)
        A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"})
        A.node_attr.update(
            {"shape": "rectangle", "color": "#650021", "style": "rounded"}
        )
        A.edge_attr.update({"color": "#650021", "arrowsize": 0.5})
        return A
1353880
def graph(bare=False, json=False, json_tree=False, reverse=False):
    """"""
    from ..core import do_graph

    do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
814074
def run_graphviz(program, code, options=[], format='png'):
    
    import os
    from subprocess import Popen, PIPE

    dot_args = [program] + options + ['-T', format]

    if os.name == 'nt':
        # Avoid opening shell window.
        # * https://github.com/tkf/ipython-hierarchymagic/issues/1
        # * http://stackoverflow.com/a/2935727/727827
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=0x08000000)
    else:
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
        wentwrong = False

    try:
        # Graphviz may close standard input when an error occurs,
        # resulting in a broken pipe on communicate()
        stdout, stderr = p.communicate(code.encode('utf-8'))
    except (OSError, IOError) as err:
        if err.errno != EPIPE:
            raise
        wentwrong = True
    except IOError as err:
        if err.errno != EINVAL:
            raise
        wentwrong = True

    if wentwrong:
    # in this case, read the standard output and standard error streams
    # directly, to get the error message(s)
        stdout, stderr = p.stdout.read(), p.stderr.read()
        p.wait()

    if p.returncode != 0:
        raise RuntimeError('dot exited with error:\n[stderr]\n{0}'.format(stderr.decode('utf-8')))

    return stdout
820064
def link_to_profile(args)
      user_or_key = args.is_a?(Hash) ? args[:value].first : args
      user = case user_or_key
             when User
               user_or_key
             when String
               ::User.find_by_user_key(user_or_key)
             end
      return user_or_key if user.nil?
      text = user.respond_to?(:name) ? user.name : user_or_key
      link_to text, Hyrax::Engine.routes.url_helpers.user_path(user)
    end
147497
def browseprofilegui(profilelog):
    '''
    
    '''
    from runsnakerun import runsnake # runsnakerun needs wxPython lib, if it's not available then we can pass if we don't want a GUI. RunSnakeRun is only used for GUI visualisation, not for profiling (and you can still use pstats for console browsing)
    app = runsnake.RunSnakeRunApp(0)
    app.OnInit(profilelog)
    #app.OnInit()
    app.MainLoop()
318737
function createGraph(modules, circular, config, options) {
	const g = graphviz.digraph('G');
	const nodes = {};
	const cyclicModules = circular.reduce((a, b) => a.concat(b), []);

	if (config.graphVizPath) {
		g.setGraphVizPath(config.graphVizPath);
	}

	Object.keys(modules).forEach((id) => {
		nodes[id] = nodes[id] || g.addNode(id);

		if (!modules[id].length) {
			setNodeColor(nodes[id], config.noDependencyColor);
		} else if (cyclicModules.indexOf(id) >= 0) {
			setNodeColor(nodes[id], config.cyclicNodeColor);
		}

		modules[id].forEach((depId) => {
			nodes[depId] = nodes[depId] || g.addNode(depId);

			if (!modules[depId]) {
				setNodeColor(nodes[depId], config.noDependencyColor);
			}

			g.addEdge(nodes[id], nodes[depId]);
		});
	});

	return new Promise((resolve, reject) => {
		g.output(options, resolve, (code, out, err) => {
			reject(new Error(err));
		});
	});
}
408951
def profile(message=None, verbose=False):
    
    import functools
    from harrison.registered_timer import RegisteredTimer

    # Adjust the call stack index for RegisteredTimer so the call is Timer use
    # is properly attributed.
    class DecoratorTimer(RegisteredTimer):
        _CALLER_STACK_INDEX = 2

    def wrapper(fn):
        desc = message or fn.__name__

        @functools.wraps(fn)
        def wrapped_fn(*args, **kwargs):
            with DecoratorTimer(desc=desc, verbose=verbose):
                return fn(*args, **kwargs)
        return wrapped_fn

    return wrapper
613225
def other_profiles(p,ifig=1,xlm=xlm,show=False,xaxis=xaxis_type, figsize2=(10,8)):
    '''
    '''

    matplotlib.rc('figure',facecolor='white',figsize=figsize2)

    mass = p.get('mass')                      # in units of Msun
    radius = p.get('radius')*ast.rsun_cm/1.e8  # in units of Mm
    if xaxis is "Eulerian":
        xxx = radius
        if xlm[0]==0 and xlm[1] == 0:
            indtop = 0
            indbot = len(mass)-1
        else: 
            indbot = np.where(radius>=xlm[0])[0][-1]
            indtop = np.where(radius<xlm[1])[0][0]
        xll = (radius[indbot],radius[indtop])
        xxlabel = "radius (Mm)"
    elif xaxis is "Lagrangian": 
        xxx = mass
        xll = xlm
        xxlabel = "$M / \mathrm{M_{sun}}$"
    else:
        print("Error: don't understand xaxis choice, must be Lagrangian or Eulerian")


    # create subplot structure
    t, ([ax1,ax2],[ax3, ax4],[ax5,ax6]) = matplotlib.pyplot.subplots(3, 2, sharex=True, sharey=False)
    
# panel 1: burns: pp, cno, burn_c
# panel 2: convection and mixing: entropy, Tgrad


    # which burning to show
    Enuc = ['pp','cno','tri_alfa','burn_c','burn_o','burn_n','burn_si','burn_mg','burn_na','burn_ne','eps_nuc']
    ax = ax1
    for thing in Enuc:
        ind = Enuc.index(thing)
        ax.plot(xxx, np.log10(p.get(thing)), ls=u.linestylecb(ind,a,b)[0],\
             marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
             markevery=50,label=thing)
        
    # set x and y lims and labels
    #ax.set_title('Nuclear Energy Production')
    ax.set_ylim(0,15)
    ax.set_xlim(xll)
    ax.legend(loc=1, ncol=2, fontsize='small')
    #ax.set_xlabel(xxlabel)
    ax.set_ylabel('$ \log \epsilon $')
#--------------------------------------------------------------------------------------------#

    # gradients

    mix = [['gradr']]
    mix1 = [['grada']]
    
    for i in range(1):
        for thing in mix[i]:
            ind = mix[i].index(thing)
    for i in range(1):
        for thing1 in mix1[i]:
            ind1 = mix1[i].index(thing1)
            ax2.plot(xxx, (np.tanh(np.log10(p.get(thing))-np.log10(p.get(thing1))))\
            ,ls=u.linestylecb(ind,a,b)[0],\
             marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
             markevery=50,label=thing)
    # set x and y lims and labels
    ax2.axhline(ls='dashed',color='black',label="")
    #ax2.set_title('Mixing Regions')
    ax2.yaxis.tick_right()
    ax2.yaxis.set_label_position("right")
    ax2.set_ylim(-.1,.1)
    ax2.set_xlim(xll)
    ax2.legend(labels='Mixing',loc=1)
    #ax2.set_xlabel(xxlabel)
    ax2.set_ylabel('$\\tanh(\\log(\\frac{\\nabla_{rad}}{\\nabla_{ad}}))$')

#--------------------------------------------------------------------------------------------#

    # entropy
    S = ['entropy']

    ax = ax5
    
    for thing in S:
        ind = 2
        ax.plot(xxx, p.get(thing), ls=u.linestylecb(ind,a,b)[0],\
         marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
         markevery=50,label=thing)
    # set x and y lims and labels
    #ax.set_title('Specific Entropy (/A*kerg)')
    ax.set_ylim(0,50)
    ax.set_xlim(xll)
    ax.legend(loc=1)
    ax.set_xlabel(xxlabel)
    ax.set_ylabel(' Specific Entropy')

#--------------------------------------------------------------------------------------------#
    # rho, mu, T
    S = ['logRho','mu','temperature']
    T8 = [False,False,True]
    ax = ax6

    for thing in S:
        ind = S.index(thing)
        thisy = p.get(thing)/1.e8 if T8[ind] else p.get(thing)
        ax.plot(xxx, thisy, ls=u.linestylecb(ind,a,b)[0],\
         marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
         markevery=50,label=thing)
    # set x and y lims and labels                                                              
    #ax.set_title('Rho, mu, T')
    ax.set_ylim(0.,9.)
    ax.set_xlim(xll)
    ax.legend(loc=0)
    ax.set_xlabel(xxlabel)
    ax.set_ylabel('log Rho, mu, T8')


#--------------------------------------------------------------------------------------------#

    
    # gas pressure fraction and opacity
    S = ['pgas_div_ptotal']
    o = ['log_opacity']

    ax = ax4
    axo = ax.twinx()
    
    for thing in S:
        ind = 5
        ax.plot(xxx, p.get(thing), ls=u.linestylecb(ind,a,b)[0],\
         marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
         markevery=50,label=thing)

    for thing in o:
        ind = 3
        axo.plot(xxx, p.get(thing), ls=u.linestylecb(ind,a,b)[0],\
         marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
         markevery=50,label=thing)

   
    # set x and y lims and labels
   # ax.set_title('Pgas fraction + opacity')
   # ax.set_ylim(0,60)
    ax.set_xlim(xll)
    axo.set_xlim(xll)
    ax.legend(loc=0)
    axo.legend(loc=(.15,.85))
    #ax.set_xlabel(xxlabel)
    ax.set_ylabel('$\mathrm{ P_{gas} / P_{tot}}$')
    axo.set_ylabel('$ log(Opacity)$')

#--------------------------------------------------------------------------------------------#

    # Diffusion coefficient
    gT = ['log_D_mix','conv_vel_div_csound']
    logy = [False,True]
    
    ax = ax3
    ind = 0
    for thing in gT:
        ind = gT.index(thing)
        thisx = np.log(p.get(thing))+16 if logy[ind] else p.get(thing)
        ax.plot(xxx, thisx, ls=u.linestylecb(ind,a,b)[0],\
         marker=u.linestylecb(ind,a,b)[1], color=u.linestylecb(ind,a,b)[2],\
         markevery=50,label=thing)
# set x and y lims and labels
    ax.axhline(16,ls='dashed',color='black',label="$\mathrm{Ma}=0$")
   # ax.set_title('Mixing')
    ax.set_ylim(10,17)
    ax.set_xlim(xll)
    ax.legend(loc=0)
   # ax.set_xlabel(xxlabel)
    ax.set_ylabel('$\\log D / [cgs] \\log v_{\mathrm{conv}}/c_s + 16 $ ')

    title_str = "Other profiles: "+'t ='+str(title_format%p.header_attr['star_age'])\
              +', dt ='+str(title_format%p.header_attr['time_step'])\
              +', model number ='+str(int(p.header_attr['model_number']))
    t.suptitle(title_str, fontsize=12)
   # t.tight_layout()
    t.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.15, hspace=0.1)
    t.savefig('other'+str(int(p.header_attr['model_number'])).zfill(6)+'.png')
1031897
def draw_lines(self, callback):
        ''''''
        from MAVProxy.modules.mavproxy_map import mp_slipmap
        self.draw_callback = callback
        self.draw_line = []
        self.map.add_object(mp_slipmap.SlipDefaultPopup(None))
353366
def profileit(path=None):
    

    def inner(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            if path is not None:
                print prof.print_stats()
                prof.dump_stats(os.path.expanduser(path))
            else:
                print prof.print_stats()
            return retval
        return wrapper
    return inner