text:
title: Sourcing from Prismic
---

In this guide, we'll walk through setting up a site with content management using [Prismic](https://prismic.io/).

Prismic is a hosted, proprietary Headless CMS (SaaS) with a web app for creating and publishing content. It's suitable for marketers, editors, and developers as it has both a "Writing Room" and a fully-fledged API & content backend. Besides the usual advantages of a SaaS CMS (hosting, security, updates), Prismic offers features like custom type builder, scheduling and content versioning, and multi-language support.

Moreover, their [Content Slices](https://prismic.io/feature/dynamic-layout-content-components) feature enables you to build dynamic layouts by defining reusable custom components and placing them on your landing page, case studies, or in your blog posts. Fortunately, you can use those in Gatsby to realize features like PrismJS highlighting or using `gatsby-image`. [This starter](https://github.com/LekoArts/gatsby-starter-prismic) shows you how to do just that!

In addition to written instructions, this guide also includes videos for more complex steps. You can find all of them in a [YouTube playlist](https://www.youtube.com/playlist?list=PLB-cmN3u7PHJCG-phPyiydhHfiosyd0VC).

_Note: This guide uses the Gatsby Hello World starter to provide a very basic understanding of how Prismic can work with your Gatsby site. If you'd like to start with a full blown template, check out [gatsby-starter-prismic](https://github.com/LekoArts/gatsby-starter-prismic). If you're not familiar with Prismic and its functionalities yet, we highly recommend to check out [Prismic's official documentation](https://prismic.io/docs) which also includes user guides and tutorials. This guide assumes that you have basic knowledge of Prismic & Gatsby (See [Gatsby's official tutorial](/tutorial))._

## Setup

### Prismic

Before initializing your Gatsby project you should sign up for an account on [Prismic.io](https://prismic.io/). The free plan is a perfect fit for personal or smaller projects. Create a new blank repository to get to the content overview of your repository.

Create your first custom type (Repeatable Type) with the name `Post` and add some fields to it. Choose rational names for the `API ID` input while configuring a field because these names will appear in your queries. You should always add the `uid` field in order to have a unique identifier (e.g. for filtering). Then switch to the content overview and create a new document with your `Post` type. Fill out the fields and publish the item.

In order for Gatsby to grab all information from Prismic you'll need to generate an access token. Head over to `Settings → API & Security`, fill out the `Application name` field (the Callback URL can be left empty), and press `Add this application`.

### Gatsby

First, open a new terminal window and run the following command to create a new site:

```shell
gatsby new prismic-tutorial https://github.com/gatsbyjs/gatsby-starter-hello-world
```

This will create a new directory called `prismic-tutorial` that contains the starters site, but you can change `prismic-tutorial` in the command above to whatever name you prefer!
Now move into the newly created directory and install the Gatsby plugin for Prismic:

```shell
cd prismic-tutorial
npm install --save gatsby-source-prismic
```

In addition to installing the Prismic plugin, you also have to install the package `dotenv` to securely use your access tokens locally as you should never commit secret API keys to your repository!

```shell
npm install --save-dev dotenv
```

Create a file called `.env.development` at the root of your project with the following content:

```
API_KEY=paste-your-secret-access-token-here-wou7evoh0eexuf
```

_Note: If you want to locally build your project you'll also have to create a `.env.production` file with the same content._

Now you need to configure the plugin (See all [available options](https://www.npmjs.com/package/gatsby-source-prismic#how-to-use)). The `repositoryName` is the name you have entered at the creation of the repository (you'll also find it as the subdomain in the URL). The `linkResolver` function is used to process links in your content. Fields with rich text formatting or links to internal content use this function to generate the correct link URL. The document node, field key (i.e. API ID), and field value are provided to the function. This allows you to use different [link resolver logic](https://prismic.io/docs/javascript/query-the-api/link-resolving) for each field if necessary.

Add the following to register the plugin:

```javascript:title=gatsby-config.js
require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-prismic`,
      options: {
        repositoryName: `your-repository-name`,
        accessToken: `${process.env.API_KEY}`,
        linkResolver: ({ node, key, value }) => post => `/${post.uid}`,
      },
    },
  ],
}
```

The best way to create your queries now is to first develop them in _GraphiQL_ at `http://localhost:8000/___graphql` and then paste them into your files. Start the local development server and experiment a bit with the available queries. You should be able to get this query:

![Prismic Index Query](./images/prismic-index-query.jpg)

Because you defined the custom type as `Post` the query is called `allPrismicPost` (and `prismicPost`). You can also see the API IDs (from the field names) you created earlier.

With this information you can create pages/templates as usual:

```js:title=gatsby-node.js
const path = require("path")

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const pages = await graphql(`
    {
      allPrismicPost {
        edges {
          node {
            id
            uid
          }
        }
      }
    }
  `)

  const template = path.resolve("src/templates/post.jsx")

  pages.data.allPrismicPost.edges.forEach(edge => {
    createPage({
      path: `/${edge.node.uid}`,
      component: template,
      context: {
        uid: edge.node.uid,
      },
    })
  })
}
```

```jsx:title=src/templates/post.jsx
import React from "react"
import { graphql } from "gatsby"

const Post = ({ data: { prismicPost } }) => {
  const { data } = prismicPost
  return (
    <React.Fragment>
      <h1>{data.title.text}</h1>
      <div dangerouslySetInnerHTML={{ __html: data.content.html }} />
    </React.Fragment>
  )
}

export default Post

export const pageQuery = graphql`
  query PostBySlug($uid: String!) {
    prismicPost(uid: { eq: $uid }) {
      uid
      data {
        title {
          text
        }
        content {
          html
        }
      }
    }
  }
`
```

## Deploying to Netlify

Earlier you defined an `API_KEY` environment variable for the source plugin. Netlify can set [build environment variables](https://www.netlify.com/docs/continuous-deployment/#build-environment-variables), too. Go to your site and enter the `API_KEY` variable under `Settings → Build & deploy`. This way the source plugin gets the access token passed on the build.

Netlify is able to automatically start builds on pushes to a repository and accepts [webhooks](https://www.netlify.com/docs/webhooks/) to do so. Fortunately, Prismic can [trigger webhook](https://user-guides.prismic.io/webhooks/webhooks) URLs when publishing content. With those features set up, new content will automatically appear on your Netlify site.

Setup your Netlify project and afterwards go to the `Build hooks` setting at `Settings → Build & deploy`. You'll receive a URL of the format `https://api.netlify.com/build_hooks/-randomstring-` after clicking `Add build hook`. On your Prismic project, visit the `Webhooks` setting and insert the copied URL into the respective field. Confirm with `Add this webhook`. Every time you publish a new document, Netlify will re-build your site.

## Adding more features

### Categories

Prismic offers a [Content Relationship](https://user-guides.prismic.io/content-modeling-and-custom-types/field-reference/content-relationship) field which is used to link to another document in your Prismic repository. You can use that in combination with a custom type to create a tagging system (in this example _categories_). And what's cool about that? You can edit your entries any time and they'll update in every post! Read the [official docs](https://user-guides.prismic.io/how-to-guides/create-a-custom-tagging-system) on that or watch the video:

The video shows the usage of a group field and relationship field — if you only want to have one category, skip the group field. Similar as to the `Post` custom type the `Category` one can also be queried. Furthermore, the `allPrismicPost` query also has the `categories` node available:

![Prismic Categories Query](./images/prismic-categories-query.jpg)

### Single Type

When creating a new custom type, you are able to choose `Single Type`, too. In this example, you'll fill the homepage with content from Prismic and therefore have complete control over the content of your site. The goal is to eliminate the need to change website code, and to change your content in Prismic instead. Visit your Prismic repository and follow the video:

Single pages (like your homepage, privacy policy page etc.) don't need [GraphQL connections](https://blog.apollographql.com/explaining-graphql-connections-c48b7c3d6976) (e.g. `allPrismicHomepage`) due to the fact that only one document for that type exists in Prismic anyway. Therefore you need to use `prismicHomepage` for your query. This also has the benefit that you don't have to map over an array. Your page could look something like this:

```jsx:title=src/pages/index.js
import React from "react"
import { graphql, Link } from "gatsby"

const Index = ({ data: { prismicHomepage } }) => (
  <React.Fragment>
    <h1>{prismicHomepage.data.title.text}</h1>
    <div
      dangerouslySetInnerHTML={{ __html: prismicHomepage.data.content.html }}
    />
  </React.Fragment>
)

export default Index

export const pageQuery = graphql`
  query IndexQuery {
    prismicHomepage {
      data {
        title {
          text
        }
        content {
          html
        }
      }
    }
  }
`
```

## Wrapping Up

This was an example meant to help you understand how Prismic works with Gatsby. With your newfound knowledge of Prismic (and perhaps even Gatsby), you're now able to:

- Create a Prismic repository and setting it up together with the Gatsby plugin
- Query data from Prismic and using it to programmatically create blogpost pages
- Use Prismic together with Netlify
- Add relationships between posts, e.g. with categories
- Query data from Prismic for single pages

As mentioned in the beginning of this guide, if you got stuck, you can compare your code to the [gatsby-starter-prismic](https://github.com/LeKoArts/gatsby-starter-prismic) which is the project set up in the videos. A working example created by following this guide is available in the [commit history](https://github.com/LeKoArts/gatsby-starter-prismic/tree/4aa5d52e79a0b4d90f0a671c24eb8289eb15a42b) of the aforementioned starter. More advanced usages of Prismic in Gatsby would be [Slices](https://intercom.help/prismicio/content-modeling-and-custom-types/field-reference/slices) and [Labels](https://intercom.help/prismicio/content-modeling-and-custom-types/structure-your-content/add-custom-styles-to-rich-text).


text:
    <button ng-click="main.onNewRecord()" class="btn btn-primary glyphicon glyphicon-plus grid-button-add">Incluir</button>

        E-mail
        Name
        Perfil
        Habilitado
        Açoes

            {{user.email}}
            {{user.user}}
            {{getDesc(user.profile)}}
            <button ng-click="main.changeState(user)" ng-class="user.state == 'A' ? 'on' : 'off'" class="btn turn-on-off" />

                <button ng-click="main.onEdit(user)" class="btn btn-sm btn-default glyphicon glyphicon-pencil" />

redpajama_set_name: RedPajamaGithub


text:
package org.debezium.driver;

import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier;

import org.debezium.Configuration;
import org.debezium.annotation.Immutable;

/**
 * A specialized configuration for the Debezium driver.
 * @author Randall Hauch
 */
@Immutable
interface ClientConfiguration extends Configuration {

    /**
     * Obtain a {@link ClientConfiguration} adapter for the given {@link Configuration}.
     *
     * @param config the configuration; may not be null
     * @return the ClientConfiguration; never null
     */
    public static ClientConfiguration adapt(Configuration config) {
        if (config instanceof ClientConfiguration) return (ClientConfiguration) config;
        return new ClientConfiguration() {
            @Override
            public Set<String> keys() {
                return config.keys();
            }
            @Override
            public String getString(String key) {
                return config.getString(key);
            }

            @Override
            public String getString(String key, String defaultValue) {
                return config.getString(key, defaultValue);
            }

            @Override
            public String getString(String key, Supplier<String> defaultValueSupplier) {
                return config.getString(key, defaultValueSupplier);
            }

            @Override
            public <T> T getInstance(String key, Class<T> clazz) {
                return config.getInstance(key, clazz);
            }

            @Override
            public <T> T getInstance(String key, Class<T> clazz, Supplier<ClassLoader> classloaderSupplier) {
                return config.getInstance(key, clazz, classloaderSupplier);
            }

            @Override
            public Integer getInteger(String key) {
                return config.getInteger(key);
            }

            @Override
            public int getInteger(String key, int defaultValue) {
                return config.getInteger(key, defaultValue);
            }

            @Override
            public Integer getInteger(String key, IntSupplier defaultValueSupplier) {
                return config.getInteger(key, defaultValueSupplier);
            }

            @Override
            public Long getLong(String key) {
                return config.getLong(key);
            }

            @Override
            public long getLong(String key, long defaultValue) {
                return config.getLong(key, defaultValue);
            }

            @Override
            public Long getLong(String key, LongSupplier defaultValueSupplier) {
                return config.getLong(key, defaultValueSupplier);
            }
            @Override
            public Boolean getBoolean(String key) {
                return config.getBoolean(key);
            }
            @Override
            public boolean getBoolean(String key, boolean defaultValue) {
                return config.getBoolean(key, defaultValue);
            }
            @Override
            public Boolean getBoolean(String key, BooleanSupplier defaultValueSupplier) {
                return config.getBoolean(key, defaultValueSupplier);
            }
        };
    }

    default public boolean initializeProducersImmediately() {
        return getBoolean("initialize.producers",true);
    }

    default public int getResponseReaderThreadCount(){
        return getInteger("response.reader.thread.count",10);
    }

    default public Configuration getProducerConfiguration() {
        return subset("producer",true);
    }

    default public Configuration getConsumerConfiguration() {
        return subset("consumers",true);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Travessa</tipo><logradouro>Piauí</logradouro><bairro>Monza</bairro><cidade>Colombo</cidade><uf>PR</uf><cep>83406650</cep></feed>


text:
package org.qi4j.migration.assembly;

import java.util.Map;
import org.qi4j.migration.operation.AddAssociation;
import org.qi4j.migration.operation.AddManyAssociation;
import org.qi4j.migration.operation.AddNamedAssociation;
import org.qi4j.migration.operation.AddProperty;
import org.qi4j.migration.operation.RemoveAssociation;
import org.qi4j.migration.operation.RemoveManyAssociation;
import org.qi4j.migration.operation.RemoveNamedAssociation;
import org.qi4j.migration.operation.RemoveProperty;
import org.qi4j.migration.operation.RenameAssociation;
import org.qi4j.migration.operation.RenameManyAssociation;
import org.qi4j.migration.operation.RenameNamedAssociation;
import org.qi4j.migration.operation.RenameProperty;

/**
 * Fluent API for creating migration rules for specific entity types.
 */
public class EntityMigrationBuilder
{
    private final VersionMigrationBuilder migrationBuilder;
    private final String[] entityTypes;

    public EntityMigrationBuilder( VersionMigrationBuilder migrationBuilder, String[] entityTypes )
    {
        this.migrationBuilder = migrationBuilder;
        this.entityTypes = entityTypes;
    }

    /**
     * Return the version builder
     *
     * @return current version builder
     */
    public VersionMigrationBuilder end()
    {
        return migrationBuilder;
    }

    // Operations on entities
    /**
     * Add rule to rename an Entity property.
     *
     * @param from property name
     * @param to   property name
     *
     * @return the builder
     */
    public EntityMigrationBuilder renameProperty( String from, String to )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RenameProperty( from, to ) ) );

        return this;
    }

    /**
     * Add rule to add an Entity property.
     *
     * @param property     to be added
     * @param defaultValue default value
     *
     * @return the builder
     */
    public EntityMigrationBuilder addProperty( String property, Object defaultValue )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new AddProperty( property, defaultValue ) ) );

        return this;
    }

    /**
     * Add rule to remove an Entity property
     *
     * @param property     to be removed
     * @param defaultValue default value (used for downgrading)
     *
     * @return the builder
     */
    public EntityMigrationBuilder removeProperty( String property, String defaultValue )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RemoveProperty( property, defaultValue ) ) );

        return this;
    }

    /**
     * Add rule to rename an Entity association.
     *
     * @param from assocation name
     * @param to   association name
     *
     * @return the builder
     */
    public EntityMigrationBuilder renameAssociation( String from, String to )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RenameAssociation( from, to ) ) );

        return this;
    }

    /**
     * Add rule to add an Entity association.
     *
     * @param association      to be added
     * @param defaultReference default reference
     *
     * @return the builder
     */
    public EntityMigrationBuilder addAssociation( String association, String defaultReference )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new AddAssociation( association, defaultReference ) ) );

        return this;
    }

    /**
     * Add rule to remove an Entity association
     *
     * @param association      to be removed
     * @param defaultReference default value (used for downgrading)
     *
     * @return the builder
     */
    public EntityMigrationBuilder removeAssociation( String association, String defaultReference )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RemoveAssociation( association, defaultReference ) ) );

        return this;
    }

    /**
     * Add rule to add an Entity many-association.
     *
     * @param association       to be added
     * @param defaultReferences default references
     *
     * @return the builder
     */
    public EntityMigrationBuilder addManyAssociation( String association, String... defaultReferences )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new AddManyAssociation( association, defaultReferences ) ) );

        return this;
    }

    /**
     * Add rule to remove an Entity many-association
     *
     * @param association       to be removed
     * @param defaultReferences default value (used for downgrading)
     *
     * @return the builder
     */
    public EntityMigrationBuilder removeManyAssociation( String association, String... defaultReferences )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RemoveManyAssociation( association, defaultReferences ) ) );

        return this;
    }

    /**
     * Add rule to rename an Entity many-association.
     *
     * @param from many-assocation name
     * @param to   many-association name
     *
     * @return the builder
     */
    public EntityMigrationBuilder renameManyAssociation( String from, String to )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RenameManyAssociation( from, to ) ) );

        return this;
    }

    /**
     * Add rule to add an Entity named-association.
     *
     * @param association       to be added
     * @param defaultReferences default references
     *
     * @return the builder
     */
    public EntityMigrationBuilder addNamedAssociation( String association, Map<String, String> defaultReferences )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new AddNamedAssociation( association, defaultReferences ) ) );

        return this;
    }

    /**
     * Add rule to remove an Entity named-association
     *
     * @param association       to be removed
     * @param defaultReferences default value (used for downgrading)
     *
     * @return the builder
     */
    public EntityMigrationBuilder removeNamedAssociation( String association, Map<String, String> defaultReferences )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RemoveNamedAssociation( association, defaultReferences ) ) );

        return this;
    }

    /**
     * Add rule to rename an Entity named-association.
     *
     * @param from many-assocation name
     * @param to   many-association name
     *
     * @return the builder
     */
    public EntityMigrationBuilder renameNamedAssociation( String from, String to )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              new RenameNamedAssociation( from, to ) ) );

        return this;
    }

    /**
     * Add rule to perform a custom operation
     *
     * @param operationEntity the custom operation to be performed during migration
     *
     * @return the builder
     */
    public EntityMigrationBuilder custom( EntityMigrationOperation operationEntity )
    {
        migrationBuilder.builder.entityMigrationRules().
            addRule( new EntityMigrationRule( migrationBuilder.fromVersion,
                                              migrationBuilder.toVersion,
                                              entityTypes,
                                              operationEntity ) );

        return this;
    }
}


