Compose a yo-ho-ho type chant with flexible options.
555916
def do_yo(self, args):
        """"""
        chant = ['yo'] + ['ho'] * args.ho
        separator = ', ' if args.commas else ' '
        chant = separator.join(chant)
        self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage))
1096061
def dialog_turns_to_string(dialog):
    
    # join utterances
    turns_as_strings = map(singe_user_utterances_to_string, dialog)
    # join turns
    return "".join(map(lambda x: x + " " + end_of_turn_symbol + " ", turns_as_strings))
860882
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)
293168
function (line) {
    members = line.split(',');

    var soundType  = members[4];
    var objectType = members[3];

    var hitObject = {
      startTime:  parseInt(members[2]),
      newCombo:   ((objectType & 4) == 4),
      soundTypes: [],
      position: [
        parseInt(members[0]),
        parseInt(members[1])
      ]
    };

    /**
     * sound type is a bitwise flag enum
     * 0 : normal
     * 2 : whistle
     * 4 : finish
     * 8 : clap
     */
    if ((soundType & 2) == 2)              { hitObject.soundTypes.push('whistle'); }
    if ((soundType & 4) == 4)              { hitObject.soundTypes.push('finish');  }
    if ((soundType & 8) == 8)              { hitObject.soundTypes.push('clap');    }
    if (hitObject.soundTypes.length === 0) { hitObject.soundTypes.push('normal'); }

    /**
     * object type is a bitwise flag enum
     * 1: circle
     * 2: slider
     * 8: spinner
     */
    if ((objectType & 1) == 1) {
      // Circle
      beatmap.nbCircles++;
      hitObject.objectName = 'circle';
      hitObject.additions  = parseAdditions(members[5]);
    } else if ((objectType & 8) == 8) {
      // Spinner
      beatmap.nbSpinners++;
      hitObject.objectName = 'spinner';
      hitObject.endTime    = parseInt(members[5]);
      hitObject.additions  = parseAdditions(members[6]);
    } else if ((objectType & 2) == 2) {
      // Slider
      beatmap.nbSliders++;
      hitObject.objectName  = 'slider';
      hitObject.repeatCount = parseInt(members[6]);
      hitObject.pixelLength = parseInt(members[7]);
      hitObject.additions   = parseAdditions(members[10]);
      hitObject.edges       = [];
      hitObject.points      = [
        [hitObject.position[0], hitObject.position[1]]
      ];

      /**
       * Calculate slider duration
       */
      var timing = getTimingPoint(hitObject.startTime);

      if (timing) {
        var pxPerBeat      = beatmap.SliderMultiplier * 100 * timing.velocity;
        var beatsNumber    = (hitObject.pixelLength * hitObject.repeatCount) / pxPerBeat;
        hitObject.duration = Math.ceil(beatsNumber * timing.beatLength);
        hitObject.endTime  = hitObject.startTime + hitObject.duration;
      }
      /**
       * Parse slider points
       */
      var points = (members[5] || '').split('|');
      if (points.length) {
        hitObject.curveType = curveTypes[points[0]] || 'unknown';

        for (var i = 1, l = points.length; i < l; i++) {
          var coordinates = points[i].split(':');
          hitObject.points.push([
            parseInt(coordinates[0]),
            parseInt(coordinates[1])
          ]);
        }
      }

      var edgeSounds    = [];
      var edgeAdditions = [];
      if (members[8]) { edgeSounds    = members[8].split('|'); }
      if (members[9]) { edgeAdditions = members[9].split('|'); }

      /**
       * Get soundTypes and additions for each slider edge
       */
      for (var j = 0, lgt = hitObject.repeatCount + 1; j < lgt; j++) {
        var edge = {
          soundTypes: [],
          additions: parseAdditions(edgeAdditions[j])
        };

        if (edgeSounds[j]) {
          var sound = edgeSounds[j];
          if ((sound & 2) == 2)             { edge.soundTypes.push('whistle'); }
          if ((sound & 4) == 4)             { edge.soundTypes.push('finish');  }
          if ((sound & 8) == 8)             { edge.soundTypes.push('clap');    }
          if (edge.soundTypes.length === 0) { edge.soundTypes.push('normal');  }
        } else {
          edge.soundTypes.push('normal');
        }

        hitObject.edges.push(edge);
      }

      // get coordinates of the slider endpoint
      var endPoint = slidercalc.getEndPoint(hitObject.curveType, hitObject.pixelLength, hitObject.points);
      if (endPoint && endPoint[0] && endPoint[1]) {
        hitObject.endPosition = [
          Math.round(endPoint[0]),
          Math.round(endPoint[1])
        ];
      } else {
        // If endPosition could not be calculated, approximate it by setting it to the last point
        hitObject.endPosition = hitObject.points[hitObject.points.length - 1];
      }
    } else {
      // Unknown
      hitObject.objectName = 'unknown';
    }

    beatmap.hitObjects.push(hitObject);
  }
