def createWave(self): """ Create the wave, using whatever starting point (basic, copy, function, etc) is necessary. """ # Check if the wave is unique in the application if not self._app.waves().goodWaveName(Util.getWidgetValue(self._ui.createWave_waveName)): warningMessage = QMessageBox() warningMessage.setWindowTitle("Error!") warningMessage.setText("The name you chose has already been used. Please enter a new name.") warningMessage.setIcon(QMessageBox.Critical) warningMessage.setStandardButtons(QMessageBox.Ok) warningMessage.setDefaultButton(QMessageBox.Ok) result = warningMessage.exec_() return False wave = Wave( Util.getWidgetValue(self._ui.createWave_waveName), Util.getWidgetValue(self._ui.createWave_dataType) ) # Check how the wave should be initially populated initialWaveDataTab = self._ui.waveDataStack.currentWidget().objectName() if initialWaveDataTab == "basicTab": # Basic wave. Need to determine the type basicWaveType = Util.getWidgetValue(self._ui.basicWaveType) if basicWaveType == "Blank": pass elif basicWaveType == "Index (starting at 0)": basicWaveLength = Util.getWidgetValue(self._ui.basicWaveLength) wave.extend(range(0, basicWaveLength)) elif basicWaveType == "Index (starting at 1)": basicWaveLength = Util.getWidgetValue(self._ui.basicWaveLength) wave.extend(range(1, basicWaveLength + 1)) elif initialWaveDataTab == "copyTab": # Copy the data from another wave originalWave = ( self._ui.copyWaveOriginalWave.model() .index(self._ui.copyWaveOriginalWave.currentIndex(), 0) .internalPointer() ) startingIndex = Util.getWidgetValue(self._ui.copyWaveStartingIndex) endingIndex = Util.getWidgetValue(self._ui.copyWaveEndingIndex) wave.extend(originalWave.data(startingIndex, endingIndex)) elif initialWaveDataTab == "functionTab": waveLength = Util.getWidgetValue(self._ui.functionWaveLength) functionString = Util.getWidgetValue(self._ui.functionEquation) data = self.parseFunction(waveLength, functionString) wave.extend(data) # Add wave to application self._app.waves().addWave(wave) # Reset certain ui fields self._ui.copyWaveOriginalWave.setCurrentIndex(0) self._ui.functionInsertWave.setCurrentIndex(0)
def importData(self): """Import data into the application as waves.""" # Check if the proposed wave name is acceptable validatedWaveName = Wave.validateWaveName(Util.getWidgetValue(self._ui.waveName)) if not self._app.waves().goodWaveName(validatedWaveName): badWaveNameMessage = QMessageBox() badWaveNameMessage.setText("Wave name is not allowed or already in use. Please change the wave name.") badWaveNameMessage.exec_() return False # Get data type and size uiDataType = Util.getWidgetValue(self._ui.dataType) uiByteOrder = Util.getWidgetValue(self._ui.byteOrder) dataType = self.dataTypes[uiDataType]['dtype'] dataTypeChar = self.dataTypes[uiDataType]['char'] numBytes = self.dataTypes[uiDataType]['numbytes'] byteOrder = self.byteOrders[uiByteOrder] # Load data fileName = Util.getWidgetValue(self._ui.fileName) if os.path.isfile(fileName): data = [] wave = Wave(str(validatedWaveName), dataType) self._app.waves().addWave(wave) fh = open(fileName, 'rb') binDatum = fh.read(numBytes) while binDatum != "": try: datum = struct.unpack(byteOrder + dataTypeChar, binDatum) wave.push(datum[0]) except: pass binDatum = fh.read(numBytes) # data = array.array(dataTypeChar) # numDataPoints = os.path.getsize(fileName) / data.itemsize # fh = open(fileName, 'rb') # data.fromfile(fh, numDataPoints) # # wave = Wave(str(validatedWaveName), dataType) # wave.replaceData(data) # self._app.waves().addWave(wave) # Close window self.window.hide()
def play(self, musicalNote): if musicalNote == None: self.mute() else: self.wave = Wave(self.system.getFrequency(musicalNote), self.samplingRate) self.samplesToMute = None
def __init__(self): # pygame initializations pygame.init() self.screen = pygame.display.set_mode(s.SCREEN_SIZE) pygame.display.set_caption('Blasteroids') self.clock = pygame.time.Clock() self.volume = .1 Sounds.set_se_volume(self.volume) self.wave_font = pygame.font.SysFont('arialblack', 35) self.score_font = pygame.font.SysFont('arialblack', 17) # background and cursor surfaces self.surfaces = {'background': pygame.image.load('assets/background.png').convert(), 'cursor': pygame.image.load('assets/cursor.png').convert_alpha(), 'tower': pygame.image.load('assets/tower.png').convert_alpha(), 'hp_outline': pygame.image.load('assets/health_bar_outline.png').convert_alpha()} # game's main variables self.health = 100 self.inv = Inventory() self.current_weapon = self.inv.armory['cannon'] self.wave = Wave() self.score = 0 self.firing = False self.auto_fire = False
def createWaves(self): self.waves = {} _begin = datetime.combine(self.day, self.firstBrief) + self.briefLength for i in range(1, self.waveNumber + 1): _end = _begin + self.waveLength w = Wave(i) w.begin = _begin w.end = _end w.schedule = self w.times["Flyer"].begin = _begin - self.briefLength w.times["Flyer"].end = _end + self.briefLength w.times["Plane"].begin = _begin w.times["Plane"].end = _end self.waves[i] = w _begin = _end self.findExclusiveWaves()
def createWaves(sked, rows, waves): for row in rows: i = int(row["wave_ID"]) wave_entry = waves[i] #if verbose: print row["schedule_ID"],row["wave_ID"],row["priority"] w = Wave(i) #Plane times midnight = datetime.combine(sked.day, time(0)) start_time = midnight + wave_entry["plane_start"] end_time = midnight + wave_entry["plane_end"] w.begin = start_time w.end = end_time w.times["Plane"].begin = start_time w.times["Plane"].end = end_time #Flyer times start_time = midnight + wave_entry["flyer_start"] end_time = midnight + wave_entry["flyer_end"] w.times["Flyer"].begin = start_time w.times["Flyer"].end = end_time w.schedule = sked w.priority = float(row["priority"]) if wave_entry["student_multiple"] != None: w.studentMultiple = float(wave_entry["student_multiple"]) sked.waves[i] = w sked.findExclusiveWaves()
def goodWaveName(self, name): """ Determine if name is a good Wave name for this Waves object. Returns False if name is an empty string. Returns True if name is not an empty string and is unique. """ name = Wave.validateWaveName(name) if name == "": return False return self.uniqueWaveName(name)
def validateWaveNames(self): """ Run Wave.validateWaveName on all potential wave names. """ dataTable = self._ui.data for col in range(dataTable.columnCount()): if dataTable.item(1, col): dataTable.setItem(1, col, QTableWidgetItem(Wave.validateWaveName(str(dataTable.item(1, col).text()))))
def importData(self): """Import data into the application as waves.""" dataTable = self._ui.data # Loop through all waves for col in range(dataTable.columnCount()): dataType = Util.getWidgetValue(dataTable.cellWidget(0, col)) wave = Wave(str(dataTable.item(1, col).text()), dataType) for row in range(2, dataTable.rowCount()): if dataTable.item(row, col): wave.push(str(dataTable.item(row, col).text())) else: wave.push('') self._app.waves().addWave(wave) # Close window self.clearTable() self.window.hide()
def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate=44100): self.note = note self.volume = 1 # Full colume for starters self.samplingRate = samplingRate # How many samples will I have to play? self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute)) if self.note.times != None: self.totalSamples /= self.note.times if note.dots: self.totalSamples = int(self.totalSamples * (2.0 - pow(2, -note.dots))) self.wave = Wave(tuningSystem.getFrequency(note), samplingRate) self.counter = 0 self.volumeRate = None self.tied = False
class LilypondNotePlayer: def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate = 44100): self.note = note self.volume = 1 # Full colume for starters self.samplingRate = samplingRate # How many samples will I have to play? self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute)) if self.note.times != None: self.totalSamples /= self.note.times if note.dots: self.totalSamples = int(self.totalSamples * ( 2.0 - pow(2, - note.dots))) self.wave = Wave(tuningSystem.getFrequency(note), samplingRate) self.counter = 0 self.volumeRate = None self.tied = False def getNextValue(self): self.counter+=1 # Do we have to lower the volume? if not self.tied and self.totalSamples - self.counter <= self.samplingRate * 0.05: # 5 hundredths of a second # Have to calculate a volume rate if self.totalSamples <= self.counter: self.volumeRate = 0 else: self.volumeRate = math.exp(math.log(0.01) / (self.totalSamples - self.counter)) sys.stderr.flush() if self.volumeRate != None: self.wave.setVolume(self.volume * self.volumeRate) return self.wave.getNextValue() def setTied(self, value): self.tied = value def isTied(self): return self.tied def isFinished(self): return self.counter >= self.totalSamples def setNewDuration(self, totalSamples): self.counter = 0 self.totalSamples = totalSamples def getAngle(self): return self.wave.getAngle() def setAngle(self, angle): self.wave.setAngle(angle) def getFrequency(self): return self.wave.getFrequency()
def main(): s = Sniv() s.begin = datetime(2015, 3, 28, 8) s.end = datetime(2015, 3, 28, 9, 30) w = Wave() w.begin = datetime(2015, 3, 28, 10) w.end = datetime(2015, 3, 28, 12, 30) w.times["Flyer"].begin = datetime(2015, 3, 28, 9) w.times["Flyer"].end = datetime(2015, 3, 28, 13, 30) w.times["Plane"].begin = datetime(2015, 3, 28, 10) w.times["Plane"].end = datetime(2015, 3, 28, 12, 30) r = Flyer(1) r.snivs[0] = s print "Flyer" print r.available(date(2015, 3, 28), w) print r._available[date(2015, 3, 28)][w] print "Plane" p = Plane(1) p.snivs[0] = s print p.available(date(2015, 3, 28), w) print p._available[date(2015, 3, 28)][w]
def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate = 44100): self.note = note self.volume = 1 # Full colume for starters self.samplingRate = samplingRate # How many samples will I have to play? self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute)) if self.note.times != None: self.totalSamples /= self.note.times if note.dots: self.totalSamples = int(self.totalSamples * ( 2.0 - pow(2, - note.dots))) self.wave = Wave(tuningSystem.getFrequency(note), samplingRate) self.counter = 0 self.volumeRate = None self.tied = False
def generate(self): #place dock and vessel randomly in the map self.dock = np.random.rand(2) * self.env_size init_pos = np.random.rand(3) * self.env_size init_pos[2] = 0 init_vel = np.array([0, 0, 0]) init_theta = np.random.rand(3) * 2 * np.pi init_theta[0:2] = 0 init_w = np.array([0, 0, 0]) init_t = 0 self.path = Path([init_pos[:2], self.dock]) #TODO add sea state to state? self.vessel = Boat(init_pos, init_vel, init_theta, init_w, init_t) #initialize waves self.wave = Wave(1, 1, 1, 0, 0) #initialize current #TODO determine current format self.current = np.array([0, 0, 0])
class TrackPlayer: """ Will play a note that's provided to it """ def __init__(self, system, samplingRate=44100): self.system = system self.wave = None self.samplingRate = samplingRate self.samplesToMute = None def play(self, musicalNote): if musicalNote == None: self.mute() else: self.wave = Wave(self.system.getFrequency(musicalNote), self.samplingRate) self.samplesToMute = None def mute(self, samplesToMute=None): if samplesToMute == None: # mute inmediately self.volume = 0 if self.wave != None: self.wave.setVolume(0) else: self.samplesToMute = samplesToMute # What is the rate for each volume decrease to apply? self.volume = 1 self.decrementRate = math.exp(math.log(0.01) / samplesToMute) def getNextValue(self): if self.wave == None: return 0 if self.samplesToMute != None: self.samplesToMute -= 1 # The volume? self.volume *= self.decrementRate self.wave.setVolume(self.volume) return self.wave.getNextValue() def getFrequency(self): if self.wave == None: return None else: return self.wave.getFrequency()
class TrackPlayer: """ Will play a note that's provided to it """ def __init__(self, system, samplingRate = 44100): self.system = system self.wave = None self.samplingRate = samplingRate self.samplesToMute = None def play(self, musicalNote): if musicalNote == None: self.mute() else: self.wave = Wave(self.system.getFrequency(musicalNote), self.samplingRate) self.samplesToMute = None def mute(self, samplesToMute = None): if samplesToMute == None: # mute inmediately self.volume=0 if self.wave != None: self.wave.setVolume(0) else: self.samplesToMute = samplesToMute # What is the rate for each volume decrease to apply? self.volume=1 self.decrementRate = math.exp(math.log(0.01) / samplesToMute) def getNextValue(self): if self.wave == None: return 0 if self.samplesToMute != None: self.samplesToMute -= 1 # The volume? self.volume*=self.decrementRate self.wave.setVolume(self.volume) return self.wave.getNextValue() def getFrequency(self): if self.wave == None: return None else: return self.wave.getFrequency()
def create_waves(self, sked): for i in range(1, 6): w = Wave(i) #Plane times dawn = datetime.combine(sked.date, sked.dawn) start_time = dawn + timedelta(hours=(i-1)*2.5) end_time = dawn + timedelta(hours=i*2.5) w.begin = start_time w.end = end_time w.times["Plane"].begin = start_time w.times["Plane"].end = end_time #Flyer times start_time = start_time - timedelta(hours=1) end_time = start_time - timedelta(hours=1) w.times["Flyer"].begin = start_time w.times["Flyer"].end = end_time w.schedule = sked w.priority = 1.0 sked.waves[i]=w sked.findExclusiveWaves()
class LilypondNotePlayer: def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate=44100): self.note = note self.volume = 1 # Full colume for starters self.samplingRate = samplingRate # How many samples will I have to play? self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute)) if self.note.times != None: self.totalSamples /= self.note.times if note.dots: self.totalSamples = int(self.totalSamples * (2.0 - pow(2, -note.dots))) self.wave = Wave(tuningSystem.getFrequency(note), samplingRate) self.counter = 0 self.volumeRate = None self.tied = False def getNextValue(self): self.counter += 1 # Do we have to lower the volume? if not self.tied and self.totalSamples - self.counter <= self.samplingRate * 0.05: # 5 hundredths of a second # Have to calculate a volume rate if self.totalSamples <= self.counter: self.volumeRate = 0 else: self.volumeRate = math.exp( math.log(0.01) / (self.totalSamples - self.counter)) sys.stderr.flush() if self.volumeRate != None: self.wave.setVolume(self.volume * self.volumeRate) return self.wave.getNextValue() def setTied(self, value): self.tied = value def isTied(self): return self.tied def isFinished(self): return self.counter >= self.totalSamples def setNewDuration(self, totalSamples): self.counter = 0 self.totalSamples = totalSamples def getAngle(self): return self.wave.getAngle() def setAngle(self, angle): self.wave.setAngle(angle) def getFrequency(self): return self.wave.getFrequency()
def _reset(self): self.health = 100 self.inv = Inventory() self.current_weapon = self.inv.armory['cannon'] self.wave = Wave() self.score = 0
from Wave import Wave song = Wave(523.25, 5, 0.8) song.play() song.record('cnote')
class Game: def __init__(self): # pygame initializations pygame.init() self.screen = pygame.display.set_mode(s.SCREEN_SIZE) pygame.display.set_caption('Blasteroids') self.clock = pygame.time.Clock() self.volume = .1 Sounds.set_se_volume(self.volume) self.wave_font = pygame.font.SysFont('arialblack', 35) self.score_font = pygame.font.SysFont('arialblack', 17) # background and cursor surfaces self.surfaces = {'background': pygame.image.load('assets/background.png').convert(), 'cursor': pygame.image.load('assets/cursor.png').convert_alpha(), 'tower': pygame.image.load('assets/tower.png').convert_alpha(), 'hp_outline': pygame.image.load('assets/health_bar_outline.png').convert_alpha()} # game's main variables self.health = 100 self.inv = Inventory() self.current_weapon = self.inv.armory['cannon'] self.wave = Wave() self.score = 0 self.firing = False self.auto_fire = False def play(self): # Show title splash screen, start main game loop once title is closed title_splash = TitleScreen(self.screen) title_splash.play_screen() Sounds.play_music(Sounds.MAIN_MUSIC) # main loop while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # Shoot stuff (toggle auto-fire): elif event.type == pygame.MOUSEBUTTONDOWN: self.firing = True elif event.type == pygame.MOUSEBUTTONUP: self.firing = False # Keyboard press events: elif event.type is pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() # Toggle full screen with 'f' key: elif event.key == pygame.K_f: self._toggle_full_screen() # Toggle sound effects with ''n' key: elif event.key == pygame.K_n: if Sounds.get_se_volume() == 0: Sounds.set_se_volume(self.volume) else: Sounds.set_se_volume(0) # Toggle music with 'm' key: elif event.key == pygame.K_m: if Sounds.get_music_volume() == 0: Sounds.set_music_volume(self.volume) else: Sounds.set_music_volume(0) # Toggle auto fire with 'r' key: elif event.key == pygame.K_r: if not self.auto_fire: self.auto_fire = True else: self.auto_fire = False # Switch weapons with '1' or '2' keys: elif event.key == pygame.K_1: self.switch_weapons('cannon') elif event.key == pygame.K_2: self.switch_weapons('laser gun') # check for game over instance if self.health <= 0: Sounds.stop_music() pygame.mouse.set_visible(True) go = GameOverScreen(self.screen) go.play_screen() self._reset() # enable rapid fire when holding down the mouse: if self.firing or self.auto_fire: self.current_weapon.fire(pygame.mouse.get_pos()) # blit most background images and update their positions self.display_and_update() # collision handlers self.collision_handler() self.remove_excess_sprites() self.check_damage_dealt() self.blit_health() # wave mechanics if self.wave.is_wave_intermission(): # if new wave just started (5 seconds ago or less), just show wave text: self.blit_wave_text() elif not self.wave.wave_is_over(): # wave ongoing, add asteroids: self.wave.add_asteroids() else: # wave ended, start new wave self.wave.start_new_wave() pygame.display.update() self.clock.tick(s.FPS) def switch_weapons(self, new_weapon): if self.current_weapon != self.inv.armory[new_weapon]: self.inv.armory[new_weapon].projectile_group.add( self.current_weapon.projectile_group ) self.current_weapon.projectile_group.empty() self.current_weapon = self.inv.armory[new_weapon] # blit backgrounds, projectiles, asteroids, score # update asteroid and projectile positions def display_and_update(self): self.screen.blit(self.surfaces['background'], (0, 0)) self.blit_projectiles() self.screen.blit(self.surfaces['tower'], s.TOWER_POS) self.blit_asteroids() score_text = self.score_font.render(str(self.score), 1, s.WHITE) self.screen.blit(score_text, s.SCORE_TEXT_POS) # display cross hair as mouse cursor x, y = pygame.mouse.get_pos() self.screen.blit(self.surfaces['cursor'], (x - 9, y - 9)) def collision_handler(self): for shot in self.current_weapon.projectile_group: for asteroid in self.wave.asteroid_group: # upon collision, destroy projectile and subtract asteroid health if pygame.sprite.collide_mask(shot, asteroid): self.current_weapon.projectile_group.remove(shot) asteroid.health -= self.current_weapon.damage if asteroid.health <= 0: # destroy asteroid if asteroid.type == 'large': self.wave.asteroid_group.add(asteroid.spawn_children()) self.score += asteroid.score self.wave.asteroid_group.remove(asteroid) Sounds.EXPLOSION.play() return def remove_excess_sprites(self): # remove projectiles falling outside of screen for p in self.current_weapon.projectile_group: if (p.position[0] < 0 or p.position[0] > s.SCREEN_WIDTH or p.position[1] < 0 or p.position[1] > s.SCREEN_HEIGHT): self.current_weapon.projectile_group.remove(p) def check_damage_dealt(self): # if an asteroid reaches its destination, deal damage to player and remove for a in self.wave.asteroid_group: if a.position[1] >= a.destination[1]: self.health -= a.damage self.wave.asteroid_group.remove(a) Sounds.HEALTH_LOSS.play() def blit_projectiles(self): self.current_weapon.projectile_group.update() self.current_weapon.projectile_group.draw(self.screen) def blit_asteroids(self): self.wave.asteroid_group.update() self.wave.asteroid_group.draw(self.screen) def blit_wave_text(self): wave_text = self.wave_font.render('W A V E ' + str(self.wave.wave_number + 1), 1, s.YELLOW) self.screen.blit(wave_text, s.WAVE_TEXT_POS) def blit_health(self): self.screen.blit(self.surfaces['hp_outline'], s.HEALTH_BAR_OUTLINE) remaining_health = self.health / 100.0 if self.health > 0: pygame.draw.rect(self.screen, s.RED, (s.HP_BAR_X, s.HP_BAR_Y, s.HP_BAR_LENGTH * remaining_health, s.HP_BAR_HEIGHT)) def _toggle_full_screen(self): if pygame.display.get_driver() == 'x11': pygame.display.toggle_fullscreen() else: if s.FULL_SCREEN: self.screen = pygame.display.set_mode(s.SCREEN_SIZE) else: self.screen = pygame.display.set_mode(s.SCREEN_SIZE, pygame.FULLSCREEN) s.FULL_SCREEN = not s.FULL_SCREEN self.screen.blit(self.screen.copy(), (0, 0)) pygame.display.update() def _reset(self): self.health = 100 self.inv = Inventory() self.current_weapon = self.inv.armory['cannon'] self.wave = Wave() self.score = 0
def main(): config = {} execfile(sys.argv[1], config) vt = TrainingSquadron(config) vtSqlScheduler.load(vt, config) # Load csv with open(sys.argv[2]) as csvfile: reader = csv.DictReader(csvfile) con = mysql.connector.connect(host=config['host'], port=config['port'], user=config['user'], passwd=config['password'], db=config['database']) cur = con.cursor(dictionary=True) # Create validation sortie s = Sortie(instructor=Instructor(instructor_ID=11)) s.schedule_ID = 113 s.takeoff = datetime.now() s.land = datetime.now() s.brief = datetime.now() s.wave = Wave(1) for crow in reader: progressing = set() print(crow['first_name'], crow['last_name']) # Look for student in user db, return student_ID cur.execute( "SELECT user_ID FROM user WHERE last_name = %(last_name)s " "AND (middle_name = %(middle_name)s OR middle_name IS NULL) " "AND first_name = %(first_name)s " "AND title = %(title)s " "LIMIT 1", crow) row = cur.fetchone() if row is None: # Create resource entries cur.execute( "INSERT INTO resource(`created_at`, `type`, `airfield_ID`) VALUES " "(NOW(),'user',4)") student_ID = cur.lastrowid else: student_ID = row['user_ID'] student = Student(student_ID=student_ID) # Enter user information cur.execute("SELECT count(1) FROM user WHERE user_ID = %(id)s;", {'id': student_ID}) row = cur.fetchone() if row['count(1)'] == 0: crow['id'] = student_ID cur.execute( "INSERT INTO user(user_ID, last_name, first_name, middle_name, title) VALUES (" "%(id)s, %(last_name)s, %(first_name)s, %(middle_name)s, %(title)s)", crow) # Enter student information cur.execute( "SELECT count(1) FROM student WHERE student_ID = %(id)s;", {'id': student_ID}) row = cur.fetchone() if row['count(1)'] == 0: cur.execute( "INSERT INTO student(student_ID, status, training_end_date) VALUES (" "%(id)s, 'active', %(end)s)", { 'id': student_ID, 'end': crow['training_end_date'] }) cur.execute( "INSERT INTO student_syllabus(student_ID, syllabus_ID) " "VALUES (%(id)s, %(syll)s)", { 'id': student_ID, 'syll': int(crow['syllabus_ID']) }) student_syllabus_ID = cur.lastrowid else: cur.execute( "SELECT student_syllabus_ID FROM student_syllabus WHERE student_ID = %(id)s LIMIT 1;", {'id': student_ID}) row = cur.fetchone() student_syllabus_ID = row['student_syllabus_ID'] student.student_syllabus_ID = student_syllabus_ID # Create class if not there cur.execute( "SELECT count(1), organization_ID FROM organization WHERE name = %(class_name)s LIMIT 1;", {'class_name': "Class " + crow['class']}) row = cur.fetchone() if row['count(1)'] == 0: cur.execute( "INSERT INTO resource(`created_at`, `type`, `airfield_ID`) VALUES " "(NOW(),'organization',4)") class_ID = cur.lastrowid cur.execute( """INSERT INTO organization(organization_ID, name, scheduling) VALUES (%(id)s, %(class_name)s, 0)""", { 'id': class_ID, 'class_name': "Class " + crow['class'] }) cur.execute( "INSERT INTO hierarchy(parent, child) VALUES (5, %(id)s)", {'id': class_ID}) else: class_ID = row['organization_ID'] # Associate student with VT-35 cur.execute( "SELECT count(1) FROM hierarchy WHERE child = %(id)s LIMIT 1;", {'id': student_ID}) row = cur.fetchone() if row['count(1)'] == 0: cur.execute( "INSERT INTO hierarchy(parent, child) VALUES (5, %(id)s)", {'id': student_ID}) # Insert resource_tags cur.execute( "SELECT count(1) FROM resource_tag WHERE resource_ID = %(id)s LIMIT 1;", {'id': student_ID}) row = cur.fetchone() if row['count(1)'] == 0: cur.execute( """INSERT INTO resource_tag(resource_ID, tag_ID) VALUES (%(id)s, 1), (%(id)s, 2), (%(id)s, 3), (%(id)s, 4), (%(id)s, 5), (%(id)s, 7), (%(id)s, 8), (%(id)s, 9), (%(id)s, 10)""", {'id': student_ID}) """# Pull progressing events cur.execute("SELECT * FROM student_sortie " "LEFT JOIN student ON student.student_ID = student_sortie.student_ID " "LEFT JOIN hierarchy ON student.student_ID = child " "LEFT JOIN student_syllabus " "ON student_sortie.student_syllabus_ID = student_syllabus.student_syllabus_ID " "LEFT JOIN sortie ON sortie.sortie_ID = student_sortie.sortie_ID " "LEFT JOIN schedule ON schedule.schedule_ID = student_sortie.schedule_ID " "WHERE student.student_ID = %(id)s " "AND (hierarchy.stop > NOW() OR hierarchy.stop IS NULL) " "AND student_syllabus.outcome IS NULL AND student_sortie.progressing_event = 1 " "AND schedule.published = TRUE", {'id': student_ID})""" # Create student sorties for each ancestor event event = vt.events[int(crow['latest_event_ID'])] ss = StudentSortie() ss.student = student ss.event = event s.studentSorties.append(ss) for a, syllabus in vt.syllabus[int( crow['syllabus_ID'])].ancestors(event): ss = StudentSortie() ss.student = student ss.event = a s.studentSorties.append(ss) print ss for i in range(1, 4): ss = StudentSortie() ss.student = Student(student_ID=student_ID) ss.event = vt.events[i] s.studentSorties.append(ss) print ss write(s, cur) con.commit() con.close()
self.data = data def run(self): self.pcm.write(self.data) if __name__ == "__main__": import math import sys argc = len(sys.argv) leftChannel = None rightChannel = None if argc == 1: print "Have to provide either a single frequency to play or a frequency for each channel (left channel first)" sys.exit(1) elif argc == 2: # Provided a single frequency for both channels leftChannel = Wave(float(sys.argv[1]), 11025) else: leftChannel = Wave(float(sys.argv[1]), 11025) rightChannel = Wave(float(sys.argv[2]), 11025) player = WavePlayer(11025) while True: leftHeight = leftChannel.getNextValue() if rightChannel == None: rightHeight = leftHeight else: rightHeight = rightChannel.getNextValue() player.play(leftHeight, rightHeight)
def on_message(self,message): print(message) # print ("message received: {}").format(message) messageHeader = message[0] # print("message header: {}").format(messageHeader) if messageHeader == "a":#done white = Color() white.setColorRBGW(255,0,0,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "s":#done white = Color() white.setColorRBGW(0,255,255,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "d":#done white = Color() white.setColorRBGW(255,0,255,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "f":#done white = Color() white.setColorRBGW(255,255,0,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "j":#done white = Color() white.setColorRBGW(0,0,255,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "k":#done white = Color() white.setColorRBGW(255,0,0,0) eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) if messageHeader == "l":#done # white = Color() # white.setColorRBGW(0,255,0,0) # eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) hardwareController.set_hue_rotation(0) if messageHeader == ";":#done # white = Color() # white.setColorRBGW(0,0,0,0) # eventLoop.effects.append(Wave(leds, 71, Direction.BOTH_NO_CENTER, white)) hardwareController.set_hue_rotation(180) # if messageHeader == "000":#done # static(message) # if messageHeader == "100":#Enable threading # pass # if messageHeader == "200":#Still searching for a library # pass # if messageHeader == "300":#Enable threading # pass # if messageHeader == "400":#Enable threading # pass # if messageHeader == "500":#Search for a good distribution of light colors # pass # if messageHeader == "600":#search for a good distibution of random in and out clouds. # pass if message == "NumberOfLights()":#done self.write_message(str(NUM_LEDS)) else: self.write_message(str("command not understood"))
self.pcm = pcm self.data = data def run(self): self.pcm.write(self.data) if __name__ == "__main__": import math import sys argc = len(sys.argv) leftChannel = None rightChannel = None if argc == 1: print "Have to provide either a single frequency to play or a frequency for each channel (left channel first)" sys.exit(1) elif argc == 2: # Provided a single frequency for both channels leftChannel = Wave(float(sys.argv[1]), 11025) else: leftChannel = Wave(float(sys.argv[1]), 11025) rightChannel = Wave(float(sys.argv[2]), 11025) player = WavePlayer(11025) while True: leftHeight = leftChannel.getNextValue() if rightChannel == None: rightHeight = leftHeight else: rightHeight = rightChannel.getNextValue() player.play(leftHeight, rightHeight)
PI = np.pi sliderDataList = [{'name': 'Left amplitude', 'min': 0, 'max': 8.0, 'init': 2, 'step': 0.01}, {'name': 'Right amplitude', 'min': 0, 'max': 8.0, 'init': 2, 'step': 0.01}, {'name': 'Left period', 'min': 0.01, 'max': 8 * PI, 'init': 2 * PI, 'step': 0.01}, {'name': 'Right period', 'min': 0.01, 'max': 8 * PI, 'init': 2 * PI, 'step': 0.01}, {'name': 'Wire tension', 'min': 0.01, 'max': 8.0, 'init': 1, 'step': 0.01}, {'name': 'Wire mass density', 'min': 0.01, 'max': 8.0, 'init': 1, 'step': 0.01}, {'name': 'Simulation speed', 'min': 0.001, 'max': 2.0, 'init': 0.1, 'step': 0.001}, {'name': 'Line thickness', 'min': 1, 'max': 10, 'init': 5, 'step': 0.1}] checkboxDataList = [{'name': 'Left wave', 'init': True}, {'name': 'Right wave', 'init': True}, {'name': 'Sum wave', 'init': True}] waveList = [Wave(amplitude=2, period=2*PI, direction=1), Wave(amplitude=2, period=2*PI, direction=-1), None] class WaveSuperposition(WaveGraphBase): def __init__(self, name='Wave superposition', granularity=2048, x_range=4 * PI, x_offset=0, y_range=6, y_offset=0, time_factor=0.1, line_thickness=5, waves=[], slider_data=[], checkbox_data=[]): super().__init__(name, granularity, x_range, x_offset, y_range, y_offset, time_factor, line_thickness, waves, slider_data, checkbox_data) def update(self, event=None): self.waves[0].amplitude = self.sliders[0].val self.waves[1].amplitude = self.sliders[1].val self.waves[0].period = self.sliders[2].val self.waves[1].period = self.sliders[3].val self.waves[0].tension = self.sliders[4].val self.waves[1].tension = self.sliders[4].val
def __init__(self, pcm, data): Thread.__init__(self) self.pcm = pcm self.data = data def run(self): self.pcm.write(self.data) if __name__ == "__main__": import math import sys argc = len(sys.argv) channel = None frequencies = list() if argc == 1: print "Have to provide frequencies to play during a second each" sys.exit(1) for i in range(1, argc): frequencies.append(float(sys.argv[i])) player = WavePlayer(11025) channel = Wave(frequencies[0], 11025) for i in frequencies: sys.stderr.write("Playing frequency " + str(i) + "\n") sys.stderr.flush() channel.setFrequency(i) for j in range(0, 11025): height = channel.getNextValue() player.play(height)
import pygame, os from Wave import Wave, Coord os.environ["SDL_VIDEO_WINDOW_POS"] = "15,30" pygame.display.init() size = Coord(1000, 600) screen = pygame.display.set_mode(size) wave = Wave(screen, size) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0, 0, 0)) wave.update() wave.draw() pygame.display.update()
from Wave import Wave #twi-nkle twinkle_song = Wave(523.25, 1, 0.8) twinkle_song = Wave(523.25, 1, 0.8) #twi-nkle twinkle_song = Wave(783.99, 1, 0.8) twinkle_song = Wave(783.99, 1, 0.8) #lit-tle twinkle_song = Wave(880.00, 1, 0.8) twinkle_song = Wave(880.00, 1, 0.8) #star twinkle_song = Wave(783.99, 1, 0.8) #how i twinkle_song = Wave(698.46, 1, 0.8) twinkle_song = Wave(698.46, 1, 0.8) #won-der twinkle_song = Wave(659.26, 1, 0.8) twinkle_song = Wave(659.26, 1, 0.8) #what you twinkle_song = Wave(587.33, 1, 0.8) twinkle_song = Wave(587.33, 1, 0.8) #are twinkle_song = Wave(523.25, 1, 0.8) twinkle_song.play() twinkle_song.record('twinkle')