text:
package org.apache.lucene.codecs.lucene50;

import java.io.IOException;

import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.codecs.DocValuesFormat;
import org.apache.lucene.codecs.DocValuesProducer;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.SmallFloat;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.packed.DirectWriter;
import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;

/**
 * Lucene 5.0 DocValues format.
 *

 * Encodes the five per-document value types (Numeric,Binary,Sorted,SortedSet,SortedNumeric) with these strategies:
 *

 * {@link DocValuesType#NUMERIC NUMERIC}:
 *

 *
Delta-compressed: per-document integers written as deltas from the minimum value,
 *        compressed with bitpacking. For more information, see {@link DirectWriter}.
 *
Table-compressed: when the number of unique values is very small (< 256), and
 *        when there are unused "gaps" in the range of values used (such as {@link SmallFloat}),
 *        a lookup table is written instead. Each per-document entry is instead the ordinal
 *        to this table, and those ordinals are compressed with bitpacking ({@link DirectWriter}).
 *
GCD-compressed: when all numbers share a common divisor, such as dates, the greatest
 *        common denominator (GCD) is computed, and quotients are stored using Delta-compressed Numerics.
 *
Monotonic-compressed: when all numbers are monotonically increasing offsets, they are written
 *        as blocks of bitpacked integers, encoding the deviation from the expected delta.
 *
Const-compressed: when there is only one possible non-missing value, only the missing
 *        bitset is encoded.
 *

 *

 * {@link DocValuesType#BINARY BINARY}:
 *

 *
Fixed-width Binary: one large concatenated byte[] is written, along with the fixed length.
 *        Each document's value can be addressed directly with multiplication ({@code docID * length}).
 *
Variable-width Binary: one large concatenated byte[] is written, along with end addresses
 *        for each document. The addresses are written as Monotonic-compressed numerics.
 *
Prefix-compressed Binary: values are written in chunks of 16, with the first value written
 *        completely and other values sharing prefixes. chunk addresses are written as Monotonic-compressed
 *        numerics. A reverse lookup index is written from a portion of every 1024th term.
 *

 *

 * {@link DocValuesType#SORTED SORTED}:
 *

 *
Sorted: a mapping of ordinals to deduplicated terms is written as Binary,
 *        along with the per-document ordinals written using one of the numeric strategies above.
 *

 *

 * {@link DocValuesType#SORTED_SET SORTED_SET}:
 *

 *
Single: if all documents have 0 or 1 value, then data are written like SORTED.
 *
SortedSet table: when there are few unique sets of values (< 256) then each set is assigned
 *        an id, a lookup table is written and the mapping from document to set id is written using the
 *        numeric strategies above.
 *
SortedSet: a mapping of ordinals to deduplicated terms is written as Binary,
 *        an ordinal list and per-document index into this list are written using the numeric strategies
 *        above.
 *

 *

 * {@link DocValuesType#SORTED_NUMERIC SORTED_NUMERIC}:
 *

 *
Single: if all documents have 0 or 1 value, then data are written like NUMERIC.
 *
SortedSet table: when there are few unique sets of values (< 256) then each set is assigned
 *        an id, a lookup table is written and the mapping from document to set id is written using the
 *        numeric strategies above.
 *
SortedNumeric: a value list and per-document index into this list are written using the numeric
 *        strategies above.
 *

 *

 * Files:
 *

 *
<tt>.dvd</tt>: DocValues data

 *
<tt>.dvm</tt>: DocValues metadata

 *

 *

 *

 *
The DocValues metadata or .dvm file.

 *
For DocValues field, this stores metadata, such as the offset into the
 *      DocValues data (.dvd)

 *
DocValues metadata (.dvm) --> Header,<Entry>NumFields,Footer

 *

 *
Entry --> NumericEntry | BinaryEntry | SortedEntry | SortedSetEntry | SortedNumericEntry

 *
NumericEntry --> GCDNumericEntry | TableNumericEntry | DeltaNumericEntry

 *
GCDNumericEntry --> NumericHeader,MinValue,GCD,BitsPerValue

 *
TableNumericEntry --> NumericHeader,TableSize,{@link DataOutput#writeLong Int64}TableSize,BitsPerValue

 *
DeltaNumericEntry --> NumericHeader,MinValue,BitsPerValue

 *
MonotonicNumericEntry --> NumericHeader,PackedVersion,BlockSize

 *
NumericHeader --> FieldNumber,EntryType,NumericType,MissingOffset,DataOffset,Count,EndOffset

 *
BinaryEntry --> FixedBinaryEntry | VariableBinaryEntry | PrefixBinaryEntry

 *
FixedBinaryEntry --> BinaryHeader

 *
VariableBinaryEntry --> BinaryHeader,AddressOffset,PackedVersion,BlockSize

 *
PrefixBinaryEntry --> BinaryHeader,AddressInterval,AddressOffset,PackedVersion,BlockSize

 *
BinaryHeader --> FieldNumber,EntryType,BinaryType,MissingOffset,MinLength,MaxLength,DataOffset

 *
SortedEntry --> FieldNumber,EntryType,BinaryEntry,NumericEntry

 *
SortedSetEntry --> SingleSortedSetEntry | AddressesSortedSetEntry | TableSortedSetEntry

 *
SingleSortedSetEntry --> SetHeader,SortedEntry

 *
AddressesSortedSetEntry --> SetHeader,BinaryEntry,NumericEntry,NumericEntry

 *
TableSortedSetEntry --> SetHeader,TotalTableLength,{@link DataOutput#writeLong Int64}TotalTableLength,TableSize,{@link DataOutput#writeInt Int32}TableSize,BinaryEntry,NumericEntry

 *
SetHeader --> FieldNumber,EntryType,SetType

 *
SortedNumericEntry --> SingleSortedNumericEntry | AddressesSortedNumericEntry | TableSortedNumericEntry

 *
SingleNumericEntry --> SetHeader,NumericEntry

 *
AddressesSortedNumericEntry --> SetHeader,NumericEntry,NumericEntry

 *
TableSortedNumericEntry --> SetHeader,TotalTableLength,{@link DataOutput#writeLong Int64}TotalTableLength,TableSize,{@link DataOutput#writeInt Int32}TableSize,NumericEntry

 *
FieldNumber,PackedVersion,MinLength,MaxLength,BlockSize,ValueCount --> {@link DataOutput#writeVInt VInt}

 *
EntryType,CompressionType --> {@link DataOutput#writeByte Byte}

 *
Header --> {@link CodecUtil#writeIndexHeader IndexHeader}

 *
MinValue,GCD,MissingOffset,AddressOffset,DataOffset,EndOffset --> {@link DataOutput#writeLong Int64}

 *
TableSize,BitsPerValue,TotalTableLength --> {@link DataOutput#writeVInt vInt}

 *
Footer --> {@link CodecUtil#writeFooter CodecFooter}

 *

 *
Sorted fields have two entries: a BinaryEntry with the value metadata,
 *      and an ordinary NumericEntry for the document-to-ord metadata.

 *
FieldNumber of -1 indicates the end of metadata.

 *
EntryType is a 0 (NumericEntry) or 1 (BinaryEntry)

 *
DataOffset is the pointer to the start of the data in the DocValues data (.dvd)

 *
EndOffset is the pointer to the end of the data in the DocValues data (.dvd)

 *
NumericType indicates how Numeric values will be compressed:
 *

 *
0 --> delta-compressed. For each block of 16k integers, every integer is delta-encoded
 *             from the minimum value within the block.
 *
1 --> gcd-compressed. When all integers share a common divisor, only quotients are stored
 *             using blocks of delta-encoded ints.
 *
2 --> table-compressed. When the number of unique numeric values is small and it would save space,
 *             a lookup table of unique values is written, followed by the ordinal for each document.
 *
3 --> monotonic-compressed. Used to implement addressing for BINARY, SORTED_SET, SORTED_NUMERIC.
 *
4 --> const-compressed. Used when all non-missing values are the same.
 *

 *
BinaryType indicates how Binary values will be stored:
 *

 *
0 --> fixed-width. All values have the same length, addressing by multiplication.
 *
1 --> variable-width. An address for each value is stored.
 *
2 --> prefix-compressed. An address to the start of every interval'th value is stored.
 *

 *
SetType indicates how SortedSet and SortedNumeric values will be stored:
 *

 *
0 --> with addresses. There are two numeric entries: a first one from document to start
 *             offset, and a second one from offset to ord/value.
 *
1 --> single-valued. Used when all documents have at most one value and is encoded like
 *             a regular Sorted/Numeric entry.
 *
2 --> table-encoded. A lookup table of unique sets of values is written, followed by a
 *             numeric entry that maps each document to an ordinal in this table.
 *

 *
MinLength and MaxLength represent the min and max byte[] value lengths for Binary values.
 *      If they are equal, then all values are of a fixed size, and can be addressed as DataOffset + (docID * length).
 *      Otherwise, the binary values are of variable size, and packed integer metadata (PackedVersion,BlockSize)
 *      is written for the addresses.
 *
MissingOffset points to a byte[] containing a bitset of all documents that had a value for the field.
 *      If it's -1, then there are no missing values. If it's -2, all values are missing.
 *

 *
The DocValues data or .dvd file.

 *
For DocValues field, this stores the actual per-document data (the heavy-lifting)

 *
DocValues data (.dvd) --> Header,<NumericData | BinaryData | SortedData>NumFields,Footer

 *

 *
NumericData --> DeltaCompressedNumerics | TableCompressedNumerics | GCDCompressedNumerics

 *
BinaryData -->  {@link DataOutput#writeByte Byte}DataLength,Addresses

 *
SortedData --> {@link FST FST<Int64>}

 *
DeltaCompressedNumerics,TableCompressedNumerics,GCDCompressedNumerics --> {@link DirectWriter PackedInts}

 *
Addresses --> {@link MonotonicBlockPackedWriter MonotonicBlockPackedInts(blockSize=16k)}

 *
Footer --> {@link CodecUtil#writeFooter CodecFooter}

 *

 *

 * @lucene.experimental
 */
