text:
(function(venn) {
    "use strict";
    /** given a list of set objects, and their corresponding overlaps.
    updates the (x, y, radius) attribute on each set such that their positions
    roughly correspond to the desired overlaps */
    venn.venn = function(areas, parameters) {
        parameters = parameters || {};
        parameters.maxIterations = parameters.maxIterations || 500;
        var lossFunction = parameters.lossFunction || venn.lossFunction;
        var initialLayout = parameters.initialLayout || venn.greedyLayout;
        var fmin = parameters.fmin || venn.fmin;

        // initial layout is done greedily
        var circles = initialLayout(areas);

        // transform x/y coordinates to a vector to optimize
        var initial = [], setids = [], setid;
        for (setid in circles) {
            if (circles.hasOwnProperty(setid)) {
                initial.push(circles[setid].x);
                initial.push(circles[setid].y);
                setids.push(setid);
            }
        }

        // optimize initial layout from our loss function
        var totalFunctionCalls = 0;
        var solution = fmin(
            function(values) {
                totalFunctionCalls += 1;
                var current = {};
                for (var i = 0; i < setids.length; ++i) {
                    var setid = setids[i];
                    current[setid] = {x: values[2 * i],
                                      y: values[2 * i + 1],
                                      radius : circles[setid].radius,
                                     // size : circles[setid].size
                                     };
                }
                return lossFunction(current, areas);
            },
            initial,
            parameters);

        // transform solution vector back to x/y points
        var positions = solution.solution;
        for (var i = 0; i < setids.length; ++i) {
            setid = setids[i];
            circles[setid].x = positions[2 * i];
            circles[setid].y = positions[2 * i + 1];
        }

        return circles;
    };

    var SMALL = 1e-10;

    /** Returns the distance necessary for two circles of radius r1 + r2 to
    have the overlap area 'overlap' */
    venn.distanceFromIntersectArea = function(r1, r2, overlap) {
        // handle complete overlapped circles
        if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap + SMALL) {
            return Math.abs(r1 - r2);
        }

        return venn.bisect(function(distance) {
            return venn.circleOverlap(r1, r2, distance) - overlap;
        }, 0, r1 + r2);
    };

    /// gets a matrix of euclidean distances between all sets in venn diagram
    venn.getDistanceMatrix = function(areas, sets, setids) {
        // initialize an empty distance matrix between all the points
        var distances = [];
        for (var i = 0; i < sets.length; ++i) {
            distances.push([]);
            for (var j = 0; j < sets.length; ++j) {
                distances[i].push(0);
            }
        }

        // compute distances between all the points
        for (i = 0; i < areas.length; ++i) {
            var current = areas[i];
            if (current.sets.length !== 2) {
                continue;
            }

            var left = setids[current.sets[0]],
                right = setids[current.sets[1]],
                r1 = Math.sqrt(sets[left].size / Math.PI),
                r2 = Math.sqrt(sets[right].size / Math.PI),
                distance = venn.distanceFromIntersectArea(r1, r2, current.size);

            distances[left][right] = distances[right][left] = distance;
        }
        return distances;
    };

    /** Lays out a Venn diagram greedily, going from most overlapped sets to
    least overlapped, attempting to position each new set such that the
    overlapping areas to already positioned sets are basically right */
    venn.greedyLayout = function(areas) {
        // define a circle for each set
        var circles = {}, setOverlaps = {}, set;
        for (var i = 0; i < areas.length; ++i) {
            var area = areas[i];
            if (area.sets.length == 1) {
                set = area.sets[0];
                circles[set] = {x: 1e10, y: 1e10,
                                rowid: circles.length,
                                size: area.size,
                                radius: Math.sqrt(area.size / Math.PI)};
                setOverlaps[set] = [];
            }
        }
        areas = areas.filter(function(a) { return a.sets.length == 2; });

        // map each set to a list of all the other sets that overlap it
        for (i = 0; i < areas.length; ++i) {
            var current = areas[i];
            var weight = current.hasOwnProperty('weight') ? current.weight : 1.0;
            var left = current.sets[0], right = current.sets[1];

            // completely overlapped circles shouldn't be positioned early here
            if (current.size + SMALL >= Math.min(circles[left].size,
                                                 circles[right].size)) {
                weight = 0;
            }

            setOverlaps[left].push ({set:right, size:current.size, weight:weight});
            setOverlaps[right].push({set:left,  size:current.size, weight:weight});
        }

        // get list of most overlapped sets
        var mostOverlapped = [];
        for (set in setOverlaps) {
            if (setOverlaps.hasOwnProperty(set)) {
                var size = 0;
                for (i = 0; i < setOverlaps[set].length; ++i) {
                    size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
                }

                mostOverlapped.push({set: set, size:size});
            }
        }

        // sort by size desc
        function sortOrder(a,b) {
            return b.size - a.size;
        }
        mostOverlapped.sort(sortOrder);

        // keep track of what sets have been laid out
        var positioned = {};
        function isPositioned(element) {
            return element.set in positioned;
        }

        // adds a point to the output
        function positionSet(point, index) {
            circles[index].x = point.x;
            circles[index].y = point.y;
            positioned[index] = true;
        }

        // add most overlapped set at (0,0)
        positionSet({x: 0, y: 0}, mostOverlapped[0].set);

        // get distances between all points. TODO, necessary?
        // answer: probably not
        // var distances = venn.getDistanceMatrix(circles, areas);
        for (i = 1; i < mostOverlapped.length; ++i) {
            var setIndex = mostOverlapped[i].set,
                overlap = setOverlaps[setIndex].filter(isPositioned);
            set = circles[setIndex];
            overlap.sort(sortOrder);

            if (overlap.length === 0) {
                throw "Need overlap information for set " + JSON.stringify( set );
            }

            var points = [];
            for (var j = 0; j < overlap.length; ++j) {
                // get appropriate distance from most overlapped already added set
                var p1 = circles[overlap[j].set],
                    d1 = venn.distanceFromIntersectArea(set.radius, p1.radius,
                                                        overlap[j].size);

                // sample positions at 90 degrees for maximum aesthetics
                points.push({x : p1.x + d1, y : p1.y});
                points.push({x : p1.x - d1, y : p1.y});
                points.push({y : p1.y + d1, x : p1.x});
                points.push({y : p1.y - d1, x : p1.x});

                // if we have at least 2 overlaps, then figure out where the
                // set should be positioned analytically and try those too
                for (var k = j + 1; k < overlap.length; ++k) {
                    var p2 = circles[overlap[k].set],
                        d2 = venn.distanceFromIntersectArea(set.radius, p2.radius,
                                                            overlap[k].size);

                    var extraPoints = venn.circleCircleIntersection(
                        { x: p1.x, y: p1.y, radius: d1},
                        { x: p2.x, y: p2.y, radius: d2});

                    for (var l = 0; l < extraPoints.length; ++l) {
                        points.push(extraPoints[l]);
                    }
                }
            }

            // we have some candidate positions for the set, examine loss
            // at each position to figure out where to put it at
            var bestLoss = 1e50, bestPoint = points[0];
            for (j = 0; j < points.length; ++j) {
                circles[setIndex].x = points[j].x;
                circles[setIndex].y = points[j].y;
                var loss = venn.lossFunction(circles, areas);
                if (loss < bestLoss) {
                    bestLoss = loss;
                    bestPoint = points[j];
                }
            }

            positionSet(bestPoint, setIndex);
        }

        return circles;
    };

    /// Uses multidimensional scaling to approximate a first layout here
    venn.classicMDSLayout = function(areas) {
        // bidirectionally map sets to a rowid  (so we can create a matrix)
        var sets = [], setids = {};
        for (var i = 0; i < areas.length; ++i ) {
            var area = areas[i];
            if (area.sets.length == 1) {
                setids[area.sets[0]] = sets.length;
                sets.push(area);
            }
        }

        // get the distance matrix, and use to position sets
        var distances = venn.getDistanceMatrix(areas, sets, setids);
        var positions = mds.classic(distances);

        // translate rows back to (x,y,radius) coordinates
        var circles = {};
        for (i = 0; i < sets.length; ++i) {
            var set = sets[i];
            circles[set.sets[0]] = {
                x: positions[i][0],
                y: positions[i][1],
                radius:  Math.sqrt(set.size / Math.PI)
            };
        }
        return circles;
    };

    /** Given a bunch of sets, and the desired overlaps between these sets - computes
    the distance from the actual overlaps to the desired overlaps. Note that
    this method ignores overlaps of more than 2 circles */
    venn.lossFunction = function(sets, overlaps) {
        var output = 0;

        function getCircles(indices) {
            return indices.map(function(i) { return sets[i]; });
        }

        for (var i = 0; i < overlaps.length; ++i) {
            var area = overlaps[i], overlap;
            if (area.sets.length == 1) {
                continue;
            } else if (area.sets.length == 2) {
                var left = sets[area.sets[0]],
                    right = sets[area.sets[1]];
                overlap = venn.circleOverlap(left.radius, right.radius,
                                             venn.distance(left, right));
            } else {
                overlap = venn.intersectionArea(getCircles(area.sets));
            }

            var weight = area.hasOwnProperty('weight') ? area.weight : 1.0;
            output += weight * (overlap - area.size) * (overlap - area.size);
        }

        return output;
    };

    // orientates a bunch of circles to point in orientation
    function orientateCircles(circles, orientation) {
        // sort circles by size
        circles.sort(function (a, b) { return b.radius - a.radius; });

        var i;
        // shift circles so largest circle is at (0, 0)
        if (circles.length > 0) {
            var largestX = circles[0].x,
                largestY = circles[0].y;

            for (i = 0; i < circles.length; ++i) {
                circles[i].x -= largestX;
                circles[i].y -= largestY;
            }
        }

        // rotate circles so that second largest is at an angle of 'orientation'
        // from largest
        if (circles.length > 1) {
            var rotation = Math.atan2(circles[1].x, circles[1].y) - orientation,
                c = Math.cos(rotation),
                s = Math.sin(rotation), x, y;

            for (i = 0; i < circles.length; ++i) {
                x = circles[i].x;
                y = circles[i].y;
                circles[i].x = c * x - s * y;
                circles[i].y = s * x + c * y;
            }
        }

        // mirror solution if third solution is above plane specified by
        // first two circles
        if (circles.length > 2) {
            var angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
            while (angle < 0) { angle += 2* Math.PI; }
            while (angle > 2*Math.PI) { angle -= 2* Math.PI; }
            if (angle > Math.PI) {
                var slope = circles[1].y / (1e-10 + circles[1].x);
                for (i = 0; i < circles.length; ++i) {
                    var d = (circles[i].x + slope * circles[i].y) / (1 + slope*slope);
                    circles[i].x = 2 * d - circles[i].x;
                    circles[i].y = 2 * d * slope - circles[i].y;
                }
            }
        }
    }

    venn.disjointCluster = function(circles) {
        // union-find clustering to get disjoint sets
        circles.map(function(circle) { circle.parent = circle; });

        // path compression step in union find
        function find(circle) {
            if (circle.parent !== circle) {
                circle.parent = find(circle.parent);
            }
            return circle.parent;
        }

        function union(x, y) {
            var xRoot = find(x), yRoot = find(y);
            xRoot.parent = yRoot;
        }

        // get the union of all overlapping sets
        for (var i = 0; i < circles.length; ++i) {
            for (var j = i + 1; j < circles.length; ++j) {
                var maxDistance = circles[i].radius + circles[j].radius;
                if (venn.distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
                    union(circles[j], circles[i]);
                }
            }
        }

        // find all the disjoint clusters and group them together
        var disjointClusters = {}, setid;
        for (i = 0; i < circles.length; ++i) {
            setid = find(circles[i]).parent.setid;
            if (!(setid in disjointClusters)) {
                disjointClusters[setid] = [];
            }
            disjointClusters[setid].push(circles[i]);
        }

        // cleanup bookkeeping
        circles.map(function(circle) { delete circle.parent; });

        // return in more usable form
        var ret = [];
        for (setid in disjointClusters) {
            if (disjointClusters.hasOwnProperty(setid)) {
                ret.push(disjointClusters[setid]);
            }
        }
        return ret;
    };

    function getBoundingBox(circles) {
        var minMax = function(d) {
            var hi = Math.max.apply(null, circles.map(
                                    function(c) { return c[d] + c.radius; } )),
                lo = Math.min.apply(null, circles.map(
                                    function(c) { return c[d] - c.radius;} ));
            return {max:hi, min:lo};
        };

        return {xRange: minMax('x'), yRange: minMax('y')};
    }

    venn.normalizeSolution = function(solution, orientation) {
        orientation = orientation || Math.PI/2;

        // work with a list instead of a dictionary, and take a copy so we
        // don't mutate input
        var circles = [], i, setid;
        for (setid in solution) {
            if (solution.hasOwnProperty(setid)) {
                var previous = solution[setid];
                circles.push({x: previous.x,
                              y: previous.y,
                              radius: previous.radius,
                              setid: setid});
            }
        }

        // get all the disjoint clusters
        var clusters = venn.disjointCluster(circles);

        // orientate all disjoint sets, get sizes
        for (i = 0; i < clusters.length; ++i) {
            orientateCircles(clusters[i], orientation);
            var bounds = getBoundingBox(clusters[i]);
            clusters[i].size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
            clusters[i].bounds = bounds;
        }
        clusters.sort(function(a, b) { return b.size - a.size; });

        // orientate the largest at 0,0, and get the bounds
        circles = clusters[0];
        var returnBounds = circles.bounds;

        var spacing = (returnBounds.xRange.max - returnBounds.xRange.min)/50;

        function addCluster(cluster, right, bottom) {
            if (!cluster) return;

            var bounds = cluster.bounds, xOffset, yOffset, centreing;

            if (right) {
                xOffset = returnBounds.xRange.max  - bounds.xRange.min + spacing;
            } else {
                xOffset = returnBounds.xRange.max  - bounds.xRange.max - spacing;
                centreing = (bounds.xRange.max - bounds.xRange.min) / 2 -
                            (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
                if (centreing < 0) xOffset += centreing;
            }

            if (bottom) {
                yOffset = returnBounds.yRange.max  - bounds.yRange.min + spacing;
            } else {
                yOffset = returnBounds.yRange.max  - bounds.yRange.max - spacing;
                centreing = (bounds.yRange.max - bounds.yRange.min) / 2 -
                            (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
                if (centreing < 0) yOffset += centreing;
            }

            for (var j = 0; j < cluster.length; ++j) {
                cluster[j].x += xOffset;
                cluster[j].y += yOffset;
                circles.push(cluster[j]);
            }
        }

        var index = 1;
        while (index < clusters.length) {
            addCluster(clusters[index], true, false);
            addCluster(clusters[index+1], false, true);
            addCluster(clusters[index+2], true, true);
            index += 3;

            // have one cluster (in top left). lay out next three relative
            // to it in a grid
            returnBounds = getBoundingBox(circles);
        }

        // convert back to solution form
        var ret = {};
        for (i = 0; i < circles.length; ++i) {
            ret[circles[i].setid] = circles[i];
        }
        return ret;
    };

    /** Scales a solution from venn.venn or venn.greedyLayout such that it fits in
    a rectangle of width/height - with padding around the borders. also
    centers the diagram in the available space at the same time */
    venn.scaleSolution = function(solution, width, height, padding) {
        var circles = [], setids = [];
        for (var setid in solution) {
            if (solution.hasOwnProperty(setid)) {
                setids.push(setid);
                circles.push(solution[setid]);
            }
        }

        width -= 2*padding;
        height -= 2*padding;

        var bounds = getBoundingBox(circles),
            xRange = bounds.xRange,
            yRange = bounds.yRange,
            xScaling = width  / (xRange.max - xRange.min),
            yScaling = height / (yRange.max - yRange.min),
            scaling = Math.min(yScaling, xScaling),

            // while we're at it, center the diagram too
            xOffset = (width -  (xRange.max - xRange.min) * scaling) / 2,
            yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;

        var scaled = {};
        for (var i = 0; i < circles.length; ++i) {
            var circle = circles[i];
            scaled[setids[i]] = {
                radius: scaling * circle.radius,
                x: padding + xOffset + (circle.x - xRange.min) * scaling,
                y: padding + yOffset + (circle.y - yRange.min) * scaling,
            };
        }

        return scaled;
    };
})(venn);


text:
package io.gatekeeper.cli.command;

import io.gatekeeper.InvalidConfigurationException;
import io.gatekeeper.cli.AbstractCommandWithConfiguration;
import io.gatekeeper.cli.Input;
import io.gatekeeper.cli.Output;
import io.gatekeeper.configuration.Configuration;
import io.gatekeeper.node.Node;

public class AgentCommand extends AbstractCommandWithConfiguration {

    @Override
    public void run(Input input, Output output) {
        Configuration configuration;

        try {
            configuration = getConfiguration(input);
        } catch (InvalidConfigurationException e) {
            output.println("Could not load configuration");
            output.println(e.getMessage());

            return;
        } catch (Exception e) {
            output.println("Could not load configuration");

            return;
        }

        Node node = new Node(configuration);

        node.start().join();
    }

    @Override
    public void configure() {
        super.configure();

        this.setName("agent");
        this.setDescription("starts and runs the gatekeeper agent");
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

# include "../../ref-countable.hh"
# include "../../stream/stream.hh"
# include "../../string-ref.hh"
# include "../../intrusive-slist.hh"

namespace mimosa
{
  namespace tpl
  {
    class AbstractValue;

    namespace ast
    {
      class Node
      {
      public:
        virtual ~Node() {}

        virtual void execute(stream::Stream::Ptr   stream,
                             const AbstractValue & value) const = 0;

        virtual void addChild(Node * /*node*/) {}
        virtual StringRef var() const { return "(none)"; }

        typedef IntrusiveSlistHook<Node *> hook_type;

        hook_type hook_;
        uint16_t  line_;
        uint16_t  col_;

        typedef IntrusiveSlist<Node, Node *, &Node::hook_> nodes_type;
      };
    }
  }
}


text:
package oceanbasepro

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// CpuInDescribeTenant is a nested struct in oceanbasepro response
type CpuInDescribeTenant struct {
	UsedCpu  float64 `json:"UsedCpu" xml:"UsedCpu"`
	TotalCpu float64 `json:"TotalCpu" xml:"TotalCpu"`
	UnitCpu  float64 `json:"UnitCpu" xml:"UnitCpu"`
}


text:
package com.cloudwick.hadoop.MultiPath;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class MultiPathMapper2 extends Mapper<LongWritable, Text, Text, Text> {
	@Override
	protected void map(LongWritable key, Text value,
			Mapper<LongWritable, Text, Text, Text>.Context context)
			throws IOException, InterruptedException {
		context.write(new Text("SecondMap"), value);
	}
}


text:
package com.morgan.server.game;

import com.google.common.collect.ImmutableSet;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.morgan.server.game.modules.GamePortals;
import com.morgan.shared.common.BackendException;
import com.morgan.shared.game.GameService;
import com.morgan.shared.game.modules.GameDescriptor;

/**
 * Default implementation of the {@link GameService} service interface.
 *
 * @author mark@mark-morgan.net (Mark Morgan)
 */
@Singleton
class DefaultGameService extends RemoteServiceServlet implements GameService {

  static final long serialVersionUID = 1L;

  private final GamePortals gamePortals;
  private final GamePortalToGameDescriptorFunction portalToDescriptionFunction;

  @Inject DefaultGameService(GamePortals gamePortals,
      GamePortalToGameDescriptorFunction portalToDescriptionFunction) {
    this.gamePortals = gamePortals;
    this.portalToDescriptionFunction = portalToDescriptionFunction;
  }

  @Override public ImmutableSet<GameDescriptor> getAllGames() throws BackendException {
    return ImmutableSet.copyOf(
        gamePortals.getPortalsMap().values().stream()
            .map(portalToDescriptionFunction)
            .iterator());
  }
}


text:
layout: home
title: Posts
comments: true
permalink: /posts/
---


text:
package redis.clients.jedis;

public interface ProtocolCommand {

  byte[] getRaw();

}


text:
package fr.laas.fape.planning.core.planning.search.flaws.flaws;

import fr.laas.fape.anml.model.concrete.VarRef;
import fr.laas.fape.planning.core.planning.planner.Planner;
import fr.laas.fape.planning.core.planning.search.flaws.resolvers.Resolver;
import fr.laas.fape.planning.core.planning.search.flaws.resolvers.VarBinding;
import fr.laas.fape.planning.core.planning.states.PartialPlan;

import java.util.LinkedList;
import java.util.List;

/**
 * A variable that is not binded (i.e. domain contains more than one value)
 */
public class UnboundVariable extends Flaw {

    public final VarRef var;

    public UnboundVariable(VarRef v) {
        this.var = v;
    }

    /**
     * Here the number of resolvers is the size of the domain.
     * Hence we lazily return that without creating the resolvers themselves.
     */
    @Override
    public int getNumResolvers(PartialPlan plan, Planner planner) {
        if(resolvers != null)
            return resolvers.size();
        else
            return plan.domainSizeOf(var);
    }

    @Override
    public List<Resolver> getResolvers(PartialPlan plan, Planner planner) {
        if(resolvers != null)
            return resolvers;

        resolvers = new LinkedList<>();
         for (String value : plan.domainOf(var)) {
            resolvers.add(new VarBinding(var, value));
        }

        return resolvers;
    }

    @Override
    public int compareTo(Flaw o) {
        assert o instanceof UnboundVariable;
        return ((UnboundVariable) o).var.id() - var.id();
    }
}


text:
<?php

namespace VirtualPersistAPI\VirtualPersistBundle\Tests\Controller;

use VirtualPersistAPI\VirtualPersistBundle\Tests\TestCases\AppFixtureTestCase;
use VirtualPersistAPI\VirtualPersistBundle\Tests\TestCases\AppFixtureTestCaseInterface;
use VirtualPersistAPI\VirtualPersistBundle\DataFixtures\ORM\LoadAPIControllerTestData;

/**
 * Functional tests for the VirtualPersistAPI controller.
 *
 * These tests are against a fixture, set up in AppFixtureTestCase.
 *
 * Note that we assume FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
 * is always a bad UUID, and that 00000000-0000-0000-0000-000000000000
 * is good.
 *
 * @TODO: test authentication.
 * @todo: Re-enable this test. Turned it off because I don't fully understand
 *        user auth in symfony.
 */
class APIControllerFixturePathTest extends AppFixtureTestCase implements AppFixtureTestCaseInterface {

  public static function getFixtureClass() {
    return 'VirtualPersistAPI\VirtualPersistBundle\DataFixtures\ORM\LoadAPIControllerTestData';
  }

  /**
   * Data provider for paths that should result in 200
   */
  public function goodPathDataProvider() {
    return array(
      array(
        '/api/00000000-0000-0000-0000-000000000000/extantCategory/extantKey',
      ),
      array(
        '/api/timestamp/00000000-0000-0000-0000-000000000000/extantCategory/extantKey',
      ),
      array(
        '/api/categories/00000000-0000-0000-0000-000000000000',
      ),
      array(
        '/api/keys/00000000-0000-0000-0000-000000000000/extantCategory',
      ),
      array(
        '/api/user/00000000-0000-0000-0000-000000000000',
      ),
    );
  }

  /**
   * Data provider for paths that should result in 404
   *
   * User EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE should exist, but is blocked.
   */
  public function blockedUserDataProvider() {
    return array(
      array(
        '/api/EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE/extantCategory/extantKey',
      ),
      array(
        '/api/categories/EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE',
      ),
      array(
        '/api/keys/EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE/extantCategory',
      ),
      array(
        '/api/user/EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE',
      ),
    );
  }

  /**
   * @dataProvider goodPathDataProvider
   * @TODO: Once the authentication system is in place,
   * this test should result in 401 or 500.
   */
  public function testPaths200($path = 'verybadpath') {
    // We assume the controller's prefix is /api
    $client = static::createClientForApp();
    $crawler = $client->request('GET', $path);
    $status = $client->getResponse()->getStatusCode();
    $this->assertEquals(200, $status, "Status code: $status path: $path");
  }

  /**
   * @dataProvider blockedUserDataProvider
   *
   * This is a test for whether non-authorized requests for blocked user's data
   * results in 404. It should.
   */
  public function testPaths404($path = '') {
    // We assume the controller's prefix is /api
    $client = static::createClientForApp();
    $crawler = $client->request('GET', $path);
    $status = $client->getResponse()->getStatusCode();
    $this->assertEquals(404, $status, "Status code: $status path: $path");
  }

}


text:
@implementation CustomObj

@end


text:
package playtorrent.com.playtorrent;

import java.util.Collection;

/**
 * Check Validation Utils
 */

public class ValidationUtils {
    public static boolean isEmptyArray(byte[] bytes) {
        return bytes == null || bytes.length == 0;
    }

    public static boolean isEmptyList(Collection<?> list) {
        return list == null || list.isEmpty();
    }
}


text:
package models

import "gopkg.in/mgo.v2/bson"

type User struct {
	Id    bson.ObjectId `bson:"_id,omitempty"`
	Name  string
	Email string
	Pass  string
}


text:
#include <iostream>
#include <climits>
#include <cassert>
#include <folly/Memory.h>
#include <thrift/lib/cpp/transport/TBufferTransports.h>
#include <thrift/lib/cpp/protocol/TBinaryProtocol.h>
#include <thrift/test/gen-cpp/test_types.h>

#include <gtest/gtest.h>

using namespace std;
using namespace folly;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::transport::TTransportException;
using apache::thrift::protocol::TBinaryProtocol;

TEST(TMemoryBufferTest,  test_roundtrip) {
  auto strBuffer = make_shared<TMemoryBuffer>();
  auto binaryProtcol = make_shared<TBinaryProtocol>(strBuffer);

  test_cpp::struct1 a;
  a.a = 10;
  a.b = "holla back a";

  a.write(binaryProtcol.get());
  string serialized = strBuffer->getBufferAsString();

  auto strBuffer2 = make_shared<TMemoryBuffer>();
  auto binaryProtcol2 = make_shared<TBinaryProtocol>(strBuffer2);

  strBuffer2->resetBuffer((uint8_t*)serialized.data(), serialized.length());
  test_cpp::struct1 a2;
  a2.read(binaryProtcol2.get());

  EXPECT_EQ(a, a2);
}

TEST(TMemoryBufferTest,  test_copy) {
  auto str1 = make_unique<string>("abcd1234");
  TMemoryBuffer buf((uint8_t*)str1->data(), str1->length(), TMemoryBuffer::COPY);
  str1 = nullptr;

  string str3 = "wxyz", str4 = "6789";
  buf.readAppendToString(str3, 4);
  buf.readAppendToString(str4, std::numeric_limits<int>::max());

  EXPECT_EQ("wxyzabcd", str3);
  EXPECT_EQ("67891234", str4);
}

TEST(TMemoryBufferTest,  test_exceptions) {
  char data[] = "foo\0bar";

  TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
  string str = buf1.getBufferAsString();
  ASSERT_EQ(7, str.length());

  buf1.resetBuffer();
  EXPECT_THROW(buf1.write((const uint8_t*)"foo", 3), TTransportException);

  TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
  buf2.write((const uint8_t*)"bar", 3);
}


text:
package examples;

import javax.servlet.annotation.WebServlet;

import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

@SuppressWarnings("serial")
@WebServlet(name = "MyAdvanced Echo WebSocket Servlet", urlPatterns = { "/advecho" })
public class MyAdvancedEchoServlet extends WebSocketServlet
{
    @Override
    public void configure(WebSocketServletFactory factory)
    {
        // set a 10 second timeout
        factory.getPolicy().setIdleTimeout(10000);

        // set a custom WebSocket creator
        factory.setCreator(new MyAdvancedEchoCreator());
    }
}


text:
;(function(global, $){
    //es5 strict mode
    "use strict";

    var Updater = global.Updater = global.Updater || {};
    Updater.queries = [];

    // ----------------------------------------------------------------------

    Updater.init = function(){

        Updater.Wrap = $('#updater');

        Updater.uploadInit();
        Updater.processInit();
        Updater.settingsInit();

        cleanTempDirs();

        Updater.Wrap.delegate('.js-test_settings', 'click', testSettings);
        Updater.Wrap.delegate('.js-show_error', 'click', showError);

        // Send a test AJAX request
        Updater.TestAJAX(Updater.MCP_AJAX_URL);
        Updater.TestAJAX(Updater.ACT_URL);
    };

    // ----------------------------------------------------------------------

    Updater.generateRandomString = function() {
        return Math.random().toString(36).substring(2);
    };

    // ----------------------------------------------------------------------

    Updater.TestAJAX = function(action_url){
        var test_ajax = $('#test_ajax_error');

        $.ajax({url:action_url+'&task=test_ajax_call',
            dataType: 'json', type: 'POST',
            error: function(xhr, a, b){
                test_ajax.show();
                test_ajax.find('a.url').attr('href', action_url).html(action_url);
                test_ajax.find('.error textarea').html( global.btoa(xhr.responseText) );

                if (xhr.status === 0) {
                    test_ajax.find('.error .inner').html('Response Code: ' + xhr.status + '   Response Text: (Probably Cross-Domain AJAX Error)');
                }
                else if (xhr.status >= 200) {
                    test_ajax.find('.error .inner').html('Response Code: ' + xhr.status + '   Response Text: ' + xhr.statusText);
                }
            },
            success: function(rData){
                if (!rData) test_ajax.show();
            }
        });

    };

    //********************************************************************************* //

    function cleanTempDirs(){
        $.ajax({
            url: Updater.MCP_AJAX_URL+'&task=clean_temp_dirs',
            type: 'POST',
            data: {XID: EE.XID}
        });
    }

    // ----------------------------------------------------------------------

    function testSettings(e){
        e.preventDefault();
        var modal = $('#test_transfer_method');

        modal.css({width:'800px', 'margin-left': function () {
                return -($(this).width() / 2);
        }}).modal().find('.loading').show();
        modal.find('.wrapper').empty();

        $.post(Updater.MCP_AJAX_URL+'&task=test_transfer_method', {}, function(rData){
            modal.find('.loading').hide();
            modal.find('.wrapper').html(rData);
        });
    }

    // ----------------------------------------------------------------------

    function showError(e){
        e.preventDefault();
        var error_log = $('#error_log');
        var html = global.atob( $(e.target).closest('.error').find('textarea').val() ) ;

        error_log.slideDown();
        error_log.find('body').empty();

        $('html, body').stop().animate({
            scrollTop: error_log.offset().top
        }, 1000);

        $('').load(function(){
            $('#updater_error_iframe').contents().find('body').append(html);
        }).appendTo(error_log.find('.body'));
    }

    // ----------------------------------------------------------------------

}(window, jQuery));

// ----------------------------------------------------------------------

$(document).ready(function() {
    Updater.init();
});


text:
package io.cdap.directives.row;

import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.wrangler.api.Arguments;
import io.cdap.wrangler.api.Directive;
import io.cdap.wrangler.api.DirectiveExecutionException;
import io.cdap.wrangler.api.DirectiveParseException;
import io.cdap.wrangler.api.ExecutorContext;
import io.cdap.wrangler.api.Row;
import io.cdap.wrangler.api.annotations.Categories;
import io.cdap.wrangler.api.parser.Expression;
import io.cdap.wrangler.api.parser.TokenType;
import io.cdap.wrangler.api.parser.UsageDefinition;
import io.cdap.wrangler.expression.EL;
import io.cdap.wrangler.expression.ELContext;
import io.cdap.wrangler.expression.ELException;
import io.cdap.wrangler.expression.ELResult;

import java.util.List;

/**
 * A directive for erroring the processing if condition is set to true.
 */
@Plugin(type = Directive.TYPE)
@Name(Fail.NAME)
@Categories(categories = { "row", "data-quality"})
@Description("Fails when the condition is evaluated to true.")
public class Fail implements Directive {
  public static final String NAME = "fail";
  private String condition;
  private final EL el = new EL(new EL.DefaultFunctions());

  @Override
  public UsageDefinition define() {
    UsageDefinition.Builder builder = UsageDefinition.builder(NAME);
    builder.define("condition", TokenType.EXPRESSION);
    return builder.build();
  }

  @Override
  public void initialize(Arguments args) throws DirectiveParseException {
    Expression expression = args.value("condition");
    if (expression.value().isEmpty()) {
      throw new DirectiveParseException("No condition has been specified.");
    }
    condition = expression.value();
    try {
      el.compile(condition);
    } catch (ELException e) {
      throw new DirectiveParseException(e.getMessage());
    }
  }

  @Override
  public void destroy() {
    // no-op
  }

  @Override
  public List<Row> execute(List<Row> rows, ExecutorContext context)
    throws DirectiveExecutionException {
    for (Row row : rows) {
      // Move the fields from the row into the context.
      ELContext ctx = new ELContext(context);
      ctx.set("this", row);
      for (String var : el.variables()) {
        ctx.set(var, row.getValue(var));
      }

      // Execution of the script / expression based on the row data
      // mapped into context.
      try {
        ELResult result = el.execute(ctx);
        if (result.getBoolean()) {
          throw new DirectiveExecutionException(
            String.format("Condition '%s' evaluated to true. Terminating processing.", condition)
          );
        }
      } catch (ELException e) {
        throw new DirectiveExecutionException(e.getMessage());
      }
    }
    return rows;
  }
}


text:
@implementation BTCommunityElement

@end


text:
// Qt includes
#include <QApplication>
#include <QTimer>

// CTK includes
#include "ctkVTKDiscretizableColorTransferWidget.h"
#include "ctkVTKScalarsToColorsComboBox.h"
#include "vtkScalarsToColorsHistogramChart.h"

// VTK includes
#include <vtkDiscretizableColorTransferFunction.h>
#include <vtkNew.h>
#include <vtkPiecewiseFunction.h>
#include <vtkRTAnalyticSource.h>

//-----------------------------------------------------------------------------
int ctkVTKDiscretizableColorTransferWidgetTest1(int argc, char * argv[])
{
  QApplication app(argc, argv);

  ///Dummy presets
  vtkNew<vtkDiscretizableColorTransferFunction> dctf0;
  dctf0->AddRGBPoint(0.0, 0.0, 0.0, 1.0);
  dctf0->AddRGBPoint(255.0, 1.0, 0.0, 0.0);
  vtkNew<vtkPiecewiseFunction> pf0;
  pf0->AddPoint(0.0, 0.0);
  pf0->AddPoint(255.0, 1.0);
  dctf0->SetScalarOpacityFunction(pf0.Get());
  dctf0->EnableOpacityMappingOn();

  vtkNew<vtkDiscretizableColorTransferFunction> dctf1;
  dctf1->AddRGBPoint(0.0, 1.0, 1.0, 1.0);
  dctf1->AddRGBPoint(255.0, 0.0, 0.0, 0.0);
  vtkNew<vtkPiecewiseFunction> pf1;
  pf1->AddPoint(0.0, 0.0);
  pf1->AddPoint(255.0, 0.5);
  dctf1->SetScalarOpacityFunction(pf1.Get());
  dctf1->EnableOpacityMappingOn();

  vtkNew<vtkColorTransferFunction> ctf0;
  ctf0->AddRGBPoint(0.0, 1.0, 0.0, 1.0);
  ctf0->AddRGBPoint(255.0, 0.0, 1.0, 0.0);

  /// Create an image to test the widget histogram
  vtkNew<vtkRTAnalyticSource> imageSource;
  imageSource->SetWholeExtent(0, 9,
                              0, 9,
                              0, 9);

  /// Discretizable transfer function widget
  ctkVTKDiscretizableColorTransferWidget mWidget;
  mWidget.copyColorTransferFunction(dctf0.Get());
  mWidget.setHistogramConnection(imageSource->GetOutputPort());
  mWidget.setLeftAxisMode(vtkScalarsToColorsHistogramChart::MAXIMUM);
  mWidget.updateHistogram(true);
  mWidget.show();

  /// Add presets to the widget selector
  mWidget.scalarsToColorsSelector()->addScalarsToColors(dctf1.Get(), "White to Black");
  mWidget.scalarsToColorsSelector()->addScalarsToColors(ctf0.Get(), "Purple to Green");

  if (argc < 2 || QString(argv[1]) != "-I")
  {
    QTimer::singleShot(1000, &app, SLOT(quit()));
  }

  return app.exec();
}


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

shared_examples "connection_refused_returns_try" do
  before do
    stub_request(:any, "dash.scrapinghub.com").to_timeout
  end

  it "returns a Kleisli::Either::Left when host is down" do
    expect(jobs.send(action, args)).to be_a Kleisli::Either::Left
  end
end

shared_examples "bad_auth_returns_try" do |cassette|
  use_vcr_cassette cassette

  it "returns a Left when bad authentication is used" do
    js = jobs.send(action, args)
    expect(js).to be_a Kleisli::Either::Left
    expect(js.left.class).to eq HTTParty::Response
    expect(js.left.response).to be_a Net::HTTPForbidden
    expect(js.left['status']).to eq("error")
    expect(js.left["message"]).to match(/^Authentication failed$/)
  end
end

describe "jobs integration" do
  let(:api_key) { "XXX" }
  let(:jobs)    { Scrapinghub::Jobs.new(api_key: api_key) }

  describe "list" do
    let(:action)        { :list }
    let(:valid_project) { 1 }
    let(:args)          { {project: valid_project} }

    it_behaves_like "connection_refused_returns_try"
    it_behaves_like "bad_auth_returns_try", "jobs/list/bad_auth"

    context "project" do
      context "given a valid project ID" do
        use_vcr_cassette "jobs/list/project/valid"

        it "returns a Right" do
          expect(jobs.send(action, args)).to be_a Kleisli::Either::Right
        end
      end

      context "given an invalid / non-owned project ID" do
        use_vcr_cassette "jobs/list/project/invalid"
        let(:invalid_project) { 2 }
        let(:args)            { {project: invalid_project} }

        it "returns a Left" do
          expect(jobs.send(action, args)).to be_a Kleisli::Either::Left
        end
      end
    end

    context "job" do
      context "given a single job" do
        use_vcr_cassette "jobs/list/job/single"
        let(:job)  { "1/1/6" }
        let(:args) { {project: valid_project, job: job} }

        it "returns the job" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(1)
        end
      end

      context "given a list of multiple jobs" do
        use_vcr_cassette "jobs/list/job/multiple"
        let(:job)  { ["1/1/1", "1/1/2"] }
        let(:args) { {project: valid_project, job: job} }

        it "returns the jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(2)
        end
      end

      context "given an invalid/non-existent job" do
        use_vcr_cassette "jobs/list/job/invalid"
        let(:job)  { "1/1/123" }
        let(:args) { {project: valid_project, job: job} }

        it "returns no jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(0)
        end
      end
    end

    context "spider" do
      context "given a valid spider with ran jobs" do
        use_vcr_cassette "jobs/list/spider/valid"
        let(:spider) { "atlantic_firearms_crawl" }
        let(:args)   { {project: valid_project, spider: spider} }

        it "returns a Right with the list of spider jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(5)
          expect(js.fmap{|j| j["jobs"]}.fmap(&:size).right).to eq(5)
        end
      end

      context "given an invalid or not-ran spider" do
        use_vcr_cassette "jobs/list/spider/invalid"
        let(:spider) { "bar" }
        let(:args)   { {project: valid_project, spider: spider} }

        it "returns a Right with no results" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(0)
          expect(js.fmap{|j| j["jobs"]}.fmap(&:size).right).to eq(0)
        end
      end
    end

    context "state" do
      context "given 'finished' with completed jobs" do
        use_vcr_cassette "jobs/list/state/finished"
        let(:state) { "finished" }
        let(:args)  { {project: valid_project, state: state} }

        it "returns a Right with the list of spider jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(9)
          expect(js.fmap{|j| j["jobs"]}.fmap(&:size).right).to eq(9)
        end
      end

      context "given 'pending' without pending jobs" do
        use_vcr_cassette "jobs/list/state/pending"
        let(:state) { "pending" }
        let(:args)  { {project: valid_project, state: state} }

        it "returns a Right without any jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(0)
          expect(js.fmap{|j| j["jobs"]}.fmap(&:size).right).to eq(0)
        end
      end
    end

    context "has_tag" do
      context "given a single tag" do
        use_vcr_cassette "jobs/list/has_tag/single"
        let(:has_tag) { "foo" }
        let(:args)    { {project: valid_project, has_tag: has_tag} }

        it "returns jobs with that tag" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(2)
          js.fmap{|j| j["jobs"].map{|j| j["tags"]} }.right.each do |tags|
            expect(tags).to include(has_tag)
          end
        end
      end

      context "given a list of multiple tags" do
        use_vcr_cassette "jobs/list/has_tag/multiple"
        let(:has_tag) { ["foo", "bar"] }
        let(:args) { {project: valid_project, has_tag: has_tag} }

        it "returns all jobs with either tag" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(3)
          js.fmap{|j| j["jobs"].map{|j| j["tags"]} }.right.each do |tags|
            in_common = tags & has_tag
            expect(in_common).not_to be_empty
          end
        end
      end

      context "given an invalid/non-existent tag" do
        use_vcr_cassette "jobs/list/has_tag/invalid"
        let(:has_tag) { "baz" }
        let(:args) { {project: valid_project, has_tag: has_tag} }

        it "returns no jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(0)
        end
      end
    end

    context "lacks_tag" do
      context "given a single tag" do
        use_vcr_cassette "jobs/list/lacks_tag/single"
        let(:lacks_tag) { "foo" }
        let(:args)      { {project: valid_project, lacks_tag: lacks_tag} }

        it "returns jobs with that tag" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(7)
          js.fmap{|j| j["jobs"].map{|j| j["tags"]} }.right.each do |tags|
            expect(tags).not_to include(lacks_tag)
          end
        end
      end

      context "given a list of tags" do
        use_vcr_cassette "jobs/list/lacks_tag/multiple"
        let(:lacks_tag) { ["foo", "bar"] }
        let(:args)      { {project: valid_project, lacks_tag: lacks_tag} }

        it "returns all jobs without either tag" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(6)
          js.fmap{|j| j["jobs"].map{|j| j["tags"]} }.right.each do |tags|
            in_common = tags & lacks_tag
            expect(in_common).to be_empty
          end
        end
      end

      context "given an invalid/non-existent tag" do
        use_vcr_cassette "jobs/list/lacks_tag/invalid"
        let(:lacks_tag) { "baz" }
        let(:args) { {project: valid_project, lacks_tag: lacks_tag} }

        it "returns no jobs" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(9)
          js.fmap{|j| j["jobs"].map{|j| j["tags"]} }.right.each do |tags|
            expect(tags).not_to include(lacks_tag)
          end
        end
      end
    end

    context "count" do
      context "given 3" do
        use_vcr_cassette "jobs/list/count/3"
        let(:count) { 3 }
        let(:args)  { {project: valid_project, count: count} }

        it "returns 3 responses" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["total"]}.right).to eq(3)
        end
      end
    end
  end

  describe "schedule" do
    let(:action)        { :schedule }
    let(:valid_project) { 1 }
    let(:args)          { {project: valid_project, spider: "atlantic_firearms_crawl"} }

    it_behaves_like "connection_refused_returns_try"
    it_behaves_like "bad_auth_returns_try", "jobs/schedule/bad_auth"

    context "project" do
      context "given an invalid / non-owned project ID" do
        use_vcr_cassette "jobs/schedule/project/invalid"
        let(:invalid_project) { 2 }

        it "returns a Left" do
          js = jobs.send(action, args.merge(project: invalid_project))
          expect(js).to be_a Kleisli::Either::Left
          expect(js.left['status']).to eq("badrequest")
        end
      end
    end

    context "spider" do
      context "given minimal parameters" do
        use_vcr_cassette "jobs/schedule/spider/minimal"

        it "returns ok status and the created jobid" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["jobid"]}.right).to eq("1/1/11")
        end
      end

      context "when an instance of the spider is already running" do
        use_vcr_cassette "jobs/schedule/spider/already-running"

        it "returns ok status and the error message" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Left
          expect(js.left["status"]).to eq("error")
          expect(js.left["message"]).to match(/^Spider.*already scheduled$/)
        end
      end

      context "given an add_tag argument" do
        use_vcr_cassette "jobs/schedule/spider/add_tag"

        it "returns ok status and the created jobid" do
          js = jobs.send(action, args.merge(add_tag: "foo"))
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["jobid"]}.right).to eq("1/1/14")
        end
      end

      context "given a priority argument" do
        use_vcr_cassette "jobs/schedule/spider/priority"

        it "returns ok status and the created jobid" do
          js = jobs.send(action, args.merge(priority: 4))
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["jobid"]}.right).to eq("1/1/16")
        end
      end

      context "given an extra argument" do
        use_vcr_cassette "jobs/schedule/spider/extra"

        it "returns ok status and the created jobid" do
          js = jobs.send(action, args.merge(extra: {:"DOWNLOAD_DELAY" => "0.5"}))
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["jobid"]}.right).to eq("1/1/17")
        end
      end
    end
  end

  describe "delete" do
    let(:action)        { :delete }
    let(:valid_project) { 1 }
    let(:args)          { {project: valid_project, job: "#{valid_project}/1/7"} }

    it_behaves_like "connection_refused_returns_try"
    it_behaves_like "bad_auth_returns_try", "jobs/delete/bad_auth"

    context "project" do
      context "given an invalid / non-owned project ID" do
        use_vcr_cassette "jobs/delete/project/invalid"
        let(:invalid_project) { 2 }

        it "returns a Left" do
          expect(jobs.send(action, args.merge(project: invalid_project))).to be_a Kleisli::Either::Left
        end
      end
    end

    context "job" do
      context "given a single job" do
        use_vcr_cassette "jobs/delete/job/single"
        let(:job)  { "#{valid_project}/3/4" }
        let(:args) { {project: valid_project, job: job} }

        it "returns the right count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["count"]}.right).to eq(1)
        end
      end

      context "given a list of multiple jobs" do
        use_vcr_cassette "jobs/delete/job/multiple"
        let(:job)  { ["#{valid_project}/1/7", "#{valid_project}/1/8"] }
        let(:args) { {project: valid_project, job: job} }

        it "returns the right count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["count"]}.right).to eq(2)
        end
      end

      context "given an invalid/non-existent job" do
        use_vcr_cassette "jobs/delete/job/invalid"
        let(:job)  { "#{valid_project}/1/123" }
        let(:args) { {project: valid_project, job: job} }

        it "returns count of 0" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["count"]}.right).to eq(0)
        end
      end
    end
  end

  describe "stop" do
    let(:action)        { :stop }
    let(:valid_project) { 1 }
    let(:args)          { {project: valid_project, job: "#{valid_project}/1/9"} }

    it_behaves_like "connection_refused_returns_try"
    it_behaves_like "bad_auth_returns_try", "jobs/stop/bad_auth"

    context "project" do
      context "given an invalid / non-owned project ID" do
        use_vcr_cassette "jobs/stop/project/invalid"
        let(:invalid_project) { 2 }

        it "returns a Left" do
          expect(jobs.send(action, args.merge(project: invalid_project))).to be_a Kleisli::Either::Left
        end
      end
    end

    context "job" do
      context "given a valid job" do
        use_vcr_cassette "jobs/stop/job/valid"
        let(:job)  { "#{valid_project}/1/9" }
        let(:args) { {project: valid_project, job: job} }

        it "returns ok" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
        end
      end

      context "given a non-existent job" do
        use_vcr_cassette "jobs/stop/job/invalid"
        let(:job)  { "#{valid_project}/123/123" }
        let(:args) { {project: valid_project, job: job} }

        it "returns ok" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
        end
      end

      context "given an already-stopped job" do
        use_vcr_cassette "jobs/stop/job/already-stopped"
        let(:job)  { "#{valid_project}/1/6" }
        let(:args) { {project: valid_project, job: job} }

        it "returns ok" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
        end
      end

    end
  end

  describe "update" do
    let(:action)        { :update }
    let(:valid_project) { 1 }
    let(:args)          { {project: valid_project, job: "1/1/18"} }

    it_behaves_like "connection_refused_returns_try"
    it_behaves_like "bad_auth_returns_try", "jobs/update/bad_auth"

    context "project" do
      context "given an invalid / non-owned project ID" do
        use_vcr_cassette "jobs/update/project/invalid"
        let(:invalid_project) { 2 }
        let(:args)            { {project: invalid_project} }

        it "returns an error" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Left
          expect(js.left['status']).to eq("badrequest")
          expect(js.left["message"]).to match(/^User.*doesn\'t have access to project/)
        end
      end
    end

    context "query filters" do
      context "without query filters" do
        use_vcr_cassette "jobs/update/no-query-filters"
        let(:args) { {project: valid_project} }

        it "returns an error" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Left
          expect(js.left["status"]).to eq("badrequest")
          expect(js.left["message"]).to match(/^No query filters provided$/)
        end
      end

      context "filtering on job" do
        use_vcr_cassette "jobs/update/job"
        let(:args) { {project: valid_project, job: ["1/3/7", "1/1/18"], add_tag: "baz"} }

        it "returns ok status and the affected count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["count"]}.right).to eq(2)
        end
      end

      context "filtering on spider" do
        use_vcr_cassette "jobs/update/spider"
        let(:args) { {project: valid_project, spider: "atlantic_firearms_crawl", add_tag: "foo"} }

        it "returns ok status and the affected count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["count"]}.right).to eq(11)
        end
      end

      context "filtering on state" do
        use_vcr_cassette "jobs/update/state"
        let(:args) { {project: valid_project, state: "running", add_tag: "bar"} }

        it "returns ok status and the affected count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["count"]}.right).to eq(2)
        end
      end

      context "filtering on has_tag" do
        use_vcr_cassette "jobs/update/has_tag"
        let(:args) { {project: valid_project, has_tag: "bar", remove_tag: "bar"} }

        it "returns ok status and the affected count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["count"]}.right).to eq(4)
        end
      end

      context "filtering on lacks_tag" do
        use_vcr_cassette "jobs/update/lacks_tag"
        let(:args) { {project: valid_project, lacks_tag: "bar", add_tag: "bar"} }

        it "returns ok status and the affected count" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Right
          expect(js.fmap{|j| j["status"]}.right).to eq("ok")
          expect(js.fmap{|j| j["count"]}.right).to eq(18)
        end
      end
    end

    context "update parameters" do
      context "without update parameters" do
        use_vcr_cassette "jobs/update/no-update-params"

        it "returns an error" do
          js = jobs.send(action, args)
          expect(js).to be_a Kleisli::Either::Left
          expect(js.left["status"]).to eq("badrequest")
          expect(js.left["message"]).to match(/^No update modifiers provided$/)
        end
      end
    end
  end

end


text:
package ixias.play.api.auth.mvc

import play.api.mvc._
import scala.concurrent.{ Future, ExecutionContext }

/**
 * Provides the custom action for authentication.
 */
trait  AuthenticatedActionBuilder extends ActionBuilder[Request, AnyContent]
object AuthenticatedActionBuilder {
  def apply(auth: AuthProfile[_, _, _], parser: BodyParser[AnyContent])
    (implicit ec: ExecutionContext): AuthenticatedActionBuilder =
    new AuthenticatedActionBuilderImpl(auth, parser)
}

// Implementation for authentication
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class AuthenticatedActionBuilderImpl(
  val auth:   AuthProfile[_, _, _],
  val parser: BodyParser[AnyContent]
)(implicit val executionContext: ExecutionContext) extends AuthenticatedActionBuilder {

  /** Invoke the block. */
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    auth.authenticate(request) flatMap {
      case Left(failed)           => Future.successful(failed)
      case Right((data, updater)) => block {
        request.addAttr(auth.RequestAttrKey.Auth, data)
      } map updater
    }
  }
}


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *kbs;

