text:
package jwtc.android.chess.ics;

import java.io.IOException;
import java.io.InterruptedIOException;

/**
 * This code was reverse engineered from the JIN project. JIN is a gpled
 * project. Its url can be found here: http://www.jinchess.com/
 */
public class TimesealPipe {

    private int _fldbyte;

    private int _fldchar;

    private volatile int _flddo;

    private final byte buffer[];

    private boolean closedFlag;

    private boolean closedFlag2;

    private Object readLock;

    private final TimesealInputStream timesealInputStream;

    private final TimesealOutputStream timesealOutputStream;

    private Object writeLock;

    public TimesealPipe() {
        this(2048);
    }

    public TimesealPipe(int i) {
        _flddo = 0;
        _fldchar = 0;
        _fldbyte = 0;
        closedFlag = false;
        closedFlag2 = false;
        writeLock = "Write Lock for PipedStreams";
        readLock = "Read Lock for PipedStream";
        timesealInputStream = new TimesealInputStream(this);
        timesealOutputStream = new TimesealOutputStream(this);
        buffer = new byte[i];
    }

    public int _mthdo() {
        return _flddo;
    }

    public void _mthif(int i) {
        synchronized (readLock) {
            _flddo = i;
        }
    }

    public TimesealInputStream getTimesealInputStream() {
        return timesealInputStream;
    }

    public TimesealOutputStream getTimesealOutputStream() {
        return timesealOutputStream;
    }

    synchronized int _mthcase() {
        if (closedFlag2) {
            return 0;
        } else {
            return _mthint();
        }
    }

    synchronized int _mthfor() throws IOException {
        synchronized (readLock) {
            if (closedFlag2) {
                throw new IOException("Stream closed");
            }
            long l = System.currentTimeMillis();
            while (_mthcase() == 0) {
                if (closedFlag) {
                    byte byte0 = -1;
                    return byte0;
                }
                long currentTime = System.currentTimeMillis();
                if (_flddo != 0 && currentTime - l >= _flddo) {
                    throw new InterruptedIOException();
                }
                try {
                    if (_flddo == 0) {
                        wait();
                    } else {
                        wait(_flddo + currentTime - l);
                    }
                } catch (InterruptedException _ex) {
                    throw new InterruptedIOException();
                }
                if (closedFlag2) {
                    throw new IOException("Stream closed");
                }
            }
            byte byte1 = buffer[_fldchar++];
            if (_fldchar == buffer.length) {
                _fldchar = 0;
            }
            notifyAll();
            int i = byte1 >= 0 ? (int) byte1 : byte1 + 256;
            return i;
        }
    }

    synchronized int _mthif(byte abyte0[], int i, int j) throws IOException {
        synchronized (readLock) {
            if (closedFlag2) {
                throw new IOException("Stream closed");
            }
            long currentTimeMillis = System.currentTimeMillis();
            while (_mthcase() == 0) {
                if (closedFlag) {
                    byte byte0 = -1;
                    return byte0;
                }
                long l1 = System.currentTimeMillis();
                if (_flddo != 0 && l1 - currentTimeMillis >= _flddo) {
                    throw new InterruptedIOException();
                }
                try {
                    if (_flddo == 0) {
                        wait();
                    } else {
                        wait(_flddo + l1 - currentTimeMillis);
                    }
                } catch (InterruptedException _ex) {
                    throw new InterruptedIOException();
                }
                if (closedFlag2) {
                    throw new IOException("Stream closed");
                }
            }
            int i1 = _mthcase();
            int j1 = j <= i1 ? j : i1;
            int k1 = buffer.length - _fldchar <= j1 ? buffer.length - _fldchar
                    : j1;
            int i2 = j1 - k1 <= 0 ? 0 : j1 - k1;
            System.arraycopy(buffer, _fldchar, abyte0, i, k1);
            System.arraycopy(buffer, 0, abyte0, i + k1, i2);
            _fldchar = (_fldchar + j1) % buffer.length;
            notifyAll();
            int k = j1;
            return k;
        }
    }

    synchronized void _mthnew() {
        if (closedFlag2) {
            throw new IllegalStateException("Already closed");
        } else {
            closedFlag2 = true;
            notifyAll();
            return;
        }
    }

    synchronized void _mthtry() {
        if (closedFlag) {
            throw new IllegalStateException("Already closed");
        } else {
            closedFlag = true;
            notifyAll();
            return;
        }
    }

    synchronized void a(int i) throws IOException {
        synchronized (writeLock) {
            if (closedFlag2 || closedFlag) {
                throw new IOException("Stream closed");
            }
            while (duno() == 0) {
                try {
                    wait();
                } catch (InterruptedException _ex) {
                    throw new InterruptedIOException();
                }
            }
            if (closedFlag2 || closedFlag) {
                throw new IOException("Stream closed");
            }
            buffer[_fldbyte++] = (byte) (i & 0xff);
            if (_fldbyte == buffer.length) {
                _fldbyte = 0;
            }
            notifyAll();
        }
    }

    synchronized void write(byte bytes[], int i, int j) throws IOException {
        synchronized (writeLock) {
            if (closedFlag2 || closedFlag) {
                throw new IOException("Stream closed");
            }
            while (j > 0) {
                while (duno() == 0) {
                    try {
                        wait();
                    } catch (InterruptedException _ex) {
                        throw new InterruptedIOException();
                    }
                }
                int k = duno();
                int l = j <= k ? j : k;
                int i1 = buffer.length - _fldbyte < l ? buffer.length
                        - _fldbyte : l;
                int j1 = l - i1 <= 0 ? 0 : l - i1;
                System.arraycopy(bytes, i, buffer, _fldbyte, i1);
                System.arraycopy(bytes, i + i1, buffer, 0, j1);
                i += l;
                j -= l;
                _fldbyte = (_fldbyte + l) % buffer.length;
                notifyAll();
            }
        }
    }

    private int _mthint() {
        if (_fldbyte >= _fldchar) {
            return _fldbyte - _fldchar;
        } else {
            return _fldbyte + buffer.length - _fldchar;
        }
    }

