/*===================================================================
Sevenths
=================================================================== diatonic
339087
function seventh(note, key) {
	var arr = triad(note, key);
	arr.push(intervals.seventh(note, key));
	return arr;
}
957446
function buildMidiNumberAttributes(midiNumber) {
  const pitchIndex = (midiNumber - MIDI_NUMBER_C0) % NOTES_IN_OCTAVE;
  const octave = Math.floor((midiNumber - MIDI_NUMBER_C0) / NOTES_IN_OCTAVE);
  const pitchName = SORTED_PITCHES[pitchIndex];
  return {
    note: `${pitchName}${octave}`,
    pitchName,
    octave,
    midiNumber,
    isAccidental: ACCIDENTAL_PITCHES.includes(pitchName),
  };
}
1096899
function MIDIParserError(actual, expected, byte) {
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);

    this.name = this.constructor.name;
    this.actual = actual;
    this.expected = expected;

    actual = format(actual);
    expected = format(expected);

    this.message = 'Invalid MIDI file: expected ' +
        expected + ' but found ' + actual;

    if (byte !== undefined) {
        this.byte = byte;
        this.message += ' (at byte ' + byte + ')';
    }
}
617293
function Note(pitch_class) {
		var accidental = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Accidental.None;
		var octave = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4;

		this._pitch_class = pitch_class;
		this._accidental = accidental;
		this._octave = octave;
	}
690739
function main() {

    var database = fs.createWriteStream('./lib/database-min.js', { flags: 'w', encoding: 'utf8' });
    var testFile;

    fs.mkdir('./data', 493, function (error) {  // 493 == 0755 (no octal in strict mode.)
        // ignore errors.
    });
    
    database.write("// Do not edit this file, your changes will be lost.\n");
    database.write("module.exports = { \n");
    getJSON('http://alscan.info/agent_groups/groups.json', function (groups) {
        var s = JSON.stringify(groups);
        database.write("groups:" + s + ",\n");
        testFile = fs.createWriteStream('./data/groups.json', { flags: 'w', encoding: 'utf8' });
        testFile.write(s+"\n");
        testFile.end();
        getJSON('http://alscan.info/agent_sources/sources.json', function (sources) {
            var s = JSON.stringify(sources);
            database.write("sources:" + s + ",\n");
            testFile = fs.createWriteStream('./data/sources.json', { flags: 'w', encoding: 'utf8' });
            testFile.write(s+"\n");
            testFile.end();
            getJSON('http://alscan.info/patterns/patterns.json', function (patterns) {
                database.write("patterns:[\n");
                patterns.forEach(function (pattern) {
                    database.write("{p: new RegExp('" + pattern.pattern + "'), x:" + 
                            agentdb.getX(pattern.groupId, pattern.sourceId) + "},");
                });
                database.write("],\n");
                testFile = fs.createWriteStream('./data/patterns.json', { flags: 'w', encoding: 'utf8' });
                testFile.write(JSON.stringify(patterns)+"\n");
                testFile.end();
                getJSON('http://alscan.info/agents/agents.json', function (agents) {
                    var hash = new HashTable(HASH_TABLE_SIZE, HASH_TABLE_SEED, HASH_TABLE_MULTIPLIER);
                    agents.forEach(function (agent) {
                        if (agent.status < 2) {
                            var obj = { a: agent.agent, x: agentdb.getX(agent.groupId, agent.sourceId) };
                            hash.add('a', obj);
                        }
                    });
                    database.write("table:" + JSON.stringify(hash.table) + ",\n");
                    database.write("HASH_TABLE_SIZE:" + HASH_TABLE_SIZE + ",\n");
                    database.write("HASH_TABLE_SEED:" + HASH_TABLE_SEED + ",\n");
                    database.write("HASH_TABLE_MULTIPLIER:" + HASH_TABLE_MULTIPLIER + ",\n");
                    database.write("hash: undefined\n}\n");
                    testFile = fs.createWriteStream('./data/agents.json', { flags: 'w', encoding: 'utf8' });
                    testFile.write(JSON.stringify(agents)+"\n");
                    testFile.end();
                    if (debug) {
                        var history = hash.getHistory();
                        console.log("Hash table history");
                        for (var n=0; n < history.length; n++) {
                            console.log("  Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / HASH_TABLE_SIZE));
                        }
                    }
                });
            });
        });
    });
}
1273869
function (number, halfSteps) {
  var diatonicHalfSteps = getDiatonicHalfSteps(number);
  var halfStepOffset = halfSteps - diatonicHalfSteps;

  // Handle various abnormalities
  if (halfStepOffset === 11) halfStepOffset = -1;
  if (halfStepOffset === -11) halfStepOffset = 1;

  return halfStepOffset;
}
1177352
public final void mOctalEscape() throws RecognitionException {
        try {
            // BELStatement.g:297:21: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) )
            int alt5=3;
            int LA5_0 = input.LA(1);

            if ( (LA5_0=='\\') ) {
                int LA5_1 = input.LA(2);

                if ( ((LA5_1>='0' && LA5_1<='3')) ) {
                    int LA5_2 = input.LA(3);

                    if ( ((LA5_2>='0' && LA5_2<='7')) ) {
                        int LA5_4 = input.LA(4);

                        if ( ((LA5_4>='0' && LA5_4<='7')) ) {
                            alt5=1;
                        }
                        else {
                            alt5=2;}
                    }
                    else {
                        alt5=3;}
                }
                else if ( ((LA5_1>='4' && LA5_1<='7')) ) {
                    int LA5_3 = input.LA(3);

                    if ( ((LA5_3>='0' && LA5_3<='7')) ) {
                        alt5=2;
                    }
                    else {
                        alt5=3;}
                }
                else {
                    NoViableAltException nvae =
                        new NoViableAltException("", 5, 1, input);

                    throw nvae;
                }
            }
            else {
                NoViableAltException nvae =
                    new NoViableAltException("", 5, 0, input);

                throw nvae;
            }
            switch (alt5) {
                case 1 :
                    // BELStatement.g:298:5: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' )
                    {
                    match('\\'); 
                    // BELStatement.g:298:10: ( '0' .. '3' )
                    // BELStatement.g:298:11: '0' .. '3'
                    {
                    matchRange('0','3'); 

                    }

                    // BELStatement.g:298:21: ( '0' .. '7' )
                    // BELStatement.g:298:22: '0' .. '7'
                    {
                    matchRange('0','7'); 

                    }

                    // BELStatement.g:298:32: ( '0' .. '7' )
                    // BELStatement.g:298:33: '0' .. '7'
                    {
                    matchRange('0','7'); 

                    }


                    }
                    break;
                case 2 :
                    // BELStatement.g:299:7: '\\\\' ( '0' .. '7' ) ( '0' .. '7' )
                    {
                    match('\\'); 
                    // BELStatement.g:299:12: ( '0' .. '7' )
                    // BELStatement.g:299:13: '0' .. '7'
                    {
                    matchRange('0','7'); 

                    }

                    // BELStatement.g:299:23: ( '0' .. '7' )
                    // BELStatement.g:299:24: '0' .. '7'
                    {
                    matchRange('0','7'); 

                    }


                    }
                    break;
                case 3 :
                    // BELStatement.g:300:7: '\\\\' ( '0' .. '7' )
                    {
                    match('\\'); 
                    // BELStatement.g:300:12: ( '0' .. '7' )
                    // BELStatement.g:300:13: '0' .. '7'
                    {
                    matchRange('0','7'); 

                    }


                    }
                    break;

            }
        }
        finally {
        }
    }
755710
function (interval) {
    return _.find(notes, function (n) {
      return root.transpose(interval).enharmonic(n);
    });
  }
368163
function() {
		var n = this;
		if (n<20) {
			return [
				'zero', 'one', 'two', 'three', 'four', 'five',
				'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
				'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
				'seventeen', 'eighteen', 'nineteen' ][n];
		} else if (n<100) {
			var tens = Math.floor(n/10);
			var ones = n%10;
			return [
				'twenty', 'thirty', 'forty', 'fifty', 'sixty',
				'seventy', 'eighty', 'ninety'
			][tens-2]+((ones>0) ? '-'+ones.toWord() : '');
		} else if (n<1000) {
			var hundreds = Math.floor(n/100);
			var tens = n%100;
			return hundreds.toWord()+' hundred and '+tens.toWord();
		}

		var places = ['thousand', 'million', 'billion', 'trillion'];
		var d   = Math.floor(new String(n).length/3);
		var pow = Math.pow(1000, d);
		var principle = Math.floor(n/pow);
		var remainder = n%pow;
		return principle.toWord()+' '+places[d-1]+' '+remainder.toWord();
	}
823100
function () {

// Parse a number value.

            var number,
                string = '';

            if (ch === '-') {
                string = '-';
                next('-');
            }
            while (ch >= '0' && ch <= '9') {
                string += ch;
                next();
            }
            if (ch === '.') {
                string += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    string += ch;
                }
            }
            if (ch === 'e' || ch === 'E') {
                string += ch;
                next();
                if (ch === '-' || ch === '+') {
                    string += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    string += ch;
                    next();
                }
            }
            number = +string;
            if (isNaN(number)) {
                error("Bad number");
            } else {
                return number;
            }
        }
971487
function determine(chord, shorthand, no_inversions, no_polychords) {
	if(shorthand == null) {
		shorthand = false;
	}
	if(no_inversions == null) {
		no_inversions = false;
	}
	if(no_polychords == null) {
		no_polychords = false;
	}
	if(chord == []) {
		return [];
	} else if(chord.length == 1) {
		return chord;
	} else if(chord.length == 2) {
		return [intervals.determine(chord[0], chord[1])];
	} else if(chord.length == 3) {
		return determine_triad(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 4) {
		return determine_seventh(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 5) {
		return determine_extended_chord5(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 6) {
		return determine_extended_chord6(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 7) {
		return determine_extended_chord7(chord, shorthand, no_inversions, no_polychords);
	} else {
		return determine_polychords(chord, shorthand);
	}
}
258890
function (chords, settings) {
  var events = _.reduce(chords, function (arr, obj) {
    var time = noteLength(obj.duration, settings);
    var chord = obj.chord.inOctave(settings.chordOctave).chord;

    arr.push(makeChordEvent(0, true, 1, chord, settings.chordVelocity)); // On
    arr.push(makeChordEvent(time, false, 1, chord, settings.chordVelocity)); // Off

    return arr;
  }, []);

  return Buffer.concat(events);
}
1293860
function(opacity) {
        return function(g, i) {
          gEnter.selectAll(".chord")
              .filter(function(d) {
                return d.source.index != i && d.target.index != i;
              })
            .transition()
              .style("opacity", opacity);
          var groups = [];
          gEnter.selectAll(".chord")
              .filter(function(d) {
                if (d.source.index == i) {
                  groups.push(d.target.index);
                }
                if (d.target.index == i) {
                  groups.push(d.source.index);
                }
              });
          groups.push(i);
          var length = groups.length;
          gEnter.selectAll('.group')
              .filter(function(d) {
                for (var i = 0; i < length; i++) {
                  if(groups[i] == d.index) return false;
                }
                return true;
              })
              .transition()
                .style("opacity", opacity);
        };
      }
621446
def determine_polychords(chord, shorthand=False):
    
    polychords = []
    function_list = [determine_triad, determine_seventh,
                     determine_extended_chord5, determine_extended_chord6,
                     determine_extended_chord7]

    # Range tracking.
    if len(chord) <= 3:
        return []
    elif len(chord) > 14:
        return []
    elif len(chord) - 3 <= 5:
        function_nr = range(0, len(chord) - 3)
    else:
        function_nr = range(0, 5)
    for f in function_nr:
        for f2 in function_nr:
            # The clever part: Try the function_list[f] on the len(chord) - (3 +
            # f) last notes of the chord. Then try the function_list[f2] on the
            # f2 + 3 first notes of the chord. Thus, trying all possible
            # combinations.
            for chord1 in function_list[f](chord[len(chord) - (3 + f):], True,
                    True, True):
                for chord2 in function_list[f2](chord[:f2 + 3], True, True,
                        True):
                    polychords.append('%s|%s' % (chord1, chord2))
    if shorthand:
        for p in polychords:
            p = p + ' polychord'
    return polychords
688651
protected void onBaseChanged() {
		//System.out.println("JChord.onBaseChanged : "+multiNote);
		byte h = multiNote.getHighestNote().getHeight();
		byte l = multiNote.getLowestNote().getHeight();

		//if normalizedChords!=null [0] stems down, [1] stems up
		//autoStemming is disabled
		byte midHeight = getClef().getMiddleNote().getHeight();
		if ((m_normalizedChords == null) && isAutoStem()) {
            boolean stemUp = h <= midHeight || l <= midHeight && (h - midHeight) < (midHeight - l);
			//recalculate anchor and valuate its note char
			setStemUp(stemUp);
		}

		if (m_normalizedChords == null) {
			// set stemYEnd
			//   get highest/lowest in group
			//   set stems appropriately
			int stemYEnd;
			if (m_stemYEndForChord == -1) {
				//auto calculated, chord is not part of group
				int stemLength = getMetrics().getStemLengthForContext(ScoreMetrics.NOTATION_CONTEXT_NOTE);
				int halfNoteHeight = (int) (getMetrics().getNoteHeight() / 2);
				int highestNoteY = (int) getHighestNote().getStemUpBeginPosition().getY() - stemLength - halfNoteHeight;
				int lowestNoteY = (int) getLowestNote().getStemDownBeginPosition().getY() + stemLength + halfNoteHeight;
				stemYEnd = isStemUp()?highestNoteY:lowestNoteY;
			} else {
				stemYEnd = m_stemYEndForChord;
			}

            for (JNote m_sNoteInstance : m_sNoteInstances) {
                ((JNotePartOfGroup) m_sNoteInstance).setStemYEnd(stemYEnd);
            }
		}
		
		double graceNotesWidth = 0;
		boolean graceNotesAfter = false;
		if (m_jGracenotes != null) {
			if (multiNote.getGracingType() == GracingType.ACCIACCATURA)
				graceNotesAfter = getTemplate().getAttributeBoolean(ScoreAttribute.ACCIACCATURA_AFTER_NOTE);
			graceNotesWidth = m_jGracenotes.getWidth()
				+ getMetrics().getGraceNotesSpacing();
			if (graceNotesAfter)
				graceNotesWidth += getMetrics().getGraceNotesSpacing();
//			m_jGracenotes.onBaseChanged();
//			graceNotesWidth = m_jGracenotes.getWidth()
//				+ getMetrics().getGraceNotesSpacing();
		}
		
		double accidentalsWidth = 0;
		if (!isPartOfANormalizedChord) { //not already calculated
			//calculate accidantal position for all notes
			Note[] notes = multiNote.toArray();
			boolean chordHasStemDownInverted = false;
			for (int i = notes.length - 1; i >= 0; i--) {
				JNote jnote = getJNote(notes[i]);
				if (!jnote.isStemUp() && jnote.isHeadInverted()) {
					chordHasStemDownInverted = true;
					break;
				}
			}
			int accOffset = 1;
			int refAccidentedNote = -1;
			for (int i = notes.length - 1; i >= 0; i--) {
				//from highest to lowest
				if (notes[i].hasAccidental()) {
					JNote jnote = getJNote(notes[i]);
					if (refAccidentedNote == -1) {
						refAccidentedNote = i;
					} else {
						//if interval between reference and this note is smaller than
						//a sixth, accidentals are moved on the left
						//else accidental is at normal position, set note as referenec
						Interval interv = new Interval(notes[refAccidentedNote], notes[i], null);
						if (interv.getLabel() < Interval.SIXTH) {
							accOffset++;
						} else {
							accOffset = 1;
							refAccidentedNote = i;
						}
					}
					
					//For stem down chord with inverted heads, add a .5 (a note head)
					//offset to the accidental position
					float w_accOffset = accOffset;
					if (!jnote.isStemUp()
							&& !jnote.isHeadInverted()
							&& chordHasStemDownInverted)
						w_accOffset += .5f;
					if (w_accOffset != 1)
						jnote.setAccidentalPositionOffset(w_accOffset);
					
					double accWidth = jnote.getNotePosition().getX() - jnote.getBase().getX();
					accidentalsWidth = Math.max(accidentalsWidth, accWidth);
				}
			}
		}
		
		/* Horizontal position of note head, after graces and accidentals */
        double m_noteHeadX = getBase().getX()
                + (graceNotesAfter ? 0 : graceNotesWidth);
		
		Point2D chordBase = new Point2D.Double(m_noteHeadX, getBase().getY());
		
		double chordWidth = 0;
		
		// TODO: setBase for decorations

		if (m_normalizedChords==null) {
			
			// calculate slur/tie position last because slurs/ties must
			//  go over any decorations
			//if (note.getSlurDefinition()!=null)
			/*for (int i=0; i<m_sNoteInstances.length; i++) {
				((JNote)m_sNoteInstances[i]).calcSlursAndTiesPosition();
			}*/

			double biggestStemX = -1;
            for (JNote m_sNoteInstance : m_sNoteInstances) {
                m_sNoteInstance.setBase(chordBase);
                if (m_sNoteInstance.getStemBeginPosition().getX() > biggestStemX)
                    biggestStemX = m_sNoteInstance.getStemBeginPosition().getX();
                if (m_sNoteInstance.getWidth() > chordWidth)
                    chordWidth = m_sNoteInstance.getWidth();
            }
			//realign all stems
            for (JNote m_sNoteInstance : m_sNoteInstances) {
                Point2D stemBegin = m_sNoteInstance.getStemBeginPosition();
                Point2D newStemBegin = new Point2D.Double(biggestStemX, stemBegin.getY());
                m_sNoteInstance.setStemBeginPosition(newStemBegin);
            }
		}
		else
		{
            for (JChord m_normalizedChord : m_normalizedChords) {
                Point2D newBase = (Point2D) chordBase.clone();
                if (accidentalsWidth > 0) {
                    double tmpAccWidth = 0;
                    //determinate accidental width of the chord
                    for (int j = 0; j < m_normalizedChord.m_sNoteInstances.length; j++) {
                        JNote jnote = m_normalizedChord.m_sNoteInstances[j];
                        double accWidth = jnote.getNotePosition().getX() - jnote.getBase().getX();
                        tmpAccWidth = Math.max(tmpAccWidth, accWidth);
                    }
                    newBase.setLocation(newBase.getX() + accidentalsWidth - tmpAccWidth,
                            newBase.getY());
                    if (newBase.getX() == chordBase.getX())
                        newBase = chordBase;
                }
                m_normalizedChord.setBase(newBase);
                if (m_normalizedChord.getWidth() > chordWidth)
                    chordWidth = m_normalizedChord.getWidth();
                //m_normalizedChords[i].onBaseChanged();
            }
		}

		//slur anchors
		if (m_normalizedChords == null) {
			ScoreMetrics metrics = getMetrics();
			slurUnderAnchor = m_sNoteInstances[0].getSlurUnderAnchor();
			slurUnderAnchorOutOfStem = stemUp
				?slurUnderAnchor
				:new Point2D.Double(getBoundingBox().getMinX(),
									getBoundingBox().getMaxY()+metrics.getSlurAnchorYOffset());
			slurAboveAnchor = m_sNoteInstances[m_sNoteInstances.length-1].getSlurAboveAnchor();
			slurAboveAnchorOutOfStem = stemUp
				?new Point2D.Double(getBoundingBox().getMaxX(),
									getBoundingBox().getMinY()-metrics.getSlurAnchorYOffset())
				:slurAboveAnchor;
				
			//calcDecorationPosition();
		}
		
		if (m_jGracenotes != null) {
			Point2D gracesPosition;
			if (!graceNotesAfter)
				gracesPosition = (Point2D) getBase().clone();
			else {
				gracesPosition = new Point2D.Double(
					m_noteHeadX +chordWidth
						+getMetrics().getGraceNotesSpacing()*2,
					getBase().getY()
				);
			}
			m_jGracenotes.setBase(gracesPosition);
		}

		m_width = (int)(graceNotesWidth/*+accidentalsWidth*/+chordWidth);
		//m_width = /*c_width + */graceNotesWidth + accidentalsWidth + chordWidth;
		//m_width = getBoundingBox().getWidth();
	}