public final class Lucene50DocValuesFormat extends DocValuesFormat {

  /** Sole Constructor */
  public Lucene50DocValuesFormat() {
    super("Lucene50");
  }

  @Override
  public DocValuesConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
    return new Lucene50DocValuesConsumer(state, DATA_CODEC, DATA_EXTENSION, META_CODEC, META_EXTENSION);
  }

  @Override
  public DocValuesProducer fieldsProducer(SegmentReadState state) throws IOException {
    return new Lucene50DocValuesProducer(state, DATA_CODEC, DATA_EXTENSION, META_CODEC, META_EXTENSION);
  }

  static final String DATA_CODEC = "Lucene50DocValuesData";
  static final String DATA_EXTENSION = "dvd";
  static final String META_CODEC = "Lucene50DocValuesMetadata";
  static final String META_EXTENSION = "dvm";
  static final int VERSION_START = 0;
  static final int VERSION_SORTEDSET_TABLE = 1;
  static final int VERSION_CURRENT = VERSION_SORTEDSET_TABLE;

  // indicates docvalues type
  static final byte NUMERIC = 0;
  static final byte BINARY = 1;
  static final byte SORTED = 2;
  static final byte SORTED_SET = 3;
  static final byte SORTED_NUMERIC = 4;

  // address terms in blocks of 16 terms
  static final int INTERVAL_SHIFT = 4;
  static final int INTERVAL_COUNT = 1 << INTERVAL_SHIFT;
  static final int INTERVAL_MASK = INTERVAL_COUNT - 1;

  // build reverse index from every 1024th term
  static final int REVERSE_INTERVAL_SHIFT = 10;
  static final int REVERSE_INTERVAL_COUNT = 1 << REVERSE_INTERVAL_SHIFT;
  static final int REVERSE_INTERVAL_MASK = REVERSE_INTERVAL_COUNT - 1;

  // for conversion from reverse index to block
  static final int BLOCK_INTERVAL_SHIFT = REVERSE_INTERVAL_SHIFT - INTERVAL_SHIFT;
  static final int BLOCK_INTERVAL_COUNT = 1 << BLOCK_INTERVAL_SHIFT;
  static final int BLOCK_INTERVAL_MASK = BLOCK_INTERVAL_COUNT - 1;

  /** Compressed using packed blocks of ints. */
  static final int DELTA_COMPRESSED = 0;
  /** Compressed by computing the GCD. */
  static final int GCD_COMPRESSED = 1;
  /** Compressed by giving IDs to unique values. */
  static final int TABLE_COMPRESSED = 2;
  /** Compressed with monotonically increasing values */
  static final int MONOTONIC_COMPRESSED = 3;
  /** Compressed with constant value (uses only missing bitset) */
  static final int CONST_COMPRESSED = 4;

  /** Uncompressed binary, written directly (fixed length). */
  static final int BINARY_FIXED_UNCOMPRESSED = 0;
  /** Uncompressed binary, written directly (variable length). */
  static final int BINARY_VARIABLE_UNCOMPRESSED = 1;
  /** Compressed binary with shared prefixes */
  static final int BINARY_PREFIX_COMPRESSED = 2;

  /** Standard storage for sorted set values with 1 level of indirection:
   *  {@code docId -> address -> ord}. */
  static final int SORTED_WITH_ADDRESSES = 0;
  /** Single-valued sorted set values, encoded as sorted values, so no level
   *  of indirection: {@code docId -> ord}. */
  static final int SORTED_SINGLE_VALUED = 1;
  /** Compressed giving IDs to unique sets of values:
   * {@code docId -> setId -> ords} */
  static final int SORTED_SET_TABLE = 2;

  /** placeholder for missing offset that means there are no missing values */
  static final int ALL_LIVE = -1;
  /** placeholder for missing offset that means all values are missing */
  static final int ALL_MISSING = -2;

  // addressing uses 16k blocks
  static final int MONOTONIC_BLOCK_SIZE = 16384;
}