    private int duno() {
        return buffer.length - _mthint() - 1;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>cn.jpush.im.android.api.enums (android API)</title>
<meta name="date" content="2018-02-28">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

cn.jpush.im.android.api.enums

Enums

ContentType

ConversationType

MessageDirect

MessageStatus

PlatformType

redpajama_set_name: RedPajamaGithub


text:
package com.sgxmobileapps.androidsqlhelper.processor.model;

import com.sgxmobileapps.androidsqlhelper.annotation.PersistentField;

import java.util.Arrays;
import java.util.List;

import javax.lang.model.element.Element;
import javax.lang.model.type.DeclaredType;

/**
 * The Field class contains the field information used by the annotation
 * processor for the generation of SQL helper code.
 *
 * @author Massimo Gaddini
 */
public class Field implements Visitable {
    protected boolean mIdField;
    protected String mFieldName;
    protected String mColumnName;
    protected boolean mUnique;
    protected boolean mNullable;
    protected String mColumnType;
    protected Table mTable;
    protected String mCustomColumnDefinition;
    protected int mIndex;
    protected String mGetterMethod;
    protected String mSetterMethod;
    protected String mGetterConvMethod;
    protected String mSetterConvMethod;
    protected String mCursorGetterMethod;
    protected Class<?> mClazz;
    protected Class<?> mClazzCast;

    /**
     * Builds a Field instance from an PersistentField annotation and
     * the annotated member Element
     * @param annotation the annotation
     * @param member the member
     * @return new Field instance
     * @throws UnsupportedFieldTypeException if the field's type is unsupported
     */
    public static Field buildField(PersistentField annotation, Element member, Table table) throws UnsupportedFieldTypeException{
        Field field = new Field();

        field.mIdField = false;

        String fieldName = member.getSimpleName().toString();
        if (fieldName.startsWith(table.getFieldPrefix())){
            fieldName = fieldName.substring(table.getFieldPrefix().length());
        }

        field.mFieldName = fieldName;

        if (annotation.columnName().isEmpty()) {
            field.mColumnName = fieldName.toUpperCase();
        } else {
            field.mColumnName = annotation.columnName().toUpperCase();
        }

        field.mUnique = annotation.unique();

        List<String> unique = Arrays.asList(table.getUniqueConstraint());
        List<String> pk = Arrays.asList(table.getPKConstraint());
        field.mNullable = !unique.contains(field.mFieldName) &&
                          !pk.contains(field.mFieldName) &&
                          !field.mUnique &&
                          annotation.nullable();

        field.mCustomColumnDefinition = annotation.customColumnDefinition();

        field.mTable = table;

        String fieldNameForGetter = field.getFieldNameForMethod();
        field.mGetterMethod = "get" + fieldNameForGetter;
        field.mSetterMethod = "set" + fieldNameForGetter;
        field.mGetterConvMethod = null;
        field.mSetterConvMethod = null;

        switch(member.asType().getKind()) {
        case BOOLEAN:
            field.mGetterMethod = "is" + fieldNameForGetter;
            field.mColumnType = "INTEGER";
            field.mCursorGetterMethod = "getLong";
            field.mClazz = boolean.class;
            field.mClazzCast = boolean.class;
            break;
        case BYTE:
            field.mColumnType = "INTEGER";
            field.mCursorGetterMethod = "getLong";
            field.mClazz = byte.class;
            field.mClazzCast = byte.class;
            break;
        case LONG:
            field.mColumnType = "INTEGER";
            field.mCursorGetterMethod = "getLong";
            field.mClazz = long.class;
            field.mClazzCast = null;
            break;
        case INT:
            field.mColumnType = "INTEGER";
            field.mCursorGetterMethod = "getLong";
            field.mClazz = int.class;
            field.mClazzCast = int.class;
            break;
        case SHORT:
            field.mColumnType = "INTEGER";
            field.mCursorGetterMethod = "getLong";
            field.mClazz = short.class;
            field.mClazzCast = short.class;
            break;
        case FLOAT:
            field.mColumnType = "REAL";
            field.mCursorGetterMethod = "getDouble";
            field.mClazz = float.class;
            field.mClazzCast = float.class;
            break;
        case DOUBLE:
            field.mColumnType = "REAL";
            field.mCursorGetterMethod = "getDouble";
            field.mClazz = double.class;
            field.mClazzCast = null;
            break;

        case DECLARED:

            String javaClass =  ((DeclaredType)member.asType()).asElement().toString();

            try {
                field.mClazz = Class.forName(javaClass);
            } catch (ClassNotFoundException e) {
                throw new UnsupportedFieldTypeException("Declared type " + javaClass + " not found", e);
            }

            if (javaClass.equals("java.lang.String")) {

                field.mColumnType = "TEXT";
                field.mCursorGetterMethod = "getString";
                field.mClazzCast = null;
            } else if ( javaClass.equals("java.lang.CharSequence") ) {

                field.mColumnType = "TEXT";
                field.mGetterConvMethod = "toString";
                field.mCursorGetterMethod = "getString";
                field.mClazzCast = null;
            } else if (javaClass.equals("java.lang.Boolean")) {

                field.mColumnType = "INTEGER";
                field.mGetterMethod = "is" + fieldNameForGetter;
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = boolean.class;
            } else if (javaClass.equals("java.lang.Byte")) {

                field.mColumnType = "INTEGER";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = byte.class;
            } else if (javaClass.equals("java.lang.Long")) {

                field.mColumnType = "INTEGER";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = null;
            } else if (javaClass.equals("java.lang.Integer")) {

                field.mColumnType = "INTEGER";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = int.class;
            } else if (javaClass.equals("java.lang.Short")) {

                field.mColumnType = "INTEGER";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = short.class;
            } else if (javaClass.equals("java.lang.Double")) {

                field.mColumnType = "REAL";
                field.mCursorGetterMethod = "getDouble";
                field.mClazzCast = null;
            } else if (javaClass.equals("java.lang.Float")) {

                field.mColumnType = "REAL";
                field.mCursorGetterMethod = "getDouble";
                field.mClazzCast = float.class;
            } else if (javaClass.equals("java.util.Date")) {

                field.mColumnType = "INTEGER";
                field.mGetterConvMethod = "getTime";
                field.mSetterConvMethod = "setTime";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = null;
            } else if ( javaClass.equals("java.util.GregorianCalendar") ) {

                field.mColumnType = "INTEGER";
                field.mGetterConvMethod = "getTimeInMillis";
                field.mSetterConvMethod = "setTimeInMillis";
                field.mCursorGetterMethod = "getLong";
                field.mClazzCast = null;
            } else {
                throw new UnsupportedFieldTypeException("Declared type " + javaClass + " unsupported");
            }
            break;

        default:
            throw new UnsupportedFieldTypeException("Kind " + member.asType().getKind() + " unsupported");
        }

        return field;
    }

    public static Field buildIdField(Table table){
        Field field = new Field();

        field.mIdField = true;
        field.mIndex = 0;
        field.mFieldName = "Id";
        field.mColumnName = "_id";
        field.mUnique = false;
        field.mNullable = false;
        field.mTable = table;
        field.mColumnType = "INTEGER";
        field.mCustomColumnDefinition = "INTEGER PRIMARY KEY AUTOINCREMENT";
        field.mGetterMethod = "get" + field.getFieldNameForMethod();
        field.mSetterMethod = "set" + field.getFieldNameForMethod();
        field.mCursorGetterMethod = "getLong";
        field.mGetterConvMethod = null;
        field.mSetterConvMethod = null;
        field.mClazz = long.class;
        field.mClazzCast = null;
        return field;
    }

    /**
     * Returns the column definition using other fields
     * @return the column definition
     */
    public String getColumnDefinition() {
        if (!mCustomColumnDefinition.isEmpty())  {
            return mCustomColumnDefinition;
        }

        String definition = mColumnType;
        if (!mNullable) {
            definition += " NOT NULL";
        }

        if (mUnique) {
            definition += " UNIQUE";
        }

        return definition;
    }

    /**
     * Returns the field name to use in method name as getter and setter
     * @return the field name
     */
    public String getFieldNameForMethod(){
        return mFieldName.substring(0,1).toUpperCase() + mFieldName.substring(1);
    }

    /**
     * Returns the field name to use in variable name
     * @return the field name
     */
    public String getFieldNameForVar(){
        return mFieldName.substring(0,1).toLowerCase() + mFieldName.substring(1);
    }

    /*
     * @see com.sgxmobileapps.androidsqlhelper.processor.model.Visitable#accept(com.sgxmobileapps.androidsqlhelper.processor.model.GeneratorVisitor)
     */
    @Override
    public void accept(Visitor visitor) throws VisitorException {
        visitor.visit(this);
    }

    /**
     * @return the columnName
     */
    public String getColumnName() {
        return mColumnName;
    }

    /**
     * @return the fieldName
     */
    public String getFieldName() {
        return mFieldName;
    }

    /**
     * @return the table
     */
    public Table getTable() {
        return mTable;
    }

    /**
     * @return the index
     */
    public int getIndex() {
        return mIndex;
    }

    /**
     * @param index the index to set
     */
    public void setIndex(int index) {
        mIndex = index;
    }

    /**
     * @return the idField
     */
    public boolean isIdField() {
        return mIdField;
    }

    /**
     * @return the getterMethod
     */
    public String getGetterMethod() {
        return mGetterMethod;
    }

    /**
     * @return the setterMethod
     */
    public String getSetterMethod() {
        return mSetterMethod;
    }

    /**
     * @return the getterConvMethod
     */
    public String getGetterConvMethod() {
        return mGetterConvMethod;
    }

    /**
     * @return the setterConvMethod
     */
    public String getSetterConvMethod() {
        return mSetterConvMethod;
    }

    /**
     * @return the cursorGetterMethod
     */
    public String getCursorGetterMethod() {
        return mCursorGetterMethod;
    }

    /**
     * @return the clazz
     */
    public Class<?> getClazz() {
        return mClazz;
    }

    /**
     * @return the clazzCast
     */
    public Class<?> getClazzCast() {
        return mClazzCast;
    }

    /**
     * @return true if the field type is INTEGER or REAL
     */
    public boolean isNumberField() {
        return mColumnType.equals("INTEGER") || mColumnType.equals("REAL");
    }

    /*
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Field [");
        if (mColumnName != null) {
            builder.append("mColumnName=");
            builder.append(mColumnName);
            builder.append(", ");
        }
        if (mColumnType != null) {
            builder.append("mColumnType=");
            builder.append(mColumnType);
            builder.append(", ");
        }
        if (mCustomColumnDefinition != null) {
            builder.append("mCustomColumnDefinition=");
            builder.append(mCustomColumnDefinition);
            builder.append(", ");
        }
        if (mFieldName != null) {
            builder.append("mFieldName=");
            builder.append(mFieldName);
            builder.append(", ");
        }
        builder.append("mIndex=");
        builder.append(mIndex);
        builder.append(", mUnique=");
        builder.append(mUnique);
        builder.append(", mNullable=");
        builder.append(mNullable);
        builder.append(", mIdField=");
        builder.append(mIdField);
        builder.append(", mGetterMethod=");
        builder.append(mGetterMethod);
        builder.append(", mSetterMethod=");
        builder.append(mSetterMethod);
        builder.append(", mGetterConvMethod=");
        builder.append(mGetterConvMethod);
        builder.append(", mSetterConvMethod=");
        builder.append(mSetterConvMethod);
        builder.append(", mCursorGetterMethod=");
        builder.append(mCursorGetterMethod);
        builder.append(", mClazz=");
        builder.append(mClazz);
        builder.append(", mClazzCast=");
        builder.append(mClazzCast);
        builder.append("]");
        return builder.toString();
    }

 }


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>mongoc_write_concern_t</title>
<link rel="stylesheet" type="text/css" href="C.css">

MongoDB C Driver › API Reference »

mongoc_write_concern_t

Write Concern abstraction

Synopsis

mongoc_write_concern_t provides an abstraction on top of the MongoDB connection write concern.  It allows for hinting to the driver how durable writes should be, both in replication as well as on a per node basis.

You can specify a read preference mode on connection objects, database objects, collection objects, or per-operation.

Write Concern Levels

Network Related

MONGOC_WRITE_CONCERN_W_DEFAULT (1)

With a receipt acknowledged write concern, the mongod confirms the receipt of the write operation. Acknowledged write concern allows clients to catch network, duplicate key, and other errors.

MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED (-1)

With an errors ignored write concern, MongoDB does not acknowledge write operations. With this level of write concern, the client cannot detect failed write operations. These errors include connection errors and mongod exceptions such as duplicate key exceptions for unique indexes. Although the errors ignored write concern provides fast performance, this performance gain comes at the cost of significant risks for data persistence and durability.

MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED (0)

With an unacknowledged write concern, MongoDB does not acknowledge the receipt of write operation. Unacknowledged is similar to errors ignored; however, mongoc attempts to receive and handle network errors when possible.

MONGOC_WRITE_CONCERN_W_MAJORITY (majority)

Require that a write has been propagated to a majority of the nodes in the replica set.

n

Require that a write has been propagated to at least n nodes in the replica set.

Node Persistence

fsync

Force a full fsync() on the node receiving the write.

journal

Force a flush to the journal on the node receiving the write.

Functions

mongoc_write_concern_copy()

mongoc_write_concern_destroy()

mongoc_write_concern_get_fsync()

mongoc_write_concern_get_journal()

mongoc_write_concern_get_w()

mongoc_write_concern_get_wmajority()

mongoc_write_concern_get_wtag()

mongoc_write_concern_get_wtimeout()

mongoc_write_concern_new()

mongoc_write_concern_set_fsync()

mongoc_write_concern_set_journal()

mongoc_write_concern_set_w()

mongoc_write_concern_set_wmajority()

mongoc_write_concern_set_wtag()

mongoc_write_concern_set_wtimeout()

More Information

API Reference


text:
"""
    sale.py

    :copyright: (c) 2015 by Fulfil.IO Inc.
    :license: see LICENSE for more details.
"""
from trytond.model import fields
from trytond.pyson import Eval
from trytond.pool import Pool, PoolMeta

__metaclass__ = PoolMeta
__all__ = ['SaleLine']

class SaleLine:
    __name__ = 'sale.line'

    product_type = fields.Function(
        fields.Char('Product Type'), 'on_change_with_product_type'
    )

    @classmethod
    def __setup__(cls):
        super(SaleLine, cls).__setup__()

        cls.warehouse = fields.Many2One(
            'stock.location', 'Warehouse',
            domain=[('type', '=', 'warehouse')], states={
                'invisible': (
                    (Eval('type') != 'line')
                    | (Eval('product_type') != 'goods')
                ),
                'required': (
                    (Eval('type') == 'line')
                    & (Eval('product_type') == 'goods')
                ),
                'readonly': ~Eval('_parent_sale', {}),
            }
        )
        cls.warehouse.depends.append('product_type')

    @fields.depends('type', 'product')
    def on_change_with_product_type(self, name=None):
        if self.type == 'line' and self.product:
            return self.product.type

    @staticmethod
    def default_warehouse():
        Sale = Pool().get('sale.sale')

        return Sale.default_warehouse()


text:
package io.reflectoring.coderadar.rest.dependencymap;

import io.reflectoring.coderadar.dependencymap.port.driver.GetCompareTreeUseCase;
import io.reflectoring.coderadar.rest.AbstractBaseController;
import io.reflectoring.coderadar.useradministration.service.security.AuthenticationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class DependencyCompareTreeController implements AbstractBaseController {
  private final GetCompareTreeUseCase getCompareTreeUseCase;
  private final AuthenticationService authenticationService;

  @GetMapping(
      produces = MediaType.APPLICATION_JSON_VALUE,
      value = "/analyzers/{projectId}/structureMap/{commitName}/{secondCommit}")
  public ResponseEntity<Object> getDependencyTree(
      @PathVariable("projectId") Long projectId,
      @PathVariable("commitName") String commitName,
      @PathVariable("secondCommit") String secondCommit) {
    authenticationService.authenticateMember(projectId);
    return ResponseEntity.ok(
        getCompareTreeUseCase.getDependencyTree(projectId, commitName, secondCommit));
  }
}


text:
const keystone = require('keystone');
const transform = require('model-transform');

const Types = keystone.Field.Types;

const User = new keystone.List('User');

User.add({
   name: { type: Types.Name, required: true, index: true },
   email: { type: Types.Email, initial: true, required: true, index: true, unique: true },
   password: { type: Types.Password, initial: true, required: true },
   canAccessKeystone: { type: Boolean, initial: true },
});

transform.toJSON(User);

User.track = true;
User.defaultColumns = 'name, email';

User.register();


text:
<?xml version="1.0"?>
<InterchangeEducationOrganization xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ed-fi.org/0100" xsi:schemaLocation="http://ed-fi.org/0100 ../../sli/edfi-schema/src/main/resources/edfiXsd-SLI/SLI-Interchange-EducationOrganization.xsd">

  <!-- ======================================================================= -->

  <!-- SEA (no parents) -->
  <EducationOrganization>
    <StateOrganizationId>SEA</StateOrganizationId>
    <NameOfInstitution>SEA</NameOfInstitution>
    <OrganizationCategories>
      <OrganizationCategory>State Education Agency</OrganizationCategory>
    </OrganizationCategories>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

  <!-- ======================================================================= -->

  <!-- CFN (no parents) -->
  <EducationOrganization>
    <StateOrganizationId>CFN</StateOrganizationId>
    <NameOfInstitution>CFN</NameOfInstitution>
    <OtherOrganizationCategories>
      <OtherOrganizationCategory>Child First Network</OtherOrganizationCategory>
    </OtherOrganizationCategories>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

  <!-- ======================================================================= -->

  <!-- ESC (parent: SEA) -->
  <EducationOrganization>
    <StateOrganizationId>ESC</StateOrganizationId>
    <NameOfInstitution>ESC</NameOfInstitution>
    <OtherOrganizationCategories>
      <OtherOrganizationCategory>Education Service Center</OtherOrganizationCategory>
    </OtherOrganizationCategories>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>SEA</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

  <!-- ======================================================================= -->

  <!-- LEA (parents: CFN, SEA, ESC) -->
  <EducationOrganization>
    <StateOrganizationId>LEA</StateOrganizationId>
    <NameOfInstitution>LEA</NameOfInstitution>
    <OrganizationCategories>
      <OrganizationCategory>Local Education Agency</OrganizationCategory>
    </OrganizationCategories>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>SEA</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>CFN</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>ESC</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

  <!-- ======================================================================= -->

  <!-- SchoolOne (parents: LEA) -->
  <EducationOrganization>
    <StateOrganizationId>SchoolOne</StateOrganizationId>
    <NameOfInstitution>SchoolOne</NameOfInstitution>
    <OrganizationCategories>
      <OrganizationCategory>School</OrganizationCategory>
    </OrganizationCategories>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>LEA</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

  <!-- ======================================================================= -->

  <!-- SchoolTwo (parents: LEA, ESC) -->
  <EducationOrganization>
    <StateOrganizationId>SchoolTwo</StateOrganizationId>
    <NameOfInstitution>SchoolTwo</NameOfInstitution>
    <OrganizationCategories>
      <OrganizationCategory>School</OrganizationCategory>
    </OrganizationCategories>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>LEA</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <ParentEducationAgencyReference>
      <EducationalOrgIdentity>
        <StateOrganizationId>ESC</StateOrganizationId>
      </EducationalOrgIdentity>
    </ParentEducationAgencyReference>
    <Address>
      <StreetNumberName>123 Street</StreetNumberName>
      <City>Chicago</City>
      <StateAbbreviation>IL</StateAbbreviation>
      <PostalCode>00000</PostalCode>
    </Address>
  </EducationOrganization>

</InterchangeEducationOrganization>


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menu_save_item_note"
        android:icon="@drawable/save"
        android:title="@string/save_note"
        android:showAsAction="ifRoom|withText"/>

</menu>


text:
from cliez.loader import ArgLoader
import os, sys, pickle

try:
    import pkg_resources
except:
    pass

def init_fabric(hosts, root, fabfile_name):
    """
    init fabfile system
    :param hosts:
    :param fabric_dir:
    :return:
    """

    fabric_dir = os.path.join(root,'fabric')
    cabric_dir = os.path.join(root,'cabric')

    dirs = [fabric_dir, cabric_dir]

    for v in dirs:
        if os.path.exists(v) is False:
            os.makedirs(v, 0755)  # can cause OSError.
        else:
            print("Directory `%s' existed.skip init." % v.replace(os.getcwd(), '.'))

    # create config files

    files = {
        # 'dev': os.path.join(fabric_dir, 'dev.conf'),
        'beta': os.path.join(fabric_dir, 'beta.conf'),
        'online': os.path.join(fabric_dir, 'online.conf'),
        'fabfile': fabfile_name + '.py',
        'cloud_file': os.path.join(cabric_dir, 'cloud.yaml'),
    }

    for k, f in files.items():
        if os.path.exists(f) is False:
            if k == 'beta':
                with open(f, 'w') as fh:
                    for item in hosts:
                        print>> fh, item

            elif k == 'fabfile':

                try:
                    template = pkg_resources.resource_string('cabric', 'tpl/fabfile.py')
                except:
                    template = open(os.path.join(os.path.dirname(__file__), 'tpl', 'fabfile.py')).read()
                    pass

                with open(f, 'w') as fh:
                    print>> fh, template.replace('{0}', fabric_dir.replace(os.getcwd(), ''))

                pass
            elif k == 'cloud_file':
                try:
                    template = pkg_resources.resource_string('cabric', 'tpl/cloud.yaml')
                except:
                    template = open(os.path.join(os.path.dirname(__file__), 'tpl', 'cloud.yaml')).read()
                    pass

                with open(f, 'w') as fh:
                    print>> fh, template.replace('{0}', fabric_dir.replace(os.getcwd(), ''))

                pass
            else:
                with open(f, 'w') as fh:
                    os.utime(f, None)

    pass

def main():
    importer = __import__

    a = ArgLoader((
        ('Useage: cabric init [host]'),
        '',
        'Arguments',
        '    host         pre-release environment host group.',
        '                     e.g:root@example.com,root1@example.com',

        'Actions',
        ('@init', 'init fabric file'),
        '',
        'Options:',
        # ('--dir-name:', 'set config directory name,default is `./config/cabric`'),
        # ('--fabfile:', 'set fabfile name,default is `fabfile`'),
        ('--debug', 'debug flag'),
        ('--help', 'print help document', '-h'),
    ))

    if a.options.get('--help'):
        print(a)
        return

    try:
        hosts = a.argv[1].split(',')
    except:
        hosts = ''

    # config_name = a.options.get('--dir-name') or 'config'
    config_name = 'config'
    # fabfile_name = a.options.get('--fabfile') or 'fabfile'
    fabfile_name = 'fabfile'

    root = os.path.join(os.getcwd(), config_name)

    if a.actions.get('init'):
        init_fabric(hosts, root, fabfile_name)
        return
    else:
        print(a)

    pass

if __name__ == '__main__':
    main()
    pass


text:
Home

Games For Sale

About us


text:
namespace Hanoi.Xmpp.InstantMessaging.PersonalEventing
{
    public sealed class MessageEvent : Event
    {
        public MessageEvent(Message message)
        {
            Message = message;
        }

        public Message Message { get; private set; }
    }
}


text:
require 'spec_helper'

describe SlackBotManager::Config do
  describe '#configure' do
    before do
      SlackBotManager.configure do |config|
        config.verbose = true
      end
    end

    after do
      SlackBotManager::Config.reset
    end

    it 'sets verbose mode' do
      expect(SlackBotManager.config.verbose).to eq true
    end
  end
end


text:
namespace OpenIddict.Sandbox.AspNetCore.Server.Services;

public interface IEmailSender
{
    Task SendEmailAsync(string email, string subject, string message);
}


text:
"""
Django settings for picha project.

Generated by 'django-admin startproject' using Django 1.8.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#^s0#&_q5yj$87lq15!9$gy=v9_a0ia$&abey@4+&lif%&-7c@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # custom apps
    'photos',
    'feedback',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'picha.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'picha.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Nairobi'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'

# Emails
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
DEFAULT_FROM_EMAIL = 'Picha <picha@example.com>'

# CELERY
BROKER_URL = 'redis://localhost:6379/8'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/8'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Africa/Nairobi'


text:
'use strict';

import {EventEmitter} from 'events';
import {ChildProcess, exec} from 'child_process';
import {request} from 'http';
import {dirname} from 'path';
import {ReadLine, createInterface} from 'readline';
import omnisharpLauncher from './omnisharpServerLauncher';
import {Disposable, CancellationToken, OutputChannel, workspace, window} from 'vscode';
import {ErrorMessage, UnresolvedDependenciesMessage, MSBuildProjectDiagnostics, ProjectInformationResponse} from './protocol';
import getLaunchTargets, {LaunchTarget} from './launchTargetFinder';

enum ServerState {
	Starting,
	Started,
	Stopped
}

interface Request {
	path: string;
	data?: any;
	onSuccess: Function;
	onError: Function;
	_enqueued: number;
}

export abstract class OmnisharpServer {

	private _eventBus = new EventEmitter();
	private _start: Promise<void>;
	private _state: ServerState = ServerState.Stopped;
	private _solutionPath: string;
	private _queue: Request[] = [];
	private _isProcessingQueue = false;
	private _channel: OutputChannel;

	protected _serverProcess: ChildProcess;
	protected _extraArgv: string[];

	constructor() {
		this._extraArgv = [];
		this._channel = window.createOutputChannel('OmniSharp Log');
	}

	public isRunning(): boolean {
		return this._state === ServerState.Started;
	}

	private _getState(): ServerState {
		return this._state;
	}

	private _setState(value: ServerState) : void {
		if (typeof value !== 'undefined' && value !== this._state) {
			this._state = value;
			this._fireEvent('stateChanged', this._state);
		}
	}

	public getSolutionPathOrFolder(): string {
		return this._solutionPath;
	}

	public getChannel(): vscode.OutputChannel {
		return this._channel;
	}

	public onStdout(listener: (e: string) => any, thisArg?: any) {
		return this._addListener('stdout', listener, thisArg);
	}

	public onStderr(listener: (e: string) => any, thisArg?: any) {
		return this._addListener('stderr', listener, thisArg);
	}

	public onError(listener: (e: ErrorMessage) => any, thisArg?: any) {
		return this._addListener('Error', listener, thisArg);
	}

	public onServerError(listener: (err: any) => any, thisArg?: any) {
		return this._addListener('ServerError', listener, thisArg);
	}

	public onUnresolvedDependencies(listener: (e: UnresolvedDependenciesMessage) => any, thisArg?:any) {
		return this._addListener('UnresolvedDependencies', listener, thisArg);
	}

	public onBeforePackageRestore(listener: () => any, thisArg?: any) {
		return this._addListener('PackageRestoreStarted', listener, thisArg);
	}

	public onPackageRestore(listener: () => any, thisArg?: any) {
		return this._addListener('PackageRestoreFinished', listener, thisArg);
	}

	public onProjectChange(listener: (e: ProjectInformationResponse) => any, thisArg?: any) {
		return this._addListener('ProjectChanged', listener, thisArg);
	}

	public onProjectAdded(listener: (e: ProjectInformationResponse) => any, thisArg?: any) {
		return this._addListener('ProjectAdded', listener, thisArg);
	}

	public onProjectRemoved(listener: (e: ProjectInformationResponse) => any, thisArg?: any) {
		return this._addListener('ProjectRemoved', listener, thisArg);
	}

	public onMsBuildProjectDiagnostics(listener: (e: MSBuildProjectDiagnostics) => any, thisArg?: any) {
		return this._addListener('MsBuildProjectDiagnostics', listener, thisArg);
	}

	public onBeforeServerStart(listener: (e:string) => any) {
		return this._addListener('BeforeServerStart', listener);
	}

	public onServerStart(listener: (e: string) => any) {
		return this._addListener('ServerStart', listener);
	}

	public onServerStop(listener: () => any) {
		return this._addListener('ServerStop', listener);
	}

	public onMultipleLaunchTargets(listener: (targets: LaunchTarget[]) => any, thisArg?: any) {
		return this._addListener('server:MultipleLaunchTargets', listener, thisArg);
	}

	public onOmnisharpStart(listener: () => any) {
		return this._addListener('started', listener);
	}

	private _addListener(event: string, listener: (e: any) => any, thisArg?: any): Disposable {
		listener = thisArg ? listener.bind(thisArg) : listener;
		this._eventBus.addListener(event, listener);
		return new Disposable(() => this._eventBus.removeListener(event, listener));
	}

	protected _fireEvent(event: string, args: any): void {
		this._eventBus.emit(event, args);
	}

	public start(solutionPath: string): Promise<void> {
		if (!this._start) {
			this._start = this._doStart(solutionPath);
		}
		return this._start;
	}

	private _doStart(solutionPath: string): Promise<void> {

		this._setState(ServerState.Starting);
		this._solutionPath = solutionPath;

		var cwd = dirname(solutionPath),
			argv = ['-s', solutionPath, '--hostPID', process.pid.toString(), 'dnx:enablePackageRestore=false'].concat(this._extraArgv);

		this._fireEvent('stdout', `[INFO] Starting OmniSharp at '${solutionPath}'...\n`);
		this._fireEvent('BeforeServerStart', solutionPath);

		return omnisharpLauncher(cwd, argv).then(value => {
			this._serverProcess = value.process;
			this._fireEvent('stdout', `[INFO] Started OmniSharp from '${value.command}' with process id ${value.process.pid}...\n`);
			return this._doConnect();
		}).then(_ => {
			this._fireEvent('ServerStart', solutionPath);
			this._setState(ServerState.Started);
			this._processQueue();
		}, err => {
			this._fireEvent('ServerError', err);
			throw err;
		});
	}

	protected abstract _doConnect(): Promise<OmnisharpServer>;

	public stop(): Promise<void> {

		var ret: Promise<OmnisharpServer>;

		if (!this._serverProcess) {
			// nothing to kill
			ret = Promise.resolve(undefined);

		} else if (/^win/.test(process.platform)) {
	        // when killing a process in windows its child
	        // processes are *not* killed but become root
	        // processes. Therefore we use TASKKILL.EXE
			ret = new Promise<OmnisharpServer>((resolve, reject) => {
				var killer = exec(`taskkill /F /T /PID ${this._serverProcess.pid}`, function (err, stdout, stderr) {
					if (err) {
						return reject(err);
					}
				});
				killer.on('exit', resolve);
				killer.on('error', reject);
			});
		} else {
			this._serverProcess.kill('SIGTERM');
			ret = Promise.resolve(undefined);
		}
		return ret.then(_ => {
			this._start = null;
			this._serverProcess = null;
			this._setState(ServerState.Stopped);
			this._fireEvent('ServerStop', this);
			return;
		});
	}

	public restart(solutionPath: string = this._solutionPath): Promise<void> {
		if (solutionPath) {
			return this.stop().then(() => {
				this.start(solutionPath)
			});
		}
	}

	public autoStart(preferredPath:string): Thenable<void> {
		return getLaunchTargets().then(targets => {
			if (targets.length === 0) {
				return new Promise<void>((resolve, reject) => {
					// 1st watch for files
					let watcher = workspace.createFileSystemWatcher('{**/*.sln,**/project.json}', false, true, true);
					watcher.onDidCreate(uri => {
						watcher.dispose();
						resolve();
					});
				}).then(() => {
					// 2nd try again
					return this.autoStart(preferredPath);
				});
			}

			if (targets.length > 1) {

				for (let target of targets) {
					if (target.target.fsPath === preferredPath) {
						// start preferred path
						return this.restart(preferredPath);
					}
				}

				this._fireEvent('server:MultipleLaunchTargets', targets);
				return Promise.reject<void>(undefined);
			}

			// just start
			return this.restart(targets[0].target.fsPath);
		});
	}

	public makeRequest<R>(path: string, data?: any, token?: CancellationToken): Promise<R> {

		if (this._getState() !== ServerState.Started) {
			return Promise.reject<R>('server has been stopped or not started');
		}

		let request: Request;
		let promise = new Promise<any>((resolve, reject) => {
			request = {
				path,
				data,
				onSuccess: resolve,
				onError: reject,
				_enqueued: Date.now()
			};
			this._queue.push(request);
			// this._statOnRequestStart(request);
			if (this._getState() === ServerState.Started && !this._isProcessingQueue) {
				this._processQueue();
			}
		});

		if (token) {
			token.onCancellationRequested(() => {
				let idx = this._queue.indexOf(request);
				if (idx !== -1) {
					this._queue.splice(idx, 1);
					let err = new Error('Canceled');
					err.message = 'Canceled';
					request.onError(err);
				}
			});
		}

		return promise;
	}

	private _processQueue(): void {

		if (this._queue.length === 0) {
			// nothing to do
			this._isProcessingQueue = false;
			return;
		}

		// signal that we are working on it
		this._isProcessingQueue = true;

		// send next request and recurse when done
		var thisRequest = this._queue.shift();
		this._makeNextRequest(thisRequest.path, thisRequest.data).then(value => {
			thisRequest.onSuccess(value);
			this._processQueue();
			// this._statOnRequestEnd(thisRequest, true);
		}, err => {
			thisRequest.onError(err);
			this._processQueue();
			// this._statOnRequestEnd(thisRequest, false);
		}).catch(err => {
			console.error(err);
			this._processQueue();
		});
	}

	protected abstract _makeNextRequest(path: string, data: any): Promise<any>;

	// private _statOnRequestStart(request: Request): void {
	// 	console.log(`[DEBUG] *enqueuing* request '${request.path}' (queue size is ${this._queue.length})\n`);
	// }

	// private _statOnRequestEnd(request: Request, successfully: boolean): void {
	// 	var duration = Date.now() - request._enqueued,
	// 		state = successfully ? 'successfully' : 'with errors';

	// 	console.log(`[DEBUG] request '${request.path}' finished *${state}* after ${duration}ms\n`);
	// }
}