@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // 沙盒路径
    NSString *directory = NSHomeDirectory();
    NSLog(@"沙盒路径 : %@", directory);

    directory = @"/Users/jay/Desktop/";
    NSString *url = @"http://yun.kubozy-youku-163.com/20190621/15575_cfedbee9/index.m3u8";
    NSString *file = [directory stringByAppendingPathComponent:@"8.mp4"];

    //ffmpeg -i https://host/really.m3u8 xinxijuzhiwang.mp4

    //ffmpeg -i http://yun.kubo-zy-youku.com/20180619/8Ne1BjmP/index.m3u8 -c copy -bsf:a aac_adtstoasc /Users/jay/Desktop/output.mp4

    //ffmpeg -i http://yun.kubo-zy-youku.com/20180619/8Ne1BjmP/index.m3u8 -c copy -bsf:a aac_adtstoasc -y /Users/jay/Desktop/output.mp4

    NSString *cmd = [NSString stringWithFormat:@"ffmpeg -i %@ -c copy -bsf:a aac_adtstoasc -y %@",url,file];
    //cmd = @"ffmpeg -i http://yun.kubo-zy-youku.com/20180619/8Ne1BjmP/index.m3u8 -c copy -bsf:a aac_adtstoasc -y /Users/jay/Desktop/output.mp4";
    [[FFmpegManager sharedManager] runCmd:cmd processBlock:^(float process,float kbs,long long size) {
        NSLog(@"%s--%f---%f---", __func__,process,kbs);
        self.progress.progress = process;
        self.kbs.text = [NSString stringWithFormat:@"%.2fKb/s",kbs];
    } completionBlock:^(NSError *error) {
        NSLog(@"%s", __func__);
    }];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //步骤1:获取视频路径
    // 沙盒路径
    NSString *directory = NSHomeDirectory();
    NSLog(@"沙盒路径 : %@", directory);
    NSString *file = [directory stringByAppendingPathComponent:@"88.mp4"];

    NSURL *webVideoUrl = [NSURL fileURLWithPath:file];
    //步骤2:创建AVPlayer
    AVPlayer *avPlayer = [[AVPlayer alloc] initWithURL:webVideoUrl];
    //步骤3:使用AVPlayer创建AVPlayerViewController,并跳转播放界面
    AVPlayerViewController *avPlayerVC =[[AVPlayerViewController alloc] init];
    avPlayerVC.player = avPlayer;
    [self presentViewController:avPlayerVC animated:YES completion:nil];
}

