text:
from decimal import Decimal as D

import datetime

import asyncio

import aiohttp
import dateutil.parser
import requests

from mondo import authorization
from mondo.exceptions import MondoApiException
from mondo.utils import build_url

class MondoApi(object):
    BASE_API_URL = 'https://api.getmondo.co.uk'

    def __init__(self, access_token: str):
        """
        :param access_token: The access token, as returned by the OAuth dance
        """
        self._access_token = access_token

    def _make_request(self, url: str, parameters: dict = None,
                      method: str = 'GET', *args, **kwargs):
        """
        Shortcut for a generic request to the mondo API

        :param url: The URL resource part
        :param parameters: Querystring parameters
        :param method: REST method
        :return: requests.Response
        """
        response = requests.request(
            method=method,
            url=build_url(
                self.BASE_API_URL, url, parameters
            ),
            headers={
                'Authorization': 'Bearer {}'.format(self._access_token)
            }, **kwargs
        )
        if response.ok:
            return response.json()
        raise MondoApiException(response.json()['message'])

    async def _make_async_request(self, url, parameters, method='GET',
                                  *args, **kwargs):

        loop = asyncio.get_event_loop()
        with aiohttp.ClientSession(loop=loop) as session:
            response = await session.request(
                method=method,
                url=build_url(
                    self.BASE_API_URL, url, parameters
                ),
                headers={
                    'Authorization': 'Bearer {}'.format(self._access_token)
                })
            response = await response.json()
        return response

    def refresh_token(self, client_id, client_secret, refresh_token):
        self._access_token, _ = authorization.refresh_access_token(
            client_id, client_secret, refresh_token
        )

class Account(object):
    def __init__(self, id, description, created, client=None, *args, **kwargs):
        self.id = id
        self.description = description
        self.created = dateutil.parser.parse(created)
        self.__client = client

    @property
    def transactions(self):
        return self.list_transactions()

    def __repr__(self):
        return "<Account {} {} ({})>".format(
            self.id, self.description, self.created
        )

    def get_balance(self):
        if self.__client:
            return self.__client.get_balance(account_id=self.id)

    def list_transactions(self, since: datetime.datetime = None,
                          before: datetime.datetime = None,
                          limit: int = None):
        if self.__client:
            return self.__client.list_transactions(
                account_id=self.id, since=since, before=before, limit=limit)

    def list_webhooks(self):
        if self.__client:
            return self.__client.list_webhooks(account_id=self.id)

    def register_webhook(self, url: str):
        if self.__client:
            return self.__client.register_webhook(account_id=self.id, url=url)

class Balance(object):
    def __init__(self, balance, spend_today, currency, generated_at, *args,
                 **kwargs):
        self.amount = Amount(D(balance) / 100, currency)  # it's in pence
        self.spent_today = Amount(D(spend_today) / 100, currency)
        self.currency = currency
        self.generated_at = generated_at

    def __repr__(self):
        return "{} (at {})".format(
            self.amount, self.generated_at)

class Amount(object):
    def __init__(self, value, currency, *args, **kwargs):
        self._value = D(value)
        self._currency = currency

    def __add__(self, other):
        assert self.currency == other.currency, Exception(
            'Different currencies')
        return Amount(self.value + other.value, self.currency)

    def __eq__(self, other):
        return self.value == other.value and self.currency == other.currency

    @property
    def value(self):
        return self._value

    @property
    def currency(self):
        return self._currency

    def __repr__(self):
        return "{:.2f} {}".format(
            self.value, self.currency
        )

class Transaction(object):
    def __init__(self, id, description, amount, currency, created,
                 account_balance, metadata, is_load, settled,
                 local_amount, local_currency, category, attachments,
                 merchant=None, decline_reason=None, client=None,
                 *args, **kwargs):
        self.__client = client
        self.id = id
        self.description = description
        self._amount = Amount(D(amount) / 100, currency)
        self.currency = currency
        self.created = dateutil.parser.parse(created)

        self.attachments = [
            Attachment(**attachment, client=client)
            for attachment in attachments
            ] if attachments else None

        self.merchant = Merchant(**merchant) if isinstance(merchant, dict) else None

        # mondo is UK only for the moment,
        # so you can only have a GBP account currency
        self._account_balance = Amount(D(account_balance) / 100, 'GBP')
        self._local_amount = Amount(D(local_amount / 100), local_currency)
        self.metadata = metadata
        self.is_load = is_load
        self.settled = settled
        self.category = category
        self.decline_reason = decline_reason
        self.emoji = getattr(self.merchant, 'emoji', None)

    @property
    def amount(self):
        return self._amount

    @property
    def account_balance(self):
        return self._account_balance

    @property
    def local_amount(self):
        return self._local_amount

    @property
    def notes(self):
        return self.metadata.get('notes')

    @notes.setter
    def notes(self, value):
        self.add_metadata({'notes': value})

    def add_metadata(self, metadata: dict):
        if self.__client:
            return self.__client.annotate_transaction(self.id, metadata)

    def register_attachment(self, file_url: str, file_type: str):
        if self.__client:
            return self.__client.register_attachment(
                self.id, file_url, file_type
            )

    def __repr__(self):
        return "<Transaction {date:%Y-%m-%d %H:%M} {id} {description} {amount}>".format(
            date=self.created, id=self.id, description=self.description,
            amount=self.amount)

class Merchant(object):
    def __init__(self, id, group_id, name, address, category, logo, emoji,
                 created, metadata, *args, **kwargs):
        self.id = id
        self.group_id = group_id
        self.name = name
        self.address = address
        self.category = category
        self.logo = logo
        self.emoji = emoji
        self.created = created
        self.metadata = metadata

    def __repr__(self):
        return "<Merchant {} ({})>".format(
            self.name, self.category
        )

class Attachment(object):
    def __init__(self, id, user_id, external_id, file_url, file_type, created,
                 client=None, *args, **kwargs):
        self.id = id
        self.user_id = user_id
        self.external_id = external_id
        self.file_url = file_url
        self.file_type = file_type
        self.created = dateutil.parser.parse(created)
        self.__client = client

    def __repr__(self):
        return "<Attachment: {} {} ({}) / {}>".format(
            self.id, self.file_url, self.file_type, self.created
        )

    def deregister(self):
        if self.__client:
            self.__client.deregister_attachment(self.id)

class Webhook(object):
    def __init__(self, id: str, account_id: str, url: str, client=None,
                 *args, **kwargs):
        self.id = id
        self.account_id = account_id
        self.url = url
        self.client = client
        self.active = True

    def delete(self):
        if self.client:
            self.client.delete_webhook(self.id)
            self.active = False
            self.url = None

    def __repr__(self):
        return "<Webhook {} {}>".format(
            self.id, self.url
        )


text:
<?php

