INPUT: array with captions, i.e.
                [{'texlines': [u"So, I'm going to rewrite this", 'in a more concise form as'],
                'time': {'hours':'1', 'min':'2','sec':44,'msec':232} }]
            OUTPUT: srtformated string
199558
def _generateSrt(self,captions):
        
        caption_number = 0
        srt_output = []
        for caption in captions:
            caption_number += 1
            #CAPTION NUMBER
            srt_output.append(str(caption_number))
            #TIME
            time_from = ( caption['time']['hours'], caption['time']['min'], caption['time']['sec'], caption['time']['msec'] ) 
            if len(captions)>caption_number:
                #display caption until next one
                next_caption_time = captions[caption_number]['time']
                time_to = ( next_caption_time['hours'], next_caption_time['min'], next_caption_time['sec'], next_caption_time['msec'] )
            else:
                #display caption for 2 seconds
                time_to = (time_from[0],time_from[1]+2,time_from[2],time_from[3]) 
            srt_output.append( (":").join([str(i) for i in time_from[0:-1]])+","+str(time_from[-1])+" --> "+(":").join([str(i) for i in time_to[0:-1]])+","+str(time_to[-1]))
            #CAPTIONS
            for caption_line in caption['textlines']:
                srt_output.append(caption_line)
            #Add two empty lines to serarate every caption showed
            srt_output.append("")
            srt_output.append("")
        return srt_output
767665
def idf2txt(txt):
    """"""
    astr = nocomment(txt)
    objs = astr.split(';')
    objs = [obj.split(',') for obj in objs]
    objs = [[line.strip() for line in obj] for obj in objs]
    objs = [[_tofloat(line) for line in obj] for obj in objs]
    objs = [tuple(obj) for obj in objs]
    objs.sort()

    lst = []
    for obj in objs:
        for field in obj[:-1]:
            lst.append('%s,' % (field, ))
        lst.append('%s;\n' % (obj[-1], ))

    return '\n'.join(lst)
378013
def format_time(time_string):
    '''
    
    '''
    subseconds = False
    data = time_string.split("_")
    hours, minutes, seconds = int(data[3]), int(data[4]), int(data[5])
    date = datetime.datetime.strptime("_".join(data[:3]), "%Y_%m_%d")
    subsec = 0.0
    if len(data) == 7:
        if float(data[6]) != 0:
            subsec = float(data[6]) / 10**len(data[6])
            subseconds = True
    date_time = date + \
        datetime.timedelta(hours=hours, minutes=minutes,
                           seconds=seconds + subsec)
    return date_time, subseconds
1329854
def tostr(self, object, indent=-2):
        
        history = []
        return self.process(object, history, indent)
24516
function(str, indent) {
			var lines = str.split("\n");
			for (var i=0; i<lines.length; i++)
				lines[i] = indent + lines[i];
			return lines.join("\n");
		}
1024740
function (timeFormat) {
		var tf = timeFormat.replace(/'.*?'/g, '').toLowerCase(), // removes literals
			isIn = function (f, t) { // does the format contain the token?
					return f.indexOf(t) !== -1 ? true : false;
				};
		return {
				hour: isIn(tf, 'h'),
				minute: isIn(tf, 'm'),
				second: isIn(tf, 's'),
				millisec: isIn(tf, 'l'),
				microsec: isIn(tf, 'c'),
				timezone: isIn(tf, 'z'),
				ampm: isIn(tf, 't') && isIn(timeFormat, 'h'),
				iso8601: isIn(timeFormat, 'Z')
			};
	}
653833
def to_ts(s):
        

        # Strip TZ portion if present
        m = Nginx.DATE_FMT.match(s)
        if m:
            s = m.group(1)
            delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else 1)) # Offset from GMT
        else:
            delta = timedelta(seconds=0)
        dt = datetime.strptime(s, "%d/%b/%Y:%H:%M:%S")
        dt += delta
        return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
