text:
package edu.buffalo.fusim;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import edu.buffalo.fusim.gtf.Strand;

public class FusionGene {

    private List<TranscriptRecord> genes = new ArrayList<TranscriptRecord>();
    private List<FusionOption> options = new ArrayList<FusionOption>();
    private FusionType fusionType = FusionType.HYBRID;
    private String geneId;
    private String transcriptId;

    public FusionGene(List<TranscriptRecord> transcripts) {
        for(TranscriptRecord tr : transcripts) {
            genes.add(tr);
        }
        this.setIds();
    }

    public FusionGene(TranscriptRecord gene1, TranscriptRecord gene2) {
        this.genes.add(gene1);
        this.genes.add(gene2);
        this.setIds();
    }

    public FusionGene(TranscriptRecord gene1, TranscriptRecord gene2, TranscriptRecord gene3) {
        this.genes.add(gene1);
        this.genes.add(gene2);
        this.genes.add(gene3);
        this.setIds();
    }

    public String outputFasta(List<int []> breaks, File reference, boolean cdsExonsOnly, boolean fixOrientation) {
        return this.outputFasta(breaks, reference, cdsExonsOnly, fixOrientation, 0);
    }

    public String outputFasta(List<int []> breaks, File reference, boolean cdsExonsOnly, boolean fixOrientation, int foreignInsertionLen) {
        ExtractSeq extractSeq = new ExtractSeq(reference);

        StringBuffer fasta = new StringBuffer();
        fasta.append(">ref|"+this.getTranscriptId()
                     +" fusionGene="+this.getGeneId()
                     +" fusionType="+this.getFusionType()
                     +" fusionOptions="+StringUtils.join(this.options, ","));

        List<StringBuffer> seqs = new ArrayList<StringBuffer>();
        for(int b = 0; b < breaks.size(); b++) {
            int[] exons = breaks.get(b);
            TranscriptRecord gene = genes.get(b);
            int breakno = b+1;
            fasta.append(" chrom"+breakno+"="+gene.getChrom()
                         +" strand"+breakno+"="+gene.getStrand()
                         +" exonIndex"+breakno+"="+StringUtils.join(ArrayUtils.toObject(exons), ",")
                         //+" exons"+breakno+"="
                         );

            StringBuffer breakSeq = new StringBuffer();
            for(int i = 0; i < exons.length; i++) {
                int[] exon = gene.getExons(cdsExonsOnly).get(exons[i]);
                //fasta.append((exon[0]+1)+"-"+exon[1]);
                //if(i != (exons.length-1)) fasta.append(",");
                breakSeq.append(extractSeq.fetch(gene.getChrom(), gene.getStrand(), exon[0]+1, exon[1]));
            }
            seqs.add(breakSeq);
        }

        fasta.append("\n");

        Strand normStrand = genes.get(0).getStrand();

        for(int i = 0; i < genes.size(); i++) {
            if(fixOrientation && !normStrand.equals(genes.get(i).getStrand())) {
                fasta.append(ExtractSeq.reverseComplement(seqs.get(i)));
            } else {
                fasta.append(seqs.get(i).toString());
            }

            if(foreignInsertionLen > 0) {
                if(i == 0 || (i == 1 && genes.size() == 3)) {
                    fasta.append(ExtractSeq.randomSequence(foreignInsertionLen));
                }
            }
        }

        return fasta.toString();
    }

    private List<String> createTxtColumns(TranscriptRecord gene, int[] breaks, boolean cdsExonsOnly) {
        List<String> cols = new ArrayList<String>();
        cols.add(this.getGeneId());
        cols.add(gene.getGeneId());
        cols.add(gene.getTranscriptId());
        cols.add(gene.getChrom());
        cols.add(gene.getStrand().toString());
        cols.add(""+breaks.length);

        int[] exonStarts = new int[breaks.length];
        int[] exonEnds = new int[breaks.length];
        int exonBases = 0;
        for(int i = 0; i < breaks.length; i++) {
            int[] exon = gene.getExons(cdsExonsOnly).get(breaks[i]);
            exonStarts[i] = (exon[0]+1);
            exonEnds[i] = exon[1];
            exonBases += exon[1]-exon[0];
        }

        cols.add(""+exonBases);
        cols.add(StringUtils.join(ArrayUtils.toObject(breaks), ","));
        cols.add(StringUtils.join(ArrayUtils.toObject(exonStarts), ","));
        cols.add(StringUtils.join(ArrayUtils.toObject(exonEnds), ","));
        cols.add(this.fusionType.toString());
        cols.add(StringUtils.join(this.options, ","));

        return cols;
    }

    public String outputText(List<int[]> breaks, boolean cdsExonsOnly) {
        StringBuffer txt = new StringBuffer();

        for(int i = 0; i < breaks.size(); i++) {
            int[] exons = breaks.get(i);
            TranscriptRecord gene = genes.get(i);
            txt.append(StringUtils.join(this.createTxtColumns(gene, exons, cdsExonsOnly), "\t")+"\n");
        }

        return txt.toString();
    }

    private void setIds() {
        this.geneId = StringUtils.join(
                            CollectionUtils.collect(
                                this.genes,
                                new Transformer() {
                                    public Object transform(Object g) {
                                        return ((TranscriptRecord)g).getGeneId();
                                    }
                                }
                            ), "-");

        this.transcriptId = StringUtils.join(
                            CollectionUtils.collect(
                                this.genes,
                                new Transformer() {
                                    public Object transform(Object g) {
                                        return ((TranscriptRecord)g).getTranscriptId();
                                    }
                                }
                            ), "-");
    }

    public String getGeneId() {
        return this.geneId;
    }

    public String getTranscriptId() {
        return this.transcriptId;
    }

    public static String[] getHeader() {
        return new String[]{
                "fusionGene", "geneName", "name", "chrom", "strand", "exonCount",
                "exonBases", "exonIndexes", "exonStarts", "exonEnds", "fusionType", "fusionOptions"
                };
    }

    public String toString() {
        String str = "";
        for(int i = 0; i < genes.size(); i++) {
            TranscriptRecord gene = genes.get(i);
            int geneno = i+1;
            str += "---- FUSION "+geneno+" -------\n";
            str += gene.toString();
        }
        return str;
    }

    public TranscriptRecord getGene(int index) {
        return genes.get(index);
    }

    public int size() {
        return genes.size();
    }

    public void addGene(TranscriptRecord gene) {
        genes.add(gene);
    }

    public FusionType getFusionType() {
        return this.fusionType;
    }

    public void setFusionType(FusionType fusionType) {
        this.fusionType = fusionType;
    }

    public List<FusionOption> getFusionOptions() {
        return this.options;
    }

    public void addOption(FusionOption option) {
        this.options.add(option);
    }
}


text:
<?php

namespace Tmdb\Api;

/**
 * Class TvEpisode
 * @package Tmdb\Api
 * @see http://docs.themoviedb.apiary.io/#tvepisodes
 */
