text:
/*
 * IpcMessageTest.cpp - boost unit test cases for IpcMessage class
 *
 *  Created on: Jan 27, 2015
 *      Author: Tim Nicholls, STFC Application Engineering Group
 */

#include <boost/test/unit_test.hpp>

#include <time.h>
#include <exception>

#include "IpcMessage.h"
#include "gettime.h"

BOOST_AUTO_TEST_SUITE(IpcMessageUnitTest);

BOOST_AUTO_TEST_CASE( ValidIpcMessageFromString )
{
  // Instantiate a valid message from a JSON string
  OdinData::IpcMessage validMsgFromString("{\"msg_type\":\"cmd\", "
                                              "\"msg_val\":\"status\", "
                                              "\"timestamp\" : \"2015-01-27T15:26:01.123456\", "
                                              "\"params\" : {"
                                              "    \"paramInt\" : 1234, "
                                              "    \"paramStr\" : \"testParam\", "
                                              "    \"paramDouble\" : 3.1415 "
                                              "  } "
                                              "}");

  // Check the message is indeed valid
  BOOST_CHECK_EQUAL(validMsgFromString.is_valid(), true);

  // Check that all attributes are as expected
  BOOST_CHECK_EQUAL(validMsgFromString.get_msg_type(), OdinData::IpcMessage::MsgTypeCmd);
  BOOST_CHECK_EQUAL(validMsgFromString.get_msg_val(), OdinData::IpcMessage::MsgValCmdStatus);
  BOOST_CHECK_EQUAL(validMsgFromString.get_msg_timestamp(), "2015-01-27T15:26:01.123456");
  struct tm timestamp_tm = validMsgFromString.get_msg_datetime();
  BOOST_CHECK_EQUAL(asctime(&timestamp_tm), "Tue Jan 27 15:26:01 2015\n");

  // Check that all parameters are as expected
  BOOST_CHECK_EQUAL(validMsgFromString.get_param<int>("paramInt"), 1234);
  BOOST_CHECK_EQUAL(validMsgFromString.get_param<std::string>("paramStr"), "testParam");
  BOOST_CHECK_EQUAL(validMsgFromString.get_param<double>("paramDouble"), 3.1415);

  // Check valid message throws exception on missing parameter
  BOOST_CHECK_THROW(validMsgFromString.get_param<int>("missingParam"), OdinData::IpcMessageException);

  // Check valid message can fall back to default value if parameter missing
  int defaultParamValue = 90210;
  BOOST_CHECK_EQUAL(validMsgFromString.get_param<int>("missingParam", defaultParamValue), defaultParamValue);

}

BOOST_AUTO_TEST_CASE( EmptyIpcMessage )
{
  // Instantiate an empty message, which will be invalid by default since no attributes have been set
  OdinData::IpcMessage emptyMsg;

  // Check the message isn't valid
  BOOST_CHECK_EQUAL(emptyMsg.is_valid(), false);
}

BOOST_AUTO_TEST_CASE( CreateValidIpcMessageFromEmpty)
{
  // Instantiate an empty message, which will be invalid by default since no attributes have been set
  OdinData::IpcMessage theMsg;

  // Empty message isn't valid
  BOOST_CHECK_EQUAL(theMsg.is_valid(), false);

  // Set message type and value
  OdinData::IpcMessage::MsgType msg_type = OdinData::IpcMessage::MsgTypeCmd;
  theMsg.set_msg_type(msg_type);
  OdinData::IpcMessage::MsgVal msg_val = OdinData::IpcMessage::MsgValCmdReset;
  theMsg.set_msg_val(msg_val);

  // Check the message is now valid
  BOOST_CHECK_EQUAL(theMsg.is_valid(), true);

}

BOOST_AUTO_TEST_CASE( CreateAndModifyParametersInEmptyIpcMessage )
{
  // Create an emprty message
  OdinData::IpcMessage emptyMsg;

  // Define and set some parameters
  int paramIntVal = 1234;
  int paramIntVal2 = 90210;
  int paramIntVal3 = 4567;
  std::string paramStringVal("paramString");

  emptyMsg.set_param("paramInt", paramIntVal);
  emptyMsg.set_param("paramInt2", paramIntVal2);
  emptyMsg.set_param("paramInt3", paramIntVal3);
  emptyMsg.set_param("paramStr", paramStringVal);

  // Read them back and check they have correct values
  BOOST_CHECK_EQUAL(emptyMsg.get_param<int>("paramInt"), paramIntVal);
  BOOST_CHECK_EQUAL(emptyMsg.get_param<int>("paramInt2"), paramIntVal2);
  BOOST_CHECK_EQUAL(emptyMsg.get_param<int>("paramInt3"), paramIntVal3);
  BOOST_CHECK_EQUAL(emptyMsg.get_param<std::string>("paramStr"), paramStringVal);

  // Modify several parameters and check they are still correct
  paramIntVal2 = 228724;
  emptyMsg.set_param("paramInt2", paramIntVal2);
  std::string paramStringValNew("another string");
  emptyMsg.set_param("paramStr", paramStringValNew);

  BOOST_CHECK_EQUAL(emptyMsg.get_param<int>("paramInt2"), paramIntVal2);
  BOOST_CHECK_EQUAL(emptyMsg.get_param<std::string>("paramStr"), paramStringValNew);

}

BOOST_AUTO_TEST_CASE( UpdateParametersInExistingIpcMessage )
{
  OdinData::IpcMessage msg1;

  // Define and set some parameters
  int paramIntVal = 1234;
  int paramIntVal2 = 90210;
  int paramIntVal3 = 4567;
  std::string paramStringVal("paramString");

  msg1.set_param("paramInt", paramIntVal);
  msg1.set_param("paramInt2", paramIntVal2);
  msg1.set_param("paramInt3", paramIntVal3);
  msg1.set_param("paramStr", paramStringVal);

  // Read them back and check they have correct values
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt"), paramIntVal);
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt2"), paramIntVal2);
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt3"), paramIntVal3);
  BOOST_CHECK_EQUAL(msg1.get_param<std::string>("paramStr"), paramStringVal);

  OdinData::IpcMessage msg2;

  // Create a different message and update the first with it
  int newParamIntVal2 = 90310;
  int paramIntVal4 = 42;
  std::string newParamStringVal("newParamStr");
  std::string paramStringVal2("paramStr2");

  msg2.set_param("paramInt2", newParamIntVal2);
  msg2.set_param("paramInt4", paramIntVal4);
  msg2.set_param("paramStr", newParamStringVal);
  msg2.set_param("paramStr2", paramStringVal2);

  msg1.update(msg2);

  // Check that values are overwritten / added / still there
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt"), paramIntVal);
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt2"), newParamIntVal2);
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt3"), paramIntVal3);
  BOOST_CHECK_EQUAL(msg1.get_param<int>("paramInt4"), paramIntVal4);
  BOOST_CHECK_EQUAL(msg1.get_param<std::string>("paramStr"), newParamStringVal);
  BOOST_CHECK_EQUAL(msg1.get_param<std::string>("paramStr2"), paramStringVal2);

}

