text:
using MatterHackers.Localizations;
using MatterHackers.Agg.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.MatterControl.CustomWidgets;

namespace MatterHackers.MatterControl.SetupWizard
{
	public class SyncingPrintersPage: WizardPage
	{
		TextWidget syncingDetails;
		public SyncingPrintersPage()
			: base("Close")
		{
			TextWidget syncingText = new TextWidget("Syncing Profiles...".Localize(),textColor: ActiveTheme.Instance.PrimaryTextColor);
			syncingDetails = new TextWidget("Retrieving sync information...".Localize(), textColor: ActiveTheme.Instance.PrimaryTextColor, pointSize:10);
			syncingDetails.AutoExpandBoundsToText = true;
			contentRow.AddChild(syncingText);
			contentRow.AddChild(syncingDetails);
			Progress<SyncReportType> progress = new Progress<SyncReportType>(ReportProgress);

			ApplicationController.SyncPrinterProfiles(progress).ContinueWith((task) =>
			{
				if (!ProfileManager.Instance.ActiveProfiles.Any())
				{
					// Switch to setup wizard if no profiles exist
					WizardWindow.ChangeToSetupPrinterForm();
				}
				else if (ProfileManager.Instance.ActiveProfiles.Count() == 1)
				{
					//Set as active printer
					ActiveSliceSettings.SwitchToProfile(ProfileManager.Instance.ActiveProfiles.First().ID);
				}
				UiThread.RunOnIdle(WizardWindow.Close);
			});
			footerRow.AddChild(new HorizontalSpacer());
			footerRow.AddChild(cancelButton);
		}

		private void ReportProgress(SyncReportType report)
		{
			syncingDetails.Text = report.actionLabel;
		}
	}
}


text:
'use strict';

require('mocha');
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const mdu = require('..');
const tests = path.join.bind(path, __dirname);

function requireFile(name, dir) {
  return require(tests((dir || 'fixtures'), `${name}.js`));
}

function readFile(name) {
  return fs.readFileSync(tests('expected', `${name}.md`), 'utf-8');
}

describe('markdown-utils', () => {
  for (const name of Object.keys(mdu)) {
    it(`.${name}`, () => {
      let fixture = requireFile(name);
      let expected;
      if (Array.isArray(fixture[0])) {
        expected = requireFile(name, 'expected');
        fixture.forEach((val, i) => {
          runTest(mdu[name], name, val, expected[i].trim());
        });
      } else {
        expected = readFile(name).trim();
        runTest(mdu[name], name, fixture, expected);
      }
    });
  }
});

function runTest(fn, name, fixture, expected) {
  let actual = fn.apply(fn, fixture).trim();
  assert.equal(actual, expected);
}

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "logging.h"

const unsigned short PORT = 8081;
const int BUFFER_SIZE = 40960;

int make_socket(unsigned short port)
{
    int sock;
    struct sockaddr_in name;

    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock < 0) {
        set_file();
        perror("failed to establish socket\n");
        log_error("failed to establish socket\n");
        close_file();
        exit(EXIT_FAILURE);
    }

    name.sin_family = AF_INET;
    name.sin_port = htons(port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(sock, (struct sockaddr *) &name, sizeof(name)) < 0) {
        set_file();
        perror("failed to bind a name to socket\n");
        log_error("failed to bind a name to socket\n");
        close_file();
        exit(EXIT_FAILURE);
    }

    return sock;
}

int read_from_client(int filedes, char *buffer) {
    int nbytes;

    nbytes = (int) read(filedes, buffer, BUFFER_SIZE);
    if(nbytes < 0) {
        set_file();
        perror("something went wrong when reading FD\n");
        log_error("something went wrong when reading FD\n");
        close_file();
        exit(EXIT_FAILURE);
    }
    else if(nbytes == 0) {
        /* End-of-file. */
        return -1;
    }
    else {
        return nbytes;
    }
}

int main() {
    int sock;
    fd_set active_fd_set, read_fd_set;
    sock = make_socket(PORT);
    if(listen(sock, SOMAXCONN) < 0) {
        set_file();
        perror("failed to listen on the socket\n");
        log_error("failed to listen on the socket\n");
        close_file();
        exit(EXIT_FAILURE);
    }
    FD_ZERO(&active_fd_set);
    FD_SET(sock, &active_fd_set);

    int size, new, nbytes;
    struct sockaddr_in clientname;
    while(1) {
        /* Block until input arrives on one or more active sockets. */
        read_fd_set = active_fd_set;
        if(select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) {
            set_file();
            perror("failed when processing \"select\"\n");
            log_error("failed when processing \"select\"\n");
            close_file();
            exit(EXIT_FAILURE);
        }

        for(int i = 0; i < FD_SETSIZE; ++i) {
            if(FD_ISSET(i, &read_fd_set)) {
                if(i == sock) {
                    size = sizeof(clientname);
                    new = accept(sock, (struct sockaddr *) &clientname, (socklen_t *) &size);
                    if(new < 0) {
                        set_file();
                        perror("failed to accept new connection\n");
                        log_error("failed to accept new connection\n");
                        close_file();
                        exit(EXIT_FAILURE);
                    }
                    char *ip = inet_ntoa((&clientname)->sin_addr);
                    set_file();
                    log_info("Server: new connection established from client, client ip is %s.\n", ip);
                    close_file();
                    FD_SET(new, &active_fd_set);
                } else {
                    /* Data arriving on an already-connected socket. */
                    char buffer[BUFFER_SIZE];
                    nbytes = read_from_client(i, buffer);
                    if(nbytes < 0) {
                        close(i);
                        FD_CLR(i, &active_fd_set);
                    } else {
                        if(send(i, buffer, (size_t) nbytes, 0) != nbytes) {
                            char *ip = inet_ntoa((&clientname)->sin_addr);
                            set_file();
                            perror("failed to send message back to client\n");
                            log_error("failed to send message back to client, client ip is %s\n", ip);
                            close_file();
                            exit(EXIT_FAILURE);
                        }
                        char *ip = inet_ntoa((&clientname)->sin_addr);
                        set_file();
                        log_info("New message from client ip: %s, message is: %s", ip, buffer);
                        close_file();
                    }
                }
            }
        }
    }
    return 0;
}


text:
package cn.org.bachelor.context.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

public abstract class PrjManagedAspect extends ManageAspect {

	@Around("!execution(public * cn.org.bachelor.**.**..**.*(..)) and execution(public * cn.org.bachelor.**.**.biz..*Biz*.*(..)) or !execution(public * cn.org.bachelor.**.**.**..**.*(..)) and execution(public * cn.org.bachelor.**.**.dao..*Dao*.*(..))")
	  public Object intercept(ProceedingJoinPoint pjp) throws Throwable{

		return doIntercept(pjp);
	}

}


text:
package com.mod_snmp.Snmp.Protocol;

import java.util.Vector;

/**
 * The SecurityVector class decodes and encodes a DatagramPacket
 * into an SnmpMessage.
 * It extends the BER class that contains all BER encoding
 * definitions. This class conatins the functions that process
 * the packages.
 */
public class SecurityVector extends Vector implements SecModelNumberInterface {
    /**
     * The Vector based Security System contstructor.
     */
    public SecurityVector() {
        /* In case we need some decoder initialization like a scratch pad. */
    }
    public void addSecModel(SecModelInterface sm) {
        addElement(sm);
    }

    public SecModelInterface getSecModel(int model) {
        for (int i = 0; i < size(); i++) {
            SecModelInterface secModel = (SecModelInterface)elementAt(i);
            if (secModel.isSecModel(model)) {
                return secModel;
            }
        }
        return null;
    }

    public static String toString(int secsys) {
        switch (secsys) {
        case SECMODEL_V1:
            return "Community Based (v1)";
        case SECMODEL_V2C:
            return "Community Based (v2c)";
        case SECMODEL_USM:
            return "USM";
        }
        return "ANY";
    }
}


text:
"""Provides scheduling routines for stackless tasklets.

The scheduler itself runs as a tasklet. It blocks waiting
for input on the channel passed in. When new data is sent
on this channel, the scheduler wakes and begins processing
of the data.

"""

import stackless  # pylint: disable=F0401
from pypes.pype import Pype
from pypes.graph import get_pairlist, topsort
import traceback

class ComponentPortError(Exception):
    """Exception raised if input or output port for the
    pypes.component.Component is not found.

    """
    pass

def connect_graph_components(graph):
    """Sort the components and connect the output of a component to the
    input of the next.

    @param graph: The graph representing the work flow
    @type graph: Python dict organized as a graph struct
    @return nodes: The sorted nodes in the graph

    """
    edgeList = get_pairlist(graph)
    nodes = topsort(edgeList)
    pipes = []

    for n in nodes:
        try:
            # get this nodes outputs
            edges = graph[n]
        except:
            pass
        else:
            # for each output
            for e in edges:
                pipe = Pype()
                pipes.append(pipe)
                # does the output port exist?
                if not n.has_port(edges[e][0]):
                    raise ComponentPortError(
                        '''Trying to connect undefined
                           output port {0} {1}'''.format(n, edges[e][0]))
                else:
                    n.connect_output(edges[e][0], pipe)

                # does the input port exist?
                if not e.has_port(edges[e][1]):
                    raise ComponentPortError(
                        '''Trying to connect undefined
                           input port {0} {1}'''.format(e, edges[e][1]))
                else:
                    e.connect_input(edges[e][1], pipe)
    return nodes

def sched(ch, graph):
    """Sits in an infinite loop waiting on the channel to receive data.

    The procedure prolog takes care of sorting the
    input graph into a dependency list and initializing
    the filter tasklets used to construct the graph.

    @param graph: The graph representing the work flow
    @type graph: Python dict organized as a graph struct
    @param ch: The stackless channel to listen on
    @type ch: stackless.channel
    @return: nothing
    """
    # Added so that incoming data is fed to every input adapter
    # should check if in exists and create it if it doesn't
    # because a user could remove the input port by accident
    nodes = connect_graph_components(graph)
    tasks = schedule_recursively(nodes)
    inputEdges = []
    # Connect all the adapters to the input
    for node in nodes:
        if node.get_type() == 'ADAPTER':
            ie = Pype()
            node.connect_input('in', ie)
            inputEdges.append(ie)

    while True:
        data = ch.receive()
        for ie in inputEdges:
            ie.send(data)
        try:
            tasks[0].run()
        except:
            traceback.print_exc()

