text:
package com.linecorp.armeria.internal.common.thrift;

import static java.util.Objects.requireNonNull;

import java.lang.reflect.Constructor;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

import org.apache.thrift.AsyncProcessFunction;
import org.apache.thrift.ProcessFunction;
import org.apache.thrift.TBaseAsyncProcessor;
import org.apache.thrift.TBaseProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import com.linecorp.armeria.internal.common.util.Types;

/**
 * Provides the metadata of a Thrift service interface or implementation.
 */
public final class ThriftServiceMetadata {

    private static final Logger logger = LoggerFactory.getLogger(ThriftServiceMetadata.class);

    private final Set<Class<?>> interfaces;

    /**
     * A map whose key is a method name and whose value is {@link AsyncProcessFunction} or
     * {@link ProcessFunction}.
     */
    private final Map<String, ThriftFunction> functions = new HashMap<>();

    /**
     * Creates a new instance from a Thrift service implementation that implements one or more Thrift service
     * interfaces.
     */
    public ThriftServiceMetadata(Object implementation) {
        this(ImmutableList.of(requireNonNull(implementation, "implementation")));
    }

    /**
     * Creates a new instance from a list of Thrift service implementations, while each service can implement
     * one or more Thrift service interfaces.
     */
    public ThriftServiceMetadata(Iterable<?> implementations) {
        requireNonNull(implementations, "implementations");

        final ImmutableSet.Builder<Class<?>> interfaceBuilder = ImmutableSet.builder();
        implementations.forEach(implementation -> {
            requireNonNull(implementation, "implementations contains null.");
            interfaceBuilder.addAll(init(implementation));
        });
        interfaces = interfaceBuilder.build();
    }

    /**
     * Creates a new instance from a single Thrift service interface.
     */
    public ThriftServiceMetadata(Class<?> serviceType) {
        requireNonNull(serviceType, "serviceType");
        interfaces = init(null, Collections.singleton(serviceType));
    }

    private Set<Class<?>> init(Object implementation) {
        return init(implementation, Types.getAllInterfaces(implementation.getClass()));
    }

    private Set<Class<?>> init(@Nullable Object implementation, Iterable<Class<?>> candidateInterfaces) {

        // Build the map of method names and their corresponding process functions.
        // If a method is defined multiple times, we take the first definition
        final Set<Class<?>> interfaces = new HashSet<>();

        for (Class<?> iface : candidateInterfaces) {
            final Map<String, AsyncProcessFunction<?, ?, ?>> asyncProcessMap;
            asyncProcessMap = getThriftAsyncProcessMap(implementation, iface);
            if (asyncProcessMap != null) {
                asyncProcessMap.forEach(
                        (name, func) -> registerFunction(iface, name, func, implementation));
                interfaces.add(iface);
            }

            final Map<String, ProcessFunction<?, ?>> processMap;
            processMap = getThriftProcessMap(implementation, iface);
            if (processMap != null) {
                processMap.forEach(
                        (name, func) -> registerFunction(iface, name, func, implementation));
                interfaces.add(iface);
            }
        }

        if (functions.isEmpty()) {
            if (implementation != null) {
                throw new IllegalArgumentException('\'' + implementation.getClass().getName() +
                                                   "' is not a Thrift service implementation.");
            } else {
                throw new IllegalArgumentException("not a Thrift service interface: " + candidateInterfaces);
            }
        }

        return Collections.unmodifiableSet(interfaces);
    }

    @Nullable
    private static Map<String, ProcessFunction<?, ?>> getThriftProcessMap(@Nullable Object service,
                                                                          Class<?> iface) {
        final String name = iface.getName();
        if (!name.endsWith("$Iface")) {
            return null;
        }

        final String processorName = name.substring(0, name.length() - 5) + "Processor";
        try {
            final Class<?> processorClass = Class.forName(processorName, false, iface.getClassLoader());
            if (!TBaseProcessor.class.isAssignableFrom(processorClass)) {
                return null;
            }

            final Constructor<?> processorConstructor = processorClass.getConstructor(iface);

            @SuppressWarnings("rawtypes")
            final TBaseProcessor processor = (TBaseProcessor) processorConstructor.newInstance(service);

            @SuppressWarnings("unchecked")
            final Map<String, ProcessFunction<?, ?>> processMap =
                    (Map<String, ProcessFunction<?, ?>>) processor.getProcessMapView();

            return processMap;
        } catch (Exception e) {
            logger.debug("Failed to retrieve the process map from: {}", iface, e);
            return null;
        }
    }

    @Nullable
    private static Map<String, AsyncProcessFunction<?, ?, ?>> getThriftAsyncProcessMap(
            @Nullable Object service, Class<?> iface) {

        final String name = iface.getName();
        if (!name.endsWith("$AsyncIface")) {
            return null;
        }

        final String processorName = name.substring(0, name.length() - 10) + "AsyncProcessor";
        try {
            final Class<?> processorClass = Class.forName(processorName, false, iface.getClassLoader());
            if (!TBaseAsyncProcessor.class.isAssignableFrom(processorClass)) {
                return null;
            }

            final Constructor<?> processorConstructor = processorClass.getConstructor(iface);

            @SuppressWarnings("rawtypes")
            final TBaseAsyncProcessor processor =
                    (TBaseAsyncProcessor) processorConstructor.newInstance(service);

            @SuppressWarnings("unchecked")
            final Map<String, AsyncProcessFunction<?, ?, ?>> processMap =
                    (Map<String, AsyncProcessFunction<?, ?, ?>>) processor.getProcessMapView();

            return processMap;
        } catch (Exception e) {
            logger.debug("Failed to retrieve the asynchronous process map from:: {}", iface, e);
            return null;
        }
    }

    @SuppressWarnings("rawtypes")
    private void registerFunction(Class<?> iface, String name,
                                  Object func, @Nullable Object implementation) {
        if (functions.containsKey(name)) {
            logger.warn("duplicate Thrift method name: " + name);
            return;
        }

        try {
            final ThriftFunction f;
            if (func instanceof ProcessFunction) {
                f = new ThriftFunction(iface, (ProcessFunction) func, implementation);
            } else {
                f = new ThriftFunction(iface, (AsyncProcessFunction) func, implementation);
            }
            functions.put(name, f);
        } catch (Exception e) {
            throw new IllegalArgumentException("failed to retrieve function metadata: " +
                                               iface.getName() + '.' + name + "()", e);
        }
    }

    /**
     * Returns the Thrift service interfaces implemented.
     */
    public Set<Class<?>> interfaces() {
        return interfaces;
    }

    /**
     * Returns the {@link ThriftFunction} that provides the metadata of the specified Thrift function.
     *
     * @return the {@link ThriftFunction}, or {@code null} if there's no such function.
     */
    @Nullable
    public ThriftFunction function(String method) {
        return functions.get(method);
    }
}


text:
layout: post
title: "OpenBSD 5.5 BGP Looking Glass"
date: 2014-05-14 21:51:51 -0500
comments: false
categories:
- Networking
- IPv6
- ISP
- BGP
- Nerd Projects
- Network Monitoring
- System Administration
---
I've written about OpenBSD and BGP Looking Glasses [before](/2013/01/27/building-an-openbsd-bgp-looking-glass/). OpenBSD has since [removed apache from base](http://undeadly.org/cgi?action=article&sid=20140314080734&mode=flat), and replaced it with nginx. This is OK with me since I prefer the simplicity and raw performance of nginx (and its ability to proxy!). This is an update which applies to OpenBSD after nginx removal (applies to 5.5 and later). This article has also been independently verified to work using OpenBSD 5.6 as well.