BOOST_AUTO_TEST_CASE( RoundTripFromEmptyIpcMessage )
{

  // Create an empty message
  OdinData::IpcMessage theMsg;

  // Set message type and value
  OdinData::IpcMessage::MsgType msg_type = OdinData::IpcMessage::MsgTypeCmd;
  theMsg.set_msg_type(msg_type);
  OdinData::IpcMessage::MsgVal msg_val = OdinData::IpcMessage::MsgValCmdReset;
  theMsg.set_msg_val(msg_val);

  // Define and set some parameters
  int paramIntVal = 1234;
  int paramIntVal2 = 90210;
  int paramIntVal3 = 4567;
  std::string paramStringVal("paramString");

  theMsg.set_param("paramInt", paramIntVal);
  theMsg.set_param("paramInt2", paramIntVal2);
  theMsg.set_param("paramInt3", paramIntVal3);
  theMsg.set_param("paramStr", paramStringVal);

  // Retrieve the encoded version
  const char* theMsgEncoded = theMsg.encode();

  // Create another message from the encoded version
  OdinData::IpcMessage msgFromEncoded(theMsgEncoded);

  // Validate the contents of all attributes and parameters of the new message
  BOOST_CHECK_EQUAL(msgFromEncoded.get_msg_type(), msg_type);
  BOOST_CHECK_EQUAL(msgFromEncoded.get_msg_val(), msg_val);
  BOOST_CHECK_EQUAL(msgFromEncoded.get_msg_timestamp(), theMsg.get_msg_timestamp());
  BOOST_CHECK_EQUAL(msgFromEncoded.get_param<int>("paramInt"), paramIntVal);
  BOOST_CHECK_EQUAL(msgFromEncoded.get_param<int>("paramInt2"), paramIntVal2);
  BOOST_CHECK_EQUAL(msgFromEncoded.get_param<int>("paramInt3"), paramIntVal3);
  BOOST_CHECK_EQUAL(msgFromEncoded.get_param<std::string>("paramStr"), paramStringVal);

}

BOOST_AUTO_TEST_CASE( RoundTripFromEmptyIpcMessageComparison )
{

  // Create an empty message
  OdinData::IpcMessage theMsg;

  // Set message type and value
  OdinData::IpcMessage::MsgType msg_type = OdinData::IpcMessage::MsgTypeCmd;
  theMsg.set_msg_type(msg_type);
  OdinData::IpcMessage::MsgVal msg_val = OdinData::IpcMessage::MsgValCmdReset;
  theMsg.set_msg_val(msg_val);

  // Define and set some parameters
  int paramIntVal = 1234;
  int paramIntVal2 = 90210;
  int paramIntVal3 = 4567;
  std::string paramStringVal("paramString");

  theMsg.set_param("paramInt", paramIntVal);
  theMsg.set_param("paramInt2", paramIntVal2);
  theMsg.set_param("paramInt3", paramIntVal3);
  theMsg.set_param("paramStr", paramStringVal);

  // Retrieve the encoded version
  const char* theMsgEncoded = theMsg.encode();

  // Create another message from the encoded version
  OdinData::IpcMessage msgFromEncoded(theMsgEncoded);

  // Test that the relational (in)equality operators work correctly for the IpcMessage class
  BOOST_CHECK_EQUAL((msgFromEncoded == theMsg), true);
  BOOST_CHECK_EQUAL((msgFromEncoded != theMsg), false);

}

BOOST_AUTO_TEST_CASE( InvalidIpcMessageFromString )
{
  // Instantiate an invalid message from an illegal JSON string - should throw an IpcMessageException
  BOOST_CHECK_THROW(OdinData::IpcMessage invalidMsgFromString("{\"wibble\" : \"wobble\" \"shouldnt be here\"}"), OdinData::IpcMessageException);
}

BOOST_AUTO_TEST_CASE( IllegalTypeIpcMessageFromString )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal type. Turning off strict validation will prevent an exception
  // at this point but render the message invalid
  OdinData::IpcMessage illegalTypeMsgFromString("{\"msg_type\":\"wrong\", \"msg_val\":\"status\", \"timestamp\" : \"2015-01-27T15:26:01.123456\" }", false);

  // Check that the message isn't valid
  BOOST_CHECK_EQUAL(illegalTypeMsgFromString.is_valid(), false);
}

BOOST_AUTO_TEST_CASE( IllegalValueIpcMessageFromString )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal value. Turning off strict validation will prevent an exception
  // at this point but render the message invalid
  OdinData::IpcMessage illegalValueMsgFromString("{\"msg_type\":\"cmd\", \"msg_val\":\"wrong\", \"timestamp\" : \"2015-01-27T15:26:01.123456\" }", false);

  // Check that the message isn't valid
  BOOST_CHECK_EQUAL(illegalValueMsgFromString.is_valid(), false);
}

BOOST_AUTO_TEST_CASE( IllegalTimestampIpcMessageFromString )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal timestamp. Turning off strict validation will prevent an exception
  // at this point but render the message invalid
  OdinData::IpcMessage illegalTimestampMsgFromString("{\"msg_type\":\"cmd\", \"msg_val\":\"status\", \"timestamp\" : \"1 Jan 1970 00:00:00\" }", false);

  // Check that the message isn't valid
  BOOST_CHECK_EQUAL(illegalTimestampMsgFromString.is_valid(), false);
}

BOOST_AUTO_TEST_CASE( IllegalTypeIpcMessageFromStringStrictValidation )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal type - with strict validation on, should throw an IpcMessageException
  BOOST_CHECK_THROW(
      OdinData::IpcMessage illegalTypeMsgFromString("{\"msg_type\":\"wrong\", \"msg_val\":\"status\", \"timestamp\" : \"2015-01-27T15:26:01.123456\" }", true),
      OdinData::IpcMessageException);
}

BOOST_AUTO_TEST_CASE( IllegalValueIpcMessageFromStringStrictValidation )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal value - with strict validation on, should throw an IpcMessageException
  BOOST_CHECK_THROW(
      OdinData::IpcMessage illegalValueMsgFromString("{\"msg_type\":\"cmd\", \"msg_val\":\"wrong\", \"timestamp\" : \"2015-01-27T15:26:01.123456\" }", true),
      OdinData::IpcMessageException);
}

BOOST_AUTO_TEST_CASE( IllegalTimestampIpcMessageFromStringStrictValidation )
{
  // Instantiate a  message from a JSON string with valid syntax but an illegal timestamp - with strict validation on, should throw an IpcMessageException
  BOOST_CHECK_THROW(
      OdinData::IpcMessage illegalTimestampMsgFromString("{\"msg_type\":\"cmd\", \"msg_val\":\"status\", \"timestamp\" : \"1 Jan 1970 00:00:00\" }", true),
      OdinData::IpcMessageException);
}

