text:
<?xml version="1.0" ?>
<Simulation verbosity="debug">
  <TestInfo>
    <name>framework/Samplers/DynamicEventTrees.testHybridDETshortRAVEN</name>
    <author>alfoa</author>
    <created>2015-10-05</created>
    <classesTested>Samplers.DynamicEventTree, Models.Code</classesTested>
    <description>
       An example of using the Dynamic Event Tree Methodology (Hybrid Dynamic Event Tree) with an external Code (RELAP7-like in this case).
       This test is a fast executing one that is aimed to check the mechanics of the DET methodology, when epistemic uncertanties
       need to be modeled.
    </description>
    <revisions>
      <revision author="cogljj" date="2016-03-21">Fixing dynamic event tree RELAP-7 inputs.</revision>
      <revision author="maljdan" date="2016-04-06">Updating test cases to reflect the changes to the user input.</revision>
      <revision author="talbpaul" date="2016-04-26">Added check for pre-existing backup files when validating</revision>
      <revision author="alfoa" date="2016-04-27">New subdirectories structure</revision>
      <revision author="maljdan" date="2016-08-03">Removing PrintCSV PostProcessor from the DET test cases.</revision>
      <revision author="alfoa" date="2016-10-20">Modified XSD and removed dim attribute from all the tests</revision>
      <revision author="alfoa" date="2017-01-21">Adding this test description.</revision>
    </revisions>
  </TestInfo>
  <RunInfo>
    <WorkingDir>HybridDynamicEventTree</WorkingDir>
    <Sequence>HybridDETrunTest,testOutstreamStep</Sequence>
    <batchSize>1</batchSize>
  </RunInfo>

  <Files>
    <Input name="pump_fake.i" type="">pump_fake.i</Input>
    <Input name="DET_HistorySet.csv" type="">DET_HistorySet.csv</Input>
  </Files>

  <Models>
    <Code name="MyRAVEN" subType="RELAP7">
      <executable>%FRAMEWORK_DIR%/../tests/framework/Samplers/DynamicEventTrees/simple_det.py</executable>
    </Code>
  </Models>

  <Distributions>
    <Uniform name="zeroToOne">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
    <Uniform name="testHybridMonteCarloDist1">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
    <Uniform name="testHybridGridDist1">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
    <Uniform name="testHybridGridDist2">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
    <Uniform name="testHybridLHSDist1">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
    <Uniform name="testHybridLHSDist2">
      <lowerBound>0.0</lowerBound>
      <upperBound>1.0</upperBound>
    </Uniform>
  </Distributions>

  <Samplers>
    <DynamicEventTree name="HybridDET_test" printEndXmlSummary="true">
      <HybridSampler type="MonteCarlo">
        <samplerInit>
          <limit>2</limit>
        </samplerInit>
        <variable name="Auxiliary|testMCHybrid1|initial_value">
          <distribution>testHybridMonteCarloDist1</distribution>
        </variable>
        <!-- The second sampled variable is directly performed in RAVEN (since we perform the seeding)-->
      </HybridSampler>
      <HybridSampler type="Grid">
        <!-- Point sampler way (directly sampling the variable) -->
        <variable name="Auxiliary|testGridHybrid1|initial_value">
          <distribution>testHybridGridDist1</distribution>
          <grid construction="equal" steps="1" type="CDF">0.1 0.2</grid>
        </variable>
        <!-- RAVEN way for the second distribution-->
        <variable name="testHybridMonteCarloDist2">
          <distribution>testHybridGridDist2</distribution>
          <grid construction="equal" steps="1" type="CDF">0.1 0.2</grid>
        </variable>
      </HybridSampler>
      <HybridSampler type="Stratified">
        <!-- Point sampler way (directly sampling the variable ) -->
        <variable name="Auxiliary|testLHSHybrid1|initial_value">
          <distribution>testHybridLHSDist1</distribution>
          <grid construction="equal" steps="1" type="CDF">0.1 0.2</grid>
        </variable>
        <!-- RAVEN way for the second distribution-->
        <variable name="testHybridMonteCarloDist2">
          <distribution>testHybridLHSDist2</distribution>
          <grid construction="equal" steps="1" type="CDF">0.1 0.2</grid>
        </variable>
      </HybridSampler>
      <!-- DYNAMIC EVENT TREE INPUT (it goes outside an inner block like HybridSampler) -->
      <variable name="zeroToOne">
        <distribution>zeroToOne</distribution>
        <grid construction="custom" type="CDF">0.1 0.8</grid>
      </variable>
    </DynamicEventTree>
  </Samplers>

  <OutStreams>
    <Print name="testprint_hist_hier" dir="print_and_plot_outputs">
      <type>csv</type>
      <source>stories</source>
    </Print>
    <Print name="testprint_tpset_hier" dir="print_and_plot_outputs">
      <type>csv</type>
      <source>Pointset</source>
    </Print>
    <Plot  interactive="false" name="2DHistoryPlot" overwrite="true" dir="print_and_plot_outputs">
      <plotSettings>
        <plot>
          <type>line</type>
          <x>stories|Output|time</x>
          <y>stories|Output|pump_mass_flow_rate</y>
          <kwargs>
            <color>green</color>
          </kwargs>
          <interpPointsX>100</interpPointsX>
          <xlabel>time [s]</xlabel>
          <ylabel>evolution</ylabel>
        </plot>
      </plotSettings>
      <actions>
        <how>pdf</how>
        <title>
          <text> </text>
        </title>
      </actions>
    </Plot>
    <Plot  interactive="false" name="2DHistoryPlot_tps" overwrite="true" dir="print_and_plot_outputs">
      <plotSettings>
        <plot>
          <type>scatter</type>
          <x>Pointset|Output|time</x>
          <y>Pointset|Output|pump_mass_flow_rate</y>
          <kwargs>
            <color>green</color>
          </kwargs>
          <xlabel>time [s]</xlabel>
          <ylabel>evolution</ylabel>
        </plot>
      </plotSettings>
      <actions>
        <how>pdf</how>
        <title>
          <text> </text>
        </title>
      </actions>
    </Plot>
  </OutStreams>

  <Steps>
    <MultiRun name="HybridDETrunTest">
      <Input class="Files" type="">pump_fake.i</Input>
      <Model class="Models" type="Code">MyRAVEN</Model>
      <Sampler class="Samplers" type="DynamicEventTree">HybridDET_test</Sampler>
      <Output class="Databases" type="HDF5">testHybridBranchDatabase</Output>
      <Output class="DataObjects" type="HistorySet">stories</Output>
      <Output class="DataObjects" type="PointSet">Pointset</Output>
    </MultiRun>
    <IOStep name="testOutstreamStep">
      <Input class="DataObjects" type="HistorySet">stories</Input>
      <Input class="DataObjects" type="PointSet">Pointset</Input>
      <Output class="OutStreams" type="Print">testprint_hist_hier</Output>
      <Output class="OutStreams" type="Print">testprint_tpset_hier</Output>
      <Output class="OutStreams" type="Plot">2DHistoryPlot</Output>
      <Output class="OutStreams" type="Plot">2DHistoryPlot_tps</Output>
    </IOStep>
  </Steps>

  <Databases>
    <HDF5 name="testHybridBranchDatabase" readMode="overwrite"/>
  </Databases>

  <DataObjects>
    <PointSet hierarchical="true" name="Pointset">
      <Input>dummy_for_branch</Input>
      <Output>pump_mass_flow_rate,outlet_TDV_T_bc,outlet_TDV_p_bc,inlet_TDV_T_bc,inlet_TDV_p_bc,time</Output>
    </PointSet>
    <HistorySet hierarchical="true" name="stories">
      <Input>dummy_for_branch</Input>
      <Output>pump_mass_flow_rate,outlet_TDV_T_bc,outlet_TDV_p_bc,inlet_TDV_T_bc,inlet_TDV_p_bc,time</Output>
    </HistorySet>
  </DataObjects>

</Simulation>


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Validate items per page option is view all.</description>
  <command name="waitForElementPresent" target="css=#main #primary div.search-result-options:nth-of-type(2) .pagination .results-hits"/>
  <command name="waitForNotElementPresent" target="css=#main #primary div.search-result-options:nth-of-type(2) .pagination .current-page"/>
  <command name="waitForNotElementPresent" target="css=#main #primary div.search-result-options:nth-of-type(4) .pagination .current-page"/>
</scriptmodule>

redpajama_set_name: RedPajamaGithub


text:
export HOME=~
export PATH=$PATH:$LAB_DIR/bin:
export PROJECT_ID=$(gcloud config get-value project)

# gke cluster values
export C1_NAME="central"
export C1_ZONE="us-central1-b"
export C1_NODES=2
export C1_SCOPE="https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append"
export PROJECT_NUMBER=$(gcloud projects describe ${PROJECT_ID} \
    --format="value(projectNumber)")
export WORKLOAD_POOL=${PROJECT_ID}.svc.id.goog
export MESH_ID="proj-${PROJECT_NUMBER}"

gcloud config set compute/zone $C1_ZONE


text:
FROM ubuntu:14.04

RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8

### Base Setup with elixir and erlang
RUN apt-get update
RUN apt-get install -y wget
RUN wget http://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
RUN apt-get update
RUN apt-get install -y gcc
RUN apt-get install -y elixir
RUN apt-get install -y erlang
RUN apt-get install -y git
RUN yes | mix local.hex
RUN yes | mix local.rebar

### Setup Microservice
RUN mkdir /var/web
RUN mkdir /var/web/contact_form_micro_service
WORKDIR /var/web/contact_form_micro_service
RUN git clone https://github.com/ninjapanzer/savvyshots_contact_form_micro_service.git .
RUN MIX_ENV=prod mix do deps.get, compile, release
WORKDIR /

ENV PORT 8888
ENV MIX_ENV prod

EXPOSE 4000
EXPOSE 8888

WORKDIR /var/web/contact_form_micro_service

CMD ["rel/contact_form_micro_service/bin/contact_form_micro_service", "start"]


text:
'use strict';
var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
var $filter = require('../internals/array-iteration').filter;
var fromSpeciesAndList = require('../internals/typed-array-from-species-and-list');

var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;

// `%TypedArray%.prototype.filter` method
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
exportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */) {
  var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  return fromSpeciesAndList(this, list);
});


