text:
//----------------------------------------------------------------------------
//
// License:  See top level LICENSE.txt file
//
// Author:  David Burken
//
// Description: OSSIM Open JPEG JP2 reader (tile source).
//
// http://www.openjpeg.org/
//
//----------------------------------------------------------------------------
// $Id$

#ifndef ossimOpjJp2Reader_HEADER
#define ossimOpjJp2Reader_HEADER 1

#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/support_data/ossimJ2kSizRecord.h>
#include <vector>

// Forward class declarations.
class ossimImageData;
class ossimJ2kCodRecord;

class ossimOpjJp2Reader : public ossimImageHandler
{
public:

   /** Anonymous enumerations: */
   enum
   {
      SIGNATURE_BOX_SIZE = 12,
      GEOTIFF_UUID_SIZE  = 16
   };

   enum ossimOpjJp2ReadMode
   {
      ossimOpjJp2ReadUnknown = 0
   };

   /** default constructor */
   ossimOpjJp2Reader();

   /** virtual destructor */
   virtual ~ossimOpjJp2Reader();

   /** @return "ossim_openjpeg_reader" */
   virtual ossimString getShortName() const;

   /** @return "ossim open jpeg reader" */
   virtual ossimString getLongName()  const;

   /** @return "ossimOpjJp2Reader" */
   virtual ossimString getClassName()    const;

   /**
    *  Returns a pointer to a tile given an origin representing the upper
    *  left corner of the tile to grab from the image.
    *  Satisfies pure virtual from TileSource class.
    */
   virtual ossimRefPtr<ossimImageData> getTile(const ossimIrect& rect,
                                               ossim_uint32 resLevel=0);

    /**
     *  Returns the number of bands in the image.
     *  Satisfies pure virtual from ImageHandler class.
     */
   virtual ossim_uint32 getNumberOfInputBands() const;

   /**
    * Returns the number of bands in a tile returned from this TileSource.
    * Note: we are supporting sources that can have multiple data objects.
    * If you want to know the scalar type of an object you can pass in the
    */
   virtual ossim_uint32 getNumberOfOutputBands()const;

   /**
    * @brief Returns the number of decimation levels.
    *
    * This returns the total number of decimation levels.  It is important to
    * note that res level 0 or full resolution is included in the list and has
    * decimation values 1.0, 1.0
    *
    * @return The number of decimation levels.
    */
   virtual ossim_uint32 getNumberOfDecimationLevels()const;

   /**
     *  Returns the number of lines in the image.
     *  Satisfies pure virtual from ImageHandler class.
     */
   virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const;

   /**
    *  Returns the number of samples in the image.
    *  Satisfies pure virtual from ImageHandler class.
    */
   virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const;

   /**
    * Returns the zero based image rectangle for the reduced resolution data
    * set (rrds) passed in.  Note that rrds 0 is the highest resolution rrds.
    */
   virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const;

   /**
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /**
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   /**
    * Returns the output pixel type of the tile source.
    */
   virtual ossimScalarType getOutputScalarType() const;

   /**
    * Returns the tile width of the image or 0 if the image is not tiled.
    * Note: this is not the same as the ossimImageSource::getTileWidth which
    * returns the output tile width which can be different than the internal
    * image tile width on disk.
    */
   virtual ossim_uint32 getImageTileWidth() const;

   /**
    * Returns the tile width of the image or 0 if the image is not tiled.
    * Note: this is not the same as the ossimImageSource::getTileWidth which
    * returns the output tile width which can be different than the internal
    * image tile width on disk.
    */
   virtual ossim_uint32 getImageTileHeight() const;

   virtual bool isOpen()const;

   virtual double getMaxPixelValue(ossim_uint32 band = 0)const;

   /**
    *  @brief open method.
    *  @return true on success, false on error.
    */
   virtual bool open();

   /** close method */
   virtual void close();

   /**
    * Returns the image geometry object associated with this tile source or
    * NULL if non defined.  The geometry contains full-to-local image
    * transform as well as projection (image-to-world).
    */
   virtual ossimRefPtr<ossimImageGeometry> getImageGeometry();

protected:
   /**
    * @brief Gets an overview tile.
    *
    * Overrides ossimImageHandler::getOverviewTile
    *
    * @param resLevel The resolution level to pull from with resLevel 0 being
    * full res.
    *
    * @param result The tile to stuff.  Note The requested rectangle in full
    * image space and bands should be set in the result tile prior to
    * passing.  This method will subtract the subImageOffset if needed for
    * external overview call since they do not know about the sub image offset.
    *
    * @return true on success false on error.  Typically this will return false
    * if resLevel==0 unless the overview has r0.  If return is false, result
    * is undefined so caller should handle appropriately with makeBlank or
    * whatever.
    */
  virtual bool getOverviewTile(ossim_uint32 resLevel,
                               ossimImageData* result);

private:

   /**
    * @param Method to get geometry from the embedded JP2 Boxes.
    */
   virtual ossimRefPtr<ossimImageGeometry> getInternalImageGeometry();

   /**
    * @param Method to get geometry from the embedded JP2 GeoTIFF Box.
    */
   virtual ossimRefPtr<ossimImageGeometry> getImageGeometryFromGeotiffBox();

   /**
    * @param Method to get geometry from the embedded JP2 GML Box.
    */
   virtual ossimRefPtr<ossimImageGeometry> getImageGeometryFromGmlBox();

   /**
    * @param Method to get geometry from the various external files like
    * .prj, .j2w .xml and so on.
    */
   ossimRefPtr<ossimImageGeometry> getMetadataImageGeometry() const;

   // Cleans memory.  Called on close or destruct.
   void destroy();

   bool initSizRecord( std::istream* str,
                       ossimJ2kSizRecord& sizRecord) const;

   bool initCodRecord( std::istream* str,
                       ossimJ2kCodRecord& sizRecord) const;

   /**
    * @brief Initializes tiles.  Called once on first getTile request.
    */
   void allocate();

   ossimJ2kSizRecord m_sizRecord;

   ossimRefPtr<ossimImageData>  m_tile;
   ossimRefPtr<ossimImageData>  m_cacheTile;
   std::ifstream*               m_str;
   ossim_uint32                 m_minDwtLevels;
   ossim_int32                  m_format; // OPJ_CODEC_FORMAT

TYPE_DATA
};

#endif


text:
title: Air Safaris

listing-type: attractions
island: south
region: canterbury
destination: Lake Tekapo

order: a
image-path: air-safaris.jpg
image-alt: Air Safaris
refer-url: http://www.airsafaris.co.nz/
---
Offers spectacular, scenic fixed-wing flights over Lake Tekapo, Mackenzie country, Mt Cook and the alpine wonderland of New Zealand's majestic Southern Alps.

redpajama_set_name: RedPajamaGithub


text:
import abc
import sys

from oslo_versionedobjects import base as obj_base
from oslo_versionedobjects import fields as obj_fields
import six

from neutron.common import constants
from neutron.common import utils
from neutron.db import api as db_api
from neutron.db.qos import models as qos_db_model
from neutron.objects import base
from neutron.objects import common_types
from neutron.services.qos import qos_consts

DSCP_MARK = 'dscp_mark'

def get_rules(context, qos_policy_id):
    all_rules = []
    with db_api.autonested_transaction(context.session):
        for rule_type in qos_consts.VALID_RULE_TYPES:
            rule_cls_name = 'Qos%sRule' % utils.camelize(rule_type)
            rule_cls = getattr(sys.modules[__name__], rule_cls_name)

            rules = rule_cls.get_objects(context, qos_policy_id=qos_policy_id)
            all_rules.extend(rules)
    return all_rules

@six.add_metaclass(abc.ABCMeta)
class QosRule(base.NeutronDbObject):
    # Version 1.0: Initial version, only BandwidthLimitRule
    #         1.1: Added DscpMarkingRule
    #
    #NOTE(mangelajo): versions need to be handled from the top QosRule object
    #                 because it's the only reference QosPolicy can make
    #                 to them via obj_relationships version map
    VERSION = '1.1'

    fields = {
        'id': obj_fields.UUIDField(),
        'qos_policy_id': obj_fields.UUIDField()
    }

    fields_no_update = ['id', 'qos_policy_id']

    # should be redefined in subclasses
    rule_type = None

    def to_dict(self):
        dict_ = super(QosRule, self).to_dict()
        dict_['type'] = self.rule_type
        return dict_

    def should_apply_to_port(self, port):
        """Check whether a rule can be applied to a specific port.

        This function has the logic to decide whether a rule should
        be applied to a port or not, depending on the source of the
        policy (network, or port). Eventually rules could override
        this method, or we could make it abstract to allow different
        rule behaviour.
        """
        is_network_rule = self.qos_policy_id != port[qos_consts.QOS_POLICY_ID]
        is_network_device_port = any(port['device_owner'].startswith(prefix)
                                     for prefix
                                     in constants.DEVICE_OWNER_PREFIXES)

        return not (is_network_rule and is_network_device_port)

@obj_base.VersionedObjectRegistry.register
class QosBandwidthLimitRule(QosRule):

    db_model = qos_db_model.QosBandwidthLimitRule

    fields = {
        'max_kbps': obj_fields.IntegerField(nullable=True),
        'max_burst_kbps': obj_fields.IntegerField(nullable=True)
    }

    rule_type = qos_consts.RULE_TYPE_BANDWIDTH_LIMIT

@obj_base.VersionedObjectRegistry.register
class QosDscpMarkingRule(QosRule):

    db_model = qos_db_model.QosDscpMarkingRule

    fields = {
        DSCP_MARK: common_types.DscpMarkField(),
    }

    rule_type = qos_consts.RULE_TYPE_DSCP_MARK


text:
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse

from scipy_central.utils import get_IP_address
from scipy_central.pagehit.views import create_hit

from haystack.views import SearchView

import logging
logger = logging.getLogger('scipycentral')
logger.debug('Initializing pages::views.py')

def front_page(request):
    create_hit(request, 'spc-main-page')
    return render_to_response('pages/front-page.html', {},
                              context_instance=RequestContext(request))

def about_page(request):
    create_hit(request, 'spc-about-page')
    return render_to_response('pages/about-page.html', {},
                              context_instance=RequestContext(request))

def licence_page(request):
    create_hit(request, 'spc-about-licenses')
    return render_to_response('pages/about-licenses.html', {},
                              context_instance=RequestContext(request))

def search(request):
    """
    Calls Haystack, but allows us to first log the search query
    """

    if request.GET['q'].strip() == '':
        return redirect(front_page)

    # Avoid duplicate logging if search request results in more than 1 page
    if 'page' not in request.GET:
        create_hit(request, 'haystack_search', request.GET['q'])
        logger.info('SEARCH [%s]: %s' % (get_IP_address(request),
                                         request.GET['q']))
    return SearchView().__call__(request)