class TvEpisodeGroup extends AbstractApi
{
    /**
     * Get the primary information about a TV episode group by it's id.
     *
     * @param $episode_group
     * @param array $parameters
     * @param array $headers
     * @return mixed
     */
    public function getEpisodeGroup(
        $episode_group,
        array $parameters = [],
        array $headers = []
    ) {
        return $this->get(
            sprintf(
                'tv/episode_group/%s',
                $episode_group
            ),
            $parameters,
            $headers
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
golang-util
===========

Some basic utilities for Go programs


text:
[![npm](https://img.shields.io/npm/v/ngconf.svg)](https://npm.taobao.org/package/ngconf)
[![Build Status](https://travis-ci.org/jasonz93/ngconf.svg?branch=master)](https://travis-ci.org/jasonz93/ngconf)
[![Coverage Status](https://coveralls.io/repos/github/jasonz93/ngconf/badge.svg?branch=master)](https://coveralls.io/github/jasonz93/ngconf?branch=master)

A new generation distribute configuration component used etcd, currently for Node.JS

## Quick Start
See example.js

```javascript
const NgConf = require('ngconf');
const path = require('path');

let ngconf = new NgConf('http://127.0.0.1:2379', 'ngconf-example');

ngconf.local({
    development: './examples',
    production: {
        '/test.conf': './examples-prod/test.conf',
        'test.json': path.join(__dirname, 'examples-prod', 'test.json')
    }
});

ngconf.raw('/test.conf', readResult, watcherResult);

ngconf.json('/test.json', readResult, watcherResult);

function readResult(err, data) {
    console.log('This is read result.', data);
}

function watcherResult(data) {
    console.log('This is watcher result.', data);
}
```

1. Put these files in the same directory

> - example.js (shown above)
> - examples/
> - examples-prod/

2. Development environment
```shell
$ node example.js
```
3. Use NODE_ENV to switch profile.
```shell
$ NODE_ENV=production node example.js
```

## Base Usage
```javascript
new NgConf(etcdHosts, namespace, [options])
```

### Args
- etcdHosts: String or array.`'http://127.0.0.1:2379'` or `['http://127.0.0.1:2379', 'http://192.168.1.1:2379']`
- namespace: String, usually use project name.
- options: Object. Full options and default values like this.
```javascript
let opts = {
    localOnly: false     //When true, ngconf will only use content in local cache, and won't update configs in etcd
    profile: function () {  //function or string, returns profile name
        return process.env.NODE_ENV || 'development';
    }
}
```

### Callbacks

#### callback
```javascript
function callback(err, data) {}
```

#### watcher
```javascript
function watcher(data) {}
```

### Methods
```javascript
ngconf.raw(name, callback, [watcher]);
```
```javascript
ngconf.json(name, callback, [watcher]);
```


text:
package com.ichorpowered.guardian.api.game.model;

import com.ichorpowered.guardian.api.game.model.value.GameValue;
import com.ichorpowered.guardian.api.game.model.value.key.GameKey;
import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.Optional;

public interface ModelFactories {

    /**
     * Creates a new physical {@link GameValue} with the
     * specified properties.
     *
     * @param component the owning component
     * @param gameKey the value gameKey
     * @param <E> the value type
     * @return the new value, if present
     */
    @NonNull <E> Optional<GameValue<E>> createValue(@NonNull Component component,
                                                    @NonNull GameKey<E> gameKey);

    @NonNull <E> Optional<GameValue<E>> createValue(@NonNull Component component,
                                                    @NonNull GameKey<E> gameKey,
                                                    @NonNull E element);

}


text:
layout: error_500
css_filename: minty.css
---


text:
import java.awt.*;

import javax.swing.*;

// A class which when given a file name, returns a JPanel with the image stretched to fit its boundaries.

class ImagePanel extends JPanel {
	private Image img;

	public ImagePanel(String imgStr) { // Constructor, passed image string
		this.img = new ImageIcon(imgStr).getImage();
		Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); // If we don't use setBounds (after instance is created), this is a fallback to the actual dimensions of the image
		setSize(size);
		setLayout(null);
	}

	public void paintComponent(Graphics g) { // Draw the image to the JPanel
		g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
	}
}


text:
if (typeof exports === 'object') {
	var assert = require('assert');
	var alasql = require('..');
}

describe('Test 08', function () {
	it('UPDATE WHERE with conditions test ', function (done) {
		var db = new alasql.Database();

		db.exec('CREATE TABLE test (a INT, b INT, c INT)');
		db.exec('INSERT INTO test VALUES (1,10,100)');
		db.exec('INSERT INTO test VALUES (2,20,200)');
		db.exec('INSERT INTO test VALUES (3,30,300)');
		db.exec('INSERT INTO test VALUES (4,40,400)');
		db.exec('INSERT INTO test VALUES (5,50,500)');

		db.exec('UPDATE test SET a=a*100, b=-b WHERE b<=3*10 AND a<>2');

		var res = db.exec('SELECT VALUE SUM(a) FROM test');
		assert.equal(411, res);

		var res = db.exec('SELECT VALUE MIN(b) FROM test');
		assert.equal(-30, res);
		done();
	});
});


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.imagebuilder.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for ProvisioningErrorCode. */
public final class ProvisioningErrorCode extends ExpandableStringEnum<ProvisioningErrorCode> {
    /** Static value BadSourceType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_SOURCE_TYPE = fromString("BadSourceType");

    /** Static value BadPIRSource for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_PIRSOURCE = fromString("BadPIRSource");

    /** Static value BadManagedImageSource for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_MANAGED_IMAGE_SOURCE = fromString("BadManagedImageSource");

    /** Static value BadSharedImageVersionSource for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_SHARED_IMAGE_VERSION_SOURCE =
        fromString("BadSharedImageVersionSource");

    /** Static value BadCustomizerType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_CUSTOMIZER_TYPE = fromString("BadCustomizerType");

    /** Static value UnsupportedCustomizerType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode UNSUPPORTED_CUSTOMIZER_TYPE = fromString("UnsupportedCustomizerType");

    /** Static value NoCustomizerScript for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode NO_CUSTOMIZER_SCRIPT = fromString("NoCustomizerScript");

    /** Static value BadValidatorType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_VALIDATOR_TYPE = fromString("BadValidatorType");

    /** Static value UnsupportedValidatorType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode UNSUPPORTED_VALIDATOR_TYPE = fromString("UnsupportedValidatorType");

    /** Static value NoValidatorScript for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode NO_VALIDATOR_SCRIPT = fromString("NoValidatorScript");

    /** Static value BadDistributeType for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_DISTRIBUTE_TYPE = fromString("BadDistributeType");

    /** Static value BadSharedImageDistribute for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_SHARED_IMAGE_DISTRIBUTE = fromString("BadSharedImageDistribute");

    /** Static value BadStagingResourceGroup for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode BAD_STAGING_RESOURCE_GROUP = fromString("BadStagingResourceGroup");

    /** Static value ServerError for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode SERVER_ERROR = fromString("ServerError");

    /** Static value Other for ProvisioningErrorCode. */
    public static final ProvisioningErrorCode OTHER = fromString("Other");

    /**
     * Creates or finds a ProvisioningErrorCode from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ProvisioningErrorCode.
     */
    @JsonCreator
    public static ProvisioningErrorCode fromString(String name) {
        return fromString(name, ProvisioningErrorCode.class);
    }

    /**
     * Gets known ProvisioningErrorCode values.
     *
     * @return known ProvisioningErrorCode values.
     */
    public static Collection<ProvisioningErrorCode> values() {
        return values(ProvisioningErrorCode.class);
    }
}


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

namespace TormentedDemonSimulator
{
	public struct AbilityDamage
	{
		/// <summary>
		/// The minimum damage dealt by this ability.
		/// </summary>
		public float Minimum;

		/// <summary>
		/// The maximum damage dealt by this ability.
		/// </summary>
		public float Maximum;

		/// <summary>
		/// The average damage dealt by this ability.
		/// </summary>
		public float Average
		{
			get { return (Maximum + Minimum) / 2.0f; }
		}
	}
}


text:
import { Component, Input } from '@angular/core';
import { Comment } from 'models';
import { PostService, PostSocketService, MessageParser } from 'services';

@Component({
    templateUrl: 'post-comment.html',
    selector: 'post-comment'
})
export class PostCommentComponent{

    @Input() comment: Comment;

    constructor(
        private postSocket: PostSocketService,
        private postService: PostService,
        private parser: MessageParser
    ) {

    }

    ngOnInit() {
        //console.log(this.comment);
        this.comment.content = this.parser.parse(this.comment);
    }

    like(){
        this.postService.like(this.comment).then((value) => {
            this.comment.liked = true;
        }, (rejected) => {
            this.comment.liked = false;
        })
    }

}


text:
/*
Driver: das16m1
Description: CIO-DAS16/M1
Author: Frank Mori Hess <fmhess@users.sourceforge.net>
Devices: [Measurement Computing] CIO-DAS16/M1 (das16m1)
Status: works

This driver supports a single board - the CIO-DAS16/M1.
As far as I know, there are no other boards that have
the same register layout.  Even the CIO-DAS16/M1/16 is
significantly different.

I was _barely_ able to reach the full 1 MHz capability
of this board, using a hard real-time interrupt
(set the TRIG_RT flag in your struct comedi_cmd and use
rtlinux or RTAI).  The board can't do dma, so the bottleneck is
pulling the data across the ISA bus.  I timed the interrupt
handler, and it took my computer ~470 microseconds to pull 512
samples from the board.  So at 1 Mhz sampling rate,
expect your CPU to be spending almost all of its
time in the interrupt handler.

This board has some unusual restrictions for its channel/gain list.  If the
list has 2 or more channels in it, then two conditions must be satisfied:
(1) - even/odd channels must appear at even/odd indices in the list
(2) - the list must have an even number of entries.

Options:
        [0] - base io address
        [1] - irq (optional, but you probably want it)

irq can be omitted, although the cmd interface will not work without it.
*/

#include <linux/ioport.h>
#include <linux/interrupt.h>
#include "../comedidev.h"

#include "8255.h"
#include "8253.h"
#include "comedi_fc.h"

#define DAS16M1_SIZE 16
#define DAS16M1_SIZE2 8

#define DAS16M1_XTAL 100	/* 10 MHz master clock */

#define FIFO_SIZE 1024		/*  1024 sample fifo */

/*
    CIO-DAS16_M1.pdf

    "cio-das16/m1"

  0	a/d bits 0-3, mux		start 12 bit
  1	a/d bits 4-11		unused
  2	status		control
  3	di 4 bit		do 4 bit
  4	unused			clear interrupt
  5	interrupt, pacer
  6	channel/gain queue address
  7	channel/gain queue data
  89ab	8254
  cdef	8254
  400	8255
  404-407 	8254

*/

#define DAS16M1_AI             0	/*  16-bit wide register */
#define   AI_CHAN(x)             ((x) & 0xf)
#define DAS16M1_CS             2
#define   EXT_TRIG_BIT           0x1
#define   OVRUN                  0x20
#define   IRQDATA                0x80
#define DAS16M1_DIO            3
#define DAS16M1_CLEAR_INTR     4
#define DAS16M1_INTR_CONTROL   5
#define   EXT_PACER              0x2
#define   INT_PACER              0x3
#define   PACER_MASK             0x3
#define   INTE                   0x80
#define DAS16M1_QUEUE_ADDR     6
#define DAS16M1_QUEUE_DATA     7
#define   Q_CHAN(x)              ((x) & 0x7)
#define   Q_RANGE(x)             (((x) & 0xf) << 4)
#define   UNIPOLAR               0x40
#define DAS16M1_8254_FIRST             0x8
#define DAS16M1_8254_FIRST_CNTRL       0xb
#define   TOTAL_CLEAR                    0x30
#define DAS16M1_8254_SECOND            0xc
#define DAS16M1_82C55                  0x400
#define DAS16M1_8254_THIRD             0x404

static const struct comedi_lrange range_das16m1 = { 9,
	{
	 BIP_RANGE(5),
	 BIP_RANGE(2.5),
	 BIP_RANGE(1.25),
	 BIP_RANGE(0.625),
	 UNI_RANGE(10),
	 UNI_RANGE(5),
	 UNI_RANGE(2.5),
	 UNI_RANGE(1.25),
	 BIP_RANGE(10),
	 }
};

struct das16m1_private_struct {
	unsigned int control_state;
	volatile unsigned int adc_count;	/*  number of samples completed */
	/* initial value in lower half of hardware conversion counter,
	 * needed to keep track of whether new count has been loaded into
	 * counter yet (loaded by first sample conversion) */
	u16 initial_hw_count;
	short ai_buffer[FIFO_SIZE];
	unsigned int do_bits;	/*  saves status of digital output bits */
	unsigned int divisor1;	/*  divides master clock to obtain conversion speed */
	unsigned int divisor2;	/*  divides master clock to obtain conversion speed */
	unsigned long extra_iobase;
};

static inline short munge_sample(short data)
{
	return (data >> 4) & 0xfff;
}

static void munge_sample_array(short *array, unsigned int num_elements)
{
	unsigned int i;

	for (i = 0; i < num_elements; i++)
		array[i] = munge_sample(array[i]);
}

static int das16m1_cmd_test(struct comedi_device *dev,
			    struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
	struct das16m1_private_struct *devpriv = dev->private;
	unsigned int err = 0, tmp, i;

	/* Step 1 : check if triggers are trivially valid */

	err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_EXT);
	err |= cfc_check_trigger_src(&cmd->scan_begin_src, TRIG_FOLLOW);
	err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_TIMER | TRIG_EXT);
	err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
	err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);

	if (err)
		return 1;

	/* Step 2a : make sure trigger sources are unique */

	err |= cfc_check_trigger_is_unique(cmd->start_src);
	err |= cfc_check_trigger_is_unique(cmd->convert_src);
	err |= cfc_check_trigger_is_unique(cmd->stop_src);

	/* Step 2b : and mutually compatible */

	if (err)
		return 2;

	/* Step 3: check if arguments are trivially valid */

	err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);

	if (cmd->scan_begin_src == TRIG_FOLLOW)	/* internal trigger */
		err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);

	if (cmd->convert_src == TRIG_TIMER)
		err |= cfc_check_trigger_arg_min(&cmd->convert_arg, 1000);

	err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);

	if (cmd->stop_src == TRIG_COUNT) {
		/* any count is allowed */
	} else {
		/* TRIG_NONE */
		err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
	}

	if (err)
		return 3;

	/* step 4: fix up arguments */

	if (cmd->convert_src == TRIG_TIMER) {
		tmp = cmd->convert_arg;
		/* calculate counter values that give desired timing */
		i8253_cascade_ns_to_timer_2div(DAS16M1_XTAL,
					       &(devpriv->divisor1),
					       &(devpriv->divisor2),
					       &(cmd->convert_arg),
					       cmd->flags & TRIG_ROUND_MASK);
		if (tmp != cmd->convert_arg)
			err++;
	}

	if (err)
		return 4;

	/*  check chanlist against board's peculiarities */
	if (cmd->chanlist && cmd->chanlist_len > 1) {
		for (i = 0; i < cmd->chanlist_len; i++) {
			/*  even/odd channels must go into even/odd queue addresses */
			if ((i % 2) != (CR_CHAN(cmd->chanlist[i]) % 2)) {
				comedi_error(dev, "bad chanlist:\n"
					     " even/odd channels must go have even/odd chanlist indices");
				err++;
			}
		}
		if ((cmd->chanlist_len % 2) != 0) {
			comedi_error(dev,
				     "chanlist must be of even length or length 1");
			err++;
		}
	}

	if (err)
		return 5;

	return 0;
}

/* This function takes a time in nanoseconds and sets the     *
 * 2 pacer clocks to the closest frequency possible. It also  *
 * returns the actual sampling period.                        */
static unsigned int das16m1_set_pacer(struct comedi_device *dev,
				      unsigned int ns, int rounding_flags)
{
	struct das16m1_private_struct *devpriv = dev->private;

	i8253_cascade_ns_to_timer_2div(DAS16M1_XTAL, &(devpriv->divisor1),
				       &(devpriv->divisor2), &ns,
				       rounding_flags & TRIG_ROUND_MASK);

	/* Write the values of ctr1 and ctr2 into counters 1 and 2 */
	i8254_load(dev->iobase + DAS16M1_8254_SECOND, 0, 1, devpriv->divisor1,
		   2);
	i8254_load(dev->iobase + DAS16M1_8254_SECOND, 0, 2, devpriv->divisor2,
		   2);

	return ns;
}

static int das16m1_cmd_exec(struct comedi_device *dev,
			    struct comedi_subdevice *s)
{
	struct das16m1_private_struct *devpriv = dev->private;
	struct comedi_async *async = s->async;
	struct comedi_cmd *cmd = &async->cmd;
	unsigned int byte, i;

	if (dev->irq == 0) {
		comedi_error(dev, "irq required to execute comedi_cmd");
		return -1;
	}

	/* disable interrupts and internal pacer */
	devpriv->control_state &= ~INTE & ~PACER_MASK;
	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);

	/*  set software count */
	devpriv->adc_count = 0;
	/* Initialize lower half of hardware counter, used to determine how
	 * many samples are in fifo.  Value doesn't actually load into counter
	 * until counter's next clock (the next a/d conversion) */
	i8254_load(dev->iobase + DAS16M1_8254_FIRST, 0, 1, 0, 2);
	/* remember current reading of counter so we know when counter has
	 * actually been loaded */
	devpriv->initial_hw_count =
	    i8254_read(dev->iobase + DAS16M1_8254_FIRST, 0, 1);
	/* setup channel/gain queue */
	for (i = 0; i < cmd->chanlist_len; i++) {
		outb(i, dev->iobase + DAS16M1_QUEUE_ADDR);
		byte =
		    Q_CHAN(CR_CHAN(cmd->chanlist[i])) |
		    Q_RANGE(CR_RANGE(cmd->chanlist[i]));
		outb(byte, dev->iobase + DAS16M1_QUEUE_DATA);
	}

	/* set counter mode and counts */
	cmd->convert_arg =
	    das16m1_set_pacer(dev, cmd->convert_arg,
			      cmd->flags & TRIG_ROUND_MASK);

	/*  set control & status register */
	byte = 0;
	/* if we are using external start trigger (also board dislikes having
	 * both start and conversion triggers external simultaneously) */
	if (cmd->start_src == TRIG_EXT && cmd->convert_src != TRIG_EXT)
		byte |= EXT_TRIG_BIT;

	outb(byte, dev->iobase + DAS16M1_CS);
	/* clear interrupt bit */
	outb(0, dev->iobase + DAS16M1_CLEAR_INTR);

	/* enable interrupts and internal pacer */
	devpriv->control_state &= ~PACER_MASK;
	if (cmd->convert_src == TRIG_TIMER)
		devpriv->control_state |= INT_PACER;
	else
		devpriv->control_state |= EXT_PACER;

	devpriv->control_state |= INTE;
	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);