@end


text:
package org.apache.ambari.server.alerts;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.orm.entities.AlertDefinitionEntity;
import org.apache.ambari.server.state.Alert;
import org.apache.ambari.server.state.AlertState;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.HostState;
import org.apache.ambari.server.state.services.AmbariServerAlertService;

/**
 * The {@link AgentHeartbeatAlertRunnable} is used by the
 * {@link AmbariServerAlertService} to check agent heartbeats and fire alert
 * events when agents are not reachable.
 */
public class AgentHeartbeatAlertRunnable extends AlertRunnable {
  /**
   * Agent initializing message.
   */
  private static final String INIT_MSG = "{0} is initializing";

  /**
   * Agent healthy message.
   */
  private static final String HEALTHY_MSG = "{0} is healthy";

  /**
   * Agent waiting for status updates message.
   */
  private static final String STATUS_UPDATE_MSG = "{0} is waiting for status updates";

  /**
   * Agent is not heartbeating message.
   */
  private static final String HEARTBEAT_LOST_MSG = "{0} is not sending heartbeats";

  /**
   * Agent is not healthy message.
   */
  private static final String UNHEALTHY_MSG = "{0} is not healthy";

  /**
   * Unknown agent state message.
   */
  private static final String UNKNOWN_MSG = "{0} has an unknown state of {1}";