def markup_help(request):
    create_hit(request, 'spc-markup-help')
    return render_to_response('pages/markup-help.html', {},
                              context_instance=RequestContext(request))

def csrf_failure(request, reason=''):
    """ Provides a better output to the user when they don't have cookies
    enabled on their computer.
    """
    ip = get_IP_address(request)
    logger.info('CSRF failure from %s for request "%s", coming from "%s"' %\
                (ip, request.path, request.META.get('HTTP_REFERER', '??')))
    return render_to_response('pages/please-enable-cookies.html', {},
                              context_instance=RequestContext(request))

def not_implemented_yet(request, issue_number=None):
    """ Track how often users uncover items that haven't been implemented, so
    we can prioritize them
    """
    ip = get_IP_address(request)
    logger.info('Not implemented yet [%s] for request "%s" and issue=%s' %\
                (ip, request.path, str(issue_number)))
    return render_to_response('pages/not-implemented-yet.html',
                              {'issue_number': issue_number},
                              context_instance=RequestContext(request))

def page_404_error(request, extra_info=''):
    """ Override Django's 404 handler, because we want to log this also.
    """
    ip = get_IP_address(request)
    logger.info('404 from %s for request "%s"; extra info=%s' %\
                                          (ip, request.path, str(extra_info)))
    t = get_template('404.html')
    c = RequestContext(request)
    c.update({'extra_info': extra_info})
    html = t.render(c)
    return HttpResponse(html, status=404)

def page_500_error(request):
    """ Override Django's 500 handler, because we want to log this also.
    """
    ip = get_IP_address(request)
    logger.error('500 from %s for request "%s"' % (ip, request.path))
    t = get_template('500.html')
    html = t.render(RequestContext(request))
    return HttpResponse(html, status=500)


text:
'use strict';

var fs = require('fs');
var path = require('path');
var utils = require('./utils');
var blockTypes = require('./blocktypes');
var listFile = null;

var getBlocks = function (content, marker, filepath) {
  /*
   * <!-- build:<type>[:target] [value] -->
   * - type (required) js, css, attr, remove, template, include
   * - target|attribute (optional) i.e. dev, prod, release or attributes like [href] [src]
   * - value (optional) i.e. script.min.js
  */
  var regStart = new RegExp('<!--\\s*' + marker + ':(\\[?[\\w-]+\\]?)(?::([\\w,]+))?(?:\\s*(inline)\\s)?(?:\\s*([^\\s]+)\\s*-->)*');

  // <!-- /build -->
  var regEnd = new RegExp('(?:<!--\\s*)*\\/' + marker + '\\s*-->');

  // <link rel="stylesheet" href="js/bower_components/bootstrap/dist/css/bootstrap.css" />
  var cssHref = new RegExp('^\\s*<\\s*\\LINK.*HREF=["' + "'" + ']([^"' + "'" + ']*)["' + "'" + '].*$', 'i');

  // <script src="js/bower_components/xdate/src/xdate.js"></script>
  var jsSrc = new RegExp('^\\s*<\\s*\\SCRIPT.*SRC=["' + "'" + ']([^"' + "'" + ']*)["' + "'" + '].*$', 'i');

  // Normalize line endings and split in lines
  var lines = content.replace(/\r\n/g, '\n').split(/\n/);
  var inside = false;
  var sections = [];
  var block;

  lines.forEach(function (line) {
    var build = line.match(regStart);
    var endbuild = regEnd.test(line);
    var attr;

    if (build) {
      inside = true;
      attr = build[1].match(/(?:\[([\w\-]+)\])*/)[1];
      block = {
        type: attr ? 'attr': build[1],
        attr: attr,
        targets: !!build[2] ? build[2].split(',') : null,
        inline: !!build[3],
        asset: build[4],
        indent: /^\s*/.exec(line)[0],
        raw: []
      };
    }

    if (inside && block) {
      block.raw.push(line);
      if (listFile) {
        var match = line.match(cssHref);
        if (match != null) {
          //call the write option where you need to append new data
          listFile.write(filepath + ":" + match[1] + "\n");
        }
        else {
          match = line.match(jsSrc);
          if (match != null) {
            listFile.write(filepath + ":" + match[1] + "\n");
          }
        }
      }
    }

    if (inside && endbuild) {
      inside = false;
      sections.push(block);
    }
  });

  return sections;
};

// The processor
var HTMLProcessor = function (options) {
  var defaults = {
    data: {},
    environment: '',
    templateSettings: null,
    includeBase: null,
    commentMarker: 'build',
    strip: false,
    recursive: false,
    customBlockTypes: []
  };

  this.options = utils._.extend({}, defaults, options);
  this.data = utils._.extend({}, this.options.data, {environment: this.options.environment});

  // Register custom block types
  if (this.options.customBlockTypes.length) {
    this.options.customBlockTypes.forEach(function (processor) {
      require(path.resolve(processor)).call(this, this);

    }, this);
  }
};

HTMLProcessor.prototype._blockTypes = blockTypes;

HTMLProcessor.prototype.registerBlockType = function (name, fn) {
  this._blockTypes[name] = fn;
};

// Returns a single line of the current block comment
HTMLProcessor.prototype._getBlockLine = function (block) {
  return block.raw.join(this.linefeed);
};

// Returns the block content (not including the build comments)
HTMLProcessor.prototype._getBlockContent = function (block) {
  return block.raw.slice(1, -1).join(this.linefeed);
};

// Replace passed block with the processed content
HTMLProcessor.prototype._replace = function (block, content, filepath) {
  var blockLine = this._getBlockLine(block);
  var blockContent = this._getBlockContent(block);
  var result = this._blockTypes[block.type].call(this, content, block, blockLine, blockContent,
      filepath);

  return result;
};

// Strips blocks not matched for the current environment
HTMLProcessor.prototype._strip = function (block, content) {
  var blockLine = this._getBlockLine(block);
  var blockContent = this._getBlockContent(block);
  var result = content.split(blockLine).join(blockContent);

  return result;
};

HTMLProcessor.prototype._replaceBlocks = function (blocks, filepath) {
  var result = this.content;

  // Replace found blocks
  utils._.each(blocks, function (block) {

    // Parse through correct block type checking the build environment
    if (this._blockTypes[block.type] && (!block.targets ||
        utils._.indexOf(block.targets, this.options.environment) >= 0) || (!this.options.strip && !this.options.environment)) {
      result = this._replace(block, result, filepath);
    } else if (this.options.strip) {
      result = this._strip(block, result, filepath);
    }
  }, this);

  return result;
};

// Process the file content
HTMLProcessor.prototype.process = function (filepath) {
  return this.processContent(fs.readFileSync(filepath).toString(), filepath);
};

// Process the input content
HTMLProcessor.prototype.processContent = function (content, filepath) {
  this.content = content;
  this.linefeed = /\r\n/g.test(this.content) ? '\r\n' : '\n';

  if (this.options && this.options.list) {
    //Set our log file as a writestream variable with the 'a' flag
    listFile = fs.createWriteStream(this.options.list, {
      flags:    "a",
      encoding: "encoding",
      mode:    parseInt('744', 8)
    });
  }

  // Parse the file content to look for build comment blocks
  var blocks = getBlocks(this.content, this.options.commentMarker, filepath);

  // Replace found blocks
  content = this._replaceBlocks(blocks, filepath);

  return content;
};

HTMLProcessor.prototype.template = utils._.template;

// Export the processor
module.exports = HTMLProcessor;


text:
/*!
 *  Copyright (c) 2018 by Contributors
 * \brief Sample golang application to demonstrate go-closure given to a packed function argument.
 * \file pack_func_closure_arg.go
 */

package main

import (
    "fmt"
    "./gotvm"
)

// sampleFunctionArg receives a Packed Function handle and calls it.
func sampleFunctionArg(args ...*gotvm.Value) (retVal interface{}, err error) {
    // Reveive Packed Function Handle
    pfunc := args[0].AsFunction()
    // Call Packed Function
    retVal, err = pfunc.Invoke(args[1].AsInt64(), args[2].AsInt64())
    return
}

// main
func main() {
    // Not passing a function name implicitely
    // picks the name from reflection as "main.sampleDunctionArg"
    gotvm.RegisterFunction(sampleFunctionArg);
    fmt.Printf("Registered: sampleFunctionArg\n")

    // Get registered global function.
    funp, err := gotvm.GetGlobalFunction("main.sampleFunctionArg")
    if err != nil {
        fmt.Print(err)
        return
    }
    fmt.Printf("GetGlobalFunction: main.sampleFunctionArg - Success\n")

    // funccall is a simple golang callback function like C = A + B.
    funccall := func (args ...*gotvm.Value) (retVal interface{}, err error) {
        for _, v := range args {
            fmt.Printf("ARGS:%T : %v\n", v.AsInt64(), v.AsInt64())
        }
        val1 := args[0].AsInt64()
        val2 := args[1].AsInt64()
        retVal = int64(val1+val2)
        return
    }

    // Call function
    result, err := funp.Invoke(funccall, 30, 50)
    if err != nil {
        fmt.Print(err)
        return
    }
    fmt.Printf("Invoked sampleFunctionArg with function closure arg : Result:%v\n", result.AsInt64())
}


text:
package org.apache.spark.streaming.kafka

import java.net.InetSocketAddress

import org.apache.spark.{Logging, SparkConf}
import kafka.admin.AdminUtils
import kafka.api.Request
import kafka.common.TopicAndPartition
import kafka.producer.{KeyedMessage, Producer, ProducerConfig}
import kafka.server.{KafkaConfig, KafkaServer}
import kafka.serializer.DefaultEncoder

import java.util.Properties
import java.util.UUID

import org.apache.zookeeper.server.{NIOServerCnxnFactory, ZooKeeperServer}
import org.I0Itec.zkclient.ZkClient
import kafka.utils.{ZKStringSerializer, ZkUtils}
import org.apache.spark.streaming.Time
import java.util.concurrent.TimeoutException

import scala.annotation.tailrec
import scala.language.postfixOps
import scala.util.control.NonFatal

import com.holdenkarau.spark.testing.Utils

/**
 * This is a helper class for Kafka test suites. This has the functionality to set up
 * and tear down local Kafka servers, and to push data using Kafka producers.
 *
 */
class KafkaTestUtils extends Logging{

  // Zookeeper related configurations
  private val zkHost = "localhost"
  private var zkPort: Int = 0
  private val zkConnectionTimeout = 6000
  private val zkSessionTimeout = 6000

  private var zookeeper: EmbeddedZookeeper = _

  private var zkClient: ZkClient = _

  // Kafka broker related configurations
  private val brokerHost = "localhost"
  private var brokerPort = 9092
  private var brokerConf: KafkaConfig = _

  // Kafka broker server
  private var server: KafkaServer = _

  // Kafka producer
  private var producer: Producer[Array[Byte], Array[Byte]] = _