785560
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False):
    ''''''

    files = {}

    working_segments = []

    audio = AudioSegment.empty()

    if layer:
        total_time = max([s['end'] - s['start'] for s in segments]) * 1000
        audio = AudioSegment.silent(duration=total_time)

    for i, s in enumerate(segments):
        try:
            start = s['start'] * 1000
            end = s['end'] * 1000
            f = s['file'].replace('.transcription.txt', '')
            if f not in files:
                if f.endswith('.wav'):
                    files[f] = AudioSegment.from_wav(f)
                elif f.endswith('.mp3'):
                    files[f] = AudioSegment.from_mp3(f)

            segment = files[f][start:end]

            print(start, end, f)

            if layer:
                audio = audio.overlay(segment, times=1)
            else:
                if i > 0:
                    audio = audio.append(segment, crossfade=crossfade)
                else:
                    audio = audio + segment

            if padding > 0:
                audio = audio + AudioSegment.silent(duration=padding)

            s['duration'] = len(segment)
            working_segments.append(s)
        except:
            continue

    audio.export(out, format=os.path.splitext(out)[1].replace('.', ''))
    return working_segments
1024628
def sing(self, number):
        """"""

        if type(number) != Decimal:
            number = Decimal(str(number))

        if number > self.limite:
            msg = "El maximo numero procesable es {} ({})".format(self.limite,
                                                                  self.sing(self.limite))
            raise ValueError(msg)
        else:
            texto = self.__to_text(int(number))
        texto += self.__calcular_decimales(number)

        return texto
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);
}
429868
function(pinyinWithoutTone)
        {
            var newToneMap = {};
            for(var i in toneMap) newToneMap[toneMap[i]] = i;
            return (pinyinWithoutTone || '').replace(/[a-z]\d/g, function(m) {
                return newToneMap[m] || m;
            });
        }
655653
function Haiku(options){
  var haiku = this

  options = options || {}

  // allow a single string opt to be the src
  //
  //    haiku('path/to/mysite.com')
  //
  if (typeof options === 'string') options = { src: options }

  prr(haiku, 'options', { src: options.src || process.cwd()
  , markdown: marked
  })
  prr(haiku, 'state', 'new', { writable: true })
  prr(haiku, 'entities', {})
  prr(haiku, 'transforms', [])

  // inherits from a basic EventEmitter below, make sure it's ctor gets called.
  EE.call(haiku)
  haiku.setMaxListeners(Infinity)

  haiku.on('reading', function(){ haiku.state = 'reading' })
  haiku.on('read',    function(){ haiku.state = 'read'    })

  // defaults
  // needs `haiku.options.src` defined ahead of calling `haiku.resolve()`
  allowedopts.forEach(function(opt){
    // only resolve -dir suffixed options
    if (! opt.match('-dir')) return

    var dirname = opt.replace('-dir', '')
    haiku.options[opt] = haiku.resolve(dirname)
  })

  haiku.configure(options)

  // has to be defined after opts are configured
  prr(haiku, 'templates', templates(haiku.opt('templates-dir')), { writable: true })
}
1025408
def _ipa_syllable_to_numbered(s):
    """"""
    ipa_syllable, tone = _parse_ipa_syllable(s)
    try:
        pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin']
    except KeyError:
        raise ValueError('Not a valid syllable: %s' % s)
    return pinyin_syllable + tone
237558
protected void adaptToTune(Tune tune, ScoreMetrics metrics) {
		//reinit the values of the engraving mode
		setMode(m_mode, m_variation);
		
		if (m_mode != NONE) {
			//11=notes spacing at 45px (default font size)
			double ratio = 100 * (11 / metrics.getNotesSpacing()) - 100;
			int oldVariation = m_variation;
			setMode(m_mode, m_variation - (int)ratio);
			m_variation = oldVariation;
			
			Music music = tune.getMusic();
			Note shortestNote = music.getShortestNoteInAllVoices();
			int shortestDuration = Note.SIXTEENTH;
			if (shortestNote != null)
				shortestDuration = shortestNote.getDuration();
			//System.out.println("shortest note duration = "+shortest.getDuration());
			short min = /*(shortestDuration >= Note.QUARTER)
				? Note.SIXTEENTH
				: */Note.SIXTEENTH;
			if (shortestDuration > min) {
				TreeSet set = new TreeSet(spacesAfter.keySet());
				Object[] durations = set.toArray();
				int iMin = 0, iShortest = 0;
				for (int i = 0; i < durations.length; i++) {
					//System.out.println("durations["+i+"] = "+durations[i]);
					int j = (Integer) durations[i];
					if (j == min)
						iMin = i;
					if (j == shortestDuration)
						iShortest = i;
				}
				int offset = (iShortest>iMin)?iShortest - iMin:0;
				if (offset != 0) {
					for (int i = durations.length-1; i >= iShortest; i--) {
						//DEBUG
						/*String s = "";
						for (Iterator itSet = set.iterator(); itSet.hasNext();) {
							Integer i2 = (Integer) itSet.next();
							System.out.print(i2+"\t");
							s += getSpaceAfter(i2.intValue())+"\t";
						}
						System.out.println("\n"+s);*/
						setSpaceAfter((Integer) durations[i],
							getSpaceAfter((Integer) durations[i - offset])
							);
					}
				}
				//System.out.println(spaceAfter.keySet().toArray());
				//System.out.println(spaceAfter.entrySet().toArray());
			}
		}
	}
