text:
import java.io.File;
import java.io.FilenameFilter;
import java.nio.IntBuffer;
import static org.bytedeco.javacpp.opencv_face.*;
import static org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_imgcodecs.*;

/**
 * I couldn't find any tutorial on how to perform face recognition using OpenCV and Java,
 * so I decided to share a viable solution here. The solution is very inefficient in its
 * current form as the training model is built at each run, however it shows what's needed
 * to make it work.
 *
 * The class below takes two arguments: The path to the directory containing the training
 * faces and the path to the image you want to classify. Not that all images has to be of
 * the same size and that the faces already has to be cropped out of their original images
 * (Take a look here http://fivedots.coe.psu.ac.th/~ad/jg/nui07/index.html if you haven't
 * done the face detection yet).
 *
 * For the simplicity of this post, the class also requires that the training images have
 * filename format: <label>-rest_of_filename.png. For example:
 *
 * 1-jon_doe_1.png
 * 1-jon_doe_2.png
 * 2-jane_doe_1.png
 * 2-jane_doe_2.png
 * ...and so on.
 *
 * Source: http://pcbje.com/2012/12/doing-face-recognition-with-javacv/
 *
 * @author Petter Christian Bjelland
 */
public class OpenCVFaceRecognizer {
    public static void main(String[] args) {
        String trainingDir = args[0];
        Mat testImage = imread(args[1], CV_LOAD_IMAGE_GRAYSCALE);

        File root = new File(trainingDir);

        FilenameFilter imgFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                name = name.toLowerCase();
                return name.endsWith(".jpg") || name.endsWith(".pgm") || name.endsWith(".png");
            }
        };

        File[] imageFiles = root.listFiles(imgFilter);

        MatVector images = new MatVector(imageFiles.length);

        Mat labels = new Mat(imageFiles.length, 1, CV_32SC1);
        IntBuffer labelsBuf = labels.getIntBuffer();

        int counter = 0;

        for (File image : imageFiles) {
            Mat img = imread(image.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);

            int label = Integer.parseInt(image.getName().split("\\-")[0]);

            images.put(counter, img);

            labelsBuf.put(counter, label);

            counter++;
        }

        FaceRecognizer faceRecognizer = createFisherFaceRecognizer();
        // FaceRecognizer faceRecognizer = createEigenFaceRecognizer();
        // FaceRecognizer faceRecognizer = createLBPHFaceRecognizer()

        faceRecognizer.train(images, labels);

        int predictedLabel = faceRecognizer.predict(testImage);

        System.out.println("Predicted label: " + predictedLabel);
    }
}


text:
Test hs_decompress() function : error conditions
--SKIPIF--
--FILE--
<?php
if (!extension_loaded('hs')) {
    dl('hs.' . PHP_SHLIB_SUFFIX);
}

echo "*** Testing hs_decompress() : error conditions ***\n";

// Zero arguments
echo "\n-- Testing hs_decompress() function with Zero arguments --\n";
var_dump( hs_decompress() );

//Test hs_decompress with one more than the expected number of arguments
echo "\n-- Testing hs_decompress() function with more than expected no. of arguments --\n";
$data = 'string_val';
$extra_arg = 10;
var_dump( hs_decompress($data, -1, -1, $extra_arg) );

echo "\n-- Testing with incorrect arguments --\n";
var_dump(hs_decompress(123));

class Tester
{
    function Hello()
    {
        echo "Hello\n";
    }
}

$testclass = new Tester();
var_dump(hs_decompress($testclass));
?>
===DONE===
--EXPECTF--
*** Testing hs_decompress() : error conditions ***

-- Testing hs_decompress() function with Zero arguments --

Warning: hs_decompress() expects at least 1 parameter, 0 given in %s on line %d
bool(false)

-- Testing hs_decompress() function with more than expected no. of arguments --

Warning: hs_decompress() expects at most 3 parameters, 4 given in %s on line %d
bool(false)

-- Testing with incorrect arguments --

Warning: hs_decompress : expects parameter to be string. in %s on line %d
bool(false)

Warning: hs_decompress : expects parameter to be string. in %s on line %d
bool(false)
===DONE===

redpajama_set_name: RedPajamaGithub


text:
"""
===============
flask_flatpages
===============

Flask-FlatPages provides a collection of pages to your Flask application.
Pages are built from "flat" text files as opposed to a relational database.

:copyright: (c) 2010-2015 by Simon Sapin, 2013-2015 by Igor Davydenko.
:license: BSD, see LICENSE for more details.
"""

from .flatpages import FlatPages  # noqa
from .page import Page  # noqa
from .utils import pygmented_markdown, pygments_style_defs  # noqa

__author__ = 'Simon Sapin, Igor Davydenko, Padraic Calpin'
__license__ = 'BSD License'
__version__ = '0.7.2'


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  include ElsToken
  els_config ELS_CONFIG

  helper_method :remote_user, :rpa_username, :els_identity

  private

  # will set a @cdid instance variable
  # determined by the REMOTE_USER or RPA_USERNAME headers.
  # cdid doesn't change often so it's gets stashed in the session
  #
  def cdid
    @cdid ||=
    session[:cdid] ||=
    request.headers["REMOTE_USER"] ||=
    request.headers["RPA_USERNAME"]
  end

  # the els_identity is backed by the ELS SSO system.
  # It will try to get a full identity object and then store
  # that in a memcache as raw retrieval currently hits performance.
  # Whilst SSO is brilliant, it can be a bit of a drag working around
  # it during development.
  #
  # This method will allow an end user to circumvent
  # the domain specific ELS login by authenticating directly with the ELS
  # system or, if a cookie is already resent, use that to retrieve an identity.
  # As an additional development bonus, it's possible to fake the identity -
  # setting it to whatever username is desired.
  #
  # It's up to the implementer to test the validity of that username in
  # their own application.
  # Likewise once you have an ElsIdentity object you may want to call your own
  # usermodel based on some value. 'cdid' and 'employee_number'
  # are common ones.
  #
  # One of the best things about the ElsIdentity is that it contains Group
  # information :) So, rather than implementing yet-another-role system in
  # your app, let the identity be managed centrally. Once you have the
  # ElsIdentity you can ask it whether it belongs to some role:
  #
  #  @els_identity.has_role? "some group"
  #
  def els_identity
    @els_identity = Rails.cache.fetch(session[:els_token], :namespace => "els_identity")
    unless @els_identity
      Rails.logger.debug("no identity in cache. Redirecting")
      session[:redirect_to] = request.env["PATH_INFO"]
      logger.debug("user will be returned to #{session[:redirect_to]}")
      redirect_to els_session_new_path
    end
  end

end


text:
package net.ontopia.topicmaps.utils.tmrap;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import javax.servlet.ServletException;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.core.TopicMapIF;
import net.ontopia.topicmaps.entry.TopicMaps;
import net.ontopia.topicmaps.nav2.utils.NavigatorUtils;
import net.ontopia.topicmaps.utils.NullResolvingExternalReferenceHandler;
import net.ontopia.topicmaps.xml.CanonicalXTMWriter;
import net.ontopia.topicmaps.xml.XTMTopicMapReader;
import net.ontopia.utils.OntopiaRuntimeException;
import net.ontopia.utils.StreamUtils;
import net.ontopia.utils.TestFileUtils;
import net.ontopia.utils.ontojsp.FakeServletConfig;
import net.ontopia.utils.ontojsp.FakeServletContext;
import net.ontopia.utils.ontojsp.FakeServletRequest;
import net.ontopia.utils.ontojsp.FakeServletResponse;
import net.ontopia.xml.DefaultXMLReaderFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

@RunWith(Parameterized.class)
public class TMRAPTestCase {

  private final static String testdataDirectory = "tmrap";

  private String base;
  private TMRAPTestDescriptor descriptor;

  @Parameters
  public static Collection generateTests() throws IOException {

    TestFileUtils.transferTestInputDirectory(testdataDirectory + "/topicmaps");

    String source = TestFileUtils.getTestInputFile(testdataDirectory, "tests.xml");
    InputStream in = StreamUtils.getInputStream(source);

    // Parse the test configuration file to get all the test descriptors.
    try {
      XMLReader parser = DefaultXMLReaderFactory.createXMLReader();
      TMRAPTestCaseContentHandler handler = new TMRAPTestCaseContentHandler();
      handler.register(parser);
      parser.parse(new InputSource(in));
      return handler.getTestDescriptors();
    } catch (SAXException e) {
      throw new OntopiaRuntimeException(e);
    } catch (MalformedURLException e) {
      throw new OntopiaRuntimeException(e);
    } catch (IOException e) {
      throw new OntopiaRuntimeException(e);
    }
  }

  public TMRAPTestCase(TMRAPTestDescriptor descriptor) {
    this.base = TestFileUtils.getTestdataOutputDirectory() + testdataDirectory + File.separator;
    this.descriptor = descriptor;
  }

  /**
   * Run an error test, i.e. a test that is meant to fail with some given exception class.
   */
  private void runErrorTest() {
    try {
      runRapServlet(base, new PrintWriter(new StringWriter()),
              descriptor.getUri(), false, false);
      Assert.fail("Expected to fail with: " + descriptor.getExpectedException()
              + " but executed without errors.");
    } catch (Exception e) {
      String eName = e.getClass().getName();
      Assert.assertTrue("Expected to fail with: "
              + descriptor.getExpectedException() + " but failed with "
              + eName + " instead.", eName.equals(descriptor
                      .getExpectedException()));
    }
  }

  @Test
  public void testFile() throws IOException, ServletException {
    if (descriptor.getId() == null) {
      runErrorTest();
      return;
    }

    TestFileUtils.verifyDirectory(base, "out");
    TestFileUtils.verifyDirectory(base, "cxtm");

    String id = descriptor.getId();

    // Path to the output.
    String out = base + "out" + File.separator + id
            + ".xtm";

    // Path to the canonicalized output.
    File cxtm = new File(base + "cxtm" + File.separator
            + id + ".cxtm");

    // Path to the baseline.
    String baseline = TestFileUtils.getTestInputFile(testdataDirectory, "baseline",
            id + ".cxtm");

    PrintWriter pw = new PrintWriter(new FileWriter(out));
    runRapServlet(base, pw,
            descriptor.getUri(), descriptor.getEdit(), descriptor.getView());
    pw.close();

    // FIXME: When other syntaxes are supported, the Reader must take the
    // chosen syntax into account.
    XTMTopicMapReader xtmReader = new XTMTopicMapReader(new File(out));
    xtmReader.setExternalReferenceHandler(
            new NullResolvingExternalReferenceHandler());

    // Import the tm.
    TopicMapIF importedTM = xtmReader.read();

    filterUnifyingTopics(importedTM);

    // Canonicalize the reimported tm.
    new CanonicalXTMWriter(cxtm).write(importedTM);

    // NOTE: Only for observational purposes when making tests.
    // (new LTMTopicMapWriter(new FileOutputStream(base + "ltm" + File.separator
    //     + id + ".ltm"))).write(importedTM);
    // Compare 'out' with 'baseline'.
    Assert.assertTrue("The output of the test with id " + id
            + " does not match the baseline: " + cxtm + " " + baseline, TestFileUtils.compareFileToResource(cxtm, baseline));
  }