  // Flag to test whether the system is correctly started
  private var zkReady = false
  private var brokerReady = false

  def zkAddress: String = {
    assert(zkReady, "Zookeeper not setup yet or already torn down, cannot get zookeeper address")
    s"$zkHost:$zkPort"
  }

  def brokerAddress: String = {
    assert(brokerReady, "Kafka not setup yet or already torn down, cannot get broker address")
    s"$brokerHost:$brokerPort"
  }

  def zookeeperClient: ZkClient = {
    assert(zkReady, "Zookeeper not setup yet or already torn down, cannot get zookeeper client")
    Option(zkClient).getOrElse(
      throw new IllegalStateException("Zookeeper client is not yet initialized"))
  }

  private def brokerConfiguration: Properties = {
    val props = new Properties()
    props.put("broker.id", "0")
    props.put("host.name", "localhost")
    props.put("port", brokerPort.toString)
    props.put("log.dir", Utils.createTempDir().getAbsolutePath)
    props.put("zookeeper.connect", zkAddress)
    props.put("log.flush.interval.messages", "1")
    props.put("replica.socket.timeout.ms", "1500")
    props
  }

  private def producerConfiguration: Properties = {
    val props = new Properties()
    props.put("metadata.broker.list", brokerAddress)
    props.put("serializer.class", classOf[DefaultEncoder].getName)
    props
  }
  // Set up the Embedded Zookeeper server and get the proper Zookeeper port
  private def setupEmbeddedZookeeper(): Unit = {
    // Zookeeper server startup
    zookeeper = new EmbeddedZookeeper(s"$zkHost:$zkPort")
    // Get the actual zookeeper binding port
    zkPort = zookeeper.actualPort
    zkClient = new ZkClient(s"$zkHost:$zkPort", zkSessionTimeout, zkConnectionTimeout,
      ZKStringSerializer)
    zkReady = true
  }

  private def waitUntilMetadataIsPropagated(topic: String, partition: Int): Unit = {
    def isPropagated: Boolean = server.apis.metadataCache.getPartitionInfo(topic, partition) match {
      case Some(partitionState) =>
        val leaderAndInSyncReplicas = partitionState.leaderIsrAndControllerEpoch.leaderAndIsr

        ZkUtils.getLeaderForPartition(zkClient, topic, partition).isDefined &&
          Request.isValidBrokerId(leaderAndInSyncReplicas.leader) &&
          leaderAndInSyncReplicas.isr.size >= 1

      case _ =>
        false
    }
    eventually(Time(10000), Time(100)) {
      assert(isPropagated, s"Partition [$topic, $partition] metadata not propagated after timeout")
    }
  }
  // Set up the Embedded Kafka server
  private def setupEmbeddedKafkaServer(): Unit = {
    assert(zkReady, "Zookeeper should be set up beforehand")

    // Kafka broker startup
    Utils.startServiceOnPort(brokerPort, port => {
      brokerPort = port
      brokerConf = new KafkaConfig(brokerConfiguration)
      server = new KafkaServer(brokerConf)
      server.startup()
      (server, port)
    }, new SparkConf(), "KafkaBroker")

    brokerReady = true
  }

  /** setup the whole embedded servers, including Zookeeper and Kafka brokers */
  def setup(): Unit = {
    setupEmbeddedZookeeper()
    setupEmbeddedKafkaServer()
  }

  def teardown(): Unit = {
    brokerReady = false
    zkReady = false

    if (producer != null) {
      producer.close()
      producer = null
    }

    if (server != null) {
      server.shutdown()
      server = null
    }

    if (zkClient != null) {
      zkClient.close()
      zkClient = null
    }

    if (zookeeper != null) {
      zookeeper.shutdown()
      zookeeper = null
    }
  }

  /** Create a Kafka topic and wait until it propagated to the whole cluster */
  def createTopic(topic: String): Unit = {
    AdminUtils.createTopic(zkClient, topic, 1, 1)
    // wait until metadata is propagated
    waitUntilMetadataIsPropagated(topic, 0)
  }

  /** Send the array of messages to the Kafka broker */
  def sendMessages(topic: String, message: Array[Byte]): Unit = {
    producer = new Producer[Array[Byte], Array[Byte]](new ProducerConfig(producerConfiguration))
    producer.send(new KeyedMessage[Array[Byte], Array[Byte]](topic, message ) )
    producer.close()
    producer = null
  }

  private class EmbeddedZookeeper(val zkConnect: String) {
    val snapshotDir = Utils.createTempDir()
    val logDir = Utils.createTempDir()

    val zookeeper = new ZooKeeperServer(snapshotDir, logDir, 500)
    val (ip, port) = {
      val splits = zkConnect.split(":")
      (splits(0), splits(1).toInt)
    }
    val factory = new NIOServerCnxnFactory()
    factory.configure(new InetSocketAddress(ip, port), 16)
    factory.startup(zookeeper)

    val actualPort = factory.getLocalPort

    def shutdown() {
      zookeeper.shutdown()
      factory.shutdown()
    }
  }

  // A simplified version of scalatest eventually, rewritten here to avoid adding extra test
  // dependency
  def eventually[T](timeout: Time, interval: Time)(func: => T): T = {
    def makeAttempt(): Either[Throwable, T] = {
      try {
        Right(func)
      } catch {
        case e if NonFatal(e) => Left(e)
      }
    }

    val startTime = System.currentTimeMillis()
    @tailrec
    def tryAgain(attempt: Int): T = {
      makeAttempt() match {
        case Right(result) => result
        case Left(e) =>
          val duration = System.currentTimeMillis() - startTime
          if (duration < timeout.milliseconds) {
            Thread.sleep(interval.milliseconds)
          } else {
            throw new TimeoutException(e.getMessage)
          }

          tryAgain(attempt + 1)
      }
    }

    tryAgain(1)
  }

}


text:
//==============================================================================
// Some useful tests-related functions
//==============================================================================

#include "testsutils.h"

//==============================================================================

#include <QFile>
#include <QIODevice>
#include <QProcess>

//==============================================================================

namespace OpenCOR {

//==============================================================================

QString fileName(const QString &pFileName)
{
    // Format and return the given file name, so that it can be used on all our
    // supported platforms

#if defined(Q_OS_WIN)
    return "..\\..\\..\\"+QString(pFileName).replace("/", "\\");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    return pFileName;
#else
    #error Unsupported platform
#endif
}

//==============================================================================

QString cliFileName(const QString &pFileName)
{
    // Format and return the given file name, so that it can be used on all our
    // supported platforms through the CLI version of OpenCOR

#if defined(Q_OS_WIN)
    return "..\\..\\"+QString(pFileName).replace("/", "\\");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    return pFileName;
#else
    #error Unsupported platform
#endif
}

//==============================================================================

QStringList fileContents(const QString &pFileName)
{
    // Read and return the contents of the given file

    QFile file(pFileName);
    QString contents = QString();

    if (file.open(QIODevice::ReadOnly|QIODevice::Text)) {
        // Note: QIODevice::Text ensures that end-of-line terminators are
        //       converted to "\n", which is exactly what we want...

        contents = file.readAll();

        file.close();
    }

    return contents.split("\n");
}

//==============================================================================

QStringList runCli(const QStringList pArguments)
{
    // Go to the directory where our tests are located
    // Note: see main()...

#ifdef Q_OS_WIN
    QString crtPath = QDir::currentPath();

    QDir::setCurrent(crtPath+"/../../bin");
#endif

    // Execute the CLI version of OpenCOR (passing to it the given arguments)
    // and return the output it has generated, if any

#if defined(Q_OS_WIN)
    QString program = "OpenCOR.com";
#elif defined(Q_OS_LINUX)
    QString program = "build/bin/OpenCOR";
#elif defined(Q_OS_MAC)
    QString program = "build/OpenCOR.app/Contents/MacOS/OpenCOR";
#else
    #error Unsupported platform
#endif

    QProcess process;

    process.setProcessChannelMode(QProcess::MergedChannels);

    QStringList defaultArguments = QStringList();

    process.start(program, defaultArguments << pArguments);

    QString output = QString();

    while (process.waitForReadyRead())
        output += process.readAll();

    // Go back to our original directory

#ifdef Q_OS_WIN
    QDir::setCurrent(crtPath);
#endif

    return output.remove("\r").split("\n");
}

//==============================================================================

}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================


text:
static s: &'static str =
    r#" string literal goes on
        and on
    //~^^ ERROR unterminated raw string


text:
'use strict';

const React = require('react');
const TweetsApp = require('./components/TweetsApp.react');

var initialState = JSON.parse(document.getElementById('initial-state').innerHTML); //Grabs initial state that was passed from server side

React.render(
  <TweetsApp tweets={initialState}/>,
  document.getElementById('react-app')
);


text:
#ifndef WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_
#define WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_

#include <cstddef> // size_t, ptrdiff_t

#include "typedefs.h"
#include "rtp_header_extension.h"
#include "rtp_rtcp_config.h"
#include "rtp_rtcp_defines.h"

namespace webrtc {
enum RtpVideoCodecTypes
{
    kRtpGenericVideo  = 0,
    kRtpFecVideo      = 10,
    kRtpVp8Video      = 11
};

const uint8_t kRtpMarkerBitMask = 0x80;

namespace ModuleRTPUtility
{
    // January 1970, in NTP seconds.
    const uint32_t NTP_JAN_1970 = 2208988800UL;

    // Magic NTP fractional unit.
    const double NTP_FRAC = 4.294967296E+9;

    struct AudioPayload
    {
        uint32_t    frequency;
        uint8_t     channels;
        uint32_t    rate;
    };
    struct VideoPayload
    {
        RtpVideoCodecTypes   videoCodecType;
        uint32_t       maxRate;
    };
    union PayloadUnion
    {
        AudioPayload Audio;
        VideoPayload Video;
    };
    struct Payload
    {
        char name[RTP_PAYLOAD_NAME_SIZE];
        bool audio;
        PayloadUnion typeSpecific;
    };

    typedef std::map<int8_t, Payload*> PayloadTypeMap;

    // Return the current RTP timestamp from the NTP timestamp
    // returned by the specified clock.
    uint32_t GetCurrentRTP(Clock* clock, uint32_t freq);

    // Return the current RTP absolute timestamp.
    uint32_t ConvertNTPTimeToRTP(uint32_t NTPsec,
                                 uint32_t NTPfrac,
                                 uint32_t freq);

    // Return the time in milliseconds corresponding to the specified
    // NTP timestamp.
    uint32_t ConvertNTPTimeToMS(uint32_t NTPsec,
                                uint32_t NTPfrac);

    uint32_t pow2(uint8_t exp);

    // Returns a pointer to the payload data given a packet.
    const uint8_t* GetPayloadData(const WebRtcRTPHeader* rtp_header,
                                  const uint8_t* packet);