Install your system as you choose, I did a fairly default [install as per the FAQ](http://www.openbsd.org/faq/faq4.html). My hardware in this case is virtual VMware hardware, 1 vCPU, 1GB vRAM, 16GB vHDD, and 1 vNIC connected to a network shared between both BGP routers.

The applicable configuration files:

{% highlight config %}
ntpd_flags=             # enabled during install
slowcgi_flags=
nginx_flags=
bgpd_flags=
{% endhighlight %}

`/etc/nginx/nginx.conf`

Uncomment this section:

{% highlight nginx %}
        # FastCGI to CGI wrapper server
        #
        location /cgi-bin/ {
            fastcgi_pass   unix:run/slowcgi.sock;
            fastcgi_split_path_info ^(/cgi-bin/[^/]+)(.*);
            fastcgi_param  PATH_INFO $fastcgi_path_info;
            include        fastcgi_params;
        }
{% endhighlight %}

and add the following if you want to serve the CGI as the index:

{% highlight nginx %}
        location / {
                index index.html;
                try_files $uri /cgi-bin/bgplg;
        }
{% endhighlight %}

`/etc/fstab`

`/var` will need to be mounted without the nosuid option present by default.

The following will need to be run to allow ping, ping6, traceroute, and traceroute6 to function and resolve domains in the chroot:

{% highlight bash %}
chmod 0555 /var/www/cgi-bin/bgplg
chmod 0555 /var/www/bin/bgpctl
mkdir /var/www/etc
cp /etc/resolv.conf /var/www/etc
chmod 4555 /var/www/bin/ping
chmod 4555 /var/www/bin/ping6
chmod 4555 /var/www/bin/traceroute
chmod 4555 /var/www/bin/traceroute6
{% endhighlight %}

The last stage is to configure your BGP peering sessions in `/etc/bgpd.conf`

{% highlight config %}
# global configuration
AS 65003
router-id x.x.x.195
fib-update no

# restricted socket for bgplg(8)
socket "/var/www/run/bgpd.rsock" restricted

neighbor 192.0.2.193 {
        remote-as       65003
        descr           BGP1
        announce none
}

neighbor 192.0.2.194 {
        remote-as       65003
        descr           BGP2
        announce none
}

neighbor 2001:DB8::193 {
        remote-as       65003
        descr           BGP1-v6
        announce none
}

neighbor 2001:DB8::194 {
        remote-as       65003
        descr           BGP2-v6
        announce none
}

# see all prefixes, since we want the visibility for a looking glass
allow from any
{% endhighlight %}

redpajama_set_name: RedPajamaGithub


text:
<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

?>

						<input id="select_all" type="checkbox" name='check_all'>

			<?php echo lang('order'); ?>
			<?php echo lang('currencies_name'); ?>
			<?php echo lang('currencies_code'); ?>
			<?php echo lang('currencies_symbol'); ?>
			<?php echo lang('id'); ?>
			<?php echo lang('published'); ?>
			<?php echo lang('action'); ?>

		<?php $number = 0; ?>
		<?php if ($currencies) foreach ($currencies as $currencie) { ?>
				<?php $number++; ?>

								<input type="checkbox" name="checkb[]" class="checkb" name="check" value="<?php echo $currencie->currency_id; ?>">

					<?php echo $number; ?>
					<?php echo $currencie->currency_name; ?>
					<?php echo $currencie->currency_code; ?>
					<?php echo $currencie->currency_symbol; ?>
					<?php echo $currencie->currency_id; ?>
					<?php if ($currencie->published == 1) { ?>
							<a class="btn btn-success btn-xs tooltips action" type="button" data-original-title="<?php echo lang('click_publish');?>" data-placement="top" rel="unpublish" data-id="<?php echo $currencie->currency_id; ?>" data-flag="1"><?php echo lang('publish'); ?>
						<?php } else { ?>
							<a class="btn btn-danger btn-xs tooltips action" type="button" data-original-title="<?php echo lang('click_publish');?>" data-placement="top" rel="publish" data-id="<?php echo $currencie->currency_id; ?>" data-flag="0"><?php echo lang('unpublish'); ?>
						<?php } ?>

							<a href="javascript:;" rel="edit" class="btn btn-teal tooltips" data-placement="top" data-original-title="<?php echo lang('edit');?>" onclick="UIModals.init('<?php echo site_url(); ?>admin/settings/edit/currencies/<?php echo $currencie->currency_id; ?>')">

							<a rel="del" class="remove btn btn-bricky tooltips action" data-placement="top" data-original-title="<?php echo lang('remove');?>" href="javascript:;" data-id="<?php echo $currencie->currency_id; ?>">

			<?php } ?>

		<?php echo $links;?>


text:
import {
	GraphQLBoolean,
	GraphQLSchema,
	GraphQLID,
	GraphQLInt,
	GraphQLList,
	GraphQLNonNull,
	GraphQLObjectType,
	GraphQLString,
	GraphQLEnumType,
} from 'graphql';

var keystoneTypes = require('./keystoneTypes');

var keystone = require('keystone');
var Gig = keystone.list('Gig');
var Artist = keystone.list('Artist');
var User = keystone.list('User');
var RSVP = keystone.list('RSVP');
var Venue = keystone.list('Venue');

function getGig (id) {
	if (id === 'next') {
		return Gig.model.findOne().sort('-startDate')
			.where('state', 'active').exec();
	} else if (id === 'last') {
		return Gig.model.findOne().sort('-startDate')
			.where('state', 'past').exec();
	} else {
		return Gig.model.findById(id).exec();
	}
}

var gigStateEnum = new GraphQLEnumType({
	name: 'GigState',
	description: 'The state of the gig',
	values: {
		draft: { description: "No published date, it's a draft gig" },
		scheduled: { description: "Publish date is before today, it's a scheduled gig" },
		active: { description: "Publish date is after today, it's an active gig" },
		past: { description: "Gig date plus one day is after today, it's a past gig" },
	},
});

var gigType = new GraphQLObjectType({
	name: 'Gig',
	fields: () => ({
		id: { type: new GraphQLNonNull(GraphQLID) },
		name: {
			type: new GraphQLNonNull(GraphQLString),
			description: 'The name of the gig.',
		},
		publishedDate: keystoneTypes.date(Gig.fields.publishedDate),
		state: { type: new GraphQLNonNull(gigStateEnum) },
		startDate: keystoneTypes.datetime(Gig.fields.startDate),
		endDate: keystoneTypes.datetime(Gig.fields.endDate),
		place: { type: GraphQLString },
		map: { type: GraphQLString },
		description: { type: GraphQLString },
		maxRSVPs: { type: new GraphQLNonNull(GraphQLInt) },
		totalRSVPs: { type: new GraphQLNonNull(GraphQLInt) },
		url: { type: GraphQLString },
		remainingRSVPs: { type: new GraphQLNonNull(GraphQLInt) },
		rsvpsAvailable: { type: new GraphQLNonNull(GraphQLBoolean) },
		artists: {
			type: new GraphQLList(artistType),
			resolve: (source, args) =>
				Artist.model.find().where('gig', source.id).exec(),
		},
		rsvps: {
			type: new GraphQLList(rsvpType),
			resolve: (source, args) =>
				RSVP.model.find().where('gig', source.id).exec(),
		},
	}),
});

var artistType = new GraphQLObjectType({
	name: 'Artist',
	fields: () => ({
		id: { type: new GraphQLNonNull(GraphQLID) },
		name: {
			type: new GraphQLNonNull(GraphQLString),
			description: 'The title of the artist.',
		},
		isLightningArtist: {
			type: GraphQLBoolean,
			description: 'Whether the artist is a Lightning artist',
		},
		gig: {
			type: gigType,
			description: 'The Gig the artist is scheduled for',
			resolve: (source, args, info) =>
				Gig.model.findById(source.gig).exec(),
		},
		who: {
			type: new GraphQLList(userType),
			description: 'A list of at least one User running the artist',
			resolve: (source, args, info) =>
				User.model.find().where('_id').in(source.who).exec(),
		},
		description: { type: GraphQLString },
		slides: {
			type: keystoneTypes.link,
			resolve: (source) => ({
				raw: source.slides,
				format: source._.slides.format,
			}),
		},
		link: {
			type: keystoneTypes.link,
			resolve: (source) => ({
				raw: source.link,
				format: source._.link.format,
			}),
		},
	}),
});

var userType = new GraphQLObjectType({
	name: 'User',
	fields: () => ({
		id: { type: new GraphQLNonNull(GraphQLID) },
		name: { type: new GraphQLNonNull(keystoneTypes.name) },
		// email: {
		// 	type: keystoneTypes.email,
		// 	resolve: (source) => ({
		// 		email: source.email,
		// 		gravatarUrl: source._.email.gravatarUrl,
		// 	}),
		// },
		artists: {
			type: new GraphQLList(artistType),
			resolve: (source, args) =>
				Artist.model.find().where('who', source.id).exec(),
		},
		rsvps: {
			type: new GraphQLList(rsvpType),
			resolve: (source, args) =>
				RSVP.model.find().where('who', source.id).exec(),
		},
	}),
});

var rsvpType = new GraphQLObjectType({
	name: 'RSVP',
	fields: {
		id: { type: new GraphQLNonNull(GraphQLID) },
		gig: {
			type: gigType,
			resolve: (source) => Gig.model.findById(source.gig).exec(),
		},
		who: {
			type: userType,
			resolve: (source) => User.model.findById(source.who).exec(),
		},
		attending: { type: GraphQLBoolean },
		createdAt: keystoneTypes.datetime(Gig.fields.createdAt),
		changedAt: keystoneTypes.datetime(Gig.fields.changedAt),
	},
});

var venueType = new GraphQLObjectType({
	name: 'Venue',
	fields: () => ({
		id: { type: new GraphQLNonNull(GraphQLID) },
		name: { type: GraphQLString },
		logo: { type: keystoneTypes.cloudinaryImage },
		website: { type: GraphQLString },
		isHiring: { type: GraphQLBoolean },
		description: { type: keystoneTypes.markdown },
		location: { type: keystoneTypes.location },
		members: {
			type: new GraphQLList(userType),
			resolve: (source, args) =>
				User.model.find().where('venue', source.id).exec(),
		},
	}),
});

var queryRootType = new GraphQLObjectType({
	name: 'Query',
	fields: {
		gigs: {
			type: new GraphQLList(gigType),
			resolve: (_, args) =>
				Gig.model.find().exec(),
		},
		gig: {
			type: gigType,
			args: {
				id: {
					description: 'id of the gig, can be "next" or "last"',
					type: new GraphQLNonNull(GraphQLID),
				},
			},
			resolve: (_, args) => getGig(args.id),
		},
		artists: {
			type: new GraphQLList(artistType),
			resolve: (_, args) =>
				Artist.model.find().exec(),
		},
		artist: {
			type: artistType,
			args: {
				id: {
					description: 'id of the artist',
					type: new GraphQLNonNull(GraphQLID),
				},
			},
			resolve: (_, args) => Artist.model.findById(args.id).exec(),
		},
		venue: {
			type: venueType,
			args: {
				id: {
					description: 'id of the venue',
					type: new GraphQLNonNull(GraphQLID),
				},
			},
			resolve: (_, args) => Venue.model.findById(args.id).exec(),
		},
		users: {
			type: new GraphQLList(userType),
			resolve: (_, args) =>
				User.model.find().exec(),
		},
		user: {
			type: userType,
			args: {
				id: {
					description: 'id of the user',
					type: new GraphQLNonNull(GraphQLID),
				},
			},
			resolve: (_, args) => User.model.findById(args.id).exec(),
		},
		rsvp: {
			type: rsvpType,
			args: {
				id: {
					description: 'id of the RSVP',
					type: new GraphQLNonNull(GraphQLID),
				},
			},
			resolve: (_, args) => RSVP.model.findById(args.id).exec(),
		},
	},
});

export default new GraphQLSchema({
	query: queryRootType,
});


text: In JavaScript, `document.activeElement` gives you the active element. How did I never know this?


text:
package org.apache.james.jspf.core;

import java.util.List;

public class IResponseImpl implements IResponse {
    private Exception exception = null;
    private List value = null;
    private Object id = null;

    public IResponseImpl(Object id, Exception e) {
        this.exception = e;
        this.id = id;
    }

    public IResponseImpl(Object id, List result) {
        this.value = result;
        this.id = id;
    }

    /**
     * @see org.apache.james.jspf.core.IResponse#getException()
     */
    public Exception getException() {
        return exception;
    }

    /**
     * @see org.apache.james.jspf.core.IResponse#getId()
     */
    public Object getId() {
        return id;
    }

    /**
     * @see org.apache.james.jspf.core.IResponse#getValue()
     */
    public Object getValue() {
        return value;
    }
}


text:
  Longevelle-sur-Doubs est
       un village
       géographiquement positionné dans le département des Doubs en Franche-Comté. Elle comptait 628 habitants en 2008.

À Longevelle-sur-Doubs, le prix moyen à l'achat d'un appartement se situe à 750 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 747 € du m². À la location la valorisation moyenne se situe à 5,13 € du m² par mois.

La ville offre quelques  aménagements, elle propose entre autres un terrain de tennis et un terrain de sport.

Si vous pensez emmenager à Longevelle-sur-Doubs, vous pourrez facilement trouver une maison à acheter.

Le parc d'habitations, à Longevelle-sur-Doubs, se décomposait en 2011 en 26 appartements et 256 maisons soit
 un marché plutôt équilibré.

À coté de Longevelle-sur-Doubs sont localisées les villes de
Beutal à 2 km, 249 habitants,
Bretigney à 3 km, 74 habitants,
Saint-Maurice-Colombier à 1 km, 849 habitants,
Blussans située à 4 km, 185 habitants,
Lougres localisée à 3 km, 738 habitants,
Colombier-Fontaine localisée à 2 km, 1 422 habitants,
 entre autres. De plus, Longevelle-sur-Doubs est située à seulement 26 km de Belfort.


text:
import core.modules.module_registry
from core.modules.vistrails_module import Module, ModuleError

###############################################################################
# PythonCalc
#
# A VisTrails package is simply a Python class that subclasses from
# Module.  For this class to be executable, it must define a method
# compute(self) that will perform the appropriate computations and set
# the results.
#
# Extra helper methods can be defined, as usual. In this case, we're
# using a helper method op(self, v1, v2) that performs the right
# operations.

class PythonCalc(Module):
    """PythonCalc is a module that performs simple arithmetic operations
on its inputs."""

    # This constructor is strictly unnecessary. However, some modules
    # might want to initialize per-object data. When implementing your
    # own constructor, remember that it must not take any extra
    # parameters.
    def __init__(self):
        Module.__init__(self)

    # This is the method you should implement in every module that
    # will be executed directly. VisTrails does not use the return
    # value of this method.
    def compute(self):
        # getInputFromPort is a method defined in Module that returns
        # the value stored at an input port. If there's no value
        # stored on the port, the method will return None.
        v1 = self.getInputFromPort("value1")
        v2 = self.getInputFromPort("value2")

        # You should call setResult to store the appropriate results
        # on the ports.  In this case, we are only storing a
        # floating-point result, so we can use the number types
        # directly. For more complicated data, you should
        # return an instance of a VisTrails Module. This will be made
        # clear in further examples that use these more complicated data.
        self.setResult("value", self.op(v1, v2))

        if self.hasInputFromPort("mat1"):
            m1 = self.getInputFromPort("mat1")
            m2 = self.getInputFromPort("mat2")
            self.setResult("mat_value", self.mat_op(v1, v2))

    def mat_op(self, v1, v2):
        reg = core.modules_module_registry.get_module_registry()
        Matrix = reg.get_descriptor_by_name(identifier, 'Matrix').module
        result = Matrix()
        matr
        op = self.getInputFromPort("op")

    def op(self, v1, v2):
        op = self.getInputFromPort("op")
        if op == '+':
            return v1 + v2
        elif op == '-':
            return v1 - v2
        elif op == '*':
            return v1 * v2
        elif op == '/':
            return v1 / v2
        # If a module wants to report an error to VisTrails, it should raise
        # ModuleError with a descriptive error. This allows the interpreter
        # to capture the error and report it to the caller of the evaluation
        # function.
        raise ModuleError(self, "unrecognized operation: '%s'" % op)

###############################################################################
# the function initialize is called for each package, after all
# packages have been loaded. It is used to register the module with
# the VisTrails runtime.

def initialize(*args, **keywords):

    # We'll first create a local alias for the module_registry so that
    # we can refer to it in a shorter way.
    reg = core.modules.module_registry.get_module_registry()

    # VisTrails cannot currently automatically detect your derived
    # classes, and the ports that they support as input and
    # output. Because of this, you as a module developer need to let
    # VisTrails know that you created a new module. This is done by calling
    # function addModule:
    reg.add_module(PythonCalc)

    # In a similar way, you need to report the ports the module wants
    # to make available. This is done by calling addInputPort and
    # addOutputPort appropriately. These calls only show how to set up
    # one-parameter ports. We'll see in later tutorials how to set up
    # multiple-parameter plots.
    reg.add_input_port(PythonCalc, "value1",
                     (core.modules.basic_modules.Float, 'the first argument'))
    reg.add_input_port(PythonCalc, "value2",
                     (core.modules.basic_modules.Float, 'the second argument'))
    reg.add_input_port(PythonCalc, "op",
                     (core.modules.basic_modules.String, 'the operation'))
    reg.add_output_port(PythonCalc, "value",
                      (core.modules.basic_modules.Float, 'the result'))


text:
/* Test stores performed in the kernel.
 *
 * This test uses both the cache and DMA to access input data.
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "aladdin_sys_connection.h"
#include "aladdin_sys_constants.h"

#ifdef DMA_MODE
#include "gem5/dma_interface.h"
#endif

#define TYPE int
#define CACHELINE_SIZE 64

int test_stores(TYPE* store_vals, TYPE* store_loc, int num_vals) {
  int num_failures = 0;
  for (int i = 0; i < num_vals; i++) {
    if (store_loc[i] != store_vals[i]) {
      fprintf(stdout, "FAILED: store_loc[%d] = %d, should be %d\n",
                               i, store_loc[i], store_vals[i]);
      num_failures++;
    }
  }
  return num_failures;
}

// Read values from store_vals and copy them into store_loc.
void store_kernel(TYPE* store_vals, TYPE* store_loc, int num_vals) {
#ifdef DMA_MODE
  dmaLoad(&store_vals[0], 0, 4096);
  // Don't DMA store_loc! That part will be accessed via coherent memory.
#endif
  loop: for (int i = 0; i < num_vals; i++)
    store_loc[i] = store_vals[i];
#ifdef DMA_MODE
  dmaStore(&store_vals[0], 0, 4096);
#endif
}

int main() {
  const int num_vals = 1024;
  TYPE *store_vals, *store_loc;
  int err = posix_memalign(
      (void**)&store_vals, CACHELINE_SIZE, sizeof(TYPE) * num_vals);
  assert(err == 0 && "Failed to allocate memory!");
  err = posix_memalign(
      (void**)&store_loc, CACHELINE_SIZE, sizeof(TYPE) * num_vals);
  assert(err == 0 && "Failed to allocate memory!");
  for (int i = 0; i < num_vals; i++) {
    store_vals[i] = i;
    store_loc[i] = -1;
  }

#ifdef LLVM_TRACE
  store_kernel(store_vals, store_loc, num_vals);
#else
  mapArrayToAccelerator(
      INTEGRATION_TEST, "store_vals", &(store_vals[0]), num_vals * sizeof(int));
  mapArrayToAccelerator(
      INTEGRATION_TEST, "store_loc", &(store_loc[0]), num_vals * sizeof(int));

  fprintf(stdout, "Invoking accelerator!\n");
  invokeAcceleratorAndBlock(INTEGRATION_TEST);
  fprintf(stdout, "Accelerator finished!\n");
#endif

  int num_failures = test_stores(store_vals, store_loc, num_vals);
  if (num_failures != 0) {
    fprintf(stdout, "Test failed with %d errors.", num_failures);
    return -1;
  }
  fprintf(stdout, "Test passed!\n");

  free(store_vals);
  free(store_loc);
  return 0;
}


text:
<?php

namespace Mintbridge\EloquentSentiment;

use Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use Mintbridge\EloquentSentiment\Activity;
use Mintbridge\EloquentSentiment\SentimentableInterface;

class SentimentManager
{
    public $sentiments;

    /**
     * @param \League\Fractal\Manager $manager
     */
    public function __construct(array $sentiments)
    {
        $this->sentiments = $sentiments;
    }

    public function __call($name, $arguments)
    {
        if (in_array($name, $this->sentiments)) {
            $this->toggle($name, $arguments[0]);
        }
    }

    /**
     * Toggle the sentiment on the given model for the user (if any)
     *
     * @param string $sentiment
     * @param \Mintbridge\EloquentSentiment\SentimentableInterface $model
     */
    public function toggle($sentiment, SentimentableInterface $model)
    {
        $user = Auth::user();

        $method = (($this->exists($sentiment, $model, $user)) ? 'remove' : 'add');

        return $this->{$method}($sentiment, $model, $user);
    }

    /**
     * Add the sentiment to the given model for the user (if any)
     *
     * @param string $sentiment
     * @param \Mintbridge\EloquentSentiment\SentimentableInterface $model
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     */
    private function add($sentiment, SentimentableInterface $model, Authenticatable $user)
    {
        $sentiment = new Sentiment([
            Sentiment::ATTR_SENTIMENT => $sentiment
        ]);

        if ($user) {
            $sentiment->user()->associate($user);
        }

        return $model->sentiments()->save($sentiment);
    }

    /**
     * Remove the sentiment from the given model for the user (if any)
     *
     * @param string $sentiment
     * @param \Mintbridge\EloquentSentiment\SentimentableInterface $model
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     */
    private function remove($sentiment, SentimentableInterface $model, Authenticatable $user)
    {
        $query = $this->query($sentiment, $model, $user);

        return $query->delete();
    }

    /**
     * Check if the sentiment is on the given model for the user (if any)
     *
     * @param string $sentiment
     * @param \Mintbridge\EloquentSentiment\SentimentableInterface $model
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     */
    private function exists($sentiment, SentimentableInterface $model, Authenticatable $user)
    {
        $query = $this->query($sentiment, $model, $user);

        return $query->exists();
    }

    /**
     * Create the query for the sentiment, modal and user
     *
     * @param string $sentiment
     * @param \Mintbridge\EloquentSentiment\SentimentableInterface $model
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     */
    private function query($sentiment, SentimentableInterface $model, Authenticatable $user)
    {
        $query = Sentiment::where(Sentiment::ATTR_SENTIMENTABLE_ID, '=', $model->getSentimentableId())
            ->where(Sentiment::ATTR_SENTIMENTABLE_TYPE, '=', $model->getSentimentableType())
            ->where(Sentiment::ATTR_SENTIMENT, '=', $sentiment)
            ->where(Sentiment::ATTR_USER_ID, '=', $user->getAuthIdentifier());

        return $query;
    }
}


