Beispiel #1
0
 def chromatic_transpose(self, semitones):
     """
     Transpose note in chromatic scale
     """
     scale = Scale(root='C',
                   notes=[
                       'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A',
                       'A#', 'B'
                   ])
     return self.diatonic_transpose(semitones, scale)
Beispiel #2
0
 def getScaleInfo(self, dev):
     scale = Scale(address=dev.addr)
     
     for (adtype, desc, value) in dev.getScanData():
         if adtype == AD_TYPES.SERVICE_DATA:
             scale.UUID = bytes.fromhex(value[0:4])[::-1].hex()
             scale.rawData = bytes.fromhex(value[4:])
         elif adtype == AD_TYPES.MANIFACTURER:
             scale.manufacturerData = bytes.fromhex(value)
     return scale
Beispiel #3
0
def foodSense():
    print('Starting Food Sense')

    # Begin initializing necessary components)
    fb = Firebase()
    detect = Detect(fb)
    monitor = Monitoring(fb)
    scale = Scale()

    # Set scale calibration
    scale.setReferenceUnit(-25.725)
    scale.reset()
    scale.tare()

    ### START DEBUG ###
    ### END DEBUG ###

    ### MAIN LOOP ###
    while True:
        while monitor.powerOn:
            print('Power is on')
            time.sleep(1)
            
            while monitor.doorClosed():
                print('Door is closed')
                monitor.checkTemp()
                time.sleep(1)

                if monitor.doorOpen():
                    print('Door was opened')
                    monitor.startDoorTimer()
                    
                    while monitor.doorOpen():
                        print('Waiting for door to close')
                        monitor.checkDoorTimer()
                        monitor.checkTemp()
                        time.sleep(1)
                    else:
                        print('Door was closed')

                        scale.getWeight()
                        detect.getImage()
                        detect.detectItem()
                        detect.parseResponse(scale.weight)
                else:
                    pass
            else:
                print('Door must be closed on program startup')
        else:
            monitor.powerSave()
    else:
        pass
Beispiel #4
0
 def test_scale(self):
     print("SCALE TESTS")
     print("c major")
     s = Scale([2, 2, 1, 2, 2, 2, 1], 0)  # C Major
     self.assertTrue(
         compare_scales(
             s.get_scale(), ["n0", "n2", "n4", "n5", "n7", "n9", "n11", "n0"]
         )
     )
     self.assertTrue(
         compare_scales(
             s.get_scale(
                 pitch_format=[
                     "c",
                     "c#",
                     "d",
                     "d#",
                     "e",
                     "f",
                     "f#",
                     "g",
                     "g#",
                     "a",
                     "a#",
                     "b",
                 ]
             ),
             ["c", "d", "e", "f", "g", "a", "b", "c"],
         )
     )
     print("g major")
     s = Scale([2, 2, 1, 2, 2, 2, 1], 7)  # G Major
     self.assertTrue(
         compare_scales(
             s.get_scale(), ["n7", "n9", "n11", "n0", "n2", "n4", "n6", "n7"]
         )
     )
     self.assertEqual(s.get_scale_and_octave_deltas()[1][3], 1)
Beispiel #5
0
 def __init__(self,
              tuning_type='equal',
              initial_duration=1,
              initial_root_tonality_frequency=440):
     self.duration = initial_duration
     self.set_root_tonality_frequency(initial_root_tonality_frequency)
     self.scale = Scale().get_ratios(tuning_type)
     intervals = [0 for i in range(5)]
     self.synths = [
         self.synthesize(freq=(self.root_tonality_frequency * interval))
         for interval in intervals
     ]
     self.set_envelope(self.duration)
     self.chord_generator = Chord(self.scale, self.root_tonality_frequency)
Beispiel #6
0
    def initFrame(self):
        self.timer = QBasicTimer()
        self.myscale = Scale(10202)

        self.lbl_weight = QLabel(self)
        self.lbl_weight.setObjectName('lbl_weight')
        self.lbl_weight.setText("0.000")
        self.lbl_weight.resize(500, 100)
        self.lbl_weight.move(200, 50)

        lbl_unit = QLabel(self)
        lbl_unit.setObjectName('lbl_unit')
        lbl_unit.setText("kg")
        lbl_unit.resize(100, 120)
        lbl_unit.move(500, 40)

        #self.lbl_status = QLabel(self)
        #self.lbl_status.setText("MAYBE ON")
        #self.lbl_status.resize(100, 100)
        #self.lbl_status.move(700, 10)

        #qbtn = QPushButton('Jalla', self)
        #qbtn.clicked.connect(QApplication.instance().quit)
        #qbtn.resize(qbtn.sizeHint())
        #qbtn.move(150, 150)

        self.setObjectName('ScaleFrame')
        self.setStyleSheet("""
            #ScaleFrame {
                background-color: #cfcfcf;
            }
            .QLabel#lbl_weight {
                font-size:100pt;
                color: #ff0000;
            }
            .QLabel#lbl_unit {
                font-size:100pt;
                color: #000000;
            }
            .QLabel {
                font-size:22pt;
                color: #000000;
            }
        """)
        self.start_timer()