	return 0;
}

static int das16m1_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct das16m1_private_struct *devpriv = dev->private;

	devpriv->control_state &= ~INTE & ~PACER_MASK;
	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);

	return 0;
}

static int das16m1_ai_rinsn(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn, unsigned int *data)
{
	struct das16m1_private_struct *devpriv = dev->private;
	int i, n;
	int byte;
	const int timeout = 1000;

	/* disable interrupts and internal pacer */
	devpriv->control_state &= ~INTE & ~PACER_MASK;
	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);

	/* setup channel/gain queue */
	outb(0, dev->iobase + DAS16M1_QUEUE_ADDR);
	byte =
	    Q_CHAN(CR_CHAN(insn->chanspec)) | Q_RANGE(CR_RANGE(insn->chanspec));
	outb(byte, dev->iobase + DAS16M1_QUEUE_DATA);

	for (n = 0; n < insn->n; n++) {
		/* clear IRQDATA bit */
		outb(0, dev->iobase + DAS16M1_CLEAR_INTR);
		/* trigger conversion */
		outb(0, dev->iobase);

		for (i = 0; i < timeout; i++) {
			if (inb(dev->iobase + DAS16M1_CS) & IRQDATA)
				break;
		}
		if (i == timeout) {
			comedi_error(dev, "timeout");
			return -ETIME;
		}
		data[n] = munge_sample(inw(dev->iobase));
	}

	return n;
}