text:
module Dominusrb
  module Database
    class Server < Sequel::Model
      one_to_many :roles , :class => Database::Role
      one_to_many :twittersearches , :class => Database::Twittersearch
      one_to_many :platoon_lobbies , :class => Database::Platoonlobby

      # Logging
      def after_create
        super
        Discordrb::LOGGER.info "created server entry #{inspect}"
      end

      def after_update
        super
        Discordrb::LOGGER.info "updated server entry #{inspect}"
      end
    end
  end
end


text:
package org.rubyforge.debugcommons;

import org.rubyforge.debugcommons.model.RubyThread;
import org.rubyforge.debugcommons.model.SuspensionPoint;

public final class RubyDebugEvent {

    private final RubyThread rubyThread;
    private final SuspensionPoint sp;
    private boolean isTerminate;

    static RubyDebugEvent createTerminateEvent() {
        RubyDebugEvent e = new RubyDebugEvent(null, null);
        e.isTerminate = true;
        return e;
    }

    public RubyDebugEvent(final RubyThread rubyThread, final SuspensionPoint sp) {
        if (sp != null) {
            assert rubyThread != null;
        }
        this.sp = sp;
        this.rubyThread = rubyThread;
    }

    public boolean isSuspensionType() {
        return !isTerminate && (sp.isBreakpoint() || sp.isStep());
    }

    public boolean isTerminateType() {
        return isTerminate;
    }

    public boolean isExceptionType() {
        return !isTerminate && sp.isException();
    }

    public RubyThread getRubyThread() {
        return rubyThread;
    }

    public String getFilePath() {
        return sp.getFile();
    }

    public int getLine() {
        return sp.getLine();
    }

    public boolean isStepping() {
        return sp.isStep();
    }

    @Override
    public String toString() {
        if (isTerminate) {
            return "[RubyDebugEvent@" + System.identityHashCode(this) + "> Terminate Event";
        }
        return "[RubyDebugEvent@" + System.identityHashCode(this) +
                "> type: " + sp +
                ", rubyThread: " + rubyThread +
                ", line: " + sp.getLine()  +
                ", filePath: " + sp.getFile() +
                ']';
    }

}


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>search.js - RDoc Documentation</title>

<link type="text/css" media="screen" href="../../rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

Gemfile

LICENSE

README

Gemfile.html

LICENSE_txt.html

LTFS.html

LTFSExtentInfo.html

LTFSFile.html

LTFSIndex.html

LTFSTape.html

README_md.html

created.rid

Gemfile_html.html

LICENSE_txt_html.html

LTFSExtentInfo_html.html

LTFSFile_html.html

LTFSIndex_html.html

LTFSTape_html.html

LTFS_html.html

README_md_html.html

created_rid.html

created_rid_html.html

index_html.html

darkfish_js.html

jquery_js.html

navigation_js.html

search_index_js.html

search_js.html

searcher_js.html

ltfs_gemspec_html.html

rdoc_css.html

table_of_contents_html.html

index.html

darkfish.js

jquery.js

navigation.js

search.js

search_index.js

searcher.js

ltfs_gemspec.html

rdoc.css

table_of_contents.html

ltfs.gemspec

Class and Module Index

LTFS

LTFS::LTFSExtentInfo

LTFS::LTFSFile

LTFS::LTFSIndex

LTFS::LTFSTape

