idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
47,300
def select ( read_streams , write_streams , timeout = 0 ) : exception_streams = [ ] try : return builtin_select . select ( read_streams , write_streams , exception_streams , timeout , ) [ 0 : 2 ] except builtin_select . error as e : no = e . errno if six . PY3 else e [ 0 ] if no == errno . EINTR : return ( [ ] , [ ] ) else : raise e
Select the streams from read_streams that are ready for reading and streams from write_streams ready for writing .
47,301
def read ( self , n = 4096 ) : while True : try : if hasattr ( self . fd , 'recv' ) : return self . fd . recv ( n ) return os . read ( self . fd . fileno ( ) , n ) except EnvironmentError as e : if e . errno not in Stream . ERRNO_RECOVERABLE : raise e
Return n bytes of data from the Stream or None at end of stream .
47,302
def do_write ( self ) : while True : try : written = 0 if hasattr ( self . fd , 'send' ) : written = self . fd . send ( self . buffer ) else : written = os . write ( self . fd . fileno ( ) , self . buffer ) self . buffer = self . buffer [ written : ] if self . close_requested and len ( self . buffer ) == 0 : self . close ( ) return written except EnvironmentError as e : if e . errno not in Stream . ERRNO_RECOVERABLE : raise e
Flushes as much pending data from the internal write buffer as possible .
47,303
def read ( self , n = 4096 ) : size = self . _next_packet_size ( n ) if size <= 0 : return else : data = six . binary_type ( ) while len ( data ) < size : nxt = self . stream . read ( size - len ( data ) ) if not nxt : return data data = data + nxt return data
Read up to n bytes of data from the Stream after demuxing .
47,304
def flush ( self , n = 4096 ) : try : read = self . from_stream . read ( n ) if read is None or len ( read ) == 0 : self . eof = True if self . propagate_close : self . to_stream . close ( ) return None return self . to_stream . write ( read ) except OSError as e : if e . errno != errno . EPIPE : raise e
Flush n bytes of data from the reader Stream to the writer Stream .
47,305
def exec_command ( client , container , command , interactive = True , stdout = None , stderr = None , stdin = None ) : exec_id = exec_create ( client , container , command , interactive = interactive ) operation = ExecOperation ( client , exec_id , interactive = interactive , stdout = stdout , stderr = stderr , stdin = stdin ) PseudoTerminal ( client , operation ) . start ( )
Run provided command via exec API in provided container .
47,306
def start ( self ) : if os . isatty ( self . fd . fileno ( ) ) and self . israw ( ) : self . original_attributes = termios . tcgetattr ( self . fd ) tty . setraw ( self . fd )
Saves the current terminal attributes and makes the tty raw .
47,307
def stop ( self ) : if self . original_attributes is not None : termios . tcsetattr ( self . fd , termios . TCSADRAIN , self . original_attributes , )
Restores the terminal attributes back to before setting raw mode .
47,308
def start ( self ) : def handle ( signum , frame ) : if signum == signal . SIGWINCH : self . pty . resize ( ) self . original_handler = signal . signal ( signal . SIGWINCH , handle )
Start trapping WINCH signals and resizing the PTY .
47,309
def stop ( self ) : if self . original_handler is not None : signal . signal ( signal . SIGWINCH , self . original_handler )
Stop trapping WINCH signals and restore the previous WINCH handler .
47,310
def resize ( self , height , width , ** kwargs ) : self . client . resize ( self . container , height = height , width = width )
resize pty within container
47,311
def resize ( self , height , width , ** kwargs ) : self . client . exec_resize ( self . exec_id , height = height , width = width )
resize pty of an execed process
47,312
def _exec_info ( self ) : if self . _info is None : self . _info = self . client . exec_inspect ( self . exec_id ) return self . _info
Caching wrapper around client . exec_inspect
47,313
def format_number ( x ) : if isinstance ( x , float ) : value = '{:.17g}' . format ( x ) else : value = str ( x ) return value
Format number to string
47,314
def parse_number_auto_dtype ( x ) : value = float ( x ) if value . is_integer ( ) : value = int ( value ) return value
Parse number from string with automatic type detection .
47,315
def _determine_datatype ( fields ) : np_typestring = _TYPEMAP_NRRD2NUMPY [ fields [ 'type' ] ] if np . dtype ( np_typestring ) . itemsize > 1 and fields [ 'encoding' ] not in [ 'ASCII' , 'ascii' , 'text' , 'txt' ] : if 'endian' not in fields : raise NRRDError ( 'Header is missing required field: "endian".' ) elif fields [ 'endian' ] == 'big' : np_typestring = '>' + np_typestring elif fields [ 'endian' ] == 'little' : np_typestring = '<' + np_typestring else : raise NRRDError ( 'Invalid endian value in header: "%s"' % fields [ 'endian' ] ) return np . dtype ( np_typestring )
Determine the numpy dtype of the data .
47,316
def _validate_magic_line ( line ) : if not line . startswith ( 'NRRD' ) : raise NRRDError ( 'Invalid NRRD magic line. Is this an NRRD file?' ) try : version = int ( line [ 4 : ] ) if version > 5 : raise NRRDError ( 'Unsupported NRRD file version (version: %i). This library only supports v%i and below.' % ( version , 5 ) ) except ValueError : raise NRRDError ( 'Invalid NRRD magic line: %s' % line ) return len ( line )
For NRRD files the first four characters are always NRRD and remaining characters give information about the file format version
47,317
def read ( filename , custom_field_map = None , index_order = 'F' ) : with open ( filename , 'rb' ) as fh : header = read_header ( fh , custom_field_map ) data = read_data ( header , fh , filename , index_order ) return data , header
Read a NRRD file and return the header and data
47,318
def add_notes ( self , note , duration = None ) : if self . instrument != None : if not self . instrument . can_play_notes ( note ) : raise InstrumentRangeError , "Note '%s' is not in range of the instrument (%s)" % ( note , self . instrument ) if duration == None : duration = 4 if len ( self . bars ) == 0 : self . bars . append ( Bar ( ) ) last_bar = self . bars [ - 1 ] if last_bar . is_full ( ) : self . bars . append ( Bar ( last_bar . key , last_bar . meter ) ) return self . bars [ - 1 ] . place_notes ( note , duration )
Add a Note note as string or NoteContainer to the last Bar .
47,319
def get_notes ( self ) : for bar in self . bars : for beat , duration , notes in bar : yield beat , duration , notes
Return an iterator that iterates through every bar in the this track .
47,320
def from_chords ( self , chords , duration = 1 ) : tun = self . get_tuning ( ) def add_chord ( chord , duration ) : if type ( chord ) == list : for c in chord : add_chord ( c , duration * 2 ) else : chord = NoteContainer ( ) . from_chord ( chord ) if tun : chord = tun . find_chord_fingering ( chord , return_best_as_NoteContainer = True ) if not self . add_notes ( chord , duration ) : dur = self . bars [ - 1 ] . value_left ( ) self . add_notes ( chord , dur ) self . add_notes ( chord , value . subtract ( duration , dur ) ) for c in chords : if c is not None : add_chord ( c , duration ) else : self . add_notes ( None , duration ) return self
Add chords to the Track .
47,321
def get_tuning ( self ) : if self . instrument and self . instrument . tuning : return self . instrument . tuning return self . tuning
Return a StringTuning object .
47,322
def transpose ( self , interval , up = True ) : for bar in self . bars : bar . transpose ( interval , up ) return self
Transpose all the notes in the track up or down the interval .
47,323
def set_meter ( self , meter ) : if _meter . valid_beat_duration ( meter [ 1 ] ) : self . meter = ( meter [ 0 ] , meter [ 1 ] ) self . length = meter [ 0 ] * ( 1.0 / meter [ 1 ] ) elif meter == ( 0 , 0 ) : self . meter = ( 0 , 0 ) self . length = 0.0 else : raise MeterFormatError ( "The meter argument '%s' is not an " "understood representation of a meter. " "Expecting a tuple." % meter )
Set the meter of this bar .
47,324
def place_notes ( self , notes , duration ) : if hasattr ( notes , 'notes' ) : pass elif hasattr ( notes , 'name' ) : notes = NoteContainer ( notes ) elif type ( notes ) == str : notes = NoteContainer ( notes ) elif type ( notes ) == list : notes = NoteContainer ( notes ) if self . current_beat + 1.0 / duration <= self . length or self . length == 0.0 : self . bar . append ( [ self . current_beat , duration , notes ] ) self . current_beat += 1.0 / duration return True else : return False
Place the notes on the current_beat .
47,325
def place_notes_at ( self , notes , at ) : for x in self . bar : if x [ 0 ] == at : x [ 0 ] [ 2 ] += notes
Place notes at the given index .
47,326
def remove_last_entry ( self ) : self . current_beat -= 1.0 / self . bar [ - 1 ] [ 1 ] self . bar = self . bar [ : - 1 ] return self . current_beat
Remove the last NoteContainer in the Bar .
47,327
def is_full ( self ) : if self . length == 0.0 : return False if len ( self . bar ) == 0 : return False if self . current_beat >= self . length - 0.001 : return True return False
Return False if there is room in this Bar for another NoteContainer True otherwise .
47,328
def change_note_duration ( self , at , to ) : if valid_beat_duration ( to ) : diff = 0 for x in self . bar : if diff != 0 : x [ 0 ] [ 0 ] -= diff if x [ 0 ] == at : cur = x [ 0 ] [ 1 ] x [ 0 ] [ 1 ] = to diff = 1 / cur - 1 / to
Change the note duration at the given index to the given duration .
47,329
def get_range ( self ) : ( min , max ) = ( 100000 , - 1 ) for cont in self . bar : for note in cont [ 2 ] : if int ( note ) < int ( min ) : min = note elif int ( note ) > int ( max ) : max = note return ( min , max )
Return the highest and the lowest note in a tuple .
47,330
def transpose ( self , interval , up = True ) : for cont in self . bar : cont [ 2 ] . transpose ( interval , up )
Transpose the notes in the bar up or down the interval .
47,331
def get_note_names ( self ) : res = [ ] for cont in self . bar : for x in cont [ 2 ] . get_note_names ( ) : if x not in res : res . append ( x ) return res
Return a list of unique note names in the Bar .
47,332
def parse_midi_file_header ( self , fp ) : try : if fp . read ( 4 ) != 'MThd' : raise HeaderError ( 'Not a valid MIDI file header. Byte %d.' % self . bytes_read ) self . bytes_read += 4 except : raise IOError ( "Couldn't read from file." ) try : chunk_size = self . bytes_to_int ( fp . read ( 4 ) ) self . bytes_read += 4 except : raise IOError ( "Couldn't read chunk size from file. Byte %d." % self . bytes_read ) if chunk_size < 6 : return False try : format_type = self . bytes_to_int ( fp . read ( 2 ) ) self . bytes_read += 2 if format_type not in [ 0 , 1 , 2 ] : raise FormatError ( '%d is not a valid MIDI format.' % format_type ) except : raise IOError ( "Couldn't read format type from file." ) try : number_of_tracks = self . bytes_to_int ( fp . read ( 2 ) ) time_division = self . parse_time_division ( fp . read ( 2 ) ) self . bytes_read += 4 except : raise IOError ( "Couldn't read number of tracks " "and/or time division from tracks." ) chunk_size -= 6 if chunk_size % 2 == 1 : raise FormatError ( "Won't parse this." ) fp . read ( chunk_size / 2 ) self . bytes_read += chunk_size / 2 return ( format_type , number_of_tracks , time_division )
Read the header of a MIDI file and return a tuple containing the format type number of tracks and parsed time division information .
47,333
def parse_time_division ( self , bytes ) : value = self . bytes_to_int ( bytes ) if not value & 0x8000 : return { 'fps' : False , 'ticks_per_beat' : value & 0x7FFF } else : SMPTE_frames = ( value & 0x7F00 ) >> 2 if SMPTE_frames not in [ 24 , 25 , 29 , 30 ] : raise TimeDivisionError , "'%d' is not a valid value for the number of SMPTE frames" % SMPTE_frames clock_ticks = ( value & 0x00FF ) >> 2 return { 'fps' : True , 'SMPTE_frames' : SMPTE_frames , 'clock_ticks' : clock_ticks }
Parse the time division found in the header of a MIDI file and return a dictionary with the boolean fps set to indicate whether to use frames per second or ticks per beat .
47,334
def parse_track ( self , fp ) : events = [ ] chunk_size = self . parse_track_header ( fp ) bytes = chunk_size while chunk_size > 0 : ( delta_time , chunk_delta ) = self . parse_varbyte_as_int ( fp ) chunk_size -= chunk_delta ( event , chunk_delta ) = self . parse_midi_event ( fp ) chunk_size -= chunk_delta events . append ( [ delta_time , event ] ) if chunk_size < 0 : print 'yikes.' , self . bytes_read , chunk_size return events
Parse a MIDI track from its header to its events .
47,335
def parse_midi_event ( self , fp ) : chunk_size = 0 try : ec = self . bytes_to_int ( fp . read ( 1 ) ) chunk_size += 1 self . bytes_read += 1 except : raise IOError ( "Couldn't read event type " "and channel data from file." ) event_type = ( ec & 0xf0 ) >> 4 channel = ec & 0x0f if event_type < 8 : raise FormatError ( 'Unknown event type %d. Byte %d.' % ( event_type , self . bytes_read ) ) if event_type == 0x0f : try : meta_event = self . bytes_to_int ( fp . read ( 1 ) ) ( length , chunk_delta ) = self . parse_varbyte_as_int ( fp ) data = fp . read ( length ) chunk_size += 1 + chunk_delta + length self . bytes_read += 1 + length except : raise IOError ( "Couldn't read meta event from file." ) return ( { 'event' : event_type , 'meta_event' : meta_event , 'data' : data } , chunk_size ) elif event_type in [ 12 , 13 ] : try : param1 = fp . read ( 1 ) chunk_size += 1 self . bytes_read += 1 except : raise IOError ( "Couldn't read MIDI event parameters from file." ) param1 = self . bytes_to_int ( param1 ) return ( { 'event' : event_type , 'channel' : channel , 'param1' : param1 } , chunk_size ) else : try : param1 = fp . read ( 1 ) param2 = fp . read ( 1 ) chunk_size += 2 self . bytes_read += 2 except : raise IOError ( "Couldn't read MIDI event parameters from file." ) param1 = self . bytes_to_int ( param1 ) param2 = self . bytes_to_int ( param2 ) return ( { 'event' : event_type , 'channel' : channel , 'param1' : param1 , 'param2' : param2 } , chunk_size )
Parse a MIDI event .
47,336
def parse_track_header ( self , fp ) : try : h = fp . read ( 4 ) self . bytes_read += 4 except : raise IOError ( "Couldn't read track header from file. Byte %d." % self . bytes_read ) if h != 'MTrk' : raise HeaderError ( 'Not a valid Track header. Byte %d.' % self . bytes_read ) try : chunk_size = fp . read ( 4 ) self . bytes_read += 4 except : raise IOError ( "Couldn't read track chunk size from file." ) chunk_size = self . bytes_to_int ( chunk_size ) return chunk_size
Return the size of the track chunk .
47,337
def parse_varbyte_as_int ( self , fp , return_bytes_read = True ) : result = 0 bytes_read = 0 r = 0x80 while r & 0x80 : try : r = self . bytes_to_int ( fp . read ( 1 ) ) self . bytes_read += 1 except : raise IOError ( "Couldn't read variable length byte from file." ) if r & 0x80 : result = ( result << 7 ) + ( r & 0x7F ) else : result = ( result << 7 ) + r bytes_read += 1 if not return_bytes_read : return result else : return ( result , bytes_read )
Read a variable length byte from the file and return the corresponding integer .
47,338
def set_note ( self , name = 'C' , octave = 4 , dynamics = { } ) : dash_index = name . split ( '-' ) if len ( dash_index ) == 1 : if notes . is_valid_note ( name ) : self . name = name self . octave = octave self . dynamics = dynamics return self else : raise NoteFormatError ( "The string '%s' is not a valid " "representation of a note in mingus" % name ) elif len ( dash_index ) == 2 : if notes . is_valid_note ( dash_index [ 0 ] ) : self . name = dash_index [ 0 ] self . octave = int ( dash_index [ 1 ] ) self . dynamics = dynamics return self else : raise NoteFormatError ( "The string '%s' is not a valid " "representation of a note in mingus" % name ) return False
Set the note to name in octave with dynamics .
47,339
def change_octave ( self , diff ) : self . octave += diff if self . octave < 0 : self . octave = 0
Change the octave of the note to the current octave + diff .
47,340
def transpose ( self , interval , up = True ) : ( old , o_octave ) = ( self . name , self . octave ) self . name = intervals . from_shorthand ( self . name , interval , up ) if up : if self < Note ( old , o_octave ) : self . octave += 1 else : if self > Note ( old , o_octave ) : self . octave -= 1
Transpose the note up or down the interval .
47,341
def from_int ( self , integer ) : self . name = notes . int_to_note ( integer % 12 ) self . octave = integer // 12 return self
Set the Note corresponding to the integer .
47,342
def from_hertz ( self , hertz , standard_pitch = 440 ) : value = ( ( log ( ( float ( hertz ) * 1024 ) / standard_pitch , 2 ) + 1.0 / 24 ) * 12 + 9 ) self . name = notes . int_to_note ( int ( value ) % 12 ) self . octave = int ( value / 12 ) - 6 return self
Set the Note name and pitch calculated from the hertz value .
47,343
def to_shorthand ( self ) : if self . octave < 3 : res = self . name else : res = str . lower ( self . name ) o = self . octave - 3 while o < - 1 : res += ',' o += 1 while o > 0 : res += "'" o -= 1 return res
Give the traditional Helmhotz pitch notation .
47,344
def from_shorthand ( self , shorthand ) : name = '' octave = 0 for x in shorthand : if x in [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ] : name = str . upper ( x ) octave = 3 elif x in [ 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' ] : name = x octave = 2 elif x in [ '#' , 'b' ] : name += x elif x == ',' : octave -= 1 elif x == "'" : octave += 1 return self . set_note ( name , octave , { } )
Convert from traditional Helmhotz pitch notation .
47,345
def interval ( key , start_note , interval ) : if not notes . is_valid_note ( start_note ) : raise KeyError ( "The start note '%s' is not a valid note" % start_note ) notes_in_key = keys . get_notes ( key ) for n in notes_in_key : if n [ 0 ] == start_note [ 0 ] : index = notes_in_key . index ( n ) return notes_in_key [ ( index + interval ) % 7 ]
Return the note found at the interval starting from start_note in the given key .
47,346
def measure ( note1 , note2 ) : res = notes . note_to_int ( note2 ) - notes . note_to_int ( note1 ) if res < 0 : return 12 - res * - 1 else : return res
Return an integer in the range of 0 - 11 determining the half note steps between note1 and note2 .
47,347
def augment_or_diminish_until_the_interval_is_right ( note1 , note2 , interval ) : cur = measure ( note1 , note2 ) while cur != interval : if cur > interval : note2 = notes . diminish ( note2 ) elif cur < interval : note2 = notes . augment ( note2 ) cur = measure ( note1 , note2 ) val = 0 for token in note2 [ 1 : ] : if token == '#' : val += 1 elif token == 'b' : val -= 1 if val > 6 : val = val % 12 val = - 12 + val elif val < - 6 : val = val % - 12 val = 12 + val result = note2 [ 0 ] while val > 0 : result = notes . augment ( result ) val -= 1 while val < 0 : result = notes . diminish ( result ) val += 1 return result
A helper function for the minor and major functions .
47,348
def invert ( interval ) : interval . reverse ( ) res = list ( interval ) interval . reverse ( ) return res
Invert an interval .
47,349
def determine ( note1 , note2 , shorthand = False ) : if note1 [ 0 ] == note2 [ 0 ] : def get_val ( note ) : r = 0 for x in note [ 1 : ] : if x == 'b' : r -= 1 elif x == '#' : r += 1 return r x = get_val ( note1 ) y = get_val ( note2 ) if x == y : if not shorthand : return 'major unison' return '1' elif x < y : if not shorthand : return 'augmented unison' return '#1' elif x - y == 1 : if not shorthand : return 'minor unison' return 'b1' else : if not shorthand : return 'diminished unison' return 'bb1' n1 = notes . fifths . index ( note1 [ 0 ] ) n2 = notes . fifths . index ( note2 [ 0 ] ) number_of_fifth_steps = n2 - n1 if n2 < n1 : number_of_fifth_steps = len ( notes . fifths ) - n1 + n2 fifth_steps = [ [ 'unison' , '1' , 0 ] , [ 'fifth' , '5' , 7 ] , [ 'second' , '2' , 2 ] , [ 'sixth' , '6' , 9 ] , [ 'third' , '3' , 4 ] , [ 'seventh' , '7' , 11 ] , [ 'fourth' , '4' , 5 ] , ] half_notes = measure ( note1 , note2 ) current = fifth_steps [ number_of_fifth_steps ] maj = current [ 2 ] if maj == half_notes : if current [ 0 ] == 'fifth' : if not shorthand : return 'perfect fifth' elif current [ 0 ] == 'fourth' : if not shorthand : return 'perfect fourth' if not shorthand : return 'major ' + current [ 0 ] return current [ 1 ] elif maj + 1 <= half_notes : if not shorthand : return 'augmented ' + current [ 0 ] return '#' * ( half_notes - maj ) + current [ 1 ] elif maj - 1 == half_notes : if not shorthand : return 'minor ' + current [ 0 ] return 'b' + current [ 1 ] elif maj - 2 >= half_notes : if not shorthand : return 'diminished ' + current [ 0 ] return 'b' * ( maj - half_notes ) + current [ 1 ]
Name the interval between note1 and note2 .
47,350
def from_shorthand ( note , interval , up = True ) : if not notes . is_valid_note ( note ) : return False shorthand_lookup = [ [ '1' , major_unison , major_unison ] , [ '2' , major_second , minor_seventh ] , [ '3' , major_third , minor_sixth ] , [ '4' , major_fourth , major_fifth ] , [ '5' , major_fifth , major_fourth ] , [ '6' , major_sixth , minor_third ] , [ '7' , major_seventh , minor_second ] , ] val = False for shorthand in shorthand_lookup : if shorthand [ 0 ] == interval [ - 1 ] : if up : val = shorthand [ 1 ] ( note ) else : val = shorthand [ 2 ] ( note ) if val == False : return False for x in interval : if x == '#' : if up : val = notes . augment ( val ) else : val = notes . diminish ( val ) elif x == 'b' : if up : val = notes . diminish ( val ) else : val = notes . augment ( val ) else : return val
Return the note on interval up or down .
47,351
def is_consonant ( note1 , note2 , include_fourths = True ) : return ( is_perfect_consonant ( note1 , note2 , include_fourths ) or is_imperfect_consonant ( note1 , note2 ) )
Return True if the interval is consonant .
47,352
def is_perfect_consonant ( note1 , note2 , include_fourths = True ) : dhalf = measure ( note1 , note2 ) return dhalf in [ 0 , 7 ] or include_fourths and dhalf == 5
Return True if the interval is a perfect consonant one .
47,353
def add_track ( self , track ) : if not hasattr ( track , 'bars' ) : raise UnexpectedObjectError ( "Unexpected object '%s', " "expecting a mingus.containers.Track object" % track ) self . tracks . append ( track ) self . selected_tracks = [ len ( self . tracks ) - 1 ]
Add a track to the composition .
47,354
def add_note ( self , note ) : for n in self . selected_tracks : self . tracks [ n ] + note
Add a note to the selected tracks .
47,355
def cfunc ( name , result , * args ) : atypes = [ ] aflags = [ ] for arg in args : atypes . append ( arg [ 1 ] ) aflags . append ( ( arg [ 2 ] , arg [ 0 ] ) + arg [ 3 : ] ) return CFUNCTYPE ( result , * atypes ) ( ( name , _fl ) , tuple ( aflags ) )
Build and apply a ctypes prototype complete with parameter flags .
47,356
def fluid_synth_write_s16_stereo ( synth , len ) : import numpy buf = create_string_buffer ( len * 4 ) fluid_synth_write_s16 ( synth , len , buf , 0 , 2 , buf , 1 , 2 ) return numpy . fromstring ( buf [ : ] , dtype = numpy . int16 )
Return generated samples in stereo 16 - bit format .
47,357
def start ( self , driver = None ) : if driver is not None : assert driver in [ 'alsa' , 'oss' , 'jack' , 'portaudio' , 'sndmgr' , 'coreaudio' , 'Direct Sound' , 'dsound' , 'pulseaudio' ] fluid_settings_setstr ( self . settings , 'audio.driver' , driver ) self . audio_driver = new_fluid_audio_driver ( self . settings , self . synth )
Start audio output driver in separate background thread .
47,358
def program_select ( self , chan , sfid , bank , preset ) : return fluid_synth_program_select ( self . synth , chan , sfid , bank , preset )
Select a program .
47,359
def noteon ( self , chan , key , vel ) : if key < 0 or key > 128 : return False if chan < 0 : return False if vel < 0 or vel > 128 : return False return fluid_synth_noteon ( self . synth , chan , key , vel )
Play a note .
47,360
def noteoff ( self , chan , key ) : if key < 0 or key > 128 : return False if chan < 0 : return False return fluid_synth_noteoff ( self . synth , chan , key )
Stop a note .
47,361
def cc ( self , chan , ctrl , val ) : return fluid_synth_cc ( self . synth , chan , ctrl , val )
Send control change value .
47,362
def is_valid_note ( note ) : if not _note_dict . has_key ( note [ 0 ] ) : return False for post in note [ 1 : ] : if post != 'b' and post != '#' : return False return True
Return True if note is in a recognised format . False if not .
47,363
def reduce_accidentals ( note ) : val = note_to_int ( note [ 0 ] ) for token in note [ 1 : ] : if token == 'b' : val -= 1 elif token == '#' : val += 1 else : raise NoteFormatError ( "Unknown note format '%s'" % note ) if val >= note_to_int ( note [ 0 ] ) : return int_to_note ( val % 12 ) else : return int_to_note ( val % 12 , 'b' )
Reduce any extra accidentals to proper notes .
47,364
def remove_redundant_accidentals ( note ) : val = 0 for token in note [ 1 : ] : if token == 'b' : val -= 1 elif token == '#' : val += 1 result = note [ 0 ] while val > 0 : result = augment ( result ) val -= 1 while val < 0 : result = diminish ( result ) val += 1 return result
Remove redundant sharps and flats from the given note .
47,365
def _gcd ( a = None , b = None , terms = None ) : if terms : return reduce ( lambda a , b : _gcd ( a , b ) , terms ) else : while b : ( a , b ) = ( b , a % b ) return a
Return greatest common divisor using Euclid s Algorithm .
47,366
def get_key_signature ( key = 'C' ) : if not is_valid_key ( key ) : raise NoteFormatError ( "unrecognized format for key '%s'" % key ) for couple in keys : if key in couple : accidentals = keys . index ( couple ) - 7 return accidentals
Return the key signature .
47,367
def get_key_signature_accidentals ( key = 'C' ) : accidentals = get_key_signature ( key ) res = [ ] if accidentals < 0 : for i in range ( - accidentals ) : res . append ( '{0}{1}' . format ( list ( reversed ( notes . fifths ) ) [ i ] , 'b' ) ) elif accidentals > 0 : for i in range ( accidentals ) : res . append ( '{0}{1}' . format ( notes . fifths [ i ] , '#' ) ) return res
Return the list of accidentals present into the key signature .
47,368
def get_notes ( key = 'C' ) : if _key_cache . has_key ( key ) : return _key_cache [ key ] if not is_valid_key ( key ) : raise NoteFormatError ( "unrecognized format for key '%s'" % key ) result = [ ] altered_notes = map ( operator . itemgetter ( 0 ) , get_key_signature_accidentals ( key ) ) if get_key_signature ( key ) < 0 : symbol = 'b' elif get_key_signature ( key ) > 0 : symbol = '#' raw_tonic_index = base_scale . index ( key . upper ( ) [ 0 ] ) for note in islice ( cycle ( base_scale ) , raw_tonic_index , raw_tonic_index + 7 ) : if note in altered_notes : result . append ( '%s%s' % ( note , symbol ) ) else : result . append ( note ) _key_cache [ key ] = result return result
Return an ordered list of the notes in this natural key .
47,369
def attach ( self , listener ) : if listener not in self . listeners : self . listeners . append ( listener )
Attach an object that should be notified of events .
47,370
def detach ( self , listener ) : if listener in self . listeners : self . listeners . remove ( listener )
Detach a listening object so that it won t receive any events anymore .
47,371
def notify_listeners ( self , msg_type , params ) : for c in self . listeners : c . notify ( msg_type , params )
Send a message to all the observers .
47,372
def set_instrument ( self , channel , instr , bank = 0 ) : self . instr_event ( channel , instr , bank ) self . notify_listeners ( self . MSG_INSTR , { 'channel' : int ( channel ) , 'instr' : int ( instr ) , 'bank' : int ( bank ) } )
Set the channel to the instrument _instr_ .
47,373
def control_change ( self , channel , control , value ) : if control < 0 or control > 128 : return False if value < 0 or value > 128 : return False self . cc_event ( channel , control , value ) self . notify_listeners ( self . MSG_CC , { 'channel' : int ( channel ) , 'control' : int ( control ) , 'value' : int ( value ) } ) return True
Send a control change message .
47,374
def stop_Note ( self , note , channel = 1 ) : if hasattr ( note , 'channel' ) : channel = note . channel self . stop_event ( int ( note ) + 12 , int ( channel ) ) self . notify_listeners ( self . MSG_STOP_INT , { 'channel' : int ( channel ) , 'note' : int ( note ) + 12 } ) self . notify_listeners ( self . MSG_STOP_NOTE , { 'channel' : int ( channel ) , 'note' : note } ) return True
Stop a note on a channel .
47,375
def stop_everything ( self ) : for x in range ( 118 ) : for c in range ( 16 ) : self . stop_Note ( x , c )
Stop all the notes on all channels .
47,376
def play_NoteContainer ( self , nc , channel = 1 , velocity = 100 ) : self . notify_listeners ( self . MSG_PLAY_NC , { 'notes' : nc , 'channel' : channel , 'velocity' : velocity } ) if nc is None : return True for note in nc : if not self . play_Note ( note , channel , velocity ) : return False return True
Play the Notes in the NoteContainer nc .
47,377
def stop_NoteContainer ( self , nc , channel = 1 ) : self . notify_listeners ( self . MSG_PLAY_NC , { 'notes' : nc , 'channel' : channel } ) if nc is None : return True for note in nc : if not self . stop_Note ( note , channel ) : return False return True
Stop playing the notes in NoteContainer nc .
47,378
def play_Bar ( self , bar , channel = 1 , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_BAR , { 'bar' : bar , 'channel' : channel , 'bpm' : bpm } ) qn_length = 60.0 / bpm for nc in bar : if not self . play_NoteContainer ( nc [ 2 ] , channel , 100 ) : return { } if hasattr ( nc [ 2 ] , 'bpm' ) : bpm = nc [ 2 ] . bpm qn_length = 60.0 / bpm ms = qn_length * ( 4.0 / nc [ 1 ] ) self . sleep ( ms ) self . notify_listeners ( self . MSG_SLEEP , { 's' : ms } ) self . stop_NoteContainer ( nc [ 2 ] , channel ) return { 'bpm' : bpm }
Play a Bar object .
47,379
def play_Track ( self , track , channel = 1 , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_TRACK , { 'track' : track , 'channel' : channel , 'bpm' : bpm } ) for bar in track : res = self . play_Bar ( bar , channel , bpm ) if res != { } : bpm = res [ 'bpm' ] else : return { } return { 'bpm' : bpm }
Play a Track object .
47,380
def play_Tracks ( self , tracks , channels , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_TRACKS , { 'tracks' : tracks , 'channels' : channels , 'bpm' : bpm } ) for x in range ( len ( tracks ) ) : instr = tracks [ x ] . instrument if isinstance ( instr , MidiInstrument ) : try : i = instr . names . index ( instr . name ) except : i = 1 self . set_instrument ( channels [ x ] , i ) else : self . set_instrument ( channels [ x ] , 1 ) current_bar = 0 max_bar = len ( tracks [ 0 ] ) while current_bar < max_bar : playbars = [ ] for tr in tracks : playbars . append ( tr [ current_bar ] ) res = self . play_Bars ( playbars , channels , bpm ) if res != { } : bpm = res [ 'bpm' ] else : return { } current_bar += 1 return { 'bpm' : bpm }
Play a list of Tracks .
47,381
def play_Composition ( self , composition , channels = None , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_COMPOSITION , { 'composition' : composition , 'channels' : channels , 'bpm' : bpm } ) if channels == None : channels = map ( lambda x : x + 1 , range ( len ( composition . tracks ) ) ) return self . play_Tracks ( composition . tracks , channels , bpm )
Play a Composition object .
47,382
def _find_log_index ( f ) : global _last_asked , _log_cache ( begin , end ) = ( 0 , 128 ) if _last_asked is not None : ( lastn , lastval ) = _last_asked if f >= lastval : if f <= _log_cache [ lastn ] : _last_asked = ( lastn , f ) return lastn elif f <= _log_cache [ lastn + 1 ] : _last_asked = ( lastn + 1 , f ) return lastn + 1 begin = lastn if f > _log_cache [ 127 ] or f <= 0 : return 128 while begin != end : n = ( begin + end ) // 2 c = _log_cache [ n ] cp = _log_cache [ n - 1 ] if n != 0 else 0 if cp < f <= c : _last_asked = ( n , f ) return n if f < c : end = n else : begin = n _last_asked = ( begin , f ) return begin
Look up the index of the frequency f in the frequency table .
47,383
def find_frequencies ( data , freq = 44100 , bits = 16 ) : n = len ( data ) p = _fft ( data ) uniquePts = numpy . ceil ( ( n + 1 ) / 2.0 ) p = [ ( abs ( x ) / float ( n ) ) ** 2 * 2 for x in p [ 0 : uniquePts ] ] p [ 0 ] = p [ 0 ] / 2 if n % 2 == 0 : p [ - 1 ] = p [ - 1 ] / 2 s = freq / float ( n ) freqArray = numpy . arange ( 0 , uniquePts * s , s ) return zip ( freqArray , p )
Convert audio data into a frequency - amplitude table using fast fourier transformation .
47,384
def find_Note ( data , freq , bits ) : data = find_frequencies ( data , freq , bits ) return sorted ( find_notes ( data ) , key = operator . itemgetter ( 1 ) ) [ - 1 ] [ 0 ]
Get the frequencies feed them to find_notes and the return the Note with the highest amplitude .
47,385
def analyze_chunks ( data , freq , bits , chunksize = 512 ) : res = [ ] while data != [ ] : f = find_frequencies ( data [ : chunksize ] , freq , bits ) res . append ( sorted ( find_notes ( f ) , key = operator . itemgetter ( 1 ) ) [ - 1 ] [ 0 ] ) data = data [ chunksize : ] return res
Cut the one channel data in chunks and analyzes them separately .
47,386
def find_melody ( file = '440_480_clean.wav' , chunksize = 512 ) : ( data , freq , bits ) = data_from_file ( file ) res = [ ] for d in analyze_chunks ( data , freq , bits , chunksize ) : if res != [ ] : if res [ - 1 ] [ 0 ] == d : val = res [ - 1 ] [ 1 ] res [ - 1 ] = ( d , val + 1 ) else : res . append ( ( d , 1 ) ) else : res . append ( ( d , 1 ) ) return [ ( x , freq ) for ( x , freq ) in res ]
Cut the sample into chunks and analyze each chunk .
47,387
def write_Note ( file , note , bpm = 120 , repeat = 0 , verbose = False ) : m = MidiFile ( ) t = MidiTrack ( bpm ) m . tracks = [ t ] while repeat >= 0 : t . set_deltatime ( '\x00' ) t . play_Note ( note ) t . set_deltatime ( "\x48" ) t . stop_Note ( note ) repeat -= 1 return m . write_file ( file , verbose )
Expect a Note object from mingus . containers and save it into a MIDI file specified in file .
47,388
def write_NoteContainer ( file , notecontainer , bpm = 120 , repeat = 0 , verbose = False ) : m = MidiFile ( ) t = MidiTrack ( bpm ) m . tracks = [ t ] while repeat >= 0 : t . set_deltatime ( '\x00' ) t . play_NoteContainer ( notecontainer ) t . set_deltatime ( "\x48" ) t . stop_NoteContainer ( notecontainer ) repeat -= 1 return m . write_file ( file , verbose )
Write a mingus . NoteContainer to a MIDI file .
47,389
def write_Bar ( file , bar , bpm = 120 , repeat = 0 , verbose = False ) : m = MidiFile ( ) t = MidiTrack ( bpm ) m . tracks = [ t ] while repeat >= 0 : t . play_Bar ( bar ) repeat -= 1 return m . write_file ( file , verbose )
Write a mingus . Bar to a MIDI file .
47,390
def write_Track ( file , track , bpm = 120 , repeat = 0 , verbose = False ) : m = MidiFile ( ) t = MidiTrack ( bpm ) m . tracks = [ t ] while repeat >= 0 : t . play_Track ( track ) repeat -= 1 return m . write_file ( file , verbose )
Write a mingus . Track to a MIDI file .
47,391
def write_Composition ( file , composition , bpm = 120 , repeat = 0 , verbose = False ) : m = MidiFile ( ) t = [ ] for x in range ( len ( composition . tracks ) ) : t += [ MidiTrack ( bpm ) ] m . tracks = t while repeat >= 0 : for i in range ( len ( composition . tracks ) ) : m . tracks [ i ] . play_Track ( composition . tracks [ i ] ) repeat -= 1 return m . write_file ( file , verbose )
Write a mingus . Composition to a MIDI file .
47,392
def get_midi_data ( self ) : tracks = [ t . get_midi_data ( ) for t in self . tracks if t . track_data != '' ] return self . header ( ) + '' . join ( tracks )
Collect and return the raw binary MIDI data from the tracks .
47,393
def header ( self ) : tracks = a2b_hex ( '%04x' % len ( [ t for t in self . tracks if t . track_data != '' ] ) ) return 'MThd\x00\x00\x00\x06\x00\x01' + tracks + self . time_division
Return a header for type 1 MIDI file .
47,394
def write_file ( self , file , verbose = False ) : dat = self . get_midi_data ( ) try : f = open ( file , 'wb' ) except : print "Couldn't open '%s' for writing." % file return False try : f . write ( dat ) except : print 'An error occured while writing data to %s.' % file return False f . close ( ) if verbose : print 'Written %d bytes to %s.' % ( len ( dat ) , file ) return True
Collect the data from get_midi_data and write to file .
47,395
def fingers_needed ( fingering ) : split = False indexfinger = False minimum = min ( finger for finger in fingering if finger ) result = 0 for finger in reversed ( fingering ) : if finger == 0 : split = True else : if not split and finger == minimum : if not indexfinger : result += 1 indexfinger = True else : result += 1 return result
Return the number of fingers needed to play the given fingering .
47,396
def add_tuning ( instrument , description , tuning ) : t = StringTuning ( instrument , description , tuning ) if _known . has_key ( str . upper ( instrument ) ) : _known [ str . upper ( instrument ) ] [ 1 ] [ str . upper ( description ) ] = t else : _known [ str . upper ( instrument ) ] = ( instrument , { str . upper ( description ) : t } )
Add a new tuning to the index .
47,397
def get_tuning ( instrument , description , nr_of_strings = None , nr_of_courses = None ) : searchi = str . upper ( instrument ) searchd = str . upper ( description ) keys = _known . keys ( ) for x in keys : if ( searchi not in keys and x . find ( searchi ) == 0 or searchi in keys and x == searchi ) : for ( desc , tun ) in _known [ x ] [ 1 ] . iteritems ( ) : if desc . find ( searchd ) == 0 : if nr_of_strings is None and nr_of_courses is None : return tun elif nr_of_strings is not None and nr_of_courses is None : if tun . count_strings ( ) == nr_of_strings : return tun elif nr_of_strings is None and nr_of_courses is not None : if tun . count_courses ( ) == nr_of_courses : return tun else : if tun . count_courses ( ) == nr_of_courses and tun . count_strings ( ) == nr_of_strings : return tun
Get the first tuning that satisfies the constraints .
47,398
def get_tunings ( instrument = None , nr_of_strings = None , nr_of_courses = None ) : search = '' if instrument is not None : search = str . upper ( instrument ) result = [ ] keys = _known . keys ( ) inkeys = search in keys for x in keys : if ( instrument is None or not inkeys and x . find ( search ) == 0 or inkeys and search == x ) : if nr_of_strings is None and nr_of_courses is None : result += _known [ x ] [ 1 ] . values ( ) elif nr_of_strings is not None and nr_of_courses is None : result += [ y for y in _known [ x ] [ 1 ] . itervalues ( ) if y . count_strings ( ) == nr_of_strings ] elif nr_of_strings is None and nr_of_courses is not None : result += [ y for y in _known [ x ] [ 1 ] . itervalues ( ) if y . count_courses ( ) == nr_of_courses ] else : result += [ y for y in _known [ x ] [ 1 ] . itervalues ( ) if y . count_strings ( ) == nr_of_strings and y . count_courses ( ) == nr_of_courses ] return result
Search tunings on instrument strings courses or a combination .
47,399
def count_courses ( self ) : c = 0 for x in self . tuning : if type ( x ) == list : c += len ( x ) else : c += 1 return float ( c ) / len ( self . tuning )
Return the average number of courses per string .