static int das16m1_di_rbits(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn, unsigned int *data)
{
	unsigned int bits;

	bits = inb(dev->iobase + DAS16M1_DIO) & 0xf;
	data[1] = bits;
	data[0] = 0;

	return insn->n;
}

static int das16m1_do_wbits(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn, unsigned int *data)
{
	struct das16m1_private_struct *devpriv = dev->private;
	unsigned int wbits;

	/*  only set bits that have been masked */
	data[0] &= 0xf;
	wbits = devpriv->do_bits;
	/*  zero bits that have been masked */
	wbits &= ~data[0];
	/*  set masked bits */
	wbits |= data[0] & data[1];
	devpriv->do_bits = wbits;
	data[1] = wbits;

	outb(devpriv->do_bits, dev->iobase + DAS16M1_DIO);

	return insn->n;
}

static void das16m1_handler(struct comedi_device *dev, unsigned int status)
{
	struct das16m1_private_struct *devpriv = dev->private;
	struct comedi_subdevice *s;
	struct comedi_async *async;
	struct comedi_cmd *cmd;
	u16 num_samples;
	u16 hw_counter;

	s = dev->read_subdev;
	async = s->async;
	async->events = 0;
	cmd = &async->cmd;

	/*  figure out how many samples are in fifo */
	hw_counter = i8254_read(dev->iobase + DAS16M1_8254_FIRST, 0, 1);
	/* make sure hardware counter reading is not bogus due to initial value
	 * not having been loaded yet */
	if (devpriv->adc_count == 0 && hw_counter == devpriv->initial_hw_count) {
		num_samples = 0;
	} else {
		/* The calculation of num_samples looks odd, but it uses the following facts.
		 * 16 bit hardware counter is initialized with value of zero (which really
		 * means 0x1000).  The counter decrements by one on each conversion
		 * (when the counter decrements from zero it goes to 0xffff).  num_samples
		 * is a 16 bit variable, so it will roll over in a similar fashion to the
		 * hardware counter.  Work it out, and this is what you get. */
		num_samples = -hw_counter - devpriv->adc_count;
	}
	/*  check if we only need some of the points */
	if (cmd->stop_src == TRIG_COUNT) {
		if (num_samples > cmd->stop_arg * cmd->chanlist_len)
			num_samples = cmd->stop_arg * cmd->chanlist_len;
	}
	/*  make sure we dont try to get too many points if fifo has overrun */
	if (num_samples > FIFO_SIZE)
		num_samples = FIFO_SIZE;
	insw(dev->iobase, devpriv->ai_buffer, num_samples);
	munge_sample_array(devpriv->ai_buffer, num_samples);
	cfc_write_array_to_buffer(s, devpriv->ai_buffer,
				  num_samples * sizeof(short));
	devpriv->adc_count += num_samples;

	if (cmd->stop_src == TRIG_COUNT) {
		if (devpriv->adc_count >= cmd->stop_arg * cmd->chanlist_len) {	/* end of acquisition */
			das16m1_cancel(dev, s);
			async->events |= COMEDI_CB_EOA;
		}
	}

	/* this probably won't catch overruns since the card doesn't generate
	 * overrun interrupts, but we might as well try */
	if (status & OVRUN) {
		das16m1_cancel(dev, s);
		async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
		comedi_error(dev, "fifo overflow");
	}

	comedi_event(dev, s);

}

static int das16m1_poll(struct comedi_device *dev, struct comedi_subdevice *s)
{
	unsigned long flags;
	unsigned int status;

	/*  prevent race with interrupt handler */
	spin_lock_irqsave(&dev->spinlock, flags);
	status = inb(dev->iobase + DAS16M1_CS);
	das16m1_handler(dev, status);
	spin_unlock_irqrestore(&dev->spinlock, flags);

	return s->async->buf_write_count - s->async->buf_read_count;
}

static irqreturn_t das16m1_interrupt(int irq, void *d)
{
	int status;
	struct comedi_device *dev = d;

	if (!dev->attached) {
		comedi_error(dev, "premature interrupt");
		return IRQ_HANDLED;
	}
	/*  prevent race with comedi_poll() */
	spin_lock(&dev->spinlock);

	status = inb(dev->iobase + DAS16M1_CS);

	if ((status & (IRQDATA | OVRUN)) == 0) {
		comedi_error(dev, "spurious interrupt");
		spin_unlock(&dev->spinlock);
		return IRQ_NONE;
	}

	das16m1_handler(dev, status);

	/* clear interrupt */
	outb(0, dev->iobase + DAS16M1_CLEAR_INTR);

	spin_unlock(&dev->spinlock);
	return IRQ_HANDLED;
}

static int das16m1_irq_bits(unsigned int irq)
{
	int ret;

	switch (irq) {
	case 10:
		ret = 0x0;
		break;
	case 11:
		ret = 0x1;
		break;
	case 12:
		ret = 0x2;
		break;
	case 15:
		ret = 0x3;
		break;
	case 2:
		ret = 0x4;
		break;
	case 3:
		ret = 0x5;
		break;
	case 5:
		ret = 0x6;
		break;
	case 7:
		ret = 0x7;
		break;
	default:
		return -1;
		break;
	}
	return ret << 4;
}

/*
 * Options list:
 *   0  I/O base
 *   1  IRQ
 */
static int das16m1_attach(struct comedi_device *dev,
			  struct comedi_devconfig *it)
{
	struct das16m1_private_struct *devpriv;
	struct comedi_subdevice *s;
	int ret;
	unsigned int irq;

	devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
	if (!devpriv)
		return -ENOMEM;
	dev->private = devpriv;

	ret = comedi_request_region(dev, it->options[0], DAS16M1_SIZE);
	if (ret)
		return ret;
	/* Request an additional region for the 8255 */
	ret = __comedi_request_region(dev, dev->iobase + DAS16M1_82C55,
				      DAS16M1_SIZE2);
	if (ret)
		return ret;
	devpriv->extra_iobase = dev->iobase + DAS16M1_82C55;

	/* now for the irq */
	irq = it->options[1];
	/*  make sure it is valid */
	if (das16m1_irq_bits(irq) >= 0) {
		ret = request_irq(irq, das16m1_interrupt, 0,
				  dev->driver->driver_name, dev);
		if (ret < 0)
			return ret;
		dev->irq = irq;
		printk
		    ("irq %u\n", irq);
	} else if (irq == 0) {
		printk
		    (", no irq\n");
	} else {
		comedi_error(dev, "invalid irq\n"
			     " valid irqs are 2, 3, 5, 7, 10, 11, 12, or 15\n");
		return -EINVAL;
	}