text:
<?php

class Google_Service_PolicyTroubleshooter_GoogleCloudPolicytroubleshooterV1BindingExplanation extends Google_Model
{
  public $access;
  protected $conditionType = 'Google_Service_PolicyTroubleshooter_GoogleTypeExpr';
  protected $conditionDataType = '';
  protected $membershipsType = 'Google_Service_PolicyTroubleshooter_GoogleCloudPolicytroubleshooterV1BindingExplanationAnnotatedMembership';
  protected $membershipsDataType = 'map';
  public $relevance;
  public $role;
  public $rolePermission;
  public $rolePermissionRelevance;

  public function setAccess($access)
  {
    $this->access = $access;
  }
  public function getAccess()
  {
    return $this->access;
  }
  /**
   * @param Google_Service_PolicyTroubleshooter_GoogleTypeExpr
   */
  public function setCondition(Google_Service_PolicyTroubleshooter_GoogleTypeExpr $condition)
  {
    $this->condition = $condition;
  }
  /**
   * @return Google_Service_PolicyTroubleshooter_GoogleTypeExpr
   */
  public function getCondition()
  {
    return $this->condition;
  }
  /**
   * @param Google_Service_PolicyTroubleshooter_GoogleCloudPolicytroubleshooterV1BindingExplanationAnnotatedMembership
   */
  public function setMemberships($memberships)
  {
    $this->memberships = $memberships;
  }
  /**
   * @return Google_Service_PolicyTroubleshooter_GoogleCloudPolicytroubleshooterV1BindingExplanationAnnotatedMembership
   */
  public function getMemberships()
  {
    return $this->memberships;
  }
  public function setRelevance($relevance)
  {
    $this->relevance = $relevance;
  }
  public function getRelevance()
  {
    return $this->relevance;
  }
  public function setRole($role)
  {
    $this->role = $role;
  }
  public function getRole()
  {
    return $this->role;
  }
  public function setRolePermission($rolePermission)
  {
    $this->rolePermission = $rolePermission;
  }
  public function getRolePermission()
  {
    return $this->rolePermission;
  }
  public function setRolePermissionRelevance($rolePermissionRelevance)
  {
    $this->rolePermissionRelevance = $rolePermissionRelevance;
  }
  public function getRolePermissionRelevance()
  {
    return $this->rolePermissionRelevance;
  }
}