def schedule_recursively(nodes):
    """Correctly schedule higher order components with a recursive function.

    """
    tasks = []
    for node in nodes:
        if not hasattr(node, "subnodes"):
            """Simple component, simply schedule it."""
            tasks.append(stackless.tasklet(node.run)())
        else:
            """Higher order component, go one level deeper."""
            tasks.extend(schedule_recursively(node.subnodes))
    return tasks


text:
/* $Id$ */

package org.apache.xmlgraphics.image.loader.impl;

import org.apache.xmlgraphics.image.loader.Image;
import org.apache.xmlgraphics.image.loader.ImageFlavor;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.java2d.Graphics2DImagePainter;

/**
 * This class is an implementation of the Image interface exposing a Graphics2DImagePainter.
 */
public class ImageGraphics2D extends AbstractImage {

    private Graphics2DImagePainter painter;

    /**
     * Main constructor.
     * @param info the image info object
     * @param painter the image painter that will paint the Java2D image
     */
    public ImageGraphics2D(ImageInfo info, Graphics2DImagePainter painter) {
        super(info);
        setGraphics2DImagePainter(painter);
    }

    /** {@inheritDoc} */
    public ImageFlavor getFlavor() {
        return ImageFlavor.GRAPHICS2D;
    }

    /** {@inheritDoc} */
    public boolean isCacheable() {
        Image img = getInfo().getOriginalImage();
        if (img == null) {
            return true;
        }
        return img.isCacheable();
    }

    /**
     * Returns the contained Graphics2DImagePainter instance.
     * @return the image painter
     */
    public Graphics2DImagePainter getGraphics2DImagePainter() {
        return this.painter;
    }

    /**
     * Sets the Graphics2DImagePainter instance.
     * @param painter the image painter
     */
    public void setGraphics2DImagePainter(Graphics2DImagePainter painter) {
        this.painter = painter;
    }

}


text:
package com.redhat.ceylon.compiler.java.runtime.metamodel;

import java.util.List;

import ceylon.language.Finished;
import ceylon.language.Iterator;
import ceylon.language.Sequential;
import ceylon.language.finished_;
import ceylon.language.meta.model.Type;
import ceylon.language.meta.model.Type$impl;

import com.redhat.ceylon.compiler.java.Util;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.Variance;
import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;

@Ceylon(major = 7)
@com.redhat.ceylon.compiler.java.metadata.Class
@TypeParameters({
    @TypeParameter(value = "Union", variance = Variance.OUT),
})
public class AppliedUnionType<Union>
    implements ceylon.language.meta.model.UnionType<Union>, ReifiedType {

    @Override
    @Ignore
    public TypeDescriptor $getType$() {
        return TypeDescriptor.klass(AppliedUnionType.class, $reifiedUnion);
    }

    @Ignore
    protected TypeDescriptor $reifiedUnion;

    com.redhat.ceylon.compiler.typechecker.model.ProducedType model;

    protected Sequential<? extends ceylon.language.meta.model.Type<? extends Union>> caseTypes;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<? extends Type<?>> iterator = caseTypes.iterator();
        Object next=iterator.next();
        sb.append(next);
        while (!((next=iterator.next()) instanceof Finished)) {
            sb.append('|').append(next);
        }
        return sb.toString();
    }

    AppliedUnionType(@Ignore TypeDescriptor $reifiedType, com.redhat.ceylon.compiler.typechecker.model.UnionType union){
        List<com.redhat.ceylon.compiler.typechecker.model.ProducedType> caseTypes = union.getCaseTypes();
        this.model = union.getType();
        this.$reifiedUnion = $reifiedType;
        @SuppressWarnings("unchecked")
        ceylon.language.meta.model.Type<? extends Union>[] types = new ceylon.language.meta.model.Type[caseTypes.size()];
        int i=0;
        for(com.redhat.ceylon.compiler.typechecker.model.ProducedType pt : caseTypes){
            types[i++] = Metamodel.getAppliedMetamodel(pt);
        }
        this.caseTypes = Util.<ceylon.language.meta.model.Type<? extends Union>>sequentialWrapper(TypeDescriptor.klass(ceylon.language.meta.model.Type.class, ceylon.language.Anything.$TypeDescriptor$), types);
    }

    @Override
    @Ignore
    public Type$impl<Union> $ceylon$language$meta$model$Type$impl() {
        return null;
    }

    @Override
    @TypeInfo("ceylon.language.Sequential<ceylon.language.meta.model::Type<Union>>")
    public ceylon.language.Sequential<? extends ceylon.language.meta.model.Type<? extends Union>> getCaseTypes() {
        return caseTypes;
    }

    @Override
    public int hashCode() {
        int result = 1;
        // do not use caseTypes.hashCode because order is not significant
        Iterator<? extends Type<?>> iterator = caseTypes.iterator();
        Object obj;
        while((obj = iterator.next()) != finished_.get_()){
            result = result + obj.hashCode();
        }
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == null)
            return false;
        if(obj == this)
            return true;
        if(obj instanceof AppliedUnionType == false)
            return false;
        AppliedUnionType<?> other = (AppliedUnionType<?>) obj;
        return other.model.isExactly(model);
    }

    @Override
    public boolean typeOf(@TypeInfo("ceylon.language::Anything") Object instance){
        return Metamodel.isTypeOf(model, instance);
    }

    @Override
    public boolean supertypeOf(@TypeInfo("ceylon.language.meta.model::Type<ceylon.language::Anything>") ceylon.language.meta.model.Type<? extends Object> type){
        return Metamodel.isSuperTypeOf(model, type);
    }

    @Override
    public boolean subtypeOf(@TypeInfo("ceylon.language.meta.model::Type<ceylon.language::Anything>") ceylon.language.meta.model.Type<? extends Object> type){
        return Metamodel.isSubTypeOf(model, type);
    }

    @Override
    public boolean exactly(@TypeInfo("ceylon.language.meta.model::Type<ceylon.language::Anything>") ceylon.language.meta.model.Type<? extends Object> type){
        return Metamodel.isExactly(model, type);
    }
}


text:
@interface NFDateFormatterISO : NSObject

+ (NFDateChainParser *)dateParser;
+ (NFDateChainParser *)dateTimeParser;

@end


text:
{% if not not_exists or not can_save or no_destiny %}

No seats can be copied

        {% if no_destiny %}

            No destination season selected

        {% endif %}