Beispiel #7
0
    def scale(self, context, width, height):
        if not self.width:
            self.width = width

        if not self.height:
            self.height = height

        scale = Scale()

        if width:
            scale.horizontal = self.width / width

        if height:
            scale.vertical = self.height / height

        if scale.horizontal:
            context.scale(scale.horizontal, 1.0)

        if scale.vertical:
            context.scale(1.0, scale.vertical)
Beispiel #8
0
    def scale(self, context, width, height):
        if not self.width:
            self.width = width

        if not self.height:
            self.height = height

        scale = Scale()
        scale.horizontal = self.width / float(width)
        scale.vertical = self.height / float(height)

        if scale.horizontal:
            context.scale(scale.horizontal, 1.0)
        else:
            scale.horizontal = 1

        if scale.vertical:
            context.scale(1.0, scale.vertical)
        else:
            scale.vertical = 1

        return (scale.horizontal, scale.vertical)
Beispiel #9
0
'''
Bot setup
'''
update_id = None
config = "config.ini"
bot = telegram_chatbot(config)

'''
Parser setup
'''
parser = configparser.SafeConfigParser()

'''
Scale setup
'''
scale = Scale(5, 6, 1509)

'''
cleanAndExit. Cleans the GPIO and exists in case of a
KeyboardInterrupt
'''
def cleanAndExit():
    GPIO.cleanup()
    sys.exit()

'''
get_timestamp - returns the timestamp in format:
DAY/MONTH/YEAR HOUR:MINUTE
'''
def get_timestamp():
    date = datetime.datetime.now()
Beispiel #10
0
 def setUp(self):
     self.scale = Scale('0', '1.34', 'chicken')
Beispiel #11
0
    # ),
    # AtChannel(9)(
    #     Amplify(0.5)(
    #         Repeat(8)(drum_reef)
    #     )
    # )
])

from instruments.ensemble import string_ensemble_1
from instruments.synth_lead import lead_1_square
from instruments.bass import synth_bass_1
from instruments.piano import acoustic_grand_piano
from instruments.drum_kits import standard_drum_kit

mid = to_midi(song,
              Scale([b + trans_key for b in scale_c_minor.base]),
              instruments={
                  0: lead_1_square,
                  1: string_ensemble_1,
                  2: synth_bass_1,
                  3: acoustic_grand_piano,
                  9: standard_drum_kit
              })
mid.save('new_song.mid')

import os
import subprocess
FNULL = open(os.devnull, 'w')
subprocess.call(['timidity', 'new_song.mid'],
                stdout=FNULL,
                stderr=subprocess.STDOUT)
Beispiel #12
0
from typing import List

from scale import Scale

scale_list: List[Scale] = [
    Scale(name='Major', pattern=[0, 2, 4, 5, 7, 9, 11]),
    Scale(name='Minor', pattern=[0, 2, 3, 5, 7, 8, 10])
]
Beispiel #13
0
    def test_scale_constructor(self):
        """Make sure it can find a scale when only the model is supplied."""

        scale = Scale(device_manager=self.manager, model="Fake Scale")
        self.assertEqual(scale.device.idProduct, mocks.usb_ids.SCALE)
Beispiel #14
0
    def test_empty_constructor(self):
        """Make sure it finds a scale by default."""

        scale = Scale(device_manager=self.manager)
        self.assertEqual(scale.device.idProduct, mocks.usb_ids.SCALE)
Beispiel #15
0
import usb.core
import usb.util
import config
from time import sleep
import threading
from scale import Scale
from AwsClient import AwsClient

PUBLISH_WEIGHT_INTERVAL = 300

if not config.config_file_exists():
    config.create_config_file()

dymo_scale = Scale()
aws_client = AwsClient()

while True:
    scale_reading = dymo_scale.read_scale()
    aws_client.publish_weight(scale_reading)
    print(scale_reading)
    sleep(PUBLISH_WEIGHT_INTERVAL)