text:
<?php declare (strict_types=1);

namespace Sabre\CardDAV;

use Sabre\DAV;

interface IAddressBook extends DAV\ICollection {

}


text: website for class project


text:
package org.apache.camel.language.groovy;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;

import static org.apache.camel.language.groovy.GroovyLanguage.groovy;

/**
 * @version
 */
public class GroovySetFixedHeaderTest extends ContextTestSupport {

    public void testSetHeader() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedBodiesReceived("Hello World");
        mock.expectedHeaderReceived("beer", "Carlsberg");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .setHeader("beer", groovy("'Carlsberg'"))
                    .to("mock:result");
            }
        };
    }
}


text:
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Team } from './team.model';
import { TeamService } from './team.service';
import { TeamResolver } from './team.resolver';
import { GymnastModule } from '../gymnast/gymnast.module';
import { MediaModule } from '../media/media.module';
import { DisciplineModule } from '../discipline/discipline.module';
import { DivisionModule } from '../division/division.module';
import { Log } from '../../common/util/logger/log';
import { UserModule } from '../user/user.module';
import { ClubModule } from '../club/club.module';
import { TournamentModule } from '../tournament/tournament.module';

@Module({
  imports: [
    TypeOrmModule.forFeature([Team]),
    forwardRef(() => GymnastModule),
    forwardRef(() => MediaModule),
    forwardRef(() => DisciplineModule),
    forwardRef(() => DivisionModule),
    forwardRef(() => UserModule),
    forwardRef(() => ClubModule),
    forwardRef(() => TournamentModule)
  ],
  providers: [TeamService, TeamResolver],
  exports: [TeamService]
})
export class TeamModule {
  constructor() {
  }
}


text:
"""
Take a bunch of FITS template spectra, and list their intrinsic magnitudes (as saved in the FITS file), and the
exposure times needed to observe them if they were at some particular reference magnitude.
"""

import argparse
import glob
import logging
import os
from os import path as os_path

import numpy as np
from astropy.io import fits
from fourgp_fourfs import FourFS
from fourgp_speclib import SpectrumLibrarySqlite, Spectrum

our_path = os_path.split(os_path.abspath(__file__))[0]
root_path = os_path.join(our_path, "../../../..")

# Read input parameters
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input',
                    required=True,
                    dest="input",
                    help="A filename wildcard where we can find the template spectra to operate on.")
parser.add_argument('--library',
                    dest="library",
                    default="louise_templates",
                    help="The spectrum library to import the templates into.")
parser.add_argument('--workspace', dest='workspace', default="",
                    help="Directory where we expect to find spectrum libraries.")
parser.add_argument('--binary-path',
                    required=False,
                    default=root_path,
                    dest="binary_path",
                    help="Specify a directory where 4FS package is installed.")
parser.add_argument('--snr-definition',
                    action="append",
                    dest="snr_definitions",
                    help="Specify a way of defining SNR, in the form 'name,minimum,maximum', meaning we calculate the "
                         "median SNR per pixel between minimum and maximum wavelengths in Angstrom.")
parser.add_argument('--snr-list',
                    required=False,
                    default="10,12,14,16,18,20,23,26,30,35,40,45,50,80,100,130,180,250",
                    dest="snr_list",
                    help="Specify a comma-separated list of the SNRs that 4FS is to degrade spectra to.")
parser.add_argument('--snr-definitions-lrs',
                    required=False,
                    default="",
                    dest="snr_definitions_lrs",
                    help="Specify the SNR definition to use for LRS. For example, 'GalDiskHR_536NM' to use the S4 "
                         "green definition of SNR. You can even specify three comma-separated definitions, e.g. "
                         "'GalDiskHR_536NM,GalDiskHR_536NM,GalDiskHR_536NM' to use different SNR metrics for the "
                         "RGB arms within 4MOST LRS, though this is a pretty weird thing to want to do.")
parser.add_argument('--snr-definitions-hrs',
                    required=False,
                    default="",
                    dest="snr_definitions_hrs",
                    help="Specify the SNR definition to use for HRS. For example, 'GalDiskHR_536NM' to use the S4 "
                         "green definition of SNR. You can even specify three comma-separated definitions, e.g. "
                         "'GalDiskHR_536NM,GalDiskHR_536NM,GalDiskHR_536NM' to use different SNR metrics for the "
                         "RGB arms within 4MOST HRS, though this is a pretty weird thing to want to do.")
parser.add_argument('--run-hrs',
                    action='store_true',
                    dest="run_hrs",
                    help="Set 4FS to produce output for 4MOST HRS [default].")
parser.add_argument('--no-run-hrs',
                    action='store_false',
                    dest="run_hrs",
                    help="Set 4FS not to produce output for 4MOST HRS. Setting this will make us run quicker.")
parser.set_defaults(run_hrs=True)
parser.add_argument('--run-lrs',
                    action='store_true',
                    dest="run_lrs",
                    help="Set 4FS to produce output for 4MOST LRS [default].")
parser.add_argument('--no-run-lrs',
                    action='store_false',
                    dest="run_lrs",
                    help="Set 4FS not to produce output for 4MOST LRS. Setting this will make us run quicker.")
parser.set_defaults(run_lrs=True)
parser.add_argument('--photometric-band',
                    required=False,
                    default="SDSS_r",
                    dest="photometric_band",
                    help="The name of the photometric band in which the magnitudes in --mag-list are specified. This "
                         "must match a band which is recognised by the pyphot python package.")
parser.add_argument('--mag-list',
                    required=False,
                    default="15",
                    dest="mag_list",
                    help="Specify a comma-separated list of the magnitudes to assume when simulating observations "
                         "of each object. If multiple magnitudes are specified, than each input spectrum we be "
                         "output multiple times, once at each magnitude.")
args = parser.parse_args()

# Start logger
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s:%(filename)s:%(message)s',
                    datefmt='%d/%m/%Y %H:%M:%S')
logger = logging.getLogger(__name__)
logger.info("Calculating magnitudes and exposure times for templates")

# Set path to workspace where we create libraries of spectra
workspace = args.workspace if args.workspace else os_path.join(our_path, "../../../workspace")
os.system("mkdir -p {}".format(workspace))

# Turn set of templates into a spectrum library with path specified above
library_path = os_path.join(workspace, args.library)
library = SpectrumLibrarySqlite(path=library_path, create=True)

# Fetch a list of all the input template spectra which match the supplied filename wildcard
templates = glob.glob(args.input)
templates.sort()

# Parse any definitions of SNR we were supplied on the command line
if (args.snr_definitions is None) or (len(args.snr_definitions) < 1):
    snr_definitions = None
else:
    snr_definitions = []
    for snr_definition in args.snr_definitions:
        words = snr_definition.split(",")
        snr_definitions.append([words[0], float(words[1]), float(words[2])])

# Look up what definition of SNR is user specified we should use for 4MOST LRS
if len(args.snr_definitions_lrs) < 1:
    # Case 1: None was specified, so we use default
    snr_definitions_lrs = None
else:
    snr_definitions_lrs = args.snr_definitions_lrs.split(",")
    # Case 2: A single definition was supplied which we use for all three arms
    if len(snr_definitions_lrs) == 1:
        snr_definitions_lrs *= 3
    # Case 3: Three definitions were supplied, one for each arm
    assert len(snr_definitions_lrs) == 3

# Look up what definition of SNR is user specified we should use for 4MOST HRS
if len(args.snr_definitions_hrs) < 1:
    # Case 1: None was specified, so we use default
    snr_definitions_hrs = None
else:
    snr_definitions_hrs = args.snr_definitions_hrs.split(",")
    # Case 2: A single definition was supplied which we use for all three arms
    if len(snr_definitions_hrs) == 1:
        snr_definitions_hrs *= 3
    # Case 3: Three definitions were supplied, one for each arm
    assert len(snr_definitions_hrs) == 3

# Parse the list of SNRs that the user specified on the command line
snr_list = [float(item.strip()) for item in args.snr_list.split(",")]

# Parse the list of magnitudes that the user specified on the command line
mag_list = [float(item.strip()) for item in args.mag_list.split(",")]