final class PhabricatorRepositoryURITestCase
  extends PhabricatorTestCase {

  protected function getPhabricatorTestCaseConfiguration() {
    return array(
      self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
    );
  }

  public function testURIGeneration() {
    $svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN;
    $git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT;
    $hg = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL;

    $user = $this->generateNewTestUser();

    $http_secret = id(new PassphraseSecret())->setSecretData('quack')->save();

    $http_credential = PassphraseCredential::initializeNewCredential($user)
      ->setCredentialType(PassphrasePasswordCredentialType::CREDENTIAL_TYPE)
      ->setProvidesType(PassphrasePasswordCredentialType::PROVIDES_TYPE)
      ->setUsername('duck')
      ->setSecretID($http_secret->getID())
      ->save();

    $repo = PhabricatorRepository::initializeNewRepository($user)
      ->setVersionControlSystem($svn)
      ->setName(pht('Test Repo'))
      ->setCallsign('TESTREPO')
      ->setCredentialPHID($http_credential->getPHID())
      ->save();

    // Test HTTP URIs.

    $repo->setDetail('remote-uri', 'http://example.com/');
    $repo->setVersionControlSystem($svn);

    $this->assertEqual('http://example.com/', $repo->getRemoteURI());
    $this->assertEqual('http://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('http://example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    $repo->setVersionControlSystem($git);

    $this->assertEqual('http://example.com/', $repo->getRemoteURI());
    $this->assertEqual('http://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('http://duck:quack@example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    $repo->setVersionControlSystem($hg);

    $this->assertEqual('http://example.com/', $repo->getRemoteURI());
    $this->assertEqual('http://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('http://duck:quack@example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    // Test SSH URIs.

    $repo->setDetail('remote-uri', 'ssh://example.com/');
    $repo->setVersionControlSystem($svn);

    $this->assertEqual('ssh://example.com/', $repo->getRemoteURI());
    $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('ssh://example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    $repo->setVersionControlSystem($git);

    $this->assertEqual('ssh://example.com/', $repo->getRemoteURI());
    $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('ssh://example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    $repo->setVersionControlSystem($hg);

    $this->assertEqual('ssh://example.com/', $repo->getRemoteURI());
    $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI());
    $this->assertEqual('ssh://example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    // Test Git URIs.

    $repo->setDetail('remote-uri', 'git@example.com:path.git');
    $repo->setVersionControlSystem($git);

    $this->assertEqual('git@example.com:path.git', $repo->getRemoteURI());
    $this->assertEqual('git@example.com:path.git', $repo->getPublicCloneURI());
    $this->assertEqual('git@example.com:path.git',
      $repo->getRemoteURIEnvelope()->openEnvelope());

    // Test SVN "Import Only" paths.

    $repo->setDetail('remote-uri', 'http://example.com/');
    $repo->setVersionControlSystem($svn);
    $repo->setDetail('svn-subpath', 'projects/example/');

    $this->assertEqual('http://example.com/', $repo->getRemoteURI());
    $this->assertEqual(
      'http://example.com/projects/example/',
      $repo->getPublicCloneURI());
    $this->assertEqual('http://example.com/',
      $repo->getRemoteURIEnvelope()->openEnvelope());

  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.calrissian.flowmix.core.model;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.calrissian.flowmix.core.model.op.FlowOp;

public class StreamDef implements Serializable {

    private String name;
    private List<FlowOp> flowOps;
    private boolean stdInput;
    private boolean stdOutput;
    private String[] outputs;

    public StreamDef(String name, List<FlowOp> flowOps, boolean stdInput, boolean stdOutput, String[] outputs) {
      this.name = name;
      this.flowOps = flowOps;
      this.stdInput = stdInput;
      this.stdOutput = stdOutput;
      this.outputs = outputs;
    }

    public String getName() {
        return name;
    }

    public List<FlowOp> getFlowOps() {
        return flowOps;
    }

    public boolean isStdInput() {
      return stdInput;
    }

    public boolean isStdOutput() {
      return stdOutput;
    }

    public String[] getOutputs() {
      return outputs;
    }

    @Override
    public String toString() {
        return "StreamDef{" +
                "name='" + name + '\'' +
                ", flowOps=" + flowOps +
                '}';
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      StreamDef streamDef = (StreamDef) o;

      if (stdInput != streamDef.stdInput) {
        return false;
      }
      if (stdOutput != streamDef.stdOutput) {
        return false;
      }
      if (flowOps != null ? !flowOps.equals(streamDef.flowOps) : streamDef.flowOps != null) {
        return false;
      }
      if (name != null ? !name.equals(streamDef.name) : streamDef.name != null) {
        return false;
      }
      if (!Arrays.equals(outputs, streamDef.outputs)) {
        return false;
      }

      return true;
    }

    @Override
    public int hashCode() {
      int result = name != null ? name.hashCode() : 0;
      result = 31 * result + (flowOps != null ? flowOps.hashCode() : 0);
      result = 31 * result + (stdInput ? 1 : 0);
      result = 31 * result + (stdOutput ? 1 : 0);
      result = 31 * result + (outputs != null ? Arrays.hashCode(outputs) : 0);
      return result;
    }
}


text:
- index.html is about Documentation
- index2.html is about Community


text:
import os
import sys

module_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(module_dir, "..", ".."))

from data.base import get_version
from data.base import setup

setup(
    __file__,
    "essential",
    [
        "booking_excluded.txt",
        "borders_vs_osm.csv",
        "categories_brands.txt",
        "categories_cuisines.txt",
        "categories.txt",
        "classificator.txt",
        "colors.txt",
        "countries_meta.txt",
        "countries_synonyms.csv",
        "countries.txt",
        "external_resources.txt",
        "fonts_blacklist.txt",
        "fonts_whitelist.txt",
        "hierarchy.txt",
        "local_ads_symbols.txt",
        "mapcss-dynamic.txt",
        "mapcss-mapping.csv",
        "mixed_nodes.txt",
        "mixed_tags.txt",
        "mwm_names_en.txt",
        "old_vs_new.csv",
        "patterns.txt",
        "replaced_tags.txt",
        "skipped_elements.json",
        "synonyms.txt",
        "transit_colors.txt",
        "types.txt",
        "ugc_types.csv",
        "unicode_blocks.txt",
        "visibility.txt",
    ],
    install_requires=["omim-data-files=={}".format(get_version())]
)


text:
Control your quadrocopter with JavaScript.

## Requirements

* Arduino board (tested with Arduino Due) and A7105 chip
* [node.js and npm](http://nodejs.org)
* [bower](http://bower.io) (install with `npm install -g bower`)
* [gulp](http://gulpjs.com) (install with `npm install -g gulp`)

## Setup instructions

1. Follow the [instructions to build the transmitter station](http://www.instructables.com/id/Easy-Android-controllable-PC-Interfaceable-Relati/step5/Building-the-Arduino-driven-radio/) with a small modification:
  * instead of 3 wire SPI use 4 wire SPI:
  * skip step 10 "Put an additional wire from the 'SDIO' pin of the A7105 to the 'MISO' pin of the due."
  * **instead wire 'gio1' of the A7105 chip to the 'MISO' port of the arduino due**
  * test some resistor values (as written in the tutorial) - mine didn't work with 22K Ohm, but it works with 10K Ohm

2. Clone this repository

3. Open `arduino/arduino.ino` with the arduino IDE and send it to your arduino board

4. Execute `bower install`, `npm install`, `npm link` and `npm link coptermanager-simple`

5. Run `node start-repl.js`

## Usage

There are 4 ways to interact with the drone:

1. Issue commands in the node.js REPL: start the REPL with `node start-repl.js` and then execute commands like `client.takeoff()`, `client.throttle(30)`, ...
2. Control the drone with your keyboard: open the webapp at [http://localhost:3000/copter/keyboard](http://localhost:3000/copter/keyboard)
3. Upload code in the webapp: open [http://localhost:3000/copter/code](http://localhost:3000/copter/code) in your browser
4. Execute autonomous scripts: see [the examples directory](https://github.com/andihit/coptermanager-simple/tree/master/examples)

## Code example

```js
var coptermanager = require('coptermanager-simple');
var client = new coptermanager.Client({serialport: '/dev/tty.usbmodem1411'});

client.bind(function() {

  client.takeoff()
  .after(5000, function() {
    this.elevator(112);
  })
  .after(1000, function() {
    this.ledOff();
  })
  .after(1000, function() {
    this.land();
  })
  .after(1000, function() {
    this.disconnect();
  });

});
```

[More examples](https://github.com/andihit/coptermanager-simple/tree/master/examples)


text:
namespace cc {

FakeContextProvider::FakeContextProvider()
    : destroyed_(false) {
}

FakeContextProvider::FakeContextProvider(
    const CreateCallback& create_callback)
    : create_callback_(create_callback),
      bound_(false),
      destroyed_(false) {
}

FakeContextProvider::~FakeContextProvider() {}

bool FakeContextProvider::InitializeOnMainThread() {
  DCHECK(!context3d_);

  if (create_callback_.is_null())
    context3d_ = TestWebGraphicsContext3D::Create().Pass();
  else
    context3d_ = create_callback_.Run();
  return context3d_;
}

bool FakeContextProvider::BindToCurrentThread() {
  bound_ = true;
  if (!context3d_->makeContextCurrent()) {
    base::AutoLock lock(destroyed_lock_);
    destroyed_ = true;
    return false;
  }
  return true;
}

WebKit::WebGraphicsContext3D* FakeContextProvider::Context3d() {
  DCHECK(context3d_);
  DCHECK(bound_);

  return context3d_.get();
}
class GrContext* FakeContextProvider::GrContext() {
  DCHECK(context3d_);
  DCHECK(bound_);

  // TODO(danakj): Make a fake GrContext.
  return NULL;
}

void FakeContextProvider::VerifyContexts() {
  DCHECK(context3d_);
  DCHECK(bound_);

  if (context3d_->isContextLost()) {
    base::AutoLock lock(destroyed_lock_);
    destroyed_ = true;
  }
}

bool FakeContextProvider::DestroyedOnMainThread() {
  base::AutoLock lock(destroyed_lock_);
  return destroyed_;
}

}  // namespace cc


text:
@class Item;

@interface FSItemView : FSHintView

@property (nonatomic, strong) Item *item;

- (void)show;

@end


text:
.bc-keypad {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: row wrap;
      flex-flow: row wrap;
  overflow: hidden;
  padding-bottom: .375em;
  text-align: center;
}

@-webkit-keyframes ripple {
  100% {
    opacity: 0;
    -webkit-transform: scale(2.5);
            transform: scale(2.5);
  }
}

@keyframes ripple {
  100% {
    opacity: 0;
    -webkit-transform: scale(2.5);
            transform: scale(2.5);
  }
}

.bc-keypad .angular-ripple {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  display: block;
  position: absolute;
  -webkit-transform: scale(0);
          transform: scale(0);
}

.bc-keypad .angular-ripple.animate {
  -webkit-animation: ripple .3s linear;
          animation: ripple .3s linear;
}

.bc-keypad__key {
  position: relative;
  text-align: center;
  width: calc(100% / 3);
}

.bc-keypad__key::before {
  display: block;
  content: '';
  padding-top: 50%;
  width: 100%;
}

.bc-keypad__key-button {
  background: none;
  background-color: transparent;
  border: 0;
  color: inherit;
  cursor: pointer;
  font-size: 1.4rem;
  line-height: 1.5em;
  outline: 0;
  padding: 2%;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  text-align: center;
  width: 100%;
}

.bc-keypad__key-button:focus {
  outline: 0;
}

.bc-keypad__key-button::after {
  background-color: #ccc;
  content: '';
  display: block;
  height: 1px;
  position: absolute;
  left: 10%;
  right: 10%;
  bottom: 0;
}

.bc-keypad__key-button svg {
  height: 44px;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  width: 50px;
}

.bc-keypad__key-button--icon {
  background-size: 50%;
  background-position: 45% 50%;
  background-repeat: no-repeat;
  border: 0;
  position: relative;
}

.bc-keypad__key-button--backspace {
  fill: inherit;
}

.bc-keypad__key-button--submit {
  fill: inherit;
}

.bc-keypad [angular-ripple] {
  overflow: hidden;
  position: relative;
}

.bc-keypad [angular-ripple].bc-keypad__key-button {
  position: absolute;
}


text:
<!doctype html>

  <title>InferenceLens Graphics Manager</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/bootstrap.min.css">


text:
import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

const WEEK_MILLIS = 7 * 24 * 3600 * 1000;

@Pipe({
  name: 'dynamicDate',
  pure: true,
})
export class DynamicDatePipe extends DatePipe implements PipeTransform {

  // @ts-ignore
  transform(value: Date | string | number, includeTime?: boolean): string | null {
    const now = new Date();
    const date = value instanceof Date ? value : new Date(value);
    let format = includeTime ? 'short' : 'mediumDate';
    if (now.getFullYear() === date.getFullYear() && now.getMonth() === date.getMonth() && now.getDate() === date.getDate()) {
      // Same day
      format = 'shortTime';
    } else if (now.getTime() - date.getTime() < WEEK_MILLIS) {
      // Less than a week ago
      format = includeTime ? 'short' : 'EEE';
    }
    return super.transform(date, format);
  }
}


text:
FOUNDATION_EXPORT double Pods_SVGPlayButton_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SVGPlayButton_ExampleVersionString[];


text:
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0

package org.terasology.engine.core.module;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.junit.jupiter.MockitoExtension;
import org.reflections.Reflections;
import org.terasology.engine.config.flexible.AutoConfig;
import org.terasology.engine.core.PathManager;
import org.terasology.engine.core.PathManagerProvider;
import org.terasology.engine.core.subsystem.EngineSubsystem;
import org.terasology.engine.logic.permission.PermissionSetComponent;
import org.terasology.engine.world.block.structure.AttachSupportRequiredComponent;
import org.terasology.gestalt.module.Module;
import org.terasology.gestalt.module.ModuleEnvironment;
import org.terasology.gestalt.module.ModuleMetadata;
import org.terasology.gestalt.module.resources.EmptyFileSource;
import org.terasology.gestalt.module.sandbox.PermissionProvider;
import org.terasology.gestalt.naming.Name;
import org.terasology.gestalt.naming.Version;
import org.terasology.unittest.stubs.StubSubsystem;

import java.util.Collections;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.when;
import static org.terasology.engine.core.TerasologyConstants.ENGINE_MODULE;

@ExtendWith(PathManagerProvider.class)
@ExtendWith(MockitoExtension.class)
public class ModuleManagerTest {

    ModuleManager manager;
    ModuleEnvironment environment;
    Module engineModule;

    /** Configure a ModuleManager with only the engine module. */
    @BeforeEach
    public void provideEngineModule(PathManager pathManager) {
        when(pathManager.getModulePaths()).thenReturn(Collections.emptyList());
        manager = new ModuleManager("");
        environment = manager.getEnvironment();
        engineModule = environment.get(ENGINE_MODULE);

        // assert we did not load extra modules that may have been laying around.
        assertThat(manager.getRegistry().getModuleIds()).containsExactly(ENGINE_MODULE);
        assertThat(environment.getModuleIdsOrderedByDependencies()).containsExactly(ENGINE_MODULE);
    }

    /** A bare minimum Module not associated with any real code or assets. */
    private Module getEmptyTestModule() {
        return new Module(
                new ModuleMetadata(new Name("EmptyTestModule"), new Version("0.0.1")),
                new EmptyFileSource(),
                Collections.emptyList(),
                new Reflections(),
                (clazz) -> false
        );
    }

    /**
     * Non-API classes are not permitted.
     *

     * Tests against the {@link PermissionProvider} that ModuleManager gives a module.
     *

     * A test failure here may indicate that modules have unrestricted access to engine classes they
     * should not.
     *

     * ⚠ This test passing should not be taken to mean the protections
     * of the sandbox are intact. The PermissionProvider provides only one piece of the logic and
     * is not always the deciding factor.
     *
     * @param disallowedClass A class in {@code org.terasology.engine} not annotated with @API
     *     nor in any package annotated with @API.
     */
    @ParameterizedTest
    @ValueSource(classes = {
            PathManager.class,
            PermissionSetComponent.class
    })
    public void nonApiClassesAreNotPermitted(Class<?> disallowedClass) {
        PermissionProvider permissionProvider = manager.getPermissionProvider(getEmptyTestModule());
        assertFalse(permissionProvider.isPermitted(disallowedClass));
    }

    /**
     * Non-API classes have a module which provides them.
     *

     * There are some classes that are not marked as being part of a public API, but we still expect the
     * {@link ModuleEnvironment} to recognize which module provides them.
     *

     * Test failures of this type can show up in the application as a failure to get a URI for a class,
     * or find a class from a URI, or get a subtype of a class. These are often NullPointerExceptions.
     *
     * @param engineClass A class in {@code org.terasology.engine} not annotated with @API
     *      nor in any package annotated with @API.
     */
    @ParameterizedTest
    @ValueSource(classes = {
            AttachSupportRequiredComponent.class,
            PermissionSetComponent.class
    })
    public void nonApiClassesHaveAModuleWhichProvidesThem(Class<?> engineClass) {
        assertThat(environment.getModuleProviding(engineClass)).isEqualTo(ENGINE_MODULE);
    }

    /**
     * Classes from subsystems are contained in the engine module.
     *

     * Test failures of this type appear as failures to find classes from the subsystem, such as
     * its {@link AutoConfig} class.
     *

     * (This policy may change in the future to better reflect the fact that the set of subsystems
     * is not always the same, and it would be useful to know which classes are provided by which
     * subsystem.)
     * */
    @Test
    public void engineModuleContainsSubsystems() {
        Class<StubSubsystem> subsystem = StubSubsystem.class;
        manager = new ModuleManager("", Collections.singletonList(subsystem));
        environment = manager.getEnvironment();
        engineModule = environment.get(ENGINE_MODULE);

        assertThat(engineModule.getModuleManifest().getSubTypesOf(EngineSubsystem.class)).contains(subsystem);

        assertThat(environment.getSubtypesOf(EngineSubsystem.class)).contains(subsystem);

        assertThat(environment.getModuleProviding(subsystem)).isEqualTo(ENGINE_MODULE);
    }
}


text:
ActiveRecord::Schema.define(version: 20_170_525_054_546) do
  # These are extensions that must be enabled in order to support this database
  enable_extension 'plpgsql'

  create_table 'departments', force: :cascade do |t|
    t.string 'name', null: false
    t.datetime 'created_at', null: false
    t.datetime 'updated_at', null: false
    t.index ['name'], name: 'index_departments_on_name', unique: true
  end

  create_table 'referrals', force: :cascade do |t|
    t.integer 'referral_type', null: false
    t.integer 'prioritization_year', null: false
    t.date 'meeting_date', null: false
    t.string 'agenda_item_number', null: false
    t.string 'title', null: false
    t.text 'recommendation', null: false
    t.string 'sponsors', null: false
    t.bigint 'department_id'
    t.text 'notes'
    t.date 'completed_on'
    t.integer 'first_year_rank'
    t.string 'tracking_number'
    t.date 'date_started'
    t.integer 'staff_time_required'
    t.integer 'cost'
    t.integer 'benefits'
    t.datetime 'created_at', null: false
    t.datetime 'updated_at', null: false
    t.index ['department_id'], name: 'index_referrals_on_department_id'
  end

  add_foreign_key 'referrals', 'departments'
end


text:
using com.lover.astd.common.config;
using System;
using System.Collections.Generic;

namespace com.lover.astd.game.ui.server.impl.economy
{
	internal class StoneServer : LogicServer
	{
        public StoneServer(NewMainForm frm)
		{
			this._mainForm = frm;
			this.ServerName = "stone";
			this.ServerReadableName = "玉石采集";
		}

		public override void renderSettings()
		{
			Dictionary<string, string> config = base.getConfig(this.ServerName);
            _mainForm.chk_get_stone.Checked = (config.ContainsKey("enabled") && config["enabled"].ToLower().Equals("true"));
			if (config.ContainsKey("ratio"))
			{
				int value = 0;
				int.TryParse(config["ratio"], out value);
                _mainForm.num_get_stone.Value = value;
			}
		}

		public override void saveSettings()
		{
			GameConfig expr_0D = base.getConfig();
            expr_0D.setConfig(this.ServerName, "enabled", _mainForm.chk_get_stone.Checked.ToString());
            expr_0D.setConfig(this.ServerName, "ratio", _mainForm.num_get_stone.Value.ToString());
		}

		public override void loadDefaultSettings()
		{
			GameConfig expr_06 = base.getConfig();
			expr_06.setConfig(this.ServerName, "enabled", "true");
			expr_06.setConfig(this.ServerName, "ratio", "50");
			this.renderSettings();
		}
	}
}


text:
package pft.sandbox;

import org.testng.Assert;
import org.testng.annotations.Test;

import javax.swing.text.DefaultEditorKit;

/**
 * Created by asus-1 on 27.12.2016.
 */
public class SquareTests {
  @Test

  public void testArea(){
   Square s = new Square(5);
 // assert s.area() == 25;
    Assert.assertEquals(s.area(), 25.0);

  }
}


text:
<!DOCTYPE html>
<html lang="en">
<body>
   <!-- if this file exists then Jet-Net uploading enabled -->
</body>
</html>


text:
class AddAuthlogicRpxMigrationGenerator < Rails::Generator::Base
  def manifest

    record do |m|

      m.migration_template template_name, 'db/migrate', :assigns => {
        :user_model_base => user_model_base,
        :user_model => user_model,
        :user_model_collection => user_model_collection
      }
    end
  end

  def file_name
    "add_authlogic_rpx_migration"
  end

  protected
    # Override with your own usage banner.
    def banner
      "Usage: #{$0} #{spec.name} [options] [mapping:mapping_mode] [user_model:model_name]"
    end

    attr_writer :params
    def params
      @params ||= {"mapping" => "internal", "user_model" => "User"}.merge( Hash[*(@args.collect { |arg| arg.split(":") }.flatten)] )
    end

    def user_model_base
      params['user_model'].singularize.downcase
    end
    def user_model
      params['user_model'].singularize.capitalize
    end
    def user_model_collection
      params['user_model'].pluralize.downcase
    end
    def mapping
      params['mapping']
    end
    def template_name
      mapping == 'none' ? 'migration_no_mapping.rb' : 'migration_internal_mapping.rb'
    end
end


text:
// ==========================================================
// ZLib library interface
//
// Design and implementation by
// - Floris van den Berg (flvdberg@wxs.nl)
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================

#include "../ZLib/zlib.h"
#include "FreeImage.h"
#include "Utilities.h"
#include "../ZLib/zutil.h"	/* must be the last header because of error C3163 in VS2008 (_vsnprintf defined in stdio.h) */

/**
Compresses a source buffer into a target buffer, using the ZLib library.
Upon entry, target_size is the total size of the destination buffer,
which must be at least 0.1% larger than source_size plus 12 bytes.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the compressed buffer, returns 0 if an error occured
@see FreeImage_ZLibUncompress
*/
DWORD DLL_CALLCONV
FreeImage_ZLibCompress(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size;

	int zerr = compress(target, &dest_len, source, source_size);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
		case Z_OK:
			return dest_len;
	}

	return 0;
}

/**
Decompresses a source buffer into a target buffer, using the ZLib library.
Upon entry, target_size is the total size of the destination buffer,
which must be large enough to hold the entire uncompressed data.
The size of the uncompressed data must have been saved previously by the compressor
and transmitted to the decompressor by some mechanism outside the scope of this
compression library.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the uncompressed buffer, returns 0 if an error occured
@see FreeImage_ZLibCompress
*/
DWORD DLL_CALLCONV
FreeImage_ZLibUncompress(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size;

	int zerr = uncompress(target, &dest_len, source, source_size);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
		case Z_DATA_ERROR:	// input data was corrupted
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
		case Z_OK:
			return dest_len;
	}

	return 0;
}

/**
Compresses a source buffer into a target buffer, using the ZLib library.
On success, the target buffer contains a GZIP compatible layout.
Upon entry, target_size is the total size of the destination buffer,
which must be at least 0.1% larger than source_size plus 24 bytes.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the compressed buffer, returns 0 if an error occured
@see FreeImage_ZLibCompress
*/
DWORD DLL_CALLCONV
FreeImage_ZLibGZip(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size - 12;
	DWORD crc = crc32(0L, NULL, 0);

    // set up header (stolen from zlib/gzio.c)
    sprintf((char *)target, "%c%c%c%c%c%c%c%c", 0x1f, 0x8b,
         Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/);
    int zerr = compress2(target + 8, &dest_len, source, source_size, Z_BEST_COMPRESSION);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
        case Z_OK: {
            // patch header, setup crc and length (stolen from mod_trace_output)
            BYTE *p = target + 8; *p++ = 2; *p = OS_CODE; // xflags, os_code
 	        crc = crc32(crc, source, source_size);
	        memcpy(target + 4 + dest_len, &crc, 4);
	        memcpy(target + 8 + dest_len, &source_size, 4);
            return dest_len + 12;
        }
	}
	return 0;
}

/**
Decompresses a gzipped source buffer into a target buffer, using the ZLib library.
Upon entry, target_size is the total size of the destination buffer,
which must be large enough to hold the entire uncompressed data.
The size of the uncompressed data must have been saved previously by the compressor
and transmitted to the decompressor by some mechanism outside the scope of this
compression library.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the uncompressed buffer, returns 0 if an error occured
@see FreeImage_ZLibGZip
*/

static int get_byte(z_stream *stream) {
    if (stream->avail_in <= 0) return EOF;
    stream->avail_in--;
    return *(stream->next_in)++;
}

static int checkheader(z_stream *stream) {
    int flags, c;
    DWORD len;

    if (get_byte(stream) != 0x1f || get_byte(stream) != 0x8b)
        return Z_DATA_ERROR;
    if (get_byte(stream) != Z_DEFLATED || ((flags = get_byte(stream)) & 0xE0) != 0)
        return Z_DATA_ERROR;
    for (len = 0; len < 6; len++) (void)get_byte(stream);

    if ((flags & 0x04) != 0) { /* skip the extra field */
        len  =  (DWORD)get_byte(stream);
        len += ((DWORD)get_byte(stream)) << 8;
        /* len is garbage if EOF but the loop below will quit anyway */
        while (len-- != 0 && get_byte(stream) != EOF) ;
    }
    if ((flags & 0x08) != 0) { /* skip the original file name */
        while ((c = get_byte(stream)) != 0 && c != EOF) ;
    }
    if ((flags & 0x10) != 0) {   /* skip the .gz file comment */
        while ((c = get_byte(stream)) != 0 && c != EOF) ;
    }
    if ((flags & 0x02) != 0) {  /* skip the header crc */
        for (len = 0; len < 2; len++) (void)get_byte(stream);
    }
    return Z_OK;
}

DWORD DLL_CALLCONV
FreeImage_ZLibGUnzip(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
    DWORD src_len  = source_size;
    DWORD dest_len = target_size;
    int   zerr     = Z_DATA_ERROR;

    if (src_len > 0) {
        z_stream stream;
        memset(&stream, 0, sizeof (stream));
        if ((zerr = inflateInit2(&stream, -MAX_WBITS)) == Z_OK) {
            stream.next_in  = source;
            stream.avail_in = source_size;

            stream.next_out  = target;
            stream.avail_out = target_size;

            if ((zerr = checkheader(&stream)) == Z_OK) {
                zerr = inflate (&stream, Z_NO_FLUSH);
                dest_len = target_size - stream.avail_out;

                if (zerr == Z_OK || zerr == Z_STREAM_END)
                    inflateEnd(&stream);
            }
        }
    }
    if (zerr != Z_OK && zerr != Z_STREAM_END) {
        FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
        return 0;
    }
    return dest_len;
}

/**
Update a running crc from source and return the updated crc, using the ZLib library.
If source is NULL, this function returns the required initial value for the crc.

@param crc Running crc value
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the new crc value
*/
DWORD DLL_CALLCONV
FreeImage_ZLibCRC32(DWORD crc, BYTE *source, DWORD source_size) {

    return crc32(crc, source, source_size);
}


text:
import {Column} from "../../../src/decorator/columns/Column";
import {TableInheritance} from "../../../src/decorator/entity/TableInheritance";
import {DiscriminatorColumn} from "../../../src/decorator/columns/DiscriminatorColumn";
import {Entity} from "../../../src/decorator/entity/Entity";
import {PrimaryColumn} from "../../../src/decorator/columns/PrimaryColumn";

// todo: some things left to do:
// * check how it works when is join (conditions are not added in the joins right now)

@Entity("sample28_person")
@TableInheritance("single-table")
@DiscriminatorColumn({ name: "type", type: "string"})
export abstract class Person {

    @PrimaryColumn("int")
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

}


text:
<!doctype html>

        <meta charset="utf-8">

        <title>NDF 2015 - UC & Catalyst</title>

        <meta name="author" content="Catalyst">

        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

        <link rel="stylesheet" href="css/reveal.css">
        <link rel="stylesheet" href="css/theme/catalyst.css" id="theme">

        <link rel="stylesheet" href="lib/css/catalyst-syntax.css">

Catalyst

Extending QuakeStudies for a Learning Legacy

                    Presented by Dr Chris Thomson (UC) & Jonathan Hunt (Catalyst)

What's it all about?

A project to capture and disseminate lessons learned from SCIRT's rebuild of Christchurch's "horizontal infrastructure"

Not so horizontal...

                 SCIRT's remit includes repairing wastewater, stormwater and freshwater infrastructure, roads, bridges and supporting structures for these (eg retaining walls).

Who's involved?

SCIRT - documenting innovative work

QuakeStudies - preservation & flexible architecture

QuakeCentre - project management & key stakeholders

Resilient Organisations - external research group

Catalyst IT - found solutions & wrote the code

Learning Legacy concept

Capture important information before it is lost

Develop a digital archiving programme for rebuild agencies

CEISMIC Learning Legacy Scholarships

An opportunity to open-source and develop the platform for future

QuakeStudies

quakestudies.canterbury.ac.nz

More than 88,000 items public items contributed to CEISMIC:

~41,000 newspaper pages

~39,000 images

~500 videos

~120 audio files

Lots of other content: graphics, composite images, research presentations, blogs, etc.

Site design and development

Audience analysis

Design

Themes

Stories

QS data structure (simplified)

Not shown: Format, Audience, Role, Event, etc.

                Full diagram .gif, ontology owl

Fedora Commons (simplified)

Mapping from LL to QuakeStudies

Discovery & Analysis phase

Want responsive site with mapping to QuakeStudies

Options:

Lightweight wrapper, e.g. Django, node.js

Extend Remote Entities approach

Islandora

Chosen path: extend Remote Entities approach

QS, LL Architecture

Drupal Remote Entities

Fedora Commons REST API -> wrapper (Tuque from Islandora) -> Clients module

Declare to Drupal as remote entity: fedoraentity.module, bundles: Collection, Object, Part, License

In QuakeStudies: top collection/735 #

match: Communications and Community (collection:741 # -> /theme/communications-and-community)

Web Service Clients: config

local Solr

Some fields streamed from QuakeStudies: e.g. videos

Lessons

Multi-stakeholder consortiums are hard work

Re-use is possible: of architecture, code

Open source communities delivering increasingly powerful components

Big problems can equal big opportunities to experiment and learn

Thanks to our collaborators...

and of course...

What's next?

The collection is available at quakestudies.canterbury.ac.nz

We're working to put the code on Github

www.scirtlearninglegacy.org.nz is coming...eventually.

Image attributions

Kenton Chambers, 21 February 2011, J Hunt, CC BY NZ

Medway Street Bridge, 13 September 2010 #P9130020 CC BY-NC-SA NZ

Wayne Youle's mural, 'I Seem to Have Temporarily Misplaced My Sense of Humour', https://quakestudies.canterbury.ac.nz/store/part/95254 CC-BY-NC-ND

Sheet piling reinforces a wastewater main trench in Woodham Road, Wainoni, ©SCIRT

More technical resources

Florian Loretan http://www.wunderkraut.com/blog/remote-entities-in-drupal-7/2012-10-25

http://colans.net/blog/integrating-remote-data-drupal-7-and-exposing-it-views

Remote Entities: Standardizing External Integrations in Drupal (Dave Bailey, Sep 2015)

Early work for Fedora Commons and Drupal 8 by David Evans

Remote entities in Drupal 8 via External Entities

Thanks

Slides: https://github.com/kayakr/ndf2015

                  This will only display in the notes window.

Who are we?

Chris Thomson

Lecturer in English and Digital Humanities

CEISMIC Programme Manager

Jonathan Hunt

Developer

List item

Who are we?

Large title

                    This will only display in the notes window.

Fragmented list

List item

List item

List item

Title (press down to see vertical slides)

Paragraph

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.

Blockquote

                              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.

Nested lists

One

Two

Three

Nested One

Nested Two

open source technologists


text:
package javax.xml.ws.handler;
import java.util.Map;

/**
 * The interface MessageContext abstracts the message
 * context that is processed by a handler in the handle
 * method.
 *
 *
The MessageContext interface provides methods to
 * manage a property set. MessageContext properties
 * enable handlers in a handler chain to share processing related
 * state.
 *
 * @since JAX-WS 2.0
 */
public interface MessageContext extends Map<String, Object> {

    /**
     * Standard property: message direction, true for
     * outbound messages, false for inbound.
     *
Type: boolean
     */
    public static final String MESSAGE_OUTBOUND_PROPERTY =
            "javax.xml.ws.handler.message.outbound";

    /**
     * Standard property: Map of attachments to a message for the inbound
     * message, key is  the MIME Content-ID, value is a DataHandler.
     *
Type: java.util.Map<String,DataHandler>
     */
    public static final String INBOUND_MESSAGE_ATTACHMENTS =
            "javax.xml.ws.binding.attachments.inbound";

    /**
     * Standard property: Map of attachments to a message for the outbound
     * message, key is the MIME Content-ID, value is a DataHandler.
     *
Type: java.util.Map<String,DataHandler>
     */
    public static final String OUTBOUND_MESSAGE_ATTACHMENTS =
            "javax.xml.ws.binding.attachments.outbound";

    /**
     * Standard property: input source for WSDL document.
     *
Type: org.xml.sax.InputSource
     */
    public static final String WSDL_DESCRIPTION =
            "javax.xml.ws.wsdl.description";

    /**
     * Standard property: name of WSDL service.
     *
Type: javax.xml.namespace.QName
     */
    public static final String WSDL_SERVICE =
            "javax.xml.ws.wsdl.service";

    /**
     * Standard property: name of WSDL port.
     *
Type: javax.xml.namespace.QName
     */
    public static final String WSDL_PORT =
            "javax.xml.ws.wsdl.port";

    /**
     * Standard property: name of wsdl interface (2.0) or port type (1.1).
     *
Type: javax.xml.namespace.QName
     */
    public static final String WSDL_INTERFACE =
            "javax.xml.ws.wsdl.interface";

    /**
     * Standard property: name of WSDL operation.
     *
Type: javax.xml.namespace.QName
     */
    public static final String WSDL_OPERATION =
            "javax.xml.ws.wsdl.operation";

    /**
     * Standard property: HTTP response status code.
     *
Type: java.lang.Integer
     */
    public static final String HTTP_RESPONSE_CODE =
            "javax.xml.ws.http.response.code";

    /**
     * Standard property: HTTP request headers.
     *
Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>>
     */
    public static final String HTTP_REQUEST_HEADERS =
            "javax.xml.ws.http.request.headers";

    /**
     * Standard property: HTTP response headers.
     *
Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>>
     */
    public static final String HTTP_RESPONSE_HEADERS =
            "javax.xml.ws.http.response.headers";

    /**
     * Standard property: HTTP request method.
     *
Type: java.lang.String
     */
    public static final String HTTP_REQUEST_METHOD =
            "javax.xml.ws.http.request.method";

    /**
     * Standard property: servlet request object.
     *
Type: javax.servlet.http.HttpServletRequest
     */
    public static final String SERVLET_REQUEST =
            "javax.xml.ws.servlet.request";

    /**
     * Standard property: servlet response object.
     *
Type: javax.servlet.http.HttpServletResponse
     */
    public static final String SERVLET_RESPONSE =
            "javax.xml.ws.servlet.response";

    /**
     * Standard property: servlet context object.
     *
Type: javax.servlet.ServletContext
     */
    public static final String SERVLET_CONTEXT =
            "javax.xml.ws.servlet.context";

    /**
     * Standard property: Query string for request.
     *
Type: String
     **/
    public static final String QUERY_STRING =
            "javax.xml.ws.http.request.querystring";

    /**
     * Standard property: Request Path Info
     *
Type: String
     */
    public static final String PATH_INFO =
            "javax.xml.ws.http.request.pathinfo";

    /**
     * Standard property: WS Addressing Reference Parameters.
     * The list MUST include all SOAP headers marked with the
     * wsa:IsReferenceParameter="true" attribute.
     *
Type: List<Element>
     *
     * @since JAX-WS 2.1
     */
    public static final String REFERENCE_PARAMETERS =
            "javax.xml.ws.reference.parameters";

    /**
     * Property scope. Properties scoped as APPLICATION are
     * visible to handlers,
     * client applications and service endpoints; properties scoped as
     * HANDLER
     * are only normally visible to handlers.
     */
    public enum Scope {APPLICATION, HANDLER};

    /**
     * Sets the scope of a property.
     *
     * @param name Name of the property associated with the
     *             MessageContext
     * @param scope Desired scope of the property
     * @throws java.lang.IllegalArgumentException if an illegal
     *             property name is specified
     */
    public void setScope(String name,  Scope scope);

    /**
     * Gets the scope of a property.
     *
     * @param name Name of the property
     * @return Scope of the property
     * @throws java.lang.IllegalArgumentException if a non-existant
     *             property name is specified
     */
    public Scope getScope(String  name);
}


text:
The contrib directory contains helper modules for Faiss for various tasks.

## Code structure

The contrib directory gets compiled in the module faiss.contrib.
Note that although some of the modules may depend on additional modules (eg. GPU Faiss, pytorch, hdf5), they are not necessarily compiled in to avoid adding dependencies. It is the user's responsibility to provide them.

In contrib, we are progressively dropping python2 support.

## List of contrib modules

### rpc.py

A very simple Remote Procedure Call library, where function parameters and results are pickled, for use with client_server.py

### client_server.py

The server handles requests to a Faiss index. The client calls the remote index.
This is mainly to shard datasets over several machines, see [Distributed index](https://github.com/facebookresearch/faiss/wiki/Indexes-that-do-not-fit-in-RAM#distributed-index)

### ondisk.py

Encloses the main logic to merge indexes into an on-disk index.
See [On-disk storage](https://github.com/facebookresearch/faiss/wiki/Indexes-that-do-not-fit-in-RAM#on-disk-storage)

### exhaustive_search.py

Computes the ground-truth search results for a dataset that possibly does not fit in RAM. Uses GPU if available.
Tested in `tests/test_contrib.TestComputeGT`

### torch_utils.py

Interoperability functions for pytorch and Faiss: Importing this will allow pytorch Tensors (CPU or GPU) to be used as arguments to Faiss indexes and other functions. Torch GPU tensors can only be used with Faiss GPU indexes. If this is imported with a package that supports Faiss GPU, the necessary stream synchronization with the current pytorch stream will be automatically performed.

Numpy ndarrays can continue to be used in the Faiss python interface after importing this file. All arguments must be uniformly either numpy ndarrays or Torch tensors; no mixing is allowed.

Tested in `tests/test_contrib_torch.py` (CPU) and `gpu/test/test_contrib_torch_gpu.py` (GPU).

### inspect_tools.py

Functions to inspect C++ objects wrapped by SWIG. Most often this just means reading
fields and converting them to the proper python array.

### ivf_tools.py

A few functions to override the coarse quantizer in IVF, providing additional flexibility for assignment.

### datasets.py

(may require h5py)

Definition of how to access data for some standard datasets.

### factory_tools.py

Functions related to factory strings.

### evaluation.py

A few non-trivial evaluation functions for search results

### clustering.py

Contains:

- a Python implementation of kmeans, that can be used for special datatypes (eg. sparse matrices).

- a 2-level clustering routine and a function that can apply it to train an IndexIVF


text:
layout: "border-collie-videos-individual"
permalink: "happy-border-collie"
title:  "Happy Border Collie"
category: "videos"
date: "2016-12-18 17:00:00"
video: "https://www.youtube.com/embed/f51On-OQbqQ"
id-youtube: "f51On-OQbqQ"
video-description: "Si pensabas que los Borders no son unos buenos bailarines estabas muy equivocados. Se lanzan como el que más a ritmo de Pharrell Williams."
source: "Youtube"
---


text:
<?php

    if ( ! defined( 'ABSPATH' ) ) {
        exit;
    }

    if ( class_exists( 'FS_EDD_Client_Migration_v1' ) ) {
        return;
    }

    // Include abstract class.
    require_once dirname( __FILE__ ) . '/class-fs-client-migration-abstract.php';

    /**
     * Class My_EDD_Freemius_Migration
     */
    class FS_EDD_Client_Migration_v1 extends FS_Client_Migration_Abstract_v1 {
        /**
         *
         * @param Freemius                      $freemius
         * @param string                        $edd_store_url                Your EDD store URL.
         * @param int                           $edd_download_id              The context EDD download ID (from your store).
         * @param FS_Client_License_Abstract_v1 $edd_license_accessor         License accessor.
         * @param bool                          $is_bundle                    Is it a bundle migration or a regular product.
         * @param bool                          $was_freemius_in_prev_version By default, the migration process will only be executed upon activation of the product for the 1st time with Freemius. By modifying this flag to `true`, it will also initiate a migration request even if the user already opted into Freemius. This flag is particularly relevant when the developer already released a Freemius powered version before releasing a version with the migration code.
         * @param bool                          $is_blocking                  Special argument for testing. When false, will
         *                                                                    initiate the migration in the same HTTP request.
         */
        public function __construct(
            Freemius $freemius,
            $edd_store_url,
            $edd_download_id,
            FS_Client_License_Abstract_v1 $edd_license_accessor,
            $is_bundle = false,
            $was_freemius_in_prev_version = false,
            $is_blocking = false
        ) {
            $this->init(
                'edd',
                $freemius,
                $edd_store_url,
                $edd_download_id,
                $edd_license_accessor,
                $is_bundle,
                $was_freemius_in_prev_version,
                $is_blocking
            );
        }
    }


text:
var fs = require('fs');

var arch = process.arch;
var platform = process.platform;

if (arch === 'ia32') {
    arch = 'x86';
}

if (platform === 'win32') {
    platform = 'win';
}

var filename = 'bin/graphql_ppx-' + platform + '-' + arch + '.exe';
var supported = fs.existsSync(filename);

if (!supported) {
    console.error('graphql_ppx does not support this platform :(');
    console.error('');
    console.error('graphql_ppx comes prepacked as built binaries to avoid large');
    console.error('dependencies at build-time.');
    console.error('');
    console.error('If you want graphql_ppx to support this platform natively,');
    console.error('please open an issue at our repository, linked above. Please');
    console.error('specify that you are on the ' + platform + ' platform,');
    console.error('on the ' + arch + ' architecture.');

    if (!process.env.IS_GRAPHQL_PPX_CI) {
        process.exit(1);
    }
}

if (process.env.IS_GRAPHQL_PPX_CI) {
    console.log('graphql_ppx: IS_GRAPHQL_PPX_CI has been set, skipping moving binary in place');
    process.exit(0);
}

if (!fs.existsSync('ppx')) {
    copyFileSync(filename, 'ppx');
    fs.chmodSync('ppx', 0755);
}

if (!fs.existsSync('ppx.exe')) {
    copyFileSync(filename, 'ppx.exe');
    fs.chmodSync('ppx.exe', 0755);
}

function copyFileSync(source, dest) {
    if (typeof fs.copyFileSync === 'function') {
        fs.copyFileSync(source, dest);
    } else {
        fs.writeFileSync(dest, fs.readFileSync(source));
    }
}


text:
from django.contrib import admin
from models import Message, Thread, MessageIndex, Settings

class MessageAdmin(admin.ModelAdmin):
    list_display = ['author', '__unicode__', 'created_at']
    search_fields = ['author']

class ThreadAdmin(admin.ModelAdmin):
    list_display = ['user_list', 'updated_at']
    search_fields = ['users']

class MessageIndexAdmin(admin.ModelAdmin):
    list_display = ['message', 'thread', 'user', 'new']
    search_fields = ['message', 'user']

class SettingsAdmin(admin.ModelAdmin):
    list_display = ['user', 'email_notifications']
    search_fields = ['user']

admin.site.register(Message, MessageAdmin)
admin.site.register(Thread, ThreadAdmin)
admin.site.register(MessageIndex, MessageIndexAdmin)
admin.site.register(Settings, SettingsAdmin)


text:
from twisted.internet import reactor
from twisted.internet.task import deferLater

from txdav.common.icommondatastore import ReservationError
from txdav.carddav.datastore.index_file import AddressBookIndex, \
    MemcachedUIDReserver

from twistedcaldav.test.util import InMemoryMemcacheProtocol
from twistedcaldav.vcard import Component
import twistedcaldav.test.util

import os

class MinimalResourceReplacement(object):
    """
    Provide the minimal set of attributes and methods from CalDAVFile required
    by L{Index}.
    """

    class MinimalTxn(object):

        def postCommit(self, _ignore):
            pass

        def postAbort(self, _ignore):
            pass

    def __init__(self, filePath):
        self.fp = filePath
        self._txn = MinimalResourceReplacement.MinimalTxn()

    def isAddressBookCollection(self):
        return True

    def getChild(self, name):
        # FIXME: this should really return something with a child method
        return self.fp.child(name)

    def initSyncToken(self):
        pass

class SQLIndexTests (twistedcaldav.test.util.TestCase):
    """
    Test abstract SQL DB class
    """

    def setUp(self):
        super(SQLIndexTests, self).setUp()
        self.site.resource.isAddressBookCollection = lambda: True
        self.indexDirPath = self.site.resource.fp
        # FIXME: since this resource lies about isCalendarCollection, it doesn't
        # have all the associated backend machinery to actually get children.
        self.db = AddressBookIndex(MinimalResourceReplacement(self.indexDirPath))

    def tearDown(self):
        self.db._db_close()

    def test_reserve_uid_ok(self):
        uid = "test-test-test"
        d = self.db.isReservedUID(uid)
        d.addCallback(self.assertFalse)
        d.addCallback(lambda _: self.db.reserveUID(uid))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertTrue)
        d.addCallback(lambda _: self.db.unreserveUID(uid))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertFalse)

        return d

    def test_reserve_uid_twice(self):
        uid = "test-test-test"
        d = self.db.reserveUID(uid)
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertTrue)
        d.addCallback(lambda _:
                      self.assertFailure(self.db.reserveUID(uid),
                                         ReservationError))
        return d

    def test_unreserve_unreserved(self):
        uid = "test-test-test"
        return self.assertFailure(self.db.unreserveUID(uid),
                                  ReservationError)

    def test_reserve_uid_timeout(self):
        # WARNING: This test is fundamentally flawed and will fail
        # intermittently because it uses the real clock.
        uid = "test-test-test"
        from twistedcaldav.config import config
        old_timeout = config.UIDReservationTimeOut
        config.UIDReservationTimeOut = 1

        def _finally():
            config.UIDReservationTimeOut = old_timeout

        d = self.db.isReservedUID(uid)
        d.addCallback(self.assertFalse)
        d.addCallback(lambda _: self.db.reserveUID(uid))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertTrue)
        d.addCallback(lambda _: deferLater(reactor, 2, lambda: None))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertFalse)
        self.addCleanup(_finally)

        return d

    def test_index(self):
        data = (
            (
                "#1.1 Simple component",
                "1.1",
                """BEGIN:VCARD
VERSION:3.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
UID:12345-67890-1.1
FN:Cyrus Daboo
N:Daboo;Cyrus
EMAIL;TYPE=INTERNET,PREF:cyrus@example.com
END:VCARD
""",
            ),
        )

        for description, name, vcard_txt in data:
            calendar = Component.fromString(vcard_txt)
            with open(os.path.join(self.site.resource.fp.path, name), "w") as f:
                f.write(vcard_txt)

            self.db.addResource(name, calendar)
            self.assertTrue(self.db.resourceExists(name), msg=description)

        self.db._db_recreate()
        for description, name, vcard_txt in data:
            self.assertTrue(self.db.resourceExists(name), msg=description)

    def test_index_revisions(self):
        data1 = """BEGIN:VCARD
VERSION:3.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
UID:12345-67890-1-1.1
FN:Cyrus Daboo
N:Daboo;Cyrus
EMAIL;TYPE=INTERNET,PREF:cyrus@example.com
END:VCARD
"""
        data2 = """BEGIN:VCARD
VERSION:3.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
UID:12345-67890-2-1.1
FN:Wilfredo Sanchez
N:Sanchez;Wilfredo
EMAIL;TYPE=INTERNET,PREF:wsanchez@example.com
END:VCARD
"""
        data3 = """BEGIN:VCARD
VERSION:3.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
UID:12345-67890-3-1.1
FN:Bruce Gaya
N:Gaya;Bruce
EMAIL;TYPE=INTERNET,PREF:bruce@example.com
END:VCARD
"""

        vcard = Component.fromString(data1)
        self.db.addResource("data1.vcf", vcard)
        vcard = Component.fromString(data2)
        self.db.addResource("data2.vcf", vcard)
        vcard = Component.fromString(data3)
        self.db.addResource("data3.vcf", vcard)
        self.db.deleteResource("data3.vcf")

        tests = (
            (0, (["data1.vcf", "data2.vcf", ], [], [],)),
            (1, (["data2.vcf", ], ["data3.vcf", ], [],)),
            (2, ([], ["data3.vcf", ], [],)),
            (3, ([], ["data3.vcf", ], [],)),
            (4, ([], [], [],)),
            (5, ([], [], [],)),
        )

        for revision, results in tests:
            self.assertEquals(self.db.whatchanged(revision), results, "Mismatched results for whatchanged with revision %d" % (revision,))

class MemcacheTests(SQLIndexTests):

    def setUp(self):
        super(MemcacheTests, self).setUp()
        self.memcache = InMemoryMemcacheProtocol()
        self.db.reserver = MemcachedUIDReserver(self.db, self.memcache)

    def tearDown(self):
        super(MemcacheTests, self).tearDown()
        for _ignore_k, v in self.memcache._timeouts.iteritems():
            if v.active():
                v.cancel()


text:
from __future__ import unicode_literals

import datetime
import json
import logging
from urllib import urlencode

from django.core.urlresolvers import reverse
from django.http.response import JsonResponse, Http404
from django.shortcuts import render, redirect
from django.template import loader
from django.utils import timezone
from django.views.generic.base import TemplateView

from trello_reporter.authentication.models import KeyVal
from trello_reporter.charting import forms
from trello_reporter.charting.constants import CUMULATIVE_FLOW_INITIAL_WORKFLOW, COMPLETED_COLUMNS, \
    SELECTED_COLUMNS_DESCRIPTION, SPRINT_COMMITMENT_DESCRIPTION, DATA_SYNCHRONIZATION_DESCRIPTION, \
    SPRINT_CALCULATION_DESCRIPTION, BURNDOWN_CHART_DESCRIPTION, CONTROL_CHART_DESCRIPTION, \
    VELOCITY_CHART_DESCRIPTION, CUMULATIVE_FLOW_CHART_DESCRIPTION
from trello_reporter.charting.models import Board, CardAction, List, Card, Sprint, ListStat
from trello_reporter.charting.processing import ChartExporter, ControlChart
from trello_reporter.charting.templatetags.card import display_card
from trello_reporter.harvesting.models import CardActionEvent

logger = logging.getLogger(__name__)

# local constants

CONTROL_INITIAL_WORKFLOW = [["Next"], ["Complete"]]

def index(request):
    logger.debug("display index")
    boards = Board.list_boards(request.user, request.COOKIES["token"])
    return render(request, "index.html", {
        "boards": boards,
        "breadcrumbs": [Breadcrumbs.text("Boards")]
    })

class Breadcrumbs(object):
    @classmethod
    def text(cls, text):
        return {"text": text}

    @classmethod
    def url(cls, url, text):
        t = {
            "url": url,
            "text": text
        }
        return t

    @classmethod
    def boards_index(cls):
        return cls.url(reverse("index"), "Boards")

    @classmethod
    def board_detail(cls, board):
        return [
            cls.boards_index(),
            Breadcrumbs.url(reverse("board-detail", args=(board.id, )), board.name)
        ]

class BaseView(TemplateView):
    view_name = None  # for javascript

def humanize_form_errors(form_list=None, formsets=None):
    """ return html with errors in forms; should be piped into notification widget """
    texts = []
    for form in form_list:
        if form and form.errors:
            form_errors_text = form.errors.as_text()
            logger.info("form errors: %s", form_errors_text)
            texts.append(form_errors_text)
    if formsets:
        for formset in formsets:
            nfe = formset.non_form_errors()
            if nfe:
                nfe_text = nfe.as_text()
                logger.info("non formset errors: %s", nfe_text)
                texts.append(nfe_text)
            for fe in formset.errors:
                if fe:
                    formset_form_error_text = fe.as_text()
                    logger.info("formset, form error: %s", formset_form_error_text)
                    texts.append(formset_form_error_text)
    return "<br>".join(texts)

class ChartView(BaseView):
    chart_name = None
    chart_data_url = None
    form_class = None
    view_name = "chart"

    def __init__(self, **kwargs):
        super(ChartView, self).__init__(**kwargs)
        # initial data populated in the form
        self.initial_form_data = {}
        # data from request.POST
        self.form_data = None
        self.formset_data = None
        self.form = None

    def get_context_data(self, **kwargs):
        context = super(ChartView, self).get_context_data(**kwargs)
        context["view_name"] = self.view_name  # django uses view to link self
        context["chart_name"] = self.chart_name
        context["chart_data_url"] = self.chart_data_url

        self.form = self.form_class(data=self.form_data, initial=self.initial_form_data)
        context["form"] = self.form
        return context

    @staticmethod
    def respond_json_form_errors(form_list, formset=None):
        return JsonResponse({"error": "Form is not valid: " +
                                      humanize_form_errors(form_list, formsets=[formset])})

class ControlChartBase(ChartView):
    """ common code for data and html """
    chart_name = "control"
    form_class = forms.ControlChartForm

    def get_context_data(self, board_id, **kwargs):
        board = Board.objects.by_id(board_id)
        sprint = Sprint.objects.latest_for_board(board)
        self.initial_form_data["sprint"] = sprint
        self.initial_form_data["count"] = 1
        self.initial_form_data["time_type"] = "d"

        context = super(ControlChartBase, self).get_context_data(**kwargs)
        self.form.set_sprint_choices(Sprint.objects.for_board_by_end_date(board))

        lis = List.objects.get_all_listnames_for_board(board)
        formset = forms.get_workflow_formset(zip(lis, lis), CONTROL_INITIAL_WORKFLOW,
                                             form_class=forms.MultiWorkflowMixin,
                                             data=self.formset_data)

        context["board"] = board
        context["formset"] = formset
        context["latest_sprint"] = sprint
        return context

class ControlChartView(ControlChartBase):
    template_name = "chart/control_chart.html"

    def get_context_data(self, board_id, **kwargs):
        logger.debug("display control chart")

        self.chart_data_url = reverse("control-chart-data", args=(board_id, ))

        context = super(ControlChartView, self).get_context_data(board_id, **kwargs)

        context["breadcrumbs"] = Breadcrumbs.board_detail(context["board"]) + \
            [Breadcrumbs.text("Control Chart")]
        context["control_chart_description"] = CONTROL_CHART_DESCRIPTION
        return context

class ControlChartDataView(ControlChartBase):
    def post(self, request, board_id, *args, **kwargs):
        self.form_data = request.POST
        self.formset_data = request.POST
        context = super(ControlChartDataView, self).get_context_data(board_id, **kwargs)
        form, formset = context["form"], context["formset"]

        if not (form.is_valid() and formset.is_valid()):
            return self.respond_json_form_errors([form], formset=formset)
        chart = ControlChart(
            context["board"], formset.workflow, form.cleaned_data["beginning"],
            form.cleaned_data["end"])

        data = chart.chart_data

        html = loader.render_to_string("chunks/control_chart_table.html",
                                       context=chart.render_stats())

        return JsonResponse({"data": data, "html": html})

class BurndownChartBase(ChartView):
    chart_name = "burndown"
    form_class = forms.BurndownChartForm

    def get_context_data(self, board_id, **kwargs):
        board = Board.objects.by_id(board_id)
        sprint = Sprint.objects.latest_for_board(board)
        self.initial_form_data["sprint"] = sprint

        context = super(BurndownChartBase, self).get_context_data(**kwargs)
        self.form.set_sprint_choices(Sprint.objects.for_board_by_end_date(board))

        lis = List.objects.get_all_listnames_for_board(board)
        self.commitment_cols = KeyVal.objects.sprint_commitment_columns(board).value["columns"]

        com_form = forms.ListsSelectorForm(
            self.commitment_cols,
            lis,
            data=self.form_data,
        )

        context["board"] = board
        context["com_form"] = com_form
        context["latest_sprint"] = sprint
        return context

class BurndownChartView(BurndownChartBase):
    template_name = "chart/burndown_chart.html"

    def get_context_data(self, board_id, **kwargs):
        logger.debug("display burndown chart")

        self.chart_data_url = reverse("burndown-chart-data", args=(board_id, ))

        context = super(BurndownChartView, self).get_context_data(board_id, **kwargs)

        context["breadcrumbs"] = Breadcrumbs.board_detail(context["board"]) + \
            [Breadcrumbs.text("Burndown Chart")]
        context["burndown_chart_description"] = BURNDOWN_CHART_DESCRIPTION
        return context

class BurndownChartDataView(BurndownChartBase):
    def get(self, request, *args, **kwargs):
        sprint_id = request.GET.get("sprint_id", None)
        if not sprint_id:
            raise Http404("Selected view of burndown chart does not exist, please specify sprint.")
        # so self.commitment_cols is set
        super(BurndownChartDataView, self).get_context_data(*args, **kwargs)
        sprint = Sprint.objects.get(id=sprint_id)
        data = ChartExporter.burndown_chart_c3(
            sprint.board, sprint.start_dt,
            sprint.end_dt, self.commitment_cols)
        return JsonResponse({"data": data})

    def post(self, request, board_id, *args, **kwargs):
        logger.debug("get data for burndown chart")
        self.form_data = request.POST
        context = super(BurndownChartDataView, self).get_context_data(board_id, **kwargs)
        form, com_form = context["form"], context["com_form"]

        if not (form.is_valid() and com_form.is_valid()):
            return self.respond_json_form_errors(form_list=(form, com_form))
        data = ChartExporter.burndown_chart_c3(
            context["board"], form.cleaned_data["beginning"],
            form.cleaned_data["end"], com_form.workflow)
        return JsonResponse({"data": data})

class CumulativeFlowChartBase(ChartView):
    chart_name = "cumulative_flow"
    form_class = forms.CumulativeFlowChartForm

    def get_context_data(self, board_id, **kwargs):
        board = Board.objects.by_id(board_id)
        today = timezone.now().date()
        self.initial_form_data["from_dt"] = today - datetime.timedelta(days=30)
        self.initial_form_data["to_dt"] = today
        self.initial_form_data["time_type"] = "d"
        self.initial_form_data["count"] = 1

        context = super(CumulativeFlowChartBase, self).get_context_data(**kwargs)
        self.form.set_sprint_choices(Sprint.objects.for_board_by_end_date(board))

        lis = List.objects.get_all_listnames_for_board(board)
        context["all_lists"] = lis
        formset = forms.get_workflow_formset([("", "")] + zip(lis, lis),
                                             CUMULATIVE_FLOW_INITIAL_WORKFLOW,
                                             data=self.formset_data)

        context["board"] = board
        context["formset"] = formset
        return context

class CumulativeFlowChartView(CumulativeFlowChartBase):
    template_name = "chart/cumulative_flow_chart.html"

    def get_context_data(self, board_id, **kwargs):
        logger.debug("display cumulative flow chart")

        self.chart_data_url = reverse("cumulative-flow-chart-data", args=(board_id, ))

        context = super(CumulativeFlowChartView, self).get_context_data(board_id, **kwargs)

        context["breadcrumbs"] = Breadcrumbs.board_detail(context["board"]) + \
            [Breadcrumbs.text("Cumulative flow chart")]
        context["cumulative_flow_chart_description"] = CUMULATIVE_FLOW_CHART_DESCRIPTION
        return context

class CumulativeFlowChartDataView(CumulativeFlowChartBase):
    def post(self, request, board_id, *args, **kwargs):
        logger.debug("get data for cumulative flow chart")
        self.form_data = request.POST
        self.formset_data = request.POST
        context = super(CumulativeFlowChartDataView, self).get_context_data(board_id, **kwargs)
        form, formset = context["form"], context["formset"]

        if not (form.is_valid() and formset.is_valid()):
            return self.respond_json_form_errors([form], formset=formset)
        order = formset.workflow
        data = ChartExporter.cumulative_chart_c3(
            context["board"],
            order,
            form.cleaned_data["beginning"], form.cleaned_data["end"],
            form.cleaned_data["delta"],
            form.cleaned_data["cards_or_sp"]
        )
        # c3 wants reversed order
        return JsonResponse({"data": data, "order": list(reversed(order)),
                             "all_lists": context["all_lists"]})

class VelocityChartBase(ChartView):
    chart_name = "velocity"
    form_class = forms.VelocityChartForm

    def get_context_data(self, board_id, **kwargs):
        board = Board.objects.by_id(board_id)
        today = timezone.now().date()
        self.initial_form_data["from_dt"] = today - datetime.timedelta(days=180)
        self.initial_form_data["to_dt"] = today

        context = super(VelocityChartBase, self).get_context_data(**kwargs)

        context["board"] = board
        return context

    def get_chart_data(self, context):
        if self.form.is_bound:
            last_n = self.form.cleaned_data["last_n"]
        else:
            last_n = self.form.fields["last_n"].initial
        sprints = Sprint.objects.for_board_last_n(context["board"], last_n)
        cc = KeyVal.objects.sprint_commitment_columns(context["board"]).value["columns"]
        return ChartExporter.velocity_chart_c3(sprints, cc)

class VelocityChartView(VelocityChartBase):
    template_name = "chart/velocity_chart.html"

    def get_context_data(self, board_id, **kwargs):
        logger.debug("display velocity chart")

        self.chart_data_url = reverse("velocity-chart-data", args=(board_id, ))

        context = super(VelocityChartView, self).get_context_data(board_id, **kwargs)

        context["breadcrumbs"] = Breadcrumbs.board_detail(context["board"]) + \
            [Breadcrumbs.text("Velocity chart")]
        context["sprint_data"] = self.get_chart_data(context)
        context["velocity_chart_description"] = VELOCITY_CHART_DESCRIPTION
        return context

class VelocityChartDataView(VelocityChartBase):
    def post(self, request, board_id, *args, **kwargs):
        logger.debug("get data for velocity chart")
        self.form_data = request.POST
        context = super(VelocityChartDataView, self).get_context_data(board_id, **kwargs)
        form = context["form"]

        if not form.is_valid():
            return self.respond_json_form_errors([form])

        data = self.get_chart_data(context)
        return JsonResponse({"data": data})

class ListDetailBase(ChartView):
    chart_name = "list_history"
    form_class = forms.ListDetailForm

    def get_context_data(self, list_id, **kwargs):
        li = List.objects.get(id=list_id)
        today = timezone.now().date()
        self.initial_form_data["from_dt"] = today - datetime.timedelta(days=60)
        self.initial_form_data["to_dt"] = today

        context = super(ListDetailBase, self).get_context_data(**kwargs)

        context["list"] = li
        return context

class ListDetailView(ListDetailBase):
    template_name = "list_detail.html"

    def get_context_data(self, list_id, **kwargs):
        logger.debug("list detail: %s", list_id)

        self.chart_data_url = reverse("list-history-chart-data", args=(list_id, ))

        context = super(ListDetailView, self).get_context_data(list_id, **kwargs)

        context["breadcrumbs"] = Breadcrumbs.board_detail(context["list"].latest_action.board) + \
            [Breadcrumbs.text("Column \"%s\"" % context["list"].name)]
        context["list_stats"] = ListStat.objects.for_list_in_range(
            context["list"], self.initial_form_data["from_dt"], self.initial_form_data["to_dt"])
        return context

class ListDetailDataView(ListDetailBase):
    def post(self, request, list_id, *args, **kwargs):
        logger.debug("get data for list history chart: %s", list_id)
        self.form_data = request.POST
        context = super(ListDetailDataView, self).get_context_data(list_id, **kwargs)
        form = context["form"]

        if not form.is_valid():
            return self.respond_json_form_errors([form])

        data = ChartExporter.list_history_chart_c3(context["list"],
                                                   form.cleaned_data["from_dt"],
                                                   form.cleaned_data["to_dt"])
        return JsonResponse({"data": data})

def board_detail(request, board_id):
    board = Board.objects.by_id(board_id)
    logger.debug("board detail %s", board)

    kv_displ_cols = KeyVal.objects.displayed_cols_in_board_detail(request.user, board)
    kv_com = KeyVal.objects.sprint_commitment_columns(board)

    if request.method == "POST":
        form_data = request.POST
    else:
        form_data = None

    lis = List.objects.get_all_listnames_for_board(board)

    columns_form = forms.ListsSelectorForm(
        kv_displ_cols.value["columns"],
        lis,
        data=form_data,
        prefix="col"
    )
    commitment_form = forms.ListsSelectorForm(
        kv_com.value["columns"],
        lis,
        data=form_data,
        prefix="com"
    )
    if request.method == "POST":
        if commitment_form.is_valid() and columns_form.is_valid():
            kv_displ_cols.value["columns"] = columns_form.workflow
            kv_displ_cols.save()
            kv_com.value["columns"] = commitment_form.workflow
            kv_com.save()
        else:
            logger.warning("formsets are not valid: %s %s", commitment_form, columns_form)
            # TODO: propagate to client

    lists = List.objects.filter_lists_for_board(board, f=kv_displ_cols.value["columns"])
    lists = sorted(lists, key=lambda x: x.name)

    sprints = Sprint.objects.filter(board__id=board_id).order_by("start_dt")
    context = {
        "board": board,
        "lists": lists,
        "sprints": sprints,
        "columns_form": columns_form,
        "commitment_form": commitment_form,
        "form_post_url": reverse("board-detail", args=(board_id, )),
        "errors": KeyVal.objects.board_messages(board).value["messages"],
        "breadcrumbs": [
            Breadcrumbs.url(reverse("index"), "Boards"),
            Breadcrumbs.text(board.name)
        ],
        "selected_columns_description": SELECTED_COLUMNS_DESCRIPTION,
        "sprint_commitment_description": SPRINT_COMMITMENT_DESCRIPTION,
        "data_synchronization_description": DATA_SYNCHRONIZATION_DESCRIPTION,
        "sprint_calculation_description": SPRINT_CALCULATION_DESCRIPTION,
    }
    return render(request, "board_detail.html", context)

def board_refresh(request, board_id):
    board = Board.objects.by_id(board_id)
    logger.debug("refresh board %s", board)
    board.ensure_actions(request.COOKIES["token"])
    return redirect('board-detail', board_id=board_id)

def sprint_create(request, board_id):
    board = Board.objects.by_id(board_id)
    logger.debug("sprint create for board: %s", board)

    if request.method == "POST":
        form = forms.SprintCreateForm(data=request.POST)
        form.instance.board = board
        logger.debug("user's timezone = %s", request.user.timezone)
        if form.is_valid():
            sprint = form.save()
            logger.debug("creating new sprint: %s", sprint)
            Sprint.set_completed_list(board)
            return redirect('sprint-detail', sprint_id=sprint.id)
    else:
        form = forms.SprintCreateForm()

    context = {
        "form": form,
        "post_url": reverse("sprint-create", args=(board_id, )),
        "breadcrumbs": Breadcrumbs.board_detail(board) +
                       [Breadcrumbs.text("Create sprint")]
    }
    return render(request, "sprint_create.html", context)

def sprint_detail(request, sprint_id):
    sprint = Sprint.objects.get(id=sprint_id)
    logger.debug("sprint detail: %s", sprint)
    # edit sprint as soon as possible
    if request.method == "POST":
        sprint_edit_form = forms.SprintEditForm(data=request.POST, instance=sprint)
        logger.debug("user's timezone = %s", request.user.timezone)
        if sprint_edit_form.is_valid():
            sprint = sprint_edit_form.save()
            logger.debug("saving updated sprint: %s", sprint)
    else:
        sprint_edit_form = forms.SprintEditForm(instance=sprint)

    sprint_cards = Card.objects.sprint_cards_with_latest_actions(sprint)
    sprint_card_ids = [x.id for x in sprint_cards]

    unfinished_cards = []
    if sprint.completed_list is not None:
        # don't supply date, we want latest stuff
        completed_card_actions = CardAction.objects.safe_card_actions_on_list_in(
            sprint.board,
            sprint.completed_list,
        )
        completed_card_ids = [x.card_id for x in completed_card_actions]
        unfinished_cards = [card for card in sprint_cards if card.id not in completed_card_ids]
    else:
        completed_card_actions = CardAction.objects.card_actions_on_list_names_in(
            sprint.board,
            COMPLETED_COLUMNS
        )

    current_sprint_cas = CardAction.objects.card_actions_on_list_names_in(
        sprint.board, ["Next", "In Progress", "Complete"], min(timezone.now(), sprint.end_dt))
    added_after_sprint_card_actions = [ca for ca in current_sprint_cas if ca.card_id not in sprint_card_ids]

    chart_url = reverse("burndown-chart-data", args=(sprint.board.id, ), )
    chart_url += "?" + urlencode({"sprint_id": sprint.id})

    context = {
        "form": sprint_edit_form,
        "post_url": reverse("sprint-detail", args=(sprint_id, )),
        "sprint": sprint,
        "sprint_cards": sprint_cards,
        "completed_card_actions": completed_card_actions,
        "unfinished_cards": unfinished_cards,
        "after_sprint_cas": added_after_sprint_card_actions,
        "view_name": "chart_without_form",
        "chart_name": "burndown",
        "chart_data_url": chart_url,
        "submit_input_type": "submit",
        "breadcrumbs": Breadcrumbs.board_detail(sprint.board) +
                       [Breadcrumbs.text("Sprint \"%s\"" % sprint.name)]
    }
    return render(request, "sprint_detail.html", context)

def card_detail(request, card_id):
    card = Card.objects.get(id=card_id)
    logger.debug("card detail: %s", card)
    # (previous_action, action)
    action_list = list(card.actions.order_by("date"))
    actions = zip([None] + action_list[:-1], action_list)

    events = [json.dumps(x.data, indent=2)
              for x in CardActionEvent.objects.for_card_by_date(card.trello_id)]

    context = {
        "card": card,
        "actions": actions,
        "events": events,
        "breadcrumbs": Breadcrumbs.board_detail(action_list[-1].board) +
                       [Breadcrumbs.text("Card \"%s\"" % display_card(action_list[-1]))]
    }
    return render(request, "card_detail.html", context)

def stalled_cards(request, list_id):
    li = List.objects.get(id=list_id)
    board = li.latest_action.board
    card_actions = CardAction.objects.safe_card_actions_on_list_in(board, li)
    card_actions = sorted(card_actions, key=lambda x: x.date)
    context = {
        "list": li,
        "card_actions": card_actions,
        "breadcrumbs": Breadcrumbs.board_detail(board) +
                       [Breadcrumbs.text("Stalled cards on \"%s\"" % li.name)]
    }
    return render(request, "stalled_cards.html", context)

# API

def api_get_card(request, card_id):
    card = Card.objects.get(id=card_id)
    logger.debug("api: get card %s", card)

    response = {
        "id": card.id,
        "name": card.name,
        "url": request.build_absolute_uri(reverse('card-detail', args=(card_id, ))),
    }
    return JsonResponse(response)


text:
import { FilterNumberFormComponent } from 'src/app/shared/components/filter-number-form/filter-number-form.component';
import { FilterStringFormComponent } from 'src/app/shared/components/filter-string-form/filter-string-form.component';
import {
  FilterOption,
  FilterParams,
  NumberFilterParams,
  StringFilterParams,
} from 'src/app/shared/models/filter';
import {
  applyDurationFilter,
  applyLongValueFilter,
  applyNumberFilter,
  applyStringFilter,
} from 'src/app/util';
import { Vehicle } from '.';

export type VehicleFilterContext = {
  vehicle: Vehicle;
  selected: boolean;
};

export type VehicleFilterPredicate<TParams extends FilterParams = FilterParams> = (
  context: VehicleFilterContext,
  params?: TParams
) => boolean;

export type VehicleFilterOption<TParams extends FilterParams = FilterParams> = FilterOption<
  VehicleFilterContext,
  VehicleFilterPredicate<TParams>
>;

export const selectedVehicleFilterOption: VehicleFilterOption = {
  id: 'selected',
  label: 'Selected',
  predicate: ({ selected }) => selected,
};

export const vehicleFilterOptions: VehicleFilterOption[] = [
  selectedVehicleFilterOption,
  {
    id: 'id',
    label: 'ID',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) => applyNumberFilter(vehicle.id, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'label',
    label: 'Label',
    form: () => FilterStringFormComponent,
    predicate: ({ vehicle }, params) => applyStringFilter(vehicle.label, params),
  } as VehicleFilterOption<StringFilterParams>,
  {
    id: 'fixedCost',
    label: 'Fixed Cost',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) => applyNumberFilter(vehicle.fixedCost, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'costPerHour',
    label: 'Cost Per Hour',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) => applyNumberFilter(vehicle.costPerHour, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'costPerKilometer',
    label: 'Cost Per Kilometer',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) => applyNumberFilter(vehicle.costPerKilometer, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'routeDistanceLimit',
    label: 'Route Distance Limit',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) =>
      applyLongValueFilter(vehicle.routeDistanceLimit?.maxMeters, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'routeDurationLimit',
    label: 'Route Duration Limit',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) =>
      applyDurationFilter(vehicle.routeDurationLimit?.maxDuration, params),
  } as VehicleFilterOption<NumberFilterParams>,
  {
    id: 'travelDurationLimit',
    label: 'Travel Duration Limit',
    form: () => FilterNumberFormComponent,
    predicate: ({ vehicle }, params) =>
      applyDurationFilter(vehicle.travelDurationLimit?.maxDuration, params),
  } as VehicleFilterOption<NumberFilterParams>,
];


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="180"
        android:endColor="#000000"
        android:startColor="@android:color/transparent" />

</shape><!-- From: file:/home/elioth010/AndroidStudioProjects/EcoEventos/app/src/main/res/drawable/textview_shadow.xml -->


text:
package grabber;

/**
 * Contains utility methods and final arrays for the OSRS hiscore package
 *
 * @author Dylan Weaver
 *
 */
public final class Utility {

	// An array of every skill in old school runescape
	static final String[] skills = { "overall", "attack", "defence", "strength", "hitpoints", "ranged", "prayer",
			"magic", "cooking", "woodcutting", "fletching", "fishing", "firemaking", "crafting", "smithing", "mining",
			"herblore", "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction" };

	// An array of every ranked member
		static final String[] playersFinal = {};

	/**
	 * A private constructor to ensure this class is not subclassed or messed with
	 *
	 * @throws assertionError This class should not be instantiated
	 */
	private Utility() {
		throw new AssertionError("This class can not be instantiated.");
	}

	/**
	 * Determines which suffix to use at the end of a given position (st, th, nd, rd)
	 *
	 * @param position The current position in an array being looped through
	 * @return A suffix to be appended to the position
	 */
	public final static String getPositionSuffix(int position) {
		if (position >= 11 && position <= 13) {
			return "th: ";
		} else {
			switch (position % 10) {
			case 1:
				return "st: ";
			case 2:
				return "nd: ";
			case 3:
				return "rd: ";
			default:
				return "th: ";
			}
		}
	}

	/**
	 * Determines if a number of arrays passed in are of the same length or not.
	 *
	 * @param arrays A collection of arrays to check for length equality
	 * @return True if the arrays are all of the same length, false otherwise
	 */
	public static boolean areSameLength(Object[]... arrays) {
		int firstLength = arrays[0].length;
		for (Object[] playerData : arrays) {
			if (playerData.length != firstLength) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Checks that {@code skill} is in {@code SKILL_NAMES}
	 *
	 * @param str The string to check against {@code SKILL_NAMES}
	 */
	static boolean checkForValidSkill(String str) {
		for (int i = 0; i < skills.length; i++) {
			if (skills[i].equalsIgnoreCase(str)) {
				return true;
			}
		}
		return false;
	}
}


text:
SYNONYM

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

#### Published in
Jb. wiss. Bot. 26: 81 (1894)

#### Original name
Diorchidium steudneri Magnus, 1891

### Remarks
null


text:
package premailer_test

import (
	"testing"

	"golang.org/x/net/html"

	premailer "github.com/mailproto/go-premailer"
)

func checkPremailerToPlaintext(t *testing.T, expect, html string) {
	p, err := premailer.New([]byte(html))
	if err != nil {
		t.Errorf("Error creating premailer from `%v`: %v", html, err)
	}

	if plain, err := p.ToPlaintext(); err != nil {
		t.Errorf("Error generating plaintext from `%v`: %v", html, err)
	} else if plain != expect {
		t.Errorf("Wrong content from `%v`, want: `%v` got: `%v`", html, expect, plain)
	}
}

// XXX: these are copied from the main pkg
func eachElement(root *html.Node, callback func(n *html.Node) bool) {
	var iter func(*html.Node)
	iter = func(n *html.Node) {
		if n == nil {
			return
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			if !callback(c) {
				return
			}
			iter(c)
		}
	}
	iter(root)
	callback(root)
}

func findElement(root *html.Node, element string) *html.Node {
	var found *html.Node
	eachElement(root, func(n *html.Node) bool {
		if n.Type == html.ElementNode && n.Data == element {
			found = n
			return false
		}
		return true
	})

	return found
}


text:
//
//  NSURLSessionTask+BKRAdditions.h
//  Pods
//
//  Created by Jordan Zucker on 1/18/16.
//
//

#import <Foundation/Foundation.h>

/**
 *  This category extends NSURLSessionTask objects
 *  for easy recording
 *
 *  @since 1.0.0
 */
@interface NSURLSessionTask (BKRAdditions)

/**
 *  This BKR_globabllyUniqueIdentifier is a NSString of an NSUUID for uniquefying all tasks we are recording.
 *
 *  @since 1.0.0
 */
@property (nonatomic, copy) NSString *BKR_globallyUniqueIdentifier;

/**
 *  Sets a BKR_globallyUniqueIdentifier for correlating recordings if one was not already set.
 *  This will not replace the existing unique identifier if one already exists.
 *
 *  @since 1.0.0
 */
- (void)BKR_uniqueify;

@end


text:
/*
 * 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.
 */
package io.trino.decoder.raw;

import io.trino.decoder.DecoderColumnHandle;
import io.trino.decoder.FieldValueProvider;
import io.trino.decoder.RowDecoder;

import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.util.Objects.requireNonNull;
import static java.util.function.Function.identity;

/**
 * Decoder for raw (direct byte) rows. All field decoders map bytes directly to Trino columns.
 */
public class RawRowDecoder
        implements RowDecoder
{
    public static final String NAME = "raw";

    private final Map<DecoderColumnHandle, RawColumnDecoder> columnDecoders;

    public RawRowDecoder(Set<DecoderColumnHandle> columnHandles)
    {
        requireNonNull(columnHandles, "columnHandles is null");
        columnDecoders = columnHandles.stream()
                .collect(toImmutableMap(identity(), this::createColumnDecoder));
    }

    private RawColumnDecoder createColumnDecoder(DecoderColumnHandle columnHandle)
    {
        return new RawColumnDecoder(columnHandle);
    }

    @Override
    public Optional<Map<DecoderColumnHandle, FieldValueProvider>> decodeRow(byte[] data, Map<String, String> dataMap)
    {
        return Optional.of(columnDecoders.entrySet().stream()
                .collect(toImmutableMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().decodeField(data))));
    }
}