Beispiel #16
0
                None: 'orange',
                'Otros': 'purple',
                'Privado': 'purple',
                'Sociedad_Civil': 'yellow'}


offcenter = 80
center = (500, 400)
rotation = -180

############
# Ego axis #
############
ego_count = Alter.objects.filter(name__contains='TL0').count()
ego_scale = Scale(domain=[Alter.objects.order_by('degree')[0].degree,
                          Alter.objects.order_by('-degree')[0].degree],
                  range=[5, 30])
ego_axis_len = sum([ego_scale.linear(e.degree) * 2.0
                    for e in Alter.objects.filter(name__contains='TL0').all()])

ego_axis_origin = rotate(offcenter + 100,
                         angle=rotation,
                         origin=center)
axis_egos = Axis(ego_axis_origin,
                 rotate(offcenter + ego_axis_len,
                        angle=rotation,
                        origin=ego_axis_origin),
                 stroke="purple",
                 stroke_opacity="1", stroke_width=2)

# place ego nodes on ego axis
Beispiel #17
0
deviceID = config.get("DEFAULT", "deviceID")
contributionType = config.get("DEFAULT", "contributionType")
emailsDev = ast.literal_eval(config.get("EMAILS", "developers"))
emailUser = ast.literal_eval(config.get("EMAILS", "emailUser"))
emailsInfra = ast.literal_eval(config.get("EMAILS", "infraestructure"))

try:
    iGpio = MyGPIO()
except:
    print "GPIO Problem"
try:
    conn = CTDRequest()
except:
    print "Connection problem"
try:
    iScale = Scale()
except:
    print "scale problem"

while True:
    success = 1
    while (success == 1):
        try:
            iGpio.clear()
            iGpio.lcdPrint("Pass your badge\non the reader")
            iGpio.lcdBlink(True)
            userRFID = iGpio.readTag()

        except KeyboardInterrupt:
            print "interrupted by admin"
            sys.exit()
# TODO Add a switch, so different algorithms can be chosen by the user
def fill_notes(song):
    """
    Fills in the notes of a song.
    Preconditions:
        The song's has at least one phrase
        Each phrase has at least one segment
        Each segment has a direction and some note constraints
    """
    # TODO Assert preconditions

    return _fill_notes_stepwise(song)

if __name__ == "__main__":
    from helpers import note_name_to_midi

    c_pentatonic = Scale('C', [0, 3, 5, 8, 10])
    first_phrase = Phrase(phrase_elements=[Segment(6), LandingNote(duration=2, pitch='Eb4'), Rest(1), Segment(4)], scale=c_pentatonic)
    second_phrase = Phrase(phrase_elements=[Segment(6), LandingNote(duration=2, pitch='F4'), Rest(1), Segment(2)], scale=c_pentatonic)
    phrases = [first_phrase, second_phrase]
    song = Song(phrases = phrases)

    sequences = _generate_possible_notes(
        6, [note_name_to_midi('C4'), note_name_to_midi('C5')],
        c_pentatonic, SegmentDirection.DOWNUP)

    fill_directions(song)
    add_note_constraints(song)
    fill_notes(song)

Beispiel #19
0
 def createScalePort(self):
     self.scale = Scale(self.scale_com.get().upper())
Beispiel #20
0
 def setUp(self):
     self.s = Scale()
     self.s2= Scale()
     self.carrot = Vegetable('carrot', 2)
     self.onion = Vegetable('onion', 1)
     self.tomato = Vegetable('tomato', 3)