    // Returns payload length given a packet.
    uint16_t GetPayloadDataLength(const WebRtcRTPHeader* rtp_header,
                                  const uint16_t packet_length);

    // Returns true if |newTimestamp| is older than |existingTimestamp|.
    // |wrapped| will be set to true if there has been a wraparound between the
    // two timestamps.
    bool OldTimestamp(uint32_t newTimestamp,
                      uint32_t existingTimestamp,
                      bool* wrapped);

    bool StringCompare(const char* str1,
                       const char* str2,
                       const uint32_t length);

    void AssignUWord32ToBuffer(uint8_t* dataBuffer, uint32_t value);
    void AssignUWord24ToBuffer(uint8_t* dataBuffer, uint32_t value);
    void AssignUWord16ToBuffer(uint8_t* dataBuffer, uint16_t value);

    /**
     * Converts a network-ordered two-byte input buffer to a host-ordered value.
     * \param[in] dataBuffer Network-ordered two-byte buffer to convert.
     * \return Host-ordered value.
     */
    uint16_t BufferToUWord16(const uint8_t* dataBuffer);

    /**
     * Converts a network-ordered three-byte input buffer to a host-ordered value.
     * \param[in] dataBuffer Network-ordered three-byte buffer to convert.
     * \return Host-ordered value.
     */
    uint32_t BufferToUWord24(const uint8_t* dataBuffer);

    /**
     * Converts a network-ordered four-byte input buffer to a host-ordered value.
     * \param[in] dataBuffer Network-ordered four-byte buffer to convert.
     * \return Host-ordered value.
     */
    uint32_t BufferToUWord32(const uint8_t* dataBuffer);

    class RTPHeaderParser
    {
    public:
        RTPHeaderParser(const uint8_t* rtpData,
                        const uint32_t rtpDataLength);
        ~RTPHeaderParser();

        bool RTCP() const;
        bool Parse(WebRtcRTPHeader& parsedPacket,
                   RtpHeaderExtensionMap* ptrExtensionMap = NULL) const;

    private:
        void ParseOneByteExtensionHeader(
            WebRtcRTPHeader& parsedPacket,
            const RtpHeaderExtensionMap* ptrExtensionMap,
            const uint8_t* ptrRTPDataExtensionEnd,
            const uint8_t* ptr) const;

        uint8_t ParsePaddingBytes(
            const uint8_t* ptrRTPDataExtensionEnd,
            const uint8_t* ptr) const;

        const uint8_t* const _ptrRTPDataBegin;
        const uint8_t* const _ptrRTPDataEnd;
    };

    enum FrameTypes
    {
        kIFrame,    // key frame
        kPFrame         // Delta frame
    };

    struct RTPPayloadVP8
    {
        bool                 nonReferenceFrame;
        bool                 beginningOfPartition;
        int                  partitionID;
        bool                 hasPictureID;
        bool                 hasTl0PicIdx;
        bool                 hasTID;
        bool                 hasKeyIdx;
        int                  pictureID;
        int                  tl0PicIdx;
        int                  tID;
        bool                 layerSync;
        int                  keyIdx;
        int                  frameWidth;
        int                  frameHeight;

        const uint8_t*   data;
        uint16_t         dataLength;
    };

    union RTPPayloadUnion
    {
        RTPPayloadVP8   VP8;
    };

    struct RTPPayload
    {
        void SetType(RtpVideoCodecTypes videoType);

        RtpVideoCodecTypes  type;
        FrameTypes          frameType;
        RTPPayloadUnion     info;
    };

    // RTP payload parser
    class RTPPayloadParser
    {
    public:
        RTPPayloadParser(const RtpVideoCodecTypes payloadType,
                         const uint8_t* payloadData,
                         const uint16_t payloadDataLength, // Length w/o padding.
                         const int32_t id);

        ~RTPPayloadParser();

        bool Parse(RTPPayload& parsedPacket) const;

    private:
        bool ParseGeneric(RTPPayload& parsedPacket) const;

        bool ParseVP8(RTPPayload& parsedPacket) const;

        int ParseVP8Extension(RTPPayloadVP8 *vp8,
                              const uint8_t *dataPtr,
                              int dataLength) const;

        int ParseVP8PictureID(RTPPayloadVP8 *vp8,
                              const uint8_t **dataPtr,
                              int *dataLength,
                              int *parsedBytes) const;

        int ParseVP8Tl0PicIdx(RTPPayloadVP8 *vp8,
                              const uint8_t **dataPtr,
                              int *dataLength,
                              int *parsedBytes) const;

        int ParseVP8TIDAndKeyIdx(RTPPayloadVP8 *vp8,
                                 const uint8_t **dataPtr,
                                 int *dataLength,
                                 int *parsedBytes) const;

        int ParseVP8FrameSize(RTPPayload& parsedPacket,
                              const uint8_t *dataPtr,
                              int dataLength) const;

    private:
        int32_t               _id;
        const uint8_t*        _dataPtr;
        const uint16_t        _dataLength;
        const RtpVideoCodecTypes    _videoType;
    };

}  // namespace ModuleRTPUtility

}  // namespace webrtc

#endif // WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_


text:
'use strict';
const Boom = require('boom');
const Included = require('./included');
const Paginate = require('./paginate');

module.exports.register = function register(server, registry) {
  server.method('jsonapi.checkMissing', function checkMissing(model) {
    if (!model)
      throw Boom.notFound('Resource not found for that identifier');
    return model;
  });
  const checkMissing = server.methods.jsonapi.checkMissing;
  const knex = server.plugins.bookshelf.knex;

  function catchErrors(handler) {
    return (function (request, reply) {
      try {
        return handler(request, reply);
      } catch(err) {
        return reply(Boom.wrap(err));
      }
    }).bind(this);
  }

  registry.forEach(function (resource) {
    const ResModel = server.plugins.bookshelf.model(resource.model);
    const tableName = (new ResModel()).tableName;
    const updatedCol = resource.specialCols.updated;
    const loaded = resource.getRelLoaded();

    function callHook(hookName, request, state, trx) {
      var hook;
      try {
        hook = server.methods.jsonapi[resource.type][hookName];
      } catch (err) {}
      if (!hook) return Promise.resolve();
      return Promise.resolve().then(() => hook.call(request, state, trx));
    }

    function getConf(action, rel, relInfo) {
      const relationship = {name: rel};
      var readonly = resource.readonly;
      if (relInfo) {
        readonly = readonly || relInfo.readonly;
        Object.assign(relationship, relInfo);
      }
      return {
        isInternal: readonly && ['index', 'fetch'].indexOf(action) === -1,
        plugins: {
          'hapi-bookshelf-jsonapi': {
            resource: resource,
            action: action,
            relationship: relationship,
          },
        },
      };
    }

    server.method(`jsonapi.${resource.type}.serialize`,
    function serializeResource(model, included, request) {
      var query;
      if (request) query = resource.parseQuery(request);
      const serializer = resource.getSerializer(query);
      return {data: serializer.serialize(model, included)};
    });

    server.route({
      method: 'POST',
      path: resource.getPath(),
      config: Object.assign(getConf('create'), {
        validate: {payload: registry.schema.getCreateSchema(resource.type)},
      }),
      handler: catchErrors(function (request, reply) {
        const query = resource.parseQuery(request);
        const serializer = resource.getSerializer(query);
        const result = serializer.deserialize(request.payload);
        server.plugins.bookshelf.transaction(trx => {
          return callHook('beforeCreate', request, result, trx)
            .then(() => serializer.save(new ResModel(), result, trx))
            .then(model => model.refresh({transacting: trx}));
        })
          .then(model => {
            return reply({data: serializer.serialize(model)})
              .code(201).header('location', resource.getPath(model.id));
          })
          .catch(err => reply(err));
      }),
    });

    server.route({
      method: 'GET',
      path: resource.getPath(),
      config: getConf('index'),
      handler: catchErrors(function (request, reply) {
        const included = new Included();
        const paginate = new Paginate(request);
        const query = resource.parseQuery(request);
        const serializer = resource.getSerializer(query);
        ResModel.query(paginate.query).query(query.query).fetchAll(query.fetch)
          .then(collection => {
            return reply({
              data: collection.map(model => serializer.serialize(model, included)),
              links: paginate.getLinks(collection),
              included: included,
            });
          })
          .catch(err => reply(err));
      }),
    });

    server.route({
      method: 'GET',
      path: resource.getPath('{id}'),
      config: getConf('fetch'),
      handler: catchErrors(function (request, reply) {
        const included = new Included();
        const query = resource.parseQuery(request);
        const serializer = resource.getSerializer(query);
        ResModel.where(`${tableName}.id`, request.params.id).query(query.query).fetch(query.fetch)
          .then(checkMissing)
          .then(model => {
            return reply({
              data: serializer.serialize(model, included),
              included: included,
            });
          })
          .catch(err => reply(err));
      }),
    });

    server.route({
      method: 'PATCH',
      path: resource.getPath('{id}'),
      config: Object.assign(getConf('update'), {
        validate: {payload: registry.schema.getUpdateSchema(resource.type)},
      }),
      handler: catchErrors(function (request, reply) {
        const query = resource.parseQuery(request);
        const serializer = resource.getSerializer(query);
        const result = serializer.deserialize(request.payload)
        server.plugins.bookshelf.transaction(trx => {
          return callHook('beforeUpdate', request, result, trx)
            .then(() => serializer.save(new ResModel({id: request.params.id}), result, trx))
            .then(model => {
              if (updatedCol) {
                return model.save(
                  {[updatedCol]: knex.fn.now()},
                  {patch: true, transacting: trx}
                );
              }
            })
            .then(checkMissing)
            .then(model => model.refresh({transacting: trx}));
        })
          .then(model => reply({data: serializer.serialize(model)}))
          .catch(err => reply(err));
      }),
    });

    server.route({
      method: 'DELETE',
      path: resource.getPath('{id}'),
      config: getConf('delete'),
      handler: catchErrors(function (request, reply) {
        const id = request.params.id;
        callHook('beforeDelete', request, id)
          .then(() => ResModel.where(`${tableName}.id`, id).destroy())
          .then(() => reply().code(204))
          .catch(err => reply(err));
      }),
    });

    resource.forEachRelOne(function (rel, relInfo) {
      server.route({
        method: 'GET',
        path: resource.getPath('{id}', rel),
        config: getConf('fetch', rel, relInfo),
        handler: catchErrors(function (request, reply) {
          const query = resource.parseQuery(request);
          const serializer = resource.getSerializer(query);
          ResModel.where(`${tableName}.id`, request.params.id)
            .query(query.query).fetch(query.fetch)
            .then(checkMissing)
            .then(model => reply(serializer.serializeRelOne(model, rel)))
            .catch(err => reply(err));
        }),
      });

      server.route({
        method: 'PATCH',
        path: resource.getPath('{id}', rel),
        config: Object.assign(getConf('update', rel, relInfo), {
          validate: {payload: registry.schema.getHasOneSchema()},
        }),
        handler: catchErrors(function (request, reply) {
          const query = resource.parseQuery(request);
          const serializer = resource.getSerializer(query);
          const relId = serializer.deserializeRelOne(request.payload, rel);
          Promise.resolve(new ResModel({id: request.params.id}))
            .then(model => serializer.saveRelOne(model, rel, relId))
            .then(checkMissing)
            .then(model => reply(serializer.serializeRelOne(model, rel)))
            .catch(err => reply(err));
        }),
      });
    });

    resource.forEachRelMany(function (rel, relInfo) {
      server.route({
        method: 'GET',
        path: resource.getPath('{id}')+`/${rel}`,
        config: getConf('index', rel, relInfo),
        handler: catchErrors(function (request, reply) {
          const included = new Included();
          const paginate = new Paginate(request);
          const query = relInfo.resource.parseQuery(request);
          const serializer = relInfo.resource.getSerializer(query);
          ResModel.where(`${tableName}.id`, request.params.id)
            .fetch({withRelated: {[rel]: qb => {
              query.query(qb);
              paginate.query(qb);
            }}})
            .then(checkMissing)
            .then(model => {
              const collection = model.related(rel);
              return collection.load(query.fetch.withRelated);
            })
            .then(collection => {
              return reply({
                data: collection.map(model => serializer.serialize(model, included)),
                links: paginate.getLinks(collection),
                included: included,
              });
            })
            .catch(err => reply(err));
        }),
      });

      server.route({
        method: 'GET',
        path: resource.getPath('{id}', rel),
        config: getConf('fetch', rel, relInfo),
        handler: catchErrors(function (request, reply) {
          const paginate = new Paginate(request);
          const serializer = resource.getSerializer();
          ResModel.where(`${tableName}.id`, request.params.id)
            .fetch({withRelated: {[rel]: qb => {
              paginate.query(qb);
              qb.select('id');
            }}})
            .then(checkMissing)
            .then(model => {
              const collection = model.related(rel);
              return reply(serializer.serializeRelMany(model, rel, collection, paginate));
            })
            .catch(err => reply(err));
        }),
      });

      server.route({
        method: 'POST',
        path: resource.getPath('{id}', rel),
        config: Object.assign(getConf('update', rel, relInfo), {
          validate: {payload: registry.schema.getHasManySchema()},
        }),
        handler: catchErrors(function (request, reply) {
          const serializer = resource.getSerializer();
          ResModel.where(`${tableName}.id`, request.params.id).fetch()
            .then(checkMissing)
            .then(model => {
              const add = serializer.deserializeRelMany(request.payload, rel);
              return serializer.saveRelMany(model, rel, add).then(() => model);
            })
            .then(model => reply(serializer.serializeRelMany(model, rel)))
            .catch(err => reply(err));
        }),
      });

      server.route({
        method: 'PATCH',
        path: resource.getPath('{id}', rel),
        config: Object.assign(getConf('update', rel, relInfo), {
          validate: {payload: registry.schema.getHasManySchema()},
        }),
        handler: catchErrors(function (request, reply) {
          const serializer = resource.getSerializer();
          ResModel.where(`${tableName}.id`, request.params.id).fetch()
            .then(checkMissing)
            .then(model => {
              const replace = serializer.deserializeRelMany(request.payload, rel);
              return server.plugins.bookshelf.transaction(trx => {
                return model.related(rel).detach(null, {transacting: trx})
                  .then(() => serializer.saveRelMany(model, rel, replace, trx))
                  .then(() => model);
              });
            })
            .then(model => reply(serializer.serializeRelMany(model, rel)))
            .catch(err => reply(err));
        }),
      });

      server.route({
        method: 'DELETE',
        path: resource.getPath('{id}', rel),
        config: getConf('update', rel, relInfo),
        handler: catchErrors(function (request, reply) {
          const serializer = resource.getSerializer();
          ResModel.where(`${tableName}.id`, request.params.id).fetch()
            .then(checkMissing)
            .then(model => {
              const remove = serializer.deserializeRelMany(request.payload, rel);
              return model.related(rel).detach(remove).then(() => model);
            })
            .then(model => reply(serializer.serializeRelMany(model, rel)))
            .catch(err => reply(err));
        }),
      });
    });
  });
};