	ret = comedi_alloc_subdevices(dev, 4);
	if (ret)
		return ret;

	s = &dev->subdevices[0];
	dev->read_subdev = s;
	/* ai */
	s->type = COMEDI_SUBD_AI;
	s->subdev_flags = SDF_READABLE | SDF_CMD_READ;
	s->n_chan = 8;
	s->subdev_flags = SDF_DIFF;
	s->len_chanlist = 256;
	s->maxdata = (1 << 12) - 1;
	s->range_table = &range_das16m1;
	s->insn_read = das16m1_ai_rinsn;
	s->do_cmdtest = das16m1_cmd_test;
	s->do_cmd = das16m1_cmd_exec;
	s->cancel = das16m1_cancel;
	s->poll = das16m1_poll;

	s = &dev->subdevices[1];
	/* di */
	s->type = COMEDI_SUBD_DI;
	s->subdev_flags = SDF_READABLE;
	s->n_chan = 4;
	s->maxdata = 1;
	s->range_table = &range_digital;
	s->insn_bits = das16m1_di_rbits;

	s = &dev->subdevices[2];
	/* do */
	s->type = COMEDI_SUBD_DO;
	s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
	s->n_chan = 4;
	s->maxdata = 1;
	s->range_table = &range_digital;
	s->insn_bits = das16m1_do_wbits;

	s = &dev->subdevices[3];
	/* 8255 */
	ret = subdev_8255_init(dev, s, NULL, devpriv->extra_iobase);
	if (ret)
		return ret;

	/*  disable upper half of hardware conversion counter so it doesn't mess with us */
	outb(TOTAL_CLEAR, dev->iobase + DAS16M1_8254_FIRST_CNTRL);

	/*  initialize digital output lines */
	outb(devpriv->do_bits, dev->iobase + DAS16M1_DIO);

	/* set the interrupt level */
	if (dev->irq)
		devpriv->control_state = das16m1_irq_bits(dev->irq);
	else
		devpriv->control_state = 0;
	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);

	return 0;
}

static void das16m1_detach(struct comedi_device *dev)
{
	struct das16m1_private_struct *devpriv = dev->private;

	comedi_spriv_free(dev, 3);
	if (devpriv && devpriv->extra_iobase)
		release_region(devpriv->extra_iobase, DAS16M1_SIZE2);
	comedi_legacy_detach(dev);
}

static struct comedi_driver das16m1_driver = {
	.driver_name	= "das16m1",
	.module		= THIS_MODULE,
	.attach		= das16m1_attach,
	.detach		= das16m1_detach,
};
module_comedi_driver(das16m1_driver);

MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");


text:
user: wyattlyonpreul
name: Wyatt Lyon Preul
topicEN: Containerized Node.js Microservices on Autopilot
topicCN: 利用 Autopilot 容器化 Node.js 微服务
company: Joyent
link:  https://github.com/geek
featured: true
type: presentspeaker
---


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using Moq;
using NUnit.Framework;

namespace Its.Log.Instrumentation.UnitTests
{
    [TestFixture]
    public class AsyncTests
    {
        [TearDown]
        public void TearDown()
        {
            Log.UnsubscribeAllFromEntryPosted();
        }

        [Test]
        public void LogActivity_Trace_captures_current_method_name()
        {
            var observer = new Mock<IObserver<LogEntry>>();
            observer.Setup(o => o.OnNext(
                It.Is<LogEntry>(
                    e => e.CallingMethod.Contains("BeginSomething"))));
            observer.Setup(o => o.OnNext(
                It.Is<LogEntry>(
                    e => e.CallingMethod.Contains("EndSomething"))));

            var helper = new AsyncTestHelper();

            using (var activity = Log.Enter(() => { }))
            using (TestHelper.LogToConsole())
            using (observer.Object.SubscribeToLogEvents())
            {
                var result = helper.BeginSomething(
                    _ => activity.Complete(() => { }),
                    activity);
                helper.EndSomething(result);
            }

            observer.VerifyAll();
        }

        [Test]
        public void LogActivity_Complete_writes_current_method_name()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            var observer = new Mock<IObserver<LogEntry>>();
            observer
                .Setup(
                    o => o.OnNext(
                        It.Is<LogEntry>(
                            e => e.CallingMethod == methodName &&
                                 e.EventType == TraceEventType.Stop)));

            var helper = new AsyncTestHelper();

            using (var activity = Log.Enter(() => { }))
            using (TestHelper.LogToConsole())
            using (observer.Object.SubscribeToLogEvents())
            {
                var result = helper.BeginSomething(
                    _ => activity.Complete(() => { }),
                    activity);
                helper.EndSomething(result);
            }

            observer.VerifyAll();
        }
    }

    public class AsyncTestHelper
    {
        public IAsyncResult BeginSomething(AsyncCallback callback, object state)
        {
            if (state != null)
            {
                var activity = state as ILogActivity;
                if (activity != null)
                {
                    activity.Trace(() => "hello");
                }
            }

            return new AsyncResult
                       {
                           AsyncState = new Tuple<AsyncCallback, ILogActivity>(callback, state as ILogActivity)
                       };
        }

        public void EndSomething(IAsyncResult result)
        {
            var state = result.AsyncState as Tuple<AsyncCallback, ILogActivity>;
            if (state != null)
            {
                if (state.Item2 != null)
                {
                    state.Item2.Trace(() => "hello");
                }
                if (state.Item1 != null)
                {
                    state.Item1.Invoke(result);
                }
            }
        }

        private class AsyncResult : IAsyncResult
        {
            public bool IsCompleted { get; set; }
            public WaitHandle AsyncWaitHandle { get; private set; }
            public object AsyncState { get; set; }
            public bool CompletedSynchronously { get; private set; }
        }
    }
}


text:
<?php

namespace Vandpibe\Form\Extension;

use Symfony\Component\Form\FormBuilderInterface;
use Vandpibe\Form\DataTransformer\NullToDateTimeTransformer;

/**
 * @author Henrik Bjornskov <henrik@bjrnskov.dk>
 */
class DateTypeExtension extends \Symfony\Component\Form\AbstractTypeExtension
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new NullToDateTimeTransformer());
    }

    /**
     * @return string
     */
    public function getExtendedType()
    {
        return 'date';
    }
}


text:
package uk.co.wumpus.tinker.builder.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.annotation.Nullable;

public final class StreamUtils {

	private StreamUtils() {
		/* hidden */
	}

	@Nullable
	public static String getStream(@Nullable final InputStream s) throws IOException {
		if (s == null) {
			return null;
		}
		byte[] stdIn = new byte[s.available()];
		s.read(stdIn);
		//TODO check output of read
		return new String(stdIn, Charset.defaultCharset());
	}
}


text:
using namespace std;

#pragma mark - Solve to Get Expression

SolvingResult solveLineWithTwoPoints(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) Q(x2, y2) Ax + By + C = 0
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        RCPoint Q{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3])};

        if (P.x == Q.x && P.y == Q.y) {
            return SolvingResultErrorCannotSolve;
        }
        else {
            Line line = lineWithTwoPoints(P, Q);
            stringstream ss;

            if (line.A != 0)
                ss << (line.A == 1 ? "" : (latex ? line.A.stringLatexValue() : line.A.stringValue())) << "x";
            if (line.B != 0)
                ss << (line.B > 0 ? "+" : "") << (line.B == 1 ? "" : (latex ? line.B.stringLatexValue() : line.B.stringValue())) << "y";
            if (line.C != 0)
                ss << (line.C > 0 ? "+" : "") << (latex ? line.C.stringLatexValue() : line.C.stringValue());
            ss << "=0.";

            string str = ss.str();
            if (str[0] == '+')
                str = str.substr(1, str.size()-1);

            outputStr = str;
        }
    }

    return SolvingResultSuccess;
}

SolvingResult solveCircleWithThreePoints(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) Q(x2, y2) M(x3, y3) x^2 + y^2 + Dx + Ey + F = 0
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        RCPoint Q{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3])};
        RCPoint M{fractionFromString(inputStrs[4]), fractionFromString(inputStrs[5])};

        Line linePQ = lineWithTwoPoints(P, Q);
        if (pointIsOnLine(M, linePQ)) {
            return SolvingResultErrorCannotSolve;
        }
        else {
            Circle circle = circleWithThreePoints(P, Q, M);
            stringstream ss;

            ss << "x^2+y^2";
            if (circle.D != 0)
                ss << (circle.D > 0 ? "+" : "") << (circle.D == 1 ? "" : (latex ? circle.D.stringLatexValue() : circle.D.stringValue())) << "x";
            if (circle.E != 0)
                ss << (circle.E > 0 ? "+" : "") << (circle.E == 1 ? "" : (latex ? circle.E.stringLatexValue() : circle.E.stringValue())) << "y";
            if (circle.F != 0)
                ss << (circle.F > 0 ? "+" : "") << (latex ? circle.F.stringLatexValue() : circle.F.stringValue());
            ss << "=0.";

            outputStr = ss.str();
        }
    }

    return SolvingResultSuccess;
}