namespace WireProtocol {

	export interface Packet {
		Type: string;
		Seq: number;
	}

	export interface RequestPacket extends Packet {
		Command: string;
		Arguments: any;
	}

	export interface ResponsePacket extends Packet {
		Command: string;
		Request_seq: number;
		Running: boolean;
		Success: boolean;
		Message: string;
		Body: any;
	}

	export interface EventPacket extends Packet {
		Event: string;
		Body: any;
	}
}

export class StdioOmnisharpServer extends OmnisharpServer {

	private static _seqPool = 1;
	private static StartupTimeout = 1000 * 60;
	private static ResponsePacketTimeout = 1000 * 60 * 15; // helps debugging

	private _rl: ReadLine;
	private _activeRequest: { [seq: number]: { onSuccess: Function; onError: Function; } } = Object.create(null);
	private _callOnStop: Function[] = [];

	constructor() {
		super();

		// extra argv
		this._extraArgv.push('--stdio');
	}

	public stop(): Promise<void> {
		while (this._callOnStop.length) {
			this._callOnStop.pop()();
		}
		return super.stop();
	}

	protected _doConnect(): Promise<OmnisharpServer> {

		this._serverProcess.stderr.on('data', (data: any) => this._fireEvent('stderr', String(data)));

		this._rl = createInterface({
			input: this._serverProcess.stdout,
			output: this._serverProcess.stdin,
			terminal: false
		});

		var p = new Promise<OmnisharpServer>((resolve, reject) => {
			var listener: Disposable;

			// timeout logic
			var handle = setTimeout(() => {
				listener && listener.dispose();
				reject(new Error('Failed to start OmniSharp'));
			}, StdioOmnisharpServer.StartupTimeout);

			// handle started-event
			listener = this.onOmnisharpStart(() => {
				listener && listener.dispose();
				clearTimeout(handle);
				resolve(this);
			});
		});

		this._startListening();

		return p;
	}