text:
package fake

import (
	"context"

	"github.com/jenkins-x/go-scm/scm"
)

type reviewService struct {
	client *wrapper
	data   *Data
}

func (s *reviewService) Find(ctx context.Context, repo string, number, reviewID int) (*scm.Review, *scm.Response, error) {
	reviews, r, err := s.List(ctx, repo, number, &scm.ListOptions{})
	if err != nil {
		return nil, r, err
	}
	for _, review := range reviews {
		if review.ID == reviewID {
			return review, nil, nil
		}
	}
	return nil, r, err
}

func (s *reviewService) List(ctx context.Context, repo string, number int, opt *scm.ListOptions) ([]*scm.Review, *scm.Response, error) {
	f := s.data
	return append([]*scm.Review{}, f.Reviews[number]...), nil, nil
}

func (s *reviewService) Create(ctx context.Context, repo string, number int, input *scm.ReviewInput) (*scm.Review, *scm.Response, error) {
	f := s.data
	review := &scm.Review{
		ID:     f.ReviewID,
		Author: scm.User{Login: botName},
		Body:   input.Body,
	}
	f.Reviews[number] = append(f.Reviews[number], review)
	f.ReviewID++
	return review, nil, nil
}

func (s *reviewService) Delete(context.Context, string, int, int) (*scm.Response, error) {
	panic("implement me")
}