  /**
   * A unifying topic is generated when a topic occurrs in multiple topicmaps of a TMRAP query. It has source locator
   * with a time stamp, which makes testing harder since it makes the output vary over time. This method removes those
   * source locators.
   *
   * @param topicMap The topic map to remove the source locators from.
   */
  public static void filterUnifyingTopics(TopicMapIF topicMap) {
    Collection topics = topicMap.getTopics();
    Iterator topicsIt = topics.iterator();
    while (topicsIt.hasNext()) {
      TopicIF currentTopic = (TopicIF) topicsIt.next();

      Collection removables = new ArrayList();

      Collection sources = currentTopic.getItemIdentifiers();
      Iterator sourcesIt = sources.iterator();
      while (sourcesIt.hasNext()) {
        LocatorIF currentLocator = (LocatorIF) sourcesIt.next();
        if (currentLocator.getAddress().indexOf("unifying-topic") != -1) {
          removables.add(currentLocator);
        }
      }

      Iterator removablesIt = removables.iterator();
      while (removablesIt.hasNext()) {
        LocatorIF currentLocator = (LocatorIF) removablesIt.next();
        currentTopic.removeItemIdentifier(currentLocator);
      }
    }
  }

  /**
   * Run RapServlet at a given base directory writing to a given PrintWriter.
   *
   * @param base The base directory of the test.
   * @param responseWriter Handles the output.
   * @param uriString The source URI which defines the TMRAP query.
   * @throws ServletException
   * @throws IOException
   */
  private static void runRapServlet(String base, PrintWriter responseWriter,
          String uriString, boolean edit, boolean view) throws ServletException,
          IOException {
    int queryIndex = uriString.indexOf('?');
    if (queryIndex == -1) {
      queryIndex = uriString.length();
    }
    String parameterPart
            = (queryIndex == 0 || queryIndex == uriString.length()) ? ""
            : uriString.substring(queryIndex + 1);
    uriString = uriString.substring(0, queryIndex);

    HashMap params = TMRAPTestUtils.tokenizeParameters(parameterPart);
    params.put("server_name", "TMRAP Test Suite");
    if (edit) {
      params.put("edit_uri", "http://localhost:8080/ontopoly/topicTypeConfig.ted?tm=%tmid%&id=%topicid%");
    }
    if (view) {
      params.put("view_uri", "http://localhost:8080/omnigator/models/topic_complete.jsp?tm=%tmid%&id=%topicid%");
    }

    Hashtable paramsTable = TMRAPTestUtils.tabularizeParameters(params);

    FakeServletContext servletContext = new FakeServletContext(base, new Hashtable(),
            Collections.singletonMap("source_config",
                    TestFileUtils.getTestInputFile(testdataDirectory, "WEB-INF/config/tm-sources.xml")));

    FakeServletConfig servletConfig = new FakeServletConfig(servletContext,
            paramsTable);
    FakeServletRequest servletRequest = new FakeServletRequest(FakeServletRequest.transform(paramsTable));

    FakeServletResponse servletResponse
            = new FakeServletResponse(responseWriter);

    RAPServlet rapServlet = new RAPServlet();

    rapServlet.init(servletConfig);
    rapServlet.doGet(servletRequest, servletResponse, uriString);

    TopicMaps.forget(NavigatorUtils.getTopicMapRepository(servletContext));

    if (servletResponse.getStatus() != 200) {
      throw new ServletException("Error in running RAP servlet: "
              + servletResponse.getStatus() + " "
              + servletResponse.getMessage());
    }
  }
}


text:
typedef void (^OnesiteServiceCallbackResultBlock)(NSData *result);
typedef void (^OnesiteServiceCallbackFailureBlock)(NSError *error);
#endif

@interface OnesiteService : NSObject
{
	NSString *_serviceUrl;
	BOOL _debug;

}
@property(nonatomic, assign) BOOL debug;
@property(nonatomic, retain) NSString *serviceUrl;

- (void)callRestServiceWithParameters:(NSDictionary*)params
					   resultCallback:(OnesiteServiceCallbackResultBlock)resultCallback
						errorCallback:(OnesiteServiceCallbackFailureBlock)errorCallback;

@end


text:
#pragma once

// 병렬 컨테이너 및 개체
// https://msdn.microsoft.com/ko-kr/library/dd504906.aspx

#include <concurrent_queue.h>
#include <concurrent_priority_queue.h>
#include <concurrent_unordered_set.h>
#include <concurrent_unordered_map.h>


text:
package com.prowidesoftware.swift.model;

import com.prowidesoftware.swift.model.field.AmountContainer;
import com.prowidesoftware.swift.model.field.CurrencyContainer;
import com.prowidesoftware.swift.model.field.Field;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * A simple POJO to represent money, an amount associated with a currency.
 *

 * This might someday be replaced by an implementation of https://javamoney.github.io/api.html
 *
 * @since 8.0.1
 */
public final class Money implements Serializable {
    private static final long serialVersionUID = -7552352742105490377L;
    private static final transient Logger log = Logger.getLogger(Money.class.getName());

    private final String currency;
    private final BigDecimal amount;

    /**
     * @param currency a not null currency
     * @param amount   the value for the amount, may be null
     */
    public Money(final Currency currency, final BigDecimal amount) {
        this(currency.getCurrencyCode(), amount);
    }

    /**
     * @param currency a not null currency code
     * @param amount   the value for the amount, may be null
     */
    public Money(final String currency, final BigDecimal amount) {
        Objects.requireNonNull(currency, "currency can not be null");
        this.currency = currency;
        if (amount == null) {
            this.amount = BigDecimal.ZERO;
        } else {
            this.amount = amount;
        }
    }

    /**
     * @param currency a not null currency
     * @param amount   the value for the amount, may be null
     */
    public Money(final Currency currency, Number amount) {
        this(currency.getCurrencyCode(), amount);
    }

    /**
     * @param currency a not null currency code
     * @param amount   the value for the amount, may be null
     */
    public Money(final String currency, Number amount) {
        this.currency = currency;
        if (amount == null) {
            this.amount = BigDecimal.ZERO;
        } else {
            if (amount instanceof BigDecimal) {
                this.amount = (BigDecimal) amount;
            } else if (amount instanceof Long) {
                this.amount = new BigDecimal(amount.longValue());
            } else if (amount instanceof Integer) {
                this.amount = new BigDecimal(amount.intValue());
            } else if (amount instanceof Short) {
                this.amount = new BigDecimal(amount.intValue());
            } else if (amount instanceof Double) {
                /*
                 * we use valueOf instead of constructor because it uses a string under the covers to eliminate floating point rounding errors
                 */
                this.amount = BigDecimal.valueOf(amount.doubleValue());
            } else {
                throw new IllegalArgumentException("class " + amount.getClass().getName() + " is not supported");
            }
        }
    }

    /**
     * Creates a currency amount from an MT field.

     * The field must at least implement the {@link AmountContainer} interface and
     * either have a currency component or implements the {@link CurrencyContainer}
     * For some fields like the signed 19A or the 62[F,M] which have a debit/credit mark
     * component, the amount will be positive or negative accordingly.
     *
     * @param field a field with currency and amount components
     * @return the created currency amount object or null if field is null or invalid.
     */
    /*
     * Do not use API from MTs and Field classes here to avoid cyclic dependency in code generation
     * Component numbers do not normally change, although keep code below in sync with fields 62FM, 19A and 33B.
     */
    static Money of(Field field) {
        if (field != null && field instanceof AmountContainer) {
            /*
             * amount from interface
             */
            BigDecimal amount = ((AmountContainer) field).amount();
            if (amount == null) {
                log.warning("cannot extract amount component from field " + field.getName() + ":" + field.getValue());
                return null;
            }

            /*
             * special cases
             */
            String currency = null;
            boolean negative = false;
            if ("62F".equals(field.getName()) || "62M".equals(field.getName())) {
                currency = field.getComponent(3);
                negative = StringUtils.equals("D", field.getComponent(1));
            } else if ("19A".equals(field.getName())) {
                negative = StringUtils.equals("N", field.getComponent(2));
            } else if ("33B".equals(field.getName())) {
                currency = field.getComponent(1);
            }

            /*
             * currency from interface
             */
            if (currency == null && field instanceof CurrencyContainer) {
                currency = ((CurrencyContainer) field).currencyString();
            }

            if (currency == null) {
                log.warning("cannot extract currency component from field " + field.getName() + ":" + field.getValue());
                return null;
            }

            if (negative) {
                amount = amount.negate();
            }
            return new Money(currency, amount);
        }
        return null;
    }

    /**
     * Creates a currency amount from the first found field in the block
     *
     * @param fieldNames a list of field names to extract the money from
     */
    static Money ofAny(SwiftTagListBlock block, String... fieldNames) {
        for (String fieldName : fieldNames) {
            Field field = block.getFieldByName(fieldName);
            if (field != null) {
                return of(field);
            }
        }
        return null;
    }

    /**
     * Creates a currency amount from the sum of all given fields.
     * Will return null if currencies not match.
     *
     * @param fields fields to sum, currency must be the same for all
     * @return total or null if cannot create amount from any field or if not all fields currency match
     */
    static Money ofSum(Field... fields) {
        if (fields == null || fields.length == 0) {
            return null;
        }
        BigDecimal total = null;
        String currency = null;
        for (Field field : fields) {
            Money money = of(field);
            if (money == null) {
                return null;
            }
            if (total == null) {
                total = money.getAmount();
                currency = money.getCurrency();
            } else if (StringUtils.equals(currency, money.getCurrency())) {
                total = total.add(money.getAmount());
            } else {
                log.warning("cannot sum amounts with different currencies, expected " + currency + " and found " + money.getCurrency() + " in field " + field.getName() + ":" + field.getValue());
                return null;
            }
        }
        if (total != null && currency != null) {
            return new Money(currency, total);
        } else {
            return null;
        }
    }

    public String getCurrency() {
        return currency;
    }

    public BigDecimal getAmount() {
        return amount;
    }

}