	private _startListening(): void {

		var onLineReceived = (line: string) => {
			if (line[0] !== '{') {
				this._fireEvent('stdout', `${line}\n`);
				return;
			}

			var packet: WireProtocol.Packet;
			try {
				packet = JSON.parse(line);
			} catch (e) {
				// not json
				return;
			}

			if (!packet.Type) {
				// bogous packet
				return;
			}

			switch (packet.Type) {
				case 'response':
					this._handleResponsePacket(<WireProtocol.ResponsePacket> packet);
					break;
				case 'event':
					this._handleEventPacket(<WireProtocol.EventPacket> packet);
					break;
				default:
					console.warn('unknown packet: ', packet);
					break;
			}
		};
		this._rl.addListener('line', onLineReceived);
		this._callOnStop.push(() => this._rl.removeListener('line', onLineReceived));
	}

	private _handleResponsePacket(packet: WireProtocol.ResponsePacket): void {

		var requestSeq = packet.Request_seq,
			entry = this._activeRequest[requestSeq];

		if (!entry) {
			console.warn('Received a response WITHOUT a request', packet);
			return;
		}

		delete this._activeRequest[requestSeq];

		if (packet.Success) {
			entry.onSuccess(packet.Body);
		} else {
			entry.onError(packet.Message || packet.Body);
		}
	}

