Matplotlib – python – click and drag a curve around

# draw one point using subplot
# click and drag a curve around

import matplotlib.pyplot as plt
import numpy as np
import pdb

x = np.linspace(0, 2*3.14, 100)
y = np.sin(x)

press = False

def onPress(event):
    global press
    contains, _ = pnt.contains(event)
    # make sure the click is on the object
    if contains:
        press = True
    print(press)

def onMove(event):
    global press
    if press == True:
        # only for events inside the axes
        if event.inaxes == pnt.axes:
            x = pnt.get_xdata()
            y = pnt.get_ydata()
            ymax = np.max(y)
            yind = np.argmax(y)
            xmax = x[yind]
            y = y + event.ydata - ymax
            x = x + event.xdata - xmax
            pnt.set_data(x, y)
            print(event.xdata, event.ydata)
            pnt.figure.canvas.draw()

def onRelease(event):
    global press
    press = False
    print(press)
    pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot(x, y, 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
pnt.figure.canvas.mpl_connect('motion_notify_event', onMove)
pnt.figure.canvas.mpl_connect('button_release_event', onRelease)

plt.show()

Matplotlib – python – click on a point and drag it around


# draw one point using subplot
# click on the point and drag it around

import matplotlib.pyplot as plt

press = False

def onPress(event):
    global press
    contains, _ = pnt.contains(event)
    # make sure the click is on the object
    if contains:
        press = True
    print(press)

def onMove(event):
    global press
    if press == True:
        # only for events inside the axes
        if event.inaxes == pnt.axes:
            print(event.xdata, event.ydata)
            pnt.set_data([event.xdata, event.ydata])
            pnt.figure.canvas.draw()

def onRelease(event):
    global press
    press = False
    print(press)
    pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot([0],[1], 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
pnt.figure.canvas.mpl_connect('motion_notify_event', onMove)
pnt.figure.canvas.mpl_connect('button_release_event', onRelease)

plt.show()

Matplotlib – python – move the curve to the clicked location


# draw one point using subplot
# move the curve to the clicked locaction

import matplotlib.pyplot as plt
import numpy as np
import pdb

x = np.linspace(0, 2*3.14, 100)
y = np.sin(x)

def onPress(event):
    print(event.xdata, event.ydata)
    #print(help(pnt.set_data))
    x = pnt.get_xdata()
    y = pnt.get_ydata()
    ymax = np.max(y)
    yind = np.argmax(y)
    xmax = x[yind]
    y = y + event.ydata - ymax
    x = x + event.xdata - xmax
    pnt.set_data(x, y)
    pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot(x, y, 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
#pnt.figure.canvas.mpl_connect('motion_notify_event', onPress)

plt.show()

Matplotlib – python – click on the curve and change its color randomly

# draw one point using subplot
# click on the curve and change its color

import matplotlib.pyplot as plt
import random
import numpy as np
import pdb

x = np.linspace(0, 2*3.14, 100)
y = np.sin(x)

def onPress(event):
    if event.inaxes == pnt.axes:
        contains, _ = pnt.contains(event)
        if contains:
            #print(True)
            print(event.xdata, event.ydata)
            x = list(pnt.get_xdata())
            y = list(pnt.get_ydata())
            pnt.set_data(x, y)
            #print(dir(pnt))
            r = random.random()
            g = random.random()
            b = random.random()
            color = (r, g, b)
            pnt.set_markerfacecolor(color)
            pnt.set_markeredgecolor(color)
            pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot(x, y, 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
#pnt.figure.canvas.mpl_connect('motion_notify_event', onPress)

plt.show()

Matplotlib – add a point at every click

# draw one point using subplot
# draw a new point at every click 

import matplotlib.pyplot as plt

def onPress(event):
    print(event.xdata, event.ydata)
    xs = list(pnt.get_xdata())
    ys = list(pnt.get_ydata())
    xs.append(event.xdata)
    ys.append(event.ydata)
    pnt.set_data(xs, ys)
    pnt.figure.canvas.draw()
    
fig, ax = plt.subplots()
pnt, = ax.plot([0],[1], 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)

plt.show()

Matplotlib – click and move a point around

# draw one point using subplot
# move the point to the clicked locaction

import matplotlib.pyplot as plt

def onPress(event):
    print(event.xdata, event.ydata)
    #print(help(pnt.set_data)) 
    pnt.set_data([event.xdata, event.ydata])
    pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot([0],[1], 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
#pnt.figure.canvas.mpl_connect('motion_notify_event', onPress)

plt.show()

Matplotlib – click and change color randomly

# click and change color randomly

import matplotlib.pyplot as plt
from matplotlib.backend_bases import MouseButton
import random

#plt.ion()

x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

def on_click(event):
    if event.button is MouseButton.LEFT:
        print(event.xdata, event.ydata)
        r = random.random()
        g = random.random()
        b = random.random()
        plt.clf()
        plt.plot(x, y, 'o', color=(r, g, b))
        plt.draw()

plt.connect('button_press_event', on_click)
plt.plot(x,y, 'ro')
plt.show()


Blender – Development – Learning – #2

Aim: to change the Language view in the splash screen. When we grep Quick Setup, we can find that the relevant code that we are lookin for here is in the file

release/scripts/startup/bl_operators/wm.py

The relevant code is:

        if bpy.app.build_options.international:
            prefs = context.preferences
            # fun-hacks - changing case
            col.prop(prefs.view, "language", text="LANGUAGE")
            col.separator()

We look at
dir(prefs.view)

The result is:

[‘__doc__’, ‘__module__’, ‘__slots__’, ‘bl_rna’, ‘color_picker_type’, ‘factor_display_type’, ‘filebrowser_display_type’, ‘font_path_ui’, ‘font_path_ui_mono’, ‘gizmo_size’, ‘gizmo_size_navigate_v3d’, ‘header_align’, ‘language’, ‘lookdev_sphere_size’, ‘mini_axis_brightness’, ‘mini_axis_size’, ‘mini_axis_type’, ‘open_sublevel_delay’, ‘open_toplevel_delay’, ‘pie_animation_timeout’, ‘pie_initial_timeout’, ‘pie_menu_confirm’, ‘pie_menu_radius’, ‘pie_menu_threshold’, ‘pie_tap_timeout’, ‘render_display_type’, ‘rna_type’, ‘rotation_angle’, ‘show_addons_enabled_only’, ‘show_column_layout’, ‘show_developer_ui’, ‘show_gizmo’, ‘show_navigate_ui’, ‘show_object_info’, ‘show_playback_fps’, ‘show_splash’, ‘show_statusbar_memory’, ‘show_statusbar_stats’, ‘show_statusbar_version’, ‘show_statusbar_vram’, ‘show_tooltips’, ‘show_tooltips_python’, ‘show_view_name’, ‘smooth_view’, ‘text_hinting’, ‘timecode_style’, ‘ui_line_width’, ‘ui_scale’, ‘use_directional_menus’, ‘use_mouse_over_open’, ‘use_save_prompt’, ‘use_text_antialiasing’, ‘use_translate_interface’, ‘use_translate_new_dataname’, ‘use_translate_tooltips’, ‘use_weight_color_range’, ‘view2d_grid_spacing_min’, ‘view_frame_keyframes’, ‘view_frame_seconds’, ‘view_frame_type’, ‘weight_color_range’]

Here we find the ‘langugage’ attribute. We can set it’s value. We need to find the code corresponding to different languages available in Blender. We do another grep. We find the following file: release/datafiles/locale/languages

The file looks like this:

0:Complete: 0:Automatic (Automatic):DEFAULT 1:English (English):en_US 9:Spanish (Español):es 2:Japanese (日本語):ja_JP 47:Slovak (Slovenčina):sk_SK 41:Vietnamese (tiếng Việt):vi_VN 13:Simplified Chinese (简体中文):zh_CN

Now let us change the language back to Japanese. The code is ja_JP. We set the language as:

context.preferences.view.language="ja_JP"

Before we test it, we also make the value of following attribute is se to True, otherwise only part of some descriptions will be translated.

context.preferences.view.use_translate_interface=True

The final result is:

Blender – Development – Learning #1

I started messing with blender source code. First compiled blender source following the procedure from blender website. When you start blender you see the following screen.

The small window in the middle is called the splash window. I wanted to change case of the names in the first column “language”, “Shortcuts” etc. to capitals. When I searched for the words like “Shortcuts” using grep:

grep -Rw "Shortcuts" .

I found out that they are in the file release/scripts/startup/bl_operators/wm.py . I looked through the file and found the place. There is a class called WM_MT_splash_quick_setup. I hacked the code there.

layout.label(text="Quick Setup".upper())
sub = col.column(heading="Shortcuts".upper())
col.row().prop(kc_prefs, "select_mouse", text="Select With".upper(), expand=True)
col.row().prop(kc_prefs, "spacebar_action", text="Spacebar".upper())
sub = col.column(heading="Theme".upper())

But “language” took me some time figure out how to change its case. Here is the piece of code:

col.prop(prefs.view, "language", text="LANGUAGE")

Here is what I have:

Python – Nutrition – NOMS – USDA API

# noms -

import noms
import pickle
import os

key=open('myapikey.txt', 'r').read()

#client=noms.Client(key)
#results = client.search_query('Raw Broccoli')
#print(results)

food_dict_daily={
        '747447': 100, # Raw Broccoli
        '1103064': 1 * 180, # Ripe plantain, raw
        '169753' : 100, # Rice, white, long-grain, regular, cooked, enriched, with salt
        '1103657': 100, # Vegetable curry
        '1100622': 100, # Bread, white, toasted
        '1100187': 100, # Egg, whole, fried no added fat
        '1099246': 100, # Chicken curry
        '1097525': 100, # Milk, lactose free, whole
        '1097524': 100, # Milk, lactose free, reduced fat (2%)
        '1429086': 100, # ENSURE, HIGH PROTEIN POWDER, VANILLA, VANILLA
        '168833' : 100, # Sugars, brown
        '1103067': 100, # Plantain chips
        '1101716': 100, # Cereal, corn flakes
        }
food_dict_daily ={
        '1103064': 1 * 180, # Ripe plantain, raw 
        '169753' : 2 * 185, # Rice, white, long-grain, regular, cooked, enriched, with salt cup
        '1103657': 1 * 245, # Vegetable curry cup
        '1100622': 0 * 25, # Bread, white, toasted
        '1100187': 2 * 49.6, # Egg, whole, fried no added fat
        '1099246': 1 * 235, # Chicken curry cup
        '1097525': 2 * 244, # Milk, lactose free, whole cup
        '1097524': 0 * 244, # Milk, lactose free, reduced fat (2%) cup
        '1429086': 1 * (57 * 2)/16, # ENSURE, HIGH PROTEIN POWDER, VANILLA, VANILLA 1 cup = 16 tablespoons, 0.5 cup --> 57 g
        '168833' : 2 * 13.56, # Sugars, brown tablespoon
        '1103067': 0 * 60, # Plantain chips 1 cup
        '1101716': 1 * 88, # Cereal, corn flakes, cup
        }
#food_objs = client.get_foods(food_dict_daily)
food_objs = pickle.load(open('mydailyfoodtestbar.pkl', 'rb'))
meal = noms.Meal(food_objs)

r = noms.report(meal)
for i in r:
    #print(i)
    print(i['name'], '\t', i['rda'], '\t', i['value'])

# scale the y values to 100
for data in r:
    if data['rda'] != 0:
        conv = 100/data['rda']
        data['rda'] = 100
        data['value'] *= conv

# termgraph
with open('ytclass_data.dat', 'w') as f:
    print('@', 'rda,y_value', file=f)
    for data in r:
        print(data['name'], data['rda'], data['value'], sep=',', file=f)

#os.system('termgraph ytclass_data.dat --color red blue')

pantry_foods = pickle.load(open('pantry_foods_data.pkl','rb'))

recommendations = noms.generate_recommendations(meal, pantry_foods, noms.nutrient_dict, 3)
for rec in recommendations:
    print(round(rec[2] * 100, 2), 'g', "of", pantry_foods[rec[1]].desc)