# Loop over all the magnitudes we are to simulate for each object
for magnitude in mag_list:

    # Instantiate 4FS wrapper
    # NB: Here we are requiring SNR/pixel=100 in GalDiskHR_545NM
    etc_wrapper = FourFS(
        path_to_4fs=os_path.join(args.binary_path, "OpSys/ETC"),
        snr_definitions=snr_definitions,
        magnitude=magnitude,
        magnitude_unreddened=False,
        photometric_band=args.photometric_band,
        run_lrs=args.run_lrs,
        run_hrs=args.run_hrs,
        lrs_use_snr_definitions=snr_definitions_lrs,
        hrs_use_snr_definitions=snr_definitions_hrs,
        snr_list=snr_list,
        snr_per_pixel=False
    )

    for template_index, template in enumerate(templates):
        name = "template_{:08d}".format(template_index)

        # Open fits spectrum
        f = fits.open(template)
        data = f[1].data
        wavelengths = data['LAMBDA']
        fluxes = data['FLUX']

        # Open ASCII spectrum
        # f = np.loadtxt(template).T
        # wavelengths = f[0]
        # fluxes = f[1]

        # Create 4GP spectrum object
        spectrum = Spectrum(wavelengths=wavelengths,
                            values=fluxes,
                            value_errors=np.zeros_like(wavelengths),
                            metadata={
                                "Starname": name,
                                "imported_from": template
                            })

        # Work out magnitude
        mag_intrinsic = spectrum.photometry(args.photometric_band)

        # Pass template to 4FS
        degraded_spectra = etc_wrapper.process_spectra(
            spectra_list=((spectrum, None),)
        )

        # Loop over LRS and HRS
        for mode in degraded_spectra:
            # Loop over the spectra we simulated (there was only one!)
            for index in degraded_spectra[mode]:
                # Loop over the various SNRs we simulated
                for snr in degraded_spectra[mode][index]:
                    # Extract the exposure time returned by 4FS from the metadata associated with this Spectrum object
                    # The exposure time is recorded in seconds
                    exposure_time = degraded_spectra[mode][index][snr]["spectrum"].metadata["exposure"]

                    # Print output
                    print("{name:100s} {mode:6s} {snr:6.1f} {magnitude:6.3f} {exposure:6.3f}". \
                          format(name=name,
                                 mode=mode,
                                 snr=snr,
                                 magnitude=mag_intrinsic,
                                 exposure=exposure_time))

        # Insert spectrum object into spectrum library
        library.insert(spectra=spectrum, filenames=os_path.split(template)[1])


text:
> Plays an ascii bell