text:
vim-bazel (Deprecated. Please use [google/vim-ft-bzl](https://github.com/google/vim-ft-bzl) instead)
=========

**Deprecation notice: Please use the official Bazel Vim plugin instead:
[google/vim-ft-bzl](https://github.com/google/vim-ft-bzl).**

Vim syntax highlighting for [Bazel](https://bazel.io) `BUILD` files.

Install
-------

For [Pathogen](https://github.com/tpope/vim-pathogen) users:

```sh
cd .vim/bundle
git clone https://github.com/davidzchen/vim-bazel.git
```

For [Vundle](https://github.com/gmarik/Vundle.vim) users:

```vim
Plugin 'davidzchen/vim-bazel'
```

License
-------

```
   Copyright 2015 Google, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
```


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

$lang['intro']	=	'Start';
$lang['step1']	=	'Schritt #1';
$lang['step2']	=	'Schritt #2';
$lang['step3']	=	'Schritt #3';
$lang['step4']	=	'Schritt #4';
$lang['final']	=	'Letzer Schritt';

$lang['installer.passwords_match']		= "Passwort stimmt überein.";
$lang['installer.passwords_dont_match']	= "Passwort stimmt nicht überein.";


text:
typedef uint8_t byte;

void pinMode(uint8_t, uint8_t);
void digitalWrite(uint8_t, uint8_t);
unsigned long millis();
void delay(unsigned long ms);
void captureSigInt(int n);

void init();
void setup();
void loop();

#endif


text:
/**
 *
 */
Ext.define('Ext.layout.Fit', {
    extend: 'Ext.layout.Default',

    isFit: true,

    alias: 'layout.fit',

    cls: Ext.baseCSSPrefix + 'layout-fit',

    itemCls: Ext.baseCSSPrefix + 'layout-fit-item',

    setContainer: function(container) {
        this.callParent(arguments);

        this.onContainerSizeFlagsChange();
        this.monitorSizeFlagsChange();
    },

    onContainerSizeFlagsChange: function() {
        var container = this.container,
            sizeFlags = container.getSizeFlags(),
            stretched = Boolean(sizeFlags & container.LAYOUT_STRETCHED),
            innerItems = container.innerItems,
            i, ln, item;

        this.callParent();

        for (i = 0,ln = innerItems.length; i < ln; i++) {
            item = innerItems[i];
            item.setLayoutSizeFlags(sizeFlags);
        }

        container.innerElement.toggleCls('x-stretched', stretched);
    },

    onItemInnerStateChange: function(item, isInner) {
        this.callParent(arguments);
        item.setLayoutSizeFlags(isInner ? this.container.getSizeFlags() : 0);
    }
});


text:
namespace System.Net.NetworkInformation
{
    internal class SystemIPInterfaceStatistics : IPInterfaceStatistics
    {
        private readonly Interop.IpHlpApi.MibIfRow2 _ifRow;

        internal SystemIPInterfaceStatistics(long index)
        {
            _ifRow = GetIfEntry2(index);
        }

        public override long OutputQueueLength { get { return (long)_ifRow.outQLen; } }

        public override long BytesSent { get { return (long)_ifRow.outOctets; } }

        public override long BytesReceived { get { return (long)_ifRow.inOctets; } }

        public override long UnicastPacketsSent { get { return (long)_ifRow.outUcastPkts; } }

        public override long UnicastPacketsReceived { get { return (long)_ifRow.inUcastPkts; } }

        public override long NonUnicastPacketsSent { get { return (long)_ifRow.outNUcastPkts; } }

        public override long NonUnicastPacketsReceived { get { return (long)_ifRow.inNUcastPkts; } }

        public override long IncomingPacketsDiscarded { get { return (long)_ifRow.inDiscards; } }

        public override long OutgoingPacketsDiscarded { get { return (long)_ifRow.outDiscards; } }

        public override long IncomingPacketsWithErrors { get { return (long)_ifRow.inErrors; } }

        public override long OutgoingPacketsWithErrors { get { return (long)_ifRow.outErrors; } }

        public override long IncomingUnknownProtocolPackets { get { return (long)_ifRow.inUnknownProtos; } }

        internal static Interop.IpHlpApi.MibIfRow2 GetIfEntry2(long index)
        {
            Interop.IpHlpApi.MibIfRow2 ifRow = new Interop.IpHlpApi.MibIfRow2();
            if (index == 0)
            {
                return ifRow;
            }

            ifRow.interfaceIndex = (uint)index;
            uint result = Interop.IpHlpApi.GetIfEntry2(ref ifRow);
            if (result != Interop.IpHlpApi.ERROR_SUCCESS)
            {
                throw new NetworkInformationException((int)result);
            }

            return ifRow;
        }
    }
}


text:
#ifndef XFILENORMAL_H
#define XFILENORMAL_H

#include "pandatoolbase.h"
#include "luse.h"

class EggVertex;
class EggPrimitive;

/**
 * This represents a single normal associated with an XFileFace.  It is
 * separate from XFileVertex, because the X syntax supports a different table
 * of normals than that of vertices.
 */
class XFileNormal {
public:
  XFileNormal();
  void set_from_egg(EggVertex *egg_vertex, EggPrimitive *egg_prim);
  int compare_to(const XFileNormal &other) const;

  LNormald _normal;
  bool _has_normal;
};

#endif


text:
echo ">> Test date"
date +"%c"
echo ">> Testing version"
../lorem -v

# NEW FILE TESTS
echo ">> NEW FILE TESTS"
# test that default = 1 paragraph lorem
../lorem -o results/test1.txt
echo ">> Default = 1 paragraph created in test1.txt"
echo ">> This should result in 1"
rx subcount -i results/test1.txt Lorem
# 1 paragraph lorem
../lorem -n 1 -o results/test2.txt
echo ">> 1 paragraph created in test2.txt"
echo ">> This should result in 1"
rx subcount -i results/test2.txt Lorem
# 5 paragraphs lorem
../lorem -n 5 -o results/test3.txt
echo ">> 5 paragraphs created in test3.txt"
echo ">> This should result in 5"
rx subcount -i results/test3.txt Lorem
# 1000 paragraphs lorem
../lorem -n 1000 -o results/test4.txt
echo ">> 1000 paragraphs created in test4.txt"
echo ">> This should result in 1000"
rx subcount -i results/test4.txt Lorem

# 1 paragraph user supplied text with default n = 1
../lorem -t text_files/replace.txt -o results/test5.txt
echo ">> 1 paragraph of user text created in test5.txt"
echo ">> This should result in 1"
rx subcount -i results/test5.txt "Normally,"
# 1 paragraph user supplied text with -n specified write
../lorem -n 1 -t text_files/replace.txt -o results/test6.txt
echo ">> 1 paragraph of user text created in test6.txt"
echo ">> This should result in 1"
rx subcount -i results/test6.txt "Normally,"
# 5 paragraphs of user supplied text
../lorem -n 5 -t text_files/replace.txt -o results/test7.txt
echo ">> 5 paragraphs of user text created in test7.txt"
echo ">> This should result in 5"
rx subcount -i results/test7.txt "Normally,"
# 1000 paragraphs of user supplied text
../lorem -n 1000 -t text_files/replace.txt -o results/test8.txt
echo ">> 1000 paragraphs of user text created in test8.txt"
echo ">> This should result in 1000"
rx subcount -i results/test8.txt "Normally,"

echo ">> NEW FILE TESTS COMPLETE"
echo " "

#APPEND & TAG TESTS
echo ">> FILE APPEND & TAG TESTS"

../lorem -a -b "
" -e "
" -t text_files/replace.txt -o results/test1.txt
echo ">> appended 1 paragraph with tags and user entered text to test1.txt using default n = 1"
echo ">> This should result in 1"
rx subcount -i results/test1.txt "Normally,"

../lorem -a -n 1 -b "
" -e "
" -t text_files/replace.txt -o results/test1.txt
echo ">> appended 1 paragraph with tags and user entered text to test1.txt using explicit n = 1"
echo ">> This should result in 2"
rx subcount -i results/test1.txt "Normally,"

../lorem -a -n 5 -b "
" -e "
" -t text_files/replace.txt -o results/test2.txt
echo ">> appended 5 paragraphs with tags and user entered text to test2.txt"
echo ">> This should result in 5"
rx subcount -i results/test2.txt "Normally,"

../lorem -a -n 1000 -b "
" -e "
" -t text_files/replace.txt -o results/test3.txt
echo ">> appended 1000 paragraphs with tags and user entered text to test3.txt"
echo ">> This should result in 1000"
rx subcount -i results/test3.txt "Normally,"

echo ">> TESTS COMPLETE"
echo " "

# SETUP FILE REPLACEMENT TESTS
#html with <lorem> in middle, test for pre and post strings with appropriate insertion
cp text_files/eg1.txt results/r1.txt
cp text_files/eg1.txt results/r2.txt
cp text_files/eg1.txt results/r3.txt
cp text_files/eg1.txt results/r4.txt
cp text_files/eg1.txt results/r5.txt
cp text_files/eg1.txt results/r6.txt
cp text_files/eg1.txt results/r7.txt
cp text_files/eg1.txt results/r8.txt
cp text_files/eg1.txt results/r9.txt
cp text_files/eg1.txt results/r10.txt

# PERFORM FILE REPLACEMENT TESTS
echo ">> FILE REPLACEMENT TESTS"

## TEST INSERTION IN MIDDLE OF DOCUMENT
#default n = 1 paragraph of lorem replacement text
../lorem -r -i results/r1.txt
echo ">> default n=1 paragraph lorem insert in r1.txt"
#explicit n = 1 paragraph of lorem replacement text
../lorem -r -n 1 -i results/r2.txt
echo ">> explicit n=1 paragraph lorem insert in r2.txt"
#n = 5 paragraph of lorem insert
../lorem -r -n 5 -i results/r3.txt
echo ">> n=5 paragraph lorem insert in r3.txt"
#n = 1000 paragraph of lorem insert
../lorem -r -n 1000 -i results/r4.txt
#default n = 1 user submitted text replacement
echo ">> default n = 1 of user submitted text replacement in results/r5.txt"
../lorem -r -t text_files/replace.txt -i results/r5.txt
#explicit n = 1 user submitted text replacement
echo ">> explicit n = 1 of user submitted text replacement in results/r6.txt"
../lorem -r -n 1 -t text_files/replace.txt -i results/r6.txt
#n = 5 paragraphs of user submitted text replacement
echo ">> n=5 paragraphs of user submitted text replacement in results/r7.txt"
../lorem -r -n 5 -t text_files/replace.txt -i results/r7.txt
#n = 1000 paragraphs of user submitted text replacement
echo ">> n = 1000 paragraphs of user submitted text replacement in results/r8.txt"
../lorem -r -n 1000 -t text_files/replace.txt -i results/r8.txt
# n = 5 with tags around lorem text
echo ">> n = 5 paragraphs of lorem text with p tags around the paragraphs in results/r9.txt"
../lorem -r -n 5 -b "
" -e "
" -i results/r9.txt
# n = 5 with tags around user submitted text
echo ">> n = 5 paragraphs of user submitted text with p tags around the paragraphs in results/r10.txt"
../lorem -r -t text_files/replace.txt -n 5 -b "
" -e "
" -i results/r10.txt

echo ">> TESTS COMPLETE"
echo " "


text:
import map from 'lodash/collection/map'

import { OFFSETS } from '../lib/constants'
const { TINY, REGULAR, COMPRESSED } = OFFSETS

function offset(tiny, compress, card, index) {
  const BASE_AMOUNT = tiny ? TINY : REGULAR
  let amount

  amount = index <= compress ?
    index * COMPRESSED :
    (COMPRESSED * compress) + ((index - compress) * BASE_AMOUNT)

  return amount
}

export default function offsets(cards, compressCount = 10, tiny = false) {
  compressCount = compressCount || Infinity
  const total = cards.length
  const compressedCount = Math.max(0, total - compressCount)
  const offsetFn = offset.bind(this, tiny, compressedCount)
  return map(cards, offsetFn)
}


text:
<?php

namespace ZendDirectoryInfo\DataAccess;

class File extends Location
{
    function __construct($location)
    {
        parent::__construct(realpath($location));
        if(empty($location))
        {
            throw new \InvalidArgumentException("No path was given");
        }
        if(!$this->isValid())
        {
            throw new \InvalidArgumentException("Not a Valid path or doesn't exist");
        }
        $this->setInformation();
    }

    public function isValid()
    {
        return realpath($this->getLocation());
    }

    public function exists()
    {
        return file_exists($this->getLocation());
    }

    public function setInformation()
    {
        //echo $this->getLocation();
        $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
        $this->information["Content-Type"] =  finfo_file($finfo, $this->getLocation());
        finfo_close($finfo);
    }
}


text:
package com.gmail.trentech.EKcore.core.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SQLPlayers extends SQLUtils {

	protected static boolean kitExist(String playerUUID, String kitName) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + prefix(playerUUID) + "`");
			ResultSet result = statement.executeQuery();
			while (result.next()) {
				if (result.getString("Kit").equalsIgnoreCase(kitName)) {
					connection.close();
					return true;
				}
			}
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	protected static void addKit(String playerUUID, String kitName, String cooldown, int limit, String obtainedBefore) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("INSERT into `" + prefix(playerUUID) + "` (Kit, Cooldown, Limits, Obtained) VALUES (?, ?, ?, ?)");
			statement.setString(1, kitName);
			statement.setString(2, cooldown);
			statement.setInt(3, limit);
			statement.setString(4, obtainedBefore);
			statement.executeUpdate();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected static void setDateObtained(String playerUUID, String kitName, String cooldown) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("UPDATE `" + prefix(playerUUID) + "` SET Cooldown = ? WHERE Kit = ?");
			statement.setString(1, cooldown);
			statement.setString(2, kitName);
			statement.executeUpdate();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected static void setObtained(String playerUUID, String kitName, String obtainedBefore) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("UPDATE `" + prefix(playerUUID) + "` SET Obtained = ? WHERE Kit = ?");
			statement.setString(1, obtainedBefore);
			statement.setString(2, kitName);
			statement.executeUpdate();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected static void setLimit(String playerUUID, String kitName, int limit) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("UPDATE `" + prefix(playerUUID) + "` SET Limits = ? WHERE Kit = ?");
			statement.setInt(1, limit);
			statement.setString(2, kitName);
			statement.executeUpdate();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected static String getDateObtained(String playerUUID, String kitName) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + prefix(playerUUID) + "`");
			ResultSet result = statement.executeQuery();
			while (result.next()) {
				if (result.getString("Kit").equalsIgnoreCase(kitName)) {
					String cooldown = result.getString("Cooldown");
					connection.close();
					return cooldown;
				}
			}
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "0";
	}

	protected static int getLimit(String playerUUID, String kitName) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + prefix(playerUUID) + "`");
			ResultSet result = statement.executeQuery();
			while (result.next()) {
				if (result.getString("Kit").equalsIgnoreCase(kitName)) {
					int limits = result.getInt("Limits");
					connection.close();
					return limits;
				}
			}
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	protected static String getObtained(String playerUUID, String kitName) {
		try {
		    Connection connection = getDataSource().getConnection();
		    PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + prefix(playerUUID) + "`");
			ResultSet result = statement.executeQuery();
			while (result.next()) {
				if (result.getString("Kit").equalsIgnoreCase(kitName)) {
					String obtained = result.getString("Obtained");
					connection.close();
					return obtained;
				}
			}
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "FALSE";
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_events_list_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:animateLayoutChanges="true">

    <RelativeLayout
        android:id="@+id/editor_events_activated_profile_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="-6dp"
        android:layout_marginBottom="5dp"
        android:paddingStart="12dp"
        android:paddingEnd="12dp"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:layout_alignParentTop="true" >

        <RelativeLayout
            android:id="@+id/editor_events_activated_profile_header_subgroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/editor_events_activated_profile_icon"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_marginStart="1dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:adjustViewBounds="true"
                android:contentDescription="@string/profile_preferences_profileIcon"
                android:scaleType="fitCenter"
                android:src="@drawable/ic_empty" />

            <LinearLayout
                android:id="@+id/editor_events_activated_profile_icon_liLa1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="-1dp"
                android:orientation="vertical"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@id/editor_events_activated_profile_icon" >

                <TextView
                    android:id="@+id/editor_events_activated_profile_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingStart="12dp"
                    android:paddingEnd="12dp"
                    android:text="@string/empty_string"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:textColor="?attr/colorAccent" />

                <ImageView
                    android:id="@+id/editor_events_activated_profile_pref_indicator"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/profile_preferences_indicator_height"
                    android:layout_marginTop="2dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/profile_preferences_indicator_image"
                    android:scaleType="@integer/profilePrefIndicatorScaleType"
                    android:src="@drawable/ic_empty"
                    android:paddingStart="10dp"
                    android:paddingEnd="10dp" />

            </LinearLayout>

        </RelativeLayout>

        <TextView
            android:id="@+id/editor_events_activated_profile_red_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="2dp"
            android:layout_marginTop="5dp"
            android:layout_below="@id/editor_events_activated_profile_header_subgroup"
            android:text="@string/event_preferences_red_texts_in_header"
            android:textColor="@color/error_in_preferences"
            android:visibility="gone"/>

    </RelativeLayout>

    <FrameLayout
        android:id="@+id/editor_events_list_frLa1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/editor_events_activated_profile_header"
        android:layout_above="@id/editor_events_list_bottom_bar" >

        <View
            android:id="@+id/editor_events_list_divider1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/divider_height"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_gravity="top"
            android:background="?attr/dialogDivider" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/editor_events_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="3dp"
            android:paddingBottom="5dp"
            android:clipToPadding="false"
            android:scrollbars="vertical"
            android:scrollbarStyle="outsideOverlay" />

        <TextView
            android:id="@+id/editor_events_list_empty"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/event_list_empty"
            android:gravity="center"
            android:textSize="20sp"
            android:visibility="gone" />

        <LinearLayout
            android:id="@+id/editor_events_list_linla_progress"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:visibility="gone" >

            <ProgressBar
                android:id="@+id/editor_events_list_progress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

        <View
            android:id="@+id/editor_events_list_divider2"
            android:layout_width="match_parent"
            android:layout_height="@dimen/divider_height"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:background="?attr/dialogDivider"
            android:layout_gravity="bottom" />

    </FrameLayout>

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/editor_events_list_bottom_bar"
        android:layout_height="55dp"
        android:layout_width="match_parent"
        android:layout_alignParentBottom="true"
        android:background="?attr/colorPrimary"
        android:theme="?attr/bottomToolbarTheme"
        app:popupTheme="?attr/toolbarPopupMenu" >

        <LinearLayout
            android:id="@+id/editor_events_list_bottom_bar_order_root"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_gravity="center_vertical">
<!--            android:layout_marginStart="-3dp"-->
<!--            android:layout_marginEnd="5dp"-->

            <TextView
                android:id="@+id/editor_events_list_bottom_bar_order_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="-5dp"
                android:layout_marginStart="1dp"
                android:ellipsize="end"
                android:textSize="16dp"
                android:clickable="true"
                android:text="@string/editor_drawer_title_events_order"
                android:maxLines="1"
                android:focusable="true"
                tools:ignore="SpUsage"/>
<!--            android:textColor="?attr/editorFilterTitleColor"-->

            <androidx.appcompat.widget.AppCompatSpinner
                android:id="@+id/editor_events_list_bottom_bar_order"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="0dp"
                android:layout_marginStart="1dp"
                android:entries="@array/emptyArray"
                android:clickable="true"
                android:focusable="true"
                android:popupElevation="0dp"
                style="@style/Base.Widget.AppCompat.Spinner" />

        </LinearLayout>

    </androidx.appcompat.widget.Toolbar>

</RelativeLayout>


text:
using System;
using System.Runtime.Serialization;

namespace DotNetRevolution.EventSourcing.Projecting2
{
    [Serializable]
    public class ProjectionNotFoundException : Exception
    {
        public ProjectionNotFoundException()
        {
        }

        public ProjectionNotFoundException(string message) : base(message)
        {
        }

        public ProjectionNotFoundException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected ProjectionNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
package pt.tecnico.dsi.kadmin

import com.typesafe.scalalogging.LazyLogging
import org.scalatest._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.exceptions.TestFailedException
import work.martins.simon.expect.core.Expect

import scala.concurrent.Future

/**
  * @define assumptions These tests make the following assumptions:
  *  - The realm EXAMPLE.COM exists.
  *  - Kerberos client is installed in the machine where the tests are being ran.
  *     And the configuration has the realm EXAMPLE.COM.
  *  - In EXAMPLE.COM KDC the kadm5.acl file has at least the following entries
  *     - kadmin/admin@EXAMPLE.COM  *
  *     - noPermissions@EXAMPLE.COM X
  *  - The password for these two principals is "MITiys4K5".
  *
  * These assumptions are valid when:
  *  - Running the tests locally with docker-compose (look at the folder kerberos-docker).
  *  - Running the tests in the Travis CI (look at .travis.yml, which makes use of the kerberos-docker).
  */
trait TestUtils extends ScalaFutures with Matchers with EitherValues with LazyLogging { self: AsyncTestSuite =>
  private val configSettings = Settings.fromConfig()
  // These are a cheat to test some of the constructors of Kadmin
  val fullPermissionsKadmin: Kadmin = new Kadmin(configSettings.copy(principal = "kadmin/admin"))
  val noPermissionsKadmin: Kadmin = new Kadmin(configSettings.realm, "noPermissions", configSettings.password)

  implicit class RichExpect[T](expect: Expect[Either[ErrorCase, T]]) {
    def test(test: Either[ErrorCase, T] => Assertion): Future[Assertion] = expect.run().map(test)

    def rightValue(testOnRight: T => Assertion): Future[Assertion] = test(t => testOnRight(t.right.value))
    def leftValue(testOnLeft: ErrorCase => Assertion): Future[Assertion] = test(t => testOnLeft(t.left.value))

    def rightValueShouldBe(t: T): Future[Assertion] = rightValue(_ shouldBe t)
    def rightValueShouldBeUnit()(implicit ev: T =:= Unit): Future[Assertion] = rightValue(ev(_).shouldBe(()))
    def leftValueShouldBe(error: ErrorCase): Future[Assertion] = leftValue(_ shouldBe error)

    def idempotentTest(test: Either[ErrorCase, T] => Assertion, repetitions: Int = 3): Future[Assertion] = {
      require(repetitions >= 2, "To test for idempotency at least 2 repetitions must be made")

      expect.run().flatMap { firstResult ⇒
        // If this fails we do not want to catch its exception, because failing in the first attempt means
        // whatever is being tested in `test` is not implemented correctly. Therefore we do not want to mask
        // the failure with a "Operation is not idempotent".
        test(firstResult)

        Future.traverse(2 to repetitions) { _ =>
          expect.run()
        } map { results ⇒
          // And now we want to catch the exception because if `test` fails here it means it is not idempotent.
          try {
            results.foreach(test)
            succeed
          } catch {
            case e: TestFailedException =>
              val numberOfDigits = Math.floor(Math.log10(repetitions.toDouble)).toInt + 1
              val resultsString = (firstResult +: results).zipWithIndex
                .map { case (result, i) =>
                  s" %${numberOfDigits}d: %s".format(i + 1, result)
                }.mkString("\n")
              throw new TestFailedException(s"""Operation is not idempotent. Results:
                                                |$resultsString
                                                |${e.message}""".stripMargin, e, e.failedCodeStackDepth + 1)
          }
        }
      }
    }

    def idempotentRightValue(testOnRight: T => Assertion): Future[Assertion] = idempotentTest(t => testOnRight(t.right.value))
    def idempotentLeftValue(testOnLeft: ErrorCase => Assertion): Future[Assertion] = idempotentTest(t => testOnLeft(t.left.value))

    def rightValueShouldIdempotentlyBe(rightValue: T): Future[Assertion] = idempotentRightValue(_ shouldBe rightValue)
    def rightValueShouldIdempotentlyBeUnit()(implicit ev: T =:= Unit): Future[Assertion] = idempotentRightValue(ev(_).shouldBe(()))
    def leftValueShouldIdempotentlyBe(leftValue: ErrorCase): Future[Assertion] = idempotentLeftValue(_ shouldBe leftValue)
  }

  def testNoSuchPrincipal[R](e: Expect[Either[ErrorCase, R]]): Future[Assertion] = e leftValueShouldIdempotentlyBe NoSuchPrincipal
  def testNoSuchPolicy[R](e: Expect[Either[ErrorCase, R]]): Future[Assertion] = e leftValueShouldIdempotentlyBe NoSuchPolicy
  def testInsufficientPermission[T](permission: String)(e: Expect[Either[ErrorCase, T]]): Future[Assertion] = {
    e leftValueShouldIdempotentlyBe InsufficientPermissions(permission)
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cdn.models;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/** Type of response errors for real user requests for which origin will be deemed unhealthy. */
public enum ResponseBasedDetectedErrorTypes {
    /** Enum value None. */
    NONE("None"),

    /** Enum value TcpErrorsOnly. */
    TCP_ERRORS_ONLY("TcpErrorsOnly"),

    /** Enum value TcpAndHttpErrors. */
    TCP_AND_HTTP_ERRORS("TcpAndHttpErrors");

    /** The actual serialized value for a ResponseBasedDetectedErrorTypes instance. */
    private final String value;

    ResponseBasedDetectedErrorTypes(String value) {
        this.value = value;
    }

    /**
     * Parses a serialized value to a ResponseBasedDetectedErrorTypes instance.
     *
     * @param value the serialized value to parse.
     * @return the parsed ResponseBasedDetectedErrorTypes object, or null if unable to parse.
     */
    @JsonCreator
    public static ResponseBasedDetectedErrorTypes fromString(String value) {
        if (value == null) {
            return null;
        }
        ResponseBasedDetectedErrorTypes[] items = ResponseBasedDetectedErrorTypes.values();
        for (ResponseBasedDetectedErrorTypes item : items) {
            if (item.toString().equalsIgnoreCase(value)) {
                return item;
            }
        }
        return null;
    }

    /** {@inheritDoc} */
    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }
}


text:
using GameLibrary.Dependencies.Physics.Dynamics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace GameLibrary.Helpers
{
    /// <summary>
    /// Class from Farseer demo, ;#. It works doe.
    /// </summary>
    public class Camera
    {
        /// <summary>
        /// The constructor for the Camera class.
        /// </summary>
        /// <param name="graphics"></param>
        public Camera(GraphicsDevice graphics)
        {
            _graphics = graphics;
            _projection = Matrix.CreateOrthographicOffCenter(0f, ConvertUnits.ToSimUnits(_graphics.Viewport.Width),
                                                             ConvertUnits.ToSimUnits(_graphics.Viewport.Height), 0f, 0f,
                                                             1f);
            _view = Matrix.Identity;
            _batchView = Matrix.Identity;

            _translateCenter = new Vector2(ConvertUnits.ToSimUnits(_graphics.Viewport.Width / 2f),
                                           ConvertUnits.ToSimUnits(_graphics.Viewport.Height / 2f));

            ResetCamera();
        }

        #region Functioning Loop

        /// <summary>
        /// Moves the camera forward one timestep.
        /// </summary>
        public void Update(GameTime gameTime)
        {
            if (_trackingBody != null)
            {
                if (_positionTracking)
                {
                    _targetPosition = _trackingBody.Position;
                    if (_minPosition != _maxPosition)
                    {
                        Vector2.Clamp(ref _targetPosition, ref _minPosition, ref _maxPosition, out _targetPosition);
                    }
                }
                if (_rotationTracking)
                {
                    _targetRotation = -_trackingBody.Rotation % MathHelper.TwoPi;
                    if (_minRotation != _maxRotation)
                    {
                        _targetRotation = MathHelper.Clamp(_targetRotation, _minRotation, _maxRotation);
                    }
                }
            }
            Vector2 delta = _targetPosition - _currentPosition;
            float distance = delta.Length();
            if (distance > 0f)
            {
                delta /= distance;
            }
            float inertia;
            if (distance < 10f)
            {
                inertia = (float)Math.Pow(distance / 10.0, 2.0);
            }
            else
            {
                inertia = 1f;
            }

            float rotDelta = _targetRotation - _currentRotation;

            float rotInertia;
            if (Math.Abs(rotDelta) < 5f)
            {
                rotInertia = (float)Math.Pow(rotDelta / 5.0, 2.0);
            }
            else
            {
                rotInertia = 1f;
            }
            if (Math.Abs(rotDelta) > 0f)
            {
                rotDelta /= Math.Abs(rotDelta);
            }

            _currentPosition += 100f * delta * inertia * (float)gameTime.ElapsedGameTime.TotalSeconds;
            _currentRotation += 80f * rotDelta * rotInertia * (float)gameTime.ElapsedGameTime.TotalSeconds;

            SetView();
        }

        #endregion Functioning Loop

        #region Methods

        public void MoveCamera(Vector2 amount)
        {
            _currentPosition += amount;
            if (_minPosition != _maxPosition)
            {
                Vector2.Clamp(ref _currentPosition, ref _minPosition, ref _maxPosition, out _currentPosition);
            }
            _targetPosition = _currentPosition;
            _positionTracking = false;
            _rotationTracking = false;
        }

        public void RotateCamera(float amount)
        {
            _currentRotation += amount;
            if (_minRotation != _maxRotation)
            {
                _currentRotation = MathHelper.Clamp(_currentRotation, _minRotation, _maxRotation);
            }
            _targetRotation = _currentRotation;
            _positionTracking = false;
            _rotationTracking = false;
        }

        /// <summary>
        /// Resets the camera to default values.
        /// </summary>
        public void ResetCamera()
        {
            _currentPosition = Vector2.Zero;
            _targetPosition = Vector2.Zero;
            _minPosition = Vector2.Zero;
            _maxPosition = Vector2.Zero;

            _currentRotation = 0f;
            _targetRotation = 0f;
            _minRotation = -MathHelper.Pi;
            _maxRotation = MathHelper.Pi;

            _positionTracking = false;
            _rotationTracking = false;

            _currentZoom = 1f;

            SetView();
        }

        public void Jump2Target()
        {
            _currentPosition = _targetPosition;
            _currentRotation = _targetRotation;

            SetView();
        }

        private void SetView()
        {
            Matrix matRotation = Matrix.CreateRotationZ(_currentRotation);
            Matrix matZoom = Matrix.CreateScale(_currentZoom);
            Vector3 translateCenter = new Vector3(_translateCenter, 0f);
            Vector3 translateBody = new Vector3(-_currentPosition, 0f);

            _view = Matrix.CreateTranslation(translateBody) *
                    matRotation *
                    matZoom *
                    Matrix.CreateTranslation(translateCenter);

            translateCenter = ConvertUnits.ToDisplayUnits(translateCenter);
            translateBody = ConvertUnits.ToDisplayUnits(translateBody);

            _batchView = Matrix.CreateTranslation(translateBody) *
                         matRotation *
                         matZoom *
                         Matrix.CreateTranslation(translateCenter);
        }

        #endregion Methods

        #region Fields

        private const float _minZoom = 0.02f;
        private const float _maxZoom = 20f;
        private static GraphicsDevice _graphics;

        private Matrix _batchView;

        private Vector2 _currentPosition;

        private float _currentRotation;

        private float _currentZoom;
        private Vector2 _maxPosition;
        private float _maxRotation;
        private Vector2 _minPosition;
        private float _minRotation;
        private bool _positionTracking;
        private Matrix _projection;
        private bool _rotationTracking;
        private Vector2 _targetPosition;
        private float _targetRotation;
        private PhysicsBody _trackingBody;
        private Vector2 _translateCenter;
        private Matrix _view;

        #endregion Fields

        #region Properties

        //Matrix.CreateOrthographicOffCenter(0f, GraphicsDevice.Viewport.Width / ConvertUnits.ToDisplayUnits(1f),
        //                                          GraphicsDevice.Viewport.Height / ConvertUnits.ToDisplayUnits(1f), 0f, 0f,
        //                                          1f);
        public Matrix View
        {
            get { return _batchView; }
        }

        public Matrix SimView
        {
            get { return _view; }
        }

        public Matrix SimProjection
        {
            get { return _projection; }
        }

        /// <summary>
        /// The current position of the camera.
        /// </summary>
        public Vector2 Position
        {
            get { return ConvertUnits.ToDisplayUnits(_currentPosition); }
            set
            {
                _targetPosition = ConvertUnits.ToSimUnits(value);
                if (_minPosition != _maxPosition)
                {
                    Vector2.Clamp(ref _targetPosition, ref _minPosition, ref _maxPosition, out _targetPosition);
                }
            }
        }

        /// <summary>
        /// The furthest up, and the furthest left the camera can go.
        /// if this value equals maxPosition, then no clamping will be
        /// applied (unless you override that function).
        /// </summary>
        public Vector2 MinPosition
        {
            get { return ConvertUnits.ToDisplayUnits(_minPosition); }
            set { _minPosition = ConvertUnits.ToSimUnits(value); }
        }

        /// <summary>
        /// the furthest down, and the furthest right the camera will go.
        /// if this value equals minPosition, then no clamping will be
        /// applied (unless you override that function).
        /// </summary>
        public Vector2 MaxPosition
        {
            get { return ConvertUnits.ToDisplayUnits(_maxPosition); }
            set { _maxPosition = ConvertUnits.ToSimUnits(value); }
        }

        /// <summary>
        /// The current rotation of the camera in radians.
        /// </summary>
        public float Rotation
        {
            get { return _currentRotation; }
            set
            {
                _targetRotation = value % MathHelper.TwoPi;
                if (_minRotation != _maxRotation)
                {
                    _targetRotation = MathHelper.Clamp(_targetRotation, _minRotation, _maxRotation);
                }
            }
        }

        /// <summary>
        /// Gets or sets the minimum rotation in radians.
        /// </summary>
        /// <value>The min rotation.</value>
        public float MinRotation
        {
            get { return _minRotation; }
            set { _minRotation = MathHelper.Clamp(value, -MathHelper.Pi, 0f); }
        }

        /// <summary>
        /// Gets or sets the maximum rotation in radians.
        /// </summary>
        /// <value>The max rotation.</value>
        public float MaxRotation
        {
            get { return _maxRotation; }
            set { _maxRotation = MathHelper.Clamp(value, 0f, MathHelper.Pi); }
        }

        /// <summary>
        /// The current rotation of the camera in radians.
        /// </summary>
        public float Zoom
        {
            get { return _currentZoom; }
            set
            {
                _currentZoom = value;
                _currentZoom = MathHelper.Clamp(_currentZoom, _minZoom, _maxZoom);
            }
        }

        /// <summary>
        /// the body that this camera is currently tracking.
        /// Null if not tracking any.
        /// </summary>
        public PhysicsBody TrackingBody
        {
            get { return _trackingBody; }
            set
            {
                _trackingBody = value;
                if (_trackingBody != null)
                {
                    _positionTracking = true;
                }
            }
        }

        public bool EnablePositionTracking
        {
            get { return _positionTracking; }
            set
            {
                if (value && _trackingBody != null)
                {
                    _positionTracking = true;
                }
                else
                {
                    _positionTracking = false;
                }
            }
        }

        public bool EnableRotationTracking
        {
            get { return _rotationTracking; }
            set
            {
                if (value && _trackingBody != null)
                {
                    _rotationTracking = true;
                }
                else
                {
                    _rotationTracking = false;
                }
            }
        }

        public bool EnableTracking
        {
            set
            {
                EnablePositionTracking = value;
                EnableRotationTracking = value;
            }
        }

        #endregion Properties

        #region Helpers

        public Vector2 ConvertScreenToWorld(Vector2 location)
        {
            Vector3 t = new Vector3(location, 0);

            t = _graphics.Viewport.Unproject(t, _projection, _view, Matrix.Identity);

            return new Vector2(t.X, t.Y);
        }

        public Vector2 ConvertWorldToScreen(Vector2 location)
        {
            Vector3 t = new Vector3(location, 0);

            t = _graphics.Viewport.Project(t, _projection, _view, Matrix.Identity);

            return new Vector2(t.X, t.Y);
        }

        public override string ToString()
        {
            return _currentPosition.ToString();
        }

        #endregion Helpers
    }
}


text:
using System;
using System.Threading.Tasks;

namespace Twitchie2
{
	public class TwitchIrcChannel
	{
		public string Name { get; }

		public bool Joined { get; private set; }

		public TwitchIrcChannel(string channel)
		{
			if (string.IsNullOrWhiteSpace(channel))
				throw new ArgumentException("Invalid channel! Channel can not be null or whitespace.");

			Name = channel[0] == '#' ? channel : '#' + channel;
		}

		public async Task SendMessageAsync(string message)
			=> await Twitchie.Instance.ChatAsync(Name, message);

		public async Task SendActionAsync(string action)
			=> await Twitchie.Instance.ActionAsync(Name, action);

		public async Task SendMentionAsync(string user, string message)
			=> await Twitchie.Instance.MentionAsync(Name, user, message);

		public async Task SendWhisperAsync(string user, string message)
			=> await Twitchie.Instance.WhisperAsync(Name, user, message);

		public async Task JoinAsync()
		{
			if (!Joined)
			{
				await Twitchie.Instance.SendAsync($"JOIN {Name}");
				Joined = true;
			}
		}

		public async Task PartAsync()
		{
			if (Joined)
			{
				await Twitchie.Instance.SendAsync($"PART {Name}");
				Joined = false;
			}
		}
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Daniel Hurley - Network Systems Biology</title>
  <meta name="description" content="Daniel Hurley - Network Systems Biology">

  <link rel="stylesheet" href="/css/tufte.css">

  <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

  <link rel="canonical" href="/content/publications.html">
  <link rel="alternate" type="application/rss+xml" title="Daniel Hurley - Network Systems Biology" href="/feed.xml" />

		About
		Research
		Teaching
		Publications

Publications List

My Google Scholar profile

Refereed journal articles

2016

Lasham, A., Mehta, S., Fitzgerald, S., Woolley, A., Hearn, J., Hurley, D.G., Ruza, I., Algie, M., Sullivan, R., Shelling, A., Braithwaite, A., Print, C.G. A novel EGR-1 dependent mechanism for YB-1 modulation of paclitaxel response in a triple negative breast cancer cell line.  Int J Cancer (accepted)

Jaudal, M., Zhang, L., Che, C., Hurley, D.G., Thomson, G., Wen, J., Mysore, K., Putterill, J. MtVRN2 is a Polycomb VRN2-like gene which represses the transition to flowering in the model legume Medicago truncatula.  The Plant Journal (accepted).

Cursons J., Angel C.E., Hurley D.G., Dunbar P.R., Jacobs M.D., Crampin E.J. (2015) Spatially transformed fluorescence image data for ERK-MAPK and selected proteins within human epidermis. GigaScience 4 (1), 1-6

James, J., Hurley D.G., Gamage, T., Zhang, T., Vather, R., Prantham, P., Murti, P., Chamley, L., Isolation and Characterisation of a Novel Trophoblast Side-Population from First Trimester Placentae.  Reproduction (accepted).

2015

Cursons J., Gao J., (Joint first authorship). Hurley D.G., Dunbar P.R., Jacobs M.D., Crampin E.J. Regulation of ERK-MAPK signaling in human epidermis. BMC Syst Biol. 2015;9(1):41.

Budden, D. M., Hurley, D. G., & Crampin, E. J. (2015). Modelling the conditional regulatory activity of methylated and bivalent promoters. Epigenetics & Chromatin 2015;8: 21. doi:10.1186/s13072-015-0013-9

2014

Hurley, D. G., Budden, D. M., & Crampin, E. J. (2014). Virtual Reference Environments: a simple way to make research reproducible. Briefings in Bioinformatics, bbu043. doi:10.1093/bib/bbu043

Hurley, D. G., Cursons, J., Wang, Y. K., Budden, D. M., Print, C. G., & Crampin, E. J. (2014). NAIL, a software toolset for inferring, analyzing and visualizing regulatory networks. Bioinformatics, 31(2), 277–278. doi:10.1093/bioinformatics/btu612

Budden, D. M., Hurley, D. G., & Crampin, E. J. (2014). Predictive modelling of gene expression from transcriptional regulatory elements. Briefings in Bioinformatics, bbu034. doi:10.1093/bib/bbu034

Budden, D. M., Hurley, D. G., Cursons, J., Markham, J. F., Davis, M. J., & Crampin, E. J. (2014). Predicting expression: the complementary power of histone modification and transcription factor binding data. Epigenetics & Chromatin, 7(1), 1–12.

Hunter, F. W., Jaiswal, J. K., Hurley, D. G., Liyanage, H. D., McManaway, S. P., Gu, Y., … others. (2014). The flavoprotein FOXRED2 reductively activates nitro-chloromethylbenzindolines and other hypoxia-targeting prodrugs. Biochemical Pharmacology, 89(2), 224–235.

Jansson, D., Rustenhoven, J., Feng, S., Hurley, D., Oldfield, R. L., Bergin, P. S., … Dragunow, M. (2014). A role for human brain pericytes in neuroinflammation. Journal of Neuroinflammation, 11(1), 104.

2013

Wang, Y. K., Hurley, D. G., Schnell, S., Crampin, E. J., others, & Print, C. G. (2013). Integration of Steady-State and Temporal Gene Expression Data for the Inference of Gene Regulatory Networks. PLOS ONE, 8(8), e72103.

Wang, J., Guise, C. P., Hsu, H.-L., Hurley, D., Wilson, W. R., & Patterson, A. V. (2013). Identification of reductases capable of metabolic activation of hypoxia targeting prodrug SN30000 and hypoxia marker EF5. In Cancer Research (Vol. 73, pp. 2111–2111).

Blenkiron, C., Hurley, D. G., Fitzgerald, S., Lasham, A., others, & Print, C. G. (2013). Links between the Oncoprotein YB-1 and Small Non-Coding RNAs in Breast Cancer. PLOS ONE, 8(11), e80171. doi:10.1371/journal.pone.0080171

2012

Hurley, D., Araki, H., Tamada, Y., Dunmore, B., Sanders, D., Humphreys, S., … Print, C. G. (2012). Gene network inference and visualization tools for biologists: application to new human transcriptome datasets. Nucleic Acids Research, 40(6), 2377–2398. doi:10.1093/nar/gkr902

Grace, P. P. M., Hurley, D., Barratt, D. T. D., Tsykin, A., Watkins, L. R., Rolan, P. E., & Hutchinson, M. R. (2012). Harnessing pain heterogeneity and RNA transcriptome to identify blood-based pain biomarkers: a novel correlational study design and bioinformatics approach in a graded chronic constriction injury model. Journal of Neurochemistry, 122(5), 976–994. doi:10.1111/j.1471-4159.2012.07833.x

Wang, L., Hurley, D. G., (Joint first authorship),Watkins, W., Araki, H., Tamada, Y., Muthukaruppan, A., … Print, C. G. (2012). Cell cycle gene networks are associated with melanoma prognosis. Plos One, 7(4), e34247. doi:10.1371/journal.pone.0034247

2011

Araki, H., Hurley, D., Crampin, E., Print, C., & Kuhara, S. (2011). Gene Network Analysis and Application. Biophysics (Seibutsu Butsuri), 51(4), 182–185.

Thesis

Hurley DG. Gene network inference and application. The University of Auckland. 2011.

Book chapters

Ellett, S., Ferguson, I. R., Shuotun, Z., Karunasinghe, N., Marlow, G., Hurley, D. G., … Ferguson, L. R. (2013). Foodomics to Study Efficacy of Human Dietary Interventions. In Nutrigenomics and Nutrigenetics in Functional Foods and Personalized Nutrition (pp. 269–280). CRC Press.

Other

Invited talks

Hurley, D. Networks in Computational Biology. Winter School in Mathematical and Computational Biology, The University of Queensland Institute for Molecular Bioscience, Brisbane, July 2-6, 2013.

Hurley, D. Network Methods in Systems Biology. Winter School in Mathematical and Computational Biology, The University of Queensland Institute for Molecular Bioscience, Brisbane, July 2-6, 2012.

Hurley, D. Applications of Network Methods in Systems Biology . Queensland Institute of Medical Research, Brisbane, July 8, 2012.

Hurley, D. Gene network inference and Systems Biology. Winter School in Mathematical and Computational Biology,  The University of Queensland Institute for Molecular Bioscience, Brisbane, July 4-8, 2011.

Hurley, D. Gene Networks for Cancer Research, Bioinformatics Institute seminar series, University of Auckland. September 2010

Other talks

Hurley, D., Wang, L. Cell cycle gene networks are associated with melanoma prognosis.  Submitted talk, Cancer Biology satellite meeting of the Queenstown Research Week 2012, Queenstown, New Zealand.

Hurley, D.  A Rapid Development Toolkit for GenePattern, Auckland Bioengineering Institute departmental seminar, University of Auckland. October 2010

Hurley, D.  Systems Biology, Gene Networks and Human Health, Auckland Bioengineering Institute PhD Completion seminar, University of Auckland. September 2010.

     - Daniel Hurley

© 2016   DANIEL HURLEY

This site created with the Tufte theme in Jekyll.


text:
<!--- master only -->
> ![warning](../../images/warning.png) This document applies to the HEAD of the calico-docker source tree.
>
> View the calico-docker documentation for the latest release [here](https://github.com/projectcalico/calico-containers/blob/v0.19.0/README.md).
<!--- else
> You are viewing the calico-docker documentation for release **release**.
<!--- end of master only -->

# Calico Policy for Kubernetes
Calico supports the v1alpha1 network policy API for Kubernetes.
> *Note*: The Kubernetes network policy API is currently in alpha and is subject to change. Calico support for this API is in beta and so is also subject to change.

## Prerequisites
* A Kubernetes v1.1+ deployment using the [Calico CNI plugin v1.3.0](https://github.com/projectcalico/calico-cni/releases/latest) or greater.
* You must running `calico/node:v0.18.0` or greater on each Kubernetes node.
* You must be using the iptables kube-proxy in your deployment. All of the Calico getting started guides configure the kube-proxy in this way.
* You must have enabled `ThirdPartyResource` objects in your Kubernetes apiserver, as described [here](https://github.com/caseydavenport/kubernetes/blob/network-policy/docs/admin/network-policy.md#enabling-network-policy).

## Behavior
Calico implements the behavior of the Kubernetes [v1alpha1 network policy API](https://github.com/caseydavenport/kubernetes/blob/network-policy/docs/admin/network-policy.md#network-policy-in-kubernetes).

## Enabling v1alpha1 policy support

To enable annotation-based policy in the Calico CNI plugin, add the `policy` section to your CNI network config file as shown - you will need to make this change on each Kubernetes worker node in your cluster (any node that allows scheduling of pods).  The CNI network configuration file can usually be found in the `/etc/cni/net.d/` directory.
```
$ cat /etc/cni/net.d/10-calico.conf
{
    "name": "calico-k8s-network",
    "type": "calico",
    "etcd_authority": "<ETCD_IP:ETCD_PORT>",
    "log_level": "info",
    "ipam": {
        "type": "calico-ipam"
    },
    "policy": {
        "type": "k8s",
        "k8s_api_root": "http://<k8s-master>:<api-port>/api/v1/"
    }
}
```
> More configuration options can be found [here](https://github.com/projectcalico/calico-cni/blob/master/configuration.md).

This will configure label-based policy on Kuberetes pods.

Once you have modified the network configuration file as shown above, you will need to restart the `kubelet` to pick up the changes.

>Example for `systemd`:
```
sudo systemctl restart kubelet
```

## Running the Calico policy agent
In order to use the Kubernetes v1alpha1 network policy API, you must run the
Calico Kubernetes policy agent.  The policy agent runs on each Master node in your
Kubernetes cluster.  It reads policy information from the Kubernetes API and
configures Calico appropriately.

To run the Calico Kubernetes policy agent:

1. Download the policy services manifest file on your master.
```
wget https://raw.githubusercontent.com/projectcalico/k8s-policy/master/examples/calico-policy-agent.yaml
```

2. Replace the ETCD_ENDPOINTS variable in that file with the correct configuration to access your etcd cluster.

3. Move the file to the kubelet config directory on your master.
```
mv calico-policy-agent.yaml /etc/kubernetes/manifests/
```
> Make sure your kubelet is started with the `--config=/etc/kubernetes/manifests` option.

After a few moments, you should see the calico-policy-agent pod running in the `calico-system` namespace.
```
$ kubectl get pods --namespace=calico-system
NAME                             READY     STATUS    RESTARTS   AGE
calico-policy-agent-k8s-master   1/1       Running   0          1m
```

## Next Steps
- Install the [policy tool](https://github.com/projectcalico/k8s-policy/blob/master/policy_tool/README.md) for easy management of NetworkPolicy objects.

- Once you have enabled network policy on your cluster and configured Calico to use the Kubernetes network
policy API, you can deploy our [Kubernetes policy example application](stars-demo/README.md).

[![Analytics](https://calico-ga-beacon.appspot.com/UA-52125893-3/calico-containers/docs/cni/kubernetes/NetworkPolicy.md?pixel)](https://github.com/igrigorik/ga-beacon)


text:
<!--
Include Base: /Users/jtsm/Chukong-Inc/pr/en/src/vungle/v3-cpp
-->

#Vungle

##Integration
Open a terminal and use the following command to install the SDKBOX Vungle plugin. Make sure you setup SDKBOX installer correctly.
```bash
$ sdkbox import vungle
```

<<[../../shared/notice.md]

## Configuration
SDKBOX Installer will automatically inject a sample configuration to your `sdkbox_config.json`, that you have to modify it before you can use it for your own app

Here is an example of the Vungle configuration, you need to replace `<vungle id>`  with your specific [Vungle](http://vungle.com) Publisher account information.
Here is an example adding `Vungle` to iOS:
```json
"Vungle" :
{
    "id":"<vungle id>",
    "ads":{
        "video":{

        },
        "reward":{
            "incentivized" : true
        }
    }
}
```

<<[sdkbox-config-encrypt.md]

Adding `Vungle` to Android is a bit different as it supports __sound__ and
__backbutton__ settings. Here is an example adding `Vungle` to Android:
```json
"Vungle" :
{
    "id":"<vungle id>",
    "ads":{
        "video":{
            "sound" : true,
            "backbutton" : true
        },
        "reward":{
            "sound" : false,
            "backbutton" : false,
            "incentivized" : true
        }
    }
}
```

##Usage
<<[usage.md]

<<[api-reference.md]

<<[manual_integration.md]

<<[manual_ios.md]

##Manual Integration For Android and Android Studio
Both __Android__ development using a command-line and using __Android Studio__ are supported. `proj.android` will be used as our `<project_root>` for __command-line__ development, while `proj.android-studio` will be used as our `<project_root>` for __Android Studio__.
<<[manual_android.md]

<<[extra-step.md]

<<[proguard.md]


text:
package com.sopranoworks.bolt

import org.specs2.mutable.Specification

class LikeMatcherTest extends Specification {

  "apply" should {
    "test%" in {
      LikeMatcher("test%").findFirstIn("testok").isDefined must_== true
      LikeMatcher("test%").findFirstIn("test").isDefined must_== false
      LikeMatcher("test%").findFirstIn(" testok").isDefined must_== false
    }
    "test$%" in {
      LikeMatcher("test$%").findFirstIn("test$ok").isDefined must_== true
      LikeMatcher("test$%").findFirstIn("test$").isDefined must_== false
      LikeMatcher("test$%").findFirstIn(" test$ok").isDefined must_== false
    }
    "test\\%%" in {
      LikeMatcher("test\\%%").findFirstIn("test%ok").isDefined must_== true
      LikeMatcher("test\\%%").findFirstIn("test%").isDefined must_== false
      LikeMatcher("test\\%%").findFirstIn(" test%ok").isDefined must_== false
    }
    "test_" in {
      LikeMatcher("test_").findFirstIn("test!").isDefined must_== true
      LikeMatcher("test_").findFirstIn("test").isDefined must_== false
      LikeMatcher("test_").findFirstIn(" test!").isDefined must_== false
    }
    "test[%]" in {
      LikeMatcher("test[%]").findFirstIn("test[test]").isDefined must_== true
      LikeMatcher("test[%]").findFirstIn("test[]").isDefined must_== false
      LikeMatcher("test[%]").findFirstIn(" test[test]").isDefined must_== false
    }
  }
}


text:
package org.apache.felix.hc.generalchecks;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.felix.hc.annotation.HealthCheckService;
import org.apache.felix.hc.api.FormattingResultLog;
import org.apache.felix.hc.api.HealthCheck;
import org.apache.felix.hc.api.Result;
import org.apache.felix.hc.api.ResultLog.Entry;
import org.apache.felix.hc.generalchecks.scrutil.DsRootCauseAnalyzer;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.component.runtime.ServiceComponentRuntime;
import org.osgi.service.component.runtime.dto.ComponentConfigurationDTO;
import org.osgi.service.component.runtime.dto.ComponentDescriptionDTO;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@HealthCheckService(name = DsComponentsCheck.HC_NAME, tags = { DsComponentsCheck.HC_DEFAULT_TAG })
@Designate(ocd = DsComponentsCheck.Config.class, factory = true)
public class DsComponentsCheck implements HealthCheck {

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

    public static final String HC_NAME = "DS Components Ready Check";
    public static final String HC_DEFAULT_TAG = "systemalive";

    @ObjectClassDefinition(name = "Health Check: "
            + HC_NAME, description = "System ready check that checks a list of DS components and provides root cause analysis in case of errors")
    public @interface Config {

        @AttributeDefinition(name = "Name", description = "Name of this health check")
        String hc_name() default HC_NAME;

        @AttributeDefinition(name = "Tags", description = "List of tags for this health check, used to select subsets of health checks for execution e.g. by a composite health check.")
        String[] hc_tags() default { HC_DEFAULT_TAG };

        @AttributeDefinition(name = "Required Component Names", description = "The components that are required to be enabled")
        String[] components_list();

        @AttributeDefinition(name = "Status for missing component", description = "Status in case components are missing enabled components")
        Result.Status statusForMissing() default Result.Status.TEMPORARILY_UNAVAILABLE;

        @AttributeDefinition
        String webconsole_configurationFactory_nameHint() default "{hc.name}: {components.list} / missing -> {statusForMissing}";
    }

    private List<String> componentsList;

    private Result.Status statusForMissing;

    @Reference(policyOption = ReferencePolicyOption.GREEDY)
    private DsRootCauseAnalyzer analyzer;

    volatile ServiceComponentRuntime scr;

    private final AtomicBoolean refreshCache = new AtomicBoolean();

    private final AtomicReference<Result> cache = new AtomicReference<>();

    @Activate
    public void activate(final BundleContext ctx, final Config config) throws InterruptedException {
        componentsList = Arrays.asList(config.components_list());
        statusForMissing = config.statusForMissing();
        this.refreshCache.set(false); // cache is empty
        LOG.debug("Activated DS Components HC for componentsList={}", componentsList);
    }

    @Override
    public Result execute() {
        Result result = this.cache.get();
        if ( result == null || this.refreshCache.compareAndSet(true, false) ) {
            result = executeInternal();
            if ( result.isOk() ) {
                this.cache.set(result);
            } else {
            	this.cache.set(null);
            }
        }
        return result;
    }

    protected Result executeInternal () {
    	FormattingResultLog log = new FormattingResultLog();

        Collection<ComponentDescriptionDTO> componentDescriptionDTOs = null;
        try {
            componentDescriptionDTOs = scr.getComponentDescriptionDTOs();
        } catch ( final Throwable e) {
            log.temporarilyUnavailable("Exception while getting ds component dtos {}", e.getMessage(), e);
        }
        if ( componentDescriptionDTOs != null ) {
            final List<ComponentDescriptionDTO> watchedComps = new LinkedList<ComponentDescriptionDTO>();
            final List<String> missingComponents = new LinkedList<String>(componentsList);
            for (final ComponentDescriptionDTO desc : componentDescriptionDTOs) {
                if (componentsList.contains(desc.name)) {
                    watchedComps.add(desc);
                    missingComponents.remove(desc.name);
                }
            }
            for (final String missingComp : missingComponents) {
                log.info("No component with name {} is registered in SCR runtime", missingComp);
            }

            int countEnabled = 0;
            int countDisabled = 0;
            for (final ComponentDescriptionDTO dsComp : watchedComps) {

                boolean isActive;

                boolean componentEnabled = scr.isComponentEnabled(dsComp);
                if (componentEnabled) {

                    try {
                        Collection<ComponentConfigurationDTO> componentConfigurationDTOs = scr.getComponentConfigurationDTOs(dsComp);
                        List<String> idStateTuples = new ArrayList<>();
                        boolean foundActiveOrSatisfiedConfig = false;
                        for (ComponentConfigurationDTO configDto : componentConfigurationDTOs) {
                            idStateTuples.add("id " + configDto.id + ":" + toStateString(configDto.state));
                            if (configDto.state == ComponentConfigurationDTO.ACTIVE || configDto.state == ComponentConfigurationDTO.SATISFIED) {
                                foundActiveOrSatisfiedConfig = true;
                            }
                        }
                        log.debug(dsComp.name + " (" + String.join(",", idStateTuples) + ")");

                        if (componentConfigurationDTOs.isEmpty() || foundActiveOrSatisfiedConfig) {
                            countEnabled++;
                            isActive = true;
                        } else {
                            countDisabled++;
                            isActive = false;
                        }
                    } catch ( final Throwable e) {
                        log.temporarilyUnavailable("Exception while getting ds component dtos {}", e.getMessage(), e);
                        isActive = true; // no info available, doesn't make sense to report as inactive
                    }

                } else {
                    countDisabled++;
                    isActive = false;
                }

                if (!isActive) {
                    analyzer.logNotEnabledComponent(log, dsComp, componentDescriptionDTOs);
                }
            }

            if (!missingComponents.isEmpty()) {
                log.add(new Entry(statusForMissing, missingComponents.size() + " required components are missing in SCR runtime"));
            }
            if (countDisabled > 0) {
                log.add(new Entry(statusForMissing, countDisabled + " required components are not active"));
            }
            log.info("{} required components are active", countEnabled);
        }
        return new Result(log);
    }

    static final String toStateString(int state) {

        final int FAILED_ACTIVATION = 16; // not yet available in r6, but dependency should be left on r6 for max compatibility

        switch (state) {
        case ComponentConfigurationDTO.ACTIVE:
            return "active";
        case ComponentConfigurationDTO.SATISFIED:
            return "satisfied";
        case ComponentConfigurationDTO.UNSATISFIED_CONFIGURATION:
            return "unsatisfied (configuration)";
        case ComponentConfigurationDTO.UNSATISFIED_REFERENCE:
            return "unsatisfied (reference)";
        case FAILED_ACTIVATION:
            return "failed activation";
        default:
            return String.valueOf(state);
        }
    }

    @Reference(name = "scr", updated = "updatedServiceComponentRuntime")
    private void setServiceComponentRuntime(final ServiceComponentRuntime c) {
        this.scr = c;
    }

    private void unsetServiceComponentRuntime(final ServiceComponentRuntime c) {
        this.scr = null;
    }

    protected void updatedServiceComponentRuntime(final ServiceComponentRuntime c) {
        // change in DS - mark cache
        this.refreshCache.compareAndSet(false, true);
        LOG.debug("invalidate DsComponentsCheck cache");
    }
}


text:
package chrome.browser

import chrome.ChromeAPI
import chrome.browser.bindings.OpenTabOptions
import chrome.permissions.APIPermission
import utils.ErrorHandling.lastErrorOrValue

import scala.concurrent.{Future, Promise}
import scala.scalajs.js

object Browser extends ChromeAPI {

  val requiredPermissions: Set[APIPermission] = Set(APIPermission.Browser)

  def openTab(url: String): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Browser.openTab(OpenTabOptions(url = url), js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

}


text:
package nz.co.fortytwo.signalk.handler;

import static nz.co.fortytwo.signalk.util.ConfigConstants.STATIC_DIR;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nz.co.fortytwo.signalk.util.SignalKConstants;
import nz.co.fortytwo.signalk.util.Util;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.FetchResult;

/*
 * Processes REST requests for Signal K installs from Github
 *
 *
 * @author robert
 */
public class GitHandler {

	private static final String SLASH = "/";
	private static Logger logger = LogManager.getLogger(GitHandler.class);
	private File staticDir = null;

	private static String github = "https://github.com/SignalK/";

	public GitHandler() {
		super();
		staticDir = new File(Util.getConfigProperty(STATIC_DIR));
	}
	/**
	 * Process a signalk install
	 *
	 * @param request
	 * @param response
	 * @param signalkModel
	 * @return
	 * @throws IOException
	 */
	public Object processInstall(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// use Restlet API to create the response
		String path = request.getPathInfo();
		// String path = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);
		if (logger.isDebugEnabled())
			logger.debug("We are processing the path = " + path);

		// check valid request.
		if (path.length() < SignalKConstants.SIGNALK_INSTALL.length() || !path.startsWith(SignalKConstants.SIGNALK_INSTALL)) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return null;
		}
		path = path.substring(SignalKConstants.SIGNALK_INSTALL.length());
		if (path.startsWith(SLASH))
			path = path.substring(1);
		if (logger.isDebugEnabled())
			logger.debug("We are processing the extension:" + path);
		// now we should have a valid github project name
		try {
			String fileName = install(path);
			response.setStatus(HttpServletResponse.SC_OK);
			response.sendRedirect("/config/logs.html");
			return fileName;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return e.getMessage();
		}

	}
	/**
	 * Process a signalk install
	 *
	 * @param request
	 * @param response
	 * @param signalkModel
	 * @return
	 * @throws IOException
	 */
	public Object processUpgrade(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// use Restlet API to create the response
		String path = request.getPathInfo();
		// String path = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);
		if (logger.isDebugEnabled())
			logger.debug("We are processing the path = " + path);

		// check valid request.
		if (path.length() < SignalKConstants.SIGNALK_UPGRADE.length() || !path.startsWith(SignalKConstants.SIGNALK_UPGRADE)) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return null;
		}
		path = path.substring(SignalKConstants.SIGNALK_UPGRADE.length());
		if (path.startsWith(SLASH))
			path = path.substring(1);
		if (logger.isDebugEnabled())
			logger.debug("We are processing the extension:" + path);
		// now we should have a valid github project name
		try {
			String fileName = upgrade(path);
			response.setStatus(HttpServletResponse.SC_OK);
			response.sendRedirect("/config/logs.html");
			return fileName;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return e.getMessage();
		}

	}

	protected String install(String path) throws Exception{
		//staticDir.mkdirs();
		Git result = null;
		try {
			File installLogDir = new File(staticDir,"logs");
			installLogDir.mkdirs();
			//make log name
			String logFile = "output.log";
			File output = new File(installLogDir,logFile);
			File destDir = new File(staticDir,SLASH+path);
			destDir.mkdirs();
			String gitPath = github+path+".git";
			logger.debug("Cloning from " + gitPath + " to " + destDir.getAbsolutePath());
			FileUtils.writeStringToFile(output, "Updating from " + gitPath + " to " + destDir.getAbsolutePath()+"\n",false);
			try{
				result = Git.cloneRepository().setURI(gitPath).setDirectory(destDir).call();
				result.fetch().setRemote(gitPath);
				logger.debug("Cloned "+gitPath+" repository: " + result.getRepository().getDirectory());
				FileUtils.writeStringToFile(output, "DONE: Cloned "+gitPath+" repository: " + result.getRepository().getDirectory(), true);
			}catch(Exception e){
				FileUtils.writeStringToFile(output, e.getMessage(),true);
				FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
				logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
			}
			/*try{
				//now run npm install
				runNpmInstall(output, destDir);
			}catch(Exception e){
				FileUtils.writeStringToFile(output, e.getMessage(),true);
				FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
				logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
			}*/
			return logFile;

		} finally {
			if(result!=null)result.close();
		}

	}
	private void runNpmInstall(final File output, File destDir)  throws Exception{
		FileUtils.writeStringToFile(output, "\nBeginning npm install" ,true);
		ProcessBuilder pb = new ProcessBuilder("npm", "install");
		Map<String, String> env = System.getenv();
		if(env.containsKey("PATH")){
			pb.environment().put("PATH", env.get("PATH"));
		}
		if(env.containsKey("Path")){
			pb.environment().put("Path", env.get("Path"));
		}
		if(env.containsKey("path")){
			pb.environment().put("path", env.get("path"));
		}
		pb.directory(destDir);
		pb.redirectErrorStream(true);
		pb.redirectOutput(output);
		final Process p = pb.start();
		Thread t = new Thread(){

			@Override
			public void run() {
				try {
					p.waitFor();
					FileUtils.writeStringToFile(output, "\nDONE: Npm ended sucessfully" ,true);
				} catch (Exception e) {
					try {
						logger.error(e);
						FileUtils.writeStringToFile(output, "\nNpm ended badly:"+e.getMessage() ,true);
						FileUtils.writeStringToFile(output, "\n"+e.getStackTrace() ,true);
					} catch (IOException e1) {
						logger.error(e1);
					}
				}
			}

		};
		t.start();
	}
	protected String upgrade(String path) throws Exception{
		//staticDir.mkdirs();
		Repository repository = null;
		try {
			String logFile = "output.log";
			File installLogDir = new File(staticDir,"logs");
			installLogDir.mkdirs();
			//
			File destDir = new File(staticDir,SLASH+path);
			destDir.mkdirs();
			File output = new File(installLogDir,logFile);
			String gitPath = github+path+".git";
			logger.debug("Updating from " + gitPath + " to " + destDir.getAbsolutePath());
			FileUtils.writeStringToFile(output, "Updating from " + gitPath + " to " + destDir.getAbsolutePath()+"\n",false);
			Git git = null;
			try{
				FileRepositoryBuilder builder = new FileRepositoryBuilder();
				repository = builder.setGitDir(new File(destDir,"/.git"))
					.readEnvironment() // scan environment GIT_* variables
					.findGitDir() // scan up the file system tree
					.build();
				git = new Git(repository);
				PullResult result = git.pull().call();
				FileUtils.writeStringToFile(output, result.getMergeResult().toString(),true);
				logger.debug("DONE: Updated "+gitPath+" repository: " + result.getMergeResult().toString());

				//now run npm install
				//runNpmInstall(output, destDir);
			}catch(Exception e){
				FileUtils.writeStringToFile(output, e.getMessage(),true);
				FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
				logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
			}finally{
				if(git!=null) git.close();
				if(repository!=null)repository.close();
			}
			return logFile;

		} finally {
			if(repository!=null)repository.close();
		}

	}

}


text:
calvin
======

Machine Learning


text:
ActiveRecord::Schema.define :version => 0 do
  create_table :cartoons, :force => true do |t|
    t.column :first_name, :string
    t.column :last_name,  :string
  end

  create_table :categories, :force => true do |t|
    t.column :name, :string
  end

  create_table :projects, :force => true do |t|
    t.column :category_id, :integer
    t.column :name,        :string
    t.column :description, :string
  end

  create_table :documents, :force => true do |t|
    t.column :title, :string
    t.column :type, :string
  end

  create_table :people, :force => true do |t|
    t.column :category_id, :integer
    t.column :type, :string
    t.column :name, :string
  end
end


text:
#ifndef __ARCH_ARM_SRC_EFM32_EFM32_PM_H
#define __ARCH_ARM_SRC_EFM32_EFM32_PM_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdbool.h>

#include "chip.h"
#include "up_internal.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Public Types
 ****************************************************************************/

/****************************************************************************
 * Public Data
 ****************************************************************************/

 #ifndef __ASSEMBLY__
#ifdef __cplusplus
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

/****************************************************************************
 * Name: efm32_pmstop
 *
 * Description:
 *   Enter STOP mode.
 *
 *   REVISIT: This power management interface was taken with no modification
 *   from the EFM32 implementation and needs to be reviewed against EFM32
 *   reduced power modes.  Comments here apply to the EFM32!
 *
 * Input Parameters:
 *   lpds - true: To further reduce power consumption in Stop mode, put the
 *          internal voltage regulator in low-power mode using the LPDS bit
 *          of the Power control register (PWR_CR).
 *
 * Returned Value:
 *   Zero means that the STOP was successfully entered and the system has
 *   been re-awakened.  The internal voltage regulator is back to its
 *   original state.  Otherwise, STOP mode did not occur and a negated
 *   errno value is returned to indicate the cause of the failure.
 *
 ****************************************************************************/

int efm32_pmstop(bool lpds);

/****************************************************************************
 * Name: efm32_pmstandby
 *
 * Description:
 *   Enter STANDBY mode.
 *
 *   REVISIT: This power management interface was taken with no modification
 *   from the EFM32 implementation and needs to be reviewed against EFM32
 *   reduced power modes.  Comments here apply to the EFM32!
 *
 * Input Parameters:
 *   None
 *
 * Returned Value.
 *   On success, this function will not return (STANDBY mode can only be
 *   terminated with a reset event).  Otherwise, STANDBY mode did not occur
 *   and a negated errno value is returned to indicate the cause of the
 *   failure.
 *
 ****************************************************************************/

int efm32_pmstandby(void);

/****************************************************************************
 * Name: efm32_pmsleep
 *
 * Description:
 *   Enter SLEEP mode.
 *
 *   REVISIT: This power management interface was taken with no modification
 *   from the EFM32 implementation and needs to be reviewed against EFM32
 *   reduced power modes.  Comments here apply to the EFM32!
 *
 * Input Parameters:
 *   sleeponexit - true:  SLEEPONEXIT bit is set when the WFI instruction is
 *                        executed, the MCU enters Sleep mode as soon as it
 *                        exits the lowest priority ISR.
 *               - false: SLEEPONEXIT bit is cleared, the MCU enters Sleep mode
 *                        as soon as WFI or WFE instruction is executed.
 * Returned Value:
 *   Zero means that the STOP was successfully entered and the system has
 *   been re-awakened.  The internal voltage regulator is back to its
 *   original state.  Otherwise, STOP mode did not occur and a negated
 *   errno value is returned to indicate the cause of the failure.
 *
 ****************************************************************************/

void efm32_pmsleep(bool sleeponexit);

#undef EXTERN
#ifdef __cplusplus
}
#endif
#endif /* __ASSEMBLY__ */

#endif /* __ARCH_ARM_SRC_EFM32_EFM32_PM_H */


text:
<?php

namespace FastPay\Tests\Error;

use FastPay\Error\CardError;

class CardErrorTest extends \PHPUnit_Framework_TestCase
{
    public function testCreate()
    {
        $body = '{"error":{"type":"card_error","message":"Your card was declined. Your request was in test mode, but used a no test card.","code":"card_declined","param":null}}';
        $code = "card_declined";
        try {
            throw new CardError(402, $body, $code);
            $this->fail("expect throw card error");
        } catch (CardError $e) {
            $this->assertSame('Status:402, Body:' . $body, $e->getMessage());
            $this->assertSame(402, $e->getHttpStatus());
            $this->assertEquals(json_decode($body), $e->getHttpBody());
            $this->assertSame($code, $e->getCode());
        }
    }
}


text:
/**
 * @author Anas Nashif
 * @author Eugene Yarmosh
 */

/**
 * @addtogroup XMLParserGeneric
 *
 * @{
 */

#ifndef XML_API_GENERIC_H_
#define XML_API_GENERIC_H_

#include "wsman-xml-api.h"

struct __WsXmlParserData {
	WsXmlDocH nsHolder;
	void *_private;
};
typedef struct __WsXmlParserData WsXmlParserData;

#define xml_parser_get_first_child(x) xml_parser_node_get(x, 0)
#define xml_parser_get_next_child(x) xml_parser_node_get(x, XML_ELEMENT_NEXT)

struct _WsXmlFindNsData {
	const char *prefix;
	const char *nsUri;
	WsXmlNodeH node;
	WsXmlNsH ns;
};
typedef struct _WsXmlFindNsData WsXmlFindNsData;

struct _FindInTreeCallbackData {
	const char *ns;
	const char *name;
	WsXmlNodeH node;
};
typedef struct _FindInTreeCallbackData FindInTreeCallbackData;

struct __WsXmlDumpNodeTreeData {
	FILE *stream;
	int indent;
};
typedef struct __WsXmlDumpNodeTreeData WsXmlDumpNodeTreeData;

WsXmlDocH ws_xml_create_envelope(void);

WsXmlDocH ws_xml_duplicate_doc(WsXmlDocH srcDoc);

WsXmlDocH ws_xml_create_doc_by_import(WsXmlNodeH node);

//SoapH ws_xml_get_doc_soap_handle(WsXmlDocH doc);

int ws_xml_parser_initialize(void);

void ws_xml_parser_destroy(void);

int ws_xml_get_child_count(WsXmlNodeH parent);

char *ws_xml_get_node_name_ns_uri(WsXmlNodeH node);

char *ws_xml_get_node_name_ns_prefix(WsXmlNodeH node);

WsXmlDocH ws_xml_read_file(const char *filename,
			   const char *encoding, unsigned long options);

WsXmlDocH ws_xml_read_memory(const char *buf, size_t size,
			     const char *encoding, unsigned long options);

WsXmlDocH ws_xml_create_doc( const char *rootNsUri, const char *rootName);

int ws_xml_check_xpath(WsXmlDocH doc, const char *xpath_expr);

int ws_xml_utf8_strlen(char *buf);

void ws_xml_set_node_lang(WsXmlNodeH node, const char *lang);

void ws_xml_unlink_node(WsXmlNodeH node);

// to check if the size of envelop exceeds a maximum size
int check_envelope_size(WsXmlDocH doc, unsigned int size, const char *charset);

/** @} */

#endif				/*XML_API_GENERIC_H_ */