text:
namespace Structures {

class IStructure {

};

}


text:
""" JSONService is a module providing JSON RPC Client side proxying.
"""

import sys
from HTTPRequest import HTTPRequest

try:
    from jsonrpc.json import dumps, loads, JSONDecodeException
except ImportError:
    from pyjamas.JSONParser import JSONParser
    parser = JSONParser()
    dumps = getattr(parser, 'encode')
    loads = getattr(parser, 'decodeAsObject')
    JSONDecodeException = None

class JSONServiceError(Exception):
    pass

__requestID = 0
__requestIDPrefix = 'ID'
__lastRequestID = None
def nextRequestID():
    """
    Return Next Request identifier.
    MUST be a JSON scalar (String, Number, True, False), but SHOULD normally
    not be Null, and Numbers SHOULD NOT contain fractional parts.
    """
    global __requestID, __requestIDPrefix, __lastRequestID
    __requestID += 1
    id = "%s%s" % (__requestIDPrefix, __requestID)
    if __lastRequestID == id:
        # javascript integer resolution problem
        __requestIDPrefix += '_'
        __requestID = 0
        id = "%s%s" % (__requestIDPrefix, __requestID)
    __lastRequestID = id
    return id

# no stream support
class JSONService(object):
    def __init__(self, url, handler=None, headers=None):
        """
        Create a JSON remote service object. The url is the URL that will
        receive POST data with the JSON request. See the JSON-RPC spec for
        more information.

        The handler object should implement
            onRemoteResponse(value, requestInfo)
        to accept the return value of the remote method, and
            onRemoteError(code, error_dict, requestInfo)
                 code = http-code or 0
                 error_dict is an jsonrpc 2.0 error dict:
                     {
                       'code': jsonrpc-error-code (integer) ,
                       'message': jsonrpc-error-message (string) ,
                       'data' : extra-error-data
                     }
        to handle errors.
        """
        self.url = url
        self.handler = handler
        self.headers = headers if headers is not None else {}
        if not self.headers.get("Accept"):
            self.headers["Accept"] = "application/json"

    def callMethod(self, method, params, handler = None):
        if handler is None:
            handler = self.handler

        if handler is None:
            return self.sendNotify(method, params)
        else:
            return self.sendRequest(method, params, handler)

    def onCompletion(self, response):
        pass

    def sendNotify(self, method, params):
        # jsonrpc: A String specifying the version of the JSON-RPC protocol.
        #          MUST be exactly "2.0"
        #          If jsonrpc is missing, the server MAY handle the Request as
        #          JSON-RPC V1.0-Request.
        # version: String specifying the version of the JSON-RPC protocol.
        #          MUST be exactly "1.1"
        # NOTE: We send both, to indicate that we can handle both.
        #
        # id:      If omitted, the Request is a Notification
        #          NOTE: JSON-RPC 1.0 uses an id of Null for Notifications.
        # method:  A String containing the name of the procedure to be invoked.
        # params:  An Array or Object, that holds the actual parameter values
        #          for the invocation of the procedure. Can be omitted if
        #          empty.
        #          NOTE: JSON-RPC 1.0 only a non-empty Array is used
        # From the spec of 1.1:
        #     The Content-Type MUST be specified and # SHOULD read
        #     application/json.
        #     The Accept MUST be specified and SHOULD read application/json.
        #
        msg = {"jsonrpc": "2.0",
               "version": "1.1",
               "method": method,
               "params": params
              }
        msg_data = dumps(msg)
        if not HTTPRequest().asyncPost(self.url, msg_data, self,
                                       False, "text/json",
                                       self.headers):
            return -1
        return 1

    def sendRequest(self, method, params, handler):
        id = nextRequestID()
        msg = {"jsonrpc": "2.0",
               "id": id,
               "method": method,
               "params": params
              }
        msg_data = dumps(msg)

        request_info = JSONRequestInfo(id, method, handler)
        if not HTTPRequest().asyncPost(self.url, msg_data,
                                       JSONResponseTextHandler(request_info),
                                       False, "text/json",
                                       self.headers):
            return -1
        return id

class JSONRequestInfo(object):
    def __init__(self, id, method, handler):
        self.id = id
        self.method = method
        self.handler = handler

class JSONResponseTextHandler(object):
    def __init__(self, request):
        self.request = request

    def onCompletion(self, json_str):
        try:
            response = loads(json_str)
        except JSONDecodeException:
            # err.... help?!!
            error = dict(
                         code=-32700,
                         message="Parse error while decoding response",
                         data=None,
                        )
            self.request.handler.onRemoteError(0, error, self.request)
            return

        if not response:
            error = dict(
                         code=-32603,
                         message="Empty Response",
                         data=None,
                        )
            self.request.handler.onRemoteError(0, error, self.request)
        elif response.get("error"):
            error = response["error"]
            jsonrpc = response.get("jsonrpc")
            code = error.get("code", 0)
            message = error.get("message", error)
            data = error.get("data")
            if not jsonrpc:
                jsonrpc = response.get("version", "1.0")
                if jsonrpc == "1.0":
                    message = error
                else:
                    data = error.get("error")
            error = dict(
                         code=code,
                         message=message,
                         data=data,
                        )
            self.request.handler.onRemoteError(0, error, self.request)
        elif "result" in response:
            self.request.handler.onRemoteResponse(response["result"],
                                                  self.request)
        else:
            error = dict(
                         code=-32603,
                         message="No result or error in response",
                         data=response,
                        )
            self.request.handler.onRemoteError(0, error, self.request)

    def onError(self, error_str, error_code):
        error = dict(
                     code=error_code,
                     message=error_str,
                     data=None,
                    )
        self.request.handler.onRemoteError(error_code, error, self.request)

class ServiceProxy(JSONService):
    def __init__(self, serviceURL, serviceName=None, headers=None):
        JSONService.__init__(self, serviceURL, headers=headers)
        self.__serviceName = serviceName

    def __call__(self, *params, **kwargs):
        if isinstance(params, tuple):
            params = list(params)
        if params and hasattr(params[-1], "onRemoteResponse"):
            handler = params.pop()
        else:
            handler = None
        if kwargs:
            if params:
                if not isinstance(params, dict):
                    raise JSONServiceError("Cannot mix positional and keyword arguments")
                params.update(kwargs)
            else:
                params = kwargs
        if handler is not None:
            return JSONService.sendRequest(self, self.__serviceName,
                                           params, handler)
        else:
            return JSONService.sendNotify(self, self.__serviceName, params)