## Getting Started
This plugin requires Grunt `~0.4.1`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-bell --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-bell');
```

## The "bell" task

### Overview
In your project's Gruntfile, use the `bell` task during your custom tasks defined with `grunt.registerTask()` or `grunt.registerMultiTask()`.

Useful for adding to the end of a task queue, so that you know when they've completed without having to monitor the terminal/console.

```js
// sound the bell when these tasks complete
grunt.registerTask('default', ['sometask', 'anothertask', 'bell']);
```

## Release History
0.1.2 - 12/11/2013 added seconds time info to output
0.1.1 - 11/11/2013 Updated readme
0.1.0 - 11/11/2013 Initial commit


text:
package com.cloud.network.nicira;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.rest.HttpClientHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;

public class NiciraNvpApiIT {

    protected NiciraNvpApi api;

    protected long timestamp = System.currentTimeMillis();

    @Before
    public void setup() throws Exception {
        PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties"));
        final String host = System.getProperty("nvp.host");
        final String user = System.getProperty("nvp.admin.user");
        final String pass = System.getProperty("nvp.admin.pwd");
        api = NiciraNvpApi.create()
                          .host(host)
                          .username(user)
                          .password(pass)
                          .httpClient(HttpClientHelper.createHttpClient(5))
                          .build();
    }

    @Test
    public void testCRUDSecurityProfile() {
        SecurityProfile sProfile = new SecurityProfile();
        sProfile.setDisplayName("SecProfile" + timestamp);

        final List<SecurityRule> egressRules = new ArrayList<>();
        sProfile.setLogicalPortEgressRules(egressRules);
        egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6));
        egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6));

        final List<SecurityRule> ingressRules = new ArrayList<>();
        sProfile.setLogicalPortIngressRules(ingressRules);
        ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6));
        ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6));

        final List<NiciraNvpTag> tags = new ArrayList<>();
        sProfile.setTags(tags);
        tags.add(new NiciraNvpTag("nvp", "MyTag1"));
        tags.add(new NiciraNvpTag("nicira", "MyTag2"));
        // In the creation we don't get to specify UUID, href or schema: they don't exist yet

        try {
            sProfile = api.createSecurityProfile(sProfile);

            // We can now update the new entity
            sProfile.setDisplayName("UpdatedSecProfile" + timestamp);
            api.updateSecurityProfile(sProfile, sProfile.getUuid());

            // Read them all
            List<SecurityProfile> profiles = api.findSecurityProfile();
            SecurityProfile scInList = null;
            for (final SecurityProfile iProfile : profiles) {
                if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) {
                    scInList = iProfile;
                }
            }
            assertEquals("Read a Security Profile different from the one just created and updated", sProfile, scInList);

            // Read them filtered by uuid (get one)
            profiles = api.findSecurityProfile(sProfile.getUuid());
            assertEquals("Read a Security Profile different from the one just created and updated", sProfile, profiles.get(0));
            assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", 1, profiles.size());

            // We can now delete the new entity
            api.deleteSecurityProfile(sProfile.getUuid());
        } catch (final NiciraNvpApiException e) {
            e.printStackTrace();
            assertTrue("Errors in Security Profile CRUD", false);
        }
    }

    @Test
    public void testCRUDAcl() {
        Acl acl = new Acl();
        acl.setDisplayName("Acl" + timestamp);

        // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type
        // Note that if the protocol is 1 (ICMP) then you cannot put ports
        final List<AclRule> egressRules = new ArrayList<>();
        acl.setLogicalPortEgressRules(egressRules);
        egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
        egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));

        final List<AclRule> ingressRules = new ArrayList<>();
        acl.setLogicalPortIngressRules(ingressRules);
        ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5));
        ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null));

        final List<NiciraNvpTag> tags = new ArrayList<>();
        acl.setTags(tags);
        tags.add(new NiciraNvpTag("nvp", "MyTag1"));
        tags.add(new NiciraNvpTag("nicira", "MyTag2"));
        // In the creation we don't get to specify UUID, href or schema: they don't exist yet

        try {
            acl = api.createAcl(acl);

            // We can now update the new entity
            acl.setDisplayName("UpdatedAcl" + timestamp);
            api.updateAcl(acl, acl.getUuid());

            // Read them all
            List<Acl> acls = api.findAcl();
            Acl scInList = null;
            for (final Acl iAcl : acls) {
                if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) {
                    scInList = iAcl;
                }
            }
            assertEquals("Read a ACL different from the one just created and updated", acl, scInList);

            // Read them filtered by uuid (get one)
            acls = api.findAcl(acl.getUuid());
            assertEquals("Read a ACL different from the one just created and updated", acl, acls.get(0));
            assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", 1, acls.size());

            // We can now delete the new entity
            api.deleteAcl(acl.getUuid());
        } catch (final NiciraNvpApiException e) {
            e.printStackTrace();
            assertTrue("Errors in ACL CRUD", false);
        }
    }

    @Test
    public void testCRUDLogicalSwitch() throws Exception {
        LogicalSwitch logicalSwitch = new LogicalSwitch();
        logicalSwitch.setDisplayName("LogicalSwitch" + timestamp);
        logicalSwitch.setPortIsolationEnabled(true);
        logicalSwitch.setReplicationMode("service");
        logicalSwitch.setTags(new ArrayList<>());
        logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo"));

        // In the creation we don't get to specify UUID, href or schema: they don't exist yet

        logicalSwitch = api.createLogicalSwitch(logicalSwitch);

        // We can now update the new entity
        logicalSwitch.setDisplayName("UpdatedLogicalSwitch" + timestamp);
        api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());

        // Read them all
        List<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
        for (final LogicalSwitch iLogicalSwitch : logicalSwitches) {
            if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
                assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, iLogicalSwitch);
            }
        }

        // Read them filtered by uuid (get one)
        logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
        assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, logicalSwitches.get(0));
        assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", 1, logicalSwitches.size());

        // Before deleting the test LogicalSwitch, test its ports
        final List<NiciraNvpTag> tags = new ArrayList<>();
        tags.add(new NiciraNvpTag("cs_account", "OwnerName"));

        LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort" + timestamp, tags, true);
        logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);

        logicalSwitchPort.setDisplayName("UpdatedLSwitchPort" + timestamp);
        api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);

        final List<LogicalSwitchPort> logicalSwitchePorts = api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
        for (final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts) {
            if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
                assertEquals("Read a LogicalSwitchPort different from the one just created and updated", logicalSwitchPort, iLSwitchPort);
            }
        }

        // And finally test attachments
        final String attachmentUuid = UUID.randomUUID().toString();
        final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
        api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment);

        assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
                api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), logicalSwitchPort.getUuid());

        api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());

        // We can now delete the new entity
        api.deleteLogicalSwitch(logicalSwitch.getUuid());
    }

    @Test
    public void testCRUDLogicalRouter() {
        LogicalRouter logicalRouter = new LogicalRouter();
        logicalRouter.setDisplayName("LogicalRouter" + timestamp);
        logicalRouter.setDistributed(true);
        logicalRouter.setNatSynchronizationEnabled(true);
        logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
        final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
                new RouterNextHop("192.168.10.20"));
        logicalRouter.setRoutingConfig(routingConfig);

        // In the creation we don't get to specify UUID, href or schema: they don't exist yet

        try {
            logicalRouter = api.createLogicalRouter(logicalRouter);

            // We can now update the new entity
            logicalRouter.setDisplayName("UpdatedLogicalSwitch" + timestamp);
            api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid());

            // Read them all
            List<LogicalRouter> logicalRouters = api.findLogicalRouter();
            LogicalRouter lsInList = null;
            for (final LogicalRouter iLogicalRouter : logicalRouters) {
                if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) {
                    lsInList = iLogicalRouter;
                }
            }
            assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, lsInList);

            // Read them filtered by uuid (get one)
            logicalRouters = api.findLogicalRouter(logicalRouter.getUuid());
            assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, logicalRouters.get(0));
            assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", 1, logicalRouters.size());

            assertEquals(logicalRouters.get(0), api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));

            // Before deleting the test LogicalRouter, test its ports
            final List<NiciraNvpTag> tags = new ArrayList<>();
            tags.add(new NiciraNvpTag("cs_account", "OwnerName"));

            LogicalRouterPort logicalRouterPort = new LogicalRouterPort();
            logicalRouterPort.setDisplayName("LRouterPort" + timestamp);
            logicalRouterPort.setTags(tags);
            logicalRouterPort.setAdminStatusEnabled(true);
            logicalRouterPort.setPortno(1024);
            logicalRouterPort.setMacAddress("00:00:00:00:00:00");

            final List<String> ipAddresses = new ArrayList<>();
            // Add some ips to this list
            logicalRouterPort.setIpAddresses(ipAddresses);
            logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);

            logicalRouterPort.setDisplayName("UpdatedLRouterPort" + timestamp);
            api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);

            final List<LogicalRouterPort> logicalRouterePorts = api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
            for (final LogicalRouterPort iLRouterPort : logicalRouterePorts) {
                if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) {
                    assertEquals("Read a LogicalRouterPort different from the one just created and updated", logicalRouterPort, iLRouterPort);
                }
            }

            UUID.randomUUID().toString();

            // Test CRUD for Nat Rules
            SourceNatRule snr = new SourceNatRule();
            snr.setToSourceIpAddressMin("192.168.10.10");
            snr.setToSourceIpAddressMax("192.168.10.20");
            snr.setOrder(200);
            final Match match = new Match();
            match.setSourceIpAddresses("192.168.150.150");
            snr.setMatch(match);
            snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr);
            snr.setToSourceIpAddressMax("192.168.10.30");
            api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr);

            api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid());
            api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid());

            api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid());

            // We can now delete the new entity
            api.deleteLogicalRouter(logicalRouter.getUuid());
        } catch (final NiciraNvpApiException e) {
            e.printStackTrace();
            assertTrue("Errors in LogicalRouter CRUD", false);
        }
    }

    @Test
    public void testGetControlClusterStatus() throws NiciraNvpApiException {
        final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
        final String clusterStatus = controlClusterStatus.getClusterStatus();
        final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") ||
                clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable");
        assertTrue("Not recognizable cluster status", correctStatus);
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Exodus 4D
 * Date: 27.05.2018
 * Time: 14:17
 */

namespace Exodus4D\Pathfinder\Controller\Api;

use Exodus4D\Pathfinder\Lib\Config;
use Exodus4D\Pathfinder\Lib\Cron;
use Exodus4D\Pathfinder\Lib\Format\Number;
use Exodus4D\Pathfinder\Controller;
use Exodus4D\Pathfinder\Model;

class Setup extends Controller\Controller {

    /**
     * get HTML table <tr>´s for all cronjobs
     * @param \Base $f3
     */
    public function cronTable(\Base $f3){
        $return = (object) [];
        $return->error = [];
        $return->jobsData = Cron::instance()->getJobsConfig();
        $return->html = $this->getCronHtml($return->jobsData);
        echo json_encode($return);
    }

    /**
     * toggle "isPaused" for a cronjob by its name
     * @param \Base $f3
     */
    public function cronPause(\Base $f3){
        $postData = (array)$f3->get('POST');
        $return = (object) [];
        $return->error = [];

        if($jobName = (string)$postData['job']){
            $cron = Cron::instance();
            if($job = $cron->getJob($jobName)){
                if($job->valid()){
                    $job->isPaused = !$job->isPaused;
                    $job->save();

                    $return->jobsData = $cron->getJobsConfig([$jobName]);
                    $return->html = $this->getCronHtml($return->jobsData);
                }
            }
        }

        echo json_encode($return);
    }

    /**
     * execute a cronjob by its name
     * -> runs sync
     * -> max execution time might be lower than CLI calls!
     * @param \Base $f3
     */
    public function cronExecute(\Base $f3){
        $postData = (array)$f3->get('POST');
        $return = (object) [];
        $return->error = [];

        if($jobName = (string)$postData['job']){
            $cron = Cron::instance();
            if($job = $cron->getJob($jobName)){
                if($job->valid()){
                    $cron->execute($jobName, false);

                    $return->jobsData = $cron->getJobsConfig([$jobName]);
                    $return->html = $this->getCronHtml($return->jobsData);
                }
            }
        }

        echo json_encode($return);
    }

    /**
     * get HTML for cronJobs
     * @param array $jobsData
     * @return string
     */
    protected function getCronHtml(array $jobsData) : string {
        $tplData = [
            'cronConfig' => [
                'jobs' => $jobsData,
                'settings' => $this->getF3()->constants(Cron::instance(), 'DEFAULT_')
            ],
            'tplCounter' => $this->counter(),
            'tplConvertBytes' => function(){
                return call_user_func_array([Number::instance(), 'bytesToString'], func_get_args());
            }
        ];
        return \Template::instance()->render('templates/ui/cron_table_row.html', null, $tplData, 0);
    }

    /**
     * build search index from existing data (e.g. Systems)
     * OR import data from ESI (e.g. Structures)
     * -> optional build/import smaller chunks of data
     * @param \Base $f3
     * @throws \Exception
     */
    public function buildIndex(\Base $f3){
        $postData = (array)$f3->get('POST');
        $type = (string)$postData['type'];
        $countAll = (int)$postData['countAll'];
        $count = (int)$postData['count'];
        $offset = (int)$postData['offset'];

        $return = (object) [];
        $return->error = [];
        $return->type = $type;
        $return->count = $count;
        $return->offset = $offset;
        $return->countAll = $countAll;
        $return->countBuild = 0;
        $return->countBuildAll = 0;
        $return->progress = 0;

        /**
         * sum array values
         * @param int $carry
         * @param int $value
         * @return int
         */
        $sum = function(int $carry, int $value) : int {
            $carry += $value;
            return $carry;
        };

        /**
         * calc percent
         * @param int $countAll
         * @param int $count
         * @return int
         */
        $percent = function(int $countAll, int $count){
            return $countAll ? floor((100/$countAll) * $count) : 0;
        };

        $controller = new Controller\Ccp\Universe();
        switch($type){
            case 'Systems':
                $length = 100;
                $buildInfo = $controller->buildSystemsIndex($offset, $length);

                $return->offset = $buildInfo['offset'];
                $return->countAll = $buildInfo['countAll'];
                $return->countBuild = $buildInfo['countBuild'];
                $return->countBuildAll = $return->offset;
                break;
            case 'Wormholes':
                $groupId = Config::ESI_GROUP_WORMHOLE_ID;
                $length = 10;
                $buildInfo = $controller->setupGroup($groupId, $offset, $length, true);

                $return->offset = $buildInfo['offset'];
                $return->countAll = $buildInfo['countAll'];
                $return->countBuild = $buildInfo['count'];
                $return->countBuildAll = $return->offset;
                break;
            case 'Structures':
                $categoryId = Config::ESI_CATEGORY_STRUCTURE_ID;
                $length = 1;
                $buildInfo = $controller->setupCategory($categoryId, $offset, $length);
                $categoryUniverseModel =  Model\Universe\AbstractUniverseModel::getNew('CategoryModel');
                $categoryUniverseModel->getById($categoryId, 0);

                $return->offset = $buildInfo['offset'];
                $return->countBuild = $buildInfo['count'];
                $return->countBuildAll = $return->offset;
                $return->subCount = [
                    'countBuildAll' => $categoryUniverseModel->getTypesCount(false)
                ];
                break;
            case 'Ships':
                $categoryId = Config::ESI_CATEGORY_SHIP_ID;
                $length = 2;
                $buildInfo = $controller->setupCategory($categoryId, $offset, $length);
                $categoryUniverseModel =  Model\Universe\AbstractUniverseModel::getNew('CategoryModel');
                $categoryUniverseModel->getById($categoryId, 0);

                $return->offset = $buildInfo['offset'];
                $return->countBuild = $buildInfo['count'];
                $return->countBuildAll = $return->offset;
                $return->subCount = [
                    'countBuildAll' => $categoryUniverseModel->getTypesCount(false)
                ];
                break;
            case 'SystemStatic':
                $length = 300;
                $buildInfo = $this->setupSystemStaticTable($offset, $length);

                $return->offset = $buildInfo['offset'];
                $return->countAll = $buildInfo['countAll'];
                $return->countBuild = $buildInfo['count'];
                $return->countBuildAll = $return->offset;
                break;
            case 'SystemNeighbour':
                $length = 1500;
                $buildInfo = $this->setupSystemJumpTable($offset, $length);

                $return->offset = $buildInfo['offset'];
                $return->countAll = $buildInfo['countAll'];
                $return->countBuild = $buildInfo['count'];
                $return->countBuildAll = $return->offset;
                break;
        }

        $return->progress = $percent($return->countAll, $return->countBuildAll);

        if($return->countBuildAll < $return->countAll){
            $return->count++;
        }

        echo json_encode($return);
    }

    /**
     * clear search index
     * @param \Base $f3
     * @throws \Exception
     */
    public function clearIndex(\Base $f3){
        $postData = (array)$f3->get('POST');
        $type = (string)$postData['type'];

        $return = (object) [];
        $return->error = [];
        $return->type = $type;
        $return->count = 0;
        $return->countAll = 0;
        $return->countBuild = 0;
        $return->countBuildAll = 0;
        $return->progress = 0;

        $controller = new Controller\Ccp\Universe();
        switch($type) {
            case 'Systems':
                $controller->clearSystemsIndex();
                $systemUniverseModel =  Model\Universe\AbstractUniverseModel::getNew('SystemModel');
                $return->countAll = $systemUniverseModel->getRowCount();
                break;
            case 'SystemNeighbour':
                $systemNeighbourModel =  Model\Universe\AbstractUniverseModel::getNew('SystemNeighbourModel');
                $systemNeighbourModel->truncate();
                $return->countAll = (int)$f3->get('REQUIREMENTS.DATA.NEIGHBOURS');
                break;
        }

        echo json_encode($return);
    }

    /**
     * import static 'system_static` table data from *.csv
     * @param int $offset
     * @param int $length
     * @return array
     * @throws \Exception
     */
    protected function setupSystemStaticTable(int $offset = 0, int $length = 0) : array {
        $info = ['countAll' => 0, 'countChunk' => 0, 'count' => 0, 'offset' => $offset];

        /**
         * @var $systemStaticModel Model\Universe\SystemStaticModel
         */
        $systemStaticModel = Model\Universe\AbstractUniverseModel::getNew('SystemStaticModel');
        if(!empty($csvData = $systemStaticModel::getCSVData($systemStaticModel->getTable()))){
            $info['countAll'] = count($csvData);
            if($length){
                $csvData = array_slice($csvData, $offset, $length);
            }
            $info['countChunk'] = count($csvData);
            $cols = ['typeId' => [], 'systemId' => []];
            foreach($csvData as $data){
                $validColCount = 0;
                $systemStaticModel->getById((int)$data['id'], 0);
                $systemStaticModel->id = (int)$data['id'];
                foreach($cols as $col => &$invalidIds){
                    if($systemStaticModel->exists($col)){
                        $colVal = (int)$data[$col];
                        if(!in_array($colVal, $invalidIds)){
                            $relModel = $systemStaticModel->rel($col);
                            $relModel->getById($colVal, 0);
                            if($relModel->valid()){
                                $systemStaticModel->$col = $relModel;
                                $validColCount++;
                            }else{
                                $invalidIds[] = $colVal;
                                break;
                            }
                        }else{
                            break;
                        }
                    }
                }

                if($validColCount == count($cols)){
                    $systemStaticModel->save();
                }
                $systemStaticModel->reset();

                $info['count']++;
                $info['offset']++;
            }
        }

        return $info;
    }

    /**
     * This function is just for setting up the cache table 'system_neighbour' which is used
     * for system jump calculation. Call this function manually when CCP adds Systems/Stargates
     * @param int $offset
     * @param int $length
     * @return array
     */
    protected function setupSystemJumpTable(int $offset = 0, int $length = 0) : array {
        $info = ['countAll' => 0, 'countChunk' => 0, 'count' => 0, 'offset' => $offset];
        $universeDB = $this->getDB('UNIVERSE');

        $query = "SELECT SQL_CALC_FOUND_ROWS
                      `system`.`id` `systemId`,
                      `system`.`name` `systemName`,
                      `system`.`constellationId` `constellationId`,
                      ROUND( `system`.`securityStatus`, 4) `trueSec`,
                      `constellation`.`regionId` `regionId`,
                      (
                        SELECT
                          GROUP_CONCAT( NULLIF(`sys_inner`.`id`, NULL) SEPARATOR ':')
                        FROM
                          `stargate` INNER JOIN
                          `system` `sys_inner` ON
                            `sys_inner`.`id` = `stargate`.`destinationSystemId`
                        WHERE
                          `stargate`.`systemId` = `system`.`id`
                      ) `jumpNodes`
                    FROM
                      `system` INNER JOIN
                      `constellation` ON
                        `constellation`.`id` = `system`.`constellationId`
                    WHERE
                      `constellation`.`regionId` != :regionIdJove1 AND
                      `constellation`.`regionId` != :regionIdJove2 AND
                      `constellation`.`regionId` != :regionIdJove3 AND
                      (
                          `system`.`security` = :ns OR
                          `system`.`security` = :ls OR
                          `system`.`security` = :hs
                      )
                    HAVING
                        `jumpNodes` IS NOT NULL
                    ";

        $args = [
            ':regionIdJove1' => 10000017,
            ':regionIdJove2' => 10000019,
            ':regionIdJove3' => 10000004,
            ':ns' => '0.0',
            ':ls' => 'L',
            ':hs' => 'H'
        ];

        if($length){
            $query .= ' LIMIT :limit';
            $args[':limit'] = $length;

            if($offset){
                $query .= ' OFFSET :offset';
                $args[':offset'] = $offset;
            }
        }

        $rows = $universeDB->exec($query, $args);

        if(!empty($countRes = $universeDB->exec("SELECT FOUND_ROWS() `count`")) && isset($countRes[0]['count'])){
            $info['countAll'] = (int)$countRes[0]['count'];
        }

        if($info['countChunk'] = count($rows)){
            $placeholderStr = function(string $str) : string {
                return ':' . $str;
            };

            $updateRule = function(string $str) : string {
                return $str . " = VALUES(" . $str . ")";
            };

            $universeDB->begin();
            foreach($rows as $row){
                $info['count']++;
                $info['offset']++;

                if(!$row['jumpNodes']){
                    // should never happen!
                    continue;
                }

                $columns = array_keys($row);
                $columnsQuoted = array_map($universeDB->quotekey, $columns);
                $placeholder = array_map($placeholderStr, $columns);
                $args = array_combine($placeholder, $row);

                $updateSql = array_map($updateRule, $columns);

                $sql = "INSERT INTO
                            system_neighbour(" . implode(', ', $columnsQuoted) . ")
                                VALUES(" . implode(', ', $placeholder) . ")
                          ON DUPLICATE KEY UPDATE
                            " . implode(', ', $updateSql);

                $universeDB->exec($sql, $args);
            }
            $universeDB->commit();
        }

        return $info;
    }

}