text:
/**
 * AccountThroughAdGroupReportScope.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.microsoft.bingads.v9.reporting;

public class AccountThroughAdGroupReportScope  implements java.io.Serializable {
    private long[] accountIds;

    private com.microsoft.bingads.v9.reporting.AdGroupReportScope[] adGroups;

    private com.microsoft.bingads.v9.reporting.CampaignReportScope[] campaigns;

    public AccountThroughAdGroupReportScope() {
    }

    public AccountThroughAdGroupReportScope(
           long[] accountIds,
           com.microsoft.bingads.v9.reporting.AdGroupReportScope[] adGroups,
           com.microsoft.bingads.v9.reporting.CampaignReportScope[] campaigns) {
           this.accountIds = accountIds;
           this.adGroups = adGroups;
           this.campaigns = campaigns;
    }

    /**
     * Gets the accountIds value for this AccountThroughAdGroupReportScope.
     *
     * @return accountIds
     */
    public long[] getAccountIds() {
        return accountIds;
    }

    /**
     * Sets the accountIds value for this AccountThroughAdGroupReportScope.
     *
     * @param accountIds
     */
    public void setAccountIds(long[] accountIds) {
        this.accountIds = accountIds;
    }

    /**
     * Gets the adGroups value for this AccountThroughAdGroupReportScope.
     *
     * @return adGroups
     */
    public com.microsoft.bingads.v9.reporting.AdGroupReportScope[] getAdGroups() {
        return adGroups;
    }

    /**
     * Sets the adGroups value for this AccountThroughAdGroupReportScope.
     *
     * @param adGroups
     */
    public void setAdGroups(com.microsoft.bingads.v9.reporting.AdGroupReportScope[] adGroups) {
        this.adGroups = adGroups;
    }

    /**
     * Gets the campaigns value for this AccountThroughAdGroupReportScope.
     *
     * @return campaigns
     */
    public com.microsoft.bingads.v9.reporting.CampaignReportScope[] getCampaigns() {
        return campaigns;
    }

    /**
     * Sets the campaigns value for this AccountThroughAdGroupReportScope.
     *
     * @param campaigns
     */
    public void setCampaigns(com.microsoft.bingads.v9.reporting.CampaignReportScope[] campaigns) {
        this.campaigns = campaigns;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof AccountThroughAdGroupReportScope)) return false;
        AccountThroughAdGroupReportScope other = (AccountThroughAdGroupReportScope) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.accountIds==null && other.getAccountIds()==null) ||
             (this.accountIds!=null &&
              java.util.Arrays.equals(this.accountIds, other.getAccountIds()))) &&
            ((this.adGroups==null && other.getAdGroups()==null) ||
             (this.adGroups!=null &&
              java.util.Arrays.equals(this.adGroups, other.getAdGroups()))) &&
            ((this.campaigns==null && other.getCampaigns()==null) ||
             (this.campaigns!=null &&
              java.util.Arrays.equals(this.campaigns, other.getCampaigns())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getAccountIds() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getAccountIds());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getAccountIds(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        if (getAdGroups() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getAdGroups());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getAdGroups(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        if (getCampaigns() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getCampaigns());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getCampaigns(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(AccountThroughAdGroupReportScope.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "AccountThroughAdGroupReportScope"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("accountIds");
        elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "AccountIds"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(true);
        elemField.setItemQName(new javax.xml.namespace.QName("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "long"));
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("adGroups");
        elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "AdGroups"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "AdGroupReportScope"));
        elemField.setMinOccurs(0);
        elemField.setNillable(true);
        elemField.setItemQName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "AdGroupReportScope"));
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("campaigns");
        elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "Campaigns"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "CampaignReportScope"));
        elemField.setMinOccurs(0);
        elemField.setNillable(true);
        elemField.setItemQName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v9", "CampaignReportScope"));
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
cask 'blink1control' do
  version '2.2.2'
  sha256 '59d7235432e018f6d8152c580b0ec38546fef0215342139b4cf95f6161efa097'

  # github.com/todbot/Blink1Control2 was verified as official when first introduced to the cask
  url "https://github.com/todbot/Blink1Control2/releases/download/v#{version}/Blink1Control#{version.major}-#{version}-mac.dmg"
  appcast 'https://github.com/todbot/Blink1Control2/releases.atom'
  name 'Blink1Control'
  homepage 'https://blink1.thingm.com/'

  app "Blink1Control#{version.major}.app"
end


text:
/*
 * IRemoteConnectionListener.h
 *
 *  Created on: Sep 22, 2012
 *      Author: Mitchell Wills
 */

#ifndef IREMOTECONNECTIONLISTENER_H_
#define IREMOTECONNECTIONLISTENER_H_

class IRemoteConnectionListener;

#include "tables/IRemote.h"

/**
 * A listener that listens for connection changes in a {@link IRemote} object
 *
 * @author Mitchell
 *
 */
class IRemoteConnectionListener {
public:
	virtual ~IRemoteConnectionListener(){}
	/**
	 * Called when an IRemote is connected
	 * @param remote the object that connected
	 */
	virtual void Connected(IRemote* remote) = 0;
	/**
	 * Called when an IRemote is disconnected
	 * @param remote the object that disconnected
	 */
	virtual void Disconnected(IRemote* remote) = 0;
};

#endif /* IREMOTECONNECTIONLISTENER_H_ */


text:
package renesca.graph

import scala.collection.mutable

object Graph {
  def apply(nodes: Traversable[Node] = Nil, relations: Traversable[Relation] = Nil): Graph = {
    val graph = new Graph
    graph.nodes ++= nodes
    graph.relations ++= relations
    graph
  }

  def empty = apply(Nil, Nil)
}

class Graph private[graph] {
  // private constructor to force usage of Factory

  val nodes = Nodes.empty // TODO: is it possible to eliminate this cyclic reference? (used for removing node incident relations)
  nodes.graph = this
  val relations = Relations.empty // TODO: is it possible to eliminate this cyclic reference? (used for adding nonexistent start/endNode to graph)
  relations.graph = this

  private[graph] val localChanges = mutable.ArrayBuffer.empty[GraphChange]

  def +=(path: Path): Unit = {
    localChanges += AddPath(path)
    nodes ++= path.allNodes
    relations ++= path.relations
  }

  def changes: Seq[GraphChange] = {
    localChanges ++
      nodes.localChanges ++
      relations.localChanges ++
      nodes.toSeq.flatMap(_.changes) ++
      relations.toSeq.flatMap(_.changes)
  }

  private[renesca] def clearChanges() {
    nodes.clearChanges()
    relations.clearChanges()

    localChanges.clear()
  }

  def outRelations(node: Node) = relations.filter(node == _.startNode)
  def inRelations(node: Node) = relations.filter(node == _.endNode)
  def incidentRelations(node: Node) = inRelations(node) ++ outRelations(node)
  def neighbours(node: Node) = incidentRelations(node).map(_.other(node))
  def successors(node: Node) = outRelations(node).map(_.endNode)
  def predecessors(node: Node) = inRelations(node).map(_.startNode)
  def inDegree(node: Node) = inRelations(node).size
  def outDegree(node: Node) = outRelations(node).size
  def degree(node: Node) = inDegree(node) + outDegree(node)

  def merge(that: Graph) = {
    val graph = Graph.apply(this.nodes ++ that.nodes, this.relations ++ that.relations)
    graph.localChanges ++= this.changes
    graph.localChanges ++= that.changes
    graph
  }

  def isEmpty = nodes.isEmpty
  def nonEmpty = nodes.nonEmpty

  override def toString = s"Graph(nodes:(${nodes.mkString(", ")}), relations:(${relations.mkString(", ")}))"

  def canEqual(other: Any): Boolean = other.isInstanceOf[Graph]

  override def equals(other: Any): Boolean = other match {
    // we are converting nodes and relations to sets, because order should not matter
    // TODO: is there a more efficient way to do this?
    case that: Graph =>
      (that canEqual this) &&
        this.nodes.toSet == that.nodes.toSet &&
        this.relations.toSet == that.relations.toSet
    case _ => false
  }

  override def hashCode(): Int = {
    // we are converting nodes and relations to sets, because order should not matter
    // TODO: is there a more efficient way to do this?
    val state = Seq(nodes.toSet, relations.toSet)
    state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
  }
}


text:
#ifndef GRPC_CORE_LIB_GPRPP_SYNC_H
#define GRPC_CORE_LIB_GPRPP_SYNC_H

#include <grpc/impl/codegen/port_platform.h>

#include <grpc/impl/codegen/log.h>
#include <grpc/impl/codegen/sync.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>

// The core library is not accessible in C++ codegen headers, and vice versa.
// Thus, we need to have duplicate headers with similar functionality.
// Make sure any change to this file is also reflected in
// include/grpcpp/impl/codegen/sync.h.
//
// Whenever possible, prefer using this file over <grpcpp/impl/codegen/sync.h>
// since this file doesn't rely on g_core_codegen_interface and hence does not
// pay the costs of virtual function calls.

namespace grpc_core {

class Mutex {
 public:
  Mutex() { gpr_mu_init(&mu_); }
  ~Mutex() { gpr_mu_destroy(&mu_); }

  Mutex(const Mutex&) = delete;
  Mutex& operator=(const Mutex&) = delete;

  gpr_mu* get() { return &mu_; }
  const gpr_mu* get() const { return &mu_; }

 private:
  gpr_mu mu_;
};

// MutexLock is a std::
class MutexLock {
 public:
  explicit MutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
  explicit MutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
  ~MutexLock() { gpr_mu_unlock(mu_); }

  MutexLock(const MutexLock&) = delete;
  MutexLock& operator=(const MutexLock&) = delete;

 private:
  gpr_mu* const mu_;
};

class ReleasableMutexLock {
 public:
  explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
  explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
  ~ReleasableMutexLock() {
    if (!released_) gpr_mu_unlock(mu_);
  }

  ReleasableMutexLock(const ReleasableMutexLock&) = delete;
  ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;

  void Lock() {
    GPR_DEBUG_ASSERT(released_);
    gpr_mu_lock(mu_);
    released_ = false;
  }

  void Unlock() {
    GPR_DEBUG_ASSERT(!released_);
    released_ = true;
    gpr_mu_unlock(mu_);
  }

 private:
  gpr_mu* const mu_;
  bool released_ = false;
};

class CondVar {
 public:
  CondVar() { gpr_cv_init(&cv_); }
  ~CondVar() { gpr_cv_destroy(&cv_); }

  CondVar(const CondVar&) = delete;
  CondVar& operator=(const CondVar&) = delete;

  void Signal() { gpr_cv_signal(&cv_); }
  void Broadcast() { gpr_cv_broadcast(&cv_); }

  int Wait(Mutex* mu) { return Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME)); }
  int Wait(Mutex* mu, const gpr_timespec& deadline) {
    return gpr_cv_wait(&cv_, mu->get(), deadline);
  }

  template <typename Predicate>
  void WaitUntil(Mutex* mu, Predicate pred) {
    while (!pred()) {
      Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME));
    }
  }

  // Returns true iff we timed-out
  template <typename Predicate>
  bool WaitUntil(Mutex* mu, Predicate pred, const gpr_timespec& deadline) {
    while (!pred()) {
      if (Wait(mu, deadline)) return true;
    }
    return false;
  }

 private:
  gpr_cv cv_;
};

}  // namespace grpc_core

#endif /* GRPC_CORE_LIB_GPRPP_SYNC_H */


text:
<!DOCTYPE html>

    <title>{resource_title}</title>

 {exp:learning_tools_integration
    prev_link_url='https://uonline-stg.newcastle.edu.au/images/ci/ng/small_previous.gif'
    next_link_url='https://uonline-stg.newcastle.edu.au/images/ci/ng/small_next.gif'
    first_link_url='https://uonline-stg.newcastle.edu.au/images/ci/ng/small_rewind.gif'
    last_link_url='https://uonline-stg.newcastle.edu.au/images/ci/ng/small_ffwd.gif'
   	plugins='lti_peer_assessment'}
     {css_link_tags}

    {if error_messages != ""}
    	{error_messages}
    {/if}
 	{if logged_in}

{resource_title}

{resource_link_description}

{general_message}

Return to course:
                {course_name}

{if is_instructor == 1}

General Settings

Group import & Plugin settings

              	{general_settings_form}

Students registered for Peer Evaluation

                            {student_table}

Give Students Access to Peer Evaluation

{upload_student_list}