Search = function(data, input, result) {

this.data = data;
this.$input = $(input);
this.$result = $(result);

this.$current = null;
this.$view = this.$result.parent();
this.searcher = new Searcher(data.index);
this.init();

}

Search.prototype = $.extend({}, Navigation, new function() {

var suid = 1;

this.init = function() {
  var _this = this;
  var observer = function() {
    _this.search(_this.$input[0].value);
  };
  this.$input.keyup(observer);
  this.$input.click(observer); // mac's clear field

  this.searcher.ready(function(results, isLast) {
    _this.addResults(results, isLast);
  })

  this.initNavigation();
  this.setNavigationActive(false);
}

this.search = function(value, selectFirstMatch) {
  value = jQuery.trim(value).toLowerCase();
  if (value) {
    this.setNavigationActive(true);
  } else {
    this.setNavigationActive(false);
  }

  if (value == '') {
    this.lastQuery = value;
    this.$result.empty();
    this.setNavigationActive(false);
  } else if (value != this.lastQuery) {
    this.lastQuery = value;
    this.firstRun = true;
    this.searcher.find(value);
  }
}

this.addResults = function(results, isLast) {
  var target = this.$result.get(0);
  if (this.firstRun && (results.length > 0 || isLast)) {
    this.$current = null;
    this.$result.empty();
  }

  for (var i=0, l = results.length; i < l; i++) {
    target.appendChild(this.renderItem.call(this, results[i]));
  };

  if (this.firstRun && results.length > 0) {
    this.firstRun = false;
    this.$current = $(target.firstChild);
    this.$current.addClass('current');
  }
  if (jQuery.browser.msie) this.$element[0].className += '';
}

this.move = function(isDown) {
  if (!this.$current) return;
  var $next = this.$current[isDown ? 'next' : 'prev']();
  if ($next.length) {
    this.$current.removeClass('current');
    $next.addClass('current');
    this.scrollIntoView($next[0], this.$view[0]);
    this.$current = $next;
  }
  return true;
}

this.hlt = function(html) {
  return this.escapeHTML(html).
    replace(/\u0001/g, '<em>').
    replace(/\u0002/g, '</em>');
}

this.escapeHTML = function(html) {
  return html.replace(/[&<>]/g, function(c) {
    return '&#' + c.charCodeAt(0) + ';';
  });
}

});

[Validate]

Generated by RDoc 4.0.0.

Generated with the Darkfish Rdoc Generator 3.


text:
@class BrowserWebView, WebModel, WebViewBackForwardList;

typedef void (^WebCompletionBlock)(NSString *, NSError *);

@protocol WebViewDelegate <NSObject>

@optional

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(BrowserWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

@end

@interface BrowserWebView : UIWebView<UIWebViewDelegate>

@property (nonatomic, unsafe_unretained) WebModel *webModel;
@property (nonatomic, assign, readonly) BOOL isMainFrameLoaded;
@property (nonatomic, unsafe_unretained, readonly) UIActivityIndicatorView *indicatorView;
@property (nonatomic, unsafe_unretained, readonly) UILongPressGestureRecognizer *longPressGestureRecognizer;

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(WebCompletionBlock)completionHandler;

- (NSString *)mainFURL;
- (NSString *)mainFTitle;
- (WebViewBackForwardList *)webViewBackForwardList;

@end


text:
NODEUNIT = ./node_modules/.bin/nodeunit
JSSTYLE_FILES := $(shell find lib test -name "*.js")
NODEOPT ?= $(HOME)/opt

all $(NODEUNIT):
	npm install

.PHONY: distclean
distclean:
	rm -rf node_modules

.PHONY: test
test: | $(NODEUNIT)
	$(NODEUNIT) test/*.test.js

.PHONY: testall
testall: test10 test08
.PHONY: test10
test10:
	@echo "# Test node 0.10.x (with node `$(NODEOPT)/node-0.10/bin/node --version`)"
	@$(NODEOPT)/node-0.10/bin/node --version
	PATH="$(NODEOPT)/node-0.10/bin:$(PATH)" make test
.PHONY: test08
test08:
	@echo "# Test node 0.8.x (with node `$(NODEOPT)/node-0.8/bin/node --version`)"
	@$(NODEOPT)/node-0.8/bin/node --version
	PATH="$(NODEOPT)/node-0.8/bin:$(PATH)" make test

.PHONY: check-jsstyle
check-jsstyle: $(JSSTYLE_FILES)
	./tools/jsstyle -o indent=4,doxygen,unparenthesized-return=0,blank-after-start-comment=0,leading-right-paren-ok $(JSSTYLE_FILES)

.PHONY: check
check: check-jsstyle
	@echo "Check ok."

# Ensure CHANGES.md and package.json have the same version.
.PHONY: versioncheck
versioncheck:
	[[ `cat package.json | json version` == `grep '^## ' CHANGES.md | head -1 | awk '{print $$2}'` ]]

.PHONY: cutarelease
cutarelease: versioncheck
	[[ `git status | tail -n1` == "nothing to commit (working directory clean)" ]]
	./tools/cutarelease.py -p dashdash -f package.json


text:
;require(['anole', 'zepto'], function (anole){
  var sceneHandler = $('
');

  sceneHandler.html("
4
")

  anole.addScene({
    sceneHandler: sceneHandler,
    onInit: function (){

    },
    onStart: function (finish){
      console.log("scene4 playing");
      setTimeout(function (){
        console.log("scene4 playend");
        finish();
      },1000);
    },
    onEnd: function (){

    }
  })
});


text:
package com.ctrip.xpipe.redis.meta.server.keeper.applier.manager;

import com.ctrip.xpipe.redis.core.entity.ApplierMeta;
import com.ctrip.xpipe.redis.meta.server.exception.MetaServerException;

/**
 * @author ayq
 * <p>
 * 2022/4/6 16:29
 */
public class DeleteApplierStillAliveException extends MetaServerException {

    private static final long serialVersionUID = 1L;

    public DeleteApplierStillAliveException(ApplierMeta currentApplier){
        super(String.format("current keeper still alive:%s:%d", currentApplier.getIp(), currentApplier.getPort()));
        setOnlyLogMessage(true);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('theme', '0007_auto_20170427_1553'),
    ]

    operations = [
        migrations.AlterField(
            model_name='quotamessage',
            name='content',
            field=models.TextField(default=b'To request additional quota, please contact {email}. We will try to accommodate reasonable requests for additional quota. If you have a large quota request you may need to contribute toward the costs of providing the additional space you need. See https://pages.myhpom.renci.org/about-myhpom/policies/quota/ for more information about the quota policy.'),
        ),
        migrations.AlterField(
            model_name='quotamessage',
            name='enforce_content_prepend',
            field=models.TextField(default=b'Your action to add content to MyHPOM was refused because you have exceeded your quota. Your quota for MyHPOM resources is {allocated}{unit} in {zone} zone. You currently have resources that consume {used}{unit}, {percent}% of your quota. '),
        ),
        migrations.AlterField(
            model_name='quotamessage',
            name='grace_period_content_prepend',
            field=models.TextField(default=b'You have exceeded your MyHPOM quota. Your quota for MyHPOM resources is {allocated}{unit} in {zone} zone. You currently have resources that consume {used}{unit}, {percent}% of your quota. You have a grace period until {cut_off_date} to reduce your use to below your quota, or to acquire additional quota, after which you will no longer be able to create new resources in MyHPOM. '),
        ),
        migrations.AlterField(
            model_name='quotamessage',
            name='warning_content_prepend',
            field=models.TextField(default=b'Your quota for MyHPOM resources is {allocated}{unit} in {zone} zone. You currently have resources that consume {used}{unit}, {percent}% of your quota. Once your quota reaches 100% you will no longer be able to create new resources in MyHPOM. '),
        ),
        migrations.AlterField(
            model_name='siteconfiguration',
            name='copyright',
            field=models.TextField(default=b'&copy {% now "Y" %} University of North Carolina Board of Trustees'),
        ),
        migrations.AlterField(
            model_name='userprofile',
            name='create_irods_user_account',
            field=models.BooleanField(default=False, help_text=b'Check to create an iRODS user account in MyHPOM user iRODS space for staging large files (>2GB) using iRODS clients such as Cyberduck (https://cyberduck.io/) and icommands (https://docs.irods.org/master/icommands/user/).Uncheck to delete your iRODS user account. Note that deletion of your iRODS user account deletes all of your files under this account as well.'),
        ),
        migrations.AlterField(
            model_name='userprofile',
            name='details',
            field=models.TextField(help_text=b'Tell the MyHPOM community a little about yourself.', null=True, verbose_name=b'Description', blank=True),
        ),
        migrations.AlterField(
            model_name='userquota',
            name='zone',
            field=models.CharField(default='myhpom_internal', max_length=100),
        ),
    ]


text:
<?php
require_once('../../../classes/crypt/5CR.php');
require_once('../../../configuration/key.inc');

$encript = new E5CR($llave); //definimos un nuevo elemento y pasamos la llave

include ('../../../classes/querys/query.php');
$query=new query();

$tipos_imagen=$query->listar_tipos_imagen();

$resultados.='
';

while ($salida=mysql_fetch_array($tipos_imagen)) {

$img_disponibles=$query->imagenes_disponibles_tipo($_POST['id'],$salida['id_tipo']);
$num_resultados=mysql_num_rows($img_disponibles);

// Inicializo las variables
$o=0;
$img=array();
$file='';
$panel=$_POST['panel'];
$fila=$_POST['fila'];
$columna=$_POST['columna'];

// Si el numero de resultados es mayor de 0 muestro los resultados
if ($num_resultados > 0) {
	$r=0;
		while ($row=mysql_fetch_array($img_disponibles)) {

				$ruta_img='ruta=../../../../repositorio/originales/'.$row['imagen'].'&size=30';
                $encript->encriptar($ruta_img,1); //OJO uno(1) es para encriptar variables para URL

				$resultados.='

';

				$r++;

		}

	} // Cierro el IF de comprobacion de si hay resultados

} // Cierro el While

$resultados.='
';
echo $resultados;
?>


text:
package com.example.arrow.app01peliculas;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class DetalleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detalle);
    }
}


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

/*
Package prober provides a prober for running a set of probes.

Prober takes in a config proto which dictates what probes should be created
with what configuration, and manages the asynchronous fan-in/fan-out of the
metrics data from these probes.
*/
package prober