SolvingResult solveEllipseWithTwoPoints(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) Q(x2, y2) mx^2 + ny^2 = 1
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        RCPoint Q{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3])};

        RationalNumber det = P.x.xSquared() * Q.y.xSquared() - Q.x.xSquared() * P.y.xSquared();
        if (det == 0) {
            return SolvingResultErrorCannotSolve;
        }
        else {
            Ellipse ellipse = ellipseWithTwoPoints(P, Q);
            stringstream ss;

            if (ellipse.m == 0 || ellipse.n == 0) {
                return SolvingResultErrorCannotSolve;
            }

            ss << (ellipse.m == 1 ? "" : (latex ? ellipse.m.stringLatexValue() : ellipse.m.stringValue())) << "x^2";
            ss << (ellipse.n > 0 ? "+" : "") << (ellipse.n == 1 ? "" : (latex ? ellipse.n.stringLatexValue() : ellipse.n.stringValue())) << "y^2";
            ss << "=1.";

            string str = ss.str();
            if (str[0] == '+')
                str = str.substr(1, str.size()-1);

            outputStr = str;
        }
    }

    return SolvingResultSuccess;
}

SolvingResult solveQuadraticFunctionWithThreePoints(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) Q(x2, y2) M(x3, y3) y = ax^2 + bx + c
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        RCPoint Q{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3])};
        RCPoint M{fractionFromString(inputStrs[4]), fractionFromString(inputStrs[5])};

        Line linePQ = lineWithTwoPoints(P, Q);
        if (pointIsOnLine(M, linePQ)) {
            return SolvingResultErrorCannotSolve;
        }
        else {
            QuadraticFunction qfunc = quadraticFunctionWithThreePoints(P, Q, M);
            stringstream ss;

            ss << "y=";
            // Excluded the situation where a = 0 above, so no need to check it
            ss << (qfunc.a == 1 ? "" : (latex ? qfunc.a.stringLatexValue() : qfunc.a.stringValue())) << "x^2";
            if (qfunc.b != 0)
                ss << (qfunc.b > 0 ? "+" : "") << (qfunc.b == 1 ? "" : (latex ? qfunc.b.stringLatexValue() : qfunc.b.stringValue())) << "x";
            if (qfunc.c != 0)
                ss << (qfunc.c > 0 ? "+" : "") << (qfunc.c == 1 ? "" : (latex ? qfunc.c.stringLatexValue() : qfunc.c.stringValue()));

            ss << ".";

            outputStr = ss.str();
        }
    }

    return SolvingResultSuccess;
}

#pragma mark - Solve to Get Distance
SolvingResult solveDistanceBetweenTwoPoints(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) Q(x2, y2)
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        RCPoint Q{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3])};

        QuadraticIrrational dist = distanceBetweenTwoPoints(P, Q);
        stringstream ss;

        ss << "d=" << (latex ? dist.stringLatexValue() : dist.stringValue());
        if (!isInt(dist.doubleValue())) {
            ss << "≈" << setiosflags(ios::fixed) << setprecision(6) << dist.doubleValue();
        }
        ss << ".";

        outputStr = ss.str();
    }

    return SolvingResultSuccess;
}

SolvingResult solveDistanceBetweenPointAndLine(std::vector<std::string> &inputStrs, std::string &outputStr, bool latex) {
    removeBlanksFrom(inputStrs);

    if (!inputIsComplete((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersIncomplete;
    }
    else if (!inputIsValid((const vector<string>)inputStrs)) {
        return SolvingResultErrorParametersInvalid;
    }
    else {
        // P(x1, y1) L: Ax + By + C = 0
        RCPoint P{fractionFromString(inputStrs[0]), fractionFromString(inputStrs[1])};
        Line line{fractionFromString(inputStrs[2]), fractionFromString(inputStrs[3]), fractionFromString(inputStrs[4])};

        if (line.A == 0 && line.B == 0) {
            return SolvingResultErrorCannotSolve;
        }
        else {
            QuadraticIrrational dist = distanceBetweenPointAndLine(P, line);
            stringstream ss;

            ss << "d=" << (latex ? dist.stringLatexValue() : dist.stringValue());
            if (!isInt(dist.doubleValue())) {
                ss << "≈" << setiosflags(ios::fixed) << setprecision(6) << dist.doubleValue();
            }
            ss << ".";

            outputStr = ss.str();
        }
    }

    return SolvingResultSuccess;
}


text:
#include "tensorflow/compiler/xla/service/cpu/cpu_layout_assignment.h"

#include <numeric>

#include "absl/container/flat_hash_map.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/service/cpu/dot_op_emitter.h"
#include "tensorflow/compiler/xla/service/cpu/ir_emission_utils.h"
#include "tensorflow/tsl/platform/errors.h"

namespace xla {
namespace cpu {

// We want to change the layout of constant arrays to be column major when all
// of their users are dot operations that can be made faster with the flipped
// layout.  To avoid going quadratic over the # of instructions, we cache this
// property in should_make_rhs_col_major -- it maps a constant to true if all of
// the users of said constant are dot operations that can be sped up.  This
// cache is populated lazily as we encounter dot operations traversing the
// instruction stream.

namespace {
using std::nullopt;
using std::optional;

using ShouldMakeOperandColMajorCache =
    absl::flat_hash_map<const HloInstruction*, bool>;
}  // namespace

static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) {
  for (auto* user : instruction->users()) {
    optional<int64_t> operand_idx =
        ProfitableToMakeDotOperandColumnMajor(*user);
    if (!operand_idx || user->operand(*operand_idx) != instruction ||
        absl::c_count(user->operands(), instruction) != 1) {
      return false;
    }
  }
  return true;
}

static optional<int64_t> ShouldMakeOperandColumnMajor(
    ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) {
  optional<int64_t> operand_idx =
      ProfitableToMakeDotOperandColumnMajor(instruction);
  if (!operand_idx) {
    return nullopt;
  }

  const HloInstruction* operand = instruction.operand(*operand_idx);
  if (operand->opcode() != HloOpcode::kConstant) {
    return nullopt;
  }

  auto it = cache->find(operand);
  if (it == cache->end()) {
    auto insert_result =
        cache->insert({operand, ShouldMakeAllUsersColMajor(operand)});
    CHECK(insert_result.second);
    it = insert_result.first;
  }

  return it->second ? operand_idx : nullopt;
}

static Shape RowMajorShape(const Shape& old_shape) {
  Shape new_shape(old_shape);
  std::vector<int64_t> dimension_order(new_shape.dimensions_size());
  std::iota(dimension_order.rbegin(), dimension_order.rend(), 0);
  *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order);
  return new_shape;
}

static Shape ColMajorShape(const Shape& old_shape) {
  Shape new_shape(old_shape);
  std::vector<int64_t> dimension_order(new_shape.dimensions_size());
  std::iota(dimension_order.begin(), dimension_order.end(), 0);
  *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order);
  return new_shape;
}

static bool OperandsAndResultMustHaveRowMajorLayout(
    const HloInstruction& instr,
    const TargetMachineFeatures& target_machine_features) {
  if (instr.opcode() == HloOpcode::kConvolution) {
    return PotentiallyImplementedAsEigenConvolution(instr,
                                                    target_machine_features);
  } else if (instr.opcode() == HloOpcode::kDot) {
    return DotOperandsAndResultMustHaveRowMajorLayout(instr,
                                                      target_machine_features);
  }
  return false;
}

Status CpuLayoutAssignment::AddBackendConstraints(
    LayoutConstraints* constraints) {
  ShouldMakeOperandColMajorCache cache;

  const HloComputation* computation = constraints->computation();
  for (auto* instruction : computation->instructions()) {
    if (OperandsAndResultMustHaveRowMajorLayout(*instruction,
                                                target_machine_features_)) {
      TF_RETURN_IF_ERROR(SetInstructionLayout(
          RowMajorShape(instruction->shape()), instruction));
      for (int i = 0; i < instruction->operand_count(); i++) {
        TF_RETURN_IF_ERROR(SetOperandLayout(
            RowMajorShape(instruction->operand(i)->shape()), instruction, i));
      }
    } else if (optional<int64_t> op_idx =
                   ShouldMakeOperandColumnMajor(&cache, *instruction)) {
      const HloInstruction* op = instruction->operand(*op_idx);
      TF_RETURN_IF_ERROR(
          SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx));
    } else {
      for (int64_t operand_no = 0; operand_no < instruction->operand_count();
           ++operand_no) {
        // Skip operands which already have a constraint.
        if (constraints->OperandLayout(instruction, operand_no) != nullptr) {
          continue;
        }
        // Skip over forwarded operands.
        if (AnyOperandBufferForwarded(instruction, operand_no)) {
          continue;
        }
        // Skip operands with non-array shapes.
        if (!instruction->operand(operand_no)->shape().IsArray()) {
          continue;
        }
        Shape operand_shape(
            RowMajorShape(instruction->operand(operand_no)->shape()));
        TF_RETURN_IF_ERROR(
            SetOperandLayout(operand_shape, instruction, operand_no));
      }
      // Skip over the root instruction for the top-level computation.
      if (computation->parent()->entry_computation() == computation &&
          computation->root_instruction() == instruction) {
        continue;
      }
      // Skip instructions which don't produce array shapes (tuples, opaque,
      // etc.).
      if (!instruction->shape().IsArray()) {
        continue;
      }
    }
  }
  return OkStatus();
}
}  // namespace cpu
}  // namespace xla


