text:
'use strict';

// Compensationforms controller
angular.module('compensationforms').controller('CompensationformsController', ['$scope', '$stateParams', '$location', '$http', 'Authentication', 'Compensationforms',
	function($scope, $stateParams, $location, $http, Authentication, Compensationforms) {

        $scope.compensationFormId = '';
        $scope.continue = false;

		// Create new Compensationform
		$scope.create = function() {
			// Create new Compensationform object
			var compensationform = new Compensationforms ({
				firstName: this.firstName,
                lastName: this.lastName,
                institution: this.institution,
                address: this.address,
                city: this.city,
                province: this.province,
                postalCode:this.postalCode
			});

			// Redirect after save
			compensationform.$save(function(response) {
                $scope.compensationFormId = response._id;

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Compensationform
		$scope.remove = function(compensationform) {
			if ( compensationform ) {
				compensationform.$remove();

				for (var i in $scope.compensationforms) {
					if ($scope.compensationforms [i] === compensationform) {
						$scope.compensationforms.splice(i, 1);
					}
				}
			} else {
				$scope.compensationform.$remove(function() {
					$location.path('compensationforms');
				});
			}
		};

		// Update existing Compensationform
		$scope.update = function() {
			var compensationform = $scope.compensationform;

			compensationform.$update(function() {
				$location.path('compensationforms/' + compensationform._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Compensationforms
		$scope.find = function() {
			$scope.compensationforms = Compensationforms.query();
		};

		// Find existing Compensationform
		$scope.findOne = function() {
			$scope.compensationform = Compensationforms.get({
				compensationformId: $stateParams.compensationformId
			});
		};

        $scope.continueToCrf = function(){

            $scope.page.title = '';
            $scope.continue = true;

        };

        $scope.registerUser = function() {

            $scope.credentials.compensationForm = $scope.compensationFormId;
            $http.post('/auth/signup', $scope.credentials).success(function(response) {
                // If successful we assign the response to the global user model
                $scope.authentication.user = response;
                $location.path('fentoracrf');

            }).error(function(response) {
                $scope.error = response.message;
            });

        };
	}
]);


text:
category: systemHeader
type2: category
position: header
outputType: basic
---
{% include _extension/helper/_extension.inc %}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/theme_color_accent">
    <item>
        <selector>
            <!--<item-->
                <!--android:drawable="@android:color/white"-->
                <!--android:state_pressed="true"/>-->
            <item android:drawable="@color/default_base_bg_dark2"/>
        </selector>
    </item>

</ripple>


text:
class Sys::Group
  include SS::Model::Group
  include Sys::Permission
  include Contact::Addon::Group

  set_permission_name "sys_users", :edit

  attr_accessor :sys_role_ids
  permit_params :sys_role_ids

  public
    def users
      SS::User.in(group_ids: id)
    end
end


text:
package net.anyflow.menton.example.twitter;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import junit.framework.TestSuite;

@RunWith(Suite.class)
@SuiteClasses({ TweetTest.class, ListTest.class })
public class ApiTestSuite extends TestSuite {

	private static net.anyflow.menton.example.twitter.Entrypoint server = null;

	@BeforeClass
	public static void setUp() throws Exception {
		server = new net.anyflow.menton.example.twitter.Entrypoint();
		server.start();
	}

	@AfterClass
	public static void tearDown() throws Exception {
		if (server == null) { return; }

		server.shutdown(false);
	}

	public static net.anyflow.menton.example.twitter.Entrypoint server() {
		return server;
	}
}


text:
package org.hisp.dhis.deduplication;

import java.util.List;

import org.hisp.dhis.common.IdentifiableObjectStore;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;

public interface PotentialDuplicateStore
    extends IdentifiableObjectStore<PotentialDuplicate>
{
    int getCountByQuery( PotentialDuplicateQuery query );

    List<PotentialDuplicate> getAllByQuery( PotentialDuplicateQuery query );

    boolean exists( PotentialDuplicate potentialDuplicate )
        throws PotentialDuplicateConflictException;

    /**
     * Moves the tracked entity attribute values from the "duplicate" tei into
     * the "original" tei. Only the trackedEntityAttributes specified in the
     * argument are considered. If a corresponding trackedEntityAttribute value
     * already exists in the old tei, they are overwritten. If no
     * trackedEntityAttributeValue exists in the old tei, then a new TEAV with
     * the value as in the duplicate is created and the old teav is deleted.
     *
     * @param original The original TEI
     * @param duplicate The duplicate TEI
     * @param trackedEntityAttributes The teas that has to be considered for
     *        moving from duplicate to original
     */
    void moveTrackedEntityAttributeValues( TrackedEntityInstance original, TrackedEntityInstance duplicate,
        List<String> trackedEntityAttributes );

    void moveRelationships( TrackedEntityInstance originalUid, TrackedEntityInstance duplicateUid,
        List<String> relationships );

    void moveEnrollments( TrackedEntityInstance original, TrackedEntityInstance duplicate, List<String> enrollments );

    void removeTrackedEntity( TrackedEntityInstance trackedEntityInstance );

    void auditMerge( DeduplicationMergeParams params );
}


text:
The WWPass Web Application SDK for Python comprises documentation and a library that is installed on a Service Provider's system to allow authentication using the WWPass system. The WWPass Authentication Service is an alternative to, or replacement for, other authentication methods such as user name/password.

### Prerequisites
You have to register your site and receive **WWPass Service Provider (SP) credentials (certificate and private key)** at <https://developers.wwpass.com>. If, for example, your site has the URL of `mysite.com` and you follow the recommended file naming convention when obtaining SP credentials, the files will be named `mysite.com.crt` (for the certificate) and `mysite.com.key` (for the private key). The [WWPass CA certificate](https://developers.wwpass.com/downloads/wwpass.ca) should also be downloaded and made accessible to WWPass application. If you have root access to your computer, then `/etc/ssl` folder is an appropriate place to store the certificates and the key. Make sure that the script will have enough rights to read the files there. Usually access to `/etc/ssl/private` is quite limited.

The **WWPass PassKey** or **WWPass PassKey Lite** is a requirement for user authentication.
**PassKey** is a hardware device that enables authentication and access for a given user. A major component of the WWPass authentication capability is the software that supports the PassKey itself. Without this software, requests to an end user to authenticate their identity will fail since this software is used to directly access information stored on the PassKey to and communicate with WWPass. To allow Administrator testing of the authentication infrastructure, this client software and an accompanying PassKey is required.
**PassKey Lite** is an application for Android and iOS smartphones and tablets. The application is used to scan QR codes to authenticate into WWPass-enabled sites. Alternatively, when browsing with these mobile devices, you can tap the QR code image to authenticate into the site to access protected information directly on your phone or tablet.
For more information about how to obtain a PassKey and register it, please refer to the WWPass web site (<https://www.wwpass.com>).

### Installation
To install WWPass Python SDK run:
```shell
$ python setup.py install
```

### Licensing
Copyright 2016 WWPass Corporation

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.

Read more about WWPass Python SDK in [`WWPass-Python-SDK.md`](WWPass-Python-SDK.md).


text:
import sublime
import sublime_plugin
import os
from os import path
import time

try:
  from FolderFiles.folder_files import FolderFiles
except ImportError as error:
  sublime.error_message("Dependency import failed; please read readme for " +
   "EvalSelection plugin for installation instructions; to disable this " +
   "message remove this plugin; message: " + str(error))
  raise error

def get_history_path():
  history_path = sublime.packages_path() + '/EvalSelection/history'
  if not path.exists(history_path):
    os.makedirs(history_path)
  return history_path

def add_code_to_history(code):
  filename = get_history_path() + '/' + str(int(time.time())) + '.py'
  io = open(filename, 'w')
  io.write(code)
  io.close()

def run(view, edit):
  for sel in view.sel():
    if sel.size() == 0:
      continue

    code = "import sublime\nimport sublime_plugin\n\n" + view.substr(sel)
    add_code_to_history(code)
    exec(code, {'view': view, 'edit': edit})


text:
import EmberObject from "ember-runtime/system/object";
import run from "ember-metal/run_loop";
import EmberView from "ember-views/views/view";
import ObjectProxy from "ember-runtime/system/object_proxy";

function appendView(view) {
  run(function() { view.appendTo('#qunit-fixture'); });
}

var compile = Ember.Handlebars.compile;

var view;

QUnit.module("Handlebars {{#if}} and {{#unless}} helpers", {
  teardown: function() {
    run(function() {
      if (view) {
        view.destroy();
      }
    });
  }
});

test("unless should keep the current context (#784)", function() {
  view = EmberView.create({
    o: EmberObject.create({foo: '42'}),

    template: compile('{{#with view.o}}{{#view Ember.View}}{{#unless view.doesNotExist}}foo: {{foo}}{{/unless}}{{/view}}{{/with}}')
  });

  appendView(view);

  equal(view.$().text(), 'foo: 42');
});

test("The `if` helper tests for `isTruthy` if available", function() {
  view = EmberView.create({
    truthy: EmberObject.create({ isTruthy: true }),
    falsy: EmberObject.create({ isTruthy: false }),

    template: compile('{{#if view.truthy}}Yep{{/if}}{{#if view.falsy}}Nope{{/if}}')
  });

  appendView(view);

  equal(view.$().text(), 'Yep');
});

test("The `if` helper does not print the contents for an object proxy without content", function() {
  view = EmberView.create({
    truthy: ObjectProxy.create({ content: {} }),
    falsy: ObjectProxy.create({ content: null }),

    template: compile('{{#if view.truthy}}Yep{{/if}}{{#if view.falsy}}Nope{{/if}}')
  });

  appendView(view);

  equal(view.$().text(), 'Yep');
});

test("The `if` helper updates if an object proxy gains or loses context", function() {
  view = EmberView.create({
    proxy: ObjectProxy.create({ content: null }),

    template: compile('{{#if view.proxy}}Yep{{/if}}')
  });

  appendView(view);

  equal(view.$().text(), '');

  run(function() {
    view.set('proxy.content', {});
  });

  equal(view.$().text(), 'Yep');

  run(function() {
    view.set('proxy.content', null);
  });

  equal(view.$().text(), '');
});

test("The `if` helper updates if an array is empty or not", function() {
  view = EmberView.create({
    array: Ember.A(),

    template: compile('{{#if view.array}}Yep{{/if}}')
  });

  appendView(view);

  equal(view.$().text(), '');

  run(function() {
    view.get('array').pushObject(1);
  });

  equal(view.$().text(), 'Yep');

  run(function() {
    view.get('array').removeObject(1);
  });

  equal(view.$().text(), '');
});

test("The `if` helper updates when the value changes", function() {
  view = EmberView.create({
    conditional: true,
    template: compile('{{#if view.conditional}}Yep{{/if}}')
  });
  appendView(view);
  equal(view.$().text(), 'Yep');
  run(function(){
    view.set('conditional', false);
  });
  equal(view.$().text(), '');
});

test("The `unbound if` helper does not update when the value changes", function() {
  view = EmberView.create({
    conditional: true,
    template: compile('{{#unbound if view.conditional}}Yep{{/unbound}}')
  });
  appendView(view);
  equal(view.$().text(), 'Yep');
  run(function(){
    view.set('conditional', false);
  });
  equal(view.$().text(), 'Yep');
});

test("The `unless` helper updates when the value changes", function() {
  view = EmberView.create({
    conditional: false,
    template: compile('{{#unless view.conditional}}Nope{{/unless}}')
  });
  appendView(view);
  equal(view.$().text(), 'Nope');
  run(function(){
    view.set('conditional', true);
  });
  equal(view.$().text(), '');
});

test("The `unbound if` helper does not update when the value changes", function() {
  view = EmberView.create({
    conditional: false,
    template: compile('{{#unbound unless view.conditional}}Nope{{/unbound}}')
  });
  appendView(view);
  equal(view.$().text(), 'Nope');
  run(function(){
    view.set('conditional', true);
  });
  equal(view.$().text(), 'Nope');
});

test("The `if` helper ignores a controller option", function() {
  var lookupCalled = false;

  view = EmberView.create({
    container: {
      lookup: function() {
        lookupCalled = true;
      }
    },
    truthy: true,

    template: compile('{{#if view.truthy controller="foo"}}Yep{{/if}}')
  });

  appendView(view);

  equal(lookupCalled, false, 'controller option should NOT be used');
});


text:
/*!
Teddy is a simd accelerated multiple substring matching algorithm. The name
and the core ideas in the algorithm were learned from the Hyperscan[1]
project.

Background
----------
The key idea of Teddy is to do *packed* substring matching. In the literature,
packed substring matching is the idea of examing multiple bytes in a haystack
at a time to detect matches. Implementations of, for example, memchr (which
detects matches of a single byte) have been doing this for years. Only
recently, with the introduction of various SIMD instructions, has this been
extended to substring matching. The PCMPESTRI instruction (and its relatives),
for example, implements substring matching in hardware. It is, however, limited
to substrings of length 16 bytes or fewer, but this restriction is fine in a
regex engine, since we rarely care about the performance difference between
searching for a 16 byte literal and a 16 + N literal---16 is already long
enough. The key downside of the PCMPESTRI instruction, on current (2016) CPUs
at least, is its latency and throughput. As a result, it is often faster to do
substring search with a Boyer-Moore variant and a well placed memchr to quickly
skip through the haystack.

There are fewer results from the literature on packed substring matching,
and even fewer for packed multiple substring matching. Ben-Kiki et al.[2]
describes use of PCMPESTRI for substring matching, but is mostly theoretical
and hand-waves performance. There is other theoretical work done by Bille[3]
as well.

The rest of the work in the field, as far as I'm aware, is by Faro and Kulekci
and is generally focused on multiple pattern search. Their first paper[4a]
introduces the concept of a fingerprint, which is computed for every block of
N bytes in every pattern. The haystack is then scanned N bytes at a time and
a fingerprint is computed in the same way it was computed for blocks in the
patterns. If the fingerprint corresponds to one that was found in a pattern,
then a verification step follows to confirm that one of the substrings with the
corresponding fingerprint actually matches at the current location. Various
implementation tricks are employed to make sure the fingerprint lookup is fast;
typically by truncating the fingerprint. (This may, of course, provoke more
steps in the verification process, so a balance must be struck.)

The main downside of [4a] is that the minimum substring length is 32 bytes,
presumably because of how the algorithm uses certain SIMD instructions. This
essentially makes it useless for general purpose regex matching, where a small
number of short patterns is far more likely.

Faro and Kulekci published another paper[4b] that is conceptually very similar
to [4a]. The key difference is that it uses the CRC32 instruction (introduced
as part of SSE 4.2) to compute fingerprint values. This also enables the
algorithm to work effectively on substrings as short at 7 bytes with 4 byte
windows. 7 bytes is unfortunately still too long. The window could be
technically shrunk to 2 bytes, thereby reducing minimum length to 3, but the
small window size ends up negating most performance benefits---and it's likely
the common case in a general purpose regex engine.

Faro and Kulekci also published [4c] that appears to be intended as a
replacement to using PCMPESTRI. In particular, it is specifically motivated by
the high throughput/latency time of PCMPESTRI and therefore chooses other SIMD
instructions that are faster. While this approach works for short substrings,
I personally couldn't see a way to generalize it to multiple substring search.

Faro and Kulekci have another paper[4d] that I haven't been able to read
because it is behind a paywall.

Teddy
-----
Finally, we get to Teddy. If the above literature review is complete, then it
appears that Teddy is a novel algorithm. More than that, in my experience, it
completely blows away the competition for short substrings, which is exactly
what we want in a general purpose regex engine. Again, the algorithm appears
to be developed by the authors of Hyperscan[1]. Hyperscan was open sourced late
2015, and no earlier history could be found. Therefore, tracking the exact
provenance of the algorithm with respect to the published literature seems
difficult.

DISCLAIMER: My understanding of Teddy is limited to reading auto-generated C
code, its disassembly and observing its runtime behavior.

At a high level, Teddy works somewhat similarly to the fingerprint algorithms
published by Faro and Kulekci, but Teddy does it in a way that scales a bit
better. Namely:

1. Teddy's core algorithm scans the haystack in 16 byte chunks. 16 is
   significant because it corresponds to the number of bytes in a SIMD vector.
   If one used AVX2 instructions, then we could scan the haystack in 32 byte
   chunks. Similarly, if one used AVX512 instructions, we could sca the
   haystack in 64 byte chunks. Hyperscan implements SIMD + AVX2, we only
   implement SIMD for the moment. (The author doesn't have a CPU with AVX2
   support... yet.)
2. Bitwise operations are performed on each chunk to discover if any region of
   it matches a set of precomputed fingerprints from the patterns. If there are
   matches, then a verification step is performed. In this implementation, our
   verificiation step is a naive. This can be improved upon.

The details to make this work are quite clever. First, we must choose how to
pick our fingerprints. In Hyperscan's implementation, I *believe* they use the
last N bytes of each substring, where N must be at least the minimum length of
any substring in the set being searched. In this implementation, we use the
first N bytes of each substring. (The tradeoffs between these choices aren't
yet clear to me.) We then must figure out how to quickly test whether an
occurrence of any fingerprint from the set of patterns appears in a 16 byte
block from the haystack. To keep things simple, let's assume N = 1 and examine
some examples to motivate the approach. Here are our patterns:

```ignore
foo
bar
baz
```

The corresponding fingerprints, for N = 1, are `f`, `b` and `b`. Now let's set
our 16 byte block to:

```ignore
bat cat foo bump
xxxxxxxxxxxxxxxx
```

To cut to the chase, Teddy works by using bitsets. In particular, Teddy creates
a mask that allows us to quickly compute membership of a fingerprint in a 16
byte block that also tells which pattern the fingerprint corresponds to. In
this case, our fingerprint is a single byte, so an appropriate abstraction is
a map from a single byte to a list of patterns that contain that fingerprint:

```ignore
f |--> foo
b |--> bar, baz
```

Now, all we need to do is figure out how to represent this map in vector space
and use normal SIMD operations to perform a lookup. The first simplification
we can make is to represent our patterns as bit fields occupying a single
byte. This is important, because a single SIMD vector can store 16 bytes.

```ignore
f |--> 00000001
b |--> 00000010, 00000100
```

How do we perform lookup though? It turns out that SSSE3 introduced a very cool
instruction called PSHUFB. The instruction takes two SIMD vectors, `A` and `B`,
and returns a third vector `C`. All vectors are treated as 16 8-bit integers.
`C` is formed by `C[i] = A[B[i]]`. (This is a bit of a simplification, but true
for the purposes of this algorithm. For full details, see Intel's Intrinsics
Guide[5].) This essentially lets us use the values in `B` to lookup values in
`A`.

If we could somehow cause `B` to contain our 16 byte block from the haystack,
and if `A` could contain our bitmasks, then we'd end up with something like
this for `A`:

```ignore
    0x00 0x01 ... 0x62      ... 0x66      ... 0xFF
A = 0    0        00000001      00000110      0
```

And if `B` contains our window from our haystack, we could use shuffle to take
the values from `B` and use them to look up our bitsets in `A`. But of course,
we can't do this because `A` in the above example contains 256 bytes, which
is much larger than the size of a SIMD vector.

Nybbles to the rescue! A nybble is 4 bits. Instead of one mask to hold all of
our bitsets, we can use two masks, where one mask corresponds to the lower four
bits of our fingerprint and the other mask corresponds to the upper four bits.
So our map now looks like:

```ignore
'f' & 0xF = 0x6 |--> 00000001
'f' >> 4  = 0x6 |--> 00000111
'b' & 0xF = 0x2 |--> 00000110
'b' >> 4  = 0x6 |--> 00000111
```

Notice that the bitsets for each nybble correspond to the union of all
fingerprints that contain that nibble. For example, both `f` and `b` have the
same upper 4 bits but differ on the lower 4 bits. Putting this together, we
have `A0`, `A1` and `B`, where `A0` is our mask for the lower nybble, `A1` is
our mask for the upper nybble and `B` is our 16 byte block from the haystack:

```ignore
      0x00 0x01 0x02      0x03 ... 0x06      ... 0xF
A0 =  0    0    00000110  0        00000001      0
A1 =  0    0    0         0        00000111      0
B  =  b    a    t         _        t             p
B  =  0x62 0x61 0x74      0x20     0x74          0x70
```

But of course, we can't use `B` with `PSHUFB` yet, since its values are 8 bits,
and we need indexes that are at most 4 bits (corresponding to one of 16
values). We can apply the same transformation to split `B` into lower and upper
nybbles as we did `A`. As before, `B0` corresponds to the lower nybbles and
`B1` corresponds to the upper nybbles:

```ignore
     b   a   t   _   c   a   t   _   f   o   o   _   b   u   m   p
B0 = 0x2 0x1 0x4 0x0 0x3 0x1 0x4 0x0 0x6 0xF 0xF 0x0 0x2 0x5 0xD 0x0
B1 = 0x6 0x6 0x7 0x2 0x6 0x6 0x7 0x2 0x6 0x6 0x6 0x2 0x6 0x7 0x6 0x7
```

And now we have a nice correspondence. `B0` can index `A0` and `B1` can index
`A1`. Here's what we get when we apply `C0 = PSHUFB(A0, B0)`:

```ignore
     b         a        ... f         o         ... p
     A0[0x2]   A0[0x1]      A0[0x6]   A0[0xF]       A0[0x0]
C0 = 00000110  0            00000001  0             0
```

And `C1 = PSHUFB(A1, B1)`:

```ignore
     b         a        ... f         o        ... p
     A1[0x6]   A1[0x6]      A1[0x6]   A1[0x6]      A1[0x7]
C1 = 00000111  00000111     00000111  00000111     0
```

Notice how neither one of `C0` or `C1` is guaranteed to report fully correct
results all on its own. For example, `C1` claims that `b` is a fingerprint for
the pattern `foo` (since `A1[0x6] = 00000111`), and that `o` is a fingerprint
for all of our patterns. But if we combined `C0` and `C1` with an `AND`
operation:

```
     b         a        ... f         o        ... p
C  = 00000110  0            00000001  0            0
```

Then we now have that `C[i]` contains a bitset corresponding to the matching
fingerprints in a haystack's 16 byte block, where `i` is the `ith` byte in that
block.

Once we have that, we can look for the position of the least significant bit
in `C`. That position, modulo `8`, gives us the pattern that the fingerprint
matches. That position, integer divided by `8`, also gives us the byte offset
that the fingerprint occurs in inside the 16 byte haystack block. Using those
two pieces of information, we can run a verification procedure that tries
to match all substrings containing that fingerprint at that position in the
haystack.

Implementation notes
--------------------
The problem with the algorithm as described above is that it uses a single byte
for a fingerprint. This will work well if the fingerprints are rare in the
haystack (e.g., capital letters or special characters in normal English text),
but if the fingerprints are common, you'll wind up spending too much time in
the verification step, which effectively negate the performance benefits of
scanning 16 bytes at a time. Remember, the key to the performance of this
algorithm is to do as little work as possible per 16 bytes.

This algorithm can be extrapolated in a relatively straight-forward way to use
larger fingerprints. That is, instead of a single byte prefix, we might use a
three byte prefix. The implementation below implements N = {1, 2, 3} and always
picks the largest N possible. The rationale is that the bigger the fingerprint,
the fewer verification steps we'll do. Of course, if N is too large, then we'll
end up doing too much on each step.

The way to extend it is:

1. Add a mask for each byte in the fingerprint. (Remember that each mask is
   composed of two SIMD vectors.) This results in a value of `C` for each byte
   in the fingerprint while searching.
2. When testing each 16 byte block, each value of `C` must be shifted so that
   they are aligned. Once aligned, they should all be `AND`'d together. This
   will give you only the bitsets corresponding to the full match of the
   fingerprint.

The implementation below is commented to fill in the nitty gritty details.

[1] - https://github.com/01org/hyperscan
[2a] - http://drops.dagstuhl.de/opus/volltexte/2011/3355/pdf/37.pdf
[2b] - http://www.cs.haifa.ac.il/~oren/Publications/bpsm.pdf
[3] - http://www.sciencedirect.com/science/article/pii/S1570866710000353
[4a] - http://www.dmi.unict.it/~faro/papers/conference/faro32.pdf
[4b] - https://pdfs.semanticscholar.org/fed7/ca62dc469314f3552017d0da7ebd669d4649.pdf
[4c] - http://arxiv.org/pdf/1209.6449.pdf
[4d] - http://www.sciencedirect.com/science/article/pii/S1570866714000471
[5] - https://software.intel.com/sites/landingpage/IntrinsicsGuide
*/

// TODO: Extend this to use AVX2 instructions.
// TODO: Extend this to use AVX512 instructions.
// TODO: Extend this to cleverly use Aho-Corasick. Possibly to replace both
//       "slow" searching and the verification step.
// TODO: Make the inner loop do aligned loads.

use std::cmp;
use std::mem::transmute;
use std::ptr;

use simd::u8x16;
use simd::x86::sse2::u64x2;
use simd::x86::ssse3::Ssse3U8x16;

use syntax;

/// Corresponds to the number of bytes read at a time in the haystack.
const BLOCK_SIZE: usize = 16;

/// Match reports match information.
#[derive(Debug, Clone)]
pub struct Match {
    /// The index of the pattern that matched. The index is in correspondence
    /// with the order of the patterns given at construction.
    pub pat: usize,
    /// The start byte offset of the match.
    pub start: usize,
    /// The end byte offset of the match. This is always start + pat.len().
    pub end: usize,
}

/// A SIMD accelerated multi substring searcher.
#[derive(Debug, Clone)]
pub struct Teddy {
    /// A list of substrings to match.
    pats: Vec<Vec<u8>>,
    /// A set of 8 buckets. Each bucket corresponds to a single member of a
    /// bitset. A bucket contains zero or more substrings. This is useful
    /// when the number of substrings exceeds 8, since our bitsets cannot have
    /// more than 8 members.
    buckets: Vec<Vec<usize>>,
    /// Our set of masks. There's one mask for each byte in the fingerprint.
    masks: Masks,
}

/// A list of masks. This has length equal to the length of the fingerprint.
/// The length of the fingerprint is always `max(3, len(smallest substring))`.
#[derive(Debug, Clone)]
struct Masks(Vec<Mask>);

/// A single mask.
#[derive(Debug, Clone, Copy)]
struct Mask {
    /// Bitsets for the low nybbles in a fingerprint.
    lo: u8x16,
    /// Bitsets for the high nybbles in a fingerprint.
    hi: u8x16,
}

impl Teddy {
    /// Create a new Teddy multi substring matcher.
    ///
    /// If a Teddy matcher could not be created (e.g., `pats` is empty or has
    /// an empty substring), then `None` is returned.
    pub fn new(pats: &syntax::Literals) -> Option<Teddy> {
        let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect();
        let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0);
        // Don't allow any empty patterns and require that we have at
        // least one pattern.
        if min_len < 1 {
            return None;
        }
        // Pick the largest mask possible, but no larger than 3.
        let nmasks = cmp::min(3, min_len);
        let mut masks = Masks::new(nmasks);
        let mut buckets = vec![vec![]; 8];
        // Assign a substring to each bucket, and add the bucket's bitfield to
        // the appropriate position in the mask.
        for (pati, pat) in pats.iter().enumerate() {
            let bucket = pati % 8;
            buckets[bucket].push(pati);
            masks.add(bucket as u8, pat);
        }
        Some(Teddy {
            pats: pats.to_vec(),
            buckets: buckets,
            masks: masks,
        })
    }

    /// Returns all of the substrings matched by this Teddy.
    pub fn patterns(&self) -> &[Vec<u8>] {
        &self.pats
    }

    /// Returns the number of substrings in this matcher.
    pub fn len(&self) -> usize {
        self.pats.len()
    }

    /// Returns the approximate size on the heap used by this matcher.
    pub fn approximate_size(&self) -> usize {
        self.pats.iter().fold(0, |a, b| a + b.len())
    }

    /// Searches `haystack` for the substrings in this Teddy. If a match was
    /// found, then it is returned. Otherwise, `None` is returned.
    pub fn find(&self, haystack: &[u8]) -> Option<Match> {
        // If our haystack is smaller than the block size, then fall back to
        // a naive brute force search.
        //
        // TODO: Use Aho-Corasick.
        if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) {
            return self.slow(haystack, 0);
        }
        match self.masks.len() {
            0 => None,
            1 => self.find1(haystack),
            2 => self.find2(haystack),
            3 => self.find3(haystack),
            _ => unreachable!(),
        }
    }

    /// find1 is used when there is only 1 mask. This is the easy case and is
    /// pretty much as described in the module documentation.
    #[inline(always)]
    fn find1(&self, haystack: &[u8]) -> Option<Match> {
        let mut pos = 0;
        let zero = u8x16::splat(0);
        let len = haystack.len();
        debug_assert!(len >= BLOCK_SIZE);
        while pos <= len - BLOCK_SIZE {
            let h = unsafe { u8x16::load_unchecked(haystack, pos) };
            // N.B. res0 is our `C` in the module documentation.
            let res0 = self.masks.members1(h);
            // Only do expensive verification if there are any non-zero bits.
            if res0.ne(zero).any() {
                if let Some(m) = self.verify_128(haystack, pos, res0) {
                    return Some(m);
                }
            }
            pos += BLOCK_SIZE;
        }
        self.slow(haystack, pos)
    }

    /// find2 is used when there are 2 masks, e.g., the fingerprint is 2 bytes
    /// long.
    #[inline(always)]
    fn find2(&self, haystack: &[u8]) -> Option<Match> {
        // This is an exotic way to right shift a SIMD vector across lanes.
        // See below at use for more details.
        let res0shuffle = u8x16::new(
            0, 0, 1, 2,
            3, 4, 5, 6,
            7, 8, 9, 10,
            11, 12, 13, 14,
        );
        let zero = u8x16::splat(0);
        let len = haystack.len();
        // The previous value of C (from the module documentation) for the
        // *first* byte in the fingerprint. On subsequent iterations, we take
        // the last bitset from the previous C and insert it into the first
        // position of the current C, shifting all other bitsets to the right
        // one lane. This causes C for the first byte to line up with C for the
        // second byte, so that they can be AND'd together.
        let mut prev0 = u8x16::splat(0xFF);
        let mut pos = 1;
        debug_assert!(len >= BLOCK_SIZE);
        while pos <= len - BLOCK_SIZE {
            let h = unsafe { u8x16::load_unchecked(haystack, pos) };
            let (res0, res1) = self.masks.members2(h);

            // The next three lines are essentially equivalent to
            //
            //     (prev0 << 15) | (res0 >> 1)
            //
            // ... if SIMD vectors could shift across lanes. There is the
            // PALIGNR instruction, but apparently LLVM doesn't expose it as
            // a proper intrinsic. Thankfully, it appears the following
            // sequence does indeed compile down to a PALIGNR.
            let prev0byte0 = prev0.extract(15);
            let res0shiftr8 = res0.shuffle_bytes(res0shuffle);
            let res0prev0 = res0shiftr8.replace(0, prev0byte0);

            // AND's our C values together.
            let res = res0prev0 & res1;
            prev0 = res0;
            if res.ne(zero).any() {
                let pos = pos.checked_sub(1).unwrap();
                if let Some(m) = self.verify_128(haystack, pos, res) {
                    return Some(m);
                }
            }
            pos += BLOCK_SIZE;
        }
        // The windowing above doesn't check the last byte in the last
        // window, so start the slow search at the last byte of the last
        // window.
        self.slow(haystack, pos.checked_sub(1).unwrap())
    }

    /// find3 is used when there are 3 masks, e.g., the fingerprint is 3 bytes
    /// long.
    ///
    /// N.B. This is a straight-forward extrapolation of find2. The only
    /// difference is that we need to keep track of two previous values of
    /// C, since we now need to align for three bytes.
    #[inline(always)]
    fn find3(&self, haystack: &[u8]) -> Option<Match> {
        let zero = u8x16::splat(0);
        let len = haystack.len();

        let res0shuffle = u8x16::new(
            0, 0, 0, 1,
            2, 3, 4, 5,
            6, 7, 8, 9,
            10, 11, 12, 13,
        );
        let res1shuffle = u8x16::new(
            0, 0, 1, 2,
            3, 4, 5, 6,
            7, 8, 9, 10,
            11, 12, 13, 14,
        );
        let mut prev0 = u8x16::splat(0xFF);
        let mut prev1 = u8x16::splat(0xFF);
        let mut pos = 2;
        while pos <= len - BLOCK_SIZE {
            let h = unsafe { u8x16::load_unchecked(haystack, pos) };
            let (res0, res1, res2) = self.masks.members3(h);

            let prev0byte0 = prev0.extract(14);
            let prev0byte1 = prev0.extract(15);
            let res0shiftr16 = res0.shuffle_bytes(res0shuffle);
            let res0prev0 = res0shiftr16.replace(0, prev0byte0)
                                        .replace(1, prev0byte1);

            let prev1byte0 = prev1.extract(15);
            let res1shiftr8 = res1.shuffle_bytes(res1shuffle);
            let res1prev1 = res1shiftr8.replace(0, prev1byte0);

            let res = res0prev0 & res1prev1 & res2;

            prev0 = res0;
            prev1 = res1;
            if res.ne(zero).any() {
                let pos = pos.checked_sub(2).unwrap();
                if let Some(m) = self.verify_128(haystack, pos, res) {
                    return Some(m);
                }
            }
            pos += BLOCK_SIZE;
        }
        // The windowing above doesn't check the last two bytes in the last
        // window, so start the slow search at the penultimate byte of the
        // last window.
        // self.slow(haystack, pos.saturating_sub(2))
        self.slow(haystack, pos.checked_sub(2).unwrap())
    }

    /// Runs the verification procedure on `res` (i.e., `C` from the module
    /// documentation), where the haystack block starts at `pos` in
    /// `haystack`.
    ///
    /// If a match exists, it returns the first one.
    #[inline(always)]
    fn verify_128(
        &self,
        haystack: &[u8],
        pos: usize,
        res: u8x16,
    ) -> Option<Match> {
        // The verification procedure is more amenable to standard 64 bit
        // values, so get those.
        let res64: u64x2 = unsafe { transmute(res) };
        let reshi = res64.extract(0);
        let reslo = res64.extract(1);
        if let Some(m) = self.verify_64(haystack, pos, reshi, 0) {
            return Some(m);
        }
        if let Some(m) = self.verify_64(haystack, pos, reslo, 8) {
            return Some(m);
        }
        None
    }

    /// Runs the verification procedure on half of `C`.
    ///
    /// If a match exists, it returns the first one.
    ///
    /// offset is an additional byte offset to add to the position before
    /// substring match verification.
    #[inline(always)]
    fn verify_64(
        &self,
        haystack: &[u8],
        pos: usize,
        mut res: u64,
        offset: usize,
    ) -> Option<Match> {
        // There's a possible match so long as there's at least one bit set.
        while res != 0 {
            // The next possible match is at the least significant bit.
            let bit = res.trailing_zeros();
            // The position of the bit in its corresponding lane gives us the
            // corresponding bucket.
            let bucket = (bit % 8) as usize;
            // The lane that the bit is in gives us its offset.
            let bytei = (bit / 8) as usize;
            // Compute the start of where a substring would start.
            let start = pos + offset + bytei;
            // Kill off this bit. If we couldn't match anything, we'll go to
            // the next bit.
            res &= !(1 << bit);
            // Actual substring search verification.
            if let Some(m) = self.verify_bucket(haystack, bucket, start) {
                return Some(m);
            }
        }
        None
    }

    /// Verifies whether any substring in the given bucket matches in haystack
    /// at the given starting position.
    #[inline(always)]
    fn verify_bucket(
        &self,
        haystack: &[u8],
        bucket: usize,
        start: usize,
    ) -> Option<Match> {
        // This cycles through the patterns in the bucket in the order that
        // the patterns were given. Therefore, we guarantee leftmost-first
        // semantics.
        for &pati in &self.buckets[bucket] {
            let pat = &*self.pats[pati];
            if start + pat.len() > haystack.len() {
                continue;
            }
            if pat == &haystack[start..start + pat.len()] {
                return Some(Match {
                    pat: pati,
                    start: start,
                    end: start + pat.len(),
                });
            }
        }
        None
    }

    /// Slow substring search through all patterns in this matcher.
    ///
    /// This is used when we don't have enough bytes in the haystack for our
    /// block based approach.
    fn slow(&self, haystack: &[u8], pos: usize) -> Option<Match> {
        // TODO: Use Aho-Corasick, or otherwise adapt the block based approach
        // to be capable of using smaller blocks.
        let mut m = None;
        for (pi, p) in self.pats.iter().enumerate() {
            if let Some(i) = find_slow(p, &haystack[pos..]) {
                let candidate = Match {
                    pat: pi,
                    start: pos + i,
                    end: pos + i + p.len(),
                };
                match m {
                    None => m = Some(candidate),
                    Some(ref mut m) => {
                        if candidate.start < m.start {
                            *m = candidate;
                        }
                    }
                }
            }
        }
        m
    }
}

impl Masks {
    /// Create a new set of masks of size `n`, where `n` corresponds to the
    /// number of bytes in a fingerprint.
    fn new(n: usize) -> Masks {
        Masks(vec![Mask::new(); n])
    }

    /// Returns the number of masks.
    fn len(&self) -> usize {
        self.0.len()
    }

    /// Adds the given pattern to the given bucket. The bucket should be a
    /// power of 2 <= 2^7.
    fn add(&mut self, bucket: u8, pat: &[u8]) {
        for (i, mask) in self.0.iter_mut().enumerate() {
            mask.add(bucket, pat[i]);
        }
    }

    /// Finds the fingerprints that are in the given haystack block. i.e., this
    /// returns C as described in the module documentation.
    ///
    /// More specifically, for i in 0..16 and j in 0..8, C[i][j] == 1 if and
    /// only if `haystack_block[i]` corresponds to a fingerprint that is part
    /// of a pattern in bucket `j`.
    #[inline(always)]
    fn members1(&self, haystack_block: u8x16) -> u8x16 {
        let masklo = u8x16::splat(0xF);
        let hlo = haystack_block & masklo;
        let hhi = (haystack_block >> 4) & masklo;

        self.0[0].lo.shuffle_bytes(hlo) & self.0[0].hi.shuffle_bytes(hhi)
    }

    /// Like members1, but computes C for the first and second bytes in the
    /// fingerprint.
    #[inline(always)]
    fn members2(&self, haystack_block: u8x16) -> (u8x16, u8x16) {
        let masklo = u8x16::splat(0xF);
        let hlo = haystack_block & masklo;
        let hhi = (haystack_block >> 4) & masklo;

        let res0 = self.0[0].lo.shuffle_bytes(hlo)
                   & self.0[0].hi.shuffle_bytes(hhi);
        let res1 = self.0[1].lo.shuffle_bytes(hlo)
                   & self.0[1].hi.shuffle_bytes(hhi);
        (res0, res1)
    }

    /// Like members1, but computes C for the first, second and third bytes in
    /// the fingerprint.
    #[inline(always)]
    fn members3(&self, haystack_block: u8x16) -> (u8x16, u8x16, u8x16) {
        let masklo = u8x16::splat(0xF);
        let hlo = haystack_block & masklo;
        let hhi = (haystack_block >> 4) & masklo;

        let res0 = self.0[0].lo.shuffle_bytes(hlo)
                   & self.0[0].hi.shuffle_bytes(hhi);
        let res1 = self.0[1].lo.shuffle_bytes(hlo)
                   & self.0[1].hi.shuffle_bytes(hhi);
        let res2 = self.0[2].lo.shuffle_bytes(hlo)
                   & self.0[2].hi.shuffle_bytes(hhi);
        (res0, res1, res2)
    }
}

impl Mask {
    /// Create a new mask with no members.
    fn new() -> Mask {
        Mask {
            lo: u8x16::splat(0),
            hi: u8x16::splat(0),
        }
    }

    /// Adds the given byte to the given bucket.
    fn add(&mut self, bucket: u8, byte: u8) {
        // Split our byte into two nybbles, and add each nybble to our
        // mask.
        let byte_lo = (byte & 0xF) as u32;
        let byte_hi = (byte >> 4) as u32;

        let lo = self.lo.extract(byte_lo);
        self.lo = self.lo.replace(byte_lo, ((1 << bucket) as u8) | lo);

        let hi = self.hi.extract(byte_hi);
        self.hi = self.hi.replace(byte_hi, ((1 << bucket) as u8) | hi);
    }
}

/// UnsafeLoad permits loading data into a SIMD vector without bounds checks.
///
/// Ideally, this would be part of the `simd` crate, or even better, we could
/// figure out how to do it without `unsafe` at all.
trait UnsafeLoad {
    type Elem;

    /// load_unchecked creates a new SIMD vector from the elements in `slice`
    /// starting at `offset`. `slice` must have at least the number of elements
    /// required to fill a SIMD vector.
    unsafe fn load_unchecked(slice: &[Self::Elem], offset: usize) -> Self;
}

impl UnsafeLoad for u8x16 {
    type Elem = u8;

    unsafe fn load_unchecked(slice: &[u8], offset: usize) -> u8x16 {
        // TODO: Can we just do pointer casting here? I don't think so, since
        // this could be an unaligned load? Help me.
        let mut x = u8x16::splat(0);
        ptr::copy_nonoverlapping(
            slice.get_unchecked(offset),
            &mut x as *mut u8x16 as *mut u8,
            16);
        x
    }
}

/// Slow single-substring search use for naive brute force matching.
#[cold]
pub fn find_slow(pattern: &[u8], haystack: &[u8]) -> Option<usize> {
    if pattern.len() > haystack.len() {
        return None;
    }
    for i in 0..(haystack.len() - pattern.len() + 1) {
        if pattern == &haystack[i..i + pattern.len()] {
            return Some(i);
        }
    }
    None
}


text:
package org.apache.sshd.common.cipher;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.sshd.common.util.buffer.BufferUtils;
import org.apache.sshd.common.util.security.SecurityUtils;

public class BaseGCMCipher extends BaseCipher {

    protected Mode mode;
    protected boolean initialized;
    protected CounterGCMParameterSpec parameters;
    protected SecretKey secretKey;

    public BaseGCMCipher(int ivsize, int authSize, int kdfSize, String algorithm, int keySize, String transformation,
                         int blkSize) {
        super(ivsize, authSize, kdfSize, algorithm, keySize, transformation, blkSize);
    }

    @Override
    protected Cipher createCipherInstance(Mode mode, byte[] key, byte[] iv) throws Exception {
        this.mode = mode;
        secretKey = new SecretKeySpec(key, getAlgorithm());
        parameters = new CounterGCMParameterSpec(getAuthenticationTagSize() * Byte.SIZE, iv);
        return SecurityUtils.getCipher(getTransformation());
    }

    protected Cipher getInitializedCipherInstance() throws Exception {
        Cipher cipher = getCipherInstance();
        if (!initialized) {
            cipher.init(mode == Mode.Encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, secretKey, parameters);
            initialized = true;
        }
        return cipher;
    }

    @Override
    public void updateAAD(byte[] data, int offset, int length) throws Exception {
        getInitializedCipherInstance().updateAAD(data, offset, length);
    }

    @Override
    public void update(byte[] input, int inputOffset, int inputLen) throws Exception {
        if (mode == Mode.Decrypt) {
            inputLen += getAuthenticationTagSize();
        }
        Cipher cipher = getInitializedCipherInstance();
        cipher.doFinal(input, inputOffset, inputLen, input, inputOffset);
        parameters.incrementCounter();
        initialized = false;
    }

    /**
     * Algorithm parameters for AES/GCM that assumes the IV uses an 8-byte counter field as its least significant bytes.
     */
    protected static class CounterGCMParameterSpec extends GCMParameterSpec {
        protected final byte[] iv;
        protected final long initialCounter;

        protected CounterGCMParameterSpec(int tLen, byte[] src) {
            super(tLen, src);
            if (src.length != 12) {
                throw new IllegalArgumentException("GCM nonce must be 12 bytes, but given len=" + src.length);
            }
            iv = src.clone();
            initialCounter = BufferUtils.getLong(iv, iv.length - Long.BYTES, Long.BYTES);
        }

        protected void incrementCounter() {
            int off = iv.length - Long.BYTES;
            long counter = BufferUtils.getLong(iv, off, Long.BYTES);
            long newCounter = counter + 1L;
            if (newCounter == initialCounter) {
                throw new IllegalStateException("GCM IV would be reused");
            }
            BufferUtils.putLong(newCounter, iv, off, Long.BYTES);
        }

        @Override
        public byte[] getIV() {
            // JCE implementation of GCM will complain if the reference doesn't change between inits
            return iv.clone();
        }
    }

}


text:
namespace HomeCloud.DataAccess.Components.Factories
{
	#region Usings

	using System;
	using System.Collections.Generic;

	using HomeCloud.DataAccess.Services.Factories;

	#endregion

	/// <summary>
	/// Defines methods to distribute factories of <see cref="IQueryHandlerFactory" /> type.
	/// </summary>
	/// <seealso cref="HomeCloud.DataAccess.Services.Factories.IQueryHandlerFactory" />
	public sealed class QueryHandlerFactory : IQueryHandlerFactory
	{
		#region Private Members

		/// <summary>
		/// The factory container.
		/// </summary>
		private readonly IDictionary<Type, object> container = new Dictionary<Type, object>();

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="QueryHandlerFactory" /> class.
		/// </summary>
		/// <param name="databaseQueryHandlerFactory">The <see cref="IDbQueryHandlerFactory" /> factory.</param>
		public QueryHandlerFactory(IDbQueryHandlerFactory databaseQueryHandlerFactory = null)
		{
			if (databaseQueryHandlerFactory != null)
			{
				this.container.Add(typeof(IDbQueryHandlerFactory), databaseQueryHandlerFactory);
			}
		}

		#endregion

		#region ICommandHandlerFactory Implementations

		/// <summary>
		/// Gets the query handler factory.
		/// </summary>
		/// <typeparam name="T">The type of factory derived from <see cref="T:HomeCloud.DataAccess.Services.Factories.IQueryHandlerFactory" />.</typeparam>
		/// <returns>
		/// The instance of <see cref="T:HomeCloud.DataAccess.Services.Factories.IQueryHandlerFactory" />.
		/// </returns>
		public T GetFactory<T>() where T : IQueryHandlerFactory
		{
			if (!this.container.ContainsKey(typeof(T)))
			{
				return default(T);
			}

			return (T)this.container[typeof(T)];
		}

		#endregion
	}
}


text:
import { Template } from 'meteor/templating';
import { Random } from 'meteor/random';

export const exampleMsg = () => {
	const record = Template.instance().record.get();
	return {
		_id: Random.id(),
		alias: record.alias,
		emoji: record.emoji,
		avatar: record.avatar,
		msg: 'Example message',
		bot: {
			i: Random.id(),
		},
		groupable: false,
		attachments: [{
			title: 'Rocket.Chat',
			title_link: 'https://rocket.chat',
			text: 'Rocket.Chat, the best open source chat',
			image_url: '/images/integration-attachment-example.png',
			color: '#764FA5',
		}],
		ts: new Date(),
		u: {
			_id: Random.id(),
			username: record.username,
		},
	};
};

export const exampleUser = () => ({
	u: {
		_id: Random.id(),
	},
});

export const exampleSettings = () => ({
	settings: {},
});


text:
// @ts-check
// @ts-ignore
import pkg from "./package.json";
import {onwarn, abortOnError} from "../../scripts/rollup";

import typescript from "rollup-plugin-typescript2";
import postcss from "rollup-plugin-postcss";
import copy from "rollup-plugin-copy-glob";

import {generateTypings} from "@focus4/styling/lib/generator";

export default (async () => {
    await generateTypings("src");

    /** @type {import("rollup").RollupOptions} */
    const config = {
        input: "src/focus4.layout.tsx",
        plugins: [
            // @ts-ignore
            postcss({extract: true, modules: true}),
            typescript({abortOnError: false}),
            copy([
                {files: "src/header/**/*.css.d.ts", dest: "lib/header"},
                {files: "src/menu/**/*.css.d.ts", dest: "lib/menu"},
                {files: "src/presentation/**/*.css.d.ts", dest: "lib/presentation"},
                {files: "src/scrollable/**/*.css.d.ts", dest: "lib/scrollable"},
                {files: "src/utils/**/*.css.d.ts", dest: "lib/utils"}
            ]),
            abortOnError
        ],
        treeshake: {
            moduleSideEffects: ["intersection-observer"]
        },
        output: {
            format: "esm",
            file: "lib/focus4.layout.js"
        },
        external: [
            ...Object.keys(pkg.dependencies || {}),
            "classnames",
            "i18next",
            "lodash",
            "mobx",
            "mobx-react",
            "moment",
            "react",
            "react/jsx-runtime",
            "react-dom",
            "stylefire",
            "tslib"
        ],
        onwarn
    };
    return config;
})();


text:
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-nodejs-bin:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withArguments(['name-x'])
      .toPromise();
  });

  it('creates files', function () {
    assert.file([
      'package.json'
    ]);
  });
});


text:
module Achievements
  def self.table_name_prefix
    'achievements_'
  end
end


text:
package sage;

public class PVR150Input implements SageTVInputPlugin
{
  private static boolean loadedLib = false;
  private SageTVInputCallback evtRtr;
  private Thread InputThread;

  public PVR150Input()
  {
    if (!loadedLib && !Sage.EMBEDDED)
    {
      System.loadLibrary("PVR150Input");
      loadedLib = true;
    }
  }

  public boolean openInputPlugin(SageTVInputCallback callback)
  {
    evtRtr = callback;
    if(!setupPVR150Input(Sage.getInt("linux/ir_input_pvr150", 0))) return false;

    InputThread = new Thread(new Runnable()
    {
      public void run()
      {
        PVR150Input.this.PVR150InputThread(Sage.getInt("linux/ir_input_pvr150", 0),
            evtRtr);
      }
    }, "PVR150Input");
    InputThread.setDaemon(true);
    // If this is too low in priority we can miss
    // the repeat timing of a button press, so we need
    // accurate timing here to some degree.
    InputThread.setPriority(Thread.MAX_PRIORITY - 3);
    InputThread.start();
    return true;
  }

  public void closeInputPlugin()
  {
    closePVR150Input();
  }

  private native boolean setupPVR150Input(int i2cdev);
  private native void closePVR150Input();
  private native void PVR150InputThread(int i2cdev, SageTVInputCallback evtRtr);
}


text:
echo "mode: count" > acc.out
for Dir in $(find ./* -maxdepth 10 -type d | grep -v test);
do
        if ls $Dir/*.go &> /dev/null;
        then
            go test -v -covermode=count -coverprofile=profile.out $Dir
            if [ -f profile.out ]
            then
                cat profile.out | grep -v "mode: count" >> acc.out
            fi
fi
done
$HOME/gopath/bin/goveralls -coverprofile=acc.out $COVERALLS
rm -rf ./profile.out
rm -rf ./acc.out


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* DatabaseStatCommand.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System.Linq;

using AM;

using JetBrains.Annotations;

#endregion

namespace ManagedIrbis.Infrastructure.ClientCommands
{
    /// <summary>
    /// Database stat.
    /// </summary>
    [PublicAPI]
    public sealed class DatabaseStatCommand
        : ClientCommand
    {
        #region Properties

        /// <summary>
        /// Client query definition.
        /// </summary>
        public StatDefinition Definition { get; set; }

        /// <summary>
        /// Result of the command.
        /// </summary>
        public string Result { get; set; }

        #endregion

        #region Construction

        /// <summary>
        /// Constructor.
        /// </summary>
        public DatabaseStatCommand()
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public DatabaseStatCommand
            (
                [NotNull] StatDefinition definition
            )
        {
            Sure.NotNull(definition, nameof(definition));

            Definition = definition;
        }

        #endregion

        #region ClientCommand members

        /// <inheritdoc cref="ClientCommand.Execute(ClientContext)" />
        public override void Execute
            (
                ClientContext context
            )
        {
            ClientQuery query = CreateQuery(context, CommandCode.DatabaseStat);

            // "2"               STAT
            // "IBIS"            database
            // "v200^a,10,100,1" field
            // "T=A$"            search
            // "0"               min
            // "0"               max
            // ""                sequential
            // ""                mfn list

            string items = string.Join
                (
                    IrbisText.IrbisDelimiter,
                    Definition.Items.Select(item => item.ToString()).ToArray()
                );

            query
                .Add(Definition.DatabaseName)
                .Add(items)
                .AddUtf8(Definition.SearchQuery)
                .Add(Definition.MinMfn)
                .Add(Definition.MaxMfn)
                .AddUtf8(Definition.SequentialQuery)
                .Add(string.Empty) // instead of MFN list
                ;

            ServerResponse result = BaseExecute(context);

            Result = "{\\rtf1 "
                + result.RemainingUtfText()
                + "}";
        }

        #endregion
    }
}


text:
(function() {
  'use strict';

  dockerboardApp.registerModule('containers.ctrl');

  angular.module('containers.ctrl')
    .controller('ContainersCtrl', ContainersController)
    .controller('ContainerCtrl', ContainerController)
    .controller('ContainerLogsCtrl', ContainerLogsController)
    .controller('ContainerTopCtrl', ContainerTopController)
    .config(['$stateProvider',
      function($stateProvider) {
        $stateProvider.
        state('containers', {
            url: '/containers',
            templateUrl: '/js/modules/containers/views/containers.tpl.html'
          })
          .state('containeritem', {
            url: '/containers/:Id',
            templateUrl: '/js/modules/containers/views/container.tpl.html'
          })
          .state('containerLogs', {
            url: '/containers/{Id}/logs',
            templateUrl: '/js/modules/containers/views/container.logs.tpl.html'
          })
          .state('containerTop', {
            url: '/containers/{Id}/top',
            templateUrl: '/js/modules/containers/views/container.top.tpl.html'
          });
      }
    ]);

  ContainersController.$inject = ['$scope', 'Containers', 'Hosts'];

  function ContainersController($scope, Containers, Hosts) {

    $scope.queryParams = Containers.queryParams;
    $scope.queryParams.host = Hosts.getCurrentHostUrl();

    $scope.queryParamsFilters = '';

    $scope.fetch = function() {
      $scope.queryParams.filters = parseFilters($scope.queryParamsFilters);
      Containers.query($scope.queryParams, function(data) {
        $scope.containers = data;
      });
    };

    $scope.fetch();

    $scope.search = function() {
      $scope.fetch();
    };

    $scope.displayablePorts = function(ports) {
      var result = [];
      for (var i = 0, l = ports.length; i < l; ++i) {
        var port = ports[i];
        if (port.IP === '') {
          result.push(port.PrivatePort + '/' + port.Type);
        } else {
          result.push(port.IP + ':' + port.PublicPort + '->' + port.PrivatePort + '/' + port.Type);
        }
      }
      return result.join(', ');
    };

    function parseFilters(text) {
      if (!text) return '';
      var filters = {};
      var arr = text.split(/\s+/g);
      for (var i = 0, l = arr.length; i < l; ++i) {
        var f = arr[i].split('=');
        if (f.length !== 2) {
          continue;
        }
        var name = f[0];
        var value = f[1];
        if (name && value) {
          filters[name] = filters[name] || [];
          filters[name].push(value);
        }
      }
      return JSON.stringify(filters);
    }
  }

  ContainerController.$inject = ['$scope', '$stateParams', '$location', '$mdDialog', 'limitToFilter', 'amTimeAgoFilter', 'Containers', 'Hosts', 'ContainerActions', 'iSockPromise'];

  function ContainerController($scope, $stateParams, $location, $mdDialog, limitToFilter, amTimeAgoFilter, Containers, Hosts, ContainerActions, iSockPromise) {
    iSockPromise.then(function(sock) {
      var data = {
        type: 'container',
        endpoint: 'stats',
        id: $stateParams.Id
      };
      sock.send(JSON.stringify(data));
    });

    Containers.get({
      Id: $stateParams.Id,
      host: Hosts.getCurrentHostUrl()
    }, function(data) {
      formatBasicAttributes(data);
      $scope.container = data;
      $scope.containerShortId = limitToFilter(data.Id, 12);
    }, function(e) {
      if (e.status === 404) {
        $location.path('/containers');
      }
    });

    ContainerActions.get({
      Id: $stateParams.Id,
      action: 'stats'
    }, function(data) {
      console.dir(data);
    });

    $scope.basicAttributes = [];

    function formatBasicAttributes(container) {
      angular.forEach(Containers.basicAttributes, function(k) {
        var v = container[k];
        if (k === 'Id' || k === 'Image') {
          v = limitToFilter(v, 12);
          var href = '#/';
          href += (k === 'Id' ? 'containers/' : 'images/') + v;
          v = '' + v + '';
        } else if (k === 'Created') {
          v = amTimeAgoFilter(v, true);
        }

        this.push({
          key: k,
          value: v
        });
      }, $scope.basicAttributes);
    }

    $scope.toggleRunning = function(ev) {
      $mdDialog.show({
          controller: RunningDialogController,
          templateUrl: '/js/modules/containers/views/container.running.dialog.tpl.html',
          locals: {
            parentScope: $scope
          },
          targetEvent: ev,
        })
        .then(function(running) {
          $scope.container.State.Running = running;
          $scope.container.State[running ? 'StartedAt' : 'FinishedAt'] = Date.now();
        });
    };

    $scope.togglePaused = function(ev) {
      $mdDialog.show({
          controller: PausedDialogController,
          templateUrl: '/js/modules/containers/views/container.paused.dialog.tpl.html',
          locals: {
            parentScope: $scope
          },
          targetEvent: ev,
        })
        .then(function(paused) {
          $scope.container.State.Paused = paused;
        });
    };

    $scope.destory = function(ev) {
      $mdDialog.show({
        controller: DestoryDialogController,
        templateUrl: '/js/modules/containers/views/container.destory.dialog.tpl.html',
        locals: {
          parentScope: $scope
        },
        targetEvent: ev,
      });
    };

    $scope.kill = function(ev) {
      $mdDialog.show({
          controller: KillDialogController,
          templateUrl: '/js/modules/containers/views/container.kill.dialog.tpl.html',
          locals: {
            parentScope: $scope
          },
          targetEvent: ev,
        })
        .then(function(running) {
          $scope.container.State.Running = running;
          $scope.container.State.Pid = 0;
        });
    };
  }

  DestoryDialogController.$inject = ['$scope', '$location', '$mdDialog', 'Containers', 'parentScope'];

  function DestoryDialogController($scope, $location, $mdDialog, Containers, parentScope) {
    $scope.container = parentScope.container;
    $scope.containerShortId = parentScope.containerShortId;

    $scope.cancel = function() {
      $mdDialog.cancel();
    };

    $scope.params = {
      force: false,
      v: false
    };

    $scope.content = '';

    $scope.ok = function() {
      Containers.delete({
          Id: $scope.containerShortId,
          force: $scope.params.force,
          v: $scope.params.v
        },
        null,
        function() {
          $mdDialog.hide();
          $location.path('/containers');
        },
        function(e) {
          if (e.status === 404) {
            $mdDialog.hide();
            $location.path('/containers');
            return;
          }
          $scope.content = e.data;
        }
      );
    };
  }

  RunningDialogController.$inject = ['$scope', '$location', '$mdDialog', 'parentScope', 'ContainerActions'];

  function RunningDialogController($scope, $location, $mdDialog, parentScope, ContainerActions) {
    $scope.container = parentScope.container;
    $scope.action = parentScope.container.State.Running ? 'stop' : 'start';
    $scope.isRestart = false;
    $scope.containerShortId = parentScope.containerShortId;

    $scope.cancel = function() {
      $mdDialog.cancel();
    };

    $scope.params = {
      t: ''
    };

    $scope.change = function(isRestart) {
      if (isRestart) {
        $scope.preAction = $scope.action;
        $scope.action = 'restart';
      } else {
        $scope.action = $scope.preAction;
      }
    };

    $scope.content = '';

    $scope.ok = function() {
      ContainerActions.update({
          Id: $scope.containerShortId,
          action: $scope.action
        },
        $scope.params,
        function() {
          var running = !$scope.container.State.Running;
          if ($scope.action == 'restart') {
            running = true;
          }
          $mdDialog.hide(running);
        },
        function(e) {
          if (e.status === 304) {
            var running = !$scope.container.State.Running;
            $mdDialog.hide(running);
          } else {
            $scope.content = e.data;
          }
        });
    };
  }

  PausedDialogController.$inject = ['$scope', '$location', '$mdDialog', 'parentScope', 'ContainerActions'];

  function PausedDialogController($scope, $location, $mdDialog, parentScope, ContainerActions) {
    $scope.container = parentScope.container;
    $scope.action = parentScope.container.State.Paused ? 'unpause' : 'pause';
    $scope.isRestart = false;
    $scope.containerShortId = parentScope.containerShortId;

    $scope.cancel = function() {
      $mdDialog.cancel();
    };

    $scope.content = '';

    $scope.ok = function() {
      ContainerActions.update({
        Id: $scope.containerShortId,
        action: $scope.action
      }, function(data) {
        var paused = !$scope.container.State.Paused;
        $mdDialog.hide(paused);
      }, function(e) {
        $scope.content = e.data;
      });
    };
  }

  ContainerLogsController.$inject = ['$scope', '$stateParams', 'ContainerActions'];

  function ContainerLogsController($scope, $stateParams, ContainerActions) {
    $scope.containerShortId = $stateParams.Id;
    $scope.queryParams = ContainerActions.logsQueryParams;

    $scope.fetch = function(Id, queryParams) {
      var params = angular.copy(queryParams, {});
      params.Id = Id;
      ContainerActions.logs(params, function(data) {
        $scope.logs = data.text || '';
      });
    };

    $scope.fetch($scope.containerShortId, $scope.queryParams);

    $scope.search = function() {
      $scope.fetch($scope.containerShortId, $scope.queryParams);
    };

    $scope.scrollToEnd = function($ev) {
      var logContent = angular.element($ev.currentTarget).parent().parent()[0];
      if (logContent) {
        logContent.scrollTop = logContent.scrollHeight;
      }
    };
  }

  KillDialogController.$inject = ['$scope', '$mdDialog', 'parentScope', 'ContainerActions'];

  function KillDialogController($scope, $mdDialog, parentScope, ContainerActions) {
    $scope.container = parentScope.container;
    $scope.containerShortId = parentScope.containerShortId;
    $scope.action = 'kill';

    $scope.params = {
      signal: ''
    };

    $scope.content = '';

    $scope.cancel = function() {
      $mdDialog.cancel();
    };

    $scope.ok = function() {
      ContainerActions.update({
          Id: $scope.containerShortId,
          action: $scope.action
        },
        $scope.params,
        function(data) {
          $mdDialog.hide(false);
        },
        function(e) {
          $scope.content = e.data;
        });
    };
  }

  ContainerTopController.$inject = ['$scope', '$stateParams', 'ContainerActions'];

  function ContainerTopController($scope, $stateParams, ContainerActions) {
    $scope.containerShortId = $stateParams.Id;
    $scope.action = 'top';

    $scope.queryParams = {
      ps_args: ''
    };

    $scope.fetch = function() {
      ContainerActions.get({
          Id: $scope.containerShortId,
          action: $scope.action,
          ps_args: $scope.queryParams.ps_args
        },
        function(data) {
          $scope.Titles = data.Titles;
          $scope.Processes = data.Processes;
        },
        function(data) {}
      );
    };

    $scope.fetch();

    $scope.search = function() {
      $scope.fetch();
    };

  }

})();


text:
id: bad88fee1348bd9aedf08825
title: Adjust the Padding of an Element
challengeType: 0
videoUrl: 'https://scrimba.com/c/cED8ZC2'
forumTopicId: 301083
dashedName: adjust-the-padding-of-an-element
---

# --description--

Now let's put our Cat Photo App away for a little while and learn more about styling HTML.

You may have already noticed this, but all HTML elements are essentially little rectangles.

Three important properties control the space that surrounds each HTML element: `padding`, `border`, and `margin`.

An element's `padding` controls the amount of space between the element's content and its `border`.

Here, we can see that the blue box and the red box are nested within the yellow box. Note that the red box has more `padding` than the blue box.

When you increase the blue box's `padding`, it will increase the distance (`padding`) between the text and the border around it.

# --instructions--

Change the `padding` of your blue box to match that of your red box.

# --hints--

Your `blue-box` class should give elements `20px` of `padding`.

```js
assert($('.blue-box').css('padding-top') === '20px');
```

# --seed--

## --seed-contents--

```html
<style>
  .injected-text {
    margin-bottom: -25px;
    text-align: center;
  }

  .box {
    border-style: solid;
    border-color: black;
    border-width: 5px;
    text-align: center;
  }

  .yellow-box {
    background-color: yellow;
    padding: 10px;
  }

  .red-box {
    background-color: crimson;
    color: #fff;
    padding: 20px;
  }

  .blue-box {
    background-color: blue;
    color: #fff;
    padding: 10px;
  }
</style>
<h5 class="injected-text">margin</h5>

<div class="box yellow-box">
  <h5 class="box red-box">padding</h5>
  <h5 class="box blue-box">padding</h5>
</div>
```

# --solutions--

```html
<style>
  .injected-text {
    margin-bottom: -25px;
    text-align: center;
  }

  .box {
    border-style: solid;
    border-color: black;
    border-width: 5px;
    text-align: center;
  }

  .yellow-box {
    background-color: yellow;
    padding: 10px;
  }

  .red-box {
    background-color: crimson;
    color: #fff;
    padding: 20px;
  }

  .blue-box {
    background-color: blue;
    color: #fff;
    padding: 20px;
  }
</style>
<h5 class="injected-text">margin</h5>

<div class="box yellow-box">
  <h5 class="box red-box">padding</h5>
  <h5 class="box blue-box">padding</h5>
</div>
```


text:
/* jshint browser: true */
/* jshint unused: false */
/* global describe, beforeEach, afterEach, it, */
/* global spyOn, expect*/
/* global templateEngine, $, uiMatchers*/
(function () {
  'use strict';

  describe('Cluster Database View', function () {
    var view, div, colView, colCol, server;

    beforeEach(function () {
      server = 'pavel';
      div = document.createElement('div');
      div.id = 'clusterDatabases';
      document.body.appendChild(div);
      colView = {
        render: function () {},
        unrender: function () {}
      };
      colCol = {
        __id: 'refId'
      };
      spyOn(window, 'ClusterCollectionView').andReturn(colView);
      spyOn(window, 'ClusterCollections').andReturn(colCol);
      uiMatchers.define(this);
    });

    afterEach(function () {
      document.body.removeChild(div);
    });

    describe('initialization', function () {
      it('should create a Cluster Collection View', function () {
        view = new window.ClusterDatabaseView({
          collection: {}
        });
        expect(window.ClusterCollections).toHaveBeenCalled();
        expect(window.ClusterCollectionView).toHaveBeenCalledWith({
          collection: colCol
        });
      });
    });

    describe('rendering', function () {
      var db1, db2, db3, databases, dbCol,
        checkButtonContent = function (db, cls) {
          var btn = document.getElementById(db.name);
          expect(btn).toBeOfClass('btn');
          expect(btn).toBeOfClass('btn-server');
          expect(btn).toBeOfClass('database');
          expect(btn).toBeOfClass('btn-' + cls);
          expect($(btn).text()).toEqual(db.name);
      };

      beforeEach(function () {
        spyOn(colView, 'render');
        spyOn(colView, 'unrender');
        db1 = {
          name: '_system',
          status: 'ok'
        };
        db2 = {
          name: 'myDatabase',
          status: 'warning'
        };
        db3 = {
          name: 'otherDatabase',
          status: 'critical'
        };
        databases = [
          db1,
          db2,
          db3
        ];
        dbCol = {
          getList: function () {
            return databases;
          }
        };
        view = new window.ClusterDatabaseView({
          collection: dbCol
        });
        view.render(server);
      });

      it('should not render the Server view', function () {
        expect(colView.render).not.toHaveBeenCalled();
        expect(colView.unrender).toHaveBeenCalled();
      });

      it('should render the ok database', function () {
        checkButtonContent(db1, 'success');
      });

      it('should render the warning database', function () {
        checkButtonContent(db2, 'warning');
      });

      it('should render the error database', function () {
        checkButtonContent(db3, 'danger');
      });

      it('should offer an unrender function', function () {
        colView.unrender.reset();
        view.unrender();
        expect($(div).html()).toEqual('');
        expect(colView.unrender).toHaveBeenCalled();
      });

      describe('user actions', function () {
        var db;

        it('should be able to navigate to _system', function () {
          db = '_system';
          $('#' + db).click();
          expect(colView.render).toHaveBeenCalledWith(db, server);
        });

        it('should be able to navigate to myDatabase', function () {
          db = 'myDatabase';
          $('#' + db).click();
          expect(colView.render).toHaveBeenCalledWith(db, server);
        });

        it('should be able to navigate to otherDatabase', function () {
          db = 'otherDatabase';
          $('#' + db).click();
          expect(colView.render).toHaveBeenCalledWith(db, server);
        });
      });
    });
  });
}());


text:
class Organisation < ApplicationRecord
  has_many :child_organisational_relationships,
           foreign_key: :parent_organisation_id,
           class_name: "OrganisationalRelationship"
  has_many :parent_organisational_relationships,
           foreign_key: :child_organisation_id,
           class_name: "OrganisationalRelationship",
           dependent: :destroy
  has_many :child_organisations,
           through: :child_organisational_relationships
  has_many :parent_organisations,
           through: :parent_organisational_relationships

  has_and_belongs_to_many :extra_sites,
                          join_table: "organisations_sites",
                          class_name: "Site"

  has_many :sites
  has_many :hosts, through: :sites
  has_many :mappings, through: :sites

  validates :whitehall_slug, presence: true
  validates :whitehall_slug, uniqueness: true
  validates :title, presence: true
  validates :content_id, presence: true

  # We have two ways of joining a site to an org:
  # 1. By the site's FK relationship to organisations
  # 2. Through the many-to-many organisations_sites
  #
  # UNION these two ways in an INNER JOIN to pretend that the FK relationship
  # is in fact a row in organisations_sites.
  scope :with_sites,
        lambda {
          select("organisations.*, COUNT(*) as site_count")
          .joins('
      INNER JOIN (
        SELECT organisation_id, site_id FROM organisations_sites
        UNION
        SELECT s.organisation_id, s.id FROM sites s
      ) AS organisations_sites ON organisations_sites.organisation_id = organisations.id
    ')
          .joins("INNER JOIN sites ON sites.id = organisations_sites.site_id")
          .group("organisations.id") # Postgres will accept a group by primary key
          .having("COUNT(*) > 0")
        }

  # Returns organisations ordered by descending error count across
  # all their sites.
  scope :leaderboard,
        lambda {
          select(
            <<-POSTGRESQL,
        organisations.title,
        organisations.whitehall_slug,
        COUNT(*)                                     AS site_count,
        SUM(site_mapping_counts.mapping_count)       AS mappings_across_sites,
        SUM(unresolved_mapping_counts.mapping_count) AS unresolved_mapping_count,
        SUM(error_counts.error_count)                AS error_count
            POSTGRESQL
          )
          .joins(
            <<-POSTGRESQL,
        INNER JOIN sites
               ON sites.organisation_id = organisations.id
        LEFT JOIN (SELECT sites.id AS site_id,
                          COUNT(*)::integer AS mapping_count
                   FROM   mappings
                          INNER JOIN sites
                                  ON sites.id = mappings.site_id
                   GROUP  BY sites.id) site_mapping_counts ON site_mapping_counts.site_id = sites.id
        LEFT JOIN (SELECT sites.id AS site_id,
                          COUNT(*)::integer AS mapping_count
                   FROM   mappings
                          INNER JOIN sites
                                  ON sites.id = mappings.site_id
                   WHERE  mappings.type = 'unresolved'
                   GROUP  BY sites.id) unresolved_mapping_counts ON unresolved_mapping_counts.site_id = sites.id
        LEFT JOIN (SELECT hosts.site_id AS site_id,
                          SUM(count)::integer AS error_count
                   FROM   daily_hit_totals
                          INNER JOIN hosts
                                  ON hosts.id = daily_hit_totals.host_id
                   WHERE  daily_hit_totals.http_status = '404'
                   AND daily_hit_totals.total_on >= (current_date - 30)
                   GROUP BY site_id) AS error_counts ON error_counts.site_id = sites.id
            POSTGRESQL
          )
          .group("organisations.id")
          .order("error_count DESC NULLS LAST")
        }

  def to_param
    whitehall_slug
  end
end


text:
package graph

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"log"
	"regexp"

	"kythe.io/kythe/go/services/graph"
	"kythe.io/kythe/go/services/xrefs"
	"kythe.io/kythe/go/serving/graph/columnar"
	"kythe.io/kythe/go/storage/keyvalue"
	"kythe.io/kythe/go/storage/table"
	"kythe.io/kythe/go/util/keys"
	"kythe.io/kythe/go/util/kytheuri"
	"kythe.io/kythe/go/util/schema"
	"kythe.io/kythe/go/util/schema/facts"

	"bitbucket.org/creachadair/stringset"
	"google.golang.org/protobuf/proto"

	cpb "kythe.io/kythe/proto/common_go_proto"
	gpb "kythe.io/kythe/proto/graph_go_proto"
	gspb "kythe.io/kythe/proto/graph_serving_go_proto"
	scpb "kythe.io/kythe/proto/schema_go_proto"
)

// ColumnarTableKeyMarker is stored within a Kythe columnar table to
// differentiate it from the legacy combined table format.
const ColumnarTableKeyMarker = "kythe:columnar"

// NewService returns an graph.Service backed by the given table.  The format of
// the table with be automatically detected.
func NewService(ctx context.Context, t keyvalue.DB) graph.Service {
	_, err := t.Get(ctx, []byte(ColumnarTableKeyMarker), nil)
	if err == nil {
		log.Println("WARNING: detected a experimental columnar graph table")
		return NewColumnarTable(t)
	}
	return NewCombinedTable(&table.KVProto{t})
}

// NewColumnarTable returns a table for the given columnar graph lookup table.
func NewColumnarTable(t keyvalue.DB) *ColumnarTable { return &ColumnarTable{t} }

// ColumnarTable implements an graph.Service backed by a columnar serving table.
type ColumnarTable struct{ keyvalue.DB }

// Nodes implements part of the graph.Service interface.
func (c *ColumnarTable) Nodes(ctx context.Context, req *gpb.NodesRequest) (*gpb.NodesReply, error) {
	reply := &gpb.NodesReply{Nodes: make(map[string]*cpb.NodeInfo, len(req.Ticket))}

	filters := req.Filter
	if len(filters) == 0 {
		filters = append(filters, "**")
	}
	patterns := xrefs.ConvertFilters(filters)

	for _, ticket := range req.Ticket {
		srcURI, err := kytheuri.Parse(ticket)
		if err != nil {
			return nil, err
		}

		src := srcURI.VName()
		key, err := keys.Append(columnar.EdgesKeyPrefix, src)
		if err != nil {
			return nil, err
		}

		val, err := c.DB.Get(ctx, key, &keyvalue.Options{LargeRead: true})
		if err == io.EOF {
			continue
		} else if err != nil {
			return nil, err
		}

		var idx gspb.Edges_Index
		if err := proto.Unmarshal(val, &idx); err != nil {
			return nil, fmt.Errorf("error decoding index: %v", err)
		}

		if info := filterNode(patterns, idx.Node); len(info.Facts) > 0 {
			reply.Nodes[ticket] = info
		}
	}

	if len(reply.Nodes) == 0 {
		reply.Nodes = nil
	}

	return reply, nil
}

// processTicket loads values associated with the search ticket and adds them to the reply.
func (c *ColumnarTable) processTicket(ctx context.Context, ticket string, patterns []*regexp.Regexp, allowedKinds stringset.Set, reply *gpb.EdgesReply) error {
	srcURI, err := kytheuri.Parse(ticket)
	if err != nil {
		return err
	}

	src := srcURI.VName()
	prefix, err := keys.Append(columnar.EdgesKeyPrefix, src)
	if err != nil {
		return err
	}

	it, err := c.DB.ScanPrefix(ctx, prefix, &keyvalue.Options{LargeRead: true})
	if err != nil {
		return err
	}
	defer it.Close()

	k, val, err := it.Next()
	if err == io.EOF || !bytes.Equal(k, prefix) {
		return nil
	} else if err != nil {
		return err
	}

	// Decode Edges Index
	var idx gspb.Edges_Index
	if err := proto.Unmarshal(val, &idx); err != nil {
		return fmt.Errorf("error decoding index: %v", err)
	}
	if len(patterns) > 0 {
		if info := filterNode(patterns, idx.Node); len(info.Facts) > 0 {
			reply.Nodes[ticket] = info
		}
	}

	edges := &gpb.EdgeSet{Groups: make(map[string]*gpb.EdgeSet_Group)}
	reply.EdgeSets[ticket] = edges
	targets := stringset.New()

	// Main loop to scan over each columnar kv entry.
	for {
		k, val, err := it.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}
		key := string(k[len(prefix):])

		// TODO(schroederc): only parse needed entries
		e, err := columnar.DecodeEdgesEntry(src, key, val)
		if err != nil {
			return err
		}

		switch e := e.Entry.(type) {
		case *gspb.Edges_Edge_:
			edge := e.Edge

			kind := edge.GetGenericKind()
			if kind == "" {
				kind = schema.EdgeKindString(edge.GetKytheKind())
			}
			if edge.Reverse {
				kind = "%" + kind
			}

			if len(allowedKinds) != 0 && !allowedKinds.Contains(kind) {
				continue
			}

			target := kytheuri.ToString(edge.Target)
			targets.Add(target)

			g := edges.Groups[kind]
			if g == nil {
				g = &gpb.EdgeSet_Group{}
				edges.Groups[kind] = g
			}
			g.Edge = append(g.Edge, &gpb.EdgeSet_Group_Edge{
				TargetTicket: target,
				Ordinal:      edge.Ordinal,
			})
		case *gspb.Edges_Target_:
			if len(patterns) == 0 || len(targets) == 0 {
				break
			}

			target := e.Target
			ticket := kytheuri.ToString(target.Node.Source)
			if targets.Contains(ticket) {
				if info := filterNode(patterns, target.Node); len(info.Facts) > 0 {
					reply.Nodes[ticket] = info
				}
			}
		default:
			return fmt.Errorf("unknown Edges entry: %T", e)
		}
	}

	if len(edges.Groups) == 0 {
		delete(reply.EdgeSets, ticket)
	}
	return nil
}

// Edges implements part of the graph.Service interface.
func (c *ColumnarTable) Edges(ctx context.Context, req *gpb.EdgesRequest) (*gpb.EdgesReply, error) {
	// TODO(schroederc): implement edge paging
	reply := &gpb.EdgesReply{
		EdgeSets: make(map[string]*gpb.EdgeSet, len(req.Ticket)),
		Nodes:    make(map[string]*cpb.NodeInfo),

		// TODO(schroederc): TotalEdgesByKind: make(map[string]int64),
	}
	patterns := xrefs.ConvertFilters(req.Filter)
	allowedKinds := stringset.New(req.Kind...)

	for _, ticket := range req.Ticket {
		err := c.processTicket(ctx, ticket, patterns, allowedKinds, reply)
		if err != nil {
			return nil, err
		}
	}

	if len(reply.EdgeSets) == 0 {
		reply.EdgeSets = nil
	}
	if len(reply.Nodes) == 0 {
		reply.Nodes = nil
	}

	return reply, nil
}

func filterNode(patterns []*regexp.Regexp, n *scpb.Node) *cpb.NodeInfo {
	c := &cpb.NodeInfo{Facts: make(map[string][]byte, len(n.Fact))}
	for _, f := range n.Fact {
		name := schema.GetFactName(f)
		if xrefs.MatchesAny(name, patterns) {
			c.Facts[name] = f.Value
		}
	}
	if kind := schema.GetNodeKind(n); kind != "" && xrefs.MatchesAny(facts.NodeKind, patterns) {
		c.Facts[facts.NodeKind] = []byte(kind)
	}
	if subkind := schema.GetSubkind(n); subkind != "" && xrefs.MatchesAny(facts.Subkind, patterns) {
		c.Facts[facts.Subkind] = []byte(subkind)
	}
	return c
}


text:
package issues

import (
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/calebamiles/github-client/comments"
	"github.com/calebamiles/github-client/handle"
	"github.com/calebamiles/github-client/labels"
	"github.com/calebamiles/github-client/milestone"
	"github.com/calebamiles/github-client/state"
)

// An Issue is a composition of a basic issue with comments added
type Issue interface {
	IssueWithoutComments
	Comments() []comments.Comment
}

// An IssueWithoutComments represents an issue as returned by the GitHub API
type IssueWithoutComments interface {
	ID() string
	OpenedBy() string
	Body() string
	CommentsURL() string
	Title() string
	Open() bool
	Labels() []labels.Label
	Milestone() milestone.Milestone
	Assignees() []string
	CreatedAt() time.Time
	UpdatedAt() time.Time
}

// New returns a slice of issues without comments from raw JSON
func New(rawJSON []byte) ([]IssueWithoutComments, error) {
	var issues []IssueWithoutComments
	is := []*issue{}

	err := json.Unmarshal(rawJSON, &is)
	if err != nil {
		log.Printf("failed unmarshalling: \n %s\n", string(rawJSON))
		return nil, err
	}

	for i := range is {
		// get rid of any pull requests returned in the JSON
		if len(is[i].PullRequest) != 0 {
			continue
		}

		assigneesSet := make(map[string]bool)
		if is[i].Assignee.ID != "" {
			assigneesSet[is[i].Assignee.ID] = true
		}

		for j := range is[i].AssigneeList {
			assigneesSet[is[i].AssigneeList[j].ID] = true
		}

		for assignee := range assigneesSet {
			is[i].assignees = append(is[i].assignees, assignee)
		}

		// add the unmarshalled labels
		lbls, loopErr := labels.New(is[i].LabelsList)
		if loopErr != nil {
			return nil, loopErr
		}

		is[i].labels = lbls

		// add the milestone
		m, loopErr := milestone.New(is[i].MilestoneJSON)
		if loopErr != nil {
			return nil, loopErr
		}

		is[i].milestone = m

		issues = append(issues, is[i])
	}

	return issues, nil
}

type issue struct {
	IssueNumber       int             `json:"number"`
	IssueTitle        string          `json:"title"`
	IssueBody         string          `json:"body"`
	StateString       string          `json:"state"`
	Assignee          handle.GitHub   `json:"assignee"`
	AssigneeList      []handle.GitHub `json:"assignees"`
	CreatedTime       time.Time       `json:"created_at"`
	UpdatedTime       time.Time       `json:"updated_at"`
	CommentsURLString string          `json:"comments_url"`
	LabelsList        json.RawMessage `json:"labels"`
	MilestoneJSON     json.RawMessage `json:"milestone"`
	PullRequest       json.RawMessage `json:"pull_request"` // allows us to filter out PR issues which don't belong here
	handle.GitHub     `json:"user"`

	labels    []labels.Label
	milestone milestone.Milestone
	assignees []string
}

func (i *issue) ID() string                     { return fmt.Sprintf("%d", i.IssueNumber) }
func (i *issue) OpenedBy() string               { return i.GitHub.ID }
func (i *issue) Title() string                  { return i.IssueTitle }
func (i *issue) Open() bool                     { return strings.EqualFold(i.StateString, state.Open) }
func (i *issue) Labels() []labels.Label         { return i.labels }
func (i *issue) Milestone() milestone.Milestone { return i.milestone }
func (i *issue) Assignees() []string            { return i.assignees }
func (i *issue) CreatedAt() time.Time           { return i.CreatedTime }
func (i *issue) UpdatedAt() time.Time           { return i.UpdatedTime }
func (i *issue) Body() string                   { return i.IssueBody }
func (i *issue) CommentsURL() string            { return i.CommentsURLString }


text:
$global:DSCModuleName = 'xWebAdministration'
$global:DSCResourceName = 'MSFT_xWebVirtualDirectory'

#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
     (-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
    & git @('clone','https://github.com/PowerShell/DscResource.Tests.git')
}
else
{
    & git @('-C',(Join-Path -Path (Get-Location) -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $Global:DSCModuleName `
    -DSCResourceName $global:DSCResourceName `
    -TestType Unit
#endregion

try
{
    InModuleScope $global:DSCResourceName {
        Describe "$global:DSCResourceName\Test-TargetResource" {
            $MockSite = @{
                Website        = 'contoso.com'
                WebApplication = 'contosoapp'
                Name           = 'shared_directory'
                PhysicalPath   = 'C:\inetpub\wwwroot\shared'
                Ensure         = 'Present'
            }
            $virtualDir = @{
                Name = 'shared_directory'
                PhysicalPath = 'C:\inetpub\wwwroot\shared'
                Count = 1
            }
            Context 'WebAdminstration is not installed' {
                It 'should throw an error if WebAdministration is not installed' {
                    Mock Get-Module -ModuleName $ModuleName { return $null }
                    {
                        Test-TargetResource -Website $MockSite.Website -WebApplication $MockSite.WebApplication -Name $MockSite.Name -PhysicalPath $MockSite.PhysicalPath -Ensure $MockSite.Ensure
                    } | Should Throw 'Please ensure that WebAdministration module is installed.'
                }
            }
            Context 'Directory is Present and PhysicalPath is Correct' {
                It 'should return true' {
                    Mock Get-WebVirtualDirectory { return $virtualDir }
                    Test-TargetResource -Website $MockSite.Website -WebApplication $MockSite.WebApplication -Name $MockSite.Name -PhysicalPath $MockSite.PhysicalPath -Ensure $MockSite.Ensure | Should Be $true
                }
            }

            Context 'Directory is Present and PhysicalPath is incorrect' {
                It 'should return false' {
                    $virtualDir = @{
                        Name = 'shared_directory'
                        PhysicalPath = 'C:\inetpub\wwwroot\shared_wrong'
                        Count = 1
                    }

                    Mock Get-WebVirtualDirectory { return $virtualDir }
                    Test-TargetResource -Website $MockSite.Website -WebApplication $MockSite.WebApplication -Name $MockSite.Name -PhysicalPath $MockSite.PhysicalPath -Ensure $MockSite.Ensure | Should Be $false
                }
            }

            Context 'Directory is Present and PhysicalPath is incorrect' {
                It 'should return false' {
                    $virtualDir = @{
                        Name = 'shared_directory'
                        PhysicalPath = 'C:\inetpub\wwwroot\shared_wrong'
                        Count = 1
                    }

                    Mock Get-WebVirtualDirectory { return $virtualDir }
                    Test-TargetResource -Website $MockSite.Website -WebApplication $MockSite.WebApplication -Name $MockSite.Name -PhysicalPath $MockSite.PhysicalPath -Ensure $MockSite.Ensure | Should Be $false
                }
            }
        }

        Describe "$global:DSCResourceName\Get-TargetResource" {
            Context 'Ensure = Absent and virtual directory does not exist' {
                It 'should return the correct values' {
                    $returnSite = @{
                        Name = 'SomeName'
                        Website = 'Website'
                        WebApplication = 'Application'
                        PhysicalPath = 'PhysicalPath'
                        Ensure = 'Absent'
                    }
                    Mock Test-Dependancies { return $null }
                    Mock Get-WebVirtualDirectory { return $null }
                    $result = Get-TargetResource -Website $returnSite.Website -WebApplication $returnSite.WebApplication -Name $returnSite.Name -PhysicalPath $returnSite.PhysicalPath

                    $result.Name | Should Be $returnSite.Name
                    $result.Website | Should Be $returnSite.Website
                    $result.WebApplication | Should Be $returnSite.WebApplication
                    $result.PhysicalPath | Should Be ''
                    $result.Ensure | Should Be $returnSite.Ensure
                }
            }
            Context 'Ensure = Present and Physical Path Exists' {
                $returnSite = @{
                    Name = 'SomeName'
                    Website = 'Website'
                    WebApplication = 'Application'
                    PhysicalPath = 'PhysicalPath'
                    Ensure = 'Present'
                }

                $returnObj = @{
                    'Name' = $returnSite.Name
                    'PhysicalPath' = $returnSite.PhysicalPath
                    'Count' = 1
                }

                Mock Test-Dependancies { return $null }
                Mock Get-WebVirtualDirectory { return $returnObj }
                $result = Get-TargetResource -Website $returnSite.Website -WebApplication $returnSite.WebApplication -Name $returnSite.Name -PhysicalPath $returnSite.PhysicalPath

                $result.Name | Should Be $returnSite.Name
                $result.Website | Should Be $returnSite.Website
                $result.WebApplication | Should Be $returnSite.WebApplication
                $result.PhysicalPath | Should Be $returnSite.PhysicalPath
                $result.Ensure | Should Be $returnSite.Ensure
            }
        }

        Describe "$global:DSCResourceName\Set-TargetResource" {
            Context 'Ensure = Present and virtual directory does not exist' {
                It 'should call New-WebVirtualDirectory' {
                    $mockSite = @{
                        Name = 'SomeName'
                        Website = 'Website'
                        WebApplication = 'Application'
                        PhysicalPath = 'PhysicalPath'
                    }

                    Mock Test-Dependancies { return $null }
                    Mock New-WebVirtualDirectory { return $null }
                    $null = Set-TargetResource -Website $mockSite.Website -WebApplication $mockSite.WebApplication -Name $mockSite.Name -PhysicalPath $mockSite.PhysicalPath -Ensure 'Present'
                    Assert-MockCalled New-WebVirtualDirectory -Exactly 1
                }
            }

            Context 'Ensure = Present and virtual directory exists' {
                It 'should call Set-ItemProperty' {
                    $mockSite = @{
                        Name = 'SomeName'
                        Website = 'Website'
                        WebApplication = 'Application'
                        PhysicalPath = 'PhysicalPath'
                        Count = 1
                    }

                    Mock Test-Dependancies { return $null }
                    Mock Get-WebVirtualDirectory { return $mockSite }
                    Mock Set-ItemProperty { return $null }
                    $null = Set-TargetResource -Website $mockSite.Website -WebApplication $mockSite.WebApplication -Name $mockSite.Name -PhysicalPath $mockSite.PhysicalPath -Ensure 'Present'
                    Assert-MockCalled Set-ItemProperty -Exactly 1
                }
            }

            Context 'Ensure = Absent' {
                It 'should call Remove-WebVirtualDirectory' {
                    $mockSite = @{
                        Name = 'SomeName'
                        Website = 'Website'
                        WebApplication = 'Application'
                        PhysicalPath = 'PhysicalPath'
                        Count = 1
                    }

                    Mock Test-Dependancies { return $null }
                    Mock Remove-WebVirtualDirectory { return $null }
                    $null = Set-TargetResource -Website $mockSite.Website -WebApplication $mockSite.WebApplication -Name $mockSite.Name -PhysicalPath $mockSite.PhysicalPath -Ensure 'Absent'
                    Assert-MockCalled Remove-WebVirtualDirectory -Exactly 1
                }
            }
        }
    }
}
finally
{
    #region FOOTER
    Restore-TestEnvironment -TestEnvironment $TestEnvironment
    #endregion
}


text:
class Labrador3 < LanguageBadge
  describe "Lab 3",
           skill:             'C#',
           description:       "Have at least three original repos where C# is the dominant language",
           for:               "having at least three original repos where C# is the dominant language.",
           image_name:        'labrador3.png',
           providers:         :github,
           language_required: "C#",
           number_required:   3,
           weight:            2

end