  /**
   * Constructor.
   *
   * @param definitionName
   */
  public AgentHeartbeatAlertRunnable(String definitionName) {
    super(definitionName);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  List<Alert> execute(Cluster cluster, AlertDefinitionEntity definition)
      throws AmbariException {
    long alertTimestamp = System.currentTimeMillis();

    Collection<Host> hosts = cluster.getHosts();

    List<Alert> alerts = new ArrayList<>(hosts.size());
    for (Host host : hosts) {
      String hostName = host.getHostName();

      String alertText;
      AlertState alertState = AlertState.OK;
      HostState hostState = host.getState();

      switch (hostState) {
        case INIT:
          alertText = MessageFormat.format(INIT_MSG, hostName);
          break;
        case HEALTHY:
          alertText = MessageFormat.format(HEALTHY_MSG, hostName);
          break;
        case WAITING_FOR_HOST_STATUS_UPDATES:
          alertText = MessageFormat.format(STATUS_UPDATE_MSG, hostName);
          break;
        case HEARTBEAT_LOST:
          alertState = AlertState.CRITICAL;
          alertText = MessageFormat.format(HEARTBEAT_LOST_MSG, hostName);
          break;
        case UNHEALTHY:
          alertState = AlertState.CRITICAL;
          alertText = MessageFormat.format(UNHEALTHY_MSG, hostName);
          break;
        default:
          alertState = AlertState.UNKNOWN;
          alertText = MessageFormat.format(UNKNOWN_MSG, hostName, hostState);
          break;
      }

      Alert alert = new Alert(definition.getDefinitionName(), null, definition.getServiceName(),
          definition.getComponentName(), hostName, alertState);

      alert.setLabel(definition.getLabel());
      alert.setText(alertText);
      alert.setTimestamp(alertTimestamp);
      alert.setClusterId(cluster.getClusterId());

      alerts.add(alert);
    }

    return alerts;
  }
}


text:
<?php

namespace Acme\contactBundle\Entity;

class contact
{
    protected $name;
    protected $mail;
    protected $message;