# reserved names: callMethod, onCompletion
class JSONProxy(JSONService):
    def __init__(self, url, methods=None, headers=None):
        self._serviceURL = url
        self.methods = methods
        self.headers = {} if headers is None else headers
        # Init with JSONService, for the use of callMethod
        JSONService.__init__(self, url, headers=self.headers)
        self.__registerMethods(methods)

    def __registerMethods(self, methods):
        if methods:
            for method in methods:
                setattr(self,
                        method,
                        getattr(ServiceProxy(self._serviceURL, method,
                                             headers=self.headers),
                                '__call__')
                       )

    # It would be nice to use __getattr__ (in stead of __registerMethods)
    # However, that doesn't work with pyjs and the use of __registerMethods
    # saves some repeated instance creations (now only once per method and
    # not once per call)
    #def __getattr__(self, name):
    #    if not name in self.methods:
    #        raise AttributeError("no such method %s" % name)
    #    return ServiceProxy(self._serviceURL, name, headers=self.headers)


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Overview List</title>
<meta name="date" content="2017-12-05">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

com.ucloud.ulive

com.ucloud.ulive.filter

com.ucloud.ulive.filter.video.cpu

com.ucloud.ulive.filter.video.gpu


text:
package com.hubspot.nebula.deploy;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.hubspot.nebula.Result;

@JsonIgnoreProperties( ignoreUnknown = true )
public class Deploy implements Result {
  private final long id;

  @NotNull
  private final DeployAction action;

  @NotNull
  private final DeployStatus status;

  @NotNull
  private final String deployKey;

  @NotNull
  private final String buildKey;

  @Min(0)
  private final int buildNumber;

  @NotNull
  private final String environment;

  @Min(0)
  private final long startTime;

  @Min(0)
  private final long duration;

  private final Optional<Long> rollbackDeployId;

  private final String deployConfigSnapshot;

  @NotNull
  private final String user;

  @JsonCreator
  public Deploy(@JsonProperty("id") long id,
                @JsonProperty("action") DeployAction action,
                @JsonProperty("status") DeployStatus status,
                @JsonProperty("deployKey") String deployKey,
                @JsonProperty("buildKey") String buildKey,
                @JsonProperty("buildNumber") int buildNumber,
                @JsonProperty("environment") String environment,
                @JsonProperty("startTime") long startTime,
                @JsonProperty("duration") long duration,
                @JsonProperty("rollbackDeployId") Optional<Long> rollbackDeployId,
                @JsonProperty("deployConfigSnapshot") String deployConfigSnapshot,
                @JsonProperty("user") String user) {
    this.id = id;
    this.action = action;
    this.status = status;
    this.deployKey = deployKey;
    this.buildKey = buildKey;
    this.buildNumber = buildNumber;
    this.environment = environment;
    this.startTime = startTime;
    this.duration = duration;
    this.rollbackDeployId = rollbackDeployId;
    this.deployConfigSnapshot = deployConfigSnapshot;
    this.user = user;
  }

  public long getId() {
    return id;
  }

  public DeployAction getAction() {
    return action;
  }

  public DeployStatus getStatus() {
    return status;
  }

  public String getDeployKey() {
    return deployKey;
  }

  public String getBuildKey() {
    return buildKey;
  }

  public int getBuildNumber() {
    return buildNumber;
  }

  public String getEnvironment() {
    return environment;
  }

  public long getStartTime() {
    return startTime;
  }

  public long getDuration() {
    return duration;
  }

  public Optional<Long> getRollbackDeployId() {
    return rollbackDeployId;
  }

  public String getDeployConfigSnapshot() {
    return deployConfigSnapshot;
  }

  public String getUser() {
    return user;
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("id", id)
        .add("action", action)
        .add("status", status)
        .add("deployKey", deployKey)
        .add("buildKey", buildKey)
        .add("buildNumber", buildNumber)
        .add("environment", environment)
        .add("startTime", startTime)
        .add("duration", duration)
        .add("rollbackDeployId", rollbackDeployId)
        .add("deployConfigSnapshot", deployConfigSnapshot)
        .add("user", user)
        .toString();
  }
}


text:
<?php

namespace BYS\CoreBundle\Controller;

use BYS\CoreBundle\Entity\Proposal;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Proposal controller.
 *
 * @Route("proposal")
 */