import (
	"context"
	"fmt"
	"math/rand"
	"regexp"
	"sync"
	"time"

	"github.com/golang/glog"
	configpb "github.com/google/cloudprober/config/proto"
	"github.com/google/cloudprober/config/runconfig"
	"github.com/google/cloudprober/logger"
	"github.com/google/cloudprober/metrics"
	spb "github.com/google/cloudprober/prober/proto"
	"github.com/google/cloudprober/probes"
	"github.com/google/cloudprober/probes/options"
	probes_configpb "github.com/google/cloudprober/probes/proto"
	rdsserver "github.com/google/cloudprober/rds/server"
	"github.com/google/cloudprober/servers"
	"github.com/google/cloudprober/surfacers"
	"github.com/google/cloudprober/sysvars"
	"github.com/google/cloudprober/targets"
	"github.com/google/cloudprober/targets/endpoint"
	"github.com/google/cloudprober/targets/lameduck"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// Prober represents a collection of probes where each probe implements the Probe interface.
type Prober struct {
	Probes    map[string]*probes.ProbeInfo
	Servers   []*servers.ServerInfo
	c         *configpb.ProberConfig
	l         *logger.Logger
	mu        sync.Mutex
	ldLister  endpoint.Lister
	Surfacers []*surfacers.SurfacerInfo

	// Probe channel to handle starting of the new probes.
	grpcStartProbeCh chan string

	// Per-probe cancelFunc map.
	probeCancelFunc map[string]context.CancelFunc

	// dataChan for passing metrics between probes and main goroutine.
	dataChan chan *metrics.EventMetrics

	// Used by GetConfig for /config handler.
	TextConfig string
}

func runOnThisHost(runOn string, hostname string) (bool, error) {
	if runOn == "" {
		return true, nil
	}
	r, err := regexp.Compile(runOn)
	if err != nil {
		return false, err
	}
	return r.MatchString(hostname), nil
}

func (pr *Prober) addProbe(p *probes_configpb.ProbeDef) error {
	pr.mu.Lock()
	defer pr.mu.Unlock()

	// Check if this probe is supposed to run here.
	runHere, err := runOnThisHost(p.GetRunOn(), sysvars.Vars()["hostname"])
	if err != nil {
		return err
	}
	if !runHere {
		return nil
	}

	if pr.Probes[p.GetName()] != nil {
		return status.Errorf(codes.AlreadyExists, "probe %s is already defined", p.GetName())
	}

	opts, err := options.BuildProbeOptions(p, pr.ldLister, pr.c.GetGlobalTargetsOptions(), pr.l)
	if err != nil {
		return status.Errorf(codes.Unknown, err.Error())
	}

	pr.l.Infof("Creating a %s probe: %s", p.GetType(), p.GetName())
	probeInfo, err := probes.CreateProbe(p, opts)
	if err != nil {
		return status.Errorf(codes.Unknown, err.Error())
	}
	pr.Probes[p.GetName()] = probeInfo

	return nil
}

// Init initialize prober with the given config file.
func (pr *Prober) Init(ctx context.Context, cfg *configpb.ProberConfig, l *logger.Logger) error {
	pr.c = cfg
	pr.l = l

	// Initialize cloudprober gRPC service if configured.
	srv := runconfig.DefaultGRPCServer()
	if srv != nil {
		pr.grpcStartProbeCh = make(chan string)
		spb.RegisterCloudproberServer(srv, pr)
	}

	// Initialize RDS server, if configured and attach to the default gRPC server.
	// Note that we can still attach services to the default gRPC server as it's
	// started later in Start().
	if c := pr.c.GetRdsServer(); c != nil {
		l, err := logger.NewCloudproberLog("rds-server")
		if err != nil {
			return err
		}
		rdsServer, err := rdsserver.New(ctx, c, nil, l)
		if err != nil {
			return err
		}

		runconfig.SetLocalRDSServer(rdsServer)
		if srv != nil {
			rdsServer.RegisterWithGRPC(srv)
		}
	}

	// Initialize lameduck lister
	globalTargetsOpts := pr.c.GetGlobalTargetsOptions()

	if globalTargetsOpts.GetLameDuckOptions() != nil {
		ldLogger, err := logger.NewCloudproberLog("lame-duck")
		if err != nil {
			return fmt.Errorf("error in initializing lame-duck logger: %v", err)
		}

		if err := lameduck.InitDefaultLister(globalTargetsOpts, nil, ldLogger); err != nil {
			return err
		}

		pr.ldLister, err = lameduck.GetDefaultLister()
		if err != nil {
			pr.l.Warningf("Error while getting default lameduck lister, lameduck behavior will be disabled. Err: %v", err)
		}
	}

	var err error

	// Initialize shared targets
	for _, st := range pr.c.GetSharedTargets() {
		tgts, err := targets.New(st.GetTargets(), pr.ldLister, globalTargetsOpts, pr.l, pr.l)
		if err != nil {
			return err
		}
		targets.SetSharedTargets(st.GetName(), tgts)
	}

	// Initiliaze probes
	pr.Probes = make(map[string]*probes.ProbeInfo)
	pr.probeCancelFunc = make(map[string]context.CancelFunc)
	for _, p := range pr.c.GetProbe() {
		if err := pr.addProbe(p); err != nil {
			return err
		}
	}

	// Initialize servers
	pr.Servers, err = servers.Init(ctx, pr.c.GetServer())
	if err != nil {
		return err
	}

	pr.Surfacers, err = surfacers.Init(ctx, pr.c.GetSurfacer())
	if err != nil {
		return err
	}

	return nil
}

// Start starts a previously initialized Cloudprober.
func (pr *Prober) Start(ctx context.Context) {
	pr.dataChan = make(chan *metrics.EventMetrics, 100000)

	go func() {
		var em *metrics.EventMetrics
		for {
			em = <-pr.dataChan
			var s = em.String()
			if len(s) > logger.MaxLogEntrySize {
				glog.Warningf("Metric entry for timestamp %v dropped due to large size: %d", em.Timestamp, len(s))
				continue
			}

			// Replicate the surfacer message to every surfacer we have
			// registered. Note that s.Write() is expected to be
			// non-blocking to avoid blocking of EventMetrics message
			// processing.
			for _, surfacer := range pr.Surfacers {
				surfacer.Write(context.Background(), em)
			}
		}
	}()

	// Start a goroutine to export system variables
	go sysvars.Start(ctx, pr.dataChan, time.Millisecond*time.Duration(pr.c.GetSysvarsIntervalMsec()), pr.c.GetSysvarsEnvVar())

	// Start servers, each in its own goroutine
	for _, s := range pr.Servers {
		go s.Start(ctx, pr.dataChan)
	}

	if pr.c.GetDisableJitter() {
		for name := range pr.Probes {
			go pr.startProbe(ctx, name)
		}
		return
	}
	pr.startProbesWithJitter(ctx)

	if runconfig.DefaultGRPCServer() != nil {
		// Start a goroutine to handle starting of the probes added through gRPC.
		// AddProbe adds new probes to the pr.grpcStartProbeCh channel and this
		// goroutine reads from that channel and starts the probe using the overall
		// Start context.
		go func() {
			for {
				select {
				case name := <-pr.grpcStartProbeCh:
					pr.startProbe(ctx, name)
				}
			}
		}()
	}
}

func (pr *Prober) startProbe(ctx context.Context, name string) {
	pr.mu.Lock()
	defer pr.mu.Unlock()

	probeCtx, cancelFunc := context.WithCancel(ctx)
	pr.probeCancelFunc[name] = cancelFunc
	go pr.Probes[name].Start(probeCtx, pr.dataChan)
}

// startProbesWithJitter try to space out probes over time, as much as possible,
// without making it too complicated. We arrange probes into interval buckets -
// all probes with the same interval will be part of the same bucket, and we
// then spread out probes within that interval by introducing a delay of
// interval / len(probes) between probes. We also introduce a random jitter
// between different interval buckets.
func (pr *Prober) startProbesWithJitter(ctx context.Context) {
	// Seed random number generator.
	rand.Seed(time.Now().UnixNano())

	// Make interval -> [probe1, probe2, probe3..] map
	intervalBuckets := make(map[time.Duration][]*probes.ProbeInfo)
	for _, p := range pr.Probes {
		intervalBuckets[p.Options.Interval] = append(intervalBuckets[p.Options.Interval], p)
	}

	for interval, probeInfos := range intervalBuckets {
		go func(interval time.Duration, probeInfos []*probes.ProbeInfo) {
			// Introduce a random jitter between interval buckets.
			randomDelayMsec := rand.Int63n(int64(interval.Seconds() * 1000))
			time.Sleep(time.Duration(randomDelayMsec) * time.Millisecond)

			interProbeDelay := interval / time.Duration(len(probeInfos))

			// Spread out probes evenly with an interval bucket.
			for _, p := range probeInfos {
				pr.l.Info("Starting probe: ", p.Name)
				go pr.startProbe(ctx, p.Name)
				time.Sleep(interProbeDelay)
			}
		}(interval, probeInfos)
	}
}


text: This directory contains a copy of all formal releases.


text:
---
uid: SolidEdgePart.LiveSections.Parent
summary:
remarks:
---


text:
"""This file implements a threaded stream controller to return logs back from
the ray clientserver.
"""
import sys
import logging
import queue
import threading
import grpc

import ray.core.generated.ray_client_pb2 as ray_client_pb2
import ray.core.generated.ray_client_pb2_grpc as ray_client_pb2_grpc

logger = logging.getLogger(__name__)
# TODO(barakmich): Running a logger in a logger causes loopback.
# The client logger need its own root -- possibly this one.
# For the moment, let's just not propogate beyond this point.
logger.propagate = False

class LogstreamClient:
    def __init__(self, channel: "grpc._channel.Channel", metadata: list):
        """Initializes a thread-safe log stream over a Ray Client gRPC channel.

        Args:
            channel: connected gRPC channel
            metadata: metadata to pass to gRPC requests
        """
        self.channel = channel
        self._metadata = metadata
        self.request_queue = queue.Queue()
        self.log_thread = self._start_logthread()
        self.log_thread.start()

    def _start_logthread(self) -> threading.Thread:
        return threading.Thread(target=self._log_main, args=(), daemon=True)

    def _log_main(self) -> None:
        stub = ray_client_pb2_grpc.RayletLogStreamerStub(self.channel)
        log_stream = stub.Logstream(
            iter(self.request_queue.get, None), metadata=self._metadata)
        try:
            for record in log_stream:
                if record.level < 0:
                    self.stdstream(level=record.level, msg=record.msg)
                self.log(level=record.level, msg=record.msg)
        except grpc.RpcError as e:
            if e.code() == grpc.StatusCode.CANCELLED:
                # Graceful shutdown. We've cancelled our own connection.
                logger.info("Cancelling logs channel")
            elif e.code() in (grpc.StatusCode.UNAVAILABLE,
                              grpc.StatusCode.RESOURCE_EXHAUSTED):
                # TODO(barakmich): The server may have
                # dropped. In theory, we can retry, as per
                # https://grpc.github.io/grpc/core/md_doc_statuscodes.html but
                # in practice we may need to think about the correct semantics
                # here.
                logger.info("Server disconnected from logs channel")
            else:
                # Some other, unhandled, gRPC error
                logger.exception(
                    f"Got Error from logger channel -- shutting down: {e}")

    def log(self, level: int, msg: str):
        """Log the message from the log stream.
        By default, calls logger.log but this can be overridden.

        Args:
            level: The loglevel of the received log message
            msg: The content of the message
        """
        logger.log(level=level, msg=msg)

    def stdstream(self, level: int, msg: str):
        """Log the stdout/stderr entry from the log stream.
        By default, calls print but this can be overridden.

        Args:
            level: The loglevel of the received log message
            msg: The content of the message
        """
        print_file = sys.stderr if level == -2 else sys.stdout
        print(msg, file=print_file, end="")

    def set_logstream_level(self, level: int):
        logger.setLevel(level)
        req = ray_client_pb2.LogSettingsRequest()
        req.enabled = True
        req.loglevel = level
        self.request_queue.put(req)

    def close(self) -> None:
        self.request_queue.put(None)
        if self.log_thread is not None:
            self.log_thread.join()

    def disable_logs(self) -> None:
        req = ray_client_pb2.LogSettingsRequest()
        req.enabled = False
        self.request_queue.put(req)


text:
import os
import subprocess

import six
import testtools

class RuntimeTests(testtools.TestCase):

    def _test_runtime(self, cmdlist, infile=None):
        process = subprocess.Popen(
            cmdlist,
            stdin=infile if infile else subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            close_fds=True
        )
        stdout, stderr = process.communicate()
        retcode = process.poll()
        return (retcode, stdout.decode('utf-8'))

    def _test_example(self, cmdlist, targets):
        for t in targets:
            cmdlist.append(os.path.join(os.getcwd(), 'examples', t))
        return self._test_runtime(cmdlist)

    def test_no_arguments(self):
        (retcode, output) = self._test_runtime(['bandit', ])
        self.assertEqual(2, retcode)
        if six.PY2:
            self.assertIn("error: too few arguments", output)
        else:
            self.assertIn("arguments are required: targets", output)

    def test_piped_input(self):
        with open('examples/imports.py', 'r') as infile:
            (retcode, output) = self._test_runtime(['bandit', '-'], infile)
            self.assertEqual(1, retcode)
            self.assertIn("Total lines of code: 4", output)
            self.assertIn("Low: 2", output)
            self.assertIn("High: 2", output)
            self.assertIn("Files skipped (0):", output)
            self.assertIn("Issue: [B403:blacklist] Consider possible", output)
            self.assertIn("<stdin>:2", output)
            self.assertIn("<stdin>:4", output)

    def test_nonexistent_config(self):
        (retcode, output) = self._test_runtime([
            'bandit', '-c', 'nonexistent.yml', 'xx.py'
        ])
        self.assertEqual(2, retcode)
        self.assertIn("nonexistent.yml : Could not read config file.", output)

    def test_help_arg(self):
        (retcode, output) = self._test_runtime(['bandit', '-h'])
        self.assertEqual(0, retcode)
        self.assertIn(
            "Bandit - a Python source code security analyzer", output
        )
        self.assertIn("usage: bandit [-h]", output)
        self.assertIn("positional arguments:", output)
        self.assertIn("optional arguments:", output)
        self.assertIn("tests were discovered and loaded:", output)

    def test_help_in_readme(self):
        replace_list = [' ', '\t']
        (retcode, output) = self._test_runtime(['bandit', '-h'])
        for i in replace_list:
            output = output.replace(i, '')
        output = output.replace("'", "\'")
        with open('README.rst') as f:
            readme = f.read()
            for i in replace_list:
                readme = readme.replace(i, '')
            self.assertIn(output, readme)

    # test examples (use _test_example() to wrap in config location argument
    def test_example_nonexistent(self):
        (retcode, output) = self._test_example(
            ['bandit', ], ['nonexistent.py', ]
        )
        self.assertEqual(0, retcode)
        self.assertIn("Files skipped (1):", output)
        self.assertIn("nonexistent.py (No such file or directory", output)

    def test_example_okay(self):
        (retcode, output) = self._test_example(['bandit', ], ['okay.py', ])
        self.assertEqual(0, retcode)
        self.assertIn("Total lines of code: 1", output)
        self.assertIn("Files skipped (0):", output)
        self.assertIn("No issues identified.", output)

    def test_example_nonsense(self):
        (retcode, output) = self._test_example(['bandit', ], ['nonsense.py', ])
        self.assertEqual(0, retcode)
        self.assertIn("Files skipped (1):", output)
        self.assertIn("nonsense.py (syntax error while parsing AST", output)

    def test_example_nonsense2(self):
        (retcode, output) = self._test_example(
            ['bandit', ], ['nonsense2.py', ]
        )
        self.assertEqual(0, retcode)
        self.assertIn(
            "Exception occurred when executing tests against", output
        )
        self.assertIn("Files skipped (1):", output)
        self.assertIn("nonsense2.py (exception while scanning file)", output)

    def test_example_imports(self):
        (retcode, output) = self._test_example(['bandit', ], ['imports.py', ])
        self.assertEqual(1, retcode)
        self.assertIn("Total lines of code: 4", output)
        self.assertIn("Low: 2", output)
        self.assertIn("High: 2", output)
        self.assertIn("Files skipped (0):", output)
        self.assertIn("Issue: [B403:blacklist] Consider possible",
                      output)
        self.assertIn("imports.py:2", output)
        self.assertIn("imports.py:4", output)


text:
<?php

declare(strict_types=1);

namespace Broadway\CommandHandling\Testing;

use Broadway\CommandHandling\CommandBus;
use Broadway\CommandHandling\CommandHandler;

/**
 * Command bus that is able to record all dispatched commands.
 */
final class TraceableCommandBus implements CommandBus
{
    private $commandHandlers = [];
    private $commands = [];
    private $record = false;

    /**
     * {@inheritdoc}
     */
    public function subscribe(CommandHandler $handler): void
    {
        $this->commandHandlers[] = $handler;
    }

    /**
     * {@inheritdoc}
     */
    public function dispatch($command): void
    {
        if (!$this->record) {
            return;
        }

        $this->commands[] = $command;
    }

    /**
     * @return mixed[]
     */
    public function getRecordedCommands(): array
    {
        return $this->commands;
    }

    public function record(): bool
    {
        return $this->record = true;
    }
}


text:
import os

from google.cloud import automl
import pytest

import translate_predict

PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]
MODEL_ID = os.environ["TRANSLATION_MODEL_ID"]