    public function getName()
    {
        return $this->name;
    }
    public function setName($name)
    {
        $this->name = $name;
    }

    public function getMail()
    {
        return $this->mail;
    }
    public function setMail($mail)
    {
        $this->mail = $mail;
    }

    public function getMessage()
    {
        return $this->message;
    }
    public function setMessage($message)
    {
        $this->message = $message;
    }
}


text:
module EventMachine
  module WebSocket
    module Close75
      def close_websocket(code, body)
        @state = :closed
        @connection.close_connection_after_writing
      end
    end
  end
end


text:
function toggle(selection) {
  var p = document.getElementById(selection);
  var style = p.className;
  p.className = style == "hide" ? "show" : "hide";
}


text:
class GURL;
class Profile;

namespace ntp_test_utils {

void SetUserSelectedDefaultSearchProvider(Profile* profile,
                                          const std::string& base_url,
                                          const std::string& ntp_url);

// Get the URL that WebContents->GetVisibleURL() will return after navigating to
// chrome://newtab/.  While this should typically be chrome://newtab/, in a test
// environment where there is no network connection, it may be
// chrome://new-tab-page-third-party.
GURL GetFinalNtpUrl(Profile* profile);

}  // namespace ntp_test_utils

#endif  // CHROME_BROWSER_UI_SEARCH_NTP_TEST_UTILS_H_


text:
/**
 * A DataSource is an interface which can be implemented to expose JSON Graph information to a Model. Every DataSource is associated with a single JSON Graph object. Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource's JSON Graph object. DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation.
 * @constructor DataSource
 * @abstract
 */

/**
 * The get method retrieves values from the DataSource's associated JSONGraph object.
 * @name get
 * @function
 * @arg {Array.<PathSet>} pathSets the path(s) to retrieve
 * @returns {Observable.<JSONGraphEnvelope>} jsonGraphEnvelope the response returned from the server.
 * @memberof DataSource.prototype
 */

/**
 * The set method accepts values to set in the DataSource's associated JSONGraph object.
 * @name set
 * @function
 * @arg {JSONGraphEnvelope} jsonGraphEnvelope a JSONGraphEnvelope containing values to set in the DataSource's associated JSONGraph object.
 * @returns {Observable.<JSONGraphEnvelope>} a JSONGraphEnvelope containing all of the requested values after the set operation.
 * @memberof DataSource.prototype
 */

/**
 * Invokes a function in the DataSource's JSONGraph object.
 * @name call
 * @function
 * @arg {Path} functionPath the path to the function to invoke
 * @arg {Array.<Object>} args the arguments to pass to the function
 * @arg {Array.<PathSet>} refSuffixes paths to retrieve from the targets of JSONGraph References in the function's response.
 * @arg {Array.<PathSet>} extraPaths additional paths to retrieve after successful function execution
 * @returns {Observable.<JSONGraphEnvelope>} jsonGraphEnvelope the response returned from the server.
 * @memberof DataSource.prototype
 */


text:
package org.kie.internal.builder.fluent;

import java.util.function.BiFunction;

import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSessionConfiguration;

public interface KieContainerFluent {