text:
package com.backend.models;

import java.util.ArrayList;
import java.util.Locale;

import org.apache.commons.lang.Validate;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.backend.models.GameEvent.GameEvent;
import com.backend.models.GameEvent.MisconductPenaltyEvent;
import com.backend.models.GameEvent.PointModifierEvent;
import com.backend.models.GameEvent.SchoolPenaltyEvent;
import com.backend.models.GameEvent.SchoolPenaltyPercentageEvent;
import com.backend.models.GameEvent.StartGameEvent;
import com.backend.models.enums.Division;
import com.backend.models.enums.GameTypeEnum;
import com.backend.models.enums.TeamEnum;
import com.framework.helpers.LocalizedString;

public class ScoreTests
{
	@BeforeClass
	public static void setUp()
    {
    }

	@AfterClass
	public static void tearDown()
	{
	}

	private ArrayList<GameEvent> getGameEvents()
	{
		ArrayList<GameEvent> gameEvents = new ArrayList<GameEvent>();
		gameEvents.add(new StartGameEvent(DateTime.now()));

		gameEvents.add(new PointModifierEvent(TeamEnum.BLUE, 100, new LocalizedString(Locale.ENGLISH, "fake game", "Game truquée"), DateTime.now()));

		return gameEvents;
	}

	@Test
	public void testPenaltyPercentage()
	{
		School school = new School(new ObjectId("545b6ccf92fc2aed1f73a57b"), "21 Jump Street");

		ArrayList<School> blueTeam = new ArrayList<School>();
		blueTeam.add(school);

		Game game = new Game(null, 1, "", DateTime.now(), GameTypeEnum.PRELIMINARY, blueTeam, new ArrayList<School>(), getGameEvents(), false);
		Tournament tournament = new Tournament(new ArrayList<School>(), new ArrayList<Game>());
		tournament.schools.add(school);
		tournament.games.add(game);

		Validate.isTrue(game.getScore(school) == 100);

		SchoolPenaltyPercentageEvent penalty = new SchoolPenaltyPercentageEvent(school, 0.04f, DateTime.now());
		game.addGameEvent(new StartGameEvent(DateTime.now()));
		game.addGameEvent(penalty);
		Validate.isTrue(game.getScore(school) == 96);
	}

	@Test
	public void testGetScore()
	{
		School school = new School(new ObjectId("545b6ccf92fc2aed1f73a57b"), "21 Jump Street");

		ArrayList<School> blueTeam = new ArrayList<School>();
		blueTeam.add(school);

		Game game = new Game(null, 1, "", DateTime.now(), GameTypeEnum.PRELIMINARY, blueTeam, new ArrayList<School>(), getGameEvents(), false);
		Tournament tournament = new Tournament(new ArrayList<School>(), new ArrayList<Game>());
		tournament.schools.add(school);
		tournament.games.add(game);

		Validate.isTrue(game.getScore(school) == 100);

		SchoolPenaltyEvent penalty = new SchoolPenaltyEvent(school, 10, DateTime.now());
		game.addGameEvent(new StartGameEvent(DateTime.now()));
		game.addGameEvent(penalty);
		Validate.isTrue(game.getScore(school) == 90);

		// Not 3 games yet.
		Validate.isTrue(tournament.getRoundScoreNoCache(school, GameTypeEnum.PRELIMINARY) == 0);

		ArrayList<GameEvent> game2Events = getGameEvents();
		game2Events.add(new PointModifierEvent(TeamEnum.BLUE, -20, null, DateTime.now()));
		Game game2 = new Game(null, 2, "", DateTime.now(), GameTypeEnum.PRELIMINARY, blueTeam, new ArrayList<School>(), game2Events, false);
		Validate.isTrue(game2.getScore(school) == 80);
		tournament.games.add(game2);

		ArrayList<GameEvent> game3Events = new ArrayList<GameEvent>();
		game3Events.add(new StartGameEvent(DateTime.now()));
		game3Events.add(new PointModifierEvent(TeamEnum.YELLOW, 40, null, DateTime.now()));
		ArrayList<School> yellowTeam = new ArrayList<School>();
		yellowTeam.add(school);

		Game game3 = new Game(null, 3, "", DateTime.now(), GameTypeEnum.PRELIMINARY, new ArrayList<School>(), yellowTeam, game3Events, false);

		tournament.games.add(game3);
		Validate.isTrue(game3.getScore(school) == 40);
		Validate.isTrue(game3.getScore(new School(null, null)) == 0);

		// Best score is 90
		Validate.isTrue(tournament.getRoundScoreNoCache(school, GameTypeEnum.PRELIMINARY) == 90);

		// Bad kids. A misconduct penalty!
		game3Events.add(new MisconductPenaltyEvent(school, DateTime.now()));
		Validate.isTrue(tournament.getRoundScoreNoCache(school, GameTypeEnum.PRELIMINARY) == 0);

		ArrayList<GameEvent> game4Events = new ArrayList<GameEvent>();
		game4Events.add(new StartGameEvent(DateTime.now()));
		game4Events.add(new PointModifierEvent(TeamEnum.YELLOW, 120, null, DateTime.now()));
		yellowTeam = new ArrayList<School>();
		yellowTeam.add(school);

		Game game4 = new Game(null, 4, "", DateTime.now(), GameTypeEnum.PRELIMINARY, new ArrayList<School>(), yellowTeam, game4Events, false);
		tournament.games.add(game4);
		Validate.isTrue(tournament.getRoundScoreNoCache(school, GameTypeEnum.PRELIMINARY) == 120);

		ArrayList<GameEvent> game5Events = new ArrayList<GameEvent>();
		game5Events.add(new StartGameEvent(DateTime.now()));
		game5Events.add(new PointModifierEvent(TeamEnum.YELLOW, 30, null, DateTime.now()));
		yellowTeam = new ArrayList<School>();
		yellowTeam.add(school);

		Game game5 = new Game(null, 5, "", DateTime.now(), GameTypeEnum.PRELIMINARY, new ArrayList<School>(), yellowTeam, game5Events, false);
		tournament.games.add(game5);
		// 3 "best games" are 0 (misconduct penalty), 120, 90
		Validate.isTrue(tournament.getRoundScoreNoCache(school, GameTypeEnum.PRELIMINARY) == 210);
	}

	@Test
	// Make sure we account for all games.
	public void testGetScorePlayoff()
	{
		testGetScorePlayoff(GameTypeEnum.PLAYOFF_REPECHAGE);
		testGetScorePlayoff(GameTypeEnum.PLAYOFF_QUARTER);
		testGetScorePlayoff(GameTypeEnum.PLAYOFF_DEMI);
		testGetScorePlayoff(GameTypeEnum.PLAYOFF_FINAL);
	}