Blackboard Rubrics

Upload rubrics here for this course, attached
                        rubrics will be used by students to grade their
                        peers.

To create and export a rubric from Blackboard,
                        go to Organisation Tools →
                        Rubrics.

Upload a rubric

{upload_blackboard_rubric}

Further Tools

Settings
{exp:lti_peer_assessment:settings}

Download Evaluations

Download Evaluations as Excel Spreadsheet
{exp:lti_peer_assessment:download_excel}

{if:else}

{exp:lti_peer_assessment:group_name}

{group_sub_heading}

{evaluation_form_heading}

Access this link for the Marking Impact document

                        {exp:lti_peer_assessment:form type='single'}
                        {/if}

Return to
                        course: {course_name}
{/if}

{/exp:learning_tools_integration}


text:
/*
Client side request can look like this:
var params = {
  requestParams : {
    rank : '-someField',
    'bq' : '(and%20item_1:1%20item_2:1)',
    'return-fields' : 'item_id,item_img&',
    'size' : '12',
    'start' : '0'
  },
  serverConfig : {
    apiVersion: '2011-02-01',
    domainName: '[your-cloud-search-domain-name]',
    region: 'us-east-1'
  }
};

serviceCall('cloudsearch', 'serviceCallbackRespond', params);
*/

'use strict';

var whiteListParams = {
  item_id : true,
  item_img : true,
  item_name : true
};

function cloudsearch(data, dbconnectorCallBackToRooms) {
  var endPoint = generateURL(data.params.requestParams, data.params.serverConfig);
  console.log(endPoint);

  var request = require("request");
  request(endPoint, function (error, response, body) {
    dbconnectorCallBackToRooms(data, body);
  });
}

function generateURL(params, serverConfig) {
  var retString = serverConfig.domainName + '.' + serverConfig.region + '.cloudsearch.amazonaws.com/2011-02-01/search?';

  for (var name in params) {
    if (whiteListParams.hasOwnProperty(name))
      retString = retString + name + '=' + params[name] + '&';
    else
      console.log('param ' + name + ' not on whitelist');
  }
  retString = retString.substring(0, retString.length-1);
  return retString;
}

module.exports.cloudsearch = cloudsearch;


text:
from .genderdetect import genderDetector

class Name:
    def __init__(self, vorname, nachname, partei, gender_in=''):
        self.vorname = vorname
        self.vorname_raw = vorname
        self.nachname = nachname
        self.partei = partei

        if len(gender_in) > 0:
            self.gender = gender_in
        else:
            # Vornamen auf elementaren Teil reduzieren
            dotted_prefix_end = self.vorname_raw.rfind('. ')
            if dotted_prefix_end > -1:
                self.vorname_raw = self.vorname_raw[dotted_prefix_end+2:]
            double_name_splitter = self.vorname_raw.rfind('-')
            if double_name_splitter > -1:
                self.vorname_raw = self.vorname_raw.partition('-')[0]
            # Strip other suffixes
            van_sufix = self.vorname_raw.rfind(' van')
            if van_sufix > -1:
                self.vorname_raw = self.vorname_raw[:van_sufix]

            print("Guessing gender of %s" % self.vorname_raw)
            gender = genderDetector.guess(self.vorname_raw)
            if gender == 'male':
                self.gender = 'm'
            elif gender == 'female':
                self.gender = 'f'
            else:
                self.gender = ''
            print("Gender detected: '%s'" % gender)

    def printout(self):
        name_str = self.nachname + ', ' + self.vorname + ' (' + self.gender + ', ' + self.partei + ')'
        return name_str


text:
package com.indvd00m.vaadin.navigator.test;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.Test;

import com.indvd00m.vaadin.navigator.SubNavigator;
import com.indvd00m.vaadin.navigator.api.ISubNavigator;
import com.indvd00m.vaadin.navigator.api.view.ISubContainer;
import com.vaadin.server.Page;
import com.vaadin.ui.UI;

/**
 * @author indvd00m (gotoindvdum[at]gmail[dot]com)
 * @date Nov 21, 2015 6:33:22 PM
 *
 */
public class TestSubPath {

	@Test
	public void test() {
		UI ui = mock(UI.class);
		Page page = mock(Page.class);
		when(ui.getPage()).thenReturn(page);
		ISubContainer root = mock(ISubContainer.class);
		when(root.getRelativePath()).thenReturn("");
		ISubNavigator subNavigator = new SubNavigator(ui, root);

		assertEquals("test1/test2//", subNavigator.trimDelimiterLeft("test1/test2//"));
		assertEquals("test1/test2//", subNavigator.trimDelimiterLeft("/test1/test2//"));
		assertEquals("test1/test2//", subNavigator.trimDelimiterLeft("//test1/test2//"));

		assertEquals("//test1/test2", subNavigator.trimDelimiterRight("//test1/test2"));
		assertEquals("//test1/test2", subNavigator.trimDelimiterRight("//test1/test2/"));
		assertEquals("//test1/test2", subNavigator.trimDelimiterRight("//test1/test2//"));

		assertEquals("test1/test2", subNavigator.trimDelimiter("//test1/test2"));
		assertEquals("test1/test2", subNavigator.trimDelimiter("/test1/test2/"));
		assertEquals("test1/test2", subNavigator.trimDelimiter("/test1/test2//"));

		assertTrue(subNavigator.equalsPath("/test/test2//", "test/test2"));
		assertFalse(subNavigator.equalsPath("/test1/test2//", "test/test2"));
		assertFalse(subNavigator.equalsPath("/test/test2d//", "test/test2"));
		assertFalse(subNavigator.equalsPath("/test/test2/test3", "test/test2"));

		assertTrue(subNavigator.isSubPath("test1/test2", "/test1/test2/"));
		assertTrue(subNavigator.isSubPath("test1/test2/test3", "test1/test2"));
		assertFalse(subNavigator.isSubPath("test1/test2", "test1/test2/test3"));
		assertFalse(subNavigator.isSubPath("test0/test1/test2", "test1/test2/"));
	}

}


text:
package bucky;

public class GUIFiftyEightMain {

}