@pytest.fixture(scope="function", autouse=True)
def setup():
    # Verify the model is deployed before trying to predict
    client = automl.AutoMlClient()
    model_full_id = client.model_path(PROJECT_ID, "us-central1", MODEL_ID)

    model = client.get_model(name=model_full_id)
    if model.deployment_state == automl.Model.DeploymentState.UNDEPLOYED:
        # Deploy model if it is not deployed
        response = client.deploy_model(name=model_full_id)
        response.result()

def test_translate_predict(capsys):
    translate_predict.predict(PROJECT_ID, MODEL_ID, "resources/input.txt")
    out, _ = capsys.readouterr()
    assert "Translated content: " in out


text:
import appearanceTypedef from "./appearance";
import behaviorTypedef from "./behavior";
import identityTypedef from "./identity";
import locationTypedef from "./location";
import stageTypedef from "./stage";
import stageChildTypedef from "./stageChild";
import lightTypedef from "./light";
import glowTypedef from "./glow";
import templateTypedef from "./template";
import enginesTypedef from "./engines";
import thrustersTypedef from "./thrusters";

export const appearance = appearanceTypedef;
export const behavior = behaviorTypedef;
export const identity = identityTypedef;
export const location = locationTypedef;
export const stage = stageTypedef;
export const stageChild = stageChildTypedef;
export const light = lightTypedef;
export const glow = glowTypedef;
export const templateEntity = templateTypedef;
export const enginesEntity = enginesTypedef;
export const thrustersEntity = thrustersTypedef;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>net.opentsdb.contrib</groupId>
	<artifactId>tsquare</artifactId>
	<version>2.0.0</version>

	<name>tsquare</name>
	<description>TSquare: Time Series Query Reporting and Exploration</description>
	<url>https://github.com/Conductor/tsquare</url>
	<inceptionYear>2013</inceptionYear>

	<packaging>war</packaging>

	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<connection>scm:git:git@github.com:Conductor/tsquare.git</connection>
		<developerConnection>scm:git:git@github.com:Conductor/tsquare.git</developerConnection>
		<url>https://github.com/Conductor/tsquare</url>
	</scm>

	<issueManagement>
		<url>https://github.com/Conductor/tsquare/issues</url>
		<system>GitHub</system>
	</issueManagement>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<compilerVersion>1.6</compilerVersion>
					<!--
					<debug>true</debug>
					<encoding>${project.build.sourceEncoding}</encoding>
					<debuglevel>lines,vars,source</debuglevel>
					-->
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warName>${project.name}</warName>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.1</version>
				<configuration>
					<path>/tsquare</path>
					<port>8080</port>
					<useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
				</configuration>
			</plugin>

		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-math3</artifactId>
			<version>3.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.3.RELEASE</version>
			<exclusions>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>net.opentsdb</groupId>
			<artifactId>opentsdb</artifactId>
			<version>2.0.1</version>
			<exclusions>
				<exclusion>
					<artifactId>gwt-user</artifactId>
					<groupId>com.google.gwt</groupId>
				</exclusion>
				<exclusion>
					<artifactId>log4j-over-slf4j</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
				<exclusion>
					<artifactId>logback-core</artifactId>
					<groupId>ch.qos.logback</groupId>
				</exclusion>
				<exclusion>
					<artifactId>logback-classic</artifactId>
					<groupId>ch.qos.logback</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

	</dependencies>

</project>


text:
using System;
using XenAPI;
using XenAdmin.Diagnostics.Problems;
using XenAdmin.Core;
using System.IO;
using XenAdmin.Diagnostics.Problems.HostProblem;
using System.Text.RegularExpressions;
using System.Xml;
using System.Collections.Generic;
using XenAdmin.Actions;
using XenAdmin.Wizards.PatchingWizard;

namespace XenAdmin.Diagnostics.Checks
{
    class PatchPrecheckCheck : Check
    {
        private readonly Pool_patch _patch;
        private readonly Pool_update _update;

        private static Regex PrecheckErrorRegex = new Regex("(<error).+(</error>)");
        private static Regex LivePatchResponseRegex = new Regex("(<livepatch).+(</livepatch>)");

        private readonly Dictionary<string, livepatch_status> livePatchCodesByHost;

        public PatchPrecheckCheck(Host host, Pool_patch patch)
            : this(host, patch, null)
        {
        }

        public PatchPrecheckCheck(Host host, Pool_update update)
            : this(host, update, null)
        {
        }

        public PatchPrecheckCheck(Host host, Pool_patch patch, Dictionary<string, livepatch_status> livePatchCodesByHost)
            : base(host)
        {
            _patch = patch;
            this.livePatchCodesByHost = livePatchCodesByHost;
        }

        public PatchPrecheckCheck(Host host, Pool_update update, Dictionary<string, livepatch_status> livePatchCodesByHost)
            : base(host)
        {
            _update = update;
            this.livePatchCodesByHost = livePatchCodesByHost;
        }

        protected override Problem RunCheck()
        {
            //
            // Check patch isn't already applied here
            //
            if ((Patch != null && Patch.AppliedOn(Host) != DateTime.MaxValue)
                || (Update != null && Update.AppliedOn(Host)))
            {
                return new PatchAlreadyApplied(this, Host);
            }

            if (!Host.IsLive)
                return new HostNotLiveWarning(this, Host);

            if (!Host.Connection.IsConnected)
                throw new EndOfStreamException(Helpers.GetName(Host.Connection));

            Session session = Host.Connection.DuplicateSession();

            try
            {
                if (Patch != null)
                {
                    string result = Pool_patch.precheck(session, Patch.opaque_ref, Host.opaque_ref);
                    log.DebugFormat("Pool_patch.precheck returned: '{0}'", result);

                    return FindProblem(result);
                }
                else if (Helpers.ElyOrGreater(Host))
                {
                    var livepatchStatus = Pool_update.precheck(session, Update.opaque_ref, Host.opaque_ref);

                    log.DebugFormat("Pool_update.precheck returned livepatch_status: '{0}'", livepatchStatus);

                    if (livePatchCodesByHost != null)
                        livePatchCodesByHost[Host.uuid] = livepatchStatus;
                }
                //trying to apply update to partially upgraded pool
                else if (Helpers.ElyOrGreater(Helpers.GetMaster(Host.Connection)) && !Helpers.ElyOrGreater(Host))
                {
                    return new WrongServerVersion(this, Host);
                }

                return null;
            }
            catch (Failure f)
            {
                log.Error(f.ToString());
                if(f.ErrorDescription.Count>0)
                    log.Error(f.ErrorDescription[0]);
                if (f.ErrorDescription.Count > 1)
                    log.Error(f.ErrorDescription[1]);
                if (f.ErrorDescription.Count > 2)
                    log.Error(f.ErrorDescription[2]);
                if (f.ErrorDescription.Count > 3)
                    log.Error(f.ErrorDescription[3]);
                // try and find problem from the xapi failure
                Problem problem = FindProblem(f);
                return problem ?? new PrecheckFailed(this, Host, f);
            }
        }