{% endif %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Charlotte.TCalcs
{
	public class FatUFloat
	{
		public FatUInt Inner;
		public int Exponent;

		public FatUFloat(FatUInt inner, int exponent)
		{
			this.Inner = inner;
			this.Exponent = exponent;
		}

		public void Normalize()
		{
			int start;

			for (start = 0; start < this.Inner.Figures.Length && this.Inner.Figures[start] == 0; start++)
			{ }

			if (start < this.Inner.Figures.Length)
			{
				int end;

				for (end = this.Inner.Figures.Length; this.Inner.Figures[end - 1] == 0; end--)
				{ }

				if (0 < start || end < this.Inner.Figures.Length)
				{
					this.Inner.Figures = TCalcArrays.CopyOfRange(this.Inner.Figures, start, end);
					this.Exponent += start;
				}
			}
			else
			{
				if (this.Inner.Figures.Length != 0)
					this.Inner.Figures = new int[0];

				this.Exponent = 0;
			}
		}

		public void Sync(FatUFloat another)
		{
			int count = this.Exponent - another.Exponent;

			if (0 < count)
			{
				this.Inner.Figures = TCalcArrays.Shift(this.Inner.Figures, count);
				this.Exponent -= count;
			}
		}
	}
}


text:
namespace MVCHoldem.UnitTests.Web.Controllers.HomeControllerTests
{
    using System;
    using MVCHoldem.Services;
    using MVCHoldem.Web.Controllers;
    using NUnit.Framework;

    [TestFixture]
    public class Constructor_Should
    {
        [Test]
        public void ThrowArgumentNullException_WhenPostServiceIsNull()
        {
            // Arrange
            PostService postService = null;

            // Act & Assert
            Assert.Throws<ArgumentNullException>(() => new HomeController(postService));
        }
    }
}


text:
'use strict';

const appConfig = {
  apiCredentials_test: { // switch to Production config later
    url: 'INSERT SHOPWARE GENERAL API ENDPOINT http://.../api',
    apiUser: 'INSERT API USER',
    apiKey: 'INSERT API KEY'
  }
};

export default appConfig;


text:
<?xml version="1.0" encoding="utf-8" ?>
<beanio xmlns="http://www.beanio.org/2015/06">
  <import resource="resource:SocialInsurance.Germany.Messages.Mappings.DSBE-v04.xml, Dataline.SocialInsurance.Germany.Messages.Mappings"/>
  <stream name="DSBE-v04" format="fixedlength">
    <record name="DSBE" occurs="1+" class="SocialInsurance.Germany.Messages.Pocos.DSBE04, Dataline.SocialInsurance.Germany.Messages.Pocos">
      <include template="DSBE-v04"/>
    </record>
  </stream>
</beanio>


text:
export function up(schema) {
  return schema.createTable('reactions', table => {
    table.increments('id');

    table.enum('type', [
      ':+1:',
      ':heart:',
      ':confetti_ball:',
      ':laughing:',
      ':disappointed:'
    ]).index().notNullable();

    table.integer('user_id')
      .index();

    table.integer('post_id')
      .index();

    table.integer('comment_id')
      .index();

    table.timestamps();
    table.index('created_at');
    table.index('updated_at');
  });
}

export function down(schema) {
  return schema.dropTable('reactions');
}


text:
package org.apache.pig.test;

import static org.junit.Assert.assertTrue;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.TaskReport;
import org.apache.pig.tools.pigstats.JobStats;
import org.apache.pig.tools.pigstats.PigStats;
import org.apache.pig.tools.pigstats.PigStats.JobGraph;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;

public class TestJobStats {

	private static final TaskReport[] mapTaskReports = new TaskReport[5];
	private static final TaskReport[] reduceTaskReports = new TaskReport[5];
	private static final JobID jobID = new JobID("jobStat", Integer.MAX_VALUE);
	private static String ASSERT_STRING;

	private static final int ONE_THOUSAND = 1000;

	private static final long[][] MAP_START_FINISH_TIME_DATA = { { 0, 100},
		{ 200, 400 }, { 500, 800 }, { 900, 1300 }, { 1400, 1900 } };

	private static final long[][] REDUCE_START_FINISH_TIME_DATA = { { 0, 100 },
		{ 200, 400 }, { 500, 700 }, { 700, 900 }, { 1000, 1500 } };

	@BeforeClass
    public static void oneTimeSetup() throws Exception {

		// setting up TaskReport for map tasks
		for (int i = 0; i < mapTaskReports.length; i++) {
			mapTaskReports[i] = Mockito.mock(TaskReport.class);
			Mockito.when(mapTaskReports[i].getStartTime()).thenReturn(MAP_START_FINISH_TIME_DATA[i][0] * ONE_THOUSAND);
			Mockito.when(mapTaskReports[i].getFinishTime()).thenReturn(MAP_START_FINISH_TIME_DATA[i][1] * ONE_THOUSAND);
		}

		// setting up TaskReport for reduce tasks
		for (int i = 0; i < reduceTaskReports.length; i++) {
			reduceTaskReports[i] = Mockito.mock(TaskReport.class);
			Mockito.when(reduceTaskReports[i].getStartTime()).thenReturn(REDUCE_START_FINISH_TIME_DATA[i][0] * ONE_THOUSAND);
			Mockito.when(reduceTaskReports[i].getFinishTime()).thenReturn(REDUCE_START_FINISH_TIME_DATA[i][1] * ONE_THOUSAND);
		}

		StringBuilder sb = new StringBuilder();
		sb.append(jobID.toString()).append("\t");
		sb.append(mapTaskReports.length).append("\t");
		sb.append(reduceTaskReports.length).append("\t");

		sb.append("500\t100\t300\t300\t500\t100\t240\t200");
		ASSERT_STRING = sb.toString();
    }

	JobStats createJobStats(String name, JobGraph plan) {
	    try {
    	    Constructor con = JobStats.class.getDeclaredConstructor(String.class, JobGraph.class);
    	    con.setAccessible(true);
    	    JobStats jobStats = (JobStats)con.newInstance(name, plan);
    	    return jobStats;
	    } catch (Exception e) {
	        return null;
	    }
	}

	Method getJobStatsMethod(String methodName, Class<?>... parameterTypes) throws Exception {
	    Method m = JobStats.class.getDeclaredMethod(methodName, parameterTypes);
        m.setAccessible(true);
        return m;
	}

	@Test
	public void testMedianMapReduceTime() throws Exception {

		JobConf jobConf = new JobConf();
		JobClient jobClient = Mockito.mock(JobClient.class);

		// mock methods to return the predefined map and reduce task reports
		Mockito.when(jobClient.getMapTaskReports(jobID)).thenReturn(mapTaskReports);
		Mockito.when(jobClient.getReduceTaskReports(jobID)).thenReturn(reduceTaskReports);

		PigStats.JobGraph jobGraph = new PigStats.JobGraph();
		JobStats jobStats = createJobStats("JobStatsTest", jobGraph);
		getJobStatsMethod("setId", JobID.class).invoke(jobStats, jobID);
		getJobStatsMethod("setSuccessful", boolean.class).invoke(jobStats, true);

		getJobStatsMethod("addMapReduceStatistics", JobClient.class, Configuration.class)
		    .invoke(jobStats, jobClient, jobConf);
		String msg = (String)getJobStatsMethod("getDisplayString", boolean.class)
		    .invoke(jobStats, false);

		System.out.println(JobStats.SUCCESS_HEADER);
		System.out.println(msg);

		assertTrue(msg.startsWith(ASSERT_STRING));
	}

	@Test
	public void testOneTaskReport() throws Exception {
		// setting up one map task report
		TaskReport[] mapTaskReports = new TaskReport[1];
		mapTaskReports[0] = Mockito.mock(TaskReport.class);
		Mockito.when(mapTaskReports[0].getStartTime()).thenReturn(300L * ONE_THOUSAND);
		Mockito.when(mapTaskReports[0].getFinishTime()).thenReturn(400L * ONE_THOUSAND);

		// setting up one reduce task report
		TaskReport[] reduceTaskReports = new TaskReport[1];
		reduceTaskReports[0] = Mockito.mock(TaskReport.class);
		Mockito.when(reduceTaskReports[0].getStartTime()).thenReturn(500L * ONE_THOUSAND);
		Mockito.when(reduceTaskReports[0].getFinishTime()).thenReturn(700L * ONE_THOUSAND);

		JobConf jobConf = new JobConf();
		JobClient jobClient = Mockito.mock(JobClient.class);

		Mockito.when(jobClient.getMapTaskReports(jobID)).thenReturn(mapTaskReports);
		Mockito.when(jobClient.getReduceTaskReports(jobID)).thenReturn(reduceTaskReports);

		PigStats.JobGraph jobGraph = new PigStats.JobGraph();
		JobStats jobStats = createJobStats("JobStatsTest", jobGraph);
		getJobStatsMethod("setId", JobID.class).invoke(jobStats, jobID);
		getJobStatsMethod("setSuccessful", boolean.class).invoke(jobStats, true);

		getJobStatsMethod("addMapReduceStatistics", JobClient.class, Configuration.class)
		    .invoke(jobStats, jobClient, jobConf);
		String msg = (String)getJobStatsMethod("getDisplayString", boolean.class)
		    .invoke(jobStats, false);
		System.out.println(JobStats.SUCCESS_HEADER);
		System.out.println(msg);

		StringBuilder sb = new StringBuilder();
		sb.append(jobID.toString()).append("\t");
		sb.append(mapTaskReports.length).append("\t");
		sb.append(reduceTaskReports.length).append("\t");
		sb.append("100\t100\t100\t100\t200\t200\t200\t200");

		System.out.println("assert msg: " + sb.toString());
		assertTrue(msg.startsWith(sb.toString()));

	}
}


text:
// AccelStepper.cpp
//
// Copyright (C) 2009 Mike McCauley
// $Id: AccelStepper.cpp,v 1.2 2010/10/24 07:46:18 mikem Exp mikem $

#define __STDC_LIMIT_MACROS 1
#include <stdint.h>
#include "AccelStepper.h"

void AccelStepper::moveTo(long absolute)
{
    _targetPos = absolute;
    computeNewSpeed();
}

void AccelStepper::move(long relative)
{
    _startPos = _currentPos;
    moveTo(_currentPos + relative);
}

// Implements steps according to the current speed
// You must call this at least once per step
// returns true if a step occurred
boolean AccelStepper::runSpeed()
{
    //unsigned long time = millis();
    unsigned long time = micros();
    unsigned long delta = time - _lastStepTime;

    if (delta > _stepInterval)
    {
	if (_speed > 0)
	{
	    // Clockwise
	    _currentPos += 1;
	}
	else if (_speed < 0)
	{
	    // Anticlockwise
	    _currentPos -= 1;
	}
	step(_currentPos & 0x3); // Bottom 2 bits (same as mod 4, but works with + and - numbers)

	_lastStepTime = time;
	return true;
    }
    else
	return false;
}

long AccelStepper::distanceToGo()
{
    return _targetPos - _currentPos;
}

long AccelStepper::targetPosition()
{
    return _targetPos;
}

long AccelStepper::currentPosition()
{
    return _currentPos;
}

// Useful during initializations or after initial positioning
void AccelStepper::setCurrentPosition(long position)
{
    _currentPos = position;
}

void AccelStepper::computeNewSpeed()
{
    setSpeed(desiredSpeed());
}

// Work out and return a new speed.
// Subclasses can override if they want
// Implement acceleration, deceleration and max speed
// Negative speed is anticlockwise
// This is called:
//  after each step
//  after user changes:
//   maxSpeed
//   acceleration
//   target position (relative or absolute)
float AccelStepper::desiredSpeed()
{
    long distanceTo = distanceToGo();

    // Max possible speed that can still decelerate in the available distance
    float requiredSpeed;
    if (distanceTo == 0)
	return 0.0f; // Were there
    else if (distanceTo > 0) // Clockwise
	requiredSpeed = sqrtf(2.0f * distanceTo * _acceleration);
    else  // Anticlockwise
	requiredSpeed = -sqrtf(2.0f * -distanceTo * _acceleration);

    if (requiredSpeed > _speed)
    {
	// Need to accelerate in clockwise direction
	if (_speed == 0)
	    requiredSpeed = sqrtf(2.0f * _acceleration);
	else
	    requiredSpeed = _speed + abs(_acceleration / _speed);
	if (requiredSpeed > _maxSpeed)
	    requiredSpeed = _maxSpeed;
    }
    else if (requiredSpeed < _speed)
    {
	// Need to accelerate in anticlockwise direction
	if (_speed == 0)
	    requiredSpeed = -sqrtf(2.0f * _acceleration);
	else
	    requiredSpeed = _speed - abs(_acceleration / _speed);
	if (requiredSpeed < -_maxSpeed)
	    requiredSpeed = -_maxSpeed;
    }
//  Serial.println(requiredSpeed);
    return requiredSpeed;
}

// Run the motor to implement speed and acceleration in order to proceed to the target position
// You must call this at least once per step, preferably in your main loop
// If the motor is in the desired position, the cost is very small
// returns true if we are still running to position
boolean AccelStepper::run()
{
    if (_targetPos == _currentPos)
	return false;

    if (runSpeed())
	computeNewSpeed();
    return true;
}

AccelStepper::AccelStepper(uint8_t pins, uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4)
{
    _pins = pins;
    _currentPos = 0;
    _targetPos = 0;
    _speed = 0.0;
    _maxSpeed = 1.0;
    _acceleration = 1.0;
    _stepInterval = 0;
    _lastStepTime = 0;
    _pin1 = pin1;
    _pin2 = pin2;
    _pin3 = pin3;
    _pin4 = pin4;
    enableOutputs();
}

AccelStepper::AccelStepper(void (*forward)(), void (*backward)())
{
    _pins = 0;
    _currentPos = 0;
    _targetPos = 0;
    _speed = 0.0;
    _maxSpeed = 1.0;
    _acceleration = 1.0;
    _lastStepTime = 0;
    _pin1 = 0;
    _pin2 = 0;
    _pin3 = 0;
    _pin4 = 0;
    _forward = forward;
    _backward = backward;
}

void AccelStepper::setMaxSpeed(float speed)
{
    _maxSpeed = speed;
    computeNewSpeed();
}

void AccelStepper::setAcceleration(float acceleration)
{
    _acceleration = acceleration;
    computeNewSpeed();
}

void AccelStepper::setSpeed(float speed)
{
    _speed = speed;
    //_stepInterval = abs(1000.0 / _speed);
    _stepInterval = (unsigned long)fabs(1000000.0 / _speed);
}

float AccelStepper::speed()
{
    return _speed;
}

// Subclasses can override
void AccelStepper::step(uint8_t step)
{
    switch (_pins)
    {
        case 0:
            step0();
            break;
	case 1:
	    step1(step);
	    break;

	case 2:
	    step2(step);
	    break;

	case 4:
	    step4(step);
	    break;
    }
}

// 0 pin step function (ie for functional usage)
void AccelStepper::step0()
{
  if (_speed > 0) {
    _forward();
  } else {
    _backward();
  }
}

// 1 pin step function (ie for stepper drivers)
// This is passed the current step number (0 to 3)
// Subclasses can override
void AccelStepper::step1(uint8_t step)
{
    digitalWrite(_pin2, _speed > 0); // Direction
    // Caution 200ns setup time
    digitalWrite(_pin1, HIGH);
    // Caution, min Step pulse width for 3967 is 1microsec
    // Delay 1microsec
    delayMicroseconds(1);
    digitalWrite(_pin1, LOW);
}

// 2 pin step function
// This is passed the current step number (0 to 3)
// Subclasses can override
void AccelStepper::step2(uint8_t step)
{
    switch (step)
    {
	case 0: /* 01 */
	    digitalWrite(_pin1, LOW);
	    digitalWrite(_pin2, HIGH);
	    break;

	case 1: /* 11 */
	    digitalWrite(_pin1, HIGH);
	    digitalWrite(_pin2, HIGH);
	    break;

	case 2: /* 10 */
	    digitalWrite(_pin1, HIGH);
	    digitalWrite(_pin2, LOW);
	    break;

	case 3: /* 00 */
	    digitalWrite(_pin1, LOW);
	    digitalWrite(_pin2, LOW);
	    break;
    }
}

// 4 pin step function
// This is passed the current step number (0 to 3)
// Subclasses can override
void AccelStepper::step4(uint8_t step)
{
    switch (step)
    {
	case 0:    // 1010
	    digitalWrite(_pin1, HIGH);
	    digitalWrite(_pin2, LOW);
	    digitalWrite(_pin3, HIGH);
	    digitalWrite(_pin4, LOW);
	    break;

	case 1:    // 0110
	    digitalWrite(_pin1, LOW);
	    digitalWrite(_pin2, HIGH);
	    digitalWrite(_pin3, HIGH);
	    digitalWrite(_pin4, LOW);
	    break;

	case 2:    //0101
	    digitalWrite(_pin1, LOW);
	    digitalWrite(_pin2, HIGH);
	    digitalWrite(_pin3, LOW);
	    digitalWrite(_pin4, HIGH);
	    break;

	case 3:    //1001
	    digitalWrite(_pin1, HIGH);
	    digitalWrite(_pin2, LOW);
	    digitalWrite(_pin3, LOW);
	    digitalWrite(_pin4, HIGH);
	    break;
    }
}

// Prevents power consumption on the outputs
void    AccelStepper::disableOutputs()
{
  if (! _pins) return;

    digitalWrite(_pin1, LOW);
    digitalWrite(_pin2, LOW);
    if (_pins == 4)
    {
	digitalWrite(_pin3, LOW);
	digitalWrite(_pin4, LOW);
    }
}

void    AccelStepper::enableOutputs()
{
    if (! _pins) return;

    pinMode(_pin1, OUTPUT);
    pinMode(_pin2, OUTPUT);
    if (_pins == 4)
    {
	pinMode(_pin3, OUTPUT);
	pinMode(_pin4, OUTPUT);
    }
}

// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
    while (run())
	;
}