text:
CREATE TABLE "MULTI_EVENT_ENTITY"
  (
    "ID"		NUMBER(9,0) NOT NULL,
    "VERSION"	NUMBER(9,0) NOT NULL,
    "NAME"		VARCHAR2(100 BYTE) NOT NULL,
    "CREATED_ON" DATE,
    "CREATED_BY" VARCHAR2(16 BYTE),
    "UPDATED_ON" DATE,
    "UPDATED_BY" VARCHAR2(16 BYTE),
    CONSTRAINT "MULTI_EVENT_ENTITY_PK" PRIMARY KEY ("ID") USING INDEX
  );
CREATE SEQUENCE "MULTI_EVENT_ENTITY_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 10000 CACHE 20 NOORDER NOCYCLE ;

CREATE TABLE "MULTI_EVENT_ENTITY2"
  (
    "ID"		NUMBER(9,0) NOT NULL,
    "VERSION"	NUMBER(9,0) NOT NULL,
    "NAME"		VARCHAR2(100 BYTE) NOT NULL,
    "CREATED_ON" DATE,
    "CREATED_BY" VARCHAR2(16 BYTE),
    "UPDATED_ON" DATE,
    "UPDATED_BY" VARCHAR2(16 BYTE),
    CONSTRAINT "MULTI_EVENT_ENTITY2_PK" PRIMARY KEY ("ID") USING INDEX
  );
CREATE SEQUENCE "MULTI_EVENT_ENTITY2_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 10000 CACHE 20 NOORDER NOCYCLE ;


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Comment = mongoose.model('Comment'),
	Subject = mongoose.model('Subject'),
	Article = mongoose.model('Article'),
	User = mongoose.model('User'),
	_ = require('lodash'),
	markdown = require('markdown').markdown;

/**
 * Create a Comment
 */
exports.create = function(req, res) {
	var obj = req.body.obj;

	var comment = new Comment(req.body);
	comment.user = req.user;
	comment.content = req.body.content ? markdown.toHTML(req.body.content) : '';
	comment.markdown = req.body.content;

	if (obj === 'articles'){
		comment.articles = req.body.value;
		comment.save(function (err,comment) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.send(comment);
			}
		});
	} else if(obj === 'subjects'){
		comment.subjects = req.body.value;
		comment.save(function (err,comment) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.send(comment);
				Subject.findOneAndUpdate({_id:req.body.value},{$inc:{pv:1},$push:{comment:comment._id}},function (err){
					if (err) {console.log(err);}
				});
			}
		});
	}
};

/**
 * Show the current Comment
 */
exports.read = function(req, res) {
	res.jsonp(req.comment);
};

/**
 * Update a Comment
 */
exports.update = function(req, res) {
	var comment = req.comment ;

	comment = _.extend(comment , req.body);

	comment.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(comment);
		}
	});
};

/**
 * Delete an Comment
 */
exports.delete = function(req, res) {
	var comment = req.comment ;

	comment.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(comment);
		}
	});
};

/**
 * List of Comments
 */
exports.list = function(req, res) {
	var obj = req.query.obj;
	if (obj === 'articles'){
		Comment.find({articles:req.query.value}).sort('created').populate('user', 'username avatar created').exec(function(err, comments) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(comments);
			}
		});
	}else if(obj === 'subjects'){
		Comment.find({subjects:req.query.value}).sort('created').populate('user', 'username avatar created').exec(function(err, comments) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(comments);
			}
		});
	}else {
		Comment.find().sort('-created').populate('user','username').populate('subjects','title').populate('articles','title').populate('goods','title').exec(function (err,comments){
			if(err){console.log(err);}
			res.send(comments);
		});
	}
};