915144
function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    }
752628
function(captions) {
        var VTT_BODY = ['WEBVTT\n']; //header
        captions.forEach(function(caption) {
            if (caption.text.length > 0 && validateText(caption.text)) {
                VTT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro));
                VTT_BODY.push(module.exports.renderMacros(caption.text) + '\n');
            }
        });
        return VTT_BODY.join('\n');
    }
535159
def tex_escape(text):
    
    conv = {
        '&': r'\&',
        '%': r'\%',
        '$': r'\$',
        '#': r'\#',
        '_': r'\_',
        '{': r'\{',
        '}': r'\}',
        '~': r'\textasciitilde{}',
        '^': r'\^{}',
        '\\': r'\textbackslash{}',
        '<': r'\textless ',
        '>': r'\textgreater ',
    }
    regex = re.compile(
        '|'.join(
            re.escape(six.text_type(key))
            for key in sorted(conv.keys(), key=lambda item: -len(item))
        )
    )
    return regex.sub(lambda match: conv[match.group()], text)
39876
def parse_datetime(text):
    

    text = text.strip().lower()

    INPUT_FORMATS = (
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%d %H:%M',
        '%Y-%m-%d',
        '%m/%d/%Y %H:%M:%S',
        '%m/%d/%Y %H:%M',
        '%m/%d/%Y',
        '%m/%d/%y %H:%M:%S',
        '%m/%d/%y %H:%M',
        '%m/%d/%y',
    )
    for format in INPUT_FORMATS:
        try:
            return datetime.datetime(*time.strptime(text, format)[:6])
        except ValueError:
            pass

    # Try descriptive texts
    if text == 'tomorrow':
        future = datetime.datetime.now() + datetime.timedelta(days=1)
        args = future.timetuple()[:3] + (23, 59, 59)
        return datetime.datetime(*args)
    elif text == 'today':
        return datetime.datetime(*datetime.datetime.today().timetuple()[:3])
    elif text == 'now':
        return datetime.datetime.now()
    elif text == 'yesterday':
        past = datetime.datetime.now() - datetime.timedelta(days=1)
        return datetime.datetime(*past.timetuple()[:3])
    else:
        days = 0
        matched = re.match(
            r'^((?P<weeks>\d+) ?w(eeks?)?)? ?((?P<days>\d+) ?d(ays?)?)?$', text)
        if matched:
            groupdict = matched.groupdict()
            if groupdict['days']:
                days += int(matched.groupdict()['days'])
            if groupdict['weeks']:
                days += int(matched.groupdict()['weeks']) * 7
            past = datetime.datetime.now() - datetime.timedelta(days=days)
            return datetime.datetime(*past.timetuple()[:3])

    raise ValueError('Wrong date: "%s"' % text)
299753
public static String format(Instance inst, String[] labels, String[] gold) {

		StringBuilder sb = new StringBuilder();
		String[][] data = (String[][]) inst.getSource();
		int feaNum = data.length;
		int seqNum = data[0].length;
		for (int i = 0; i < seqNum; i++) {
			for (int j = 0; j < feaNum; j++) {
				sb.append(data[j][i]);
				sb.append("\t");
			}
			sb.append(labels[i]);
			sb.append("\t");
			sb.append(gold[i]);
			sb.append("\n");
		}
		return sb.toString();
	}
654545
function(lines, param) {
              var csvLines = [];
              var left = "";
              while (lines.length) {
                var line = left + lines.shift();
                var row = rowSplit(line, param);
                if (row.closed) {
                  csvLines.push(row.cols);
                  left = "";
                } else {
                  left = line + (getEol(line, param) || "\n"); // if unable to getEol from data, assume "\n"
                }
              }
              return {lines: csvLines, partial: left};
            }