	private _handleEventPacket(packet: WireProtocol.EventPacket): void {

		if (packet.Event === 'log') {
			// handle log events
			var entry = <{ LogLevel: string; Name: string; Message: string; }> packet.Body;
			this._fireEvent('stdout', `[${entry.LogLevel}:${entry.Name}] ${entry.Message}\n`);
			return;
		} else {
			// fwd all other events
			this._fireEvent(packet.Event, packet.Body);
		}
	}

	protected _makeNextRequest(path: string, data: any): Promise<any> {

		var thisRequestPacket: WireProtocol.RequestPacket = {
			Type: 'request',
			Seq: StdioOmnisharpServer._seqPool++,
			Command: path,
			Arguments: data
		};

		return new Promise<any>((c, e) => {

			this._activeRequest[thisRequestPacket.Seq] = {
				onSuccess: c,
				onError: e
			};

			this._serverProcess.stdin.write(JSON.stringify(thisRequestPacket) + '\n');
		});
	}
}


text:
package com.amazonaws.services.elasticmapreduce.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * ConfigurationMarshaller
 */
public class ConfigurationJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(Configuration configuration,
            SdkJsonGenerator jsonGenerator) {
        if (configuration == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (configuration.getClassification() != null) {
                jsonGenerator.writeFieldName("Classification").writeValue(
                        configuration.getClassification());
            }

            com.amazonaws.internal.SdkInternalList<Configuration> configurationsList = (com.amazonaws.internal.SdkInternalList<Configuration>) configuration
                    .getConfigurations();
            if (!configurationsList.isEmpty()
                    || !configurationsList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("Configurations");
                jsonGenerator.writeStartArray();
                for (Configuration configurationsListValue : configurationsList) {
                    if (configurationsListValue != null) {

                        ConfigurationJsonMarshaller.getInstance().marshall(
                                configurationsListValue, jsonGenerator);
                    }
                }
                jsonGenerator.writeEndArray();
            }

            com.amazonaws.internal.SdkInternalMap<String, String> propertiesMap = (com.amazonaws.internal.SdkInternalMap<String, String>) configuration
                    .getProperties();
            if (!propertiesMap.isEmpty() || !propertiesMap.isAutoConstruct()) {
                jsonGenerator.writeFieldName("Properties");
                jsonGenerator.writeStartObject();

                for (Map.Entry<String, String> propertiesMapValue : propertiesMap
                        .entrySet()) {
                    if (propertiesMapValue.getValue() != null) {
                        jsonGenerator.writeFieldName(propertiesMapValue
                                .getKey());

                        jsonGenerator.writeValue(propertiesMapValue.getValue());
                    }
                }
                jsonGenerator.writeEndObject();
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ConfigurationJsonMarshaller instance;

    public static ConfigurationJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ConfigurationJsonMarshaller();
        return instance;
    }

}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Data.Services.Providers
{
  sealed public partial class ResourceAssociationSet
  {
    #region Methods and constructors
    public ResourceAssociationSet(string name, ResourceAssociationSetEnd end1, ResourceAssociationSetEnd end2)
    {
      Contract.Requires(!string.IsNullOrEmpty(name));
      Contract.Requires(end1 != null);
      Contract.Requires(end2 != null);
    }
    #endregion

    #region Properties and indexers
    public ResourceAssociationSetEnd End1
    {
      get
      {
        Contract.Ensures(Contract.Result<ResourceAssociationSetEnd>() != null);

        return default(ResourceAssociationSetEnd);
      }
    }

    public ResourceAssociationSetEnd End2
    {
      get
      {
        Contract.Ensures(Contract.Result<ResourceAssociationSetEnd>() != null);

        return default(ResourceAssociationSetEnd);
      }
    }

    public string Name
    {
      get
      {
        Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

        return default(string);
      }
    }
    #endregion
  }
}


text:
<?php

namespace Composer\IO;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

/**
 * The Input/Output helper.
 *
 * @author François Pluchino <francois.pluchino@opendisplay.com>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class ConsoleIO extends BaseIO
{
    protected $input;
    protected $output;
    protected $helperSet;
    protected $lastMessage;
    protected $lastMessageErr;
    private $startTime;
    private $verbosityMap;

    /**
     * Constructor.
     *
     * @param InputInterface  $input     The input instance
     * @param OutputInterface $output    The output instance
     * @param HelperSet       $helperSet The helperSet instance
     */
    public function __construct(InputInterface $input, OutputInterface $output, HelperSet $helperSet)
    {
        $this->input = $input;
        $this->output = $output;
        $this->helperSet = $helperSet;
        $this->verbosityMap = array(
            self::QUIET => OutputInterface::VERBOSITY_QUIET,
            self::NORMAL => OutputInterface::VERBOSITY_NORMAL,
            self::VERBOSE => OutputInterface::VERBOSITY_VERBOSE,
            self::VERY_VERBOSE => OutputInterface::VERBOSITY_VERY_VERBOSE,
            self::DEBUG => OutputInterface::VERBOSITY_DEBUG,
        );
    }

    public function enableDebugging($startTime)
    {
        $this->startTime = $startTime;
    }

    /**
     * {@inheritDoc}
     */
    public function isInteractive()
    {
        return $this->input->isInteractive();
    }

    /**
     * {@inheritDoc}
     */
    public function isDecorated()
    {
        return $this->output->isDecorated();
    }

    /**
     * {@inheritDoc}
     */
    public function isVerbose()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE;
    }

    /**
     * {@inheritDoc}
     */
    public function isVeryVerbose()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE;
    }

    /**
     * {@inheritDoc}
     */
    public function isDebug()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG;
    }

    /**
     * {@inheritDoc}
     */
    public function write($messages, $newline = true, $verbosity = self::NORMAL)
    {
        $this->doWrite($messages, $newline, false, $verbosity);
    }

    /**
     * {@inheritDoc}
     */
    public function writeError($messages, $newline = true, $verbosity = self::NORMAL)
    {
        $this->doWrite($messages, $newline, true, $verbosity);
    }

    /**
     * @param array|string $messages
     * @param bool         $newline
     * @param bool         $stderr
     * @param int          $verbosity
     */
    private function doWrite($messages, $newline, $stderr, $verbosity)
    {
        $sfVerbosity = $this->verbosityMap[$verbosity];
        if ($sfVerbosity > $this->output->getVerbosity()) {
            return;
        }

        if (null !== $this->startTime) {
            $memoryUsage = memory_get_usage() / 1024 / 1024;
            $timeSpent = microtime(true) - $this->startTime;
            $messages = array_map(function ($message) use ($memoryUsage, $timeSpent) {
                return sprintf('[%.1fMB/%.2fs] %s', $memoryUsage, $timeSpent, $message);
            }, (array) $messages);
        }

        if (true === $stderr && $this->output instanceof ConsoleOutputInterface) {
            $this->output->getErrorOutput()->write($messages, $newline, $sfVerbosity);
            $this->lastMessageErr = join($newline ? "\n" : '', (array) $messages);

            return;
        }

        $this->output->write($messages, $newline, $sfVerbosity);
        $this->lastMessage = join($newline ? "\n" : '', (array) $messages);
    }

    /**
     * {@inheritDoc}
     */
    public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL)
    {
        $this->doOverwrite($messages, $newline, $size, false, $verbosity);
    }

    /**
     * {@inheritDoc}
     */
    public function overwriteError($messages, $newline = true, $size = null, $verbosity = self::NORMAL)
    {
        $this->doOverwrite($messages, $newline, $size, true, $verbosity);
    }

    /**
     * @param array|string $messages
     * @param bool         $newline
     * @param int|null     $size
     * @param bool         $stderr
     * @param int          $verbosity
     */
    private function doOverwrite($messages, $newline, $size, $stderr, $verbosity)
    {
        // messages can be an array, let's convert it to string anyway
        $messages = join($newline ? "\n" : '', (array) $messages);

        // since overwrite is supposed to overwrite last message...
        if (!isset($size)) {
            // removing possible formatting of lastMessage with strip_tags
            $size = strlen(strip_tags($stderr ? $this->lastMessageErr : $this->lastMessage));
        }
        // ...let's fill its length with backspaces
        $this->doWrite(str_repeat("\x08", $size), false, $stderr, $verbosity);

        // write the new message
        $this->doWrite($messages, false, $stderr, $verbosity);

        $fill = $size - strlen(strip_tags($messages));
        if ($fill > 0) {
            // whitespace whatever has left
            $this->doWrite(str_repeat(' ', $fill), false, $stderr, $verbosity);
            // move the cursor back
            $this->doWrite(str_repeat("\x08", $fill), false, $stderr, $verbosity);
        }

        if ($newline) {
            $this->doWrite('', true, $stderr, $verbosity);
        }

        if ($stderr) {
            $this->lastMessageErr = $messages;
        } else {
            $this->lastMessage = $messages;
        }
    }

    /**
     * {@inheritDoc}
     */
    public function ask($question, $default = null)
    {
        $output = $this->output;

        if ($output instanceof ConsoleOutputInterface) {
            $output = $output->getErrorOutput();
        }

        /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
        $helper = $this->helperSet->get('question');
        $question = new Question($question, $default);

        return $helper->ask($this->input, $output, $question);
    }

    /**
     * {@inheritDoc}
     */
    public function askConfirmation($question, $default = true)
    {
        $output = $this->output;

        if ($output instanceof ConsoleOutputInterface) {
            $output = $output->getErrorOutput();
        }

        /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
        $helper = $this->helperSet->get('question');
        $question = new ConfirmationQuestion($question, $default);

        return $helper->ask($this->input, $output, $question);
    }

    /**
     * {@inheritDoc}
     */
    public function askAndValidate($question, $validator, $attempts = null, $default = null)
    {
        $output = $this->output;

        if ($output instanceof ConsoleOutputInterface) {
            $output = $output->getErrorOutput();
        }

        /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
        $helper = $this->helperSet->get('question');
        $question = new Question($question, $default);
        $question->setValidator($validator);
        $question->setMaxAttempts($attempts);

        return $helper->ask($this->input, $output, $question);
    }

    /**
     * {@inheritDoc}
     */
    public function askAndHideAnswer($question)
    {
        $this->writeError($question, false);

        return \Seld\CliPrompt\CliPrompt::hiddenPrompt(true);
    }
}