Beispiel #21
0
def flights2kmz(flights, roots=[], tz_offset=0, task=None):
    stock = Stock()
    globals = util.OpenStruct()
    globals.stock = stock
    globals.bounds = util.BoundsSet()
    for flight in flights:
        globals.bounds.update(flight.track.bounds)
    if globals.bounds.climb.min < -5.0:
        globals.bounds.climb.min = -5.0
    if globals.bounds.climb.max > 5.0:
        globals.bounds.climb.max = 5.0
    globals.tz_offset = datetime.timedelta(0, 3600 * tz_offset)
    globals.task = task
    globals.scales = util.OpenStruct()
    globals.scales.altitude = Scale(globals.bounds.ele.tuple(),
                                    title='altitude',
                                    gradient=default_gradient)
    globals.altitude_styles = []
    for i in xrange(0, 3):
        altitude_styles = []
        for c in globals.scales.altitude.colors():
            balloon_style = kml.BalloonStyle(text='$[description]')
            icon_style = kml.IconStyle(globals.stock.icons[i],
                                       color=c,
                                       scale=globals.stock.icon_scales[i])
            label_style = kml.LabelStyle(color=c,
                                         scale=globals.stock.label_scales[i])
            style = kml.Style(balloon_style, icon_style, label_style)
            altitude_styles.append(style)
        stock.kmz.add_roots(*altitude_styles)
        globals.altitude_styles.append(altitude_styles)
    gradient = bilinear_gradient
    globals.scales.climb = ZeroCenteredScale(globals.bounds.climb.tuple(),
                                             title='climb',
                                             step=0.1,
                                             gradient=gradient)
    globals.scales.speed = Scale(globals.bounds.speed.tuple(),
                                 title='ground speed',
                                 gradient=default_gradient)
    globals.scales.time = TimeScale(globals.bounds.time.tuple(),
                                    tz_offset=globals.tz_offset)
    globals.scales.tec = ZeroCenteredScale(
        globals.bounds.tec.tuple(),
        title='climb with energy compensation',
        gradient=gradient)
    globals.scales.t = Scale(globals.bounds.t.tuple(),
                             title='time',
                             gradient=default_gradient)
    if hasattr(globals.bounds, 'tas'):
        globals.scales.tas = Scale(globals.bounds.tas.tuple(),
                                   title='air speed',
                                   gradient=default_gradient)
    globals.graph_width = 600
    globals.graph_height = 300
    globals.default_track = 'solid_color'
    if len(flights) == 1:
        if flights[0].track.elevation_data:
            globals.default_track = 'climb'
        else:
            globals.default_track = 'speed'
    result = kmz.kmz()
    result.add_siblings(stock.kmz)
    result.add_roots(kml.open(1), *roots)
    if globals.task:
        result.add_siblings(make_task_folder(globals, globals.task))
    for flight in flights:
        result.add_siblings(flight.to_kmz(globals))
    return result
    'Otros': 'purple',
    'Privado': 'purple',
    'Sociedad_Civil': 'gold'
}

offcenter = 80
center = (500, 400)
rotation = -180

############
# Ego axis #
############
ego_count = Alter.objects.filter(name__contains='TL0').count()
ego_scale = Scale(domain=[
    Alter.objects.order_by('degree')[0].degree,
    Alter.objects.order_by('-degree')[0].degree
],
                  range=[5, 30])
ego_axis_len = sum([
    ego_scale.linear(e.degree) * 2.0
    for e in Alter.objects.filter(name__contains='TL0').all()
])

ego_axis_origin = rotate(offcenter + 100, angle=rotation, origin=center)
axis_egos = Axis(ego_axis_origin,
                 rotate(offcenter + ego_axis_len,
                        angle=rotation,
                        origin=ego_axis_origin),
                 stroke="purple",
                 stroke_opacity="1",
                 stroke_width=2)
Beispiel #23
0
        'ref': 399,  # output from calibration procedure				
        'sku': "98099",
        'name': "Bohrer 2mm",
        'weight': 23.39,  # in gram
        'price': 19.90
    }
}
#pprint.pprint (config)

# initialize scales
scales = {}
transactions = {}
#print (config['Scale 1'])
for key in config:
    print("Initializing " + key)
    scales[key] = Scale(HX711(config[key]['dout'], config[key]['spd_sck']))
    scales[key].setReferenceUnit(config[key]['ref'])
    scales[key].reset()
    transactions[key] = {
        'weight': 0.0,
        'prev_weight': 0.0,
        'weight_loss': 0,
        'items_taken': 0,
        'description': "",
        'price': 0.0
    }

# tare scales
for key in config:
    print("Taring " + key)
    scales[key].reset()
Beispiel #24
0
    os.makedirs(videopath)

if not os.path.exists(datapath):
    os.makedirs(datapath)

# Define camera variable and its settings
camera = PiCamera()
camera.rotation = 0
camera.resolution = (1296, 730)
camera.framerate = 30
camera.annotate_foreground = Color('white')
camera.annotate_background = Color('black')
cameraAnnoSize = 50

# Load the scale and tare it
scale = Scale()  # Turns the scale on
scale.setReferenceUnit(4001.7805)  # Calibration factor for load-cell
scale.reset()  # Resets the HX711 chip
scale.tare()  # Tares the load-cell - Sets output to zero.
scale.reset()  # Resets the HX711 chip
scale.tare()  # Tares the load-cell - Sets output to zero.