	private void testGetScorePlayoff(GameTypeEnum gameType)
	{
	School school = new School(new ObjectId("545b6ccf92fc2aed1f73a57b"), "21 Jump Street");

		ArrayList<School> blueTeam = new ArrayList<School>();
		blueTeam.add(school);

		Game game = new Game(null, 1, "", DateTime.now(), gameType, blueTeam, new ArrayList<School>(), getGameEvents(), false);
		Tournament tournament = new Tournament(new ArrayList<School>(), new ArrayList<Game>());
		tournament.schools.add(school);
		tournament.games.add(game);

		Validate.isTrue(game.getScore(school) == 100);
		Validate.isTrue(tournament.getRoundScoreNoCache(school, gameType) == 100);

		ArrayList<GameEvent> game2Events = getGameEvents();
		game2Events.add(new PointModifierEvent(TeamEnum.BLUE, -20, null, DateTime.now()));
		Game game2 = new Game(null, 2, "", DateTime.now(), gameType, blueTeam, new ArrayList<School>(), game2Events, false);
		Validate.isTrue(game2.getScore(school) == 80);
		tournament.games.add(game2);
		Validate.isTrue(tournament.getRoundScoreNoCache(school, gameType) == 180);

		ArrayList<GameEvent> game3Events = new ArrayList<GameEvent>();
		game3Events.add(new StartGameEvent(DateTime.now()));
		game3Events.add(new PointModifierEvent(TeamEnum.YELLOW, 40, null, DateTime.now()));
		ArrayList<School> yellowTeam = new ArrayList<School>();
		yellowTeam.add(school);

		Game game3 = new Game(null, 3, "", DateTime.now(), gameType, new ArrayList<School>(), yellowTeam, game3Events, false);
		tournament.games.add(game3);
		Validate.isTrue(tournament.getRoundScoreNoCache(school, gameType) == 220);
	}
}


text:
#ifndef __SYSLANDSCAPE_LOG_CONVERSIONNAME_HPP
#define __SYSLANDSCAPE_LOG_CONVERSIONNAME_HPP

#include <syslandscape/log/Conversion.hpp>

namespace syslandscape::log {

/**
 * Conversion specifier for logger name.
 *
 * @see Pattern
 * @see Conversion
 */
class ConversionName : public Conversion {
 public:
  ConversionName();

  virtual ~ConversionName();

  virtual std::string getName() const override;

  bool setParameters(const std::vector<std::string>&) noexcept override;

  virtual void format(const ConversionContext&) const noexcept override;
};

} /* namespace syslandscape::log */

#endif /* __SYSLANDSCAPE_LOG_CONVERSIONNAME_HPP */


text:
A Nagios check plugin for connected/disconnected OSSEC agents

## Special Considerations On OSSEC Server:
* /etc/ossec-init.conf needs to be chgrp'ed to nagios and needs to be
  group readable
* nagios user must have password-less sudo to /opt/ossec/bin/list_agents
  or wherever OSSEC is installed

Beyond that it's a standard Nagios check plugin. It should work on any Nagios install but it's only been tested on v3.


text:
class Search_Poi
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paperclip

  field :email, type: String
  field :name, type: String
  field :poi_type, type: String

  field :postcode, type: Integer
  field :city, type: String
  field :country, type: String

end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using System.Web.Compilation;
using Orchard.FileSystems.VirtualPath;
using Orchard.Logging;
using Orchard.Exceptions;

namespace Orchard.Environment {
    public interface IViewsBackgroundCompilation {
        void Start();
        void Stop();
    }

    public class ViewsBackgroundCompilation : IViewsBackgroundCompilation {
        private readonly IVirtualPathProvider _virtualPathProvider;
        private volatile bool _stopping;

        public ViewsBackgroundCompilation(IVirtualPathProvider virtualPathProvider) {
            _virtualPathProvider = virtualPathProvider;

            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public void Start() {
            _stopping = false;
            var timer = new Timer();
            timer.Elapsed += CompileViews;
            timer.Interval = TimeSpan.FromMilliseconds(1500).TotalMilliseconds;
            timer.AutoReset = false;
            timer.Start();
        }

        public void Stop() {
            _stopping = true;
        }

        public class CompilationContext {
            public IEnumerable<string> DirectoriesToBrowse { get; set; }
            public IEnumerable<string> FileExtensionsToCompile { get; set; }
            public HashSet<string> ProcessedDirectories { get; set; }
        }

        private void CompileViews(object sender, ElapsedEventArgs elapsedEventArgs) {
            var totalTime = new Stopwatch();
            totalTime.Start();
            Logger.Information("Starting background compilation of views");
            ((Timer)sender).Stop();

            // Hard-coded context based on current orchard profile
            var context = new CompilationContext {
                // Put most frequently used directories first in the list
                DirectoriesToBrowse = new[] {
                    // Setup
                    "~/Modules/Orchard.Setup/Views",
                    "~/Themes/SafeMode/Views",

                    // Common
                    "~/Core/Contents/Views",
                    "~/Core/Common/Views",
                    "~/Core/Settings/Views",

                    // Dashboard
                    "~/Core/Dashboard/Views",
                    "~/Themes/TheAdmin/Views",

                    // Content Items
                    "~/Modules/Orchard.PublishLater/Views",

                    // Content Types
                    "~/Modules/Orchard.ContentTypes/Views",

                    // "Edit" homepage
                    "~/Modules/TinyMce/Views",
                    "~/Modules/Orchard.Tags/Views",
                    "~/Core/Navigation/Views",

                    // Various other admin pages
                    "~/Core/Settings/Views",
                    "~/Core/Containers/Views",
                    "~/Modules/Orchard.Widgets/Views",
                    "~/Modules/Orchard.Users/Views",
                    "~/Modules/Orchard.MediaLibrary/Views",
                    "~/Modules/Orchard.Comments/Views",

                    // Leave these at end (as a best effort)
                    "~/Core", "~/Modules", "~/Themes"
                },
                FileExtensionsToCompile = new[] { ".cshtml" },
                ProcessedDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
            };

            var directories = context
                .DirectoriesToBrowse
                .SelectMany(folder => GetViewDirectories(folder, context.FileExtensionsToCompile));

            int directoryCount = 0;
            foreach (var viewDirectory in directories) {
                if (_stopping) {
                    if (Logger.IsEnabled(LogLevel.Information)) {
                        var leftOvers = directories.Except(context.ProcessedDirectories).ToList();
                        Logger.Information("Background compilation stopped before all directories were processed ({0} directories left)", leftOvers.Count);
                        foreach (var directory in leftOvers) {
                            Logger.Information("Directory not processed: '{0}'", directory);
                        }
                    }
                    break;
                }

                CompileDirectory(context, viewDirectory);
                directoryCount++;
            }

            totalTime.Stop();
            Logger.Information("Ending background compilation of views, {0} directories processed in {1} sec", directoryCount, totalTime.Elapsed.TotalSeconds);
        }

        private void CompileDirectory(CompilationContext context, string viewDirectory) {
            // Prevent processing of the same directories multiple times (sligh performance optimization,
            // as the build manager second call to compile a view is essentially a "no-op".
            if (context.ProcessedDirectories.Contains(viewDirectory))
                return;
            context.ProcessedDirectories.Add(viewDirectory);

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try {
                var firstFile = _virtualPathProvider
                    .ListFiles(viewDirectory)
                    .Where(f => context.FileExtensionsToCompile.Any(e => f.EndsWith(e, StringComparison.OrdinalIgnoreCase)))
                    .FirstOrDefault();

                if (firstFile != null)
                    BuildManager.GetCompiledAssembly(firstFile);
            }
            catch(Exception ex) {
                if (ex.IsFatal()) {
                    throw;
                }
                // Some views might not compile, this is ok and harmless in this
                // context of pre-compiling views.
                Logger.Information(ex, "Compilation of directory '{0}' skipped", viewDirectory);
            }
            stopwatch.Stop();
            Logger.Information("Directory '{0}' compiled in {1} msec", viewDirectory, stopwatch.ElapsedMilliseconds);
        }

        private IEnumerable<string> GetViewDirectories(string directory, IEnumerable<string> extensions) {
            var result = new List<string>();
            GetViewDirectories(_virtualPathProvider, directory, extensions, result);
            return result;
        }

        private static void GetViewDirectories(IVirtualPathProvider vpp, string directory, IEnumerable<string> extensions, ICollection<string> files) {
            if (vpp.ListFiles(directory).Where(f => extensions.Any(e => f.EndsWith(e, StringComparison.OrdinalIgnoreCase))).Any()) {
                files.Add(directory);
            }

            foreach (var childDirectory in vpp.ListDirectories(directory).OrderBy(d => d, StringComparer.OrdinalIgnoreCase)) {
                GetViewDirectories(vpp, childDirectory, extensions, files);
            }
        }
    }
}