idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
235,200
def apply_visitor ( visitor , decl_inst ) : fname = 'visit_' + decl_inst . __class__ . __name__ [ : - 2 ] # removing '_t' from class name if not hasattr ( visitor , fname ) : raise runtime_errors . visit_function_has_not_been_found_t ( visitor , decl_inst ) return getattr ( visitor , fname ) ( )
Applies a visitor on declaration instance .
94
8
235,201
def does_match_exist ( self , inst ) : answer = True if self . _decl_type is not None : answer &= isinstance ( inst , self . _decl_type ) if self . name is not None : answer &= inst . name == self . name if self . parent is not None : answer &= self . parent is inst . parent if self . fullname is not None : if inst . name : answer &= self . fullname == declaration_utils . full_name ( inst ) else : answer = False return answer
Returns True if inst does match one of specified criteria .
116
11
235,202
def partial_name ( self ) : if None is self . _partial_name : self . _partial_name = self . _get_partial_name_impl ( ) return self . _partial_name
Declaration name without template default arguments .
44
8
235,203
def top_parent ( self ) : parent = self . parent while parent is not None : if parent . parent is None : return parent else : parent = parent . parent return self
Reference to top parent declaration .
37
6
235,204
def clone ( self , * * keywd ) : return argument_t ( name = keywd . get ( 'name' , self . name ) , decl_type = keywd . get ( 'decl_type' , self . decl_type ) , default_value = keywd . get ( 'default_value' , self . default_value ) , attributes = keywd . get ( 'attributes' , self . attributes ) )
constructs new argument_t instance
93
7
235,205
def required_args ( self ) : r_args = [ ] for arg in self . arguments : if not arg . default_value : r_args . append ( arg ) else : break return r_args
list of all required arguments
44
5
235,206
def overloads ( self ) : if not self . parent : return [ ] # finding all functions with the same name return self . parent . calldefs ( name = self . name , function = lambda decl : decl is not self , allow_empty = True , recursive = False )
A list of overloaded callables ( i . e . other callables with the same name within the same scope .
60
23
235,207
def file_signature ( filename ) : if not os . path . isfile ( filename ) : return None if not os . path . exists ( filename ) : return None # Duplicate auto-generated files can be recognized with the sha1 hash. sig = hashlib . sha1 ( ) with open ( filename , "rb" ) as f : buf = f . read ( ) sig . update ( buf ) return sig . hexdigest ( )
Return a signature for a file .
96
7
235,208
def __load ( file_name ) : if os . path . exists ( file_name ) and not os . path . isfile ( file_name ) : raise RuntimeError ( 'Cache should be initialized with valid full file name' ) if not os . path . exists ( file_name ) : open ( file_name , 'w+b' ) . close ( ) return { } cache_file_obj = open ( file_name , 'rb' ) try : file_cache_t . logger . info ( 'Loading cache file "%s".' , file_name ) start_time = timeit . default_timer ( ) cache = pickle . load ( cache_file_obj ) file_cache_t . logger . debug ( "Cache file has been loaded in %.1f secs" , ( timeit . default_timer ( ) - start_time ) ) file_cache_t . logger . debug ( "Found cache in file: [%s] entries: %s" , file_name , len ( list ( cache . keys ( ) ) ) ) except ( pickle . UnpicklingError , AttributeError , EOFError , ImportError , IndexError ) as error : file_cache_t . logger . exception ( "Error occurred while reading cache file: %s" , error ) cache_file_obj . close ( ) file_cache_t . logger . info ( "Invalid cache file: [%s] Regenerating." , file_name ) open ( file_name , 'w+b' ) . close ( ) # Create empty file cache = { } # Empty cache finally : cache_file_obj . close ( ) return cache
Load pickled cache from file and return the object .
357
11
235,209
def update ( self , source_file , configuration , declarations , included_files ) : record = record_t ( source_signature = file_signature ( source_file ) , config_signature = configuration_signature ( configuration ) , included_files = included_files , included_files_signature = list ( map ( file_signature , included_files ) ) , declarations = declarations ) # Switched over to holding full record in cache so we don't have # to keep creating records in the next method. self . __cache [ record . key ( ) ] = record self . __cache [ record . key ( ) ] . was_hit = True self . __needs_flushed = True
Update a cached record with the current key and value contents .
150
12
235,210
def cached_value ( self , source_file , configuration ) : key = record_t . create_key ( source_file , configuration ) if key not in self . __cache : return None record = self . __cache [ key ] if self . __is_valid_signature ( record ) : record . was_hit = True # Record cache hit return record . declarations # some file has been changed del self . __cache [ key ] return None
Attempt to lookup the cached declarations for the given file and configuration .
95
13
235,211
def find_version ( file_path ) : with io . open ( os . path . join ( os . path . dirname ( __file__ ) , os . path . normpath ( file_path ) ) , encoding = "utf8" ) as fp : content = fp . read ( ) version_match = re . search ( r"^__version__ = ['\"]([^'\"]*)['\"]" , content , re . M ) if version_match : return version_match . group ( 1 ) raise RuntimeError ( "Unable to find version string." )
Find the version of pygccxml .
126
9
235,212
def __read_byte_size ( decl , attrs ) : size = attrs . get ( XML_AN_SIZE , 0 ) # Make sure the size is in bytes instead of bits decl . byte_size = int ( size ) / 8
Using duck typing to set the size instead of in constructor
52
11
235,213
def __read_byte_offset ( decl , attrs ) : offset = attrs . get ( XML_AN_OFFSET , 0 ) # Make sure the size is in bytes instead of bits decl . byte_offset = int ( offset ) / 8
Using duck typing to set the offset instead of in constructor
53
11
235,214
def __read_byte_align ( decl , attrs ) : align = attrs . get ( XML_AN_ALIGN , 0 ) # Make sure the size is in bytes instead of bits decl . byte_align = int ( align ) / 8
Using duck typing to set the alignment
53
7
235,215
def bind_aliases ( decls ) : visited = set ( ) typedefs = [ decl for decl in decls if isinstance ( decl , declarations . typedef_t ) ] for decl in typedefs : type_ = declarations . remove_alias ( decl . decl_type ) if not isinstance ( type_ , declarations . declarated_t ) : continue cls_inst = type_ . declaration if not isinstance ( cls_inst , declarations . class_types ) : continue if id ( cls_inst ) not in visited : visited . add ( id ( cls_inst ) ) del cls_inst . aliases [ : ] cls_inst . aliases . append ( decl )
This function binds between class and it s typedefs .
152
12
235,216
def after_scenario ( ctx , scenario ) : if hasattr ( ctx , 'container' ) and hasattr ( ctx , 'client' ) : try : ctx . client . remove_container ( ctx . container , force = True ) except : pass
Cleans up docker containers used as test fixtures after test completes .
58
13
235,217
def set_blocking ( fd , blocking = True ) : old_flag = fcntl . fcntl ( fd , fcntl . F_GETFL ) if blocking : new_flag = old_flag & ~ os . O_NONBLOCK else : new_flag = old_flag | os . O_NONBLOCK fcntl . fcntl ( fd , fcntl . F_SETFL , new_flag ) return not bool ( old_flag & os . O_NONBLOCK )
Set the given file - descriptor blocking or non - blocking .
122
12
235,218
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 : # POSIX signals interrupt select() 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 .
114
24
235,219
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 .
84
15
235,220
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 : ] # try to close after writes if a close was requested 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 .
137
14
235,221
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 : # the stream has closed, return what data we got return data data = data + nxt return data
Read up to n bytes of data from the Stream after demuxing .
91
15
235,222
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 .
94
15
235,223
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 .
98
10
235,224
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 .
61
13
235,225
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 .
45
12
235,226
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 .
51
12
235,227
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 .
32
13
235,228
def resize ( self , height , width , * * kwargs ) : self . client . resize ( self . container , height = height , width = width )
resize pty within container
34
6
235,229
def resize ( self , height , width , * * kwargs ) : self . client . exec_resize ( self . exec_id , height = height , width = width )
resize pty of an execed process
39
9
235,230
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
42
10
235,231
def format_number ( x ) : if isinstance ( x , float ) : # Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision. # However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a # floating point number. # The g option is used rather than f because g precision uses significant digits while f is just the number of # digits after the decimal. (NRRD C implementation uses g). value = '{:.17g}' . format ( x ) else : value = str ( x ) return value
Format number to string
125
4
235,232
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 .
36
10
235,233
def _determine_datatype ( fields ) : # Convert the NRRD type string identifier into a NumPy string identifier using a map np_typestring = _TYPEMAP_NRRD2NUMPY [ fields [ 'type' ] ] # This is only added if the datatype has more than one byte and is not using ASCII encoding # Note: Endian is not required for ASCII encoding 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 .
266
12
235,234
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
136
24
235,235
def read ( filename , custom_field_map = None , index_order = 'F' ) : """Read a NRRD file and return a tuple (data, header).""" 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
88
12
235,236
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 # Check whether the last bar is full, if so create a new bar and add the # note there 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 ) ) # warning should hold note if it doesn't fit return self . bars [ - 1 ] . place_notes ( note , duration )
Add a Note note as string or NoteContainer to the last Bar .
184
14
235,237
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 .
30
14
235,238
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 ) : # This should be the standard behaviour of add_notes dur = self . bars [ - 1 ] . value_left ( ) self . add_notes ( chord , dur ) # warning should hold note 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 .
209
6
235,239
def get_tuning ( self ) : if self . instrument and self . instrument . tuning : return self . instrument . tuning return self . tuning
Return a StringTuning object .
30
7
235,240
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 .
31
14
235,241
def set_meter ( self , meter ) : # warning should raise exception 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 .
128
7
235,242
def place_notes ( self , notes , duration ) : # note should be able to be one of strings, lists, Notes or # NoteContainers 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 .
154
9
235,243
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 .
38
7
235,244
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 .
48
9
235,245
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 .
50
16
235,246
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 .
83
13
235,247
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 .
71
11
235,248
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 .
32
13
235,249
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 .
51
11
235,250
def parse_midi_file_header ( self , fp ) : # Check header 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." ) # Parse chunk size 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 ) # Expect chunk size to be at least 6 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 .
379
24
235,251
def parse_time_division ( self , bytes ) : # If highest bit is set, time division is set in frames per second # otherwise in ticks_per_beat 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 .
196
35
235,252
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 .
140
12
235,253
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." ) # Get the nibbles event_type = ( ec & 0xf0 ) >> 4 channel = ec & 0x0f # I don't know what these events are supposed to do, but I keep finding # them. The parser ignores them. if event_type < 8 : raise FormatError ( 'Unknown event type %d. Byte %d.' % ( event_type , self . bytes_read ) ) # Meta events can have strings of variable length 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 ] : # Program change and Channel aftertouch events only have one # parameter 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 .
533
6
235,254
def parse_track_header ( self , fp ) : # Check the header 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 ) # Parse the size of the header 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 .
159
8
235,255
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 .
148
14
235,256
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 .
201
11
235,257
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 .
31
15
235,258
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 .
95
10
235,259
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 .
36
8
235,260
def from_hertz ( self , hertz , standard_pitch = 440 ) : value = ( ( log ( ( float ( hertz ) * 1024 ) / standard_pitch , 2 ) + 1.0 / 24 ) * 12 + 9 ) # notes.note_to_int("A") 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 .
99
13
235,261
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 .
70
9
235,262
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 .
164
10
235,263
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 .
113
17
235,264
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 .
51
22
235,265
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 ) # We are practically done right now, but we need to be able to create the # minor seventh of Cb and get Bbb instead of B######### as the result val = 0 for token in note2 [ 1 : ] : if token == '#' : val += 1 elif token == 'b' : val -= 1 # These are some checks to see if we have generated too much #'s or too much # b's. In these cases we need to convert #'s to b's and vice versa. if val > 6 : val = val % 12 val = - 12 + val elif val < - 6 : val = val % - 12 val = 12 + val # Rebuild the note 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 .
274
10
235,266
def invert ( interval ) : interval . reverse ( ) res = list ( interval ) interval . reverse ( ) return res
Invert an interval .
25
5
235,267
def determine ( note1 , note2 , shorthand = False ) : # Corner case for unisons ('A' and 'Ab', for instance) if note1 [ 0 ] == note2 [ 0 ] : def get_val ( note ) : """Private function: count the value of accidentals.""" 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' # Other intervals 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 # [name, shorthand_name, half notes for major version of this interval] fifth_steps = [ [ 'unison' , '1' , 0 ] , [ 'fifth' , '5' , 7 ] , [ 'second' , '2' , 2 ] , [ 'sixth' , '6' , 9 ] , [ 'third' , '3' , 4 ] , [ 'seventh' , '7' , 11 ] , [ 'fourth' , '4' , 5 ] , ] # Count half steps between note1 and note2 half_notes = measure ( note1 , note2 ) # Get the proper list from the number of fifth steps current = fifth_steps [ number_of_fifth_steps ] # maj = number of major steps for this interval maj = current [ 2 ] # if maj is equal to the half steps between note1 and note2 the interval is # major or perfect if maj == half_notes : # Corner cases for perfect fifths and fourths 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 maj + 1 is equal to half_notes, the interval is augmented. if not shorthand : return 'augmented ' + current [ 0 ] return '#' * ( half_notes - maj ) + current [ 1 ] elif maj - 1 == half_notes : # etc. 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 .
677
10
235,268
def from_shorthand ( note , interval , up = True ) : # warning should be a valid note. if not notes . is_valid_note ( note ) : return False # [shorthand, interval function up, interval function down] 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 ] , ] # Looking up last character in interval in shorthand_lookup and calling that # function. val = False for shorthand in shorthand_lookup : if shorthand [ 0 ] == interval [ - 1 ] : if up : val = shorthand [ 1 ] ( note ) else : val = shorthand [ 2 ] ( note ) # warning Last character in interval should be 1-7 if val == False : return False # Collect accidentals 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 .
316
9
235,269
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 .
59
9
235,270
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 .
53
12
235,271
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 .
77
7
235,272
def add_note ( self , note ) : for n in self . selected_tracks : self . tracks [ n ] + note
Add a note to the selected tracks .
27
8
235,273
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 .
87
12
235,274
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 .
81
10
235,275
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 .
107
9
235,276
def program_select ( self , chan , sfid , bank , preset ) : return fluid_synth_program_select ( self . synth , chan , sfid , bank , preset )
Select a program .
44
4
235,277
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 .
64
4
235,278
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 .
49
4
235,279
def cc ( self , chan , ctrl , val ) : return fluid_synth_cc ( self . synth , chan , ctrl , val )
Send control change value .
34
5
235,280
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 .
55
14
235,281
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 .
114
10
235,282
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 .
83
11
235,283
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 .
60
13
235,284
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 .
69
5
235,285
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 .
129
12
235,286
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 = [ ] # Calculate notes 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 ) # Save result to cache _key_cache [ key ] = result return result
Return an ordered list of the notes in this natural key .
238
12
235,287
def attach ( self , listener ) : if listener not in self . listeners : self . listeners . append ( listener )
Attach an object that should be notified of events .
24
10
235,288
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 .
23
15
235,289
def notify_listeners ( self , msg_type , params ) : for c in self . listeners : c . notify ( msg_type , params )
Send a message to all the observers .
32
8
235,290
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_ .
73
11
235,291
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 .
92
6
235,292
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 .
121
7
235,293
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 .
34
8
235,294
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 .
90
10
235,295
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 .
77
10
235,296
def play_Bar ( self , bar , channel = 1 , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_BAR , { 'bar' : bar , 'channel' : channel , 'bpm' : bpm } ) # length of a quarter note qn_length = 60.0 / bpm for nc in bar : if not self . play_NoteContainer ( nc [ 2 ] , channel , 100 ) : return { } # Change the quarter note length if the NoteContainer has a bpm # attribute 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 .
229
5
235,297
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 .
108
5
235,298
def play_Tracks ( self , tracks , channels , bpm = 120 ) : self . notify_listeners ( self . MSG_PLAY_TRACKS , { 'tracks' : tracks , 'channels' : channels , 'bpm' : bpm } ) # Set the right instruments 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 ] ) # Play the bars 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 .
247
6
235,299
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 .
104
6