594099
function() {
            var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
            var m0 = this.m[3] * d;
            var m1 = -this.m[1] * d;
            var m2 = -this.m[2] * d;
            var m3 = this.m[0] * d;
            var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]);
            var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]);
            this.m[0] = m0;
            this.m[1] = m1;
            this.m[2] = m2;
            this.m[3] = m3;
            this.m[4] = m4;
            this.m[5] = m5;
            return this;
        }
1117384
public int getSemitones() {
		int semitones = 0;
		switch (getLabel() % OCTAVE) {
		case UNISON: semitones = 0; break; //unison
		case SECOND: semitones = 2; break; //major 2nd
		case THIRD: semitones = 4; break; //major 3rd
		case FOURTH: semitones = 5; break; //perfect 4th
		case FIFTH: semitones = 7; break; //perfect 5th
		case SIXTH: semitones = 9; break; //major 6th
		case SEVENTH: semitones = 11; break; //major 7th
		}
		switch (getQuality()) {
		case QUADRUPLE_DIMINISHED:
		case TRIPLE_DIMINISHED:
		case DOUBLE_DIMINISHED:
		case DIMINISHED:
			if (allowPerfectQuality())
				semitones += getQuality() + 1;
			else
				semitones += getQuality();
			break;
		case MINOR: semitones -= 1; break;
		case PERFECT:
		case MAJOR: break; //do not change pitch for major and perfect
		case AUGMENTED:
		case DOUBLE_AUGMENTED:
		case TRIPLE_AUGMENTED:
		case QUADRUPLE_AUGMENTED:
			semitones += getQuality() - 1;
			break;
		}
		semitones += 12 * getOctaveNumber();
		return semitones;
	}