text:
"""
usage: upgrade.py [-h] [--crs] [--geoip] [--cron] [--quiet]

Install upgrades to the ModSecurity CRS and/or GeoIP country database.

Run util/upgrade.py -h for explanation and examples.
"""

from __future__ import unicode_literals
from __future__ import print_function
import argparse
import os
import random
import subprocess
from subprocess import check_output, STDOUT, CalledProcessError
import sys
import time
import zlib

try:
    from urllib.request import urlopen # Python 3
except ImportError:
    from urllib2 import urlopen        # Python 2

def upgrade_crs(crs_directory, quiet):
    """Upgrade the CRS using Git. Assumes the CRS is a local Git repo."""

    git_directory = os.path.join(crs_directory, '.git')
    if not os.path.isdir(git_directory):
        raise Exception('Not a git repository: ' + crs_directory)

    # Do a git 'git pull'
    os.chdir(crs_directory)
    gitcmd = "git pull origin HEAD --ff-only"
    try:
        git_output = check_output(gitcmd, stderr=STDOUT, shell=True)
        returncode = 0
    except CalledProcessError as ex:
        git_output = ex.output
        returncode = ex.returncode
    if returncode != 0:
        raise Exception ("Git pull failed! Error: " + git_output)
    if not quiet:
        print('crs:')
        print(git_output.decode('utf-8'))

    # Could be improved. We're not supposed to parse 'git pull' output.
    changed = False if b'Already up-to-date' in git_output else True
    return changed

def upgrade_geoip(crs_directory, quiet):
    """
    Upgrade MaxMind GeoIP database by fetching from maxmind.com.
    Download page: http://dev.maxmind.com/geoip/legacy/geolite/
    This product includes GeoLite data created by MaxMind, available from
    http://www.maxmind.com.
    """
    url = 'https://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz'
    db_directory = os.path.join(crs_directory, 'util', 'geo-location')
    db_name = os.path.join(db_directory, 'GeoIP.dat')

    if not os.path.isdir(db_directory):
        raise Exception('Database directory not found: ' + db_directory)

    # Fetch GeoIP.dat.gz from HTTPS into memory
    response = urlopen(url)
    db_gzipped = response.read()
    if not db_gzipped:
        raise Exception('Empty response from ' + url)

    # Uncompress gzip stream
    db_contents = zlib.decompress(db_gzipped, zlib.MAX_WBITS | 32)

    # Check if database content is changed from existing file
    # If not changed, return the status to the caller and skip overwriting
    old_db_contents = ""
    if os.path.isfile(db_name):
        with open(db_name, 'rb') as db_file:
            old_db_contents = db_file.read()

    # zlib returns a byte string, therefore we must cast old_db_contents to str
    old_db_contents = str(old_db_contents)
    if db_contents == old_db_contents:
        if not quiet:
            print('geoip:')
            print('Already up-to-date.')
        return False

    # Write uncompressed stream to tempfile
    tmp_file_name = db_name + '.tmp'
    with open(tmp_file_name, 'wb') as tmp_file:
        tmp_file.write(db_contents)

    # Atomically replace GeoIP.dat
    os.rename(tmp_file_name, db_name)

    if not quiet:
        print('geoip:')
        print('Downloaded ' + db_name + '.')
    return True

def parse_args():
    """
    Parse our inputs including help and support messages to guide the user.
    Returns an argparse object that can be used to access results
    """
    # Our constants for help
    returns_val = """
If you schedule this script via cron or similar, please add the --cron option
to insert a random delay and prevent hammering the upgrade servers.

Return value:
  Success if updates were applied
  Failure if no updates were available or an error occurred
    """
    examples = """
Example:
  util/upgrade.py --crs
  util/upgrade.py --geoip
  util/upgrade.py --crs --geoip
  util/upgrade.py --crs --quiet && apachectl configtest && apachectl restart
    """

    # When changing command line parameters, please remind to update:
    # (1) the __doc__ comment, (2) the examples above.
    parser = argparse.ArgumentParser(
        description = 'Install upgrades to the ModSecurity CRS and/or GeoIP country database.',
        epilog = returns_val+examples,
        formatter_class = argparse.RawTextHelpFormatter)
    parser.add_argument('--crs',
        action = 'store_true',
        help = 'Upgrade the CRS using Git')
    parser.add_argument('--geoip',
        action = 'store_true',
        help = 'Upgrade the MaxMind GeoLite Country database from maxmind.com')
    parser.add_argument('--cron',
        action = 'store_true',
        help = 'Randomly sleep 0-3 minutes before upgrading; use from cron')
    parser.add_argument('--quiet',
        action = 'store_true',
        help = 'Be quiet unless an error occurred')
    args = parser.parse_args()
    return args

def main():
    """
    The main function that handles kicking off all the functionality.
    It returns to the system 1 if failed or no updates were done, otherwise 0.
    """

    _max_sleep_mins = 3
    args = parse_args()
    if not (args.crs or args.geoip):
        print(__doc__)
        sys.exit(1)

    crs_directory = os.path.realpath(os.path.join(sys.path[0], '..'))
    if not os.path.isdir(crs_directory):
        raise Exception('Cannot determine CRS directory: ' + crs_directory)

    # If --cron supplied, sleep 0-3 minutes to be nice to upstream servers
    if args.cron:
        secs = random.randint(0, _max_sleep_mins*60)
        time.sleep(secs)

    changed = False

    if args.crs:
        try:
            crs_changed = upgrade_crs(crs_directory, args.quiet)
            changed = changed or crs_changed
        except Exception as e:
            print('crs:', e)

    if args.geoip:
        try:
            geoip_changed = upgrade_geoip(crs_directory, args.quiet)
            changed = changed or geoip_changed
        except Exception as e:
            print('geoip:', e)

    # Set process error value: if something was upgraded, return success
    # This allows idioms like: upgrade.py --crs && apachectl restart
    sys.exit(0 if changed else 1)

if __name__ == "__main__":
    main()


text:
            <?php
  if (!empty($this->session->flashdata('err_msg'))) {
    echo '
×

'.$this->session->flashdata('err_msg').'

';
  } elseif (!empty($this->session->flashdata('scss_msg'))) {
    echo '
×

'. $this->session->flashdata('scss_msg').'

';
  } ?>