BOOST_AUTO_TEST_CASE( MissingParamsIpcMessageFromStringStrictValidation )
{
  // Instantiate a valid message from a JSON string
  BOOST_CHECK_THROW(
      OdinData::IpcMessage missingParamsMsgFromString("{\"msg_type\":\"cmd\", \"msg_val\":\"status\", \"timestamp\" : \"2015-01-27T15:26:01.123456\" }", true),
      OdinData::IpcMessageException);
}

// Calculate the difference, in seconds, between two timespecs
#define NANOSECONDS_PER_SECOND 1000000000
double timeDiff(struct timespec* start, struct timespec* end)
{

  double startNs = ((double)start->tv_sec * NANOSECONDS_PER_SECOND) + start->tv_nsec;
  double endNs   = ((double)  end->tv_sec * NANOSECONDS_PER_SECOND) +   end->tv_nsec;

  return (endNs - startNs) / NANOSECONDS_PER_SECOND;
}

BOOST_AUTO_TEST_CASE( TestIpcMessageCreationSpeed )
{
  int numLoops = 10000;
  struct timespec start, end;
  double deltaT, rate;

  gettime(&start);

  BOOST_CHECK_NO_THROW(
      for (int i = 0; i < numLoops; i++)
      {
        OdinData::IpcMessage simpleMessage(OdinData::IpcMessage::MsgTypeCmd, OdinData::IpcMessage::MsgValCmdStatus);
        simpleMessage.set_param<int>("loopParam", i);
        const char *encodedMsg = simpleMessage.encode();
      }
  );

  gettime(&end);
  deltaT = timeDiff(&start, &end);
  rate = (double)numLoops / deltaT;
  BOOST_TEST_MESSAGE("Created and encoded " << numLoops << " IPC messages in " << timeDiff(&start, &end) << " secs, rate " << rate << " Hz" );

  gettime(&start);

  BOOST_CHECK_NO_THROW(
      for (int i = 0 ; i < numLoops; i++)
      {
        OdinData::IpcMessage validMsgFromString("{\"msg_type\":\"cmd\", "
                                                    "\"msg_val\":\"status\", "
                                                    "\"timestamp\" : \"2015-01-27T15:26:01.123456\", "
                                                    "\"params\" : {"
                                                    "    \"paramInt\" : 1234, "
                                                    "    \"paramStr\" : \"testParam\", "
                                                    "    \"paramDouble\" : 3.1415 "
                                                    "  } "
                                                    "}");
        validMsgFromString.set_param<int>("loopParam", i);
      }
  );

  gettime(&end);
  deltaT = timeDiff(&start, &end);
  rate = (double)numLoops / deltaT;
  BOOST_TEST_MESSAGE("Created and parsed " << numLoops << " IPC messages from string in " << timeDiff(&start, &end) << " secs, rate " << rate << " Hz");

}

BOOST_AUTO_TEST_SUITE_END();


text:
module Main where

import Control.Lens (view, itraverse_)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Logger (LoggingT, runStderrLoggingT, filterLogger, LogLevel(..))
import Control.Monad.State (modify)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Yaml (decodeFileEither, prettyPrintParseException)
import Network.Wai.Handler.Warp (run, defaultSettings, setPort)
import Network.Wai.Handler.WarpTLS (runTLS, tlsSettings)
import Network.Wai.Middleware.RequestLogger (logStdout)
import System.Cron (Job(Job), Schedule, execSchedule)
import System.Environment (lookupEnv)

import API
import App
import PayloadTag (fromText)
import Upload (doUpload)

-- | Run with our standard logging settings.
runLoggingT :: (MonadIO m) => LoggingT m a -> m a
runLoggingT = runStderrLoggingT . filterLogger (const (> LevelDebug))

-- | Schedule uploads to a particular destination.
scheduleUpload :: App
               -- ^ Application record.
               -> Text
               -- ^ Text form of the payload tag.
               -> UploadSchedule
               -- ^ Schedule uploads will be run on.
               -> Schedule ()
               -- ^ An action in the 'Schedule' monad.
scheduleUpload app typeText (UploadSchedule schedule destinations targets) =
  case fromText typeText of
    Nothing -> return ()
    Just importType -> modify (Job schedule job:)
      where job = runLoggingT . runAppT app $ doUpload importType destinations targets

main :: IO ()
main = do
  configPath <- lookupEnv "CATCHER_CONFIG"
  config <- either (fail . prettyPrintParseException) return =<<
    decodeFileEither (fromMaybe "config.yaml" configPath)
  app <- runLoggingT (mkApp config)
  _ <- execSchedule $ itraverse_ (scheduleUpload app) (view configSchedules config)
  let wapp = logStdout (serveApp app)
  case view configHttpsPort config of
    Just port -> case view configCertificate config of
      Just certPath ->
        runTLS (tlsSettings certPath certPath) (setPort port defaultSettings) wapp
      Nothing -> error "Missing certificate path"
    Nothing -> run port wapp
      where port = fromMaybe 8080 . view configHttpPort $ config

redpajama_set_name: RedPajamaGithub


text:
from tkinter import Tk, Frame, Canvas, Scrollbar, HORIZONTAL, VERTICAL, Label, \
     PhotoImage

from PIL import Image, ImageTk

root=Tk()

frame=Frame(root,width=500,height=100)
frame.grid(row=0,column=0)

#img = PhotoImage(file = '/home/raja/Pictures/Python_vs._others.png');
image = Image.open("/home/raja/Pictures/facebook/FB_IMG_14625555879653356.jpg");
photo = ImageTk.PhotoImage(image)
canvas=Canvas(frame,bg='violet',width=800,height=500,scrollregion=(0,0,900,800));
canvas.create_image(300, 300, image = photo)

hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.grid(row = 1, column = 0, sticky = 'ew');
hbar.config(command=canvas.xview)

vbar=Scrollbar(frame,orient=VERTICAL)
vbar.grid(row = 0, column = 1, sticky = 'ns');
vbar.config(command=canvas.yview)

##canvas.config(width=300,height=300)
canvas.config(xscrollcommand = hbar.set, yscrollcommand = vbar.set)
canvas.grid(row = 0, column = 0, sticky = 'nsew');

l = Label(frame, bg = 'red').grid(row = 0, column = 2 , sticky = 'nsew');

root.mainloop()