/**
 * Count of Comments
 */
exports.count = function(req, res) {
	Comment.count().exec(function(err, comments) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(comments);
		}
	});
};

/**
 *  count of User comments
 */
exports.userCount = function (req,res){

	Comment.count({user:req.user._id}, function (err,count){
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(count);
		}
	});
};

/**
 * Modify a Comment
 */
exports.modify = function(req, res) {
	var commentObj = req.body;
	Comment.findOneAndUpdate({_id:commentObj._id},{subcat:commentObj.subcat,name:commentObj.name,title:commentObj.title,price:commentObj.price},function (err,comment) {
		if (err) {
			console.log(err);
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(comment);
		}
	});
};

/**
 * Comment middleware
 */
exports.commentByID = function(req, res, next, id) {
	Comment.findById(id).populate('user', 'displayName').exec(function(err, comment) {
		if (err) return next(err);
		if (! comment) return next(new Error('Failed to load Comment ' + id));
		req.comment = comment ;
		next();
	});
};

/**
 * Comment authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.comment.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
package nitezh.ministock.mocks;

import java.util.HashMap;

import nitezh.ministock.Storage;

public class MockStorage implements Storage {

    @Override
    public HashMap<String, ?> getAll() {
        return new HashMap<>();
    }

    @Override
    public int getInt(String widgetSize, int defaultVal) {
        return 0;
    }

    @Override
    public String getString(String key, String defaultVal) {
        return "";
    }

    @Override
    public boolean getBoolean(String large_font, boolean defaultVal) {
        return false;
    }

    @Override
    public void putInt(String key, int value) {
    }

    @Override
    public Storage putString(String key, String value) {
        return this;
    }

    @Override
    public void putBoolean(String key, Boolean value) {
    }

    @Override
    public void putFloat(String key, Float value) {
    }

    @Override
    public void putLong(String key, Long value) {
    }

    @Override
    public void apply() {
    }
}


text:
// Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Unit tests for ContributionOpportunitiesBackendApiService.
 */

import { HttpClientTestingModule, HttpTestingController } from
  '@angular/common/http/testing';
import { TestBed, fakeAsync, flushMicrotasks } from '@angular/core/testing';

import { ContributionOpportunitiesBackendApiService } from
  // eslint-disable-next-line max-len
  'pages/contributor-dashboard-page/services/contribution-opportunities-backend-api.service';
import { SkillOpportunity } from
  'domain/opportunity/skill-opportunity.model';
import { UrlInterpolationService } from
  'domain/utilities/url-interpolation.service';
import { FeaturedTranslationLanguage } from 'domain/opportunity/featured-translation-language.model';
import { ExplorationOpportunitySummary } from 'domain/opportunity/exploration-opportunity-summary.model';

describe('Contribution Opportunities backend API service', function() {
  let contributionOpportunitiesBackendApiService:
    ContributionOpportunitiesBackendApiService;
  let httpTestingController: HttpTestingController;
  let urlInterpolationService: UrlInterpolationService;
  const skillOpportunityResponse = {
    opportunities: [{
      id: 'skill_id',
      skill_description: 'A new skill for question',
      topic_name: 'A new topic',
      question_count: 30
    }],
    next_cursor: '6',
    more: true
  };
  const skillOpportunity = {
    opportunities: [{
      id: 'exp_id',
      topic_name: 'Topic',
      story_title: 'A new story',
      chapter_title: 'Introduction',
      content_count: 100,
      translation_counts: {
        hi: 15
      },
      translation_in_review_counts: {
        hi: 15
      }
    }],
    next_cursor: '6',
    more: true
  };
  let sampleSkillOpportunitiesResponse: SkillOpportunity[];
  let sampleTranslationOpportunitiesResponse: ExplorationOpportunitySummary[];
  let sampleVoiceoverOpportunitiesResponse: ExplorationOpportunitySummary[];

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    contributionOpportunitiesBackendApiService =
      TestBed.get(ContributionOpportunitiesBackendApiService);
    httpTestingController = TestBed.get(HttpTestingController);
    urlInterpolationService = TestBed.get(UrlInterpolationService);
    sampleSkillOpportunitiesResponse = [
      SkillOpportunity.createFromBackendDict(
        skillOpportunityResponse.opportunities[0])
    ];
    sampleTranslationOpportunitiesResponse = [
      ExplorationOpportunitySummary.createFromBackendDict(
        skillOpportunity.opportunities[0]
      )
    ];
    sampleVoiceoverOpportunitiesResponse = [
      ExplorationOpportunitySummary.createFromBackendDict(
        skillOpportunity.opportunities[0]
      )
    ];
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should successfully fetch the skill opportunities data',
    fakeAsync(() => {
      const successHandler = jasmine.createSpy('success');
      const failHandler = jasmine.createSpy('fail');

      contributionOpportunitiesBackendApiService.fetchSkillOpportunitiesAsync(
        '').then(
        successHandler, failHandler
      );
      const req = httpTestingController.expectOne(
        urlInterpolationService.interpolateUrl(
          '/opportunitiessummaryhandler/<opportunityType>',
          { opportunityType: 'skill' }
        ) + '?cursor='
      );
      expect(req.request.method).toEqual('GET');
      req.flush(skillOpportunityResponse);

      flushMicrotasks();

      expect(successHandler).toHaveBeenCalledWith({
        opportunities: sampleSkillOpportunitiesResponse,
        nextCursor: skillOpportunityResponse.next_cursor,
        more: skillOpportunityResponse.more
      });
      expect(failHandler).not.toHaveBeenCalled();
    })
  );

  it('should fail to fetch the skill opportunities data ' +
    'given invalid cursor ' +
    'when calling \'fetchSkillOpportunitiesAsync\'', fakeAsync(() => {
    const successHandler = jasmine.createSpy('success');
    const failHandler = jasmine.createSpy('fail');

    contributionOpportunitiesBackendApiService.fetchSkillOpportunitiesAsync(
      'invalidCursor').then(successHandler, failHandler);
    const req = httpTestingController.expectOne(
      urlInterpolationService.interpolateUrl(
        '/opportunitiessummaryhandler/<opportunityType>',
        { opportunityType: 'skill' }
      ) + '?cursor=invalidCursor'
    );

    expect(req.request.method).toEqual('GET');
    req.flush({
      error: 'Failed to fetch skill opportunities data.'
    }, {
      status: 500, statusText: 'Internal Server Error'
    });

    flushMicrotasks();

    expect(successHandler).not.toHaveBeenCalled();
    expect(failHandler).toHaveBeenCalledWith(
      new Error('Failed to fetch skill opportunities data.'));
  }));

  it('should successfully fetch the translation opportunities data',
    fakeAsync(() => {
      const successHandler = jasmine.createSpy('success');
      const failHandler = jasmine.createSpy('fail');

      contributionOpportunitiesBackendApiService
        .fetchTranslationOpportunitiesAsync('hi', 'All', '').then(
          successHandler, failHandler
        );
      const req = httpTestingController.expectOne(
        urlInterpolationService.interpolateUrl(
          '/opportunitiessummaryhandler/<opportunityType>',
          { opportunityType: 'translation' }
        ) + '?language_code=hi&topic_name=&cursor='
      );
      expect(req.request.method).toEqual('GET');
      req.flush(skillOpportunity);

      flushMicrotasks();

      expect(successHandler).toHaveBeenCalledWith({
        opportunities: sampleTranslationOpportunitiesResponse,
        nextCursor: skillOpportunity.next_cursor,
        more: skillOpportunity.more
      });
      expect(failHandler).not.toHaveBeenCalled();
    })
  );

  it('should fail to fetch the translation opportunities data ' +
    'given invalid language code ' +
    'when calling \'fetchTranslationOpportunitiesAsync\'', fakeAsync(() => {
    const successHandler = jasmine.createSpy('success');
    const failHandler = jasmine.createSpy('fail');

    contributionOpportunitiesBackendApiService
      .fetchTranslationOpportunitiesAsync(
        'invlaidCode', 'Topic', 'invalidCursor').then(
        successHandler, failHandler
      );
    const req = httpTestingController.expectOne(
      urlInterpolationService.interpolateUrl(
        '/opportunitiessummaryhandler/<opportunityType>',
        { opportunityType: 'translation' }
      ) + '?language_code=invlaidCode&topic_name=Topic&cursor=invalidCursor'
    );

    expect(req.request.method).toEqual('GET');
    req.flush({
      error: 'Failed to fetch translation opportunities data.'
    }, {
      status: 500, statusText: 'Internal Server Error'
    });
    flushMicrotasks();

    expect(successHandler).not.toHaveBeenCalled();
    expect(failHandler).toHaveBeenCalledWith(
      new Error('Failed to fetch translation opportunities data.'));
  }));

  it('should successfully fetch the voiceover opportunities data',
    fakeAsync(() => {
      const successHandler = jasmine.createSpy('success');
      const failHandler = jasmine.createSpy('fail');

      contributionOpportunitiesBackendApiService
        .fetchVoiceoverOpportunitiesAsync('hi', '',).then(
          successHandler, failHandler
        );
      const req = httpTestingController.expectOne(
        urlInterpolationService.interpolateUrl(
          '/opportunitiessummaryhandler/<opportunityType>',
          { opportunityType: 'voiceover' }
        ) + '?language_code=hi&cursor='
      );
      expect(req.request.method).toEqual('GET');
      req.flush(skillOpportunity);

      flushMicrotasks();

      expect(successHandler).toHaveBeenCalledWith({
        opportunities: sampleVoiceoverOpportunitiesResponse,
        nextCursor: skillOpportunity.next_cursor,
        more: skillOpportunity.more
      });
      expect(failHandler).not.toHaveBeenCalled();
    })
  );

  it('should fail to fetch the voiceover opportunities data ' +
    'given invalid language code ' +
    'when calling \'fetchVoiceoverOpportunitiesAsync\'', fakeAsync(() => {
    const successHandler = jasmine.createSpy('success');
    const failHandler = jasmine.createSpy('fail');

    contributionOpportunitiesBackendApiService
      .fetchVoiceoverOpportunitiesAsync('invalidCode', 'invalidCursor',).then(
        successHandler, failHandler
      );
    const req = httpTestingController.expectOne(
      urlInterpolationService.interpolateUrl(
        '/opportunitiessummaryhandler/<opportunityType>',
        { opportunityType: 'voiceover' }
      ) + '?language_code=invalidCode&cursor=invalidCursor'
    );

    expect(req.request.method).toEqual('GET');
    req.flush({
      error: 'Failed to fetch voiceover opportunities data.'
    }, {
      status: 500, statusText: 'Internal Server Error'
    });
    flushMicrotasks();

    expect(successHandler).not.toHaveBeenCalled();
    expect(failHandler).toHaveBeenCalledWith(
      new Error('Failed to fetch voiceover opportunities data.'));
  }));

  it('should successfully fetch the featured translation languages',
    fakeAsync(() => {
      const successHandler = jasmine.createSpy('success');
      const failHandler = jasmine.createSpy('fail');

      contributionOpportunitiesBackendApiService
        .fetchFeaturedTranslationLanguagesAsync()
        .then(successHandler, failHandler);

      const req = httpTestingController.expectOne(
        '/retrivefeaturedtranslationlanguages'
      );
      expect(req.request.method).toEqual('GET');
      req.flush({
        featured_translation_languages:
          [{ language_code: 'en', explanation: 'English' }]
      });

      flushMicrotasks();

      expect(successHandler).toHaveBeenCalledWith([
        FeaturedTranslationLanguage.createFromBackendDict(
          { language_code: 'en', explanation: 'English' }
        )
      ]);
      expect(failHandler).not.toHaveBeenCalled();
    })
  );

  it('should fail to fetch the featured translation languages ' +
    'when calling \'fetchFeaturedTranslationLanguagesAsync\'', fakeAsync(() => {
    const successHandler = jasmine.createSpy('success');
    const failHandler = jasmine.createSpy('fail');
    let emptyList: FeaturedTranslationLanguage[] = [];

    contributionOpportunitiesBackendApiService
      .fetchFeaturedTranslationLanguagesAsync()
      .then(successHandler, failHandler);

    const req = httpTestingController.expectOne(
      '/retrivefeaturedtranslationlanguages'
    );
    expect(req.request.method).toEqual('GET');
    req.flush({
      error: 'Failed to fetch featured translation languages.'
    }, {
      status: 500, statusText: 'Internal Server Error'
    });

    flushMicrotasks();

    expect(successHandler).toHaveBeenCalledWith(emptyList);
    expect(failHandler).not.toHaveBeenCalled();
  }));

  it('should successfully fetch all topic names', fakeAsync(() => {
    const successHandler = jasmine.createSpy('success');
    const failHandler = jasmine.createSpy('fail');

    contributionOpportunitiesBackendApiService
      .fetchAllTopicNamesAsync()
      .then(successHandler, failHandler);

    const req = httpTestingController.expectOne('/getalltopicnames');
    expect(req.request.method).toEqual('GET');
    req.flush({ topic_names: ['Topic 1', 'Topic 2'] });

    flushMicrotasks();

    expect(successHandler).toHaveBeenCalledWith(
      ['All', 'Topic 1', 'Topic 2']
    );
    expect(failHandler).not.toHaveBeenCalled();
  }));

  it('should fail to fetch all topic names when calling \'getalltopicnames',
    fakeAsync(() => {
      const successHandler = jasmine.createSpy('success');
      const failHandler = jasmine.createSpy('fail');
      const emptyResponse: string [] = [];

      contributionOpportunitiesBackendApiService
        .fetchAllTopicNamesAsync()
        .then(successHandler, failHandler);

      const req = httpTestingController.expectOne(
        '/getalltopicnames'
      );
      expect(req.request.method).toEqual('GET');
      req.flush({
        error: 'Failed to fetch all topic names.'
      }, {
        status: 500, statusText: 'Internal Server Error'
      });

      flushMicrotasks();

      expect(successHandler).toHaveBeenCalledWith(emptyResponse);
      expect(failHandler).not.toHaveBeenCalled();
    }));
});