        public override string Description
        {
            get { return Messages.SERVER_SIDE_CHECK_DESCRIPTION; }
        }

        public Pool_patch Patch
        {
            get { return _patch; }
        }

        public Pool_update Update
        {
            get { return _update; }
        }

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Find problem from xml result
        /// </summary>
        /// <param name="result">xml result, as returned by Pool_patch.precheck() call.
        ///     E.g.:
        ///     <error errorcode="PATCH_PRECHECK_FAILED_OUT_OF_SPACE">
        ///         <found>2049859584</found>
        ///         <required>10000000000</required>
        ///     </error>
        /// </param>
        /// <returns>Problem or null, if no problem found</returns>
        private Problem FindProblem(string result)
        {
            if (!PrecheckErrorRegex.IsMatch(result.Replace("\n", "")))
                return null;

            Match m = PrecheckErrorRegex.Match(result.Replace("\n", ""));

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(m.ToString());
            log.Error(m.ToString());
            XmlNode errorNode = doc.FirstChild;

            string errorcode = errorNode.Attributes != null && errorNode.Attributes["errorcode"] != null
                                   ? errorNode.Attributes["errorcode"].Value
                                   : string.Empty;

            if (errorcode == "")
                return null;

            var found = "";
            var required = "";

            foreach (XmlNode node in errorNode.ChildNodes)
            {
                if (node.Name == "found")
                    found = node.InnerXml;
                else if (node.Name == "required")
                    required = node.InnerXml;
            }
            var problem = FindProblem(errorcode, found, required);
            return problem ?? new PrecheckFailed(this, Host, new Failure(errorcode));
        }

        /// <summary>
        /// Find problem from xapi Failure
        /// </summary>
        /// <param name="failure">Xapi failure, thrown by Pool_patch.precheck() call.
        ///     E.g.: failure.ErrorDescription.Count = 4
        ///         ErrorDescription[0] = "PATCH_PRECHECK_FAILED_WRONG_SERVER_VERSION"
        ///         ErrorDescription[1] = "OpaqueRef:612b5eee-03dc-bbf5-3385-6905fdc9b079"
        ///         ErrorDescription[2] = "6.5.0"
        ///         ErrorDescription[3] = "^6\\.2\\.0$"
        ///     E.g.: failure.ErrorDescription.Count = 2
        ///         ErrorDescription[0] = "OUT_OF_SPACE"
        ///         ErrorDescription[1] = "/var/patch"
        /// </param>
        /// <returns>Problem or null, if no problem found</returns>
        private Problem FindProblem(Failure failure)
        {
            if (failure.ErrorDescription.Count == 0)
                return null;

            var errorcode = failure.ErrorDescription[0];
            var found = "";
            var required = "";

            if (failure.ErrorDescription.Count > 2)
                found = failure.ErrorDescription[2];
            if (failure.ErrorDescription.Count > 3)
                required = failure.ErrorDescription[3];

            return FindProblem(errorcode, found, required);
        }

        private Problem FindProblem(string errorcode, string found, string required)
        {
            long requiredSpace = 0;
            long foundSpace = 0;
            long reclaimableDiskSpace = 0;

            DiskSpaceRequirements diskSpaceReq;

            switch (errorcode)
            {
                case "UPDATE_PRECHECK_FAILED_WRONG_SERVER_VERSION":
                    return new WrongServerVersion(this, Host);

                case "UPDATE_PRECHECK_FAILED_CONFLICT_PRESENT":
                    return new ConflictingUpdatePresent(this, found, Host);

                case "UPDATE_PRECHECK_FAILED_PREREQUISITE_MISSING":
                    return new PrerequisiteUpdateMissing(this, found, Host);

                case "PATCH_PRECHECK_FAILED_WRONG_SERVER_VERSION":
                    return new WrongServerVersion(this, required, Host);

                case "PATCH_PRECHECK_FAILED_OUT_OF_SPACE":
                    System.Diagnostics.Trace.Assert(Helpers.CreamOrGreater(Host.Connection));  // If not Cream or greater, we shouldn't get this error
                    System.Diagnostics.Trace.Assert(!Helpers.ElyOrGreater(Host.Connection));   // If Ely or greater, we shouldn't get this error

                    long.TryParse(found, out foundSpace);
                    long.TryParse(required, out requiredSpace);
                    // get reclaimable disk space (excluding current patch)
                    try
                    {
                        var args = new Dictionary<string, string> { { "exclude", Patch.uuid } };
                        var resultReclaimable = Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "disk-space", "get_reclaimable_disk_space", args);
                        reclaimableDiskSpace = Convert.ToInt64(resultReclaimable);
                    }
                    catch (Failure failure)
                    {
                        log.WarnFormat("Plugin call disk-space.get_reclaimable_disk_space on {0} failed with {1}", Host.Name, failure.Message);
                    }

                    diskSpaceReq = new DiskSpaceRequirements(DiskSpaceRequirements.OperationTypes.install, Host, Patch.Name, requiredSpace, foundSpace, reclaimableDiskSpace);

                    return new HostOutOfSpaceProblem(this, Host, Patch, diskSpaceReq);

                case "UPDATE_PRECHECK_FAILED_OUT_OF_SPACE":
                    System.Diagnostics.Trace.Assert(Helpers.ElyOrGreater(Host.Connection));  // If not Ely or greater, we shouldn't get this error
                    long.TryParse(found, out foundSpace);
                    long.TryParse(required, out requiredSpace);

                    diskSpaceReq = new DiskSpaceRequirements(DiskSpaceRequirements.OperationTypes.install, Host, Update.Name, requiredSpace, foundSpace, 0);

                    return new HostOutOfSpaceProblem(this, Host, Update, diskSpaceReq);

                case "OUT_OF_SPACE":
                    if (Helpers.CreamOrGreater(Host.Connection) && (Patch != null || Update != null))
                    {
                        var action = Patch != null
                            ? new GetDiskSpaceRequirementsAction(Host, Patch, true)
                            : new GetDiskSpaceRequirementsAction(Host, Update.Name, Update.installation_size, true);
                        try
                        {
                            action.RunExternal(action.Session);
                        }
                        catch
                        {
                            log.WarnFormat("Could not get disk space requirements");
                        }
                        if (action.Succeeded)
                            return Patch != null
                                ? new HostOutOfSpaceProblem(this, Host, Patch, action.DiskSpaceRequirements)
                                : new HostOutOfSpaceProblem(this, Host, Update, action.DiskSpaceRequirements);
                    }
                    break;
            }
            return null;
        }
    }
}


text:
Configuration for a dense input feature in a sequence item.

To treat a sparse input as dense, provide `allow_missing=True`; otherwise,
the parse functions will fail on any examples missing this feature.

Fields:
  shape: Shape of input data.
  dtype: Data type of input.
  allow_missing: Whether to allow this feature to be missing from a feature
    list item.
- - -

#### `tf.FixedLenSequenceFeature.__getnewargs__()` {#FixedLenSequenceFeature.__getnewargs__}

Return self as a plain tuple.  Used by copy and pickle.

- - -

#### `tf.FixedLenSequenceFeature.__getstate__()` {#FixedLenSequenceFeature.__getstate__}

Exclude the OrderedDict from pickling

- - -

#### `tf.FixedLenSequenceFeature.__new__(_cls, shape, dtype, allow_missing=False)` {#FixedLenSequenceFeature.__new__}

Create new instance of FixedLenSequenceFeature(shape, dtype, allow_missing)

- - -

#### `tf.FixedLenSequenceFeature.__repr__()` {#FixedLenSequenceFeature.__repr__}

Return a nicely formatted representation string

- - -

#### `tf.FixedLenSequenceFeature.allow_missing` {#FixedLenSequenceFeature.allow_missing}

Alias for field number 2

- - -

#### `tf.FixedLenSequenceFeature.dtype` {#FixedLenSequenceFeature.dtype}

Alias for field number 1

- - -

#### `tf.FixedLenSequenceFeature.shape` {#FixedLenSequenceFeature.shape}

Alias for field number 0


text:
require 'fileutils'

module HerokuHook
  module Runner
    # Class for cleaning up after successful deploy
    class PostInstall < HerokuHook::Runner::Base
      def run(language)
        script_path = File.expand_path(
          File.join([File.dirname(__FILE__), '..', '..', '..', 'scripts', "#{language}.postinstall"])
        )
        [nil, File.exist?(script_path) ? system("#{script_path} #{app_path}") : true]
      end
    end
  end
end


text:
require 'rails_helper'