    KieSessionFluent newSession();

    KieSessionFluent newSession(String sessionName);

    KieSessionFluent newSessionCustomized(String sessionName, BiFunction<String, KieContainer, KieSessionConfiguration> kieSessionConfigurationCustomizer);

    DMNRuntimeFluent newDMNRuntime();
}


text:
class Chef
  class Knife
    class GoiardiJobStatus < Chef::Knife
      banner "knife goiardi job status <job id>"

      def run
        job_id = name_args[0]
        job = rest.get_rest("shovey/jobs/#{job_id}")
        output(job)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:src="@drawable/default_place_holder_banner"
    android:scaleType="fitXY" />


text:
import { AttributeSizeType } from './AttributeSizeType';

/**
 * An array of attribute values associated with meta data describing how to interpret the values.
 */
export interface Attribute {

    /**
     * The values of the attribute.
     */
    values: number[];

    /**
     * The number of values that are associated with a given vertex.
     */
    size: AttributeSizeType;
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 5: 187 (1951)

#### Original name
Aulographum filicinum Lib., 1834

### Remarks
null


text:
package org.apache.camel.util.backoff;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;

import org.apache.camel.util.function.ThrowingFunction;

final class BackOffTimerTask implements BackOffTimer.Task, Runnable {
    private final BackOff backOff;
    private final ScheduledExecutorService scheduler;
    private final ThrowingFunction<BackOffTimer.Task, Boolean, Exception> function;
    private final AtomicReference<ScheduledFuture<?>> futureRef;
    private final List<BiConsumer<BackOffTimer.Task, Throwable>> consumers;