text:
PROJ = test_tpsn_net
ROOTDIR = ../../../../..

include $(ROOTDIR)/modules/Makerules


text:
package controller;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JButton;

import model.Model;
import model.MutantModel;
import mutant.Mutant;
import reader.TriangleMutantReader;

public class MutantController implements Controller{

	private MutantModel model;
	private TriangleMutantReader reader = new TriangleMutantReader("this");
	private JButton lastButton = null;

	@Override
	public void setModel(Model m) {
		this.model = (MutantModel) m;
	}

	@Override
	public Model getModel() {
		return model;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
    	try {
            //do something with the registered model
    		//System.out.println("hello "+ e.getSource());
    		JButton temp = (JButton) e.getSource();
    		temp.setBorder(BorderFactory.createLineBorder(Color.black));
    		if(lastButton != null && lastButton != temp){
    			lastButton.setBorder(BorderFactory.createEtchedBorder());
    		}
    		lastButton = temp;
    		int n = Integer.parseInt(temp.getName());
    		//System.out.println(n);
    		model.changeCurrentMutant(n, temp);
    	} catch (Exception exception){
    		//System.out.println(exception.);
    		exception.printStackTrace();
    	}

	}

	public void readMutants(){
		ArrayList<Mutant> mutants = reader.getResults();
		model.setMutant(mutants);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Baja California</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california/mexicali-baja-california-mexico</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/geo-political/north-america-and-caribbean/mexico/baja-california/tijuana-baja-california-mexico</sem:object>
  </sem:triple>
</sem:triples>


text:
package com.commodityvectors.snapshotmatchers.playJson

import com.commodityvectors.snapshotmatchers.{SnapshotLoader, SnapshotMessages, SnapshotSerializer}
import org.scalactic.Equality
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json.{JsValue, Json, Reads}

trait PlayJsonSnapshotMatcher extends SnapshotLoader with SnapshotMessages {
  implicit lazy val playJsonSerializer = new SnapshotSerializer[JsValue] {
    override def serialize(in: JsValue): String = Json.prettyPrint(in)
  }

  class JsonDeserializerShouldMatch[T](in: T)(implicit reads: Reads[T], equals: Equality[T]) extends Matcher[String] {
    override def apply(explicitId: String): MatchResult = {
      loadSnapshot(explicitId) match {
        case Some(content) =>
          val parsed = Json.parse(content).as[T]
          val isEquals = equals.areEqual(parsed, in)
          MatchResult(isEquals, errorMessage(in.toString, parsed.toString), ContentsAreEqual)
        case None => MatchResult(matches = false, s"Could not find snapshot for id: $explicitId", ContentsAreEqual)
      }
    }
  }

  def deserializeAs[T](in: T)(implicit reads: Reads[T], equals: Equality[T]): Matcher[String] =
    new JsonDeserializerShouldMatch[T](in)
}


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

namespace Poderosa.Protocols {
    internal class MonitorableStreamTemplate<T> {
        protected LinkedList<T> _monitors;  //can be null
        protected IEnumerator<T> _enumerator;

        public void AddMonitor(T monitor) {
            if (_monitors == null)
                _monitors = new LinkedList<T>();
            _monitors.AddLast(monitor);
        }
        public void RemoveMonitor(T monitor) {
            if (_monitors != null)
                _monitors.Remove(monitor);
        }

        protected void ResetEnumerator() {
            if (_enumerator == null)
                _enumerator = _monitors.GetEnumerator();
            else
                _enumerator.Reset(); //TODO コレクションの中身変わってもResetが有効なことを確認
        }
    }

    internal class MonitorableByteAsyncInputStream : MonitorableStreamTemplate<IByteAsyncInputStream>, IByteAsyncInputStream {
        private IByteAsyncInputStream _receiver;

        public MonitorableByteAsyncInputStream(IByteAsyncInputStream receiver) {
            _receiver = receiver;
        }

        public void OnReception(ByteDataFragment data) {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.OnReception(data);
            }

            _receiver.OnReception(data);
        }

        public void OnNormalTermination() {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.OnNormalTermination();
            }

            _receiver.OnNormalTermination();
        }

        public void OnAbnormalTermination(string message) {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.OnAbnormalTermination(message);
            }

            _receiver.OnAbnormalTermination(message);
        }

    }

    internal class MonitorableByteOutputStream : MonitorableStreamTemplate<IByteOutputStream>, IByteOutputStream {
        private IByteOutputStream _transmitter;

        public MonitorableByteOutputStream(IByteOutputStream transmitter) {
            _transmitter = transmitter;
        }

        public void Transmit(ByteDataFragment data) {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.Transmit(data);
            }
            _transmitter.Transmit(data);
        }

        public void Transmit(byte[] buffer, int offset, int length) {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.Transmit(buffer, offset, length);
            }
            _transmitter.Transmit(buffer, offset, length);
        }

        public void Close() {
            if (_monitors != null) {
                ResetEnumerator();
                while (_enumerator.MoveNext())
                    _enumerator.Current.Close();
            }
            _transmitter.Close();
        }

    }
}