describe Campaign do
  describe '.default_campaign' do
    it 'returns a the default campaign' do
      expect(Campaign.default_campaign.slug).to eq(ENV['default_campaign'])
    end
    it 'returns another campaign if the default one is not found' do
      Campaign.destroy_all
      Campaign.create(title: 'Not the default one')
      expect(Campaign.default_campaign).to be_a(Campaign)
    end
  end

  describe 'association' do
    it { should have_many(:campaigns_courses) }
    it { should have_many(:campaigns_users) }
    it { should have_many(:question_group_conditionals) }
    it { should have_many(:rapidfire_question_groups).through(:question_group_conditionals) }
    it { should have_many(:articles_courses) }
  end

  describe 'active campaign' do
    it 'should return campaigns without dates or where end date is in the future' do
      campaign = Campaign.create(
        title: 'My awesome 2010 campaign',
        start: Date.civil(2010, 1, 10),
        end: Date.civil(2010, 2, 10)
      )
      campaign2 = Campaign.create(
        title: 'My awesome 2050 campaign',
        start: Date.civil(2050, 1, 10),
        end: Date.civil(2050, 2, 10)
      )
      campaign3 = Campaign.create(
        title: 'My awesome early century campaign',
        start: Date.civil(2010, 1, 10),
        end: Date.civil(2040, 2, 10)
      )
      campaign4 = Campaign.create(title: 'My awesome campaign')
      expect(Campaign.active.collect(&:id)).to_not include(campaign.id)
      expect(Campaign.active.collect(&:id)).to include(campaign2.id)
      expect(Campaign.active.collect(&:id)).to include(campaign3.id)
      expect(Campaign.active.collect(&:id)).to include(campaign4.id)
    end
  end

  describe 'slug' do
    it 'creates a slug for the campaign based on the title' do
      campaign = Campaign.create(title: 'My awesome 2016 campaign')
      expect(campaign.slug).to eq('my_awesome_2016_campaign')
    end
    it 'handles non-ascii campaign titles' do
      title = 'Карыстальнік Група Беларусь 2016'
      campaign = Campaign.create(title: title)
      expect(campaign.slug).to eq('карыстальнік_група_беларусь_2016')
    end
  end

  describe 'date validation' do
    let(:campaign) { create(:campaign) }

    it 'should convert date-like strings to date object and save them' do
      campaign.start = '2016-01-10'
      campaign.end = '20160210'
      expect(campaign.valid?).to eq(true)
      expect(campaign.start.to_date).to eq(Date.civil(2016, 1, 10))
      expect(campaign.end.to_date).to eq(Date.civil(2016, 2, 10))
    end

    it 'should add an error if a date string is invalid' do
      campaign.start = '2016-01-10'
      campaign.end = 'not a valid date'
      expect(campaign.valid?).to eq(false)
      # retains attempted value that was valid
      expect(campaign.start.to_date).to eq(Date.civil(2016, 1, 10))
      expect(campaign.errors.messages.keys).to include(:end)
    end

    it 'should add an error if one date is blank but the other is valid' do
      campaign.start = '2016-01-10'
      campaign.end = ''
      expect(campaign.valid?).to eq(false)
      expect(campaign.start.to_date).to eq(Date.civil(2016, 1, 10))
      expect(campaign.errors.messages.keys).to include(:end)
      expect(campaign.reload.start).to eq(nil)
    end

    it 'should add an error if the start date is after the end date' do
      campaign.start = '2016-02-10'
      campaign.end = '2016-01-10'
      expect(campaign.valid?).to eq(false)
      expect(campaign.errors.messages[:start])
        .to include(I18n.t('error.start_date_before_end_date'))
    end

    it 'should allow the date values to be changed to nil' do
      campaign.start = '2016-02-10'
      campaign.end = '2016-01-10'
      campaign.save
      campaign.start = nil
      campaign.end = '' # blank should be converted to nil
      expect(campaign.valid?).to eq(true)
      expect(campaign.start).to eq(nil)
      expect(campaign.end).to eq(nil)
    end

    it 'should set the default times for the dates' do
      campaign.start = '2016-01-10'
      campaign.end = '2016-02-10'
      campaign.save
      expect(campaign.start).to eq(Time.new(2016, 1, 10, 0, 0, 0, '+00:00'))
      expect(campaign.end).to eq(Time.new(2016, 2, 10, 23, 59, 59, '+00:00'))
    end
  end
end


text:
<ot-view>

Change password

            <form class="form-horizontal" ng-submit="changePassword()">

                    Old password

                        <input id="old-password" class="form-control" ng-model="passwordForm.oldPassword"
                               type="password" required>

                    New password

                        <input id="new-password" class="form-control" ng-model="passwordForm.newPassword"
                               type="password" required>

                    Confirm password

                        <input id="confirm-password" class="form-control" ng-model="passwordForm.confirmPassword"
                               type="password" required>

                        <button id="password-submit" type="submit" class="btn btn-primary" ng-disabled="passwordForm.changing">
                            <ot-loading ng-show="passwordForm.changing"></ot-loading>
                            Submit
                        </button>

                            Password confirmation is not correct.

                            Password changed successfully.

                            {{passwordForm.error}}

            </form>

API token

            <form class="form-horizontal">

                    Token

                            <input id="token" class="form-control" ng-model="token.token.value" type="text" readonly>

                            <button class="btn btn-default"
                                    id="token-copy"
                                    title="Copy API token"
                                    ng-click="copyToken()"
                                    ng-disabled="!token.token.value">

                            </button>
                            <button class="btn btn-warning"
                                    id="token-generate"
                                    ng-if="localUser._changeToken"
                                    ng-click="changeToken()"
                                    title="Regenerate token">

                            </button>
                            <button class="btn btn-danger"
                                    id="token-revoke"
                                    ng-if="localUser._revokeToken"
                                    ng-click="revokeToken()"
                                    title="Revoke token">

                            </button>

                    Created on

                            {{ token.token.creation | date:'fullDate'}}
                            {{ token.token.creation | date:'mediumTime'}}

                    Valid until

                            {{ token.token.validUntil | date:'fullDate'}}
                            {{ token.token.validUntil | date:'mediumTime'}}

                                Valid

                                Expired

                            Does not expire

            </form>

</ot-view>


text:
require('newrelic');

var express         = require('express');

var env             = process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var app             = express();

var config          = require('./server/config/config')[env];

var user = process.env.DB_ID;
var pass = process.env.DB_KEY;

//if (env === 'development' || env === 'local') {
//    var user = process.env.USER_DEV_ID;
//    var pass = process.env.USER_DEV_KEY;
//} else if (env === 'production') {
//    var user = process.env.USER_PROD_ID;
//    var pass = process.env.USER_PROD_KEY;
//}

require('./server/config/express')(app, config);

require('./server/config/mongoose')(config, user, pass, env);

require('./server/config/passport')();

require('./server/config/routes')(app);

app.listen(config.port);
console.log('Listening on port ' + config.port + '...');


text:
title: More About Docker Containers
---

## More Commands to manage Docker Containers

* Command to list Running Containers

```
docker conatiner ls

```

* Command to list all the containers (including the stopped containers)

```
docker container ls -a

```

* Command to execute command in the container

```
docker exec -it <container name> run --rm <command>

```

* Command to view logs of the container

```
docker logs <container name>

```

* Command to remove all stopped containers

```
docker container prune

```

#### More Information
- [More commands for docker containers]
(https://docs.docker.com/engine/reference/commandline/container/)


text:
using UnityEditor;
using System.IO;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;

class PerformBuild
{
    private static string BUILD_LOCATION = "+buildlocation";

    static string GetBuildLocation(BuildTarget buildTarget)
    {
        string[] args = System.Environment.GetCommandLineArgs();
        int indexOfBuildLocation = System.Array.IndexOf(args, BUILD_LOCATION);
        if (indexOfBuildLocation >= 0)
        {
            indexOfBuildLocation++;
            Debug.Log(string.Format("Build Location for {0} set to {1}", buildTarget.ToString(), args[indexOfBuildLocation]));
            return args[indexOfBuildLocation];
        }
        else
        {
            Debug.Log(string.Format("Build Location for {0} not set. Defaulting to {1}", buildTarget.ToString(),
                                    EditorUserBuildSettings.GetBuildLocation(buildTarget)));
            return EditorUserBuildSettings.GetBuildLocation(buildTarget);
        }
    }

    static string[] GetBuildScenes()
    {
        List<string> names = new List<string>();

        foreach (EditorBuildSettingsScene e in EditorBuildSettings.scenes)
        {
            if (e == null)
                continue;

            if (e.enabled)
                names.Add(e.path);
        }
        return names.ToArray();
    }

    [UnityEditor.MenuItem("Perform Build/Android Command Line Build")]
    static void CommandLineBuildAndroid()
    {
        Debug.Log("Command line build android version\n------------------\n------------------");

        string[] scenes = GetBuildScenes();
        string path = GetBuildLocation(BuildTarget.Android);
        if (scenes == null || scenes.Length == 0 || path == null)
            return;

        Debug.Log(string.Format("Path: \"{0}\"", path));
        for (int i = 0; i < scenes.Length; ++i)
        {
            Debug.Log(string.Format("Scene[{0}]: \"{1}\"", i, scenes[i]));
        }

        Debug.Log(string.Format("Creating Directory \"{0}\" if it does not exist", path));
        (new FileInfo(path)).Directory.Create();

        Debug.Log(string.Format("Switching Build Target to {0}", "Android"));
        EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);

        // automatically set build system to internal, as gradle is not working (see #882)
        //EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Internal;

        Debug.Log("Starting Android Build!");
        BuildPipeline.BuildPlayer(scenes, path, BuildTarget.Android, BuildOptions.None);
    }
}


text:
"""
Manages a container: loads data, adds/deletes elements, saves data.
"""
import os

def load(file_name):
    """
    Creates and loads a new list of data (from a file).

    :param file_name: Basename of the file.
    :return: List of data.
    """
    data = []
    file_path = get_full_path(file_name)

    if os.path.exists(file_path):
        print('... loading safe list from: ' + file_path + '\n')
        with open(file_path) as stream_from_file:
            for element in stream_from_file.readlines():
                data.append(element.rstrip())

    return data

def save(file_name, data):
    """
    Saves the data from the list into a file.

    :param file_name: Basename of the file.
    :param data: List of data.
    """
    file_path = get_full_path(file_name)
    print('... saving to: ' + file_path)

    with open(file_path, 'w') as stream_to_file:
        for element in data:
            stream_to_file.write(element + '\n')

def get_full_path(file_name):
    file_path = os.path.abspath(os.path.join('.', 'containers', file_name + '.cont'))

    return file_path

def add_element(element, data):
    """
    Adds an element to the list of data.

    :param element: String to be added.
    :param data: List of data.
    """
    data.append(element)

def delete_element(index, data):
    """
    Deletes an element from the list of data.

    :param index: Index of the element to be deleted.
    :param data: List of data.
    """
    del data[index - 1]


text:
//
//  ISO8601DateFormatterValueTransformer.h
//  RestKit
//
//  Created by Blake Watters on 9/11/13.
//  Copyright (c) 2013 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <RKValueTransformers/RKValueTransformers.h>
#import "ISO8601DateFormatter.h"

/**
 The `RKValueTransformers` category extends ISO8601DateFormatter to support the `RKValueTransforming` interface, making it usable with the RestKit value transformation architecture.
 */
@interface ISO8601DateFormatter (RKValueTransformers) <RKValueTransforming>

/**
 Returns an ISO 8601 date formatter configured to strictly parse times into `NSDate` instances with the UTC time zone and `en_US_POSIX` locale.
 */
+ (instancetype)defaultISO8601DateFormatter;

@end


text:
typedef struct SPoint3D
{
	GLfloat x;
	GLfloat y;
	GLfloat z;
} Point3D;

@interface Tools : NSObject {

}

+(void) loadTexture:(NSString*)_path id:(GLuint*) _id;
+(void) loadTextureWithImage:(UIImage*)_image id:(GLuint*) _id;

+(Boolean) poinSphereCollision:(Point3D) _point center:(Point3D) _center radius:(GLfloat)_radius;

@end


text:
package com.worescloud.workdesk.storage.impl.dsl;

import com.worescloud.workdesk.storage.StorageQueryBuilder.StorageQuery;
import com.worescloud.workdesk.storage.exception.StorageException;

import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public interface StorageTestDefinition {

	interface GivenType<T> {
		Type<T> givenType(Class<T> type) throws StorageException;
	}

	interface DoAction<T> {
		ExpectedSucceed<T> save(T entity, Supplier keySupplier);
		ExpectedSucceed<T> saveOrUpdate(T entity, Supplier keySupplier);
		ExpectedSucceed<T> saveOrUpdate(T entity, Set<String> attributes, Supplier keySupplier);
		ExpectedSucceed<T> update(T entity, Set<String> attributes);
		ExpectedSucceed<T> delete(Object key);
		ExpectedMatch<Optional<T>> find(Object key);
		ExpectedMatch<T> query(Function<StorageQuery<T>, ?> function);
	}

	interface Type<T> extends DoAction<T> {
	}

	interface ExpectedSucceed<T> extends DoAction<T> {
		void success() throws StorageException;
	}

	interface ExpectedMatch<T> {
		<R> void match(Predicate<R> r) throws StorageException;
	}
}