text:
dbm.registerClass("dbm.utils.canvas.3d.drawcommands.BaseDrawCommand", "dbm.core.FlowBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.utils.canvas.3d.drawcommands.BaseDrawCommand");

	var BaseDrawCommand = dbm.importClass("dbm.utils.canvas.3d.drawcommands.BaseDrawCommand");

	var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");
	var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");
	var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");

	var AnyChangeMultipleInputProperty = dbm.importClass("dbm.core.objectparts.AnyChangeMultipleInputProperty");
	var TypedArrayFunctions = dbm.importClass("dbm.utils.native.typedarray.TypedArrayFunctions");

	var VariableAliases = dbm.importClass("dbm.utils.data.VariableAliases");

	/**
	 * Constructor.
	 */
	objectFunctions._init = function() {
		//console.log("dbm.utils.canvas.3d.drawcommands.BaseDrawCommand::_init");

		this.superCall();

		this._graphicsUpdate = this.addProperty("graphicsUpdate", AnyChangeMultipleInputProperty.create());

		return this;
	};

	objectFunctions.draw = function(aContext, aProjectionMatrix, aTransformationMatrix) {
		//MENOTE: should be overridden
	};

	/**
	 * Sets all the references to null
	 */
	objectFunctions.setAllReferencesToNull = function() {

		this._graphicsUpdate = null;

		this.superCall();
	};
});