class ProposalController extends Controller
{
    /**
     * Lists all proposal entities.
     *
     * @Route("/", name="proposal_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $proposals = $em->getRepository('BYSCoreBundle:Proposal')->findAll();

        return $this->render('proposal/index.html.twig', array(
            'proposals' => $proposals,
        ));
    }

    /**
     * Creates a new proposal entity.
     *
     * @Route("/new", name="proposal_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $proposal = new Proposal();
        $form = $this->createForm('BYS\CoreBundle\Form\ProposalType', $proposal);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($proposal);
            $em->flush($proposal);

            return $this->redirectToRoute('proposal_show', array('id' => $proposal->getId()));
        }

        return $this->render('proposal/new.html.twig', array(
            'proposal' => $proposal,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a proposal entity.
     *
     * @Route("/{id}", name="proposal_show")
     * @Method("GET")
     */
    public function showAction(Proposal $proposal)
    {
        $deleteForm = $this->createDeleteForm($proposal);

        return $this->render('proposal/show.html.twig', array(
            'proposal' => $proposal,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing proposal entity.
     *
     * @Route("/{id}/edit", name="proposal_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Proposal $proposal)
    {
        $deleteForm = $this->createDeleteForm($proposal);
        $editForm = $this->createForm('BYS\CoreBundle\Form\ProposalType', $proposal);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('proposal_edit', array('id' => $proposal->getId()));
        }

        return $this->render('proposal/edit.html.twig', array(
            'proposal' => $proposal,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a proposal entity.
     *
     * @Route("/{id}", name="proposal_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Proposal $proposal)
    {
        $form = $this->createDeleteForm($proposal);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($proposal);
            $em->flush($proposal);
        }

        return $this->redirectToRoute('proposal_index');
    }

    /**
     * Creates a form to delete a proposal entity.
     *
     * @param Proposal $proposal The proposal entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Proposal $proposal)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('proposal_delete', array('id' => $proposal->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
from __future__ import absolute_import, division, print_function

from itertools import chain
import os
import sys
from fnmatch import fnmatch

from setuptools import setup

import versioneer

def ispackage(x):
    return os.path.isdir(x) and os.path.exists(os.path.join(x, '__init__.py'))

def istestdir(x):
    return os.path.isdir(x) and not os.path.exists(os.path.join(x, '__init__.py'))

def find_packages(where='blaze', exclude=('ez_setup', 'distribute_setup'),
                  predicate=ispackage):
    if sys.version_info[0] == 3:
        exclude += ('*py2only*', '*__pycache__*')

    func = lambda x: predicate(x) and not any(fnmatch(x, exc)
                                              for exc in exclude)
    return list(filter(func, [x[0] for x in os.walk(where)]))

packages = find_packages()
testdirs = find_packages(predicate=(lambda x: istestdir(x) and
                                    os.path.basename(x) == 'tests'))

def find_data_files(exts, where='blaze'):
    exts = tuple(exts)
    for root, dirs, files in os.walk(where):
        for f in files:
            if any(fnmatch(f, pat) for pat in exts):
                yield os.path.join(root, f)

exts = '*.h5', '*.tsv', '*.csv', '*.xls', '*.xlsx', '*.db', '*.json', '*.gz', '*.hdf5'
package_data = [os.path.join(x.replace('blaze' + os.sep, ''), '*.py')
                for x in testdirs]
package_data += [x.replace('blaze' + os.sep, '')
                 for x in find_data_files(exts)]

def read(filename):
    with open(filename, 'r') as f:
        return f.read()

def read_reqs(filename):
    return read(filename).strip().splitlines()

def install_requires():
    reqs = read_reqs('etc/requirements.txt')
    if sys.version_info[0] == 2:
        reqs += read_reqs('etc/requirements_py2.txt')
    return reqs

def extras_require():
    extras = {req: read_reqs('etc/requirements_%s.txt' % req)
              for req in {'bcolz',
                          'ci',
                          'dask',
                          'h5py',
                          'mongo',
                          'mysql',
                          'numba',
                          'postgres',
                          'pyhive',
                          'pytables',
                          'server',
                          'sql',
                          'test'}}

    extras['mysql'] += extras['sql']
    extras['postgres'] += extras['sql']

    # don't include the 'ci' or 'test' targets in 'all'
    extras['all'] = list(chain.from_iterable(v for k, v in extras.items()
                                             if k not in {'ci', 'test'}))
    return extras

if __name__ == '__main__':
    setup(name='blaze',
          version=versioneer.get_version(),
          cmdclass=versioneer.get_cmdclass(),
          author='Continuum Analytics',
          author_email='blaze-dev@continuum.io',
          description='Blaze',
          long_description=read('README.rst'),
          install_requires=install_requires(),
          extras_require=extras_require(),
          license='BSD',
          classifiers=['Development Status :: 2 - Pre-Alpha',
                       'Environment :: Console',
                       'Intended Audience :: Developers',
                       'Intended Audience :: Science/Research',
                       'Intended Audience :: Education',
                       'License :: OSI Approved :: BSD License',
                       'Operating System :: OS Independent',
                       'Programming Language :: Python',
                       'Topic :: Scientific/Engineering',
                       'Topic :: Utilities'],
          entry_points={'console_scripts': ['blaze-server = blaze.server.spider:_main']},
          package_data={'blaze': package_data},
          packages=packages)


text:
from __future__ import absolute_import, print_function, unicode_literals

import copy
import json
import tempfile

from ..hooks import WebpackBundleHook

TEST_STATS_FILE_DATA = {
    "status": "done",
    "chunks": {
        "untitled": [
            {
                "name": "non_default_frontend-2c4fb3d6a29238b06f84.js",
                "publicPath": "non_default_frontend/non_default_frontend-2c4fb3d6a29238b06f84.js",
                "path": "kolibri/core/static/non_default_frontend/non_default_frontend-2c4fb3d6a29238b06f84.js"
            }
        ]
    },
    "publicPath": "default_frontend/",
    "messages": "true",
}

class TestHookMixin(object):
    """
    This hook will automatically create a stats file (normally created by npm)
    and populate it with test data according to the uniqe_slug of the hook
    that it's mixed into.
    """
    src_file = "assets/src/kolibri_core_app.js"

    @property
    def _stats_file(self):
        self.TEST_STATS_FILE = tempfile.NamedTemporaryFile(mode='w+', delete=False)
        self.TEST_STATS_FILE_DATA = copy.deepcopy(TEST_STATS_FILE_DATA)
        self.TEST_STATS_FILE_DATA['chunks'][self.unique_slug] = self.TEST_STATS_FILE_DATA['chunks'].pop('untitled')
        json.dump(
            self.TEST_STATS_FILE_DATA,
            self.TEST_STATS_FILE,
        )
        self.TEST_STATS_FILE.close()
        print(self.unique_slug)
        return self.TEST_STATS_FILE.name

class TestHook(TestHookMixin, WebpackBundleHook):
    unique_slug = 'non_default_frontend'


text:
module Azure::NetApp::Mgmt::V2020_07_01
  module Models
    #
    # exportPolicy

    # Set of export policy rules
    #
    class VolumePropertiesExportPolicy

      include MsRestAzure

      # @return [Array<ExportPolicyRule>] Export policy rule. Export policy
      # rule
      attr_accessor :rules

      #
      # Mapper for VolumePropertiesExportPolicy class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'volumeProperties_exportPolicy',
          type: {
            name: 'Composite',
            class_name: 'VolumePropertiesExportPolicy',
            model_properties: {
              rules: {
                client_side_validation: true,
                required: false,
                serialized_name: 'rules',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ExportPolicyRuleElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ExportPolicyRule'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package host

import (
	"bytes"
	"encoding/binary"
	"io/ioutil"
	"os"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
	"syscall"
	"unsafe"

	common "github.com/shirou/gopsutil/common"
)

type LSB struct {
	ID          string
	Release     string
	Codename    string
	Description string
}

func HostInfo() (*HostInfoStat, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return nil, err
	}

	ret := &HostInfoStat{
		Hostname: hostname,
		OS:       runtime.GOOS,
	}

	platform, family, version, err := GetPlatformInformation()
	if err == nil {
		ret.Platform = platform
		ret.PlatformFamily = family
		ret.PlatformVersion = version
	}
	system, role, err := GetVirtualization()
	if err == nil {
		ret.VirtualizationSystem = system
		ret.VirtualizationRole = role
	}
	uptime, err := BootTime()
	if err == nil {
		ret.Uptime = uptime
	}

	return ret, nil
}

func BootTime() (uint64, error) {
	sysinfo := &syscall.Sysinfo_t{}
	if err := syscall.Sysinfo(sysinfo); err != nil {
		return 0, err
	}
	return uint64(sysinfo.Uptime), nil
}

func Users() ([]UserStat, error) {
	utmpfile := "/var/run/utmp"

	file, err := os.Open(utmpfile)
	if err != nil {
		return nil, err
	}

	buf, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	u := utmp{}
	entrySize := int(unsafe.Sizeof(u))
	count := len(buf) / entrySize

	ret := make([]UserStat, 0, count)

	for i := 0; i < count; i++ {
		b := buf[i*entrySize : i*entrySize+entrySize]

		var u utmp
		br := bytes.NewReader(b)
		err := binary.Read(br, binary.LittleEndian, &u)
		if err != nil {
			continue
		}
		user := UserStat{
			User:     common.IntToString(u.User[:]),
			Terminal: common.IntToString(u.Line[:]),
			Host:     common.IntToString(u.Host[:]),
			Started:  int(u.Tv.TvSec),
		}
		ret = append(ret, user)
	}

	return ret, nil

}

func getLSB() (*LSB, error) {
	ret := &LSB{}
	if common.PathExists("/etc/lsb-release") {
		contents, err := common.ReadLines("/etc/lsb-release")
		if err != nil {
			return ret, err // return empty
		}
		for _, line := range contents {
			field := strings.Split(line, "=")
			if len(field) < 2 {
				continue
			}
			switch field[0] {
			case "DISTRIB_ID":
				ret.ID = field[1]
			case "DISTRIB_RELEASE":
				ret.Release = field[1]
			case "DISTRIB_CODENAME":
				ret.Codename = field[1]
			case "DISTRIB_DESCRIPTION":
				ret.Description = field[1]
			}
		}
	} else if common.PathExists("/usr/bin/lsb_release") {
		out, err := exec.Command("/usr/bin/lsb_release").Output()
		if err != nil {
			return ret, err
		}
		for _, line := range strings.Split(string(out), "\n") {
			field := strings.Split(line, ":")
			if len(field) < 2 {
				continue
			}
			switch field[0] {
			case "Distributor ID":
				ret.ID = field[1]
			case "Release":
				ret.Release = field[1]
			case "Codename":
				ret.Codename = field[1]
			case "Description":
				ret.Description = field[1]
			}
		}

	}

	return ret, nil
}

func GetPlatformInformation() (platform string, family string, version string, err error) {

	lsb, err := getLSB()
	if err != nil {
		lsb = &LSB{}
	}

	if common.PathExists("/etc/oracle-release") {
		platform = "oracle"
		contents, err := common.ReadLines("/etc/oracle-release")
		if err == nil {
			version = getRedhatishVersion(contents)
		}
	} else if common.PathExists("/etc/enterprise-release") {
		platform = "oracle"
		contents, err := common.ReadLines("/etc/enterprise-release")
		if err == nil {
			version = getRedhatishVersion(contents)
		}
	} else if common.PathExists("/etc/debian_version") {
		if lsb.ID == "Ubuntu" {
			platform = "ubuntu"
			version = lsb.Release
		} else if lsb.ID == "LinuxMint" {
			platform = "linuxmint"
			version = lsb.Release
		} else {
			if common.PathExists("/usr/bin/raspi-config") {
				platform = "raspbian"
			} else {
				platform = "debian"
			}
			contents, err := common.ReadLines("/etc/debian_version")
			if err == nil {
				version = contents[0]
			}
		}
	} else if common.PathExists("/etc/redhat-release") {
		contents, err := common.ReadLines("/etc/redhat-release")
		if err == nil {
			version = getRedhatishVersion(contents)
			platform = getRedhatishPlatform(contents)
		}
	} else if common.PathExists("/etc/system-release") {
		contents, err := common.ReadLines("/etc/system-release")
		if err == nil {
			version = getRedhatishVersion(contents)
			platform = getRedhatishPlatform(contents)
		}
	} else if common.PathExists("/etc/gentoo-release") {
		platform = "gentoo"
		contents, err := common.ReadLines("/etc/gentoo-release")
		if err == nil {
			version = getRedhatishVersion(contents)
		}
		// TODO: suse detection
		// TODO: slackware detecion
	} else if common.PathExists("/etc/arch-release") {
		platform = "arch"
		// TODO: exherbo detection
	} else if lsb.ID == "RedHat" {
		platform = "redhat"
		version = lsb.Release
	} else if lsb.ID == "Amazon" {
		platform = "amazon"
		version = lsb.Release
	} else if lsb.ID == "ScientificSL" {
		platform = "scientific"
		version = lsb.Release
	} else if lsb.ID == "XenServer" {
		platform = "xenserver"
		version = lsb.Release
	} else if lsb.ID != "" {
		platform = strings.ToLower(lsb.ID)
		version = lsb.Release
	}

	switch platform {
	case "debian", "ubuntu", "linuxmint", "raspbian":
		family = "debian"
	case "fedora":
		family = "fedora"
	case "oracle", "centos", "redhat", "scientific", "enterpriseenterprise", "amazon", "xenserver", "cloudlinux", "ibm_powerkvm":
		family = "rhel"
	case "suse":
		family = "suse"
	case "gentoo":
		family = "gentoo"
	case "slackware":
		family = "slackware"
	case "arch":
		family = "arch"
	case "exherbo":
		family = "exherbo"
	}

	return platform, family, version, nil

}

func getRedhatishVersion(contents []string) string {
	c := strings.ToLower(strings.Join(contents, ""))

	if strings.Contains(c, "rawhide") {
		return "rawhide"
	}
	if matches := regexp.MustCompile(`release (\d[\d.]*)`).FindStringSubmatch(c); matches != nil {
		return matches[1]
	}
	return ""
}

func getRedhatishPlatform(contents []string) string {
	c := strings.ToLower(strings.Join(contents, ""))

	if strings.Contains(c, "red hat") {
		return "redhat"
	}
	f := strings.Split(c, " ")

	return f[0]
}

func GetVirtualization() (string, string, error) {
	var system string
	var role string

	if common.PathExists("/proc/xen") {
		system = "xen"
		role = "guest" // assume guest

		if common.PathExists("/proc/xen/capabilities") {
			contents, err := common.ReadLines("/proc/xen/capabilities")
			if err == nil {
				if common.StringContains(contents, "control_d") {
					role = "host"
				}
			}
		}
	}
	if common.PathExists("/proc/modules") {
		contents, err := common.ReadLines("/proc/modules")
		if err == nil {
			if common.StringContains(contents, "kvm") {
				system = "kvm"
				role = "host"
			} else if common.StringContains(contents, "vboxdrv") {
				system = "vbox"
				role = "host"
			} else if common.StringContains(contents, "vboxguest") {
				system = "vbox"
				role = "guest"
			}
		}
	}

	if common.PathExists("/proc/cpuinfo") {
		contents, err := common.ReadLines("/proc/cpuinfo")
		if err == nil {
			if common.StringContains(contents, "QEMU Virtual CPU") ||
				common.StringContains(contents, "Common KVM processor") ||
				common.StringContains(contents, "Common 32-bit KVM processor") {
				system = "kvm"
				role = "guest"
			}
		}
	}

	if common.PathExists("/proc/bc/0") {
		system = "openvz"
		role = "host"
	} else if common.PathExists("/proc/vz") {
		system = "openvz"
		role = "guest"
	}

	// not use dmidecode because it requires root

	if common.PathExists("/proc/self/status") {
		contents, err := common.ReadLines("/proc/self/status")
		if err == nil {

			if common.StringContains(contents, "s_context:") ||
				common.StringContains(contents, "VxID:") {
				system = "linux-vserver"
			}
			// TODO: guest or host
		}
	}

	if common.PathExists("/proc/self/cgroup") {
		contents, err := common.ReadLines("/proc/self/cgroup")
		if err == nil {

			if common.StringContains(contents, "lxc") ||
				common.StringContains(contents, "docker") {
				system = "lxc"
				role = "guest"
			} else if common.PathExists("/usr/bin/lxc-version") { // TODO: which
				system = "lxc"
				role = "host"
			}
		}
	}

	return system, role, nil
}


text:
/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2-vsdoc.js" />
/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.19/jquery-ui.js" />

//*************************************************************************************************************
// AppCommon.js
// Description - Code for common object used on this site.
//                 contains useful and re-usable behaviors.
//                  TODO:  Document this....
//*************************************************************************************************************

var AppCommon = function () {          //constructor for Common library
    this.BaseUrl = "~/";

    //Properties in support of ForcePageRefresh() //////////////
    this.ReloadTimer = null;
    this.URL = unescape(window.location.pathname);
    ///////////////////////////////////////////////////////////
}

AppCommon.prototype = {
    CloseFormOK: function (strReturn) {
        if (!strReturn) strReturn = true;

        window.returnValue = strReturn;
        self.close();
    },

    CloseFormCancel: function () {
        window.returnValue = "0";
        self.close();
    },

    FormatJSONDateTime: function (jsonDate) {
        var date = eval(jsonDate.replace(/\/Date\((.*?)\)\//gi, "new Date($1)"));
        var month = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");

        return date.getDate() + " " +
                month[date.getMonth()] + " " +
                date.getFullYear() + " " +
                date.getHours() + ":" +
                this.FormatMinutes(date.getMinutes());
    },

    FormatJSONDate: function (jsonDate) {
        var date = null;

        try {
            date = eval(jsonDate.replace(/\/Date\((.*?)\)\//gi, "new Date($1)"));
        } catch (err) {  //try using sugar.js here (note: make sure it's referenced!
            date = Date.create(jsonDate);
        }

        var month = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");

        return date.getDate() + " " +
                month[date.getMonth()] + " " +
                date.getFullYear();
    },

    TickerSlider: function (container, delay) {
        if ($(container).length) {
            container = $(container);

            var slides = container.length, slide = 0;
            setInterval(function () {
                if (slide == slides) {
                    container.slideDown();
                    slide = 0;
                } else {
                    container.eq(slide).slideUp();
                    slide++;
                }
            }, delay)
        } else return false;
    },

    ForcePageRefresh: function (seconds) {
        if (arguments.length == 1) {
            if (this.ReloadTimer) clearTimeout(this.ReloadTimer);

            var self = this;
            this.ReloadTimer = setTimeout(function () { self.ForcePageRefresh(); }, Math.ceil(parseFloat(seconds) * 1000));
        } else {
            this.ReloadTimer = null;
            location.reload(true);
            window.location.replace(this.URL);
        }
    },

    ParseUrl: function (url) {
        var expr = /((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/;

        if (url.match(expr))
            return { url: RegExp["$&"], protocol: RegExp.$2, host: RegExp.$3, path: RegExp.$4, file: RegExp.$6, hash: RegExp.$7 };
        else
            return { url: "No match", protocol: "", host: "", path: "", file: "", hash: "" };
    },

    StringEscape: function (str) {
        var specials = ['#', '&', '~', '=', '>', "'", ':', '"', '!', ';', ','];
        var regexSpecials = ['.', '*', '+', '|', '[', ']', '(', ')', '/', '^', '$'];
        var regex = new RegExp('(' + specials.join('|') + '|\\' + regexSpecials.join('|\\') + ')', 'g');

        return str.replace(regex, '\\$1');
    },

    GetCharCount: function (str, c) {
        return (str.length - str.replace(new RegExp(c, "g"), '').length) / c.length;
    },

    // Define Modal windows
    ModalFadeOut: function (hash) {
        hash.o.remove(); hash.w.fadeOut(100);
    },

    ModalFadeIn: function (hash) {
        hash.w.fadeIn(100);
    },

    IsSameElement: function (elm1, elm2) {
        return elm1.get(0) == elm2.get(0);
    },

    ResolveUrl: function (url) {
        if (url.indexOf("~/") == 0)
            url = this.BaseUrl + url.substring(2);

        return url;
    },

    //why not a generic message box, eh?
    MessageBox: function (boxId, title, actionFunc, html, dialogWidth) {
        if (actionFunc == null) actionFunc = function () { return; };

        if ((dialogWidth == null) || (dialogWidth == "")) dialogWidth = 300;

        if (html.length > 50) {
            dialogWidth = dialogWidth + ((html.length - 50) * 10);

            if (dialogWidth > 860) dialogWidth = 860;
        }

        $("
" + html + "
").dialog(
            {
                modal: true,
                title: title,
                show: 'slide', hide: 'slide',
                width: dialogWidth,
                buttons: {
                    "OK": function () {
                        $(this).dialog("close");
                        actionFunc();
                    }
                }
            });
    },

    JqGridLoadError: function (grid, jqXHR, textStatus, errorThrown) {
        // remove error div if exist
        $('#' + grid.id + '_err').remove();
        // insert div with the error description before the grid
        $('#' + grid.id).closest('div.ui-jqgrid').before(
                        '

' +
		                AppCommon.prototype.DecodeErrorMessage(jqXHR, textStatus, errorThrown) + '

');
    },

    DecodeErrorMessage: function (jqXHR, errorThrown, errorMsg) {
        var err = null;
        var html = '';

        try {
            err = eval('(' + jqXHR.responseText + ')');
            html = errorThrown + '
' +
                    '' + errorMsg + '

' +
                    'Exception Type:  ' + err.ExceptionType + '
' +
                    'Message:  ' + err.Message + '
' +
                    'Stack Trace:  ' + err.StackTrace;
        } catch (ex) {
            html = jqXHR.status + " - " + jqXHR.statusText
        }

        this.MessageBox('divErrorMessage', errorThrown, null, html, null);
    }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/rl_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/pink"
        android:padding="10dip" >

        <LinearLayout
            android:id="@+id/ll_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="10dip"
            android:paddingRight="10dip" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/back_arrowhead" />
        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/lost_password_lost"
            android:textColor="@color/text_login"
            android:textSize="20dip" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/ll_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rl_title"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="15dip"
        android:layout_marginRight="15dip"
        android:layout_marginTop="20dip"
        android:background="@drawable/login_box"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
			<TextView
			    android:layout_marginLeft="10dp"
			    android:id="@+id/tv_country"
			    android:layout_width="wrap_content"
			    android:layout_height="wrap_content"
			    android:textSize="18sp"
			    android:layout_centerVertical="true"
			    android:text="@string/register_country"
			    />
            <EditText
                android:layout_toRightOf="@+id/tv_country"
                android:id="@+id/et_register_mobile_number"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@null"
                android:hint="@string/register_input_mobile_number"
                android:imeOptions="actionNext"
                android:inputType="number"
                android:maxLength="11"
                android:nextFocusDown="@+id/et_input_captcha"
                android:paddingBottom="15dip"
                android:paddingLeft="20dip"
                android:paddingTop="15dip"
                android:singleLine="true"
                android:textColorHint="@color/text_hint"
                android:textSize="18sp" />
        </RelativeLayout>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/login_line_gray" />

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:id="@+id/et_input_captcha"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@null"
                android:hint="@string/register_input_captcha"
                android:imeOptions="actionNext"
                android:inputType="number"
                android:maxLength="6"
                android:nextFocusDown="@+id/et_input_login_password"
                android:paddingBottom="15dip"
                android:paddingLeft="20dip"
                android:paddingTop="15dip"
                android:singleLine="true"
                android:textColorHint="@color/text_hint"
                android:textSize="18sp" />

            <Button
                android:id="@+id/btn_request_captcha"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:background="@drawable/button_blue"
                android:paddingBottom="10dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:textSize="18sp"
                android:paddingTop="10dp"
                android:text="@string/get_register"
                android:textColor="@color/white" />
        </RelativeLayout>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/login_line_gray" />

        <EditText
            android:id="@+id/et_input_login_password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:hint="@string/lost_password_resetting_password"
            android:inputType="text"
            android:nextFocusDown="@+id/btn_register"
            android:paddingBottom="15dip"
            android:paddingLeft="20dip"
            android:paddingTop="15dip"
            android:password="true"
            android:singleLine="true"
            android:textColorHint="@color/text_hint"
            android:textSize="18sp" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ll_input"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dip"
        android:background="@drawable/btn_login_selector"
        android:paddingBottom="10dp"
        android:paddingLeft="80dp"
        android:paddingRight="80dp"
        android:paddingTop="10dp"
        android:text="@string/lost_password_btn_submit"
        android:textColor="@color/text_login"
        android:textSize="20sp" />
</RelativeLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<form	xmlns="http://www.todoyu.com/schema/form"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.todoyu.com/schema/form ../../../../../core/config/form.xsd">
	<attributes>
		<attribute name="name">config</attribute>
	</attributes>
	<hiddenFields>
		<field name="dummy" noStorage="true" />
	</hiddenFields>

	<fieldsets>
		<fieldset name="config">
			<legend>timetracking.form.legend.admin.basics</legend>
			<elements>
				<field type="checkbox" name="stopOnLogout">
					timetracking.ext.extconf.stopOnLogout
				</field>

				<field type="text" name="tolerance">
					timetracking.ext.extconf.tolerance
					<validate>
						<isDecimal />
						<min>0</min>
					</validate>
				</field>
			</elements>

		</fieldset>
	</fieldsets>
</form>


text:
export TMPDIR=$(pwd)/tmp
mkdir -p $TMPDIR

# ruby-hiera is specified as a makedepend for ruby-hiera-json. But packer tries
# to install ruby-hiera-json first and fails. Install ruby-hiera first so
# puppet installs cleanly first time.
packer -S --noconfirm --noedit ruby-hiera
# Mark ruby-hiera as a dependency package manually since packer does not pass
# the --asdeps flag https://github.com/keenerd/packer/pull/100
pacman -D --asdeps ruby-hiera

# Install puppet
packer -S --noconfirm --noedit puppet

rm -rf $TMPDIR


text:
<?xml version="1.0" encoding="UTF-8"?>

<salesforce-mapping xmlns="https://github.com/swisscat/SalesforceBundle"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="https://github.com/swisscat/SalesforceBundle
                                        https://raw.githubusercontent.com/swisscat/SalesforceBundle/master/src/Resources/config/salesforce/schema/mapping-1.0.xsd">
    <entity class="Swisscat\SalesforceBundle\Test\TestData\Customer" object="Contact">
        <id name="id" externalId="None" />
        <salesforce-id type="mappingTable" />
        <property name="firstName" field="FirstName" />
        <property name="lastName" field="LastName" />
        <property name="email" field="Email" />
    </entity>
</salesforce-mapping


text:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jquery抽奖插件</title>


text:
<?php
/**
 * Sage includes
 *
 * The $sage_includes array determines the code library included in your theme.
 * Add or remove files to the array as needed. Supports child theme overrides.
 *
 * Please note that missing files will produce a fatal error.
 *
 * @link https://github.com/roots/sage/pull/1042
 */

remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
define('ICL_DONT_LOAD_NAVIGATION_CSS', true);
define('ICL_DONT_LOAD_LANGUAGE_SELECTOR_CSS', true);
define('ICL_DONT_LOAD_LANGUAGES_JS', true);

$sage_includes = [
  'lib/soil/soil.php',             // Soil functions
  'lib/utils.php',                 // Utility functions
  'lib/init.php',                  // Initial theme setup and constants
  'lib/wrapper.php',               // Theme wrapper class
  'lib/config.php',                // Configuration
  'lib/assets.php',                // Scripts and stylesheets
  'lib/titles.php',                // Page titles
  'lib/extras.php',                // Custom functions
  'lib/custom.php',                // Custom functions

];

foreach ($sage_includes as $file) {
  if (!$filepath = locate_template($file)) {
    trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR);
  }

  require_once $filepath;
}
unset($file, $filepath);