    private Status status;
    private long currentAttempts;
    private long currentDelay;
    private long currentElapsedTime;
    private long lastAttemptTime;
    private long nextAttemptTime;

    BackOffTimerTask(BackOff backOff, ScheduledExecutorService scheduler, ThrowingFunction<BackOffTimer.Task, Boolean, Exception> function) {
        this.backOff = backOff;
        this.scheduler = scheduler;
        this.status = Status.Active;

        this.currentAttempts = 0;
        this.currentDelay = backOff.getDelay().toMillis();
        this.currentElapsedTime = 0;
        this.lastAttemptTime = BackOff.NEVER;
        this.nextAttemptTime = BackOff.NEVER;

        this.function = function;
        this.consumers = new ArrayList<>();
        this.futureRef = new AtomicReference<>();
    }

    // *****************************
    // Properties
    // *****************************

    @Override
    public BackOff getBackOff() {
        return backOff;
    }

    @Override
    public Status getStatus() {
        return status;
    }

    @Override
    public long getCurrentAttempts() {
        return currentAttempts;
    }

    @Override
    public long getCurrentDelay() {
        return currentDelay;
    }

    @Override
    public long getCurrentElapsedTime() {
        return currentElapsedTime;
    }

    @Override
    public long getLastAttemptTime() {
        return lastAttemptTime;
    }

    @Override
    public long getNextAttemptTime() {
        return nextAttemptTime;
    }

    @Override
    public void reset() {
        this.currentAttempts = 0;
        this.currentDelay = 0;
        this.currentElapsedTime = 0;
        this.lastAttemptTime = BackOff.NEVER;
        this.nextAttemptTime = BackOff.NEVER;
        this.status = Status.Active;
    }

    @Override
    public void cancel() {
        stop();

        ScheduledFuture<?> future = futureRef.get();
        if (future != null) {
            future.cancel(true);
        }

        // signal task completion on cancel.
        complete(null);
    }

    @Override
    public void whenComplete(BiConsumer<BackOffTimer.Task, Throwable> whenCompleted) {
        synchronized (this.consumers) {
            consumers.add(whenCompleted);
        }
    }

    // *****************************
    // Task execution
    // *****************************

    @Override
    public void run() {
        if (status == Status.Active) {
            try {
                lastAttemptTime = System.currentTimeMillis();

                if (function.apply(this)) {
                    long delay = next();
                    if (status != Status.Active) {
                        // if the call to next makes the context not more
                        // active, signal task completion.
                        complete(null);
                    } else {
                        nextAttemptTime = lastAttemptTime + delay;

                        // Cache the scheduled future so it can be cancelled
                        // later by Task.cancel()
                        futureRef.lazySet(scheduler.schedule(this, delay, TimeUnit.MILLISECONDS));
                    }
                } else {
                    stop();

                    // if the function return false no more attempts should
                    // be made so stop the context.
                    complete(null);
                }
            } catch (Exception e) {
                stop();

                complete(e);
            }
        }
    }

    void stop() {
        this.currentAttempts = 0;
        this.currentDelay = BackOff.NEVER;
        this.currentElapsedTime = 0;
        this.lastAttemptTime = BackOff.NEVER;
        this.nextAttemptTime = BackOff.NEVER;
        this.status = Status.Inactive;
    }

    void complete(Throwable throwable) {
        synchronized (this.consumers) {
            consumers.forEach(c -> c.accept(this, throwable));
        }
    }

    // *****************************
    // Impl
    // *****************************

    /**
     * Return the number of milliseconds to wait before retrying the operation
     * or ${@link BackOff#NEVER} to indicate that no further attempt should be
     * made.
     */
    long next() {
        // A call to next when currentDelay is set to NEVER has no effects
        // as this means that either the timer is exhausted or it has explicit
        // stopped
        if (status == Status.Active) {

            currentAttempts++;

            if (currentAttempts > backOff.getMaxAttempts()) {
                currentDelay = BackOff.NEVER;
                status = Status.Exhausted;
            } else if (currentElapsedTime > backOff.getMaxElapsedTime().toMillis()) {
                currentDelay = BackOff.NEVER;
                status = Status.Exhausted;
            } else {
                if (currentDelay <= backOff.getMaxDelay().toMillis()) {
                    currentDelay = (long) (currentDelay * backOff.getMultiplier());
                }

                currentElapsedTime += currentDelay;
            }
        }

        return currentDelay;
    }

    @Override
    public String toString() {
        return "BackOffTimerTask["
            + "status=" + status
            + ", currentAttempts=" + currentAttempts
            + ", currentDelay=" + currentDelay
            + ", currentElapsedTime=" + currentElapsedTime
            + ", lastAttemptTime=" + lastAttemptTime
            + ", nextAttemptTime=" + nextAttemptTime
            + ']';
    }
}


text:
from django.contrib.auth.models import User

from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    # for security, send back id and username, nothing more
    class Meta:
        model = User
        fields = ('id', 'username')


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/trace/bufferpage.H $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2012,2014              */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __TRACE_BUFFERPAGE_H
#define __TRACE_BUFFERPAGE_H

#include <trace/interface.H>

namespace TRACE
{
    class Entry;

    /** @struct BufferPage
     *
     *  A structure which can be overlaid onto a page of memory to allocate
     *  entries within the page.
     */
    struct BufferPage
    {
        BufferPage* next;       //< Linked-list 'next' ptr.
        BufferPage* prev;       //< Linked-list 'prev' ptr.

        uint32_t commonPage;    //< Status used by daemon pages.
        uint32_t usedSize;      //< Size already allocated for entries.

        char data[0];           //< Data for entries.

        /** @brief Lockless-ly claim an entry from the page.
         *
         *  @param[in] i_size - Size in bytes.
         *
         *  @return Entry* or NULL, if not enough space.
         */
        Entry* claimEntry(size_t i_size);

        /** @brief Utility function to allocate a page.
         *
         *  @param[in] i_common - Page is "common" from a daemon perspective.
         *
         *  @return Pointer to page.
         */
        static BufferPage* allocate(bool i_common = false);

        /** @brief Utility function to free a page.
         *
         *  @param[in] i_page - Page to deallocate.
         */
        static void deallocate(BufferPage* i_page);

    };
}

#endif


text:
package member

import (
	"log"

	"github.com/urfave/cli"
	"github.com/garlsecurity/securepassctl/spctl/service"
)

func init() {
	Command.Subcommands = append(Command.Subcommands,
		cli.Command{
			Name:        "add",
			Usage:       "add group",
			ArgsUsage:   "USERNAME GROUP",
			Description: "Add a user to a group.",
			Action:      ActionAdd,
			Flags:       []cli.Flag{},
		})
}

// ActionAdd provides the add subcommand
func ActionAdd(c *cli.Context) {
	if len(c.Args()) != 2 {
		log.Fatal("error: must specify a username and a group")
	}

	username := c.Args()[0]
	group := c.Args()[1]

	if c.Bool("debug") {
		log.Printf("Adding user %s to group %s\n", username, group)
	}

	_, err := service.Service.GroupMemberAdd(username, group)

	if err != nil {
		log.Fatalf("error: %v", err)
	}
}


text:
import isJapanese from './isJapanese';
import isKana from './isKana';
import isKanji from './isKanji';
import tokenize from './tokenize';

const isLeadingWithoutInitialKana = (input, leading) => leading && !isKana(input[0]);
const isTrailingWithoutFinalKana = (input, leading) => !leading && !isKana(input[input.length - 1]);
const isInvalidMatcher = (input, matchKanji) =>
  (matchKanji && ![...matchKanji].some(isKanji)) || (!matchKanji && isKana(input));

/**
 * Strips [Okurigana](https://en.wikipedia.org/wiki/Okurigana)
 * @param  {String} input text
 * @param  {Object} [options={ leading: false, matchKanji: '' }] optional config
 * @return {String} text with okurigana removed
 * @example
 * stripOkurigana('踏み込む')
 * // => '踏み込'
 * stripOkurigana('お祝い')
 * // => 'お祝'
 * stripOkurigana('お腹', { leading: true });
 * // => '腹'
 * stripOkurigana('ふみこむ', { matchKanji: '踏み込む' });
 * // => 'ふみこ'
 * stripOkurigana('おみまい', { matchKanji: 'お祝い', leading: true });
 * // => 'みまい'
 */
function stripOkurigana(input = '', { leading = false, matchKanji = '' } = {}) {
  if (
    !isJapanese(input) ||
    isLeadingWithoutInitialKana(input, leading) ||
    isTrailingWithoutFinalKana(input, leading) ||
    isInvalidMatcher(input, matchKanji)
  ) {
    return input;
  }

  const chars = matchKanji || input;
  const okuriganaRegex = new RegExp(
    leading ? `^${tokenize(chars).shift()}` : `${tokenize(chars).pop()}$`
  );
  return input.replace(okuriganaRegex, '');
}

export default stripOkurigana;


text:
@implementation NSObject (Parse)

+(instancetype)lz_parse:(id)responseObj{
    if ([responseObj isKindOfClass:[NSArray class]]) {
        return [self mj_objectArrayWithKeyValuesArray:responseObj];
    }
    if ([responseObj isKindOfClass:[NSDictionary class]]) {
        return [self mj_objectWithKeyValues:responseObj];
    }
    return  responseObj;
}

+ (BOOL)lz_isNullOrNilWithObject:(id)object;
{
    if (object == nil || [object isEqual:[NSNull null]]) {
        return YES;
    } else if ([object isKindOfClass:[NSString class]]) {
        if ([object isEqualToString:@""]) {
            return YES;
        } else {
            return NO;
        }
    } else if ([object isKindOfClass:[NSNumber class]]) {
        if ([object isEqualToNumber:@0]) {
            return YES;
        } else {
            return NO;
        }
    }
    return NO;
}

@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
  <meta name="description" content="A shorthand syntax for communicating xAPI Statements">
  <meta name="author" content="ADL">
  <link rel="icon" href="media/favicon.ico">

  <title>xAPI Remarks</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="media/css/styles.css" />

 xAPI Remarks

A shorthand syntax for communicating xAPI Statements