text:
package org.apache.asterix.dataflow.data.nontagged.serde;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.dataflow.data.nontagged.Coordinate;
import org.apache.asterix.om.base.APoint;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public class APointSerializerDeserializer implements ISerializerDeserializer<APoint> {

    private static final long serialVersionUID = 1L;

    public static final APointSerializerDeserializer INSTANCE = new APointSerializerDeserializer();

    private APointSerializerDeserializer() {
    }

    @Override
    public APoint deserialize(DataInput in) throws HyracksDataException {
        try {
            return new APoint(in.readDouble(), in.readDouble());
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void serialize(APoint instance, DataOutput out) throws HyracksDataException {
        try {
            out.writeDouble(instance.getX());
            out.writeDouble(instance.getY());
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    public static void serialize(double x, double y, DataOutput out) throws HyracksDataException {
        try {
            out.writeDouble(x);
            out.writeDouble(y);
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    public final static int getCoordinateOffset(Coordinate coordinate) throws HyracksDataException {

        switch (coordinate) {
            case X:
                return 1;
            case Y:
                return 9;
            default:
                throw new HyracksDataException("Wrong coordinate");
        }

    }

}


text:
from ddapp import callbacks
from ddapp.fieldcontainer import FieldContainer

import re
import numpy as np
from collections import OrderedDict

def cleanPropertyName(s):
    """
    Generate a valid python property name by replacing all non-alphanumeric characters with underscores and adding an initial underscore if the first character is a digit
    """
    return re.sub(r'\W|^(?=\d)','_',s).lower()  # \W matches non-alphanumeric, ^(?=\d) matches the first position if followed by a digit

class PropertyAttributes(FieldContainer):

    def __init__(self, **kwargs):

        self._add_fields(
          decimals = 5,
          minimum = -1e4,
          maximum = 1e4,
          singleStep = 1,
          hidden = False,
          enumNames = None,
          readOnly = False,
          )

        self._set_fields(**kwargs)

from PythonQt import QtGui

def fromQColor(propertyName, propertyValue):
    if isinstance(propertyValue, QtGui.QColor):
        return [propertyValue.red()/255.0, propertyValue.green()/255.0, propertyValue.blue()/255.0]
    else:
        return propertyValue

def toQProperty(propertyName, propertyValue):
    if 'color' in propertyName.lower() and isinstance(propertyValue, (list, tuple)) and len(propertyValue) == 3:
        return QtGui.QColor(propertyValue[0]*255.0, propertyValue[1]*255.0, propertyValue[2]*255.0)
    elif isinstance(propertyValue, np.float):
        return float(propertyValue)
    elif isinstance(propertyValue, (list, tuple, np.ndarray)) and len(propertyValue) and isinstance(propertyValue[0], np.float):
        return [float(x) for x in propertyValue]
    else:
        return propertyValue

class PropertySet(object):

    PROPERTY_CHANGED_SIGNAL = 'PROPERTY_CHANGED_SIGNAL'
    PROPERTY_ADDED_SIGNAL = 'PROPERTY_ADDED_SIGNAL'
    PROPERTY_ATTRIBUTE_CHANGED_SIGNAL = 'PROPERTY_ATTRIBUTE_CHANGED_SIGNAL'

    def __getstate__(self):
        d = dict(_properties=self._properties, _attributes=self._attributes)
        return d

    def __setstate__(self, state):
        self.__init__()
        attrs = state['_attributes']
        for propName, propValue in state['_properties'].iteritems():
            self.addProperty(propName, propValue, attributes=attrs.get(propName))

    def __init__(self):

        self.callbacks = callbacks.CallbackRegistry([self.PROPERTY_CHANGED_SIGNAL,
                                                     self.PROPERTY_ADDED_SIGNAL,
                                                     self.PROPERTY_ATTRIBUTE_CHANGED_SIGNAL])

        self._properties = OrderedDict()
        self._attributes = {}
        self._alternateNames = {}

    def propertyNames(self):
        return self._properties.keys()

    def hasProperty(self, propertyName):
        return propertyName in self._properties

    def assertProperty(self, propertyName):
        assert self.hasProperty(propertyName), "Missing property: {:s}".format(propertyName)

    def connectPropertyChanged(self, func):
        return self.callbacks.connect(self.PROPERTY_CHANGED_SIGNAL, func)

    def disconnectPropertyChanged(self, callbackId):
        self.callbacks.disconnect(callbackId)

    def connectPropertyAdded(self, func):
        return self.callbacks.connect(self.PROPERTY_ADDED_SIGNAL, func)

    def disconnectPropertyAdded(self, callbackId):
        self.callbacks.disconnect(callbackId)

    def connectPropertyAttributeChanged(self, func):
        return self.callbacks.connect(self.PROPERTY_ATTRIBUTE_CHANGED_SIGNAL, func)

    def disconnectPropertyAttributeChanged(self, callbackId):
        self.callbacks.disconnect(callbackId)

    def getProperty(self, propertyName):
        self.assertProperty(propertyName)
        return self._properties[propertyName]

    def getPropertyEnumValue(self, propertyName):
        self.assertProperty(propertyName)
        return self._attributes[propertyName].enumNames[self._properties[propertyName]]

    def removeProperty(self, propertyName):
        assert self.hasProperty(propertyName)
        alternateName = cleanPropertyName(propertyName)
        del self._alternateNames[alternateName]
        del self._properties[propertyName]
        del self._attributes[propertyName]

    def addProperty(self, propertyName, propertyValue, attributes=None):
        alternateName = cleanPropertyName(propertyName)
        if propertyName not in self._properties and alternateName in self._alternateNames:
            raise ValueError('Adding this property would conflict with a different existing property with alternate name {:s}'.format(alternateName))

        propertyValue = fromQColor(propertyName, propertyValue)

        self._alternateNames[alternateName] = propertyName
        self._properties[propertyName] = propertyValue
        self._attributes[propertyName] = attributes or PropertyAttributes()

        self.callbacks.process(self.PROPERTY_ADDED_SIGNAL, self, propertyName)

    def setPropertyIndex(self, propertyName, newIndex):
        assert self.hasProperty(propertyName)
        currentIndex = self._properties.keys().index(propertyName)
        inds = range(len(self._properties))
        inds.remove(currentIndex)
        inds.insert(newIndex, currentIndex)
        items = self._properties.items()
        self._properties = OrderedDict([items[i] for i in inds])

    def setProperty(self, propertyName, propertyValue):
        self.assertProperty(propertyName)
        propertyValue = fromQColor(propertyName, propertyValue)

        names = self.getPropertyAttribute(propertyName, 'enumNames')
        if names and type(propertyValue) != int:
            propertyValue = names.index(propertyValue)

        self.oldPropertyValue = (propertyName, self.getProperty(propertyName))
        self._properties[propertyName] = propertyValue
        self.oldPropertyValue = None
        self.callbacks.process(self.PROPERTY_CHANGED_SIGNAL, self, propertyName)

    def getPropertyAttribute(self, propertyName, propertyAttribute):
        self.assertProperty(propertyName)
        return getattr(self._attributes[propertyName], propertyAttribute)

    def setPropertyAttribute(self, propertyName, propertyAttribute, value):
        self.assertProperty(propertyName)
        attributes = self._attributes[propertyName]
        assert hasattr(attributes, propertyAttribute), "Missing attribute: {:s}".format(propertyAttribute)
        setattr(attributes, propertyAttribute, value)
        self.callbacks.process(self.PROPERTY_ATTRIBUTE_CHANGED_SIGNAL, self, propertyName, propertyAttribute)

    def __getattribute__(self, name):
        try:
            alternateNames = object.__getattribute__(self, '_alternateNames')
            if name in alternateNames:
                return object.__getattribute__(self, 'getProperty')(alternateNames[name])
            else:
                raise AttributeError()
        except AttributeError:
            return object.__getattribute__(self, name)

class PropertyPanelHelper(object):

    @staticmethod
    def addPropertiesToPanel(properties, panel):

        for propertyName in properties.propertyNames():
            value = properties.getProperty(propertyName)
            attributes = properties._attributes[propertyName]
            if value is not None and not attributes.hidden:
                PropertyPanelHelper._addProperty(panel, propertyName, attributes, value)

    @staticmethod
    def onPropertyValueChanged(panel, properties, propertyName):
        prop = panel.getProperty(propertyName)

        if prop is not None:

            propertyValue = properties.getProperty(propertyName)
            propertyValue = toQProperty(propertyName, propertyValue)

            if isinstance(propertyValue, list):
                for i, subValue in enumerate(propertyValue):
                    panel.getSubProperty(prop, i).setValue(subValue)

                groupName = PropertyPanelHelper.getPropertyGroupName(propertyName, propertyValue)
                prop.setPropertyName(groupName)

            else:
                prop.setValue(propertyValue)

    @staticmethod
    def setPropertyFromPanel(prop, propertiesPanel, propertySet):

        if prop.isSubProperty():
            if not propertiesPanel.getParentProperty(prop):
                return

            propertyIndex = propertiesPanel.getSubPropertyIndex(prop)
            propertyName = prop.propertyName()
            propertyName = propertyName[:propertyName.index('[')]

            propertyValue = propertySet.getProperty(propertyName)
            propertyValue = list(propertyValue)
            propertyValue[propertyIndex] = prop.value()

            propertySet.setProperty(propertyName, propertyValue)

            groupName = PropertyPanelHelper.getPropertyGroupName(propertyName, propertyValue)
            propertiesPanel.getParentProperty(prop).setPropertyName(groupName)

        else:

            propertyName = prop.propertyName()
            propertyValue = prop.value()
            propertyValue = fromQColor(propertyName, propertyValue)
            propertySet.setProperty(propertyName, propertyValue)

    @staticmethod
    def _setPropertyAttributes(prop, attributes):

        prop.setAttribute('decimals', attributes.decimals)
        prop.setAttribute('minimum', attributes.minimum)
        prop.setAttribute('maximum', attributes.maximum)
        prop.setAttribute('singleStep', attributes.singleStep)
        if attributes.enumNames:
            prop.setAttribute('enumNames', attributes.enumNames)

    @staticmethod
    def getPropertyGroupName(name, value):
        return '%s [%s]' % (name, ', '.join(['%.2f' % v if isinstance(v, float) else str(v) for v in value]))

    @staticmethod
    def _addProperty(panel, name, attributes, value):

        value = toQProperty(name, value)

        if isinstance(value, list):
            groupName = PropertyPanelHelper.getPropertyGroupName(name, value)
            groupProp = panel.addGroup(name, groupName)
            for v in value:
                p = panel.addSubProperty(name, v, groupProp)
                PropertyPanelHelper._setPropertyAttributes(p, attributes)
            return groupProp
        elif attributes.enumNames:
            p = panel.addEnumProperty(name, value)
            PropertyPanelHelper._setPropertyAttributes(p, attributes)
            p.setValue(value)
            return p
        else:
            p = panel.addProperty(name, value)
            PropertyPanelHelper._setPropertyAttributes(p, attributes)
            return p

class PropertyPanelConnector(object):
    def __init__(self, propertySet, propertiesPanel):
        self.propertySet = propertySet
        self.propertiesPanel = propertiesPanel
        self.propertySet.connectPropertyAdded(self._onPropertyAdded)
        self.propertySet.connectPropertyChanged(self._onPropertyChanged)
        self.propertySet.connectPropertyAttributeChanged(self._onPropertyAttributeChanged)
        self.propertiesPanel.connect('propertyValueChanged(QtVariantProperty*)', self._onPanelPropertyChanged)

        self._blockSignals = True
        PropertyPanelHelper.addPropertiesToPanel(self.propertySet, self.propertiesPanel)
        self._blockSignals = False

    def _onPropertyAdded(self, propertySet, propertyName):
        self._blockSignals = True
        self.propertiesPanel.clear()
        PropertyPanelHelper.addPropertiesToPanel(propertySet, self.propertiesPanel)
        self._blockSignals = False

    def _onPropertyAttributeChanged(self, propertySet, propertyName, propertyAttribute):
        self._blockSignals = True
        self.propertiesPanel.clear()
        PropertyPanelHelper.addPropertiesToPanel(propertySet, self.propertiesPanel)
        self._blockSignals = False

    def _onPropertyChanged(self, propertySet, propertyName):
        self._blockSignals = True
        PropertyPanelHelper.onPropertyValueChanged(self.propertiesPanel, propertySet, propertyName)
        self._blockSignals = False

    def _onPanelPropertyChanged(self, panelProperty):
        if not self._blockSignals:
            PropertyPanelHelper.setPropertyFromPanel(panelProperty, self.propertiesPanel, self.propertySet)


text:
static UIImage *avatarImage;
static NSURL *avatarURL;

@implementation EM_ChatResourcesUtils

NSString * const kEMChatIconFontName = @"em_chat_icon";

NSString * const kEMChatIconToolVoice = @"\ue600";
NSString * const kEMChatIconToolFace = @"\ue601";
NSString * const kEMChatIconToolAction = @"\ue602";
NSString * const kEMChatIconToolKeyboard = @"\ue603";
NSString * const kEMChatIconToolDown = @"\ue604";
NSString * const kEMChatIconToolUp = @"\ue605";

NSString * const kEMChatIconActionImage = @"\ue606";
NSString * const kEMChatIconActionCamera = @"\ue607";
NSString * const kEMChatIconActionAudio = @"\ue608";
NSString * const kEMChatIconActionVideo = @"\ue609";
NSString * const kEMChatIconActionLocation = @"\ue60a";
NSString * const kEMChatIconActionFile = @"\ue60b";

NSString * const kEMChatIconMoreRepeal = @"\ue60c";
NSString * const kEMChatIconMoreRecord = @"\ue60d";
NSString * const kEMChatIconMoreTrash = @"\ue60e";
NSString * const KEMChatIconMorePlay = @"\ue60f";
NSString * const kEMChatIconMoreStop = @"\ue610";

NSString * const kEMChatIconBubbleTailLeft = @"\ue611";
NSString * const kEMChatIconBubbleTailRight = @"\ue612";

NSString * const kEMChatIconCallHangup = @"\ue613";
NSString * const kEMChatIconCallConnect = @"\ue614";
NSString * const kEMChatIconCallSilence = @"\ue615";
NSString * const kEMChatIconCallExpand = @"\ue616";

+ (NSString *)stringWithName:(NSString *)name{
    return [self stringWithName:name table:@"EM_ChatStrings"];
}

+ (NSString *)stringWithName:(NSString *)name table:(NSString *)table{
    return NSLocalizedStringFromTable(name,table,@"");
}

+ (UIImage *)imageWithName:(NSString *)name{
    return [UIImage imageNamed:name];
}

+ (UIImage *)defaultAvatarImage{
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        avatarImage = [self imageWithName:@"EM_Resource.bundle/images/avatar_default"];
    });
    return avatarImage;
}

+ (NSURL *)defaultAvatarURL{
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        avatarURL = [NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"EM_Resource.bundle/images/avatar_default.png"]];;
    });
    return avatarURL;
}

+ (UIImage *)cellImageWithName:(NSString *)name{
    return [self imageWithName:[NSString stringWithFormat:@"EM_Resource.bundle/images/cell/%@",name]];
}

+ (UIImage *)callImageWithName:(NSString *)name{
    return [self imageWithName:[NSString stringWithFormat:@"EM_Resource.bundle/images/call/%@",name]];
}

+ (UIImage *)fileImageWithName:(NSString *)name{
    return [self imageWithName:[NSString stringWithFormat:@"EM_Resource.bundle/images/file/%@",name]];
}

+ (UIFont *)iconFontWithSize:(float)size{
#ifndef DISABLE_FONTAWESOME_AUTO_REGISTRATION
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *fontUrl = [[NSBundle mainBundle] URLForResource:kEMChatIconFontName withExtension:@"ttf" subdirectory:@"EM_Resource.bundle/file"];
        CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
        CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
        CGDataProviderRelease(fontDataProvider);
        CFErrorRef error;
        CTFontManagerRegisterGraphicsFont(newFont, &error);
        CGFontRelease(newFont);
    });