1152456
def format(self):
        

        values = {}
        title = "Description"
        description = self.command.description + "\n\n" + self.get_ending_note() if not self.is_cog() else inspect.getdoc(self.command)
        sections = []

        if isinstance(self.command, Command):
                description = self.command.short_doc
                sections = [{"name": "Usage", "value": self.get_command_signature()},
                            {"name": "More Info", "value": self.command.help.replace(self.command.short_doc, "").format(prefix=self.clean_prefix),
                             "inline": False}]

        def category(tup):
            cog = tup[1].cog_name
            return cog + ':' if cog is not None else '\u200bNo Category:'

        if self.is_bot():
            title = self.bot.user.display_name + " Help"
            data = sorted(self.filter_command_list(), key=category)
            for category, commands in itertools.groupby(data, key=category):
                section = {}
                commands = list(commands)
                if len(commands) > 0:
                    section['name'] = category
                section['value'] = self.add_commands(commands)
                section['inline'] = False
                sections.append(section)
        elif not sections or self.has_subcommands():
            section = {"name": "Commands:", "inline": False, "value": self.add_commands(self.filter_command_list())}
            sections.append(section)

        values['title'] = title
        values['description'] = description
        values['sections'] = sections
        return values
132055
def array_indented(level, l, quote_char='\'', comma_after=False):
    # type: (int, List[str], str, bool) -> str
    
    out = "[\n"
    for x in l:
        out += (((level+1) * 4) * " ") + '{}{}{}'.format(quote_char, x, quote_char) + ",\n"
    out += ((level * 4) * " ") + "]"
    if comma_after:
        out += ","
    return out
969099
function parse(string) {
    var result = {},
        lines = string.split(/\r\n|\r|\n/),
        count = lines.length,
        pieces,
        key,
        value,
        meta,
        namespace;

    for (var i = 0; i < count; i++) {
        if (lines[i] === '') {
            continue;
        }
        if (lines[i].toUpperCase() === PREFIX || lines[i].toUpperCase() === POSTFIX) {
            continue;
        }
        var data = lines[i];

        /**
         * Check that next line continues current
         * @param {number} i
         * @returns {boolean}
         */
        var isValueContinued = function (i) {
            return i + 1 < count && (lines[i + 1][0] === ' ' || lines[i + 1][0] === '\t');
        };
        // handle multiline properties (i.e. photo).
        // next line should start with space or tab character
        if (isValueContinued(i)) {
            while (isValueContinued(i)) {
                data += lines[i + 1].trim();
                i++;
            }
        }

        pieces = data.split(':');
        key = pieces.shift();
        value = pieces.join(':');
        namespace = false;
        meta = {};

        // meta fields in property
        if (key.match(/;/)) {
            key = key
                .replace(/\\;/g, 'ΩΩΩ')
                .replace(/\\,/, ',');
            var metaArr = key.split(';').map(function (item) {
                return item.replace(/ΩΩΩ/g, ';');
            });
            key = metaArr.shift();
            metaArr.forEach(function (item) {
                var arr = item.split('=');
                arr[0] = arr[0].toLowerCase();
                if (arr[0].length === 0) {
                    return;
                }
                if (meta[arr[0]]) {
                    meta[arr[0]].push(arr[1]);
                } else {
                    meta[arr[0]] = [arr[1]];
                }
            });
        }

        // values with \n
        value = value
            .replace(/\\n/g, '\n');

        value = tryToSplit(value);

        // Grouped properties
        if (key.match(/\./)) {
            var arr = key.split('.');
            key = arr[1];
            namespace = arr[0];
        }

        var newValue = {
            value: value
        };
        if (Object.keys(meta).length) {
            newValue.meta = meta;
        }
        if (namespace) {
            newValue.namespace = namespace;
        }

        if (key.indexOf('X-') !== 0) {
            key = key.toLowerCase();
        }

        if (typeof result[key] === 'undefined') {
            result[key] = [newValue];
        } else {
            result[key].push(newValue);
        }

    }

    return result;
}
551659
def titles2marc(self, key, values):
    
    first, rest = values[0], values[1:]

    self.setdefault('245', []).append({
        'a': first.get('title'),
        'b': first.get('subtitle'),
        '9': first.get('source'),
    })

    return [
        {
            'a': value.get('title'),
            'b': value.get('subtitle'),
            '9': value.get('source'),
        } for value in rest
    ]