func (s *reviewService) ListComments(ctx context.Context, repo string, prID, reviewID int, options *scm.ListOptions) ([]*scm.ReviewComment, *scm.Response, error) {
	return nil, nil, scm.ErrNotSupported
}

func (s *reviewService) Update(ctx context.Context, repo string, prID, reviewID int, body string) (*scm.Review, *scm.Response, error) {
	return nil, nil, scm.ErrNotSupported
}

func (s *reviewService) Submit(ctx context.Context, repo string, prID, reviewID int, input *scm.ReviewSubmitInput) (*scm.Review, *scm.Response, error) {
	return nil, nil, scm.ErrNotSupported
}

func (s *reviewService) Dismiss(ctx context.Context, repo string, prID, reviewID int, msg string) (*scm.Review, *scm.Response, error) {
	return nil, nil, scm.ErrNotSupported
}

redpajama_set_name: RedPajamaGithub


text:
@interface ttRecommendCategoryCell ()
@property (weak, nonatomic) IBOutlet UIView *indicatorView;

@end

@implementation ttRecommendCategoryCell

#pragma mark - 从xib加载时会调用的方法
- (void)awakeFromNib {
    self.backgroundColor = ttRGBColor(244, 244, 244);
    self.indicatorView.backgroundColor = [UIColor redColor];

}

#pragma mark - 重写category的set方法
-(void)setCategory:(ttRecommendCategory *)category{
    _category = category;

    //设置类名
    self.textLabel.text = category.name;
}

#pragma mark - 重新布局
-(void)layoutSubviews{
    [super layoutSubviews];

    //分割线的高度为1, 为了textLabel不遮住分割线, 调整内部的textLabel的frame
    self.textLabel.y = 2;
    self.textLabel.height = self.contentView.height - 2 * self.textLabel.y;
}

#pragma mark - 选中cell调用的方法
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    //如果没选中就隐藏indicatorView
    self.indicatorView.hidden = !selected;
    self.textLabel.textColor = selected ? self.indicatorView.backgroundColor : ttRGBColor(78, 78, 78);
}

@end


text:
import logging
import os
import string
import sys
from base64 import b64encode
from datetime import datetime
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from socket import gethostname
from tempfile import mkstemp
from zipfile import ZIP_DEFLATED, ZipFile

from azure.storage.blob import BlockBlobService
from azure.storage.blob.models import ContentSettings
from azure.storage.queue import QueueService
from azure.storage.table import TableBatch, TableService

_PY3 = sys.version_info[0] == 3