Read Comment

            <?php if(isset($data)){ ?>
            <?php foreach ($data as $datas) { ?>

<?php echo $datas->time_publish; ?>

From : <?php echo $datas->nama.' ('.$datas->email.')'; ?>

In        : <?php echo $datas->title ?>

                <?php echo $datas->comment;?>

                <input class="form-control" disabled value="<?php echo $datas->nama; ?>">

              <?php echo form_open('do_reply/'.$datas->hash);  ?>

                    <textarea id="compose-textarea" name="reply" disabled="true" class="form-control" style="height: 300px">
                      <?php echo $datas->reply; ?>
                    </textarea>

              <?php echo form_close(); ?>
              <?php }} ?>


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic

    Friend MustInherit Class BlockBaseBinder
        Inherits BlockBaseBinder(Of LocalSymbol)

        Public Sub New(enclosing As Binder)
            MyBase.New(enclosing)
        End Sub
    End Class

    Friend MustInherit Class BlockBaseBinder(Of T As Symbol)
        Inherits Binder

        Public Sub New(enclosing As Binder)
            MyBase.New(enclosing)
        End Sub

        Friend MustOverride ReadOnly Property Locals As ImmutableArray(Of T)
        Private _lazyLocalsMap As Dictionary(Of String, T)

        Private ReadOnly Property LocalsMap As Dictionary(Of String, T)
            Get
                If Me._lazyLocalsMap Is Nothing AndAlso Not Me.Locals.IsEmpty Then
                    Interlocked.CompareExchange(Me._lazyLocalsMap, BuildMap(Me.Locals), Nothing)
                End If
                Return Me._lazyLocalsMap
            End Get
        End Property

        Private Function BuildMap(locals As ImmutableArray(Of T)) As Dictionary(Of String, T)
            Debug.Assert(Not locals.IsEmpty)

            Dim map = New Dictionary(Of String, T)(locals.Length, IdentifierComparison.Comparer)
            For Each local In locals
                If Not map.ContainsKey(local.Name) Then
                    map(local.Name) = local
                End If
            Next
            Return map
        End Function

        Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,
                                                      name As String,
                                                      arity As Integer,
                                                      options As LookupOptions,
                                                      originalBinder As Binder,
                                                      <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
            ' locals are always arity 0, and never types and namespaces.
            Dim locals = Me.Locals
            Dim localSymbol As T = Nothing
            If Not locals.IsEmpty AndAlso (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly Or LookupOptions.MustNotBeLocalOrParameter)) = 0 Then

                'with small lists linear search may be cheaper than dictionary.
                'TODO: 6 is sufficiently small, but may need tuning.
                If locals.Length < 6 Then
                    For Each localSymbol In locals
                        Dim symName = localSymbol.Name
                        If symName Is name OrElse (symName.Length = name.Length And IdentifierComparison.Equals(symName, name)) Then
                            lookupResult.SetFrom(CheckViability(localSymbol, arity, options, Nothing, useSiteDiagnostics))
                            Exit For
                        End If
                    Next
                Else
                    If Me.LocalsMap.TryGetValue(name, localSymbol) Then
                        lookupResult.SetFrom(CheckViability(localSymbol, arity, options, Nothing, useSiteDiagnostics))
                    End If
                End If
            End If

            Return
        End Sub

        Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,
                                                                    options As LookupOptions,
                                                                    originalBinder As Binder)
            Dim locals = Me.Locals
            If Not locals.IsEmpty AndAlso (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = 0 Then
                For Each localSymbol In locals
                    If originalBinder.CanAddLookupSymbolInfo(localSymbol, options, nameSet, Nothing) Then
                        nameSet.AddSymbol(localSymbol, localSymbol.Name, 0)
                    End If
                Next
            End If
        End Sub
    End Class
End Namespace


text:
Windows shell utility for centralised management of .NET assembly file version numbers.

Will support multiple solutions in one or more CVS repositories.

Integration with CI servers for build number increments is straightforward.

### Notes

Note: You will need to update the paths to the 1v Config directory to match the location of the 1v app folders in the following places:

D:\_git\gh-pu\1v\CI_Tools\1v\1v\Properties\Settings.settings -> productsVersionRootDir

D:\_git\gh-pu\1v\CI_Tools\CI_Config\ProductVersionNumbering\ProductVersionNumberingConfig.xml

Note: To use the 1v app to version your project files for Release builds you need to add the 1v build diretory to your SYSTEM PATH* and the following command line Pre-Build event to your project files:

IF NOT $(ConfigurationName) == Debug 1v "$(SolutionName)" "$(MSBuildProjectDirectory)" "$(MSBuildProjectExtension)"

* ( for development use your 1v bin\debug path, eg. "D:\_git\gh-pu\1v\CI_Tools\1v\1v\bin\Debug")

This will allow debug builds during development without assembly versions being updated and then on the build server the release build will result in the assemblyInfo version numbers being updated.


text:
title: markdown-menu
order: 0
---

[→ addon/components/markdown-menu.js](https://github.com/willviles/ember-cli-markdown-resolver/blob/master/addon/components/markdown-menu.js)

Ember CLI Markdown Resolver defines a `markdown-menu` component for creating nested menus from your markdown file trees and can be styled using your own css. It uses a `markdown-menu-item` component to loop through each level of nesting.

```hbs
<!-- templates/guides.hbs -->

{{markdown-menu title="My Markdown Menu" tree=model}}
{{outlet}}
```

##### Styles

[→ tests/dummy/app/styles/components/markdown/_menu.scss](https://github.com/willviles/ember-cli-markdown-resolver/blob/master/tests/dummy/app/styles/components/markdown/_menu.scss)

The simple menu on this page has been styled using the following css.

```css
.markdown-menu {
  .markdown-menu-title {
    font-weight: 800;
    font-size: 1.1em;
    text-transform: capitalize;
    margin-bottom: .75em;
  }
  & > ul {
    a {
      padding: .5em 0;
      &:hover {
        font-weight: 800;
      }
      &.active {
        color: red;
        font-weight: 800;
      }
    }
    ul {
      margin-left: 1em;
    }
  }
}

```


text:
/*******************************************************************************
Program:   Wake Forest University - Virginia Tech CTC Software
Id:        $Id$
Language:  C++
*******************************************************************************/

#ifndef __CTCPOLYPSET_H__
#define __CTCPOLYPSET_H__

#include <string>
#include <map>

#include "ctcPolyp.h"

using namespace std;

namespace ctc {

    /**
     * Holds a set of CTCPolyp objects.
     *
     * TODO:
     * <li/>Embed std::map<> rather than derive from std::map<>.
     */
    class CTCPolypSet : public map<string, CTCPolyp>
    {
    public:
        /**
         * Insert CTCPolyp object.
         * @param polyp  CTCPolyp object.
         * @return pointer to an inserted CTCPolyp object. NULL if failed.
         */
        CTCPolyp * insert(const CTCPolyp & polyp)
        {
            pair<CTCPolypSet::iterator, bool> p =
                    super::insert(make_pair(polyp.pid, polyp));

           return p.second? &(p.first->second) : NULL;
        }

        /**
         * Find teh CTCPolyp obj through the polyp id.
         * @param pid  polyp id.
         * @return pointer to the CTCPolyp obj. NULL if failed.
         */
        CTCPolyp * find(string pid)
        {
            CTCPolypSet::iterator  it = super::find(pid);
            if (it != this->end())
                return &(it->second);
            else
                return NULL;
        }

    private:
        typedef map<string, CTCPolyp> super;
    };

}

#endif


text:
<?php

/**
 * Abstract utility class for parsing binary files.
 *
 * Provides a library of methods to quickly navigate and extract various data
 * types (signed and unsigned integers, floating- and fixed-point numbers,
 * strings, etc.) from the file.
 *
 * File access is managed via a {@link Zend_Pdf_FileParserDataSource} object.
 * This allows the same parser code to work with many different data sources:
 * in-memory objects, filesystem files, etc.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_FileParser
{
  /**** Class Constants ****/

    /**
     * Little-endian byte order (0x04 0x03 0x02 0x01).
     */
    const BYTE_ORDER_LITTLE_ENDIAN = 0;

    /**
     * Big-endian byte order (0x01 0x02 0x03 0x04).
     */
    const BYTE_ORDER_BIG_ENDIAN    = 1;

  /**** Instance Variables ****/

    /**
     * Flag indicating that the file has passed a cursory validation check.
     * @var boolean
     */
    protected $_isScreened = false;

    /**
     * Flag indicating that the file has been sucessfully parsed.
     * @var boolean
     */
    protected $_isParsed = false;

    /**
     * Object representing the data source to be parsed.
     * @var Zend_Pdf_FileParserDataSource
     */
    protected $_dataSource = null;

  /**** Public Interface ****/

  /* Abstract Methods */

    /**
     * Performs a cursory check to verify that the binary file is in the expected
     * format. Intended to quickly weed out obviously bogus files.
     *
     * Must set $this->_isScreened to true if successful.
     *
     * @throws Zend_Pdf_Exception
     */
    abstract public function screen();

    /**
     * Reads and parses the complete binary file.
     *
     * Must set $this->_isParsed to true if successful.
     *
     * @throws Zend_Pdf_Exception
     */
    abstract public function parse();

  /* Object Lifecycle */

    /**
     * Object constructor.
     *
     * Verifies that the data source has been properly initialized.
     *
     * @param Zend_Pdf_FileParserDataSource $dataSource
     * @throws Zend_Pdf_Exception
     */
    public function __construct(Zend_Pdf_FileParserDataSource $dataSource)
    {
        if ($dataSource->getSize() == 0) {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('The data source has not been properly initialized',
                                         Zend_Pdf_Exception::BAD_DATA_SOURCE);
        }
        $this->_dataSource = $dataSource;
    }

    /**
     * Object destructor.
     *
     * Discards the data source object.
     */
    public function __destruct()
    {
        $this->_dataSource = null;
    }

  /* Accessors */

    /**
     * Returns true if the file has passed a cursory validation check.
     *
     * @return boolean
     */
    public function isScreened()
    {
        return $this->_isScreened;
    }

    /**
     * Returns true if the file has been successfully parsed.
     *
     * @return boolean
     */
    public function isParsed()
    {
        return $this->_isParsed;
    }

    /**
     * Returns the data source object representing the file being parsed.
     *
     * @return Zend_Pdf_FileParserDataSource
     */
    public function getDataSource()
    {
        return $this->_dataSource;
    }

  /* Primitive Methods */

    /**
     * Convenience wrapper for the data source object's moveToOffset() method.
     *
     * @param integer $offset Destination byte offset.
     * @throws Zend_Pdf_Exception
     */
    public function moveToOffset($offset)
    {
        $this->_dataSource->moveToOffset($offset);
    }

    public function getOffset() {
       return $this->_dataSource->getOffset();
    }

    public function getSize() {
       return $this->_dataSource->getSize();
    }

    /**
     * Convenience wrapper for the data source object's readBytes() method.
     *
     * @param integer $byteCount Number of bytes to read.
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public function readBytes($byteCount)
    {
        return $this->_dataSource->readBytes($byteCount);
    }

    /**
     * Convenience wrapper for the data source object's skipBytes() method.
     *
     * @param integer $byteCount Number of bytes to skip.
     * @throws Zend_Pdf_Exception
     */
    public function skipBytes($byteCount)
    {
        $this->_dataSource->skipBytes($byteCount);
    }

  /* Parser Methods */

    /**
     * Reads the signed integer value from the binary file at the current byte
     * offset.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * @param integer $size Size of integer in bytes: 1-4
     * @param integer $byteOrder (optional) Big- or little-endian byte order.
     *   Use the BYTE_ORDER_ constants defined in {@link Zend_Pdf_FileParser}.
     *   If omitted, uses big-endian.
     * @return integer
     * @throws Zend_Pdf_Exception
     */
    public function readInt($size, $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN)
    {
        if (($size < 1) || ($size > 4)) {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception("Invalid signed integer size: $size",
                                         Zend_Pdf_Exception::INVALID_INTEGER_SIZE);
        }
        $bytes = $this->_dataSource->readBytes($size);
        /* unpack() will not work for this method because it always works in
         * the host byte order for signed integers. It also does not allow for
         * variable integer sizes.
         */
        if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN) {
            $number = ord($bytes[0]);
            if (($number & 0x80) == 0x80) {
                /* This number is negative. Extract the positive equivalent.
                 */
                $number = (~ $number) & 0xff;
                for ($i = 1; $i < $size; $i++) {
                    $number = ($number << 8) | ((~ ord($bytes[$i])) & 0xff);
                }
                /* Now turn this back into a negative number by taking the
                 * two's complement (we didn't add one above so won't
                 * subtract it below). This works reliably on both 32- and
                 * 64-bit systems.
                 */
                $number = ~$number;
            } else {
                for ($i = 1; $i < $size; $i++) {
                    $number = ($number << 8) | ord($bytes[$i]);
                }
            }
        } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) {
            $number = ord($bytes[$size - 1]);
            if (($number & 0x80) == 0x80) {
                /* Negative number. See discussion above.
                 */
                $number = 0;
                for ($i = --$size; $i >= 0; $i--) {
                    $number |= ((~ ord($bytes[$i])) & 0xff) << ($i * 8);
                }
                $number = ~$number;
            } else {
                $number = 0;
                for ($i = --$size; $i >= 0; $i--) {
                    $number |= ord($bytes[$i]) << ($i * 8);
                }
            }
        } else {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception("Invalid byte order: $byteOrder",
                                         Zend_Pdf_Exception::INVALID_BYTE_ORDER);
        }
        return $number;
    }

    /**
     * Reads the unsigned integer value from the binary file at the current byte
     * offset.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * NOTE: If you ask for a 4-byte unsigned integer on a 32-bit machine, the
     * resulting value WILL BE SIGNED because PHP uses signed integers internally
     * for everything. To guarantee portability, be sure to use bitwise operators
     * operators on large unsigned integers!
     *
     * @param integer $size Size of integer in bytes: 1-4
     * @param integer $byteOrder (optional) Big- or little-endian byte order.
     *   Use the BYTE_ORDER_ constants defined in {@link Zend_Pdf_FileParser}.
     *   If omitted, uses big-endian.
     * @return integer
     * @throws Zend_Pdf_Exception
     */
    public function readUInt($size, $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN)
    {
        if (($size < 1) || ($size > 4)) {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception("Invalid unsigned integer size: $size",
                                         Zend_Pdf_Exception::INVALID_INTEGER_SIZE);
        }
        $bytes = $this->_dataSource->readBytes($size);
        /* unpack() is a bit heavyweight for this simple conversion. Just
         * work the bytes directly.
         */
        if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN) {
            $number = ord($bytes[0]);
            for ($i = 1; $i < $size; $i++) {
                $number = ($number << 8) | ord($bytes[$i]);
            }
        } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) {
            $number = 0;
            for ($i = --$size; $i >= 0; $i--) {
                $number |= ord($bytes[$i]) << ($i * 8);
            }
        } else {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception("Invalid byte order: $byteOrder",
                                         Zend_Pdf_Exception::INVALID_BYTE_ORDER);
        }
        return $number;
    }

    /**
     * Returns true if the specified bit is set in the integer bitfield.
     *
     * @param integer $bit Bit number to test (i.e. - 0-31)
     * @param integer $bitField
     * @return boolean
     */
    public function isBitSet($bit, $bitField)
    {
        $bitMask = 1 << $bit;
        $isSet = (($bitField & $bitMask) == $bitMask);
        return $isSet;
    }

    /**
     * Reads the signed fixed-point number from the binary file at the current
     * byte offset.
     *
     * Common fixed-point sizes are 2.14 and 16.16.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * @param integer $mantissaBits Number of bits in the mantissa
     * @param integer $fractionBits Number of bits in the fraction
     * @param integer $byteOrder (optional) Big- or little-endian byte order.
     *   Use the BYTE_ORDER_ constants defined in {@link Zend_Pdf_FileParser}.
     *   If omitted, uses big-endian.
     * @return float
     * @throws Zend_Pdf_Exception
     */
    public function readFixed($mantissaBits, $fractionBits,
                              $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN)
    {
        $bitsToRead = $mantissaBits + $fractionBits;
        if (($bitsToRead % 8) !== 0) {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Fixed-point numbers are whole bytes',
                                         Zend_Pdf_Exception::BAD_FIXED_POINT_SIZE);
        }
        $number = $this->readInt(($bitsToRead >> 3), $byteOrder) / (1 << $fractionBits);
        return $number;
    }

    /**
     * Reads the Unicode UTF-16-encoded string from the binary file at the
     * current byte offset.
     *
     * The byte order of the UTF-16 string must be specified. You must also
     * supply the desired resulting character set.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * @todo Consider changing $byteCount to a character count. They are not
     *   always equivalent (in the case of surrogates).
     * @todo Make $byteOrder optional if there is a byte-order mark (BOM) in the
     *   string being extracted.
     *
     * @param integer $byteCount Number of bytes (characters * 2) to return.
     * @param integer $byteOrder (optional) Big- or little-endian byte order.
     *   Use the BYTE_ORDER_ constants defined in {@link Zend_Pdf_FileParser}.
     *   If omitted, uses big-endian.
     * @param string $characterSet (optional) Desired resulting character set.
     *   You may use any character set supported by {@link iconv()}. If omitted,
     *   uses 'current locale'.
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public function readStringUTF16($byteCount,
                                    $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN,
                                    $characterSet = '')
    {
        if ($byteCount == 0) {
            return '';
        }
        $bytes = $this->_dataSource->readBytes($byteCount);
        if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_BIG_ENDIAN) {
            if ($characterSet == 'UTF-16BE') {
                return $bytes;
            }
            return iconv('UTF-16BE', $characterSet, $bytes);
        } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) {
            if ($characterSet == 'UTF-16LE') {
                return $bytes;
            }
            return iconv('UTF-16LE', $characterSet, $bytes);
        } else {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception("Invalid byte order: $byteOrder",
                                         Zend_Pdf_Exception::INVALID_BYTE_ORDER);
        }
    }

    /**
     * Reads the Mac Roman-encoded string from the binary file at the current
     * byte offset.
     *
     * You must supply the desired resulting character set.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * @param integer $byteCount Number of bytes (characters) to return.
     * @param string $characterSet (optional) Desired resulting character set.
     *   You may use any character set supported by {@link iconv()}. If omitted,
     *   uses 'current locale'.
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public function readStringMacRoman($byteCount, $characterSet = '')
    {
        if ($byteCount == 0) {
            return '';
        }
        $bytes = $this->_dataSource->readBytes($byteCount);
        if ($characterSet == 'MacRoman') {
            return $bytes;
        }
        return iconv('MacRoman', $characterSet, $bytes);
    }

    /**
     * Reads the Pascal string from the binary file at the current byte offset.
     *
     * The length of the Pascal string is determined by reading the length bytes
     * which preceed the character data. You must supply the desired resulting
     * character set.
     *
     * Advances the offset by the number of bytes read. Throws an exception if
     * an error occurs.
     *
     * @param string $characterSet (optional) Desired resulting character set.
     *   You may use any character set supported by {@link iconv()}. If omitted,
     *   uses 'current locale'.
     * @param integer $lengthBytes (optional) Number of bytes that make up the
     *   length. Default is 1.
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public function readStringPascal($characterSet = '', $lengthBytes = 1)
    {
        $byteCount = $this->readUInt($lengthBytes);
        if ($byteCount == 0) {
            return '';
        }
        $bytes = $this->_dataSource->readBytes($byteCount);
        if ($characterSet == 'ASCII') {
            return $bytes;
        }
        return iconv('ASCII', $characterSet, $bytes);
    }

}


text:
import sys
sys.path.append("gen-py")

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from excep import TradeHistory
from excep.ttypes import BadFish

trans = TSocket.TSocket("localhost", 9090)
trans = TTransport.TBufferedTransport(trans)
proto = TBinaryProtocol.TBinaryProtocol(trans)
client = TradeHistory.Client(proto)

try:
    trans.open()
    print("[Client] received: %f" % client.GetLastSale(sys.argv[1]))
except BadFish as bf:
    print("[Client] GetLastSale() call failed for fish: %s, error %d" % (bf.fish, bf.error_code))

trans.close()


text:
require 'spec_helper'
require 'mini_transformer'
require 'mini_transformer/key_list'

describe "KeyList" do
  context "Given a new KeyList" do
    it "should respond to all KeyList attributes" do
      @key_list = MiniTransformer::KeyList.new
      expect { @key_list.name }.to_not raise_error
      @key_list.respond_to?(:name).should be_true
      @key_list.respond_to?(:key_label).should be_true
      @key_list.respond_to?(:description_label).should be_true
      @key_list.respond_to?(:entries).should be_true
    end
  end
end