#endif

    UIFont *font = [UIFont fontWithName:kEMChatIconFontName size:size];
    return font;
}

@end


text:
PHP engine
=================

 * [Aliases for path/url/namespace](https://github.com/romeOz/rock-template/blob/master/docs/aliases.md)
 * [Render] (https://github.com/romeOz/rock-template/blob/master/docs/render.md)
 * [Placeholder](#placeholder)
 * [Resource](#resource)
 * [Chunk](#chunk)
 * [Snippet](https://github.com/romeOz/rock-template/blob/master/docs/snippets/readme.md)
 * [Autoescape](#autoescape)
 * [Caching](#caching)

Placeholder
-----------------

The engine supports local and global placeholders.
> Note: local placeholders in contrast to global, used only in the context of the current tpl-entity (chunk, snippet).

Adding/getting local placeholder:

```php
$template = new Template;
$template->addPlaceholder('foo', 'Hello');

// or by using setter
$template->foo = 'Hello';

echo $template->getPlaceholder('foo'); // result: Hello

// or by using getter

echo $template->foo; // result: Hello
```

Adding/getting a global placeholder:

```php
$template = new Template;
$template->addPlaceholder('foo', 'Hello', true);

echo $template->getPlaceholder('foo', false, true); // result: Hello

// or by using getter

echo $template->foo; // result: Hello
```

__set() and __unset() using only for local placeholders.

> Conflict resolution of names when using getter (`__get()`): The first is returned to the local placeholder, second - global placeholder, and third - resource.

If placeholder is an array:

```php
$template->foo = ['bar' => 'Hello'];

echo $template->getPlaceholder('foo.bar'); // result: Hello
```

Resource
-----------------

Typically, the page of the site is a resource with data, retrieved from the database or controller. E.g., article/topic: id, title, description, content, url.
All these data it is appropriate to stored in `resources`. Are available anywhere template.

Adding/getting resource:

```php
$template = new Template;

$template->addResource('content', 'Text...');

echo $template->getResource('content'); // result: Text...

// or by using getter

echo $template->content; // result: Text...
```

Chunk
-----------------

Chunk is an html-entity. Autoescape is not affect.

```php
$template = new Template;

//absolute path
echo $template->getChunk('/path/to/chunk.php', ['foo' => 'text']);

// using alias
echo $template->getChunk('@views/chunk.php', ['foo' => 'text']);
```

Autoescape
-----------------

By default, escaping be made on all entities of a template, except chunks and some snippets (`listView`, `for`,... see to the docs snippet).

###Include

You can set globally autoescape in config of `\rock\template\Template`:

```php
use \rock\template\Template;

$config = [
    'autoescape' => Template::STRIP_TAGS // only strip tags
];

$template = new Template($config);
```

or

```php
use \rock\template\Template;

$template = new Template;
$template->autoescape = Template::STRIP_TAGS;
```
> Note: the property `autoescape` has a default value: `\rock\template\Template::ESCAPE`.

###Usage

You can specify custom escaping for any entity Template engine:

```php
$template = new Template;

$template->getPlaceholder('foo', false);
$template->getSnippet('Snippet', [], Template::TO_TYPE);
```

Possible value:

 * true - default globally autoescape `rock\template\Template::ESCAPE`.
 * false - doesn't escape.
 * integer - `Template::ESCAPE`, `Template::STRIP_TAGS`, `Template::TO_TYPE`, or derived from bitwise operations.

Caching
------------------

You can caching any entity template engine.

###Include

```php
use \rock\template\Template;

$config = [
    'cache' => new \rock\cache\Memcached;
];

$template = new Template($config);
```

or

```php
use \rock\template\Template;

$template = new Template;
$template->cache = new \rock\cache\Memcached;
```

###Usage

The parameters to use for caching:

 * `cacheKey` - key of cache
 * `cacheExpire` - expire time
 * `cacheTags` - tags of cache

###Example

```php
$params = [
    'cacheKey' => 'plh',
    'cacheExpire' => 3600
];
echo $template->getPlaceholder('placeholder', $params);

$params = [
    'cacheKey' => 'list',
    'cacheTags' => ['articles', 'news']
];
echo $template->getSnippet('listView', $params);
```

Grouping multiple entities:

```php
$cache = \rock\cache\Memcached;

// get the content from the cache
if (($result = $cache->get('list')) !== false) {
    return $result;
}

$result = $template->getPlaceholder('placeholder');
$result .= $template->getSnippet('listView');

// set cache
$cache->set('list', $result, 3600);

return $result;
```

More detailed information [see Rock Cache](https://github.com/romeOz/rock-cache/).


text:
package com.example;

import java.lang.management.ManagementFactory;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.management.MBeanServer;
import javax.management.ObjectName;

public class JmxMainMXBean {

	public static void main(String[] args) throws Exception{
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		ObjectName name = new ObjectName("com.example", "type", "QueueSampler");
		Queue<String> queue = new ArrayBlockingQueue(10);
		queue.add("Row - 1");
		queue.add("Row - 2");
		queue.add("Row - 3");
		QueueSampler sampler = new QueueSampler(queue);
		server.registerMBean(sampler, name);

		Thread.sleep(Long.MAX_VALUE);

	}

}


text:
#ifndef TENSORFLOW_LITE_INTERNAL_SIGNATURE_DEF_H_
#define TENSORFLOW_LITE_INTERNAL_SIGNATURE_DEF_H_

#include <map>
#include <string>

namespace tflite {
namespace internal {

// Structure representing SignatureDef inputs/outputs.
struct SignatureDef {
  // Maps name in signature def as key to index of the tensor in the model.
  std::map<std::string, uint32_t> inputs;
  // Maps name in signature def as key to index of the tensor in the model.
  std::map<std::string, uint32_t> outputs;
  // The key of this SignatureDef in the SavedModel signature def map.
  std::string signature_key;
  // The subgraph index of the signature in the model.
  uint32_t subgraph_index;
};

}  // namespace internal
}  // namespace tflite
#endif  // TENSORFLOW_LITE_INTERNAL_SIGNATURE_DEF_H_


text:
#ifndef CCACHE_COMPOPT_H
#define CCACHE_COMPOPT_H

#include "system.h"

bool compopt_short(bool (*fn)(const char *option), const char *option);
bool compopt_affects_cpp(const char *option);
bool compopt_too_hard(const char *option);
bool compopt_too_hard_for_direct_mode(const char *option);
bool compopt_takes_path(const char *option);
bool compopt_takes_arg(const char *option);

#endif /* CCACHE_COMPOPT_H */


text:
package org.testy.http.model;

import org.junit.Test;
import org.testy.http.TestyHttpClient;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.testy.TestyHttp.*;
import static org.testy.http.UrlBuilder.path;

public class TestyHttpHttpGetRequestTest {
    private TestyHttpClient google = server("http://www.google.com");

    @Test
    public void example() throws Exception {
        google.receives(get().to(path("/")));

        assertThat(google.sends(), response()
                .withStatusCode(equalTo(200))
        );
    }

}


text:
package lib

import (
	"bytes"
	"compress/gzip"
	"crypto/tls"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

type redirectCaughtError struct{}

type ProxyServer struct {
	local     string
	remote    string
	log       io.Writer
	rewriters []Rewriter
	mappings  []Mapping
	noLogging bool

	server http.Server
	client http.Client
}

type requestContext struct {
	incomingRequest       *http.Request
	upstreamResponse      *http.Response
	hostMappings          []HostMapping
	outgoingHeaders       http.Header
	logs                  []string
	contentLength         int
	suppressContentLength bool
	requestUrl            string
}

func (c redirectCaughtError) Error() string {
	return "redirect caught"
}

func (r *requestContext) IncomingRequest() *http.Request {
	return r.incomingRequest
}

func (r *requestContext) UpstreamResponse() *http.Response {
	return r.upstreamResponse
}

func (r *requestContext) HostMappings() []HostMapping {
	return r.hostMappings
}

func (r *requestContext) Log(message string) {
	r.logs = append(r.logs, message)
}

func (r *requestContext) RequestUrl() string {
	if r.requestUrl == "" {
		r.requestUrl = "http://" + r.incomingRequest.Host + r.incomingRequest.RequestURI
	}

	return r.requestUrl
}

func newRequestContext() *requestContext {
	return &requestContext{
		logs:          make([]string, 0, 10),
		contentLength: -1,
	}
}

func (p *ProxyServer) ServeHTTP(outgoing http.ResponseWriter, incoming *http.Request) {
	var err error

	ctx := newRequestContext()
	ctx.hostMappings = buildHostMappings(p.mappings, incoming.Host)
	ctx.incomingRequest = incoming

	upstreamRequest, err := p.buildUpstreamRequest(ctx)

	if err == nil {
		ctx.upstreamResponse, err = p.client.Do(upstreamRequest)

		if isRedirectError(err) {
			err = nil
		}
	}

	if err != nil {
		fmt.Fprintf(p.log, "error during proxy request: %v\n", err)
		http.Error(outgoing, err.Error(), http.StatusBadGateway)
	} else {
		p.sendResponse(outgoing, ctx)
	}
}

func isRedirectError(err error) (q bool) {
	urlError, q := err.(*url.Error)
	if !q {
		return
	}

	_, q = urlError.Err.(redirectCaughtError)

	return
}

func (p *ProxyServer) buildUpstreamRequest(ctx *requestContext) (outgoing *http.Request, err error) {
	outgoing, err = http.NewRequest(
		ctx.incomingRequest.Method,
		p.remote+ctx.incomingRequest.RequestURI,
		ctx.incomingRequest.Body)

	if err != nil {
		return
	}

	for key, values := range ctx.incomingRequest.Header {
		for _, value := range values {
			outgoing.Header.Add(key, value)
		}
	}

	for _, rewriter := range p.rewriters {
		if rewriter, ok := rewriter.(IncomingHeaderRewriter); ok {
			rewriter.RewriteIncomingHeaders(outgoing.Header, ctx)
		}
	}

	// We also try to compress upstream communication
	outgoing.Header.Set("accept-encoding", "gzip")

	return
}

func (p *ProxyServer) sendResponse(outgoing http.ResponseWriter, ctx *requestContext) {
	var err error

	defer ctx.upstreamResponse.Body.Close()

	ctx.outgoingHeaders = p.setupOutgoingHeaders(outgoing, ctx)

	bodyRewriters := p.rewriteOutgoingHeaders(ctx)
	rewriteBody := len(bodyRewriters) > 0

	bodyReader, bodyWriter, err :=
		p.handleCompression(ctx.upstreamResponse.Body, outgoing, rewriteBody, ctx)
	if err != nil {
		http.Error(outgoing, err.Error(), http.StatusBadGateway)
		return
	}

	if rewriteBody {
		bodyReader = p.rewriteBody(bodyReader, bodyRewriters, ctx)
	}

	p.setupContentLength(ctx)

	// Add the log
	if !p.noLogging {
		p.addLog(ctx)
	}

	// Send headers
	outgoing.WriteHeader(ctx.upstreamResponse.StatusCode)

	// Send body
	io.Copy(bodyWriter, bodyReader)

	// Close writer if applicable (looking at you, gzip)
	if bodyWriter, ok := bodyWriter.(io.Closer); ok {
		bodyWriter.Close()
	}
}

func (p *ProxyServer) setupOutgoingHeaders(outgoing http.ResponseWriter, ctx *requestContext) (outgoingHeaders http.Header) {
	// Transfer headers
	outgoingHeaders = outgoing.Header()
	for key, values := range ctx.upstreamResponse.Header {
		for _, value := range values {
			outgoingHeaders.Add(key, value)
		}
	}

	if contentLength, e := strconv.Atoi(ctx.upstreamResponse.Header.Get("content-length")); e == nil {
		ctx.contentLength = contentLength
	}

	// Content length will be recalculated as content may be rewritten
	outgoingHeaders.Del("content-length")

	// Reset transfer-encoding
	outgoingHeaders.Del("transfer-encoding")

	// We need to remove any domain information set on the cookies
	outgoingHeaders.Del("set-cookie")
	for _, cookie := range ctx.upstreamResponse.Cookies() {
		cookie.Domain = ""

		http.SetCookie(outgoing, cookie)
	}

	return
}

func (p *ProxyServer) rewriteOutgoingHeaders(ctx *requestContext) (bodyRewriters []BodyRewriter) {
	// First rewrite pass: identify matching content rewriters and process headers
	bodyRewriters = make([]BodyRewriter, 0, len(p.rewriters))

	for _, rewriter := range p.rewriters {
		if r, ok := rewriter.(BodyRewriter); ok {
			if r.Matches(ctx) {
				bodyRewriters = append(bodyRewriters, r)
			}
		}

		if r, ok := rewriter.(HeaderRewriter); ok {
			r.RewriteHeaders(ctx.outgoingHeaders, ctx)
		}
	}

	return
}

func (p *ProxyServer) handleCompression(readerIn io.Reader, writerIn io.Writer, rewriteResponse bool, ctx *requestContext) (
	readerOut io.Reader, writerOut io.Writer, err error) {

	readerOut = readerIn
	writerOut = writerIn

	// We are ignoring any q-value here, so this is wrong for the case q=0
	clientAcceptsGzip := strings.Contains(ctx.incomingRequest.Header.Get("accept-encoding"), "gzip")

	if ctx.upstreamResponse.Header.Get("content-encoding") == "gzip" &&
		(rewriteResponse || !clientAcceptsGzip) {

		var e error
		readerOut, e = gzip.NewReader(readerIn)
		if e != nil {
			// Work around the closed-body-on-redirect bug in the runtime
			// https://github.com/golang/go/issues/10069
			readerOut = readerIn
			return
		}

		if clientAcceptsGzip {
			writerOut = gzip.NewWriter(writerIn)
			ctx.suppressContentLength = true
			ctx.outgoingHeaders.Set("content-encoding", "gzip")
		} else {
			ctx.outgoingHeaders.Del("content-encoding")
		}
	}

	return
}

func (p *ProxyServer) rewriteBody(reader io.Reader, bodyRewriters []BodyRewriter, ctx *requestContext) io.Reader {
	bodyData, err := ioutil.ReadAll(reader)

	if err == nil {
		for _, rewriter := range bodyRewriters {
			bodyData = rewriter.RewriteResponse(bodyData, ctx)
		}
	} else {
		// Work around the closed-body-on-redirect bug in the runtime
		// https://github.com/golang/go/issues/10069
		bodyData = make([]byte, 0)
	}

	ctx.contentLength = len(bodyData)

	return bytes.NewBuffer(bodyData)
}

func (p *ProxyServer) addLog(ctx *requestContext) {
	for _, entry := range ctx.logs {
		ctx.outgoingHeaders.Add("x-go-repro-log", entry)
	}
}

func (p *ProxyServer) setupContentLength(ctx *requestContext) {
	if ctx.contentLength > 0 && !ctx.suppressContentLength {
		ctx.outgoingHeaders.Set("content-length", strconv.Itoa(ctx.contentLength))
	}
}

func (p *ProxyServer) Start() <-chan error {
	c := make(chan error, 1)

	go func() {
		c <- p.server.ListenAndServe()
	}()

	fmt.Fprintf(p.log, "proxying requests for %s to %s\n", p.local, p.remote)

	return c
}

func (p *ProxyServer) AddRewriter(r Rewriter) {
	p.rewriters = append(p.rewriters, r)
}

func (p *ProxyServer) SetNoLogging(flag bool) {
	p.noLogging = flag
}

func NewProxyServer(m Mapping, mappings []Mapping, log io.Writer, sslAllowInsecure bool) (p *ProxyServer, err error) {
	p = &ProxyServer{
		local:     m.local,
		remote:    m.remote,
		log:       log,
		rewriters: make([]Rewriter, 0),
		mappings:  mappings,
	}

	p.server = http.Server{
		Addr:    p.local,
		Handler: p,
	}

	var tlsConfig *tls.Config
	if sslAllowInsecure {
		tlsConfig = &tls.Config{
			InsecureSkipVerify: true,
		}
	}

	p.client = http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return redirectCaughtError{}
		},
		Transport: &http.Transport{
			// We rather handle compression ourselves
			DisableCompression: true,
			TLSClientConfig:    tlsConfig,
		},
	}

	return
}


text:
package org.javaan.print;

import java.util.ArrayList;
import java.util.List;

import org.javaan.model.Dependency;
import org.javaan.model.Method;

public class MethodListDependencyFormatter implements ObjectFormatter<Dependency> {

	private static final String MORE = "...";

	private final int maxNumberOfMethods;

	public MethodListDependencyFormatter(int maxNumberOfMethods) {
		this.maxNumberOfMethods = maxNumberOfMethods;
	}

	@Override
	public String format(Dependency dependency) {
		StringBuilder buffer = new StringBuilder();
		List<Method> methods = new ArrayList<>(dependency.getCallee());
		int count = methods.size();
		count = Math.min(count, maxNumberOfMethods);
		for (int i=0; i < count; i++) {
			buffer.append(methods.get(i).getMethodName()).append(System.lineSeparator());
		}
		if (count < methods.size()) {
			buffer.append(MORE);
		}
		return buffer.toString();
	}

}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe Pkgr do
  it "should have a version" do
    Pkgr::VERSION.should_not be_nil
  end
end