74883
function compose(patterns, options, matcher) {
  let matchers;

  return memoize('compose', String(patterns), options, function() {
    return function(file) {
      // delay composition until it's invoked the first time,
      // after that it won't be called again
      if (!matchers) {
        matchers = [];
        for (var i = 0; i < patterns.length; i++) {
          matchers.push(matcher(patterns[i], options));
        }
      }

      let len = matchers.length;
      while (len--) {
        if (matchers[len](file) === true) {
          return true;
        }
      }
      return false;
    };
  });
}
627516
def _sounds_re(include_erhua=False):
    """"""

    tone = '[1-5]'
    optional_final_erhua = '|r\\b' if include_erhua else ''
    pattern = '({}{}{})'.format(_joined_syllables_re(), tone, optional_final_erhua)
    return re.compile(pattern, re.IGNORECASE)
565376
function ControlComposer(opts) {
  opts = opts || {};

  this._methods = [];

  this._parameters = [ 'x' ,'y', 'axisScaledX', 'axisScaledY', 'zoom', 'yaw', 'pitch', 'roll' ];

  this._now = opts.nowForTesting || now;

  this._composedOffsets = { };

  this._composeReturn = { offsets: this._composedOffsets, changing: null };
}
796898
def run():
    """"""
    import optparse

    parser = optparse.OptionParser(usage=r"%prog [<options>] [file ...]")
    parser.add_option(
        "-p", "--spread", type="float", default=3.0, help="Rainbow spread"
    )
    parser.add_option(
        "-F", "--freq", type="float", default=0.1, help="Rainbow frequency"
    )
    parser.add_option("-S", "--seed", type="int", default=0, help="Rainbow seed")
    parser.add_option(
        "-a",
        "--animate",
        action="store_true",
        default=False,
        help="Enable psychedelics",
    )
    parser.add_option(
        "-d", "--duration", type="int", default=12, help="Animation duration"
    )
    parser.add_option(
        "-s", "--speed", type="float", default=20.0, help="Animation speed"
    )
    parser.add_option(
        "-f",
        "--force",
        action="store_true",
        default=False,
        help="Force colour even when stdout is not a tty",
    )

    parser.add_option(
        "-3", action="store_const", dest="mode", const=8, help="Force 3 bit colour mode"
    )
    parser.add_option(
        "-4",
        action="store_const",
        dest="mode",
        const=16,
        help="Force 4 bit colour mode",
    )
    parser.add_option(
        "-8",
        action="store_const",
        dest="mode",
        const=256,
        help="Force 8 bit colour mode",
    )

    parser.add_option(
        "-c",
        "--charset-py2",
        default="utf-8",
        help="Manually set a charset to convert from, for python 2.7",
    )

    options, args = parser.parse_args()
    options.os = random.randint(0, 256) if options.seed == 0 else options.seed
    options.mode = options.mode or detect_mode()

    lolcat = LolCat(mode=options.mode)

    if not args:
        args = ["-"]

    for filename in args:
        if filename == "-":
            lolcat.cat(sys.stdin, options)
        else:
            try:
                with open(filename, "r") as handle:
                    lolcat.cat(handle, options)
            except IOError as error:
                sys.stderr.write(str(error) + "\n")
1342160
private void startMusic(float pitch, float volume, boolean loop) {
		if (currentMusic != null) {
			currentMusic.stop();
			currentMusic.fireMusicSwapped(this);
		}
		
		currentMusic = this;
		if (volume < 0.0f)
			volume = 0.0f;
		if (volume > 1.0f)
			volume = 1.0f;

		sound.playAsMusic(pitch, volume, loop);
		playing = true;
		setVolume(volume);
		if (requiredPosition != -1) {
			setPosition(requiredPosition);
		}
	}
944942
def pinyin_syllable_to_ipa(s):
    """"""
    pinyin_syllable, tone = _parse_pinyin_syllable(s)
    try:
        ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA']
    except KeyError:
        raise ValueError('Not a valid syllable: %s' % s)
    return ipa_syllable + _IPA_TONES[tone]