def _formatName(name, params):
    if _PY3:
        # try all possible formattings
        name = string.Template(name).substitute(**params)
        name = name.format(**params)
    return name % params

class _BlobStorageFileHandler(object):

    def __init__(self,
                  account_name=None,
                  account_key=None,
                  protocol='https',
                  container='logs',
                  zip_compression=False,
                  max_connections=1,
                  max_retries=5,
                  retry_wait=1.0,
                  is_emulated=False):
        self.service = BlockBlobService(account_name=account_name,
                                        account_key=account_key,
                                        is_emulated=is_emulated,
                                        protocol=protocol)
        self.container_created = False
        hostname = gethostname()
        self.meta = {'hostname': hostname.replace('_', '-'),
                     'process': os.getpid()}
        self.container = (container % self.meta).lower()
        self.meta['hostname'] = hostname
        self.zip_compression = zip_compression
        self.max_connections = max_connections
        self.max_retries = max_retries
        self.retry_wait = retry_wait

    def put_file_into_storage(self, dirName, fileName):
        """
        Ship the outdated log file to the specified blob container.
        """
        if not self.container_created:
            self.service.create_container(self.container)
            self.container_created = True
        fd, tmpfile_path = None, ''
        try:
            file_path = os.path.join(dirName, fileName)
            if self.zip_compression:
                suffix, content_type = '.zip', 'application/zip'
                fd, tmpfile_path = mkstemp(suffix=suffix)
                with os.fdopen(fd, 'wb') as f:
                    with ZipFile(f, 'w', ZIP_DEFLATED) as z:
                        z.write(file_path, arcname=fileName)
                file_path = tmpfile_path
            else:
                suffix, content_type = '', 'text/plain'
            self.service.create_blob_from_path(container_name=self.container,
                                               blob_name=fileName+suffix,
                                               file_path=file_path,
                                               content_settings=ContentSettings(content_type=content_type),
                                               max_connections=self.max_connections
                                               )  # max_retries and retry_wait no longer arguments in azure 0.33
        finally:
            if self.zip_compression and fd:
                os.remove(tmpfile_path)

