text:
from sqlalchemy import create_engine
from sqlalchemy.schema import MetaData, Table, Column
from sqlalchemy.types import String, Integer
from sqlalchemy.orm import scoped_session, sessionmaker

from unittest import TestCase

from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from wtforms.form import Form

class LazySelect(object):
    def __call__(self, field, **kwargs):
        return list((val, unicode(label), selected) for val, label, selected in field.iter_choices())

class DummyPostData(dict):
    def getlist(self, key):
        return self[key]

class Base(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
            setattr(self, k, v)

class TestBase(TestCase):
    def _do_tables(self, mapper, engine):
        metadata = MetaData()

        test_table = Table('test', metadata,
            Column('id', Integer, primary_key=True, nullable=False),
            Column('name', String, nullable=False),
        )

        pk_test_table = Table('pk_test', metadata,
            Column('foobar', String, primary_key=True, nullable=False),
            Column('baz', String, nullable=False),
        )

        Test = type('Test', (Base, ), {})
        PKTest = type('PKTest', (Base, ), {
            '__unicode__': lambda x: x.baz,
            '__str__': lambda x: x.baz,
        })

        mapper(Test, test_table, order_by=[test_table.c.name])
        mapper(PKTest, pk_test_table, order_by=[pk_test_table.c.baz])
        self.Test = Test
        self.PKTest = PKTest

        metadata.create_all(bind=engine)

    def _fill(self, sess):
        for i, n in [(1, 'apple'),(2, 'banana')]:
            s = self.Test(id=i, name=n)
            p = self.PKTest(foobar='hello%s' % (i, ), baz=n)
            sess.add(s)
            sess.add(p)
        sess.flush()
        sess.commit()

class QuerySelectFieldTest(TestBase):
    def setUp(self):
        engine = create_engine('sqlite:///:memory:', echo=False)
        self.Session = sessionmaker(bind=engine)
        from sqlalchemy.orm import mapper
        self._do_tables(mapper, engine)

    def test_without_factory(self):
        sess = self.Session()
        self._fill(sess)
        class F(Form):
            a = QuerySelectField(get_label='name', widget=LazySelect(), get_pk=lambda x: x.id)
        form = F(DummyPostData(a=['1']))
        form.a.query = sess.query(self.Test)
        self.assert_(form.a.data is not None)
        self.assertEqual(form.a.data.id, 1)
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', False)])
        self.assert_(form.validate())

    def test_with_query_factory(self):
        sess = self.Session()
        self._fill(sess)

        class F(Form):
            a = QuerySelectField(get_label=(lambda model: model.name), query_factory=lambda:sess.query(self.Test), widget=LazySelect())
            b = QuerySelectField(allow_blank=True, query_factory=lambda:sess.query(self.PKTest), widget=LazySelect())

        form = F()
        self.assertEqual(form.a.data, None)
        self.assertEqual(form.a(), [(u'1', 'apple', False), (u'2', 'banana', False)])
        self.assertEqual(form.b.data, None)
        self.assertEqual(form.b(), [(u'__None', '', True), (u'hello1', 'apple', False), (u'hello2', 'banana', False)])
        self.assert_(not form.validate())

        form = F(DummyPostData(a=[u'1'], b=[u'hello2']))
        self.assertEqual(form.a.data.id, 1)
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', False)])
        self.assertEqual(form.b.data.baz, 'banana')
        self.assertEqual(form.b(), [(u'__None', '', False), (u'hello1', 'apple', False), (u'hello2', 'banana', True)])
        self.assert_(form.validate())

        # Make sure the query iQuerySelectMultipleFields cached
        sess.add(self.Test(id=3, name='meh'))
        sess.flush()
        sess.commit()
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', False)])
        form.a._object_list = None
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', False), (u'3', 'meh', False)])

class QuerySelectMultipleFieldTest(TestBase):
    def setUp(self):
        from sqlalchemy.orm import mapper
        engine = create_engine('sqlite:///:memory:', echo=False)
        Session = sessionmaker(bind=engine)
        self._do_tables(mapper, engine)
        self.sess = Session()
        self._fill(self.sess)

    class F(Form):
        a = QuerySelectMultipleField(get_label='name', widget=LazySelect())

    def test_unpopulated_default(self):
        form = self.F()
        self.assertEqual([], form.a.data)

    def test_single_value_without_factory(self):
        form = self.F(DummyPostData(a=['1']))
        form.a.query = self.sess.query(self.Test)
        self.assertEqual([1], [v.id for v in form.a.data])
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', False)])
        self.assert_(form.validate())

    def test_multiple_values_without_query_factory(self):
        form = self.F(DummyPostData(a=['1', '2']))
        form.a.query = self.sess.query(self.Test)
        self.assertEqual([1, 2], [v.id for v in form.a.data])
        self.assertEqual(form.a(), [(u'1', 'apple', True), (u'2', 'banana', True)])
        self.assert_(form.validate())

        form = self.F(DummyPostData(a=['1', '3']))
        form.a.query = self.sess.query(self.Test)
        self.assertEqual([x.id for x in form.a.data], [1])
        self.assert_(not form.validate())

    def test_single_default_value(self):
        first_test = self.sess.query(self.Test).get(2)
        class F(Form):
            a = QuerySelectMultipleField(get_label='name', default=[first_test],
                widget=LazySelect(), query_factory=lambda: self.sess.query(self.Test))
        form = F()
        self.assertEqual([v.id for v in form.a.data], [2])
        self.assertEqual(form.a(), [(u'1', 'apple', False), (u'2', 'banana', True)])
        self.assert_(form.validate())

if __name__ == '__main__':
    from unittest import main
    main()


text:
require "io/console"
require_relative "../config/environment"
require_relative "models/singer"
require_relative "models/album"

class Application
  def self.run
    puts ""
    puts "Listing all singers using additional parallelism:"
    # A statement hint must be prefixed with 'statement_hint:'
    Singer.optimizer_hints("statement_hint: @{USE_ADDITIONAL_PARALLELISM=TRUE}")
          .order("last_name, first_name").each do |singer|
      puts singer.full_name
    end

    puts ""
    puts "Listing all singers using the index on full_name:"
    # All table hints must be prefixed with 'table_hint:'.
    # Queries may contain multiple table hints.
    Singer.optimizer_hints("table_hint: singers@{FORCE_INDEX=index_singers_on_full_name}")
          .order("full_name").each do |singer|
      puts singer.full_name
    end

    puts ""
    puts "Listing all singers with at least one album that starts with 'blue':"
    # Join hints cannot be specified using an optimizer_hint. Instead, the join can
    # be specified using a string that includes the join hint.
    Singer.joins("INNER JOIN @{JOIN_METHOD=HASH_JOIN} albums " \
                 "on singers.id=albums.singer_id AND albums.title LIKE 'blue%'")
          .distinct.order("last_name, first_name").each do |singer|
      puts singer.full_name
    end

    puts ""
    puts "Press any key to end the application"
    STDIN.getch
  end
end

Application.run

redpajama_set_name: RedPajamaGithub


text:
package ru.atom.lecture10.synchronizedexample;

/**
 * @author Alpi
 * @since 22.11.16
 */
public class SynchronizedExample {
    private final Object lock = new Object();//Any object here

    public synchronized void criticalMethod() {
        System.out.println("This method is protected by internal monitor of 'this'" +
                "and will be executed only one at a time on 'this'");
    }

    public void criticalBlockInside() {
        System.out.println("Some work here");
        synchronized (lock) {
            System.out.println("This block will by Object lock and executed only one at a time on given lock object");
        }
        System.out.println("Some work here too");
    }
}


text:
<!DOCTYPE html>

    <title>Day Mapper</title>

    <link href="gdaymapper.css" type="text/css" rel="stylesheet"/>

Day2 Mapper

    <button id="authorize-button">Authorize</button>

	Select your calendar: <select class="calendarList"><option value="blank"></option></select>
	Day: <input class="day"></input> Month: <input class="month"></input>
	Year: <input class="year"></input>

Events list


text: @import url( 'http://myurl.de');


text:
from django.template.response import TemplateResponse
from django.test import TestCase
from django.views.generic import TemplateView
from mock import Mock
import json

from django_backend.backend.ajax import DialogResponseMixin

class SimpleTemplateView(DialogResponseMixin, TemplateView):
    template_name = 'static_content.html'

class DialogResponseMixinTest(TestCase):
    def setUp(self):
        self.request = Mock()
        self.request.is_ajax.return_value = False
        self.ajax_request = Mock()
        self.ajax_request.is_ajax.return_value = True

    def test_normal_request(self):
        view = SimpleTemplateView(request=self.request)

        response = view.render_to_response({})
        self.assertTrue(isinstance(response, TemplateResponse))
        self.assertEqual(response.template_name,
                         ['django_backend/page_wrapper.html'])
        self.assertEqual(response.context_data['template_name'],
                         'static_content.html')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')

    def test_ajax_request(self):
        view = SimpleTemplateView(request=self.ajax_request)

        response = view.render_to_response({})
        self.assertTrue(not isinstance(response, TemplateResponse))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json; charset=utf-8')
        data = json.loads(response.content)
        # We strip to remove trailing newline.
        self.assertEqual(data['html'].strip(), 'static content')
        self.assertEqual(data['status'], 'ok')


text:
package org.lilyproject.indexer.engine.test;

import org.lilyproject.indexer.model.indexerconf.Formatter;
import org.lilyproject.repository.api.HierarchyPath;
import org.lilyproject.repository.api.ValueType;

import java.util.Collections;
import java.util.List;
import java.util.Set;

public class IntegerHierarchyUnderscoreFormatter implements Formatter {
    private static final Set<String> types = Collections.singleton("INTEGER");

    public List<String> format(Object value, ValueType valueType) {
        HierarchyPath path = (HierarchyPath)value;

        StringBuilder builder = new StringBuilder();
        for (Object item : path.getElements()) {
            if (builder.length() > 0)
                builder.append("_");
            builder.append(item);
        }

        return Collections.singletonList(builder.toString());
    }

    public Set<String> getSupportedPrimitiveValueTypes() {
        return types;
    }

    public boolean supportsSingleValue() {
        return true;
    }

    public boolean supportsMultiValue() {
        return false;
    }

    public boolean supportsNonHierarchicalValue() {
        return false;
    }

    public boolean supportsHierarchicalValue() {
        return true;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Surefire Strategy"</title>
		<link>http://bvs.wikidot.com/forum/t-1120015/surefire-strategy</link>
		<description>Posts in the discussion thread "Surefire Strategy"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:58:44 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-1120015#post-2237259</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-1120015/surefire-strategy#post-2237259</link>
				<description></description>
				<pubDate>Sat, 21 Feb 2015 20:05:53 +0000</pubDate>
				<wikidot:authorName>Thyme</wikidot:authorName>								<content:encoded>
					<![CDATA[

I just got this with my only bet being 11.

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
(function($, Vis) {

Vis.blocks['b-render-overlay'] = {
    init: function(params) {
        var _this = this;

        _this.params = params;

        _this.render = Vis.create(
            _this.params,
            _this.params.renderName || 'b-line-render'
        );
    },

    layersRequest: function() {
        var content = this.params.content,
            items = content.items,
            request = [];

        for (var i = 0, l = items.length; i < l; ++i) {
            request.push({
                xAxisNo: items[i].xAxisNo,
                yAxisNo: items[i].yAxisNo,
                item: i
            });
        }

        return request;
    },

   _run: function(sched, layers, itemNo) {
        var _this = this,
            content = this.params.content,
            items = content.items;

        if (itemNo >= items.length) {
            return sched.next();
        } else if (items[itemNo]._rendered) {
            _this._run(sched, layers, itemNo + 1);
        } else {
            sched.next(function(sched) {
                _this.drawItem(sched, layers, itemNo);
            });
        }
    },

    draw: function(sched, layers) {
        this._run(sched, layers, 0);
    },

    drawItem: function(sched, layers, itemNo) {
        var dim = this.params.dimensions,
            content = this.params.content,
            layer = layers[itemNo],
            xAxis = content.xAxes[layer.xAxisNo] || Vis.error("No x-axis for layer #" + itemNo),
            yAxis = content.yAxes[layer.yAxisNo] || Vis.error("No y-axis for layer #" + itemNo),
            canvas = layers[itemNo].canvas,
            ctx = layers[itemNo].ctx;
        if (canvas) {
            ctx.clearRect(0, 0, dim.width, dim.height);
            canvas.css('left', '0');
            canvas.css('top', '0');
            canvas.css('width', '100%');
            canvas.css('height', dim.height + 'px');
        }
        layer.xAxisRange = {
            min: xAxis.scale.inputMin,
            max: xAxis.scale.inputMax
        };
        layer.yAxisRange = {
            min: yAxis.scale.inputMin,
            max: yAxis.scale.inputMax
        };
        this.render.drawItem(sched, layers, itemNo);

        this._run(sched, layers, itemNo + 1);
    }
};

})(jQuery, Vis);


text:
if [ $# -lt 1 ];
then
  echo "USAGE: $0 [-daemon] [-name servicename] [-loggc] classname [opts]"
  exit 1
fi

base_dir=$(dirname $0)/..

# create logs directory
if [ "x$LOG_DIR" = "x" ]; then
    LOG_DIR="$base_dir/logs"
fi

if [ ! -d "$LOG_DIR" ]; then
    mkdir -p "$LOG_DIR"
fi

if [ -z "$SCALA_VERSION" ]; then
	SCALA_VERSION=2.8.0
fi

# run ./gradlew copyDependantLibs to get all dependant jars in a local dir
for file in $base_dir/core/build/dependant-libs-${SCALA_VERSION}/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

for file in $base_dir/examples/build/libs//kafka-examples*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

for file in $base_dir/contrib/hadoop-consumer/build/libs//kafka-hadoop-consumer*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

for file in $base_dir/contrib/hadoop-producer/build/libs//kafka-hadoop-producer*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

for file in $base_dir/clients/build/libs/kafka-clients*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

# classpath addition for release
for file in $base_dir/libs/*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

for file in $base_dir/core/build/libs/kafka_${SCALA_VERSION}*.jar;
do
  CLASSPATH=$CLASSPATH:$file
done

# JMX settings
if [ -z "$KAFKA_JMX_OPTS" ]; then
  KAFKA_JMX_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false  -Dcom.sun.management.jmxremote.ssl=false "
fi

# JMX port to use
if [  $JMX_PORT ]; then
  KAFKA_JMX_OPTS="$KAFKA_JMX_OPTS -Dcom.sun.management.jmxremote.port=$JMX_PORT "
fi

# Log4j settings
if [ -z "$KAFKA_LOG4J_OPTS" ]; then
  KAFKA_LOG4J_OPTS="-Dlog4j.configuration=file:$base_dir/config/tools-log4j.properties"
fi

KAFKA_LOG4J_OPTS="-Dkafka.logs.dir=$LOG_DIR $KAFKA_LOG4J_OPTS"

# Generic jvm settings you want to add
if [ -z "$KAFKA_OPTS" ]; then
  KAFKA_OPTS=""
fi

# Which java to use
if [ -z "$JAVA_HOME" ]; then
  JAVA="java"
else
  JAVA="$JAVA_HOME/bin/java"
fi

# Memory options
if [ -z "$KAFKA_HEAP_OPTS" ]; then
  KAFKA_HEAP_OPTS="-Xmx256M"
fi

# JVM performance options
if [ -z "$KAFKA_JVM_PERFORMANCE_OPTS" ]; then
  KAFKA_JVM_PERFORMANCE_OPTS="-server -XX:+UseCompressedOops -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSScavengeBeforeRemark -XX:+DisableExplicitGC -Djava.awt.headless=true"
fi

while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in
    -name)
      DAEMON_NAME=$2
      CONSOLE_OUTPUT_FILE=$LOG_DIR/$DAEMON_NAME.out
      shift 2
      ;;
    -loggc)
      if [ -z "$KAFKA_GC_LOG_OPTS"] ; then
        GC_LOG_ENABLED="true"
      fi
      shift
      ;;
    -daemon)
      DAEMON_MODE="true"
      shift
      ;;
    *)
      break
      ;;
  esac
done

# GC options
GC_FILE_SUFFIX='-gc.log'
GC_LOG_FILE_NAME=''
if [ "x$GC_LOG_ENABLED" = "xtrue" ]; then
  GC_LOG_FILE_NAME=$DAEMON_NAME$GC_FILE_SUFFIX
  KAFKA_GC_LOG_OPTS="-Xloggc:$LOG_DIR/$GC_LOG_FILE_NAME -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps "
fi

# Launch mode
if [ "x$DAEMON_MODE" = "xtrue" ]; then
  nohup $JAVA $KAFKA_HEAP_OPTS $KAFKA_JVM_PERFORMANCE_OPTS $KAFKA_GC_LOG_OPTS $KAFKA_JMX_OPTS $KAFKA_LOG4J_OPTS -cp $CLASSPATH $KAFKA_OPTS "$@" > "$CONSOLE_OUTPUT_FILE" 2>&1 < /dev/null &
else
  exec $JAVA $KAFKA_HEAP_OPTS $KAFKA_JVM_PERFORMANCE_OPTS $KAFKA_GC_LOG_OPTS $KAFKA_JMX_OPTS $KAFKA_LOG4J_OPTS -cp $CLASSPATH $KAFKA_OPTS "$@"
fi


text:
set -euo pipefail

# This script installs and starts a KDC with the default EXAMPLE.COM realm.
# !!!! The kadmin principal password is highly insecure !!!!

# Install packages and create the database.
#
yum install -y krb5-server krb5-libs rng-tools krb5-workstation
rngd -r /dev/urandom -o /dev/random
/usr/sbin/kdb5_util create -s -r EXAMPLE.COM -P admin
kadmin.local add_principal -pw admin admin/admin@EXAMPLE.COM

# Update /etc/krb5.conf
#
/vagrant/provisioning/copy-krb5-conf.sh

# Restart services.
#
systemctl restart krb5kdc
systemctl restart kadmin


text:
'use strict';

var mongoose = require('mongoose');
var restifier = require('restifier');

module.exports = ModelFactory;

function ModelFactory(app) {
  this.app = app;
  this.restifier = restifier.api();
}

ModelFactory.prototype.createFactoryFunction = function() {
  var factory = this;
  return function() {
    if (arguments.length === 0) {
      throw new Error('You must specify arguments for the model factory function.');
    }

    var arg = arguments[0];
    if (arg.modelName) {
      return factory.modelFromMongoose(arg);
    }

    if (arguments.length === 1) {
      throw new Error('You must specify both a name and schema.');
    }

    if (typeof arg !== 'string') {
      throw new Error('First argument in model factory function must be a string.');
    }

    var schema = arguments[1];
    if (schema.paths) {
      return factory.modelFromSchema(arg, schema);
    } else if (typeof schema === 'object') {
      return factory.modelFromObject(arg, schema);
    }

    throw new Error('Unknown schema "' + schema + '" for factory function.');
  };
};

ModelFactory.prototype.modelFromMongoose = function(model) {
  return this.restifier.model(model);
};

ModelFactory.prototype.modelFromSchema = function(name, schema) {
  return this.modelFromMongoose(this.app.mongoose.model(name, schema));
};

ModelFactory.prototype.modelFromObject = function(name, object) {
  return this.modelFromObject(name, new mongoose.Schema(object));
};


text:
require "test_helper"

=begin

  What's being tested here?

    - Invoice belongs_to Order

=end

class Admin::InvoicesControllerTest < ActionController::TestCase

  setup do
    @typus_user = Factory(:typus_user)
    @request.session[:typus_user_id] = @typus_user.id
  end

  ##
  # Here we are using the create_with_back_to method.
  #
  #   /admin/invoices/new?back_to=&order_id=4&resource=Order&resource_id=4
  #
  context "Create an invoice from an Order" do

    setup do
      @order = Factory(:order)
      @invoice = { :number => "Invoice#0000001" }
    end

    should "initialize the object with the params passed on the url" do
      get :new, { :resource => "Order", :resource => "Order", :order_id => @order.id }
      assert assigns(:item)
      assert_equal @order.id, assigns(:item).order_id
    end

    # TODO: Take a look at this to refactor the create method.
    should "create new invoice assign it to order and redirect to order" do
      @invoice = { :number => "Invoice#0000001", :order_id => @order.id }

      assert_difference('Invoice.count') do
        post :create, { :invoice => @invoice, :resource => "Order", :order_id => @order.id }
      end
      assert_response :redirect
      assert_redirected_to "/admin/orders/edit/#{@order.id}"
    end

    should_eventually "raise an error if we try to add an invoice to an order which already has an invoice" do
      @invoice = Factory(:invoice)
      get :new, { :resource => "Order", :resource_id => @invoice.order.id, :order_id => @invoice.order.id }
      assert_response :unprocessable_entity
    end

    should_eventually "raise an error if we try to create an invoice to an order which already has an invoice" do
      @invoice = Factory(:invoice)
      post :create, { :invoice => { :number => "Invoice#0000001" },
                      :resource => "Order", :resource_id => @invoice.order.id, :order_id => @invoice.order.id }
      assert_response :unprocessable_entity
    end

  end

  context "Unrelate" do

    setup do
      @invoice = Factory(:invoice)
      @order = @invoice.order
      @request.env['HTTP_REFERER'] = "/admin/orders/edit/#{@order.id}"
    end

    should "work for unrelate Invoice from Order" do
      post :unrelate, :id => @invoice.id, :resource => 'Order', :resource_id => @order.id
      assert @order.reload.invoice.nil?
      assert_equal "Order successfully updated.", flash[:notice]
    end

  end

end


text:
package phases

import (
	"github.com/pkg/errors"
	"k8s.io/klog"
	"k8s.io/kubernetes/cmd/kubeadm/app/cmd/options"
	"k8s.io/kubernetes/cmd/kubeadm/app/cmd/phases/workflow"
	cmdutil "k8s.io/kubernetes/cmd/kubeadm/app/cmd/util"
	kubeletphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/kubelet"
)

var (
	kubeletStartPhaseExample = cmdutil.Examples(`
		# Writes a dynamic environment file with kubelet flags from a InitConfiguration file.
		kubeadm init phase kubelet-start --config config.yaml
		`)
)

// NewKubeletStartPhase creates a kubeadm workflow phase that start kubelet on a node.
func NewKubeletStartPhase() workflow.Phase {
	return workflow.Phase{
		Name:    "kubelet-start",
		Short:   "Write kubelet settings and (re)start the kubelet",
		Long:    "Write a file with KubeletConfiguration and an environment file with node specific kubelet settings, and then (re)start kubelet.",
		Example: kubeletStartPhaseExample,
		Run:     runKubeletStart,
		InheritFlags: []string{
			options.CfgPath,
			options.NodeCRISocket,
			options.NodeName,
		},
	}
}

// runKubeletStart executes kubelet start logic.
func runKubeletStart(c workflow.RunData) error {
	data, ok := c.(InitData)
	if !ok {
		return errors.New("kubelet-start phase invoked with an invalid data struct")
	}

	// First off, configure the kubelet. In this short timeframe, kubeadm is trying to stop/restart the kubelet
	// Try to stop the kubelet service so no race conditions occur when configuring it
	if !data.DryRun() {
		klog.V(1).Infoln("Stopping the kubelet")
		kubeletphase.TryStopKubelet()
	}

	// Write env file with flags for the kubelet to use. We do not need to write the --register-with-taints for the control-plane,
	// as we handle that ourselves in the mark-control-plane phase
	// TODO: Maybe we want to do that some time in the future, in order to remove some logic from the mark-control-plane phase?
	if err := kubeletphase.WriteKubeletDynamicEnvFile(&data.Cfg().ClusterConfiguration, &data.Cfg().NodeRegistration, false, data.KubeletDir()); err != nil {
		return errors.Wrap(err, "error writing a dynamic environment file for the kubelet")
	}

	// Write the kubelet configuration file to disk.
	if err := kubeletphase.WriteConfigToDisk(data.Cfg().ComponentConfigs.Kubelet, data.KubeletDir()); err != nil {
		return errors.Wrap(err, "error writing kubelet configuration to disk")
	}

	// Try to start the kubelet service in case it's inactive
	if !data.DryRun() {
		klog.V(1).Infoln("Starting the kubelet")
		kubeletphase.TryStartKubelet()
	}

	return nil
}


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

<TITLE>
Overview (Javadocs: oscP5)
</TITLE>

<META NAME="date" CONTENT="2011-12-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

    Overview
      Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Javadocs: oscP5

Packages

netP5

oscP5

    Overview
      Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

processing library oscP5 by Andreas Schlegel. (c) 2004-2011


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.apisupport.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
            <code-name-base>mars.libs.jME3utilities</code-name-base>
            <suite-component/>
            <module-dependencies>
                <dependency>
                    <code-name-base>mars.libs.jMonkeyEngineCore</code-name-base>
                    <build-prerequisite/>
                    <compile-dependency/>
                    <run-dependency>
                        <specification-version>1.2</specification-version>
                    </run-dependency>
                </dependency>
            </module-dependencies>
            <public-packages>
                <package>jme3utilities</package>
                <package>jme3utilities.controls</package>
                <package>jme3utilities.debug</package>
                <package>jme3utilities.debug.test</package>
                <package>jme3utilities.math</package>
                <package>jme3utilities.navigation</package>
                <package>jme3utilities.nifty</package>
                <package>jme3utilities.nifty.test</package>
                <package>jme3utilities.physics</package>
                <package>jme3utilities.sky</package>
                <package>jme3utilities.sky.test</package>
                <package>jme3utilities.sky.textures</package>
                <package>jme3utilities.ui</package>
                <package>jme3utilities.xml</package>
            </public-packages>
            <class-path-extension>
                <runtime-relative-path>ext/jME3-utilities.jar</runtime-relative-path>
                <binary-origin>release/modules/ext/jME3-utilities.jar</binary-origin>
            </class-path-extension>
        </data>
    </configuration>
</project>


text:
  Les Essards est
       un village
       géographiquement positionné dans le département de Charente-Maritime en Poitou-Charentes. On dénombrait 555 habitants en 2008.

À Les Essards, le prix moyen à l'achat d'un appartement s'évalue à 1 491 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 298 € du m². À la location le prix moyen se situe à 8,38 € du m² mensuel.

À proximité de Les Essards sont localisées les communes de
Corme-Royal localisée à 6 km, 1 507 habitants,
Nieul-lès-Saintes située à 4 km, 979 habitants,
Crazannes située à 7 km, 432 habitants,
Saint-Sulpice-d'Arnoult localisée à 7 km, 595 habitants,
Port-d'Envaux située à 7 km, 961 habitants,
Saint-Georges-des-Coteaux à 4 km, 2 430 habitants,
 entre autres. De plus, Les Essards est située à seulement dix km de Saintes.

La commune propose quelques  équipements sportifs, elle propose entre autres un terrain de sport et une boucle de randonnée.

Le parc de logements, à Les Essards, était réparti en 2011 en quatre appartements et 298 maisons soit
 un marché relativement équilibré.

Si vous envisagez de venir habiter à Les Essards, vous pourrez facilement trouver une maison à vendre.


text:
  margin: 15px;
  background-color: #D1CFC5;
  border-bottom: 2px solid #C0BEB4;
  border-radius: 2px;

  padding: 20px;
  display: flex;
  flex-direction: row;

  font-size: 30px;
}

#tasks ul li.new-task input {
  background-color: inherit;
  border: none;
}

#tasks ul li.new-task input:focus {
  outline: none;
  border-bottom: 2px solid #30353A;
  padding-bottom: 5px;
  transition: 0.3s all ease-in-out;
}


text:
package org.txazo.weixin.resource;

/**
 * ResourceLoader
 *
 * @author txazo
 * @email txazo1218@163.com
 * @since 05.06.2015
 */
public interface ResourceLoader {

    String CLASSPATH_URL_PREFIX = "classpath:";

    Resource getResource(String path);

}


text:
FROM dmce/php-base:latest
MAINTAINER Stephen Melrose <me@stephenmelrose.co.uk>

# Install packages
RUN apt-get install -y \
    php5-xdebug

# Add config files
ADD images/php-dev/env.ini /etc/php5/mods-available/env.ini
RUN php5enmod env


text:
'use strict';

var cloneDeep = require('lodash.clonedeep');
var SchemaOrgValidator = require('schema.org-validator');
var ValidationError = require('../../../../../../../model.js').ValidationError;

var sov = new SchemaOrgValidator({schemas: ['Organization']});

module.exports = {
    additionalValidators: [
        function(d) {
            var obj = cloneDeep(d);
            delete obj.bookmarks;
            delete obj.contactPerson;
            delete obj._id;
            delete obj._meta;
            delete obj._type;
            delete obj._rev;

            var result = sov.validate(obj, 'Organization');
            if (result.length) {
                throw ValidationError.fromErrors({
                    keyword: 'require',
                    dataPath: '.',
                    message: 'Must be a valid Schema.org Organization. Result = ' + JSON.stringify(result, false, '  '),
                });
            } else {
                return true;
            }
        }
    ]
};


text:
require 'spec_helper'

describe Mongo::Error::NoServerAvailable do
  describe 'message' do
    let(:selector) do
      Mongo::ServerSelector::Primary.new
    end

    let(:cluster) do
      Mongo::Cluster.new(['127.0.0.1:27017'],
        Mongo::Monitoring.new, monitoring_io: false)
    end

    let(:error) do
      Mongo::Error::NoServerAvailable.new(selector, cluster)
    end

    it 'is correct' do
      expect(error.message).to eq('No primary server is available in cluster: #<Cluster topology=Unknown[127.0.0.1:27017] servers=[#<Server address=127.0.0.1:27017 UNKNOWN>]> with timeout=30, LT=0.015')
    end
  end
end


text:
import logging
import logging.config
import logging.handlers
import os
import warnings
from pprint import pformat

import yaml
from flask import has_request_context, request, session

from indico.core.config import config
from indico.web.util import get_request_info, get_request_user

class AddRequestIDFilter:
    def filter(self, record):
        # Add our request ID if available
        record.request_id = request.id if has_request_context() else '0' * 16
        return True

class AddUserIDFilter:
    def filter(self, record):
        user = get_request_user()[0] if has_request_context() else None
        record.user_id = str(session.user.id) if user else '-'
        return True

class RequestInfoFormatter(logging.Formatter):
    def format(self, record):
        rv = super().format(record)
        info = get_request_info()
        if info:
            rv += '\n\n' + pformat(info)
        return rv

class FormattedSubjectSMTPHandler(logging.handlers.SMTPHandler):
    def getSubject(self, record):
        return self.subject % record.__dict__

class BlacklistFilter(logging.Filter):
    def __init__(self, names):
        self.filters = [logging.Filter(name) for name in names]

    def filter(self, record):
        return not any(x.filter(record) for x in self.filters)

class Logger:
    @classmethod
    def init(cls, app):
        path = config.LOGGING_CONFIG_PATH
        if not path:
            return
        if not os.path.exists(path):
            default_path = os.path.join(app.root_path, 'logging.yaml.sample')
            warnings.warn('Logging config file not found; using defaults. '
                          'Copy {default_path} to {path} to get rid of this warning.'
                          .format(path=path, default_path=default_path))
            path = default_path
        with open(path) as f:
            data = yaml.safe_load(f)
        data['disable_existing_loggers'] = False
        data['incremental'] = False
        # Make the request ID available in all loggers
        data.setdefault('filters', {})
        data['filters']['_add_request_id'] = {'()': AddRequestIDFilter}
        data['filters']['_add_user_id'] = {'()': AddUserIDFilter}
        for handler in data['handlers'].values():
            handler.setdefault('filters', [])
            handler['filters'].insert(0, '_add_request_id')
            handler['filters'].insert(1, '_add_user_id')
            if handler['class'] == 'logging.FileHandler' and handler['filename'][0] != '/':
                # Make relative paths relative to the log dir
                handler['filename'] = os.path.join(config.LOG_DIR, handler['filename'])
            elif handler['class'] in ('logging.handlers.SMTPHandler', 'indico.core.logger.FormattedSubjectSMTPHandler'):
                # Configure email handlers with the data from the config
                if not handler.get('mailhost'):
                    handler['mailhost'] = config.SMTP_SERVER
                    handler['secure'] = () if config.SMTP_USE_TLS else None  # yuck, empty tuple == STARTTLS
                    if config.SMTP_LOGIN and config.SMTP_PASSWORD:
                        handler['credentials'] = (config.SMTP_LOGIN, config.SMTP_PASSWORD)
                handler.setdefault('fromaddr', f'logger@{config.WORKER_NAME}')
                handler.setdefault('toaddrs', [config.SUPPORT_EMAIL])
                subject = ('Unexpected Exception occurred at {}: %(message)s'
                           if handler['class'] == 'indico.core.logger.FormattedSubjectSMTPHandler' else
                           'Unexpected Exception occurred at {}')
                handler.setdefault('subject', subject.format(config.WORKER_NAME))
        for formatter in data['formatters'].values():
            # Make adding request info to log entries less ugly
            if formatter.pop('append_request_info', False):
                assert '()' not in formatter
                formatter['()'] = RequestInfoFormatter
        # Enable the database logger for our db_log util
        if config.DB_LOG:
            data['loggers']['indico._db'] = {'level': 'DEBUG', 'propagate': False, 'handlers': ['_db']}
            data['handlers']['_db'] = {'class': 'logging.handlers.SocketHandler', 'host': '127.0.0.1', 'port': 9020}
        # If customization debugging is enabled, ensure we get the debug log messages from it
        if config.CUSTOMIZATION_DEBUG and config.CUSTOMIZATION_DIR:
            data['loggers'].setdefault('indico.customization', {})['level'] = 'DEBUG'
        logging.config.dictConfig(data)

    @classmethod
    def get(cls, name=None):
        """Get a logger with the given name.

        This behaves pretty much like `logging.getLogger`, except for
        prefixing any logger name with ``indico.`` (if not already
        present).
        """
        if name is None:
            name = 'indico'
        elif name != 'indico' and not name.startswith('indico.'):
            name = 'indico.' + name
        return logging.getLogger(name)


text:
/* CSS Reset */{}
.charsheet .sheet-wrapper div, .charsheet .sheet-wrapper span, .charsheet .sheet-wrapper label,
.charsheet .sheet-wrapper h1, .charsheet .sheet-wrapper h2, .charsheet .sheet-wrapper h3, .charsheet .sheet-wrapper h4, .charsheet .sheet-wrapper h5, .charsheet .sheet-wrapper h6, .charsheet .sheet-wrapper p,
.charsheet .sheet-wrapper table, .charsheet .sheet-wrapper caption, .charsheet .sheet-wrapper tbody, .charsheet .sheet-wrapper tfoot, .charsheet .sheet-wrapper thead, .charsheet .sheet-wrapper tr, .charsheet .sheet-wrapper th, .charsheet .sheet-wrapper td {
    margin: 0;
    padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	color: #404040;
	vertical-align: baseline;
	box-sizing: border-box;
	-moz-box-sizing: border-box;
	-webkit-box-sizing: border-box;
}

.charsheet .sheet-wrapper table {
	border-collapse: collapse;
	border-spacing: 0;
}

.charsheet .sheet-wrapper input::-webkit-outer-spin-button,
.charsheet .sheet-wrapper input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.charsheet .sheet-wrapper textarea {
  resize: none;
}

/* Main Styles */{}

.charsheet {
	background-color: white;
}

.charsheet .sheet-wrapper h2 {
	margin: 1px 0;
	font-weight:bold;
	font-size: 15px;
}

.charsheet .sheet-wrapper input, .charsheet .sheet-wrapper textarea, .charsheet .sheet-wrapper select, .charsheet .sheet-wrapper input[type="number"] {
	display: inline-block;
	border: 1px solid #ccc;
	padding: 2px;
	height: 28px;
	width: 100%;
	font-size: 12px;
	line-height: 16px;
	font-weight: normal;
	margin: 0;
	color: #555;
	background-color: white;
	vertical-align: middle;
	cursor: auto;
	letter-spacing: normal;
	word-spacing: normal;
	text-transform: none;
	text-indent: 0px;
	text-shadow: none;
	text-align: start;

	-webkit-rtl-ordering: logical;
	-webkit-user-select: text;

	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-webkit-transition: border linear .2s,box-shadow linear .2s;
	-moz-transition: border linear .2s,box-shadow linear .2s;
	-ms-transition: border linear .2s,box-shadow linear .2s;
	-o-transition: border linear .2s,box-shadow linear .2s;
	transition: border linear .2s,box-shadow linear .2s;

	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;

	-webkit-writing-mode: horizontal-tb;
}

.charsheet .sheet-wrapper input:not([type='checkbox']) {
	-webkit-appearance: textfield;
}

.charsheet .sheet-wrapper input[type="checkbox"] {
	margin-top: 7px;
	height: 13px;
	width: 13px;
	color: #555;
	border: 1px solid #ccc;

	-webkit-border-radius: 0;
	-moz-border-radius: 0;
	border-radius: 0;

	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-webkit-transition: border linear .2s,box-shadow linear .2s;
	-moz-transition: border linear .2s,box-shadow linear .2s;
	-ms-transition: border linear .2s,box-shadow linear .2s;
	-o-transition: border linear .2s,box-shadow linear .2s;
	transition: border linear .2s,box-shadow linear .2s;
}

.charsheet .sheet-wrapper input[disabled], .charsheet .sheet-wrapper select[disabled], .charsheet .sheet-wrapper textarea[disabled], .charsheet .sheet-wrapper input[readonly], .charsheet .sheet-wrapper select[readonly], .charsheet .sheet-wrapper textarea[readonly] {
    background-color: #f5f5f5;
    border-color: #ddd;
    cursor: not-allowed;
}

.charsheet .sheet-wrapper textarea {
    width: 98%;
    height: 50px;
    font-size: 13px;
    line-height: 18px;
}

.charsheet .sheet-wrapper label {
	display: inline-block;
	width: 100%;
	font-size: 12px;
	text-align: left;
	height: 28px;
	line-height: 28px;
	vertical-align: middle;
}

.charsheet .sheet-wrapper .sheet-3colrow .sheet-col {
	width: calc(33% - 3px) !important;
	margin-right: 2px !important;
}

.charsheet .sheet-wrapper .sheet-3colrow .sheet-col:last-child {
	margin-right: 0 !important;
}

.charsheet .sheet-wrapper .sheet-2colrow .sheet-col {
	width: calc(50% - 3px) !important;
	margin-right: 2px !important;
}

.charsheet .sheet-wrapper .sheet-2colrow .sheet-col:last-child {
	margin-right: 0 !important;
}

/* Row And Items */{}

.charsheet .sheet-wrapper .sheet-row {
    height: 34px;
    margin: 0 0 2px;
}

.charsheet .sheet-wrapper .sheet-alternative:nth-child(2n) {
    background-color: #E3E3E3;
}

.charsheet .sheet-wrapper .sheet-header {
    height: 20px;
    margin: 0;
}

.charsheet .sheet-wrapper .sheet-header label {
    padding: 0;
    font-size: 9px;
    height: 20px;
    line-height: 20px;
    font-weight: normal;
    word-wrap:break-word;
}

.charsheet .sheet-wrapper .sheet-item {
	display: inline-block;
	width: 100%;
	height: 34px;
	vertical-align: middle;
	margin: 0 -2px;
	text-align: left;
	padding: 3px 2px;
}

.charsheet .sheet-wrapper .sheet-item.sheet-multiline label {
	line-height: 9px;
	padding-top: 1px;
}

.charsheet .sheet-wrapper .sheet-item.sheet-nano {
	width: calc(7.5% - 3%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-micro {
	width: calc(10% - 3%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-tiny {
	width: calc(15% - 3%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-smaller {
    width: calc(19% - 3%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-small {
	width: calc(20% - 0.5%);
}

.charsheet .sheet-wrapper textarea.sheet-small {
	height: 32px;
}

.charsheet .sheet-wrapper .sheet-item.sheet-med {
	width: calc(30% - 0.5%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-large {
	width: calc(40% - 5%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-hulking {
    width: calc(60% - 0.5%);
}

.charsheet .sheet-wrapper .sheet-item.sheet-huge {
	width: calc(80% - 3%);
}

/* Base Info */{}

.sheet-baseinfo {
	display: inline-block;
	width: 145px;
	margin-right: 3px;
}

.sheet-baseinfo.sheet-number {
    width: 39px;
    margin-right: 10px;
}

.sheet-baseinfo.sheet-short {
    width: 60px;
}

.sheet-baseinfo.sheet-medium {
    width: 100px;
}

/* Stat Blocks */{}

.charsheet .sheet-wrapper .sheet-statblock {
    margin-bottom: 5px;
	display: block;
    visibility: visible;

	-webkit-transition: .125s linear;
    -moz-transition: .125s linear;
    -ms-transition: .125s linear;
    -o-transition: .125s linear;
    transition: .125s linear;
}

.charsheet .sheet-wrapper .sheet-statblock:last-child {
    margin-bottom: 0!important;
}

.charsheet .sheet-wrapper .sheet-statblock .sheet-black label {
    color: white;
}

.charsheet .sheet-wrapper .sheet-statblock h2, .charsheet .sheet-wrapper .sheet-headtwo {
    width: 100%;
    background-color: black;
    color: white;
    text-align: center;
	margin: 1px 0;
	font-weight:bold;
	font-size: 15px;
}

.charsheet .sheet-wrapper input[type=checkbox]:checked ~ label.sheet-headtwo {
    background-color: #333;
}

.charsheet .sheet-wrapper input[type=checkbox]:checked ~ .sheet-statblock {
	display: none;
    visibility: hidden;
}

.charsheet .sheet-wrapper .sheet-hidden {
	display: none;
    visibility: hidden;
}

.charsheet .sheet-wrapper .sheet-statblock .sheet-halfblack {
    background: linear-gradient(to right, white 50%, black 50%);
}
.charsheet .sheet-wrapper .sheet-statblock .sheet-black {
    background: black;
    color: white;
}

/* Pure CSS Hide/Show - For settings */{}

.charsheet .sheet-wrapper .sheet-hider .sheet-article input[type=checkbox] ~ label {
    display: inline-block;
	font-size: 16px;
	line-height: 16px;
	font-weight: bold;
	color: #555;
    width: 100%;
    border: 1px solid #CCC;
    padding: 5px;
    text-align: center;

    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
	-webkit-transition: border linear .2s,box-shadow linear .2s;
	-moz-transition: border linear .2s,box-shadow linear .2s;
	-ms-transition: border linear .2s,box-shadow linear .2s;
	-o-transition: border linear .2s,box-shadow linear .2s;
	transition: border linear .2s,box-shadow linear .2s;

	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;
}

.charsheet .sheet-wrapper .sheet-hider input[type=checkbox]:checked ~ label {
    color: white;
    background-color: #555;
    border: 1px solid black;
}

.charsheet .sheet-wrapper .sheet-hider .sheet-article .sheet-section:last-of-type {
    display: none;
    visibility: hidden;
}

.charsheet .sheet-wrapper .sheet-hider .sheet-section {
    -webkit-transition: .125s linear;
    -moz-transition: .125s linear;
    -ms-transition: .125s linear;
    -o-transition: .125s linear;
    transition: .125s linear;
}

.charsheet .sheet-wrapper .sheet-hider input[type=checkbox] {
    display: none;
    visibility: hidden;
}

.charsheet .sheet-wrapper .sheet-hider input[type=checkbox]:checked ~ .sheet-section {
    display: block;
    visibility: visible;
    width: 100%;
}


text:
layout: splash
permalink: /
header:
  overlay_color: "#5e616c"
  overlay_image: /assets/images/mrobot.jpg
  caption:
excerpt: 'Witty caption'
---


text:
<!DOCTYPE html>

There should be one yellow box below, on a blue background. the "second column" part should be clipped out.

        first

        column

        second

        column

FAIL


text:
#ifndef OFFSETS_H
#define OFFSETS_H

#include "eiface.h"
#include "server_class.h"

extern IServerGameDLL *serverGameDLL;

//=================================================================================
// Container class for various NetVar offsets
// May expand to hold function offsets when moving to signature scanning (TODO)
//
// NetVars appended with 'p', functions with 'f' (TODO ^)
//
//
// MakePtr, CrawlForPropOffset and WS_FindOffset are based on code by various
// posters from AlliedMods and GameDeception.
// They have been modified to be able to find any property in the hierarchy of
// a class.
//   CTFPlayer example:
//       "m_iHealth" will find CTFPlayer->m_iHealth,
//    and "m_iClass" will find CTFPlayer->m_PlayerClass->m_iClass
//=================================================================================

class WSOffsets {
public:
	static int pCTFPlayer__m_iClass;
	static int pCWeaponMedigun__m_flChargeLevel;

	static void PrepareOffsets();
	static int FindOffsetOfClassProp(const char *className, const char *propName);

private:
	static bool CrawlForPropOffset(SendTable *sTable, const char *propName, int &offset);
};

#define MakePtr( cast, ptr, addValue ) (cast)( (unsigned long)(ptr) + (unsigned long)(addValue))

#endif


text:
#ifndef THRIFT_UTIL_SCOPEDSERVEREVENTBASETHREAD_H
#define THRIFT_UTIL_SCOPEDSERVEREVENTBASETHREAD_H

#include <thrift/lib/cpp/util/ScopedServerThread.h>
#include <thrift/lib/cpp/transport/TSocketAddress.h>

namespace apache { namespace thrift {

class ServerInterface;
class ThriftServer;

/**
 * ScopedServerInterfaceThread spawns a thrift cpp2 server in a new thread.
 *
 * The server is stopped automatically when the instance is destroyed.
 */
class ScopedServerInterfaceThread {

 public:

  explicit ScopedServerInterfaceThread(
      std::shared_ptr<ServerInterface> si,
      const std::string& host = "::1",
      uint16_t port = 0);

  explicit ScopedServerInterfaceThread(
      std::shared_ptr<ThriftServer> ts);

  ThriftServer& getThriftServer() const;
  const folly::SocketAddress& getAddress() const;
  uint16_t getPort() const;

 private:

  std::shared_ptr<ThriftServer> ts_;
  util::ScopedServerThread sst_;

};

}}

#endif


text:
require 'net/dns'
require 'net/dns/resolver'

class Gman < NaughtyOrNice
  class Parser

    COMMENT_REGEX = /\/\/[\/\s]*(.*)$/i

    class << self

      # Given a public-suffix list formatted file
      # Converts to a hash in the form of :group => [domain1, domain2...]
      def file_to_hash(file)
        array_to_hash(file_to_array(file))
      end

      # Given a public-suffix list formatted file
      # Convert it into an array of comments and domains representing each line
      def file_to_array(file)
        domains = File.open(file).read
        domains.gsub! /\r\n?/, "\n" # Normalize line endings
        domains = domains.split("\n")
      end

      # Given an array of comments/domains in public suffix format
      # Converts to a hash in the form of :group => [domain1, domain2...]
      def array_to_hash(domains)
        group = ""
        domain_hash = {}
        domains.each do |line|
          next if line.empty?
          if match = COMMENT_REGEX.match(line)
            group = match[1]
          else
            domain_hash[group] = [] if domain_hash[group].nil?
            domain_hash[group].push line.downcase
          end
        end
        domain_hash
      end

      def resolver
        @resolver ||= begin
          resolver = Net::DNS::Resolver.new
          resolver.nameservers = ["8.8.8.8","8.8.4.4", "208.67.222.222", "208.67.220.220"]
          resolver
        end
      end

      # Verifies that the given domain has an MX record, and thus is valid
      def domain_resolves?(domain)
        resolver.search(domain).header.anCount > 0 ||
        resolver.search(domain, Net::DNS::NS).header.anCount > 0 ||
        resolver.search(domain, Net::DNS::MX).header.anCount > 0
      end
    end
  end
end


text:
<?php
declare(strict_types=1);

use PeekAndPoke\Aviator\ServiceContainer\Environment;
use PeekAndPoke\AviatorDemo\App\Api\ApiApp;

error_reporting(E_ALL);

require __DIR__ . '/../vendor/autoload.php';

$app = new ApiApp(new Environment('dev', true));

$request  = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
$response = $app->handle($request);

http_response_code($response->getStatusCode());

foreach ($response->getHeaders() as $k => $v) {
    header($k . ': ' . (is_array($v) ? implode(',', $v) : $v));
}

echo $response->getBody();


text:
module Main where

import Control.Applicative
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.HUnit
import Test.Proctest
import Test.QuickCheck.Property (morallyDubiousIOProperty)

-- Example of communicating with `cat`.
--
-- See below for integration with hspec and hunit.
catTest :: IO ()
catTest = do
  (hIn, hOut, hErr, p) <- run "cat" []

  hPutStrLn hIn "test line 1"

  let catWait h = fmap asUtf8Str <$> waitOutputNoEx (seconds 0.01) 1000 h -- Wait max 10 ms, 1000 bytes

  sleep (seconds 0.00001) -- Give cat time to digest

  response <- catWait hOut

  putStrLn $ case response of
    Just x | x == "test line 1\n" -> "cat test successful"
    Just x                        -> "cat test failed. Output was: " ++ show x
    Nothing                       -> "cat timed out, producing no output"

  mExitCode <- getProcessExitCode p

  case mExitCode of
    Just ExitSuccess     -> putStrLn $ "process exited normally"
    Just (ExitFailure n) -> putStrLn $ "process quit with exit code " ++ show n
    Nothing              -> do putStrLn "process did not quit, killing it"
                               terminateProcess p

{-
Some convenience for declaring tests:

  - '?@' for giving the label first, then the monadic action.

  - Separating assertions from their labels:

    -- '?==' creates an assertion

    -- 'label' optionally labels it
-}

infix 1 ?@
(?@) :: (AssertionPredicable t) => String -> t -> Assertion
(?@) = flip (@?)

data EqualAssertion a = EqualAssertion a a

data LabeledAssertion a = LabeledAssertion String (EqualAssertion a)

(?==) :: (Eq a, Show a) => a -> a -> EqualAssertion a
actual ?== expected = EqualAssertion actual expected

label :: String -> EqualAssertion a -> LabeledAssertion a
label = LabeledAssertion

instance (Eq a, Show a) => Assertable (EqualAssertion a) where
  assert (EqualAssertion actual expected) = actual @?= expected

instance (Eq a, Show a) => Assertable (LabeledAssertion a) where
  assert (LabeledAssertion msg (EqualAssertion actual expected)) =
    assertEqual msg actual expected

assertLabel str equalsAssertion = assert (label str equalsAssertion)

ncTestHunit = it "does a simple server <-> client interaction (1)" $ do

  (serverIn, serverOut, serverErr, serverP) <- run "nc" ["-l", "1234"]
  (clientIn, clientOut, clientErr, clientP) <- run "nc" ["localhost", "1234"]

  -- Make sure processes are running
  serverExitCode <- getProcessExitCode serverP
  clientExitCode <- getProcessExitCode clientP

  assertLabel "server is running" $ serverExitCode ?== Nothing
  assertLabel "client is running" $ clientExitCode ?== Nothing

  let ncWait h = asUtf8Str <$> waitOutput (seconds 0.01) 100 h

  hPutStrLn clientIn "request 1"
  r <- ncWait serverOut
  assertLabel "server receives client request" $ r ?== "request 1\n"

  hPutStrLn serverIn "response 1"
  r <- ncWait clientOut
  assertLabel "client receives server response" $ r ?== "response 1\n"

  terminateProcesses [serverP, clientP]

ncTestHunitClean = it "does a simple server <-> client interaction (2)" $ do

  -- Spawn
  (serverIn, serverOut, serverErr, serverP) <- run "nc" ["-l", "1234"]
  (clientIn, clientOut, clientErr, clientP) <- run "nc" ["localhost", "1234"]

  -- Check
  assertProcessesRunning serverP clientP

  -- Buffering
  setBuffering NoBuffering [clientIn, clientOut, serverIn, serverOut]

  -- Send
  assertLabel "server receives client request"  =<< popsOut clientIn serverOut "request 1\n"
  assertLabel "client receives server response" =<< popsOut serverIn clientOut "response 1\n"

  -- Close
  closeHandles [serverIn, serverOut, clientIn, clientOut]
  sleep (seconds 0.001)

  assertLabel "server shut down" =<< assertionExitSuccess serverP

  where
    ncWait h = asUtf8Str <$> waitOutput (seconds 0.01) 100 h

    assertionRunning     proc = (?== Nothing)          <$> getProcessExitCode proc
    assertionExitSuccess proc = (?== Just ExitSuccess) <$> getProcessExitCode proc

    assertProcessesRunning serverP clientP = do
      assertLabel "server is running" =<< assertionRunning serverP
      assertLabel "client is running" =<< assertionRunning clientP

    popsOut hIn hOut content = do
      hPutStr hIn content
      r <- ncWait hOut
      return $ r ?== content

catSpec = describe "cat" $ do
  it "prints out what we put in" $ do

    -- Start up the program to test
    (hIn, hOut, hErr, p) <- run "cat" []

    -- Make sure buffering doesn't prevent us from reading what we expect
    setBuffering NoBuffering [hIn, hOut]

    -- Communicate with the program
    hPutStrLn hIn "hello world"

    -- Define a convenient wrapper around 'waitOutput'.
    --
    -- It specifies how long we have to wait
    -- (malfunctioning programs shall not block automated testing for too long)
    -- and how many bytes we are sure the expected response fits into
    -- (malfunctioning programs shall not flood us with garbage either).
    let catWait h = asUtf8Str <$> waitOutput (seconds 0.01) 1000 h -- Wait max 10 ms, 1000 bytes

    -- Wait a little to allow `cat` processing the input
    sleep (seconds 0.00001)

    -- Read the response
    response <- catWait hOut

    -- Test if it is what we want (here using HUnit's 'expectEqual')
    response @?= "hello world\n"

catCheck :: [String] -> IO Bool
catCheck lines = do

  (hIn, hOut, hErr, p) <- run "cat" []

  let catWait h = asUtf8Str <$> waitOutput (seconds 0.01) 1000 h

      checkLine l = do hPutStrLn hIn l
                       sleep (seconds 0.00001)
                       (== (l ++ "\n")) <$> catWait hOut

  and <$> (mapM checkLine lines)

catProp inputLines = morallyDubiousIOProperty $ catCheck inputLines

catPropSpec = describe "cat QuickCheck test" $ do
  prop "it gives back whatever we put in" catProp

main = do
  -- catTest -- This is not a hspec test.
  hspec $ do
    describe "cat" $ do
      catSpec
      catPropSpec
    describe "netcat" $ do
      ncTestHunit
      ncTestHunitClean


text:
package org.jfree.ui;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * A 'ready-made' panel that has one button on the left and another button on the right - a layout
 * manager takes care of resizing.
 *
 * @author David Gilbert
 */
public class L1R1ButtonPanel extends JPanel {

    /** The button on the left. */
    private JButton left;

    /** The button on the right. */
    private JButton right;

    /**
     * Standard constructor - creates a two-button panel with the specified labels.
     *
     * @param leftLabel  the label for the left button.
     * @param rightLabel  the label for the right button.
     */
    public L1R1ButtonPanel(final String leftLabel, final String rightLabel) {

        setLayout(new BorderLayout());
        this.left = new JButton(leftLabel);
        this.right = new JButton(rightLabel);
        add(this.left, BorderLayout.WEST);
        add(this.right, BorderLayout.EAST);

    }

    /**
     * Returns a reference to button 1, allowing the caller to set labels, action-listeners etc.
     *
     * @return the button.
     */
    public JButton getLeftButton() {
        return this.left;
    }

    /**
     * Returns a reference to button 2, allowing the caller to set labels, action-listeners etc.
     *
     * @return the button.
     */
    public JButton getRightButton() {
        return this.right;
    }

}


text:
namespace ICSharpCode.AvalonEdit.Edi.BlockSurround
{
  /// <summary>
  /// Class can be used to mark/unmark text in a block of code.
  ///
  /// Workflow:
  /// - The user selects a part of the text and hits CTRL+1
  /// - The editor marks the selected text as comment or
  ///   uncomments the selected section if the user selected
  ///   a comment.
  /// </summary>
  public class BlockDefinition
  {
    #region constructor
    /// <summary>
    /// Class constructor
    /// </summary>
    public BlockDefinition(string blockstart,
                         string blockend,
                         BlockAt typeOfBlock,
                         string fileextension,
                         System.Windows.Input.Key key,
                         System.Windows.Input.ModifierKeys modifier = 0)
      : this()
    {
      this.TypeOfBlock = typeOfBlock;
      this.StartBlock = blockstart;
      this.EndBlock = blockend;
      this.FileExtension = fileextension;

      this.Key = key;
      this.Modifier = modifier;
    }

    /// <summary>
    /// Hide standard constructor to ensur construction with minimal
    /// required data items.
    /// </summary>
    /// <returns></returns>
    protected BlockDefinition()
    {
      this.TypeOfBlock = BlockAt.StartAndEnd;
      this.StartBlock = this.EndBlock = this.FileExtension = string.Empty;

      this.Key = System.Windows.Input.Key.D1;
      this.Modifier = System.Windows.Input.ModifierKeys.Control;
    }
    #endregion constructor

    #region enum
    /// <summary>
    /// Define whether a selection is parsed/edit
    /// at both ends or only at one end.
    /// </summary>
    public enum BlockAt
    {
      /// <summary>
      /// Edit selected text at its start only
      /// </summary>
      Start,

      /// <summary>
      /// Edit selected text at its end only
      /// </summary>
      End,

      /// <summary>
      /// Edit selected text at start and end.
      /// </summary>
      StartAndEnd,
    }
    #endregion enum

    #region properties
    /// <summary>
    /// Get/set type of block selection/change
    /// </summary>
    public BlockAt TypeOfBlock { get; set; }

    /// <summary>
    /// String to remove/add at the begining of a selection.
    /// </summary>
    public string StartBlock { get; set; }

    /// <summary>
    /// String to remove/add at the end of a selection.
    /// </summary>
    public string EndBlock { get; set; }

    /// <summary>
    /// Configures the file extension for which this selection should be applied.
    /// </summary>
    public string FileExtension { get; set; }

    /// <summary>
    /// Configures the key that a user can use to apply the selection add/remove function.
    /// </summary>
    public System.Windows.Input.Key Key { get; set; }

    /// <summary>
    /// Configures the key modifier (if any) that a user can use to apply the selection add/remove function.
    /// </summary>
    public System.Windows.Input.ModifierKeys Modifier { get; set; }
    #endregion properties
  }
}


text:
package com.virtusa.isq.vtaf.report.reporter;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;

/**
 * The Class Reporter.
 */
public class Reporter {

    /** The builder. */
    private ReportBuilder builder;

    /**
     * Instantiates a new reporter.
     */
    public Reporter() {

        builder = new ReportBuilder(initReportDirectory());
    }

    /**
     * Inits the report directory.
     *
     * @return the string
     */
    private String initReportDirectory() {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ssa");
        String timestamp = sdf.format(date);

        File reportFolder =
                new File("target" + File.separator + "Reports" + File.separator
                        + "ExecutionReport" + timestamp);

        try {
            if (!reportFolder.exists() && !reportFolder.mkdirs()) {
                throw new RuntimeException(
                        "Cannot create new folder in location "
                                + reportFolder.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        copyReportHelperFiles(reportFolder.getAbsolutePath());

        System.out.println(reportFolder.getAbsolutePath());
        return reportFolder.getAbsolutePath();
    }

    /**
     * Copy report helper files.
     *
     * @param reportFolderStr
     *            the report folder str
     */
    private void copyReportHelperFiles(final String reportFolderStr) {
        File reportTemplateHtml =
                new File(new File("src" + File.separator + "main"
                        + File.separator + "resources" + File.separator
                        + "ReportTemplate").getAbsolutePath());
        /*File reportTemplateHtml =
                new File(new File("ReportTemplate").getAbsolutePath());*/
        File reportFolder = new File(reportFolderStr);
        try {
            FileUtils.copyDirectory(reportTemplateHtml, reportFolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Adds the new test execution.
     */
    public final void addNewTestExecution() {
        builder.addNewTestExecution();
    }

    /**
     * Adds the new test suite.
     *
     * @param testSuiteName
     *            the test suite name
     */
    public final void addNewTestSuite(final String testSuiteName) {
        builder.addNewTestSuite(testSuiteName, "0ms");
    }

    /**
     * Adds the new test case.
     *
     * @param testCaseName
     *            the test case name
     */
    public final void addNewTestCase(final String testCaseName) {
        builder.addNewTestCase(testCaseName, "0ms");
    }

    /**
     * Report step results.
     *
     * @param isPassed
     *            the is passed
     * @param category
     *            the category
     * @param message
     *            the message
     * @param loglvl
     *            the loglvl
     * @param stacktrace
     *            the stacktrace
     */
    public final void reportStepResults(final boolean isPassed,
            final String category, final String message, final String loglvl,
            final String stacktrace) {

        if (isPassed) {

            if ("SCREENSHOT ".equals(category)) {
                String screenShot =
                        saveScreenShot(builder.getReportFolderLocation());
                String thumbScreenShot = saveScreenshotThumb(screenShot);
                builder.addNewTestStep(isPassed, category, "images"
                        + File.separator + screenShot, thumbScreenShot, message,
                        stacktrace, "Success");
            } else {
                builder.addNewTestStep(isPassed, category, message, loglvl);
            }

        } else {

            String screenShot =
                    saveScreenShot(builder.getReportFolderLocation());
            String thumbScreenShot = saveScreenshotThumb(screenShot);
            builder.addNewTestStep(isPassed, category, "images"
                    + File.separator + screenShot, thumbScreenShot, message,
                    stacktrace, "Error");
        }

    }

    /**
     * Save screen shot.
     *
     * @param reportFolderLocation
     *            the report folder location
     * @return the string
     */
    private String saveScreenShot(final String reportFolderLocation) {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String timestamp = sdf.format(date);
        Rectangle screenRect =
                new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage capture;
        String screenShotFile = timestamp + ".png";
        String screenShotImgFolder =
                reportFolderLocation + File.separator + "images";
        try {
            capture = new Robot().createScreenCapture(screenRect);
            File screenShotImgFolderFile = new File(screenShotImgFolder);

            if (!screenShotImgFolderFile.exists()
                    && !screenShotImgFolderFile.mkdirs()) {

                throw new RuntimeException(
                        "Cannot create new folder in location "
                                + screenShotImgFolderFile.getAbsolutePath());
            }
            File screenShotImg =
                    new File(screenShotImgFolder + File.separator
                            + screenShotFile);
            ImageIO.write(capture, "png", screenShotImg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AWTException e1) {
            e1.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return screenShotFile;
    }

    /**
     * Save screenshot thumb.
     *
     * @param screenShotFile
     *            the screen shot file
     * @return the string
     */
    private String saveScreenshotThumb(final String screenShotFile) {
        final int thumbWidth = 150;
        final int thumbHeight = 100;
        String screenShotThumb =
                "images" + File.separator + screenShotFile + "_Thumb.png";
        try {
            String screenShotOriginalFile =
                    builder.getReportFolderLocation() + File.separator
                            + "images" + File.separator + screenShotFile;
            BufferedImage img = ImageIO.read(new File(screenShotOriginalFile));
            BufferedImage thumb =
                    Scalr.resize(img, Method.SPEED, thumbWidth, thumbHeight,
                            Scalr.OP_ANTIALIAS, Scalr.OP_BRIGHTER);

            ImageIO.write(thumb, "png", new File(screenShotOriginalFile
                    + "_Thumb.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return screenShotThumb;
    }

    /**
     * End test reporting.
     */
    public final void endTestReporting() {

        builder.setExecutionSummary();
        Generator generator = new Generator();
        generator.generateReport(builder);
    }

}