text:
All notable changes to this project will be documented in this file. See [versionize](https://github.com/saintedlama/versionize) for commit guidelines.

## 0.8.0 (2019-12-6)

### Features

* add ability to @type operations

### Breaking Changes

* change the API of supported operation to allow easy extensions

## 0.7.0 (2019-11-21)

### Bug Fixes

* use property annotation as predicate if absolute URI (#26)
* more relaxed null guards on supported operation builder

### Features

* attributes for readable/writable properties (#25)
* attributes for readable/writable

## 0.6.0 (2019-9-23)

### Bug Fixes

* don't throw from NancyContextWrapper when NancyContext is null

### Features

* manages block
* update to nancy 2.0

## 0.5.0 (2019-8-18)

### Features

* update to nancy 2.0

### [0.4.3](https://github.com/wikibus/Argolis/compare/v0.4.2...v0.4.3) (2019-07-02)

### Bug Fixes

* don't throw from NancyContextWrapper when NancyContext is null ([ed20ae5](https://github.com/wikibus/Argolis/commit/ed20ae5))

### [0.4.3](https://github.com/wikibus/Argolis/compare/v0.4.2...v0.4.3) (2019-07-02)

### Bug Fixes

* don't throw from NancyContextWrapper when NancyContext is null ([ed20ae5](https://github.com/wikibus/Argolis/commit/ed20ae5))

### [0.4.2](https://github.com/wikibus/Argolis/compare/v0.4.1...v0.4.2) (2019-04-30)

### Bug Fixes

* [Drop .NET Framework](https://github.com/wikibus/Argolis/pull/18)
* [Create a NancyContext wrapper so that API authors can inject it](https://github.com/wikibus/Argolis/pull/17)

### [0.4.1](https://github.com/wikibus/Argolis/compare/v0.4...v0.4.1) (2019-04-28)

### Bug Fixes

* update RDF vocabs to fix broken hydra uri in contexts

### Build

* change package dependencies to simplify installation

## [0.4](https://github.com/wikibus/Argolis/compare/v0.2.1...v0.4) (2019-04-28)

### Features

* [IRI templates](https://github.com/wikibus/Argolis/pull/10)
* [Generate HTTP doc link behind proxy](https://github.com/wikibus/Argolis/pull/14)
* [.NET Standard](https://github.com/wikibus/Argolis/pull/13)

## 0.2.1 (2017-10-25)

Ancient history, initial usable release.


text:
var JSONStream = require('JSONStream')
var Readable = require('stream').Readable
var SearchIndexAdder = require('../')
var SearchIndexSearcher = require('search-index-searcher')
var fs = require('fs')
var test = require('tape')

var resultsForStarUSA = [
  '998',
  '997',
  '996',
  '995',
  '994',
  '993',
  '992',
  '991',
  '510',
  '287'
]

test('set seperator at field level', function (t) {
  t.plan(5)
  var batch = [{
    id: '1',
    title: 'thisxisxaxtitle',
    body: 'horsexzebraxelephant'
  }, {
    id: '2',
    title: 'this is a title',
    body: 'horse zebra elephant'
  }]
  const s = new Readable({ objectMode: true })
  batch.forEach(function (elem) {
    s.push(elem)
  })
  s.push(null)
  SearchIndexAdder({
    indexPath: 'test/sandbox/separatorTest'
  }, function (err, indexer) {
    t.error(err)
    s.pipe(indexer.defaultPipeline())
      .on('data', function (data) {
        t.looseEqual(
          Object.keys(data),
          [ 'normalised', 'options', 'raw', 'stored', 'tokenised', 'vector', 'id' ])
      })
      .pipe(indexer.add())
      .on('data', function (data) {})
      .on('end', function () {
        indexer.close(function (err) {
          t.error(err)
          SearchIndexSearcher(indexer.options, function (err, searcher) {
            t.error(err)
            var q = {}
            q.query = [{
              AND: {'*': ['zebra']}
            }]
            searcher.search(q)
              .on('data', function (data) {
                t.ok(data.document.id === '1')
              })
          })
        })
      })
  })
})

test('simple indexing test', function (t) {
  t.plan(5)
  var j = 0
  var k = 0
  SearchIndexAdder({
    indexPath: 'test/sandbox/simpleIndexing',
    searchable: false,
    wildcard: false,
    compositeField: false,
    appendOnly: true,
    fastSort: false,
    storeDocument: false,
    fieldOptions: {
      places: {
        searchable: true
      }
    }
  }, function (err, indexer) {
    t.error(err)
    fs.createReadStream('./node_modules/reuters-21578-json/data/fullFileStream/000.str')
      .pipe(JSONStream.parse())
      .on('data', function (data) {
        j++
      })
      .pipe(indexer.defaultPipeline())
      .on('data', function (data) {
        k++
      })
      .pipe(indexer.add())
      .on('data', function (data) {})
      .on('finish', function () {
        indexer.close(function (err) {
          t.error(err)
          t.equals(j, 1000)
          t.equals(k, 1000)
          SearchIndexSearcher(indexer.options, function (err, searcher) {
            t.error(err)
            var q = {}
            q.query = {
              AND: {'places': ['usa']}
            }
            q.pageSize = 10
            var i = 0
            searcher.search(q).on('data', function (data) {
              console.log(data.document.id)
              t.equals(resultsForStarUSA[i++], data.document.id)
            })
          })
        })
      })
  })
})

// TODO: make this work again

test('preserve array fields in stored document', function (t) {
  t.plan(5)
  SearchIndexAdder({indexPath: 'test/sandbox/preserveArrayFields'}, function (err, indexer) {
    t.error(err)
    SearchIndexSearcher(indexer.options, function (err, searcher) {
      t.error(err)
      const s = new Readable({ objectMode: true })
      s.push({'id': '1', 'anArray': ['one', 'two', 'three']})
      s.push(null)
      s.pipe(indexer.defaultPipeline())
        .pipe(indexer.add())
        .on('data', function (data) {})
        .on('finish', function () {
          var q = {}
          q.query = {
            AND: {'*': ['one']}
          }
          searcher.search(q)
            .on('data', function (data) {
              t.equals(data.document.id, '1')
              t.looseEquals(data.document.anArray, ['one', 'two', 'three'])
            })
            .on('end', function () {
              t.ok(true)
            })
        })
    })
  })
})


text:
package nate.cluster;

public interface Cluster {

  /**
   * A destructive function that merges another cluster into this one.
   */
  public void merge(Object cluster);
}


text:
<?php

namespace Minor\Event;

use ArrayAccess;

class Event implements ArrayAccess
{
    public $elements;

    public function offsetExists($offset)
    {
        return isset($this->elements[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->elements[$offset];
    }

    public function offsetSet ($offset, $value)
    {
        $this->elements[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->elements[$offset]);
    }
}


text:
--TEST--
executes two queries as part of a transaction
--SKIPIF--

--FILE--
<?php
require('connect.inc');

// First, reset the RevisionNumber to make sure it won't overflow
ResetRevisionNumber( $server, $databaseName, $uid, $pwd );

$connectionInfo = array( "Database"=>"$databaseName", "UID"=>$uid, "PWD"=>$pwd);
$conn = sqlsrv_connect( $server, $connectionInfo);
if( $conn === false )
{
     echo "Could not connect.\n";
     die( print_r( sqlsrv_errors(), true ));
}

/* Initiate transaction. */
/* Exit script if transaction cannot be initiated. */
if ( sqlsrv_begin_transaction( $conn ) === false )
{
     echo "Could not begin transaction.\n";
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 43659; $qty = 5; $productId = 709;
$offerId = 1; $price = 5.70;

/* Set up and execute the first query. */
$tsql1 = "INSERT INTO Sales.SalesOrderDetail
                     (SalesOrderID,
                      OrderQty,
                      ProductID,
                      SpecialOfferID,
                      UnitPrice)
          VALUES (?, ?, ?, ?, ?)";
$params1 = array( $orderId, $qty, $productId, $offerId, $price);
$stmt1 = sqlsrv_query( $conn, $tsql1, $params1 );

/* Set up and execute the second query. */
$tsql2 = "UPDATE Production.ProductInventory
          SET Quantity = (Quantity - ?)
          WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $tsql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 )
{
     sqlsrv_commit( $conn );
     echo "Transaction was committed.\n";
}
else
{
     sqlsrv_rollback( $conn );
     echo "Transaction was rolled back.\n";
}

/* Revert the changes */
$d_sql = "DELETE FROM Sales.SalesOrderDetail WHERE SalesOrderID=43659 AND OrderQty=5 AND ProductID=709 AND SpecialOfferID=1 AND Unitprice=5.70";
$stmt3 = sqlsrv_query($conn, $d_sql);

/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt1);
sqlsrv_free_stmt( $stmt2);
sqlsrv_free_stmt($stmt3);
sqlsrv_close( $conn);
?>
--EXPECT--
Transaction was committed.


text:
Omgrepet "teori" blir brukt forskjellig i dagleglivet og i vitskapen. I naturfag er teoriar den sikraste kunnskapen vi har til no, mens vi til dagleg ser på ein teori som noko usikkert. Vi kjem fram til vitskaplege teoriar gjennom eksperiment og observasjonar.

Lenke til animasjon.
Animasjon: Frå hypotesedanning til teori.

Pipettering
Eksperiment går føre seg!

> Alt for å finne det sannes mysterium,
> - det er den ekte forskers kriterium.
> Henrik Ibsen

##Frå hypotese til teori

Når du skal løyse eit problem etter naturvitskapleg arbeidsmåte, begynner du med å setje opp ein eller fleire hypotesar for kva du meiner løysinga kan vere. Ein hypotese kan nærast beskrivast som ei kvalifisert gjetting – du veit enno ikkje kva løysinga vil vere, men du har ein idé.

For å kontrollere om hypotesen din stemmer, konstruerer du ulike eksperiment (forsøk) som vil vise om du har rett eller ikkje. Det er viktig å beskrive desse forsøka nøye, slik at andre kan etterprøve konklusjonane dine ved å gjennomføre dei same eksperimenta på den same måten.

Veien fra observasjon til teori
Utveljing av ein hypotese som skal testast.

##Eit foreløpig mål

Dersom andre gjennomfører dei same eksperimenta som deg og kjem til dei same resultata, vil det bli semje om at hypotesen er ein god modell for å beskrive det verkelege. Når forskarmiljøet har komme fram til ei slik semje, vil hypotesen bli omdøypt til ein teori.

Ein teori er altså inga gjetting, men noko som er underbygd av ulike eksperiment over lang tid – noko som forskarar verda over stort sett er einige om.


text: mp3tagiconv --do-update *.mp3


text:
#pragma once

// ensure the MCU series is correct
#ifndef STM32PLUS_F0
#error This class can only be used with the STM32F0 series
#endif

namespace stm32plus {

  /**
   * Base class for I2C peripherals. Takes care of the common operations
   * that each peripheral can have
   */

  class I2C {

    public:

      /**
       * I2C parameters class
       */

      struct Parameters {
        uint32_t i2c_timing;
        bool     i2c_analogFilter;
        uint8_t  i2c_digitalFilter;       // number of i2c clocks to ignore spikes
        bool     i2c_ack;
        uint16_t i2c_ackAddress;
        uint16_t i2c_ownAddress;
        uint8_t  i2c_addressSize;        // byte-size of the 'address' or 'register' index on the peripheral

        Parameters(uint32_t timing=0x00201D2B) {
          i2c_timing=timing;
          i2c_analogFilter=true;
          i2c_digitalFilter=0;
          i2c_ack=true;
          i2c_ackAddress=I2C_AcknowledgedAddress_7bit;
          i2c_ownAddress=0xFE;
          i2c_addressSize=1;
        }
      };

      enum {
        E_I2C_TIMEOUT=1         ///< timed out waiting for a response
      };

    protected:
      I2C_TypeDef *_peripheralAddress;
      uint8_t _addressSize;

    protected:
      I2C(const Parameters& params,I2C_TypeDef *peripheralAddress);

    public:
      void enablePeripheral() const;
      void disablePeripheral() const;

      uint8_t getAddressSize() const;
      void setAddressSize(uint8_t addressSize);

      operator I2C_TypeDef *();
  };

  /**
   * Constructor
   */

  inline I2C::I2C(const Parameters& params,I2C_TypeDef *peripheralAddress)
    : _peripheralAddress(peripheralAddress),
      _addressSize(params.i2c_addressSize) {
  }

  /**
   * Enable the peripheral
   */

  inline void I2C::enablePeripheral() const {
    I2C_Cmd(_peripheralAddress,ENABLE);
  }

  /**
   * Disable the peripheral
   */

  inline void I2C::disablePeripheral() const {
    I2C_Cmd(_peripheralAddress,DISABLE);
  }

  /**
   * Cast to a I2C peripheral structure
   */

  inline I2C::operator I2C_TypeDef *() {
    return _peripheralAddress;
  }

  /**
   * Get the address or register size in bytes. Often this is just one byte where the IC has
   * less than 255 registers but in EEPROMs etc. could be multiple bytes to fit in an 'address'
   * to read or write from/to.
   * @return The byte width
   */

  inline uint8_t I2C::getAddressSize() const {
    return _addressSize;
  }

  /**
   * Set the address size
   * @param addressSize The new address size
   */

  inline void I2C::setAddressSize(uint8_t addressSize) {
    _addressSize=addressSize;
  }
}


text:
//! \file

#ifndef TNT_FILAMENT_BOX_H
#define TNT_FILAMENT_BOX_H

#include <utils/compiler.h>

#include <limits>

#include <math/mat4.h>
#include <math/vec3.h>

namespace filament {

/**
 * An axis aligned 3D box represented by its center and half-extent.
 */
class UTILS_PUBLIC Box {
public:
    /** Center of the 3D box */
    math::float3 center = {};

    /** Half extent from the center on all 3 axis */
    math::float3 halfExtent = {};

    /**
     * Whether the box is empty, i.e.: it's volume is null.
     * @return true if the volume of the box is null
     */
    constexpr bool isEmpty() const noexcept {
        return length2(halfExtent) == 0;
    }

    /**
     * Computes the lowest coordinates corner of the box.
     * @return center - halfExtent
     */
    constexpr math::float3 getMin() const noexcept {
        return center - halfExtent;
    }

    /**
     * Computes the largest coordinates corner of the box.
     * @return center + halfExtent
     */
    constexpr math::float3 getMax() const noexcept {
        return center + halfExtent;
    }

    /**
     * Initializes the 3D box from its min / max coordinates on each axis
     * @param min lowest coordinates corner of the box
     * @param max largest coordinates corner of the box
     * @return This bounding box
     */
    Box& set(const math::float3& min, const math::float3& max) noexcept {
        // float3 ctor needed for visual studio
        center     = (max + min) * math::float3(0.5f);
        halfExtent = (max - min) * math::float3(0.5f);
        return *this;
    }

    /**
     * Computes the bounding box of the union of two boxes
     * @param box The box to be combined with
     * @return The bounding box of the union of *this and box
     */
    Box& unionSelf(const Box& box) noexcept {
        set(min(getMin(), box.getMin()), max(getMax(), box.getMax()));
        return *this;
    }

    /**
     * Translates the box *to* a given center position
     * @param tr position to translate the box to
     * @return A box centered in \p tr with the same extent than *this
     */
    constexpr Box translateTo(const math::float3& tr) const noexcept {
        return Box{ tr, halfExtent };
    }

    /**
     * Computes the smallest bounding sphere of the box.
     * @return The smallest sphere defined by its center (.xyz) and radius (.w) that contains *this
     */
    math::float4 getBoundingSphere() const noexcept {
        return { center, length(halfExtent) };
    }

    /**
     * Computes the bounding box of a box transformed by a rigid transform
     * @param box the box to transform
     * @param m a 4x4 matrix that must be a rigid transform
     * @return the bounding box of the transformed box.
     *         Result is undefined if \p m is not a rigid transform
     */
    friend Box rigidTransform(Box const& box, const math::mat4f& m) noexcept;

    /**
     * Computes the bounding box of a box transformed by a rigid transform
     * @param box the box to transform
     * @param m a 3x3 matrix that must be a rigid transform
     * @return the bounding box of the transformed box.
     *         Result is undefined if \p m is not a rigid transform
     */
    friend Box rigidTransform(Box const& box, const math::mat3f& m) noexcept;
};

/**
 * An axis aligned box represented by its min and max coordinates
 */
struct UTILS_PUBLIC Aabb {

    /** min coordinates */
    math::float3 min = std::numeric_limits<float>::max();

    /** max coordinates */
    math::float3 max = std::numeric_limits<float>::lowest();

    /**
     * Computes the center of the box.
     * @return (max + min)/2
     */
    math::float3 center() const noexcept {
        // float3 ctor needed for visual studio
        return (max + min) * math::float3(0.5f);
    }

    /**
     * Computes the half-extent of the box.
     * @return (max - min)/2
     */
    math::float3 extent() const noexcept {
        // float3 ctor needed for visual studio
        return (max - min) * math::float3(0.5f);
    }

    /**
     * Whether the box is empty, i.e.: it's volume is null or negative.
     * @return true if min >= max, i.e: the volume of the box is null or negative
     */
    bool isEmpty() const noexcept {
        return any(greaterThanEqual(min, max));
    }

    struct Corners {
        using value_type = math::float3;
        value_type const* begin() const { return vertices; }
        value_type const* end() const { return vertices + 8; }
        value_type * begin() { return vertices; }
        value_type * end() { return vertices + 8; }
        value_type const* data() const { return vertices; }
        value_type * data() { return vertices; }
        size_t size() const { return 8; }
        value_type vertices[8];
    };

    /**
     * Returns the 8 corner vertices of the AABB.
     */
    Corners getCorners() const;

    /**
     * Returns whether the box contains a given point.
     *
     * @param p the point to test
     * @return the maximum signed distance to the box. Negative if p is in the box
     */
    float contains(math::float3 p) const noexcept;

    /**
     * Applies an affine transformation to the AABB.
     *
     * @param m the 4x4 transformation to apply
     * @return the transformed box
     */
    Aabb transform(const math::mat4f& m) const noexcept;
};

} // namespace filament

#endif // TNT_FILAMENT_BOX_H


text:
pub use algorithms::generator::{Generator, DefaultGenerator, DigitBaseGenerator};

pub use expectest::prelude::be_equal_to;

describe! generator_tests {

    describe! default_generator_tests {

        it "should generate numbers from 0 till 100" {
            let mut generator = DefaultGenerator::new();

            let data = (0..).take(101).collect::<Vec<usize>>();
            let mut vec = Vec::with_capacity(100);
            for _ in (0..).take(101) {
                vec.push(generator.next());
            }

            expect!(vec).to(be_equal_to(data));
        }
    }

    describe! digit_base_generator_tests {

        it "should generate numebrs with spaces between 10..16, 26..32 and so on" {
            let mut generator = DigitBaseGenerator::new(16, 10);

            let mut data = Vec::new();
            for i in (0..).take(101) {
                let iter = i / 16;
                if i < 10 + iter*16 {
                    data.push(i);
                }
            }

            let mut vec = Vec::new();
            for _ in 0..data.len() {
                vec.push(generator.next());
            }

            expect!(vec).to(be_equal_to(data));
        }
    }
}


text:
The easiest way to run microservices, big data, and containers in production.

# What is DC/OS?

Like traditional operating systems, DC/OS is system software that manages computer hardware and software resources and provides common services for computer programs.

Unlike traditional operating systems, DC/OS spans multiple machines within a network, aggregating their resources to maximize utilization by distributed applications.

To learn more, see the [DC/OS Overview](https://dcos.io/docs/latest/overview/).

# How Do I...?

- Learn More - <https://dcos.io/>
- Find the Docs - <https://dcos.io/docs/>
- Install - <https://dcos.io/install/>
- Get Started - <https://dcos.io/get-started/>
- Get Help - <http://chat.dcos.io/>
- Join the Discussion - <https://groups.google.com/a/dcos.io/d/forum/users>
- Report an Issue - <https://jira.dcos.io>
- Contribute - <https://dcos.io/contribute/>

# Releases

DC/OS releases are publicly available on <http://dcos.io/releases/>

Release artifacts are managed by Mesosphere on Amazon S3, using a CloudFront cache.

To find the git SHA of any given release, check the latest commit in the versioned branches on GitHub: <https://github.com/dcos/dcos/branches/>

| Release Type | URL Pattern |
|--------------|--------------------|
| Latest Stable| `https://downloads.dcos.io/dcos/stable/dcos_generate_config.sh` |
| Latest Master | `https://downloads.dcos.io/dcos/testing/master/dcos_generate_config.sh` |
| Specific PR, Latest Build	| `https://downloads.dcos.io/dcos/testing/pull/<github-pr-number>/dcos_generate_config.sh` |

# Development Environment

**Linux is required for building and testing DC/OS.**

1. Linux distribution:
    - Docker doesn't have all the features needed on OS X or Windows
    - `tar` needs to be GNU tar for the set of flags used
    - `unzip` needs to be installed
1. [tox](https://tox.readthedocs.org/en/latest/)
1. git 1.8.5+
1. Docker 1.11+
    - [Install Instructions for various distributions](https://docs.docker.com/engine/installation/). Docker needs to be configured so your user can run docker containers. The command `docker run alpine  /bin/echo 'Hello, World!'` when run at a new terminal as your user should just print `"Hello, World!"`. If it says something like "Unable to find image 'alpine:latest' locally" then re-run and the message should go away.
1. Python 3.6
    - Arch Linux: `sudo pacman -S python`
    - Fedora 23 Workstation: Already installed by default / no steps
    - Ubuntu 16.04 LTS:
        - [pyenv-installer](https://github.com/yyuu/pyenv-installer)
        - Python dependencies: `sudo apt-get install make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils liblzma-dev python3-venv`
        - Install Python 3.6.3: `pyenv install 3.6.3`
        - Create DC/OS virtualenv: `pyenv virtualenv 3.6.3 dcos`
        - Activate environment: `pyenv activate dcos`
1. Over 10GB of free disk space and 8GB of RAM
    - The build makes use of hard links, so if you're using VirtualBox the disk space cannot be a synced folder.
1. _Optional_ pxz (speeds up package and bootstrap compression)
    - ArchLinux: [pxz-git in the AUR](https://aur.archlinux.org/packages/pxz-git). The pxz package corrupts tarballs fairly frequently.
    - Fedora 23: `sudo dnf install pxz`

# Unit Tests

Unit tests can be run locally but require the [development environment](#development-environment) specified above.

```
tox
```

[Tox](https://tox.readthedocs.io/en/latest/) is used to run the codebase unit tests, as well as coding standard checks. The config is in `tox.ini`.

# Integration Tests

Integration tests can be run on any deployed DC/OS cluster. For installation instructions, see <https://dcos.io/install/>.

Integration tests are installed via the [dcos-integration-test](./packages/dcos-integration-test/) Pkgpanda package.

Integration test files are stored on the DC/OS master node at `/opt/mesosphere/active/dcos-integration-test`.
Therefore, in order to test changes to test files, move files from `packages/dcos-integration-test/extra/` in your checkout to `/opt/mesosphere/active/dcos-integration-test` on the master node.

The canonical source of the test suite's results is the continuous integration system.
There may be differences between the results of running the integration tests as described in this document and the results given by the continuous integration system.
In particular, some tests may pass on the continuous integration system and fail locally or vice versa.

## Minimum Requirements

- 1 master node
- 2 private agent nodes
- 1 public agent node
- Task resource allocation is currently insignificantly small
- DC/OS itself requires at least 2 (virtual) cpu cores on each node

## Instructions

1. SSH into a master node
The tests can be run via Pytest while SSH'd as root into a master node of the cluster to be tested.

1. Switch to root

    ```
    sudo su -
    ```

1. Add the test user

    ```
    dcos-shell python /opt/mesosphere/active/dcos-oauth/bin/dcos_add_user.py albert@bekstil.net
    ```

    Running the above mentioned command will result in an output

    ```
    User albert@bekstil.net successfully added
    ```

    This test user has a known login token with far future expiration. DO NOT USE IN PRODUCTION.
    After the test, remember to delete the test user.

    For more information, see [User Management](https://dcos.io/docs/latest/administration/user-management/).

2. Run the tests using pytest in the cluster.

    ```
    cd /opt/mesosphere/active/dcos-integration-test
    dcos-shell pytest
    ```

## Using DC/OS Docker

One way to run the integration tests is to use [DC/OS Docker](https://github.com/dcos/dcos-docker).

1. Setup DC/OS in containers using [DC/OS Docker](https://github.com/dcos/dcos-docker).

One way to do this is to use the [DC/OS Docker Quick Start tool](https://github.com/dcos/dcos-docker#quick-start).

2. Run `make test`.

# Build

DC/OS can be built locally but requires the [development environment](#development-environment) specified above.

DC/OS builds are packaged as a self-extracting Docker image wrapped in a bash script called `dcos_generate_config.sh`.

**WARNING**: Building a release from scratch the first time on a modern dev machine (4 cores / 8 hyper threads, SSD, reasonable internet bandwidth) takes about 1 hour.

## Instructions

```
./build_local.sh
```

That will run a simple local build, and output the resulting DC/OS installers to $HOME/dcos-artifacts. You can run the created `dcos_generate_config.sh like so:

```
$ $HOME/dcos-artifacts/testing/`whoami`/dcos_generate_config.sh
```

## Build Details

If you look inside of the bash script `build_local.sh` there are the commands with descriptions of each.

The general flow is to:
 1. Check the environment is reasonable
 2. Write a `release` tool configuration if one doesn't exist
 3. Setup a python virtualenv where we can install the DC/OS python tools to in order to run them
 4. Install the DC/OS python tools to the virtualenv
 5. Build the release using the `release` tool

These steps can all be done by hand and customized / tweaked like standard python projects. You can hand create a virtualenvironment, and then do an editable pip install (`pip install -e`) to have a "live" working environment (as you change code you can run the tool and see the results).

## Release Tool Configuration

This release tool always loads the config in `dcos-release.config.yaml` in the current directory.

The config is [YAML](http://yaml.org/). Inside it has two main sections. `storage` which contains a dictionary of different storage providers which the built artifacts should be sent to, and `options` which sets general DC/OS build configuration options.

Config values can either be specified directly, or you may use $ prefixed environment variables (the env variable must set the whole value).

### Storage Providers

All the available storage providers are in [release/storage](./release/storage/). The configuration is a dictionary of a reference name for the storage provider (local, aws, my_azure), to the configuration.

Each storage provider (ex: aws.py) is an available kind prefix. The dictionary `factories` defines the suffix for a particular kind. For instance `kind: aws_s3` would map to the S3StorageProvider.

The configuration options for a storage provider are the storage provider's constructor parameters.

Sample config storage that will save to my home directory (/home/cmaloney):
```yaml
storage:
  local:
    kind: local_path
    path: /home/cmaloney/dcos-artifacts
```

Sample config that will store to a local archive path as well as AWS S3. To authenticate with AWS S3, reference the [boto3 docs](http://boto3.readthedocs.io/en/latest/guide/configuration.html#configuring-credentials) to learn how to configure access.
```yaml
storage:
  aws:
    kind: aws_s3
    bucket: downloads.dcos.io
    object_prefix: dcos
    download_url: https://downloads.dcos.io/dcos/
  local:
    kind: local_path
    path: /mnt/big_artifact_store/dcos/
```

# Repo Structure

DC/OS itself is composed of many individual components precisely configured to work together in concert.

This repo contains the release and package building tools necessary to produce installers for various on-premises and cloud platforms.

| Directory | Contents |
| --------- | -------- |
| *cloud_images*       | Base OS image building tools
| *config*             | Release configuration
| *docs*               | Documentation
| *flake8_dcos_lint*   | Flake8 plugin for testing code quality
| *dcos_installer*     | Backend for Web, SSH, and some bits of the Advanced installer. Code is being cleaned up
| *gen*                | Python library for rendering yaml config files for various platforms into packages, with utilities to do things like make "late binding" config set by CloudFormation
| *packages*           | Packages which make up DC/OS (Mesos, Marathon, AdminRouter, etc). These packages are built by pkgpanda, and combined into a "bootstrap" tarball for deployment.
| *pkgpanda*           | DC/OS baseline/host package management system. Tools for building, deploying, upgrading, and bundling packages together which live on the root filesystem of a machine / underneath Mesos.
| *release*            | Release tools for DC/OS. (Building releases, building installers for releases, promoting between channels)
| *ssh*                | AsyncIO based parallel ssh library used by the installer
| *test_util*          | various scripts, utilities to help with integration testing

# Pull Requests Statuses

Pull requests automatically trigger a new DC/OS build and run several tests. These are the details on the various status checks against a DC/OS Pull Request.

| Status Check                                   | Purpose                                                                                | Source and Dependencies                                                                                |
|------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|
| continuous-integration/jenkins/pr-head         | Admin Router Endpoint tests                                                                                | [dcos/dcos/packages/adminrouter/extra/src/test-harness](https://github.com/dcos/dcos/tree/master/packages/adminrouter/extra/src/test-harness) Docker Dependency: [dcos/dcos/packages/adminrouter](https://github.com/dcos/dcos/blob/master/packages/adminrouter/buildinfo.json) |
| mergebot/enterprise/build-status/aggregate     | EE Test Enforcement                                                                                | Private [mesosphere/dcos-enterprise](https://github.com/mesosphere/dcos-enterprise) repo is tested against the SHA.                                             |
| mergebot/enterprise/has_ship-it                | Code Review Enforcement                                                                                | Private [Mergebot](https://github.com/mesosphere/mergebot) service in prod cluster                                                                       |
| mergebot/enterprise/review/approved/min_2      | Code Review Enforcement                                                                                | Mergebot service in prod cluster                                                                       |
| mergebot/has_ship-it                           | Code Review Enforcement                                                                                | Mergebot service in prod cluster                                                                       |
| mergebot/review/approved/min_2                 | Code Review Enforcement                                                                                | Mergebot service in prod cluster                                                                       |
| teamcity/dcos/build/dcos                       | Builds DCOS Image (dcos_generate_config.sh)                                                                             | [gen/build_deploy/bash.py](https://github.com/dcos/dcos/blob/master/gen/build_deploy/bash.py)                                                                            |
| teamcity/dcos/build/tox                        | Runs check-style, unit-tests                                                                                | [tox.ini](https://github.com/dcos/dcos/blob/master/tox.ini)                                                                                |
| teamcity/dcos/test/aws/cloudformation/simple   | Deployment using single-master-cloudformation.json and runs integration tests                                           | [gen/build_deploy/aws.py](https://github.com/dcos/dcos/blob/master/gen/build_deploy/aws.py), Uses [dcos-launch](https://github.com/dcos/dcos-launch/) binary in CI                                                 |
| teamcity/dcos/test/aws/onprem/static           | Installation via dcos_generation_config.sh and runs Integration Tests                                                   | [gen/build_deploy/bash.py](https://github.com/dcos/dcos/blob/master/gen/build_deploy/bash.py), Uses [dcos-launch](https://github.com/dcos/dcos-launch/) binary in CI                                                |
| teamcity/dcos/test/azure/arm                   | Deployment using acs-1master.azuredeploy.json and runs integration tests.                                               | [gen/build_deploy/azure.py](https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py), Uses [dcos-launch](https://github.com/dcos/dcos-launch/) binary in CI                                               |
| teamcity/dcos/test/docker                      | Exercises dcos-docker by launching dcos-docker against this PR and running integration tests within the docker cluster. | [dcos-docker](https://github.com/dcos/dcos-docker) repo                                                                                |
| teamcity/dcos/test/docker/smoke                | Exercises dcos-docker by launching dcos-docker against this PR and running *smoke* tests within the docker cluster.     | dcos-docker repo                                                                                |
| teamcity/dcos/test/upgrade                     | Upgrade from stable minor version                                                                                | [mesosphere/advanced-tests](https://github.com/mesosphere/advanced-tests/) repo (transitively, [dcos/dcos-test-utils](https://github.com/dcos/dcos-test-utils) , dcos/dcos-launch)                  |
| teamcity/dcos/test/upgrade-from-previous-major | Upgrade from previous major version                                                                                | mesosphere/advanced-tests repo (transitively, dcos/dcos-test-utils, dcos/dcos-launch)                  |
| teamcity/dcos/test/upgrade-to-next-major       | Upgrade to Next Major version                                                                                | mesosphere/advanced-tests repo (transitively, dcos/dcos-test-utils, dcos/dcos-launch)                  |


text:
/*
 * INET		An implementation of the TCP/IP protocol suite for the LINUX
 *		operating system.  INET is implemented using the  BSD Socket
 *		interface as the means of communication with the user level.
 *
 *		Global definitions for the Frame relay interface.
 *
 * Version:	@(#)if_ifrad.h	0.20	13 Apr 96
 *
 * Author:	Mike McLagan <mike.mclagan@linux.org>
 *
 * Changes:
 *		0.15	Mike McLagan	Structure packing
 *
 *		0.20	Mike McLagan	New flags for S508 buffer handling
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 */

#ifndef SDLA_H
#define SDLA_H

/* adapter type */
#define SDLA_TYPES
#define SDLA_S502A			5020
#define SDLA_S502E			5021
#define SDLA_S503			5030
#define SDLA_S507			5070
#define SDLA_S508			5080
#define SDLA_S509			5090
#define SDLA_UNKNOWN			-1

/* port selection flags for the S508 */
#define SDLA_S508_PORT_V35		0x00
#define SDLA_S508_PORT_RS232		0x02

/* Z80 CPU speeds */
#define SDLA_CPU_3M			0x00
#define SDLA_CPU_5M			0x01
#define SDLA_CPU_7M			0x02
#define SDLA_CPU_8M			0x03
#define SDLA_CPU_10M			0x04
#define SDLA_CPU_16M			0x05
#define SDLA_CPU_12M			0x06

/* some private IOCTLs */
#define SDLA_IDENTIFY			(FRAD_LAST_IOCTL + 1)
#define SDLA_CPUSPEED			(FRAD_LAST_IOCTL + 2)
#define SDLA_PROTOCOL			(FRAD_LAST_IOCTL + 3)

#define SDLA_CLEARMEM			(FRAD_LAST_IOCTL + 4)
#define SDLA_WRITEMEM			(FRAD_LAST_IOCTL + 5)
#define SDLA_READMEM			(FRAD_LAST_IOCTL + 6)

struct sdla_mem {
   int  addr;
   int  len;
   void *data;
};

#define SDLA_START			(FRAD_LAST_IOCTL + 7)
#define SDLA_STOP			(FRAD_LAST_IOCTL + 8)

/* some offsets in the Z80's memory space */
#define SDLA_NMIADDR			0x0000
#define SDLA_CONF_ADDR			0x0010
#define SDLA_S502A_NMIADDR		0x0066
#define SDLA_CODE_BASEADDR		0x0100
#define SDLA_WINDOW_SIZE		0x2000
#define SDLA_ADDR_MASK			0x1FFF

/* largest handleable block of data */
#define SDLA_MAX_DATA			4080
#define SDLA_MAX_MTU			4072	/* MAX_DATA - sizeof(fradhdr) */
#define SDLA_MAX_DLCI			24

/* this should be the same as frad_conf */
struct sdla_conf {
   short station;
   short config;
   short kbaud;
   short clocking;
   short max_frm;
   short T391;
   short T392;
   short N391;
   short N392;
   short N393;
   short CIR_fwd;
   short Bc_fwd;
   short Be_fwd;
   short CIR_bwd;
   short Bc_bwd;
   short Be_bwd;
};

/* this should be the same as dlci_conf */
struct sdla_dlci_conf {
   short config;
   short CIR_fwd;
   short Bc_fwd;
   short Be_fwd;
   short CIR_bwd;
   short Bc_bwd;
   short Be_bwd;
   short Tc_fwd;
   short Tc_bwd;
   short Tf_max;
   short Tb_max;
};

void sdla(void *cfg_info, char *dev, struct frad_conf *conf, int quiet);

#endif


text:
using System;

namespace FSL.MvcDataAnnotationsHtmlHelpersKnockoutJS.Annotations
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public class DataBindAttribute : TagAttribute
    {
        public DataBindAttribute(string tagValue)
            : base(tagValue)
        {

        }

        public override void InitData()
        {
            TagName = "data-bind";
        }
    }
}


text:
define(["jquery", "jquery.stacky"], function($) {

    $(function() {
        'use strict';

        var sizes = ['thin', 'medium', 'wide'],
            content = $('

'),
            open = $('').addClass('open-panel').append($('').addClass('fa fa-folder-open-o')),
            openFloating = $('').addClass('open-panel open-floating-panel').append($('').addClass('fa fa-folder-open')),
            close = $('').addClass('close').append($('').addClass('fa fa-times')),
            expand = $('').addClass('expand').append($('').addClass('fa fa-expand')),
            collapse = $('').addClass('collapse').append($('').addClass('fa fa-minus')),
            header = $('')
                        .append(open)
                        .append(openFloating)
                        .append(expand)
                        .append(collapse)
                        .append(close);

            content.append(header);

        // Returns a random integer between min (included) and max (excluded)
        function getRandomInt(min, max) {
          return Math.floor(Math.random() * (max - min)) + min;
        };

        // Initialize the Stacky plugin
        var stackyContainer = $('#panels').Stacky({
            fadeInSpeed: 'fast',
            scrollToSpeed: 600,
            panelDefaults: {
                content: content.html(),
                onBeforeOpen: function($panel){
                    console.log('Pushing', $panel);
                },
                onBeforeClose: function($panel){
                    console.log('Removed', $panel);
                }
            }
        });

        // Binds click to create new panels
        $(document).on('click', ".open-panel", function(){
            var self = $(this),
                afterPanel = self.closest('.panel'),
                isFloating = self.hasClass('open-floating-panel'),
                identifier = getRandomInt(0, 1000);

            if(afterPanel.length == 0){
                afterPanel = undefined;
            }

            var $panel = stackyContainer.data('Stacky').push({
                id: 'panel-' + identifier,
                class: 'regular',   // width
                floating: isFloating,
                after: isFloating ? afterPanel : undefined
            });
        });

    });

});


text:
package com.lachesis.support.objects.vo.auth;

import java.util.ArrayList;
import java.util.Collection;

public class LocalUserVO{
	private String id;
	private String username;
	private String password;
	private Collection<String> roles = new ArrayList<String>();
	private Collection<String> permissions = new ArrayList<String>();

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Collection<String> getRoles() {
		return roles;
	}

	public void setRoles(Collection<String> roles) {
		if (roles != null) {
			this.roles.clear();
			this.roles.addAll(roles);
		}
	}

	public Collection<String> getPermissions() {
		return permissions;
	}

	public void setPermissions(Collection<String> permissions) {
		if(permissions != null){
			this.permissions.clear();
			this.permissions.addAll(permissions);
		}
	}
}


text:
using namespace llvm;

PreservedAnalyses BitcodeWriterPass::run(Module &M) {
  WriteBitcodeToFile(&M, OS, ShouldPreserveUseListOrder, EmitFunctionSummary);
  return PreservedAnalyses::all();
}

namespace {
  class WriteBitcodePass : public ModulePass {
    raw_ostream &OS; // raw_ostream to print on
    bool ShouldPreserveUseListOrder;
    bool EmitFunctionSummary;

  public:
    static char ID; // Pass identification, replacement for typeid
    explicit WriteBitcodePass(raw_ostream &o, bool ShouldPreserveUseListOrder,
                              bool EmitFunctionSummary)
        : ModulePass(ID), OS(o),
          ShouldPreserveUseListOrder(ShouldPreserveUseListOrder),
          EmitFunctionSummary(EmitFunctionSummary) {}

    const char *getPassName() const override { return "Bitcode Writer"; }

    bool runOnModule(Module &M) override {
      WriteBitcodeToFile(&M, OS, ShouldPreserveUseListOrder,
                         EmitFunctionSummary);
      return false;
    }
  };
}

char WriteBitcodePass::ID = 0;

ModulePass *llvm::createBitcodeWriterPass(raw_ostream &Str,
                                          bool ShouldPreserveUseListOrder,
                                          bool EmitFunctionSummary) {
  return new WriteBitcodePass(Str, ShouldPreserveUseListOrder,
                              EmitFunctionSummary);
}


text:
#ifndef ELFCLOUD_SERVERCONNECTION_H_
#define ELFCLOUD_SERVERCONNECTION_H_

#include "Object.h"
//#include "Client.h"

//#ifdef ELFCLOUD_LIB
#include <json/json.h>
#include <json/value.h>
#include <curl/curl.h>

#include "ext_cryptopp.h"
//#include <cryptopp/md5.h>
//#endif

#include <map>
#include <string>

using namespace std;

typedef enum elfcloudInterfaceType {
	ELFCLOUD_INTERFACE_JSON = 1,
	ELFCLOUD_INTERFACE_STORE,
	ELFCLOUD_INTERFACE_FETCH
} elfcloudInterfaceType;

typedef enum DataItemStoreMode {
	ELFCLOUD_STORE_MODE_NEW = 1,
	ELFCLOUD_STORE_MODE_REPLACE,
	ELFCLOUD_STORE_MODE_APPEND,
	ELFCLOUD_STORE_MODE_PATCH
} DataItemStoreMode;

namespace elfcloud {
    class Client;
    class Container;
    class DataItemFilePassthrough;
}

typedef struct httpBuffer {
		unsigned int bytesUsed;
		unsigned char* buffer;
		unsigned int bufferSize;
		httpBuffer* nextBuffer;

        // Passthrough fetch handlers
        std::shared_ptr<elfcloud::CryptoHelper> cryptoHelper;
        std::shared_ptr<elfcloud::DataItemFilePassthrough> dataitem;
        unsigned int bytesWritten;
        elfcloud::Client *client;
        std::string serverResponseHash;

        // ELFCLOUD response headers when used as header buffer
        std::map<std::string, std::string> headers;

        httpBuffer() {
            bytesUsed=0;
            buffer=0;
            bufferSize=0;
            nextBuffer=0;
            bytesWritten=0;
            client=0;
        }

} httpBuffer;

namespace elfcloud {

class ServerConnection: public elfcloud::Object {
public:
	ServerConnection(Client *pInelfcloudClient);
	virtual ~ServerConnection();

#ifdef ELFCLOUD_LIB
    Json::Value performServerJSONRequest(const Json::Value& pInServerRequest, bool pInAuthRequest = false);
#endif
    void setAddress(const string& pInAddress);

	void performStoreRequestWithFile(
			const DataItemStoreMode pInStoreMode,
			const string& pInKey,
			const unsigned int pInPatchOffset,
			Container& pInParent,
			const string& pInDataPtr,
			const unsigned int pInDataSize,
			Client* client);

	void performStoreRequestWithBuffer(
			const DataItemStoreMode pInStoreMode,
			const string& pInKey,
			const unsigned int pInPatchOffset,
			Container& pInParent,
			unsigned char* pInDataPtr,
			const unsigned int pInDataSize);

	void performFetchRequest(
			const string& pInKey,
			Container& pInParent,
			unsigned char **pOutDataBuffer,
			unsigned int *pOutDataLength,
			Client* client);

	void performServerCoreRequest(const map<string, string> &pInMapRequestHeaders,
			const byte *pInRequestBody,
			const unsigned int pInBodyLength,
			map<string, string> &pOutMapResponseHeaders,
			byte **pOutResponseBody,
			unsigned int *pOutResponseBodyLength,
			const elfcloudInterfaceType pInInterfaceType,
            shared_ptr<DataItemFilePassthrough> pInDataItem=0);

	void setAPIKey(const string& pInAPIKey);
	void setAuthUsername(const string& pInUsername);
	void setAuthPassword(const string& pInPassword);
	void setAuthMethod(const string& pInAuthMethod);

    void setSpeedLimitReceive(unsigned int pInLimit) {
        speedLimitReceive=pInLimit;
    }

    void setSpeedLimitSend(unsigned int pInLimit) {
        speedLimitSend=pInLimit;
    }

	static size_t write_data(void *ptr, size_t size, size_t nmemb, void *userData);
    static size_t write_header(void *ptr, size_t size, size_t nmemb, void *userData);

private:
	bool authenticated;
#ifdef ELFCLOUD_LIB
    CURL *curl;
	CURLcode res;
#endif

	Client *client;

	// elfcloud.org server JSON interface URL
	string address;

	// elfcloud.org server interface URLs for Data Item API Store and Fetch operations
	string dataItemAPIStoreAddress;
	string dataItemAPIFetchAddress;

	string getAPIKey();
	string getAuthMethod();
	string getAuthUsername();
	string getAuthPassword();
	string getAddress();

	static void parseHeader(std::map<string, string>& pOutelfcloudHeaders, std::map<string, string>& pOutAllHeaders, httpBuffer* pInHeaderBuffer);

	string apiKey;
	string authMethod;
	string username;
	string password;

    // Bytes/second, enforced by libcurl. Value of 0 means unlimited speed.
    unsigned int speedLimitSend;

    // Bytes/second, enforced by libcurl. Value of 0 means unlimited speed.
    unsigned int speedLimitReceive;

#ifdef ELFCLOUD_LIB
	Json::Value createRequestAuth();
#endif

	void deleteBufferChain(httpBuffer *httpBodyBuffer);

	// Combine given buffer chain into a single node chain. Returns a new httpBuffer structs that has no further nodes.
	// Both old and new buffers must be released by the caller.
	httpBuffer mergeBufferChain(const httpBuffer& pInBuffer);

	void ensureAuthenticatedState();
};
}

#endif


text:
layout: page
title: Seattle Police Officer 5801 Michael S. Teeter
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/5801/
---

**Age as of Feb. 24, 2016:** 47


text:
package main

import (
	"fmt"
	"sort"
	"strings"

	cloudmonitoring "google.golang.org/api/monitoring/v3"

	"v.io/jiri/tool"
	"v.io/v23/context"
	"v.io/x/lib/cmdline"
	"v.io/x/lib/gcm"
	"v.io/x/ref/lib/v23cmd"
)

// checkFunctions is a map from check names to the corresponding check functions.
var checkFunctions = map[string]func(*context.T, *tool.Context, *cloudmonitoring.Service) error{
	"cloud-syncbase":            checkCloudSyncbaseInstances,
	"jenkins":                   checkJenkins,
	"service-latency":           checkServiceLatency,
	"service-permethod-latency": checkServicePerMethodLatency,
	"service-counters":          checkServiceCounters,
	"service-metadata":          checkServiceMetadata,
	"service-qps":               checkServiceQPS,
	"gce-instance":              checkGCEInstances,
	"rpc-load-test":             checkRPCLoadTest,
}

// cmdCheck represents the "check" command of the vmon tool.
var cmdCheck = &cmdline.Command{
	Name:  "check",
	Short: "Manage checks used for alerting and graphing",
	Long:  "Manage checks whose results are used in GCM for alerting and graphing.",
	Children: []*cmdline.Command{
		cmdCheckList,
		cmdCheckRun,
	},
}

// cmdCheckList represents the "vmon check list" command.
var cmdCheckList = &cmdline.Command{
	Runner: v23cmd.RunnerFunc(runCheckList),
	Name:   "list",
	Short:  "List known checks",
	Long:   "List known checks.",
}

func runCheckList(_ *context.T, env *cmdline.Env, _ []string) error {
	checks := []string{}
	for name := range checkFunctions {
		checks = append(checks, name)
	}
	sort.Strings(checks)
	for _, check := range checks {
		fmt.Fprintf(env.Stdout, "%v\n", check)
	}
	return nil
}

// cmdCheckRun represents the "vmon check run" command.
var cmdCheckRun = &cmdline.Command{
	Runner:   v23cmd.RunnerFunc(runCheckRun),
	Name:     "run",
	Short:    "Run the given checks",
	Long:     "Run the given checks.",
	ArgsName: "<names>",
	ArgsLong: "<names> is a list of names identifying the checks to run. Available: " + strings.Join(knownCheckNames(), ", "),
}

func runCheckRun(v23ctx *context.T, env *cmdline.Env, args []string) error {
	// Check args.
	for _, arg := range args {
		if _, ok := checkFunctions[arg]; !ok {
			return env.UsageErrorf("check %v does not exist", arg)
		}
	}
	if len(args) == 0 {
		return env.UsageErrorf("no checks provided")
	}
	ctx := tool.NewContextFromEnv(env)

	// Authenticate monitoring APIs.
	s, err := gcm.Authenticate(keyFileFlag)
	if err != nil {
		return err
	}

	// Run checks.
	hasError := false
	for _, check := range args {
		// We already checked the given checks all exist.
		checkFn, _ := checkFunctions[check]
		fmt.Fprintf(ctx.Stdout(), "##### Running check %q #####\n", check)
		err := checkFn(v23ctx, ctx, s)
		if err != nil {
			fmt.Fprintf(ctx.Stderr(), "%v\n", err)
			fmt.Fprintf(ctx.Stdout(), "##### FAIL #####\n")
			hasError = true
		} else {
			fmt.Fprintf(ctx.Stdout(), "##### PASS #####\n")
		}
	}
	if hasError {
		return fmt.Errorf("Failed to run some checks.")
	}

	return nil
}

func knownCheckNames() []string {
	names := []string{}
	for n := range checkFunctions {
		names = append(names, n)
	}
	sort.Strings(names)
	return names
}