        Example Remarks
<textarea class="form-control" rows="15" aria-describedby="Example Remarks" id="example-remarks">
<tyler@example.com> <passed> <assessment1>
<tyler@example.com | Tyler Mulligan> <passed> <assessment1>
<tyler@example.com> <passed | has passed> <assessment1>
<5a7a72c5ec7d3a7291b9b6101ae26101eb925099> <passed> <assessment1>
<http://tyler.openid.example.com> <passed> <assessment1>
<tyler@example.com> <progressed> <http://adlnet.github.io>
<tyler@example.com> <added> <http://adlnet.github.io>
<tyler@example.com> <passed> <assessment1> ( score: [2, 0, 3], duration: "PT2M" ) { parent: ["page 5"], grouping: ["chapter 1", "science 101", "science"] }
<tyler@example.com> <passed> <assessment1> ( score: [2, 0, 3], duration: "PT2M", response: "hello", completion: true, success: false ) { parent: ["page 5"], grouping: ["chapter 1", "science 101", "science"] }
<tyler@example.com> <passed> <assessment1> ( score: [2, 0, 3], duration: "PT2M", response: "hello", completion: true, success: false ) { parent: ["page 5"], grouping: ["chapter 1", "science 101", "science"], category: ["http://example.com/profiles/ebook"], other: ["test"] }
<tyler@example.com> <voided> <137ca18f-97f6-4477-981a-696fb41c6b63>
</textarea>
        Copy & Paste one of these into the Remark box below

        Remark
        <input type="text" class="form-control" value="" placeholder="<Actor> <Verb> <Object> (Result) {Context}" aria-describedby="Remark" id="remark">

        Generate xAPI Statement

        Statement
        <textarea class="form-control" rows="25" aria-describedby="Statement" id="statement"></textarea>

Open your developer tools (f12) and refresh this page for more examples.

More Examples

Bulk converting & sending to an LRS

Looking for more?

Check out an organized list of ADL's resources available on github, including xAPI related software at  adlnet.github.io.


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer as HotReload } from 'react-hot-loader';
import { BrowserRouter as Router } from 'react-router-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Provider } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import OfflinePluginRuntime from 'offline-plugin/runtime';
import getRootNode from '@libs/getRootNode';
import App from './components/App';
import store from './store';
import './main.css';

OfflinePluginRuntime.install();

// Because we load in a UIWebView
injectTapEventPlugin({ shouldRejectClick: () => true });

const render = () => {
  ReactDOM.render(
    <HotReload>
      <Provider store={store}>
        <MuiThemeProvider>
          <Router>
            <App />
          </Router>
        </MuiThemeProvider>
      </Provider>
    </HotReload>,
    getRootNode('root'),
  );
};

render();

if (module.hot) {
  module.hot.accept('./components/App', () => {
    render();
  });
}


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is the Netscape Portable Runtime (NSPR).
 *
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1999-2000 Netscape Communications Corporation.  All
 * Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL"), in which case the provisions of the GPL are applicable
 * instead of those above.  If you wish to allow use of your
 * version of this file only under the terms of the GPL and not to
 * allow others to use your version of this file under the MPL,
 * indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by
 * the GPL.  If you do not delete the provisions above, a recipient
 * may use your version of this file under either the MPL or the
 * GPL.
 */

/*
** prrng.h -- NSPR Random Number Generator
**
**
** lth. 29-Oct-1999.
*/

#ifndef prrng_h___
#define prrng_h___

#include "prtypes.h"

PR_BEGIN_EXTERN_C

/*
** PR_GetRandomNoise() -- Get random noise from the host platform
**
** Description:
** PR_GetRandomNoise() provides, depending on platform, a random value.
** The length of the random value is dependent on platform and the
** platform's ability to provide a random value at that moment.
**
** The intent of PR_GetRandomNoise() is to provide a "seed" value for a
** another random number generator that may be suitable for
** cryptographic operations. This implies that the random value
** provided may not be, by itself, cryptographically secure. The value
** generated by PR_GetRandomNoise() is at best, extremely difficult to
** predict and is as non-deterministic as the underlying platfrom can
** provide.
**
** Inputs:
**   buf -- pointer to a caller supplied buffer to contain the
**          generated random number. buf must be at least as large as
**          is specified in the 'size' argument.
**
**   size -- the requested size of the generated random number
**
** Outputs:
**   a random number provided in 'buf'.
**
** Returns:
**   PRSize value equal to the size of the random number actually
**   generated, or zero. The generated size may be less than the size
**   requested. A return value of zero means that PR_GetRandomNoise() is
**   not implemented on this platform, or there is no available noise
**   available to be returned at the time of the call.
**
** Restrictions:
**   Calls to PR_GetRandomNoise() may use a lot of CPU on some platforms.
**   Some platforms may block for up to a few seconds while they
**   accumulate some noise. Busy machines generate lots of noise, but
**   care is advised when using PR_GetRandomNoise() frequently in your
**   application.
**
** History:
**   Parts of the model dependent implementation for PR_GetRandomNoise()
**   were taken in whole or part from code previously in Netscape's NSS
**   component.
**
*/
NSPR_API(PRSize) PR_GetRandomNoise(
    void    *buf,
    PRSize  size
);

PR_END_EXTERN_C

#endif /* prrng_h___ */
/* end prrng.h */


text:
var Foo = (function () {
    function Foo(store) {
        this._store = store;
    }
    Foo.prototype.foo = function () {
        return this._store.length;
    };

    Foo.prototype.bar = function () {
        return this.store;
    };
    return Foo;
})();

var Bar = (function () {
    function Bar(store) {
        this._store = store;
    }
    Bar.prototype.foo = function () {
        return this._store.length;
    };
    return Bar;
})();


text:
@extends('layouts.frontend')

@section('title', __('labels.frontend.titles.legal_mentions'))

@section('body_class', 'page-legal-mentions')

@section('content')

Etiam ut purus mattis mauris sodales aliquam. Curabitur ullamcorper ultricies nisi. Quisque rutrum. Proin faucibus arcu quis ante. Sed cursus turpis vitae tortor.

Morbi mattis ullamcorper velit. Nullam vel sem. Nam commodo suscipit quam. Nunc nonummy metus. Etiam sollicitudin, ipsum eu pulvinar rutrum, tellus ipsum laoreet sapien, quis venenatis ante odio sit amet eros.

Fusce ac felis sit amet ligula pharetra condimentum. Nullam cursus lacinia erat. Fusce egestas elit eget lorem. Vestibulum volutpat pretium libero. Praesent metus tellus, elementum eu, semper a, adipiscing nec, purus.

Donec interdum, metus et hendrerit aliquet, dolor diam sagittis ligula, eget egestas libero turpis vel mi. Morbi nec metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Sed cursus turpis vitae tortor.

Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam eu nunc. Quisque id odio. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Aliquam eu nunc.

@endsection


text:
package org.kaaproject.kaa.server.common.dao.impl.sql;

import static org.kaaproject.kaa.server.common.dao.DaoConstants.AUTHORITY_PROPERTY;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EXTERNAL_UID_PROPERTY;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.TENANT_ALIAS;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.TENANT_PROPERTY;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.TENANT_REFERENCE;

import org.hibernate.criterion.Restrictions;
import org.kaaproject.kaa.common.dto.KaaAuthorityDto;
import org.kaaproject.kaa.server.common.dao.impl.UserDao;
import org.kaaproject.kaa.server.common.dao.model.sql.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class HibernateUserDao extends HibernateAbstractDao<User> implements UserDao<User> {

  private static final Logger LOG = LoggerFactory.getLogger(HibernateUserDao.class);

  @Override
  public User findByExternalUid(String externalUid) {
    LOG.debug("Searching user by external uid [{}]", externalUid);
    return findOneByCriterion(Restrictions.eq(EXTERNAL_UID_PROPERTY, externalUid));
  }

  @Override
  public List<User> findByTenantIdAndAuthority(String id, String authority) {
    LOG.debug("Searching users by tenant id [{}] and authority [{}]", id, authority);
    List<User> users = findListByCriterionWithAlias(TENANT_PROPERTY, TENANT_ALIAS, Restrictions.and(
        Restrictions.eq(TENANT_REFERENCE, Long.valueOf(id)),
        Restrictions.eq(AUTHORITY_PROPERTY, KaaAuthorityDto.parse(authority))));
    if (LOG.isTraceEnabled()) {
      LOG.trace("[{},{}] Search result: {}.", id, authority, Arrays.toString(users.toArray()));
    } else {
      LOG.debug("[{},{}] Search result: {}.", id, authority, users.size());
    }
    return users;
  }

  @Override
  public List<User> findByTenantIdAndAuthorities(String id, String... authorities) {
    if (authorities != null) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("Searching user by tenant id [{}] and authorities [{}]",
                id, Arrays.toString(authorities));
      } else {
        LOG.debug("Searching user by tenant id [{}] and authorities [{}]", id, authorities.length);
      }
    }
    List<User> users = findListByCriterionWithAlias(TENANT_PROPERTY, TENANT_ALIAS, Restrictions.and(
        Restrictions.eq(TENANT_REFERENCE, Long.valueOf(id)),
        Restrictions.in(AUTHORITY_PROPERTY, KaaAuthorityDto.parseList(authorities))));
    if (LOG.isTraceEnabled()) {
      LOG.trace("[{}] Search result: {}.", id, Arrays.toString(users.toArray()));
    } else {
      LOG.debug("[{}] Search result: {}.", id, users.size());
    }
    return users;
  }

  @Override
  public void removeByTenantId(String tenantId) {
    List<User> users = findListByCriterionWithAlias(TENANT_PROPERTY, TENANT_ALIAS,
        Restrictions.eq(TENANT_REFERENCE, Long.valueOf(tenantId)));
    removeList(users);
    LOG.debug("Removed users by tenant id [{}] ", tenantId);
  }

  @Override
  protected Class<User> getEntityClass() {
    return User.class;
  }
}


text:
import { NestedOptionHost } from '../../core/nested-option';
import { NestedOption } from '../../core/nested-option';
export declare class DxoSortingComponent extends NestedOption {
    ascendingText: any;
    clearText: any;
    descendingText: any;
    mode: any;
    protected readonly _optionPath: string;
    constructor(parentOptionHost: NestedOptionHost, optionHost: NestedOptionHost);
}
export declare class DxoSortingModule {
}


text:
import Converter from './Converter';
export default class StripToNullConverter extends Converter {
  valueToString(value) {
    if (value) {
      return value;
    }

    return '';
  }

  stringToValue(string) {
    if (string) {
      return string;
    }

    return null;
  }
}