boolean AccelStepper::runSpeedToPosition()
{
    return _targetPos!=_currentPos ? AccelStepper::runSpeed() : false;
}

// Blocks until the new target position is reached
void AccelStepper::runToNewPosition(long position)
{
    moveTo(position);
    runToPosition();
}


text:
var fs = require('fs');
var path = require('path');
var vm = require('vm');

var preproc = require('..');

var fixturesPath = path.resolve(__dirname, 'fixtures/');

describe('basic jest preproc', function () {
  it('should export `process` property', function () {
    preproc.process.should.be.a.Function;
  });

  it('should preprocess regular file', function () {
    var filepath = path.resolve(fixturesPath, 'hello.js');
    var code = preproc.process(fs.readFileSync(filepath), filepath);
    var sandbox = { module: {} };
    vm.runInNewContext(code, sandbox);
    sandbox.module.exports.should.be.equal("Hello, World!");
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView

        android:background="@drawable/default_img"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:scaleType="centerCrop"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:visibility="gone"
        android:id="@+id/nd_header"
        android:layout_gravity="center_vertical"
        android:orientation="vertical">

            <ImageView

                android:src="@drawable/smile"
                android:id="@+id/navigation_drawer_header_icon"
                android:layout_width="64dp"
                android:layout_height="64dp"/>

            <com.devspark.robototextview.widget.RobotoTextView
                android:id="@+id/secondary_navigation_title"
                app:typeface="roboto_medium"
                android:text="@string/app_name"
                android:gravity="center_vertical"
                android:layout_marginTop="5dp"
                android:textSize="18sp"
                android:textColor="@color/text_color_primary"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </LinearLayout>
</FrameLayout>


text:
package guru.breakthemonolith.docker;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility class to execute Docker-related commands locally. This assumes that
 * command 'docker ps' works on the machine that this executes on.
 *
 * @author D. Ashmore
 *
 */
public class DockerCommandUtils {

	public static final String LOGGER_LABEL = "DockerProcessAPI";
	private static Logger logger = LoggerFactory.getLogger(LOGGER_LABEL);

	/**
	 * Issues 'docker pull' command.
	 *
	 * @param imageName including tag reference
	 */
	public static void dockerPull(String imageName) {
		Validate.notBlank(imageName, "Null or blank imageName not allowed.");
		CommandUtils.issueCommand(new String[] { "docker", "pull", imageName }, "Error with 'docker pull'",
				new Pair[] { new ImmutablePair("imageName", imageName) });
	}

	/**
	 * Kills and deletes a running container ('docker rm -f').
	 *
	 * @param containerName
	 */
	public static void dockerKillContainer(String containerName) {
		Validate.notBlank(containerName, "Null or blank containerName not allowed.");
		CommandUtils.issueCommand(new String[] { "docker", "rm", "-f", containerName }, "Error with 'docker rm'",
				new Pair[] { new ImmutablePair("containerName", containerName) });
	}

	/**
	 * Logs "log" output from a running container ('docker logs --details').
	 *
	 * @param containerName
	 */
	public static void dockerLogContainer(String containerName) {
		Validate.notBlank(containerName, "Null or blank containerName not allowed.");
		CommandUtils.issueCommand(new String[] { "docker", "logs", "--details", containerName },
				"Error with 'docker logs'",
				new Pair[] { new ImmutablePair("containerName", containerName) });
	}

	/**
	 * Logs all running Docker containers (issues 'docker ps'). All output under
	 * logger 'DockerProcessAPI'.
	 *
	 * @param containerName
	 */
	public static void dockerContainerListing() {
		CommandUtils.issueCommand(new String[] { "docker", "ps" }, "Error with 'docker ps'");
	}

	/**
	 * Issues a 'docker run' command.
	 *
	 * @param dockerRunSpecification
	 */
	public static String dockerRun(DockerRunSpecification dockerRunSpecification) {
		Validate.notNull(dockerRunSpecification, "Null dockerRunSpecification not allowed.");
		Validate.notBlank(dockerRunSpecification.getImageName(), "Null or blank imageName not allowed.");

		String containerName = null;

		List<String> commandItemList = new ArrayList<String>();
		commandItemList.add("docker");
		commandItemList.add("run");

		if (dockerRunSpecification.isDetachInd()) {
			commandItemList.add("-d");
			commandItemList.add("--name");
			containerName = UUID.randomUUID().toString();
			commandItemList.add(containerName);
		}

		if (dockerRunSpecification.getVolumeMap().size() > 0) {
			for (Map.Entry<String, String> volume : dockerRunSpecification.getVolumeMap().entrySet()) {
				commandItemList.add("-v");
				commandItemList.add(volume.getKey() + ":" + volume.getValue());
			}
		}

		if (dockerRunSpecification.getPortMap().size() > 0) {
			for (Map.Entry<String, String> port : dockerRunSpecification.getPortMap().entrySet()) {
				commandItemList.add("-p");
				commandItemList.add(port.getKey() + ":" + port.getValue());
			}
		}

		if (dockerRunSpecification.getEnvironmentMap().size() > 0) {
			for (Map.Entry<String, String> envVariable : dockerRunSpecification.getEnvironmentMap().entrySet()) {
				commandItemList.add("-e");
				if (StringUtils.isEmpty(envVariable.getValue())) {
					commandItemList.add(envVariable.getKey());
				} else {
					commandItemList.add(envVariable.getKey() + ":" + envVariable.getValue());
				}
			}
		}

		commandItemList.add(dockerRunSpecification.getImageName());

		if (StringUtils.isNotBlank(dockerRunSpecification.getCommand())) {
			for (String commandPart : StringUtils.split(dockerRunSpecification.getCommand(), ' ')) {
				commandItemList.add(commandPart);
			}
		}

		String[] commandArray = commandItemList.toArray(new String[0]);
		String commandStr = StringUtils.join(commandArray, ' ');

		logger.info("Docker command: {}", commandStr);
		try {
			Process docker = CommandUtils.createProcess(commandArray);
			if (dockerRunSpecification.isDetachInd()) {
				Thread.sleep(dockerRunSpecification.getDetachedWaitTimeMillis());

				BufferedReader inputReader = new BufferedReader(new InputStreamReader(docker.getInputStream()));
				BufferedReader errorReader = new BufferedReader(new InputStreamReader(docker.getErrorStream()));

				String stdOut = IOUtils.toString(inputReader);
				String stdErr = IOUtils.toString(errorReader);

				logger.info(stdOut);
				if (StringUtils.isNoneBlank(stdErr)) {
					logger.error(stdErr);
				}
			} else {
				CommandUtils.waitForThrowingException(docker, commandStr);
			}
		} catch (Exception e) {
			throw new ContextedRuntimeException("Error with 'docker run'", e)
					.addContextValue("containerName", containerName)
					.addContextValue("dockerRunSpecification", dockerRunSpecification)
					.addContextValue("commandStr", commandStr);
		}

		return containerName;
	}
}


text:
#region Copyright

#endregion

#region

using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using System.Collections.Generic;
using Dynamo.Nodes;
using Kodestruct.Common.Section.Interfaces;
using ds = Kodestruct.Common.Section.SectionTypes;
using dm = Kodestruct.Common.Mathematics;
using System;

#endregion

namespace Analysis.Section.SectionTypes
{

    public partial class SectionDoubleStacked : CustomProfile
    {

        [IsVisibleInDynamoLibrary(false)]
        internal SectionDoubleStacked(CustomProfile ShapeUpper, CustomProfile ShapeLower, double d_tops)
        {
            if (ShapeLower.Section is Kodestruct.Common.Section.CompoundShape && ShapeUpper.Section is Kodestruct.Common.Section.CompoundShape)
            {
                Kodestruct.Common.Section.CompoundShape lowerSectionComp = ShapeLower.Section as Kodestruct.Common.Section.CompoundShape;
                Kodestruct.Common.Section.CompoundShape upperSectionComp = ShapeUpper.Section as Kodestruct.Common.Section.CompoundShape;

            Kodestruct.Common.Section.SectionDoubleStacked section = new Kodestruct.Common.Section.SectionDoubleStacked(upperSectionComp, lowerSectionComp, d_tops);
            Section = section;
            }
            else
            {
                throw new Exception("Provided shape type is not supported. Please select a different shape as parameter.");
            }

        }

        /// <summary>
        /// Creates a custom profile object consisting of 2 stacked shapes on top of each other, separated by a vertical distance d_tops, measured as distance between  top of lower shape and top of upper shape.
        /// </summary>
        /// <param name="ShapeUpper">Upper shape object</param>
        /// <param name="ShapeLower">Lower shape object</param>
        /// <param name="d_tops">Distance measured  between  top of lower shape and top of upper shape.</param>
        /// <returns></returns>
        public static SectionDoubleStacked ByShapesAndTopToTopDistance(CustomProfile ShapeUpper, CustomProfile ShapeLower, double d_tops)
        {
            return new SectionDoubleStacked(ShapeUpper, ShapeLower, d_tops);
        }

    }
}


text:
body{
    margin:0;
    padding: 0;
}

.activityModel {
    border: 1px;
    width: 19px;
    height: 19px;
    background: linear-gradient(70deg, indianred, white);
    position: absolute;
}


text:
<?php
/**
 * Class:  DatasourcesHandler
 * @author: Minh Duc Nguyen <minh.nguyen@ands.org.au>
 */

namespace ANDS\API\Registry\Handler;
use ANDS\DataSource;
use ANDS\DataSource\DataSourceLog;
use ANDS\DataSource\Harvest;
use ANDS\DataSourceAttribute;
use ANDS\Payload;
use ANDS\Registry\API\Router;
use ANDS\Registry\Importer;
use ANDS\RegistryObject;
use ANDS\Repository\RegistryObjectsRepository;
use ANDS\Util\Config;
use \Exception as Exception;
use ANDS\Registry\Providers\ServiceDiscovery\ServiceDiscovery as ServiceDiscoveryProvider;

/**
 * Class DatasourcesHandler
 * @package ANDS\API\Registry\Handler
 */
class DatasourcesHandler extends Handler
{
    private $input = [];

    public function handle()
    {
        $this->getParentAPI()->providesOwnResponse();
        $this->getParentAPI()->outputFormat = "application/json";

        $router = new Router('/api/registry/');

        // RESOURCE ds/:id
        $router->resource('datasources', 'DataSourcesController');

        // RESOURCE ds/:id/attributes
        $router->resource('datasources/(\w+)/attributes', 'DataSourcesAttributesController');

        // GET ds/:id/log
        $router->get('datasources/(\w+)/log', 'DataSourcesLogController@index');

        // GET ds/:id/harvest
        $router->get('datasources/(\w+)/harvest', 'DataSourcesHarvestController@index');

        // PUT|POST ds/:id/harvest
        $router->route(['put', 'post'], 'datasources/(\w+)/harvest', 'DataSourcesHarvestController@triggerHarvest');

        // DELETE ds/:id/harvest
        $router->route(['delete'], 'datasources/(\w+)/harvest', 'DataSourcesHarvestController@stopHarvest');

        // PUT ds/:id/services
        $router->route(['put', 'post'], 'datasources/(\w+)/services', 'DataSourcesServiceController@index');

        // standard resources
        $router->resource('datasources/(\w+)/records', 'DataSourcesRecordsController');
        $router->route(['delete'], 'datasources/(\w+)/records', 'DataSourcesRecordsController@delete');

        // sync
        $router->route(['get', 'put', 'post'], 'datasources/(\w+)/sync', 'DataSourcesController@sync');

        return $this->format($router->execute());
    }

    public function format($data)
    {
        return json_encode($data);
    }

    // from this point on, it's old formatting
    /**
     * @return array
     * @throws Exception
     */
    public function handle_old()
    {
        $this->middleware();

        if ($this->params['identifier'] === false) {

            // POST api/registry/datasources
            if ($this->isPost()) {
                $newDataSource = $this->handleDataSourceCreation();
                return $newDataSource->toArray();
            }

            // GET api/registry/datasources
            return DataSource::all();
        }

        $identifier = $this->params['identifier'];
        $dataSource = DataSource::find($identifier);
        if (!$dataSource) {
            $dataSource = DataSource::where('slug', $identifier)
                ->get()->first();
        }
        if (!$dataSource) {
            $dataSource = DataSource::where('title', $identifier)
                ->get()->first();
        }

        if (!$dataSource) {
            throw new Exception("DataSource with identifier (id|slug) $identifier not found");
        }

        $dataSource->load('harvest');
        $dataSource->load('dataSourceAttributes');

        if ($this->params['object_module'] === false) {

            // DELETE api/registry/datasources/:id
            if ($this->isDelete()) {
                return $this->handleDataSourceDelete($dataSource);
            }

            // GET api/registry/datasources/:id
            return $dataSource;
        }

        switch ($this->params['object_module']) {
            case "harvest":
                return $this->handleHarvest($dataSource);
            case "attributes":
                return $this->handleAttribute($dataSource);
            case "records":
                return $this->handleRecords($dataSource);
            case "log":
                return $this->handleDataSourceLog($dataSource);
            case "services":
                return $this->handleServiceCreation($dataSource);
        }

        return null;
    }

    private function handleServiceCreation(DataSource $dataSource)
    {
        // trigger service creation
        if (!$this->isPost() && !$this->isPut()) {
            return;
        }

        $ids = RegistryObject::where("status", "PUBLISHED")
            ->where('data_source_id', $dataSource->data_source_id)
            ->where('class', 'collection')->pluck('registry_object_id');

        if (count($ids) === 0) {
            return "No collection found";
        }

        $links = ServiceDiscoveryProvider::getServiceByRegistryObjectIds($ids);
        $links = ServiceDiscoveryProvider::processLinks($links);
        $links = ServiceDiscoveryProvider::formatLinks($links);

        if (count($links) === 0) {
            return "No links found for {$ids->count()} collections";
        }

        $acronym = $dataSource->acronym ? : "ACRONYM";
        $batchID = "MANUAL";
        $directoryPath = "/var/ands/data/{$acronym}";

        try {
            if (!is_dir($directoryPath)) {
                mkdir($directoryPath, 0775, true);
            }
            $filePath = "{$directoryPath}/services_{$batchID}.json";

            file_put_contents($filePath, json_encode($links, true));

            return [
                'count' => count($links),
                'path' => $filePath
            ];
        } catch (Exception $e) {
            return get_exception_msg($e);
        }
    }

    /**
     * @param DataSource $dataSource
     * @return mixed
     */
    private function handleDataSourceLog(DataSource $dataSource)
    {
        $dataSource->load('dataSourceLog');
        return $dataSource->dataSourceLog;
    }

    /**
     * @param DataSource $dataSource
     * @return mixed
     */
    private function handleHarvest(DataSource $dataSource)
    {
        // trigger harvest
        // PUT|POST api/registry/datasources/:id/harvest
        if ($this->isPost() || $this->isPut()) {
            $dataSource->startHarvest();
        }

        // cancel harvest
        // DELETE api/registry/datasources/:id/harvest
        if ($this->isDelete()) {
            $dataSource->stopHarvest();
            $dataSource->appendDataSourceLog(
                "Harvest stopped via API", "info", "IMPORTER"
            );
        }

        return $dataSource->harvest;
    }

    /**
     * @param DataSource $dataSource
     * @return array
     */
    private function handleRecords(DataSource $dataSource)
    {
        // define list
        $limit = $this->getInput('limit') !== null ? $this->getInput('limit') : 10;
        $offset = $this->getInput('offset') !== null ? $this->getInput('offset') : 0;

        $filters = [];
        $fields = ['status', 'class', 'type', 'group'];
        foreach ($fields as $field) {
            if ($this->getInput($field) !== null) {
                $filters[$field] = $this->getInput($field);
            }
        }

        $records = RegistryObjectsRepository::getRecordsByDataSource($dataSource, $limit, $offset, $filters);

        // delete all records in a datasource
        // DELETE api/registry/datasources/:id/records
        if ($this->isDelete()) {
            $task = Importer::instantDeleteRecords($dataSource, [
                'ids' => $records->pluck('registry_object_id')
            ]);
            return $task ? $task->toArray() : [];
        }

        // import records from url provided in GET or POST
        // POST api/registry/datasources/:id/records
        if ($this->isPost()) {
            if (!array_key_exists('url', $this->input)) {
                throw new Exception("Missing url. Input: " . implode(', ', array_keys($this->input)));
            }
            $url = $this->input['url'];
            $content = @file_get_contents($url);

            $batchID = "MANUAL-URL-".str_slug($url).'-'.time();
            Payload::write($dataSource->data_source_id, $batchID, $content);
            $task =  Importer::instantImportRecordFromBatchID($dataSource, $batchID);
            return $task->toArray();
        }

        // browse records
        return $records;
    }

    /**
     * @return DataSource
     * @throws Exception
     */
    private function handleDataSourceCreation()
    {
        $missing = $this->getMissingInput(['key', 'title', 'record_owner']);
        if (count($missing) > 0) {
            throw new Exception("Missing POST fields: ". implode(", ", $missing));
        }

        $dataSource = DataSource::create([
            'key' => $this->getInput('key'),
            'title' => $this->getInput('title'),
            'record_owner' => $this->getInput('record_owner'),
            'slug' => url_title($this->getInput('title'))
        ]);

        $attributes = [
            'provider_type' => 'rif',
            'uri' => 'http://',
            'harvest_method'=>'GETHarvester',
            'allow_reverse_internal_links' => DB_TRUE,
            'allow_reverse_external_links' => DB_TRUE,
            'manual_publish' => DB_FALSE,
            'qa_flag' => DB_TRUE,
            'create_primary_relationships' => DB_FALSE,
            'assessment_notify_email_addr' => '',
            'created' => '',
            'updated' => '',
            'export_dci' => DB_FALSE,
            'crosswalks' => '',
            'title' => $this->getInput('title'),
            'record_owner' => $this->getInput('record_owner'),
            'contact_name'=>' ',
            'contact_email'=>' ',
            'notes'=>'',
            'harvest_date' => '',
            'oai_set' => '',
            'advanced_harvest_mode' => 'STANDARD',
            'harvest_frequency' => '',
            'metadataPrefix' => '',
            'xsl_file' => '',
            'user_defined_params' => ''
        ];

        foreach ($attributes as $key => $value) {
            $dataSource->setDataSourceAttribute($key, $value);
        }

        return $dataSource;
    }

    /**
     * @param DataSource $dataSource
     * @return bool
     */
    private function handleDataSourceDelete(DataSource $dataSource)
    {
        // delete attributes
        $attributes = DataSourceAttribute::where('data_source_id', $dataSource->data_source_id)->delete();

        // delete logs
        $logs = DataSourceLog::where('data_source_id', $dataSource->data_source_id)->delete();

        // delete harvest
        $harvest = Harvest::where('data_source_id', $dataSource->data_source_id)->delete();

        // wipe all records from existence
        $ids = RegistryObject::where('data_source_id', $dataSource->data_source_id)
            ->get()->pluck('registry_object_id');
        $records = [];
        foreach ($ids as $id) {
            $records[$id] = RegistryObjectsRepository::completelyEraseRecordByID($id);
        }

        // TODO: wipe index as well
        $index = false;

        $ds = $dataSource->delete();
        return compact('attributes', 'logs', 'harvest', 'ds', 'records', 'index');
    }

    /**
     * @param DataSource $dataSource
     * @return array
     * @throws Exception
     */
    public function handleAttribute(DataSource $dataSource)
    {
        if($this->params['object_submodule'] === false) {

            //POST api/registry/datasources/:id/attributes
            //Creates new attributes
            if ($this->isPost()) {
                $missing = $this->getMissingInput(['attribute', 'value']);
                if (count($missing) > 0) {
                    return "Missing POST fields: ". implode(", ", $missing);
                }

                return DataSourceAttribute::create([
                    'attribute' => $this->input['attribute'],
                    'value' => $this->input['value'],
                    'data_source_id' => $dataSource->data_source_id
                ])->toArray();
            }

            return $dataSource->dataSourceAttributes;
        }

        //specific attribute
        $specific = $this->params['object_submodule'];
        $attribute = $dataSource
            ->getDataSourceAttribute($specific);

        if (!$attribute) {
            $attribute = DataSourceAttribute::find($specific);
        }

        if (!$attribute) {
            throw new Exception("No attribute $specific found in data source $dataSource->title");
        }

        // PUT api/registry/datasources/:id/attributes/[:id/:attribute]
        if ($this->isPut()) {
            $missing = $this->getMissingInput(['value']);
            if (count($missing) > 0) {
                return "Missing POST fields: ". implode(", ", $missing);
            }
            $attribute->value = $this->input['value'];
            $attribute->save();
            return $attribute;
        }

        if ($this->isDelete()) {
            return $attribute->delete();
        }

        // GET api/registry/datasources/:id/attributes/[:id/:attribute]
        return $attribute;
    }

    // Helpers

    /**
     * @param $key
     * @return mixed|null
     */
    public function getInput($key)
    {
        return array_key_exists($key, $this->input) ? $this->input[$key] : null;
    }

    /**
     * @param $required
     * @return array
     */
    public function getMissingInput($required)
    {
        return collect($required)->filter(function($item){
            return !array_key_exists($item, $this->input);
        })->toArray();
    }

    /**
     * @return bool
     */
    public function isPost()
    {
        return $_SERVER['REQUEST_METHOD'] === "POST";
    }

    /**
     * @return bool
     */
    public function isDelete()
    {
        return $_SERVER['REQUEST_METHOD'] === "DELETE";
    }

    /**
     * @return bool
     */
    public function isPut()
    {
        return $_SERVER['REQUEST_METHOD'] === "PUT";
    }

    public function middleware()
    {
        $this->input = $_GET;

        if (($this->isPost() || $this->isDelete() || $this->isPut())){

            if ($this->isPost()) {
                $this->input = array_merge($_GET, $_POST);
            }
            if ($this->isPut()) {
                parse_str(file_get_contents("php://input"),$post_vars);
                $this->input = array_merge($_GET, $post_vars);
            }

            $this->verifyAuth();
        }
    }

    /**
     * @return bool
     * @throws Exception
     */
    public function verifyAuth()
    {
        $whitelist = Config::get('app.api_whitelist_ip');

        if (!$whitelist) {
            throw new Exception("Whitelist IP not configured properly. This operation is unsafe.");
        }

        $ip = $this->getIPAddress();
        if (!in_array($ip, $whitelist)) {
            throw new Exception("IP: $ip is not whitelist for this behavior");
        }

        return true;
    }

    /**
     * @return string
     */
    private function getIPAddress()
    {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            return $_SERVER["HTTP_X_FORWARDED_FOR"];
        }

        if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            return $_SERVER["HTTP_CLIENT_IP"];
        }

        if (isset($_SERVER["REMOTE_ADDR"])) {
            return $_SERVER["REMOTE_ADDR"];
        }

        // Run by command line??
        return "127.0.0.1";
    }
}


text:
Quickly serve a PHP project. Do you want a server:

- That is perfectly suited for your PHP project with a single index file that
  should receive all requests, except those for static resources.
- That quickly starts and stops when you request it.
- That runs in any directory right away.
- That handles multiple requests in parallel.
- That can have multiple instances running at the same time.

Then this is what you want. This is a quick python script that allows you to
run a server using nginx and php-fpm in any server. This script will create
some temporary configuration for nginx and php-fpm and then run these services
using these configuration files. When you're done developing you just press
`Ctrl + C` and the script stops the server and removes all temporary files,
leaving you with a nice and clean filesystem.

## Requirements
This script requires recent versions of `nginx` and `php-fpm`. By default the
script requires these commands to be available on the `PATH` for the user
you're executing the script under.

- **Windows**: I don't think this is going to work for you.
- **Mac OS**: You can use macports to get nginx and a more recent version
  of php-fpm. Note that macports installs php-fpm for php 5.4 as a binary
  with the name `php-fpm54`. The `php-fpm` you'll find installed is the one
  provided with Mac OS. Either edit the script, provide a command line
  parameter every time you're using the script or create a symlink that
  precedes the one Mac OS provides.
- **Linux**: nginx and php-fpm are available in most recent distributions their
  package managers. Just make sure nginx and php-fpm are available on the
  `PATH` and you should be good to go.

## Getting started
Want to get some help? USe `--help` on the script to see what options are
available. Some examples:

```sh
# Run the script in the current directory using app.php as the index
quickserve.py app.php

# Change the root folder to public and use index.php (default) as the index
quickserve.py -r ./public

# Determine the root and index by giving a path
quickserve.py -b ~/development/website/public/app.php

# Change the port and interface (only allow from localhost on port 1234)
quickserve.py -i 127.0.0.1 -p 1234

# Use a different php-fpm binary
quickserve.py --php-fpm-bin php-fpm54
```


text:
from IPython.core.magic import Magics, magics_class, cell_magic
import os, sys, importlib, argparse, tempfile

## Functions for loading the extension
def load_ipython_extension(ipython):
    ipython.register_magics(ModuleMagics)

@magics_class
class ModuleMagics(Magics):
    '''Magics for creating modules in IPython.'''

    def __init__(self, shell=None, namespace=None):
        if shell is None:
            shell = get_ipython()

        super(ModuleMagics, self).__init__(shell)

        self.namespace = namespace

        # Get the kernel id
        self.kernelID = os.path.basename(shell.kernel.config['IPKernelApp']['connection_file'])[:-5]

        # Create kernel-specific tmp-module directory
        self.module_dir = tempfile.mkdtemp(self.kernelID)
        os.makedirs(self.module_dir, exist_ok=True)

    def __del__(self):
        # Remove module_dir from file system and sys.path
        # I'm not sure this works - evidence so far says no...
        tmpfiles = os.listdir(self.module_dir)
        for file in tmpfiles:
            os.remove(os.path.join(self.module_dir, file))

        os.rmdir(self.module_dir)

        sys.path.remove(self.module_dir)

    @cell_magic
    def module(self, line, cell):
        '''Import the cell as a module.'''
        # Parse the parameters
        parser = argparse.ArgumentParser('%%module cell magic')
        parser.add_argument('name')
        parser.add_argument('-p','--path', default=self.module_dir)
        args = parser.parse_args(line.split())

        name = args.name

        # Save to file
        os.makedirs(args.path, exist_ok=True)
        filename = os.path.join(args.path, name + '.py')
        with open(filename, 'w') as f:
            f.write(cell)

        # Import module
        if args.path not in sys.path:
            sys.path.insert(0, args.path)

        if name in sys.modules:
            # Always reload
            del sys.modules[name]

        module = importlib.import_module(name)

        if self.namespace:
            self.namespace[name] = module
        else:
            self.shell.push({name: module})

        return module


text:
namespace Burrows.Util
{
    using System;
    using Exceptions;
    using Magnum;
    using Magnum.Extensions;

    /// <summary>
	///   Check class for verifying the condition of items included in interface contracts
	/// </summary>
	public static class CheckConvention
	{
		public static void EnsureSerializable(object message)
		{
			Guard.AgainstNull(message, "message cannot be null");

			Type t = message.GetType();
			if (!t.IsSerializable)
			{
				throw new ConventionException(
					"Whoa, slow down buddy. The message '{0}' must be marked with the 'Serializable' attribute!".FormatWith(t.FullName));
			}
		}
	}
}


text:
RSpec.describe Mediators::Notifications::ReadAll, "#call" do
  let(:mediator) { described_class.new(user: user) }
  let(:user) { Fabricate(:user) }

  it "marks all recent notification as read" do
    count = 6
    notifications = Fabricate.times(count, :notification, user: user, read_at: nil)
    result = mediator.call
    expect(result).to eq(count)

    notifications.each do |note|
      note.reload
      expect(note.read_at).to be_within(1.second).of(Time.now)
    end
  end

  it "only marks notifications read for the user passed in" do
    to_be_read = Fabricate(:notification, user: user, read_at: nil)
    another_user = Fabricate(:user)
    to_not_be_read = Fabricate(:notification, user: another_user, read_at: nil)
    result = mediator.call
    expect(result).to eq(1)

    to_be_read.reload
    expect(to_be_read.read_at).to be_within(1.second).of(Time.now)

    to_not_be_read.reload
    expect(to_not_be_read.read_at).to be_nil
  end

  it "ignores notifications that are no longer valid" do
    one_month_ago = Date.today << 1
    notification = Fabricate(:notification, user: user, created_at: one_month_ago)
    result = mediator.call
    expect(result).to_not be_nil
    notification.reload
    expect(notification.read_at).to be_nil
  end
end


text:
#ifndef _ADC_SPI_H
#define _ADC_SPI_H

//Setup for use with XYZ SPI ADC unit

void setup_adc_spi(void);
void step_adc_spi();

unsigned int get_avg_adc_spi(int chid);
unsigned int get_adc_spi(int chid);
unsigned int get_sum_adc_spi(int ch);

#define ADC_SPI_NUM_CH 1
#define ADC_SPI_NUM_SMOOTH	8 //Must be even
#define ADC_SPI_SHIFT_SMOOTH 3 //2^ADC_SHIFT_SMOOTH
//Define Bit-bang pins for XYZ SPI ADC unit

#define	BB_ASPI_SS				LATCbits.LATC2		//RB3	OUTPUT	PIN24	SPI_SS_ADC/
#define	BB_ASPI_CLK				LATCbits.LATC0		//RC1	OUTPUT	PIN26	SPI_CLK_ADC
#define BB_PIN_ASPI_DI			PORTBbits.RB5		//RB6	INPUT	PIN42	SPI_DI_ADC

#define BB_ASPI_SS_SET			BB_ASPI_SS=1;
#define BB_ASPI_SS_CLR			BB_ASPI_SS=0;
#define BB_ASPI_CLK_SET			BB_ASPI_CLK=1;
#define BB_ASPI_CLK_CLR			BB_ASPI_CLK=0;

////Unlike the Vert-X encoder, the MCP3201 outputs dat on the FALLING EDGDE of CLK. But the CLK should still be initialized at 0.
////The Bit-bang sequence below is "time optimized" and reads the sensor ADC value during the low level of CLK

//Max CLK is 0.8MHz (period of 1250NS, so half period of 625NS)
//Also, minimum 200NS between falling edge of CLK and valid output of the ADC sensor
//The specs below should respect those criterias
#define BB_ASPI_BIT_IN(x)	{				\
							BB_ASPI_CLK_SET\
							DELAY_700NS\
							BB_ASPI_CLK_CLR\
							DELAY_225NS\
							x=x|BB_PIN_ASPI_DI;	\
							DELAY_500NS\
							}

#endif


text:
var Lab = require('lab');
var Hapi = require('../..');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;

describe('Ext', function () {

    describe('#onRequest', function (done) {

        it('replies with custom response', function (done) {

            var server = new Hapi.Server();
            server.ext('onRequest', function (request, next) {

                return next(Hapi.error.badRequest('boom'));
            });

            server.route({ method: 'GET', path: '/', handler: function () { this.reply('ok'); } });

            server.inject({ method: 'GET', url: '/' }, function (res) {

                expect(res.result.message).to.equal('boom');
                done();
            });
        });
    });

    describe('#onPreResponse', function (done) {

        it('replies with custom response', function (done) {

            var server = new Hapi.Server();
            server.ext('onPreResponse', function (request, next) {

                return next(request.response().variety === 'text' ? Hapi.error.badRequest('boom') : null);
            });

            server.route({ method: 'GET', path: '/text', handler: function () { this.reply('ok'); } });
            server.route({ method: 'GET', path: '/obj', handler: function () { this.reply({ status: 'ok' }); } });

            server.inject({ method: 'GET', url: '/text' }, function (res) {

                expect(res.result.message).to.equal('boom');
                server.inject({ method: 'GET', url: '/obj' }, function (res) {

                    expect(res.result.status).to.equal('ok');
                    done();
                });
            });
        });
    });

    describe('#ext', function () {

        it('supports adding an array of ext methods', function (done) {

            var server = new Hapi.Server();
            server.ext('onPreHandler', [
                function (request, next) {

                    request.x = '1';
                    next();
                },
                function (request, next) {

                    request.x += '2';
                    next();
                }
            ]);

            server.route({ method: 'GET', path: '/', handler: function () { this.reply(this.x); } });

            server.inject({ method: 'GET', url: '/' }, function (res) {

                expect(res.result).to.equal('12');
                done();
            });
        });
    });
});


text:
<?php

include "../include/config.php";

function sendCsvHeaders($filename){
  sendDownloadHeaders("text/csv", $filename);
}

$editorid = loginbycookie();
if(!isAdmin($editorid))
	die("У вас недостаточно прав доступа, чтобы скачать CSV. ");

$hiddenFields =
  [ "pwhash"
  , "pw"
  , "active"
  , "activecode"
  , "added"
  , "is_admin"
  , "photo_src"
  , "updated"
  , "unread"
  , "quenta"
  ];

sendCsvHeaders(PROJECT_NAME . ".csv");

$out = fopen('php://output', 'w');

$sql = "SELECT *
	FROM ".PREF."users AS u
	ORDER BY u.id";
$result = query($sql);

while($row = fetch_assoc($result)){
  foreach($hiddenFields as $hiddenField){
    unset($row[$hiddenField]);
  }
	fputcsv($out, $row);
	}

fclose($out);

?>


text:
package org.jclouds.openstack.trove.v1.utils;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.jclouds.openstack.trove.v1.TroveApi;
import org.jclouds.openstack.trove.v1.domain.Instance;
import org.jclouds.openstack.trove.v1.features.InstanceApi;
import org.jclouds.openstack.trove.v1.predicates.InstancePredicates;
import org.jclouds.logging.Logger;

import com.google.common.util.concurrent.Uninterruptibles;

/**
 *
 * Helper methods for dealing with instances that get created with errors.
 */
public class TroveUtils {
   private final TroveApi api;
   @Resource
   protected Logger logger = Logger.NULL;

   public TroveUtils(TroveApi api) {
      this.api = api;
   }

   /**
    * Create an ACTIVE operational instance.
    *
    * @see InstanceApi#create(String, int, String)
    *
    * @param region
    *           The instance region.
    * @param name
    *           Instance name.
    * @param flavorId
    *           Id of the flavor to be used when creating the instance.
    * @param size
    *           Size of the instance.
    * @return Instance object in active state or NULL.
    */
   public Instance getWorkingInstance(String region, String name, String flavorId, int size) {
      InstanceApi instanceApi = api.getInstanceApi(region);
      for (int retries = 0; retries < 10; retries++) {
         Instance instance = null;
         try {
            instance = instanceApi.create(flavorId, size, name);
         } catch (Exception e) {

            Uninterruptibles.sleepUninterruptibly(15, TimeUnit.SECONDS);

            logger.error(Arrays.toString(e.getStackTrace()));
            continue;
         }

         Instance updatedInstance = awaitAvailable(instance, instanceApi);
         if (updatedInstance != null) {
            return updatedInstance;
         }
         instanceApi.delete(instance.getId());
         InstancePredicates.awaitDeleted(instanceApi).apply(instance);

      }
      return null;
   }

   /**
    * This will return a small working instance.
    *
    * @param region The region where the instance should be created.
    * @return A working database instance.
    */
   public Instance getWorkingInstance(String region) {
      return getWorkingInstance(region, UUID.randomUUID().toString(), "1", 1);
   }

   private Instance awaitAvailable(Instance instance, InstanceApi iapi) {
      for (int n = 0; n < 100; n = n + 1) {
         Instance updatedInstance = iapi.get(instance.getId());
         if (updatedInstance.getStatus() == Instance.Status.ACTIVE)
            return updatedInstance;
         if (updatedInstance.getStatus() == Instance.Status.UNRECOGNIZED)
            return null; // fast fail
         Uninterruptibles.sleepUninterruptibly(15, TimeUnit.SECONDS);
      }
      return null;
   }
}


text:
import main from '../main';

test('cli should provide main function', () => {
  expect(main).toBeDefined();
});


text:
namespace xig {
namespace stdlib {

class boolean_not : public method {
  int amount_of_arguments() const { return 1; }

  data_ptr run(call_info fci) {
    if (fci.args.at(0)->type() != data_type::boolean)
      throw error(error_type::invalid_arguments, "Not A Boolean", fci.debug);

    return make_boolean(!fci.args.at(0)->as_boolean());
  }
};

class boolean_and : public method {
  int amount_of_arguments() const { return 2; }
  bool has_repeating_arguments() const { return true; }

  data_ptr run(call_info fci) {
    auto inputs = utils::parse_arguments(fci.args, 2);
    if (!utils::all_types_are(inputs, data_type::boolean))
      throw error(error_type::invalid_arguments, "Not A Boolean", fci.debug);

    for (auto &i : inputs) {
      if (!i->as_boolean())
        return make_boolean(false);
    }
    return make_boolean(true);
  }
};

class boolean_or : public method {
  int amount_of_arguments() const { return 2; }
  bool has_repeating_arguments() const { return true; }

  data_ptr run(call_info fci) {
    auto inputs = utils::parse_arguments(fci.args, 2);
    if (!utils::all_types_are(inputs, data_type::boolean))
      throw error(error_type::invalid_arguments, "Not A Boolean", fci.debug);

    for (auto &i : inputs) {
      if (i->as_boolean())
        return make_boolean(true);
    }
    return make_boolean(false);
  }
};
}
}


text:
import sys
import datetime
import signal
import queue

def produce(config, queue):
    try:
        def graceful(signum, frame):
            raise Exception("caught {0} signal, exiting".format(signum))

        signal.signal(signal.SIGTERM, graceful)
        signal.signal(signal.SIGINT, graceful)
        signal.signal(signal.SIGQUIT, graceful)

        droppedcount = 0
        firstdropped = None
        while True:
            # read the line
            line = sys.stdin.readline()
            if not line:
                # EOF
                break
            # strip trailing newline
            line = line.rstrip()

            if config.stdout:
                print(line)

            # toss it in the queue
            try:
                queue.put([datetime.datetime.utcnow().isoformat('T') + 'Z', line], config.block)
            except Queue.Full:
                if not firstdropped:
                    firstdropped = datetime.datetime.utcnow().isoformat('T') + 'Z'
                droppedcount += 1

            if droppedcount:
                try:
                    queue.put_nowait([
                        datetime.datetime.utcnow().isoformat('T') + 'Z',
                        "dropped {0} messages starting at {1} due to full queue".format(droppedcount, firstdropped)
                        ],
                    )
                    droppedcount = 0
                    firstdropped = 0
                except Queue.Full:
                    # queue still full. keep going
                    pass

    except Exception as e:
        # FIXME: handle this properly. maybe by putting a message in the queue
        # if there's an uncaught exception besides an interrupt?
        pass

    queue.put(None)


text:
{% extends "_layouts/cp" %}

{% import "_includes/forms" as forms %}

{% includeCssResource 'cpnav/css/CPNav.css' %}
{% includeJsResource 'cpnav/js/CPNav.js' %}

{% set title = 'Control Panel Nav' %}

{% set tabs = {
    navigation: { label: "Navigation" | t, url: url('cpnav') },
} %}

{% if craft.app.getEditionName() != 'Personal' %}
    {% set tabs = tabs | merge({ layouts: { label: "Layouts" | t, url: url('cpnav/layouts') } }) %}
{% endif %}


text:
Assets = {
  attachEvents: function() {
    $('a.attach_asset').off('click').click(function(e){
      e.preventDefault();
      var link = $(this);
      var container = link.parents('li.asset');
      var title = link.parents('div.title').html();
      var image = link.parents('img');
      container.addClass('waiting');
      $.ajax({
        url: link.attr('href'),
        success: function(data, textStatus, jqXHR) {
          container.removeClass('waiting');
          Assets.addToList(data);
        }
      });
    });

    $('a.detach_asset').off('click').click(function(e){
      e.preventDefault();
      var link = $(this);
      Assets.removeFromList(link.parents('li.asset'));
    });

    $('a.insert_asset').off('click').click(function(e){
      e.preventDefault();
      var part_name = $("a.tab.here").children('span').html();
      if (part_name.indexOf(' ')) part_name = part_name.replace(' ', '-').toLowerCase();
      part_name = part_name.replace('_', '-');
      var part_id = 'part_' + part_name + '_content';
      var tag_parts = $(this).attr('rel').split('_');
      var tag_name = tag_parts[0];
      var asset_size = tag_parts[1];
      var asset_id = tag_parts[2];
      var radius_tag = '<r:asset:' + tag_name;
      if (asset_size != '') radius_tag = radius_tag + ' size="' + asset_size + '"';
      radius_tag =  radius_tag +' id="' + asset_id + '" />';
      Assets.insertAtCursor(part_id, radius_tag);

    });

    $(".pagination a").off('click').click(function(e){
      e.preventDefault();
      $.ajax({
        method: 'get',
        url: $(this).attr('href') + Assets.assetFilterParameters(),
        complete: function(data, textStatus, jqXHR) {
          Assets.updateTable(data.responseText);
          Assets.attachEvents();
        }
      });
    });

  },

  assetFilterParameters: function() {
    var parameters = [];
    if ($('#filesearchforminput').val() !== '') {
      parameters.push(['search', $('#filesearchforminput').val()]);
    }

    if ($('#page_id').val() !== undefined) {
      parameters.push(['page_id', $('#page_id').val()]);
    }

    var filters = [];
    var url_params = "";
    $('a.selective.pressed').each(function(){
      filters.push($(this).attr('rel'));
    });

    if (filters.length > 0) {parameters.push(['filter', filters.toString()])}

    for(var i = 0; i < parameters.length; i++) {
      if (i > 0) {url_params = url_params + '&'}
      url_params = url_params + parameters[i][0] + '=' + parameters[i][1];
    }
    return url_params + '&pp=20';
  },

  activateUpload: function(){
    $('#upload-controls').hide();
    $('#update-controls').show();
    $('#asset_title').prop( "disabled", false );
    $('#new_asset input[name="commit"]').prop( "disabled", false );
  },
  activateUpdate: function() {
    $('#upload-controls').show();
    $('#update-controls').hide();
    $('#asset_title').prop( "disabled", true );
    $('#new_asset input[name="commit"]').prop( "disabled", true );
  },

  insertAtCursor: function(part_id, insertion) {
    if (CKEDITOR.instances[part_id].mode == 'wysiwyg') {
      CKEDITOR.instances[part_id].insertText( insertion );
    } else {
      var textbox = $("textarea.cke_source[title~=" + part_id +"]");
      var caretPos = textbox[0].selectionStart;
      var textAreaTxt = textbox.val();
      textbox.val(textAreaTxt.substring(0, caretPos) + insertion + textAreaTxt.substring(caretPos) );
    }
  },
  filterAssets: function() {
    var url = $("#filesearchform").attr('action');
    var parameters = Assets.assetFilterParameters();

    url = url + "?" + parameters;
    $.ajax({
      url: url,
      complete: function(data, textStatus, jqXHR) {
        Assets.updateTable(data.responseText);
      }
    });
  },
  updateTable: function(html) {
    $("#assets_table").html(html);
    Assets.attachEvents();
  },
  addToList: function(html){
    var list = $('#attachment_fields');
    list.append(html);
    Assets.showListIfHidden();
    Assets.notify('Save page to commit changes');
    Assets.attachEvents();
    // I'm not sure what Sortable does and can't find any example of
    // its use in current Trusty, so I'm going to comment it out for now.

    //Assets.makeSortable(list);

  },
  removeFromList: function(container) {
    container.children('input.attacher').remove();
    container.children('input.pos').remove();
    container.children('input.destroyer').val(1);
    container.fadeOut();
    container.addClass('detached');
  },
  showListIfHidden: function() {
    var list = $('#attachment_fields');
    if (list.hasClass('empty')) {
      list.removeClass('empty');
    }
  },
  notify: function(message){
    $('#attachment_list span.message').html(message).addClass('important');
  }

};

$(function() {

  $('a.selective').click(function(e){
    e.preventDefault();
    var element = $(this);
    var type_id = element.attr('rel');
    var type_check = $('#' + type_id + '-check');

    if(element.hasClass('pressed')) {
      element.removeClass('pressed');
      $(type_check).prop('checked', false);
      if ($('a.selective.pressed').length == 0) $('#select_all').addClass('pressed');
    }
    else {
      element.addClass('pressed');
      $('a.deselective').each(function() { $(this).removeClass('pressed'); });
      $(type_check).prop('checked', true);
    }
    Assets.filterAssets();
    Assets.attachEvents();

  });

  $('a.deselective').click(function(e){
    e.preventDefault();
    var element = $(this);
    if(!element.hasClass('pressed')) {
      $('a.selective').each(function() { $(this).removeClass('pressed'); });
      $('input.selective').each(function() { $(this).prop('checked', false); });
      element.addClass('pressed');
      Assets.filterAssets();
      Assets.attachEvents();
    }
  });

  $('#filesearchforminput').keyup(function(){
    Assets.filterAssets();
    Assets.attachEvents();
  });

  $("#attach_assets").click(function(e) {
    e.preventDefault();
    Popup.show('attach_asset');
    $('.close_popup').click(function(e){
      e.preventDefault();
      Popup.close();
      $('#attach_asset').hide();
    });
  });

  $('#filesearchforminput').keyup(function(){
    Assets.filterAssets();
  });

  $("#upload_asset_link").click(function(e) {
    e.preventDefault();
    Popup.close();
    $('#attach_asset').hide();
    Assets.activateUpdate();
    Popup.show('upload_asset');

    $("#attach-popup").click(function(e) {
      e.preventDefault();
      Popup.close();
      $('#upload_asset').hide();
      Popup.show('attach_asset');
      $('.close_popup').click(function(e){
        e.preventDefault();
        Popup.close();
        $('#attach_asset').hide();
      });
    });

  $('.close_popup').click(function(e){
    e.preventDefault();
    Popup.close();
    $('#upload_asset').hide();
    });
  });

  $('#update_asset').submit(function(e){
    e.preventDefault();
    $("#update-asset").attr("disabled", true);
    $('#update-status').show();
    $.ajax({
      method: 'put',
      url: $(this).attr('action') + $("#asset_id").val(),
      data: $(this).serialize(),
      complete: function(data, textStatus, jqXHR) {
        Popup.close();
        $('#upload_asset').hide();
        $('#update-status').hide();
        $("#update-asset").attr("disabled", false);
        $('#update_asset').trigger("reset");
      }
    });
  });

  $('#asset_asset').fileupload({
    add: function(e, data) {
      $("#asset_asset").attr("disabled", true);
      $('#upload-status').show();
      data.submit();
    },
    done: function (e, data) {
      $("#asset_id").val($(data.result).find(".attacher").val());
      Assets.addToList($(data.result));
      Assets.activateUpload();
      $("#asset_asset").attr("disabled", false);
      $('#upload-status').hide();
      $("#popup_window").hide();
    }
  });

  Assets.attachEvents();

});


text:
#ifndef MediaPlayerProxy_h
#define MediaPlayerProxy_h

#if ENABLE(VIDEO)

#include <wtf/Forward.h>
#include "ScriptInstance.h"

namespace WebCore {

    class IntRect;
    class IntSize;
    class MediaPlayer;
    class PluginView;
    class HTMLMediaElement;

    enum MediaPlayerProxyNotificationType {
        MediaPlayerNotificationPlayPauseButtonPressed,
        Idle,
        Loading,
        Loaded,
        FormatError,
        NetworkError,
        DecodeError
    };

    class WebMediaPlayerProxy {
    public:
        WebMediaPlayerProxy(MediaPlayer* player);
        ~WebMediaPlayerProxy();

        MediaPlayer* mediaPlayer() {return m_mediaPlayer;}
        void initEngine();
        void load(const String& url);
        HTMLMediaElement* element();
        void invokeMethod(const String& methodName);
        ScriptInstance pluginInstance();

    private:
        MediaPlayer* m_mediaPlayer;
        bool m_init;
        WebCore::PluginView* m_pluginView;
        bool m_hasSentResponseToPlugin;
        ScriptInstance m_instance;
    };

}
#endif // ENABLE(VIDEO)

#endif