class BlobStorageRotatingFileHandler(RotatingFileHandler,
                                         _BlobStorageFileHandler):
    """
    Handler for logging to a file, which switches from one file
    to the next when the current file reaches a certain size.

    The outdated log file is shipped to the specified Azure Storage
    blob container and removed from the local file system immediately.
    """
    def __init__(self,
                  filename,
                  mode='a',
                  maxBytes=0,
                  encoding=None,
                  delay=False,
                  account_name=None,
                  account_key=None,
                  protocol='https',
                  container='logs',
                  zip_compression=False,
                  max_connections=1,
                  max_retries=5,
                  retry_wait=1.0,
                  is_emulated=False):
        meta = {'hostname': gethostname(), 'process': os.getpid()}
        RotatingFileHandler.__init__(self,
                                     filename % meta,
                                     mode=mode,
                                     maxBytes=maxBytes,
                                     backupCount=1,
                                     encoding=encoding,
                                     delay=delay)
        _BlobStorageFileHandler.__init__(self,
                                         account_name=account_name,
                                         account_key=account_key,
                                         protocol=protocol,
                                         container=container,
                                         zip_compression=zip_compression,
                                         max_connections=max_connections,
                                         max_retries=max_retries,
                                         retry_wait=retry_wait,
                                         is_emulated=is_emulated)

    def doRollover(self):
        """
        Do a rollover, as described in __init__().
        """
        if self.stream:
            self.stream.close()
            self.stream = None
        dfn = "%s.%s" % (self.baseFilename,
                         datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S'))
        if os.path.exists(self.baseFilename):
            os.rename(self.baseFilename, dfn)
            self.put_file_into_storage(*os.path.split(dfn))
            os.remove(dfn)
        if not self.delay:
            self.stream = self._open()

class BlobStorageTimedRotatingFileHandler(TimedRotatingFileHandler,
                                               _BlobStorageFileHandler):
    """
    Handler for logging to a file, rotating the log file at certain timed
    intervals.

    The outdated log file is shipped to the specified Azure Storage
    blob container and removed from the local file system immediately.
    """
    def __init__(self,
                 filename,
                 when='h',
                 interval=1,
                 encoding=None,
                 delay=False,
                 utc=False,
                 account_name=None,
                 account_key=None,
                 protocol='https',
                 container='logs',
                 zip_compression=False,
                 max_connections=1,
                 max_retries=5,
                 retry_wait=1.0,
                 is_emulated=False):
        meta = {'hostname': gethostname(), 'process': os.getpid()}
        TimedRotatingFileHandler.__init__(self,
                                          filename % meta,
                                          when=when,
                                          interval=interval,
                                          backupCount=1,
                                          encoding=encoding,
                                          delay=delay,
                                          utc=utc)
        _BlobStorageFileHandler.__init__(self,
                                         account_name=account_name,
                                         account_key=account_key,
                                         protocol=protocol,
                                         container=container,
                                         zip_compression=zip_compression,
                                         max_connections=max_connections,
                                         max_retries=max_retries,
                                         retry_wait=retry_wait,
                                         is_emulated=is_emulated)

    def emit(self, record):
        """
        Emit a record.

        Output the record to the file, catering for rollover as described
        in doRollover().
        """
        record.hostname = self.meta['hostname']
        super(BlobStorageTimedRotatingFileHandler, self).emit(record)

    def getFilesToDelete(self):
        """
        Determine the files to delete when rolling over.
        """
        dirName, baseName = os.path.split(self.baseFilename)
        fileNames = os.listdir(dirName)
        result = []
        prefix = baseName + "."
        plen = len(prefix)
        for fileName in fileNames:
            if fileName[:plen] == prefix:
                suffix = fileName[plen:]
                if self.extMatch.match(suffix):
                    self.put_file_into_storage(dirName, fileName)
                    result.append(os.path.join(dirName, fileName))
        # delete the stored log file from the local file system immediately
        return result

class QueueStorageHandler(logging.Handler):
    """
    Handler class which sends log messages to a Azure Storage queue.
    """
    def __init__(self,
                 account_name=None,
                 account_key=None,
                 protocol='https',
                 queue='logs',
                 message_ttl=None,
                 visibility_timeout=None,
                 base64_encoding=False,
                 is_emulated=False,
                 ):
        """
        Initialize the handler.
        """
        logging.Handler.__init__(self)
        self.service = QueueService(account_name=account_name,
                                    account_key=account_key,
                                    is_emulated=is_emulated,
                                    protocol=protocol)
        self.meta = {'hostname': gethostname(), 'process': os.getpid()}
        self.queue = _formatName(queue, self.meta)
        self.queue_created = False
        self.message_ttl = message_ttl
        self.visibility_timeout = visibility_timeout
        self.base64_encoding = base64_encoding

    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified queue.
        """
        try:
            if not self.queue_created:
                self.service.create_queue(self.queue)
                self.queue_created = True
            record.hostname = self.meta['hostname']
            msg = self._encode_text(self.format(record))
            self.service.put_message(self.queue,
                                     msg,
                                     self.visibility_timeout,
                                     self.message_ttl)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def _encode_text(self, text):
        if self.base64_encoding:
            text = b64encode(text.encode('utf-8')).decode('ascii')
        # fallback for the breaking change in azure-storage 0.33
        elif sys.version_info < (3,):
            if not isinstance(text, unicode):
                text = text.decode('utf-8')
        return text

class TableStorageHandler(logging.Handler):
    """
    Handler class which writes log messages to a Azure Storage table.
    """
    MAX_BATCH_SIZE = 100

    def __init__(self,
                 account_name=None,
                 account_key=None,
                 protocol='https',
                 table='logs',
                 batch_size=0,
                 extra_properties=None,
                 partition_key_formatter=None,
                 row_key_formatter=None,
                 is_emulated=False,
                 ):
        """
        Initialize the handler.
        """
        logging.Handler.__init__(self)
        self.service = TableService(account_name=account_name,
                                    account_key=account_key,
                                    is_emulated=is_emulated,
                                    protocol=protocol)
        self.meta = {'hostname': gethostname(), 'process': os.getpid()}
        self.table = _formatName(table, self.meta)
        self.ready = False
        self.rowno = 0
        if not partition_key_formatter:
            # default format for partition keys
            fmt = '%(asctime)s'
            datefmt = '%Y%m%d%H%M'
            partition_key_formatter = logging.Formatter(fmt, datefmt)
        self.partition_key_formatter = partition_key_formatter
        if not row_key_formatter:
            # default format for row keys
            fmt = '%(asctime)s%(msecs)03d-%(hostname)s-%(process)d-%(rowno)02d'
            datefmt = '%Y%m%d%H%M%S'
            row_key_formatter = logging.Formatter(fmt, datefmt)
        self.row_key_formatter = row_key_formatter
        # extra properties and formatters for them
        self.extra_properties = extra_properties
        if extra_properties:
            self.extra_property_formatters = {}
            self.extra_property_names = {}
            for extra in extra_properties:
                if _PY3:
                    f = logging.Formatter(fmt=extra, style=extra[0])
                else:
                    f = logging.Formatter(fmt=extra)
                self.extra_property_formatters[extra] = f
                self.extra_property_names[extra] = self._getFormatName(extra)
        # the storage emulator doesn't support batch operations
        if batch_size <= 1 or is_emulated:
            self.batch = None
        else:
            self.batch = TableBatch()
            if batch_size > TableStorageHandler.MAX_BATCH_SIZE:
                self.batch_size = TableStorageHandler.MAX_BATCH_SIZE
            else:
                self.batch_size = batch_size
        if self.batch:
            self.current_partition_key = None

    def _copyLogRecord(self, record):
        copy = logging.makeLogRecord(record.__dict__)
        copy.exc_info = None
        copy.exc_text = None
        if _PY3:
            copy.stack_info = None
        return copy

    def _getFormatName(self, extra):
        name = extra
        style = extra[0]
        if style == '%':
            name = extra[2:extra.index(')')]
        elif _PY3:
            if style == '{':
                name = next(string.Formatter().parse(extra))[1]
            elif style == '$':
                name = extra[1:]
                if name.startswith('{'):
                    name = name[1:-1]
        return name

    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified table.
        """
        try:
            if not self.ready:
                self.service.create_table(self.table)
                self.ready = True
            # generate partition key for the entity
            record.hostname = self.meta['hostname']
            copy = self._copyLogRecord(record)
            partition_key = self.partition_key_formatter.format(copy)
            # ensure entities in the batch all have the same patition key
            if self.batch:
                if self.current_partition_key is not None:
                    if partition_key != self.current_partition_key:
                        self.flush()
                self.current_partition_key = partition_key
            # add log message and extra properties to the entity
            entity = {}
            if self.extra_properties:
                for extra in self.extra_properties:
                    formatter = self.extra_property_formatters[extra]
                    name = self.extra_property_names[extra]
                    entity[name] = formatter.format(copy)
            entity['message'] = self.format(record)
            # generate row key for the entity
            copy.rowno = self.rowno
            row_key = self.row_key_formatter.format(copy)
            # add entitiy to the table
            entity['PartitionKey'] = partition_key
            entity['RowKey'] = row_key
            if not self.batch:
                self.service.insert_or_replace_entity(self.table, entity)
            else:
                self.batch.insert_or_replace_entity(entity)
                # commit the ongoing batch if it reaches the high mark
                self.rowno += 1
                if self.rowno >= self.batch_size:
                    self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def flush(self):
        """
        Ensure all logging output has been flushed.
        """
        if self.batch and self.rowno > 0:
            try:
                self.service.commit_batch(self.table, self.batch)
            finally:
                self.rowno = 0
                self.batch = TableBatch()

    def setFormatter(self, fmt):
        """
        Set the message formatter.
        """
        super(TableStorageHandler, self).setFormatter(fmt)
        if self.extra_properties:
            logging._acquireLock()
            try:
                for extra in self.extra_property_formatters.values():
                    extra.converter = fmt.converter
                    extra.datefmt = fmt.datefmt
                    if _PY3:
                        extra.default_time_format = fmt.default_time_format
                        extra.default_msec_format = fmt.default_msec_format
            finally:
                logging._releaseLock()

    def setPartitionKeyFormatter(self, fmt):
        """
        Set the partition key formatter.
        """
        self.partition_key_formatter = fmt

    def setRowKeyFormatter(self, fmt):
        """
        Set the row key formatter.
        """
        self.row_key_formatter = fmt


text:
package edu.uiowa.icts.inv.dao;

import edu.uiowa.icts.spring.*;
import edu.uiowa.icts.inv.domain.*;

/**
 * Generated by Protogen
 * @since 10/16/2015 11:14:56 CDT
 */
public interface SystemSettingService extends GenericDaoInterface<SystemSetting> {

	public SystemSetting findById( String id );

	public String getValue( String name, String defaultVal );

}


text:
import React from "react";
import { inject, observer } from "mobx-react";
import classNames from "classnames";

import warnIcon from "assets/images/icons/warning.png";
import errorIcon from "assets/images/icons/error.png";
import { timestampMsToTimeString } from "utils/misc";

@observer
export class MonitorItem extends React.Component {
    render() {
        const { level, text, time } = this.props;

        const levelClass = (level === "ERROR" || level === "FATAL") ?
                           "alert" : "warn";
        const icon = levelClass === "alert" ? errorIcon : warnIcon;

        return (

                    {text}

                {time}

        );
    }
}

@inject("store") @observer
export default class Console extends React.Component {
    render() {
        const { monitor } = this.props.store;

        return (

Console

                        {monitor.items.map((item, index) => (
                            <MonitorItem key={index} text={item.msg}
                                level={item.logLevel}
                                time={timestampMsToTimeString(item.timestampMs)} />
                        ))}

        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Projecto.DependencyInjection
{
    /// <summary>
    /// Interface that defines a lifetime scope for resolving dependencies.
    /// </summary>
    public interface IDependencyLifetimeScope : IDisposable
    {
        /// <summary>
        /// Property dictionary for sharing data between different event handlers.
        /// </summary>
        [SuppressMessage("ReSharper", "UnusedMemberInSuper.Global")]
        IDictionary<object, object> Properties { get; }

        /// <summary>
        /// Called when a certain dependency needs to be resolved.
        /// </summary>
        /// <param name="dependencyType">The type of the dependency.</param>
        /// <returns>An instance of the requested dependency type or null when the type was not found.</returns>
        object Resolve(Type dependencyType);

        /// <summary>
        /// Event triggered when a dependency was resolved from the lifetime scope.
        /// </summary>
        [SuppressMessage("ReSharper", "EventNeverSubscribedTo.Global")]
        event DependencyResolvedEvent DependencyResolved;

        /// <summary>
        /// Event triggered when the lifetime scope is about to end (right before disposal).
        /// </summary>
        [SuppressMessage("ReSharper", "EventNeverSubscribedTo.Global")]
        event DependencyLifetimeScopeEndingEvent ScopeEnding;
    }
}


text:
endmacro
--------

Ends a list of commands in a macro block.

.. code-block:: cmake

  endmacro([<name>])

See the :command:`macro` command.

The optional ``<name>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the ``<name>`` argument
of the opening ``macro`` command.


text:
<?php

abstract class PhabricatorPackagerController
  extends PhabricatorController {

  protected function buildSideNavView($for_app = false) {
    $nav = new AphrontSideNavFilterView();
    $nav->setBaseURI(new PhutilURI($this->getApplicationURI()));

    if ($for_app) {
      $nav->addLabel(pht('Register Package'));
      $nav->addFilter('',
        pht('Register Package'),
        $this->getApplicationURI('/register/'));
    }

    $nav->addLabel(pht('Packages'));
    $nav->addFilter('/', pht('All Packages'));
    $nav->addLabel(pht('Package Requests'));
    $nav->addFilter('request', pht('Active Requests'), '/packager/request/');

    return $nav;
  }

  public function buildApplicationMenu() {
    return $this->buildSideNavView($for_app = true)->getMenu();
  }

  protected function buildApplicationCrumbs() {
    $crumbs = parent::buildApplicationCrumbs();

    $crumbs->addAction(
      id(new PhabricatorMenuItemView())
        ->setName(pht('Register new package'))
        ->setHref($this->getApplicationURI('/register/'))
        ->setWorkflow(true)
        ->setIcon('create'));

    $crumbs->addAction(
      id(new PhabricatorMenuItemView())
        ->setName(pht('Request new package'))
        ->setHref($this->getApplicationURI('/request/new/'))
        ->setWorkflow(true)
        ->setIcon('tag'));

    return $crumbs;
  }

}


text:
package net.davidtanzer.html;

import net.davidtanzer.html.values.AttributeName;
import net.davidtanzer.html.values.AttributeValue;
import net.davidtanzer.html.values.TagName;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class EmptyElementTest {
	private EmptyElement element;

	@Before
	public void setup() {
		element = new EmptyElement(TagName.of("testElement")) {
		};
	}

	@Test
	public void rendersEmptyElementWithCloseTagWhenNoContentOrAttributesWereAdded() {
		String rendered = element.render();

		assertEquals("<testElement>", rendered);
	}

	@Test
	public void rendersElementWithAttributesWhenAttributesWereAdded() {
		element.setAttribute(AttributeName.of("attr1"), new AttributeValue("value1"));
		element.setAttribute(AttributeName.of("attr2"), new AttributeValue("value2"));

		String rendered = element.render();

		assertTrue(rendered.contains(" attr1=\"value1\""));
		assertTrue(rendered.contains(" attr2=\"value2\""));
	}
}