# Turn on LED
GPIO.setup(26, GPIO.OUT)
GPIO.output(26, True)

print("Scale ready...")  # Prints a ready to terminal for debugging

# Open a new CSV file, naming and storing it as defined above
with open(csvLocation, "w", newline="") as csvfile:
Beispiel #25
0


pygame.init()
screen=pygame.display.set_mode(SCREEN_SIZE, pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN)


#Main Game Loop:
FPS=60
clock=pygame.time.Clock()



#initialisations
keyboard=Keyboard()
scale=Scale()
goals=Goals()
visual=visual()
chordbox=Chordbox()
chordrec=ChordRec()
sound=Sound()


screen.fill((255,255,255))
pygame.draw.rect(screen, (0,0,0), pygame.Rect(0,HEIGHT*.8, WIDTH*.75, HEIGHT*.2), 2)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(WIDTH*.75,HEIGHT*.75, WIDTH*.25, HEIGHT*.25), 2)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(WIDTH*.75,0, WIDTH*.25, HEIGHT*.75), 2)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(0,HEIGHT*.1, WIDTH*.75, HEIGHT*.7), 2)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(WIDTH*.125,0, WIDTH*.5, HEIGHT*.1), 2)
scroll=0
while True:
Beispiel #26
0
    def run(self):
        # Set up LED pin
        LED = 27
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(LED, GPIO.OUT)

        # Initialize objects
        f = Firebase(self.q)
        d = Detect(f, self.q)
        m = Monitoring(f, self.q)
        s = Scale(self.q)

        # Set scale calibration
        s.setReferenceUnit(-25.725)
        s.reset()
        s.tare()

        self.q.put('Ready')

        # Loop until stop event is set
        while not self.event.is_set():

            # Loop while RPi is on AC power
            while m.powerOn:

                # Check if stop has been set
                if self.event.is_set():
                    break

                # Loop while fridge door is closed
                while m.doorClosed():
                    if not m.powerOn():
                        break
                    m.checkTemp()

                    # Check if stop hsa been set
                    if self.event.is_set():
                        break
                else:
                    print('Door was opened')
                    self.q.put('Door opened')
                    GPIO.output(LED, True)
                    m.startDoorTimer()

                    while m.doorOpen():
                        print('Waiting for door to close')

                        m.checkDoorTimer()
                        m.checkTemp()
                    else:
                        print('Door closed')
                        self.q.put('Door closed')

                        s.getWeight()
                        d.getImage()
                        d.detectItem()
                        d.parseResponse(s.weight)
                        s.tare()
                        GPIO.output(LED, False)

                        print('Done')
                        self.q.put('Done')
            else:
                m.powerSave()

        f.close(
        )  # Firebase app must be closed before we can create another instance
Beispiel #27
0
    def test_vendor_constructor(self):
        """Make sure it can find a manufacturer by name."""

        scale = Scale(device_manager=self.manager, manufacturer="Fake Vendor")
        self.assertEqual(scale.device.idVendor, mocks.usb_ids.FAKE_VDR)
        self.assertIn("Fake Vendor", scale.name)
Beispiel #28
0
#!/usr/bin/env python

import csv
from scale import Scale
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []

thescale = Scale('192.168.1.4', '4001')

with open('output.csv', 'w', newline='') as csvfile:
    datawriter = csv.writer(csvfile,
                            delimiter=';',
                            quotechar='"',
                            quoting=csv.QUOTE_MINIMAL)
    datawriter.writerow(["timenow", "weightnow"])

    # This function is called periodically from FuncAnimation
    def animate(i, xs, ys):
        # Add x and y to lists
        timenow = dt.datetime.now().strftime('%H:%M:%S')

        scaledata = thescale.lastdata()
        weightnow = scaledata[2]
Beispiel #29
0
 def setUp(self):
     self.scale = Scale()
Beispiel #30
0
from midi_generator import MIDIGenerator
from melody_composer import MelodyComposer
from chord_composer import ChordComposer
from scale import Scale

output_file_name = "output.mid"
duration_beats = 1024
scale = Scale('C').major

test_melody = MelodyComposer().compose(scale, duration_beats)
chords = ChordComposer(scale).get_random_chords(duration_beats)

MIDIGen = MIDIGenerator(output_file_name)

MIDIGen.add_melody(test_melody)

for chord in chords:
    # Assumes 3 notes in chord
    MIDIGen.add_chord(chord.notes, chord.time, chord.beats)

MIDIGen.write_midi_to_file()