def test_data_stabilized_load_removed(self): # Arrange input_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("a26455e2070b0f082a23"), ) expected_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", isStabilized=True, loadRemoved=True, manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("a26455e2070b0f082a23"), sequence= 10787, unit= "kg", weight= 109.3 ) # Act def callback(result_scale): # Assert assert expected_scale == result_scale delegate = ScanDelegate("c8:0f:10:bf:cc:66", callback, False) delegate.handleData(input_scale)
def fromscale(cls, root, scale): ''' Return chord of "root" within "scale" ''' scale = Scale(root, scale) third = scale.transpose(root, 2) fifth = scale.transpose(root, 4) return cls((root, third, fifth))
def lerBalanca(): iScale = Scale() while True: x = iScale.readStability() if (x == "1"): print "balanca foi pressionada" break
def test_scale_are_equals(self): # Arrange first_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", isStabilized=False, loadRemoved=True, manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("820000e2070b0f082924"), sequence= 10532, unit= "kg", weight= 0.0 ) second_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", isStabilized=False, loadRemoved=True, manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("820000e2070b0f082924"), sequence= 10532, unit= "kg", weight= 0.0 ) # Act, Assert assert first_scale == second_scale
def test_data_not_stabilized_load_not_removed(self): # Arrange input_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("02e402b2080101010422"), ) expected_scale = Scale( UUID="181d", address="c8:0f:10:bf:cc:66", isStabilized=False, loadRemoved=False, manufacturerData= bytes.fromhex("5701c80f10bfcc66"), rawData= bytes.fromhex("02e402b2080101010422"), sequence= 1058, unit= "kg", weight= 3.7 ) # Act def callback(result_scale): # Assert assert expected_scale == result_scale delegate = ScanDelegate("c8:0f:10:bf:cc:66", callback, False) delegate.handleData(input_scale)
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.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
def get_cents(self, ratio=None, low=None, high=None): if ratio: return (Scale.get_cents(self, ratio)) else: intervals = ["1", "M2", "M3", "4", "5", "M6", "M7", "1o"] degrees = [1, 18, 20, 21, 3, 27, 30, 2] return (Scale.get_cents(self, low=low, high=high, \ intervals=intervals, degrees=degrees))
def main2(): if len(sys.argv) < 4: print('Usage: python %s input N output' % os.path.basename(__file__)) exit(-1) input_f = sys.argv[1] new_node = int(sys.argv[2]) output = sys.argv[3] scaler = Scale(input_f, new_node, output) scaler.run()
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
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
def get_args(self): if self.op == None: return pts = self._requirements.get(self.op) # Get requirements if self.op == 'rotate': p = PopupWindow(self.pz.frame, "Insira o angulo (em graus)") self.pz.frame.wait_window(p.top) p_list = list(sum(self.pz.buffer[:pts], ())) T = Rotation(float(p.getval()), p_list[0], p_list[1]) if self.op == 'scale': px = PopupWindow(self.pz.frame, "Insira um fator para x") self.pz.frame.wait_window(px.top) py = PopupWindow(self.pz.frame, "Insira um fator para y") self.pz.frame.wait_window(py.top) p_list = list(sum(self.pz.buffer[:pts], ())) T = Scale(float(px.getval()), float(py.getval()), p_list[0], p_list[1]) if self.op == 'translate': px = PopupWindow(self.pz.frame, "Insira um offset para x") self.pz.frame.wait_window(px.top) py = PopupWindow(self.pz.frame, "Insira um offset para y") self.pz.frame.wait_window(py.top) T = Translation(float(px.getval()), float(py.getval())) if self.op == 'zoom': self.zoom(self.pz.buffer[:pts]) T = None self.pz.buffer = self.pz.buffer[pts:] # Remove points of buffer return T
def test_neither_constructor(self): """Make sure it finds nothing when nothing matches exactly.""" scale = Scale(device_manager=self.manager, manufacturer="Fake Vendor", model="DNE") self.assertEqual(scale.device, None)
def test_weigh_5_lb(self): """Make sure the scale properly weighs zero ounces.""" with Scale(device_manager=self.manager) as scale: scale.device.set_weight("5.10 lb") weighing = scale.weigh(endpoint=self.endpoint) self.assertEqual(weighing.weight, 5.10) self.assertEqual(weighing.unit, POUNDS)
def test_weigh_2_kg(self): """Make sure the scale properly weighs 1.94 kilograms.""" with Scale(device_manager=self.manager) as scale: scale.device.set_weight("1.94 kg") weighing = scale.weigh(endpoint=self.endpoint) self.assertEqual(weighing.weight, 1.94) self.assertEqual(weighing.unit, KILOS)
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()
def main(): """Main function""" scale = Scale("A3", "major") params = Params() layers = music_algorithm.make_piece(params, scale.length) timeline_ = timeline.Timeline() render_timeline(timeline_, layers, params, scale) data = timeline_.render(volume=0.05) playback.play(data)
def __init__(self, scales): """ Initializes the ScaleCollection from a dictionary of raw scale data and creates/stores a Scale object for each one. """ # A dictionary of Scale objects keyed by their scale_id. self._scales = {} for key in scales.keys(): self._scales[key] = Scale(key, scales[key])
def Q_train_and_test(): pong = Game() while True: pong.update_q() if pong.finished_training: break x_values = [i[0] for i in pong.training_stats] y_values = [i[1] for i in pong.training_stats] plt.plot(x_values, y_values, 'b', label = 'Average reward') plt.xlabel('Game number') plt.ylabel('Average reward') plt.title('Mean episode rewards vs episodes') plt.grid(True) y_values_2 = [9] * len(x_values) plt.plot(x_values, y_values_2, 'r', label = '9') plt.legend(loc = 'lower right') plt.show() pygame.init() fps = pygame.time.Clock() window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Pong Game') scale = Scale() pong.ball = Ball() pong.paddle = Paddle() pong.state = (pong.ball.x, pong.ball.y, pong.ball.velocity_x, pong.ball.velocity_y, pong.paddle.y) pong.agent.epsilon = 0 pong.is_active = True pong.score = 0 pong.game_number = 0 while True: # draw(pong.ball, pong.paddle, scale, window) pong.update_test_q() if pong.finished_testing: break # pygame.display.update() # fps.tick(30) x_values = [i[0] for i in pong.test_stats] y_values = [i[1] for i in pong.test_stats] print(pong.test_stats) print(float(sum(y_values))/len(y_values)) plt.plot(x_values, y_values) plt.xlabel('Game number') plt.ylabel('Reward') plt.title('Rewards/game for 200 test games') plt.show()
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)
def test_both_scale_constructor(self): """Make sure it can find a scale when both arguments are supplied.""" scale = Scale(device_manager=self.manager, manufacturer="Faux Manufacturer", model="Faux Scale") self.assertEqual(scale.device.idVendor, mocks.usb_ids.FAUX_MFR) self.assertEqual(scale.device.idProduct, mocks.usb_ids.SCALE) self.assertIn("Faux Manufacturer", scale.name) self.assertIn("Faux Scale", scale.name)
def test_both_other_constructor(self): """Make sure it find anything when both arguments are supplied.""" scale = Scale(device_manager=self.manager, manufacturer="Fake Vendor", model="Fake Device of Some Other Stripe") self.assertEqual(scale.device.idVendor, mocks.usb_ids.FAKE_VDR) self.assertEqual(scale.device.idProduct, mocks.usb_ids.OTHER) self.assertIn("Fake Vendor", scale.name) self.assertIn("Fake Device of Some Other Stripe", scale.name)
class Generator(object): def __init__(self): self.chain = Chain().make() self.angle_scale = Scale([-1.0, 1.0], [-0.5, 0.5]) self.position_scale = Scale([-3.0, 3.0], [-0.5, 0.5]) def generate_angles(self): theta1 = np.random.uniform(-1.0, 1.0) theta2 = np.random.uniform(-1.0, 1.0) theta3 = np.random.uniform(-1.0, 1.0) return [theta1, theta2, theta3] def scale_angles(self, a): theta1 = self.angle_scale.forward_scale(a[0]) theta2 = self.angle_scale.forward_scale(a[1]) theta3 = self.angle_scale.forward_scale(a[2]) return [theta1, theta2, theta3] def generate_positions(self, a): p = self.chain.forward({ 'theta1': a[0], 'theta2': a[1], 'theta3': a[2] }) return ([p[0], p[1], p[2]]) def scale_positions(self, p): p0 = self.position_scale.forward_scale(p[0]) p1 = self.position_scale.forward_scale(p[1]) p2 = self.position_scale.forward_scale(p[2]) return [p0, p1, p2] def make(self, batch_size): while 1: features = [] labels = [] for i in range(batch_size): angles = self.generate_angles() positions = self.generate_positions(angles) features.append(self.scale_positions(positions)) labels.append(self.scale_angles(angles)) yield np.array([features, labels])
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)
class AnyScaleTest(unittest.TestCase): def setUp(self): self.scale = Scale() def tearDown(self): self.scale = None # 测试用例 1,测试十进制下的 16 转化为十六进制。 def test1_10_16_16(self): self.assertEquals('10', self.scale.any_scale(10, 16, 16)) # 测试用例 2,测试十进制下的 17 转化为八进制。 def test2_10_17_8(self): self.assertEquals('19', self.scale.any_scale(10, 17, 8)) # 测试用例 3,测试八进制下的 19 转化为十进制。 def test3_8_19_10(self): self.assertEquals('17', self.scale.any_scale(8, 19, 10))
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)
def infer(self): Flow().defaults() model = Model().make_fcn() model.load_weights('model_weights.h5') chain = Chain().make() angle_scale = Scale([-1.0, 1.0], [-0.5, 0.5]) position_scale = Scale([-3.0, 3.0], [-0.5, 0.5]) # Reference angles theta1_ref = 0.3 theta2_ref = 0.4 theta3_ref = 0.35 ref = np.array([theta1_ref, theta2_ref, theta3_ref]) print('\nReference angles:') print(ref) # Forward kinematic positions px, py, pz = chain.forward({ 'theta1': theta1_ref, 'theta2': theta2_ref, 'theta3': theta3_ref }) print('\nComputed positions:') print(np.array([px, py, pz])) # Normalize the position px = position_scale.forward_scale(px) py = position_scale.forward_scale(py) pz = position_scale.forward_scale(pz) p = np.array([[px, py, pz]]) # Inference returns normalized angle r = model.predict(p) # De-normalized inference angles theta1_ik = angle_scale.reverse_scale(r[0][0]) theta2_ik = angle_scale.reverse_scale(r[0][1]) theta3_ik = angle_scale.reverse_scale(r[0][2]) inf = np.array([theta1_ik, theta2_ik, theta3_ik]) print('\nInferred IK angles:') print(inf) # Relative error err = np.abs(ref - inf) / ref print('\nAngle error (relative):') print(err)
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)
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)
def identify(o_notes, o_uncertainty): """Tries to identify which chord is being played Returns: (str) - the chord being played """ o_notes = [i[1][:-1] for i in o_notes] chord_certainties = [] for chord in ChordIdentifier._chords: counter = 0 certainty = 0 for i, note in enumerate(o_notes): if note in chord['notes']: certainty += 1 - o_uncertainty[i] elif any(v in chord for v in Scale.next_to(note)): certainty += o_uncertainty[i] counter += 1 chord_certainties.append(certainty / counter) return ChordIdentifier._chords[chord_certainties.index( max(chord_certainties))], max(chord_certainties)
def setUp(self): self.s = Scale() self.s2= Scale() self.carrot = Vegetable('carrot', 2) self.onion = Vegetable('onion', 1) self.tomato = Vegetable('tomato', 3)
class ScaleTestCase(unittest.TestCase): def setUp(self): self.s = Scale() self.s2= Scale() self.carrot = Vegetable('carrot', 2) self.onion = Vegetable('onion', 1) self.tomato = Vegetable('tomato', 3) def test_add_remove_item(self): self.assertEqual(self.s.add_item(self.onion), 1) self.assertEqual(self.s.add_item(self.carrot), 3) self.assertEqual(self.s.add_item(self.tomato), 6) self.assertEqual(self.s2.add_item(self.tomato), 3) # remove item assertions self.assertEqual(self.s.remove_item('tomato'), 3) self.assertEqual(self.s.remove_item('onion'), 2) self.assertEqual(self.s.remove_item('carrot'), 0) def test_list_items(self): self.assertEqual(self.s.list_items(), []) self.s.add_item(self.carrot) self.assertEqual(self.s.list_items(), ['carrot']) self.s.add_item(self.onion) self.assertEqual(self.s.list_items(), ['carrot','onion']) self.s.add_item(self.tomato) self.assertEqual(self.s.list_items(), ['carrot', 'onion', 'tomato']) self.s.remove_item('onion') self.assertEqual(self.s.list_items(), ['carrot', 'tomato']) self.s.remove_item('carrot') self.assertEqual(self.s.list_items(), ['tomato']) self.s.remove_item('tomato') self.assertEqual(self.s.list_items(), [])
def third(self, scale='major'): from scale import Scale scale = Scale(self, scale) return scale.transpose(self, 2)
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)
def fifth(self, scale='major'): from scale import Scale scale = Scale(self, scale) return scale.transpose(self, 4)
def seventh(self, scale='major'): from scale import Scale scale = Scale(self, scale) return scale.transpose(self, 6)
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)
def octave(self, scale='major'): from scale import Scale scale = Scale(self, scale) return scale.transpose(self, 7)
def second(self, scale='major'): from scale import Scale scale = Scale(self, scale) return scale.transpose(self, 1)