text:
import { describe, it } from 'mocha';
import { expect } from 'chai';
import dedent from '../../jsutils/dedent';
import { printSchema, printIntrospectionSchema } from '../schemaPrinter';
import { buildSchema } from '../buildASTSchema';
import {
  GraphQLSchema,
  GraphQLInputObjectType,
  GraphQLScalarType,
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLString,
  GraphQLInt,
  GraphQLBoolean,
  GraphQLList,
  GraphQLNonNull,
} from '../../';
import { GraphQLDirective } from '../../type/directives';
import { DirectiveLocation } from '../../language/directiveLocation';

function printForTest(schema) {
  const schemaText = printSchema(schema);
  // keep printSchema and buildSchema in sync
  expect(printSchema(buildSchema(schemaText))).to.equal(schemaText);
  return schemaText;
}

function printSingleFieldSchema(fieldConfig) {
  const Root = new GraphQLObjectType({
    name: 'Root',
    fields: { singleField: fieldConfig },
  });
  return printForTest(new GraphQLSchema({ query: Root }));
}

function listOf(type) {
  return GraphQLList(type);
}

function nonNull(type) {
  return GraphQLNonNull(type);
}

describe('Type System Printer', () => {
  it('Prints String Field', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: String
      }
    `);
  });

  it('Prints [String] Field', () => {
    const output = printSingleFieldSchema({
      type: listOf(GraphQLString),
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: [String]
      }
    `);
  });

  it('Prints String! Field', () => {
    const output = printSingleFieldSchema({
      type: nonNull(GraphQLString),
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: String!
      }
    `);
  });

  it('Prints [String]! Field', () => {
    const output = printSingleFieldSchema({
      type: nonNull(listOf(GraphQLString)),
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: [String]!
      }
    `);
  });

  it('Prints [String!] Field', () => {
    const output = printSingleFieldSchema({
      type: listOf(nonNull(GraphQLString)),
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: [String!]
      }
    `);
  });

  it('Prints [String!]! Field', () => {
    const output = printSingleFieldSchema({
      type: nonNull(listOf(nonNull(GraphQLString))),
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField: [String!]!
      }
    `);
  });

  it('Print Object Field', () => {
    const FooType = new GraphQLObjectType({
      name: 'Foo',
      fields: { str: { type: GraphQLString } },
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: { foo: { type: FooType } },
    });

    const Schema = new GraphQLSchema({ query: Root });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Foo {
        str: String
      }

      type Root {
        foo: Foo
      }
    `);
  });

  it('Prints String Field With Int Arg', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: { argOne: { type: GraphQLInt } },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int): String
      }
    `);
  });

  it('Prints String Field With Int Arg With Default', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: { argOne: { type: GraphQLInt, defaultValue: 2 } },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int = 2): String
      }
    `);
  });

  it('Prints String Field With String Arg With Default', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: { argOne: { type: GraphQLString, defaultValue: 'tes\t de\fault' } },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: String = "tes\t de\fault"): String
      }
    `);
  });

  it('Prints String Field With Int Arg With Default Null', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: { argOne: { type: GraphQLInt, defaultValue: null } },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int = null): String
      }
    `);
  });

  it('Prints String Field With Int! Arg', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: { argOne: { type: nonNull(GraphQLInt) } },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int!): String
      }
    `);
  });

  it('Prints String Field With Multiple Args', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: {
        argOne: { type: GraphQLInt },
        argTwo: { type: GraphQLString },
      },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int, argTwo: String): String
      }
    `);
  });

  it('Prints String Field With Multiple Args, First is Default', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: {
        argOne: { type: GraphQLInt, defaultValue: 1 },
        argTwo: { type: GraphQLString },
        argThree: { type: GraphQLBoolean },
      },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int = 1, argTwo: String, argThree: Boolean): String
      }
    `);
  });

  it('Prints String Field With Multiple Args, Second is Default', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: {
        argOne: { type: GraphQLInt },
        argTwo: { type: GraphQLString, defaultValue: 'foo' },
        argThree: { type: GraphQLBoolean },
      },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int, argTwo: String = "foo", argThree: Boolean): String
      }
    `);
  });

  it('Prints String Field With Multiple Args, Last is Default', () => {
    const output = printSingleFieldSchema({
      type: GraphQLString,
      args: {
        argOne: { type: GraphQLInt },
        argTwo: { type: GraphQLString },
        argThree: { type: GraphQLBoolean, defaultValue: false },
      },
    });
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Root {
        singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
      }
    `);
  });

  it('Print Interface', () => {
    const FooType = new GraphQLInterfaceType({
      name: 'Foo',
      fields: { str: { type: GraphQLString } },
    });

    const BarType = new GraphQLObjectType({
      name: 'Bar',
      fields: { str: { type: GraphQLString } },
      interfaces: [FooType],
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: { bar: { type: BarType } },
    });

    const Schema = new GraphQLSchema({
      query: Root,
      types: [BarType],
    });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Bar implements Foo {
        str: String
      }

      interface Foo {
        str: String
      }

      type Root {
        bar: Bar
      }
    `);
  });

  it('Print Multiple Interface', () => {
    const FooType = new GraphQLInterfaceType({
      name: 'Foo',
      fields: { str: { type: GraphQLString } },
    });

    const BaazType = new GraphQLInterfaceType({
      name: 'Baaz',
      fields: { int: { type: GraphQLInt } },
    });

    const BarType = new GraphQLObjectType({
      name: 'Bar',
      fields: {
        str: { type: GraphQLString },
        int: { type: GraphQLInt },
      },
      interfaces: [FooType, BaazType],
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: { bar: { type: BarType } },
    });

    const Schema = new GraphQLSchema({
      query: Root,
      types: [BarType],
    });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      interface Baaz {
        int: Int
      }

      type Bar implements Foo & Baaz {
        str: String
        int: Int
      }

      interface Foo {
        str: String
      }

      type Root {
        bar: Bar
      }
    `);
  });

  it('Print Unions', () => {
    const FooType = new GraphQLObjectType({
      name: 'Foo',
      fields: {
        bool: { type: GraphQLBoolean },
      },
    });

    const BarType = new GraphQLObjectType({
      name: 'Bar',
      fields: {
        str: { type: GraphQLString },
      },
    });

    const SingleUnion = new GraphQLUnionType({
      name: 'SingleUnion',
      types: [FooType],
    });

    const MultipleUnion = new GraphQLUnionType({
      name: 'MultipleUnion',
      types: [FooType, BarType],
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        single: { type: SingleUnion },
        multiple: { type: MultipleUnion },
      },
    });

    const Schema = new GraphQLSchema({ query: Root });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      type Bar {
        str: String
      }

      type Foo {
        bool: Boolean
      }

      union MultipleUnion = Foo | Bar

      type Root {
        single: SingleUnion
        multiple: MultipleUnion
      }

      union SingleUnion = Foo
    `);
  });

  it('Print Input Type', () => {
    const InputType = new GraphQLInputObjectType({
      name: 'InputType',
      fields: {
        int: { type: GraphQLInt },
      },
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        str: {
          type: GraphQLString,
          args: { argOne: { type: InputType } },
        },
      },
    });

    const Schema = new GraphQLSchema({ query: Root });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      input InputType {
        int: Int
      }

      type Root {
        str(argOne: InputType): String
      }
    `);
  });

  it('Custom Scalar', () => {
    const OddType = new GraphQLScalarType({
      name: 'Odd',
      serialize(value) {
        return value % 2 === 1 ? value : null;
      },
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        odd: { type: OddType },
      },
    });

    const Schema = new GraphQLSchema({ query: Root });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      scalar Odd

      type Root {
        odd: Odd
      }
    `);
  });

  it('Enum', () => {
    const RGBType = new GraphQLEnumType({
      name: 'RGB',
      values: {
        RED: { value: 0 },
        GREEN: { value: 1 },
        BLUE: { value: 2 },
      },
    });

    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        rgb: { type: RGBType },
      },
    });

    const Schema = new GraphQLSchema({ query: Root });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      schema {
        query: Root
      }

      enum RGB {
        RED
        GREEN
        BLUE
      }

      type Root {
        rgb: RGB
      }
    `);
  });

  it('Prints custom directives', () => {
    const Query = new GraphQLObjectType({
      name: 'Query',
      fields: {
        field: { type: GraphQLString },
      },
    });

    const CustomDirective = new GraphQLDirective({
      name: 'customDirective',
      locations: [DirectiveLocation.FIELD],
    });

    const Schema = new GraphQLSchema({
      query: Query,
      directives: [CustomDirective],
    });
    const output = printForTest(Schema);
    expect(output).to.equal(dedent`
      directive @customDirective on FIELD

      type Query {
        field: String
      }
    `);
  });

  it('Print Introspection Schema', () => {
    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        onlyField: { type: GraphQLString },
      },
    });
    const Schema = new GraphQLSchema({ query: Root });
    const output = printIntrospectionSchema(Schema);
    const introspectionSchema = dedent`
      schema {
        query: Root
      }

      """
      Directs the executor to include this field or fragment only when the \`if\` argument is true.
      """
      directive @include(
        """Included when true."""
        if: Boolean!
      ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

      """
      Directs the executor to skip this field or fragment when the \`if\` argument is true.
      """
      directive @skip(
        """Skipped when true."""
        if: Boolean!
      ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

      """Marks an element of a GraphQL schema as no longer supported."""
      directive @deprecated(
        """
        Explains why this element was deprecated, usually also including a suggestion
        for how to access supported similar data. Formatted in
        [Markdown](https://daringfireball.net/projects/markdown/).
        """
        reason: String = "No longer supported"
      ) on FIELD_DEFINITION | ENUM_VALUE

      """
      A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.

      In some cases, you need to provide options to alter GraphQL's execution behavior
      in ways field arguments will not suffice, such as conditionally including or
      skipping a field. Directives provide this by describing additional information
      to the executor.
      """
      type __Directive {
        name: String!
        description: String
        locations: [__DirectiveLocation!]!
        args: [__InputValue!]!
        onOperation: Boolean! @deprecated(reason: "Use \`locations\`.")
        onFragment: Boolean! @deprecated(reason: "Use \`locations\`.")
        onField: Boolean! @deprecated(reason: "Use \`locations\`.")
      }

      """
      A Directive can be adjacent to many parts of the GraphQL language, a
      __DirectiveLocation describes one such possible adjacencies.
      """
      enum __DirectiveLocation {
        """Location adjacent to a query operation."""
        QUERY

        """Location adjacent to a mutation operation."""
        MUTATION

        """Location adjacent to a subscription operation."""
        SUBSCRIPTION

        """Location adjacent to a field."""
        FIELD

        """Location adjacent to a fragment definition."""
        FRAGMENT_DEFINITION

        """Location adjacent to a fragment spread."""
        FRAGMENT_SPREAD

        """Location adjacent to an inline fragment."""
        INLINE_FRAGMENT

        """Location adjacent to a schema definition."""
        SCHEMA

        """Location adjacent to a scalar definition."""
        SCALAR

        """Location adjacent to an object type definition."""
        OBJECT

        """Location adjacent to a field definition."""
        FIELD_DEFINITION

        """Location adjacent to an argument definition."""
        ARGUMENT_DEFINITION

        """Location adjacent to an interface definition."""
        INTERFACE

        """Location adjacent to a union definition."""
        UNION

        """Location adjacent to an enum definition."""
        ENUM

        """Location adjacent to an enum value definition."""
        ENUM_VALUE

        """Location adjacent to an input object type definition."""
        INPUT_OBJECT

        """Location adjacent to an input object field definition."""
        INPUT_FIELD_DEFINITION
      }

      """
      One possible value for a given Enum. Enum values are unique values, not a
      placeholder for a string or numeric value. However an Enum value is returned in
      a JSON response as a string.
      """
      type __EnumValue {
        name: String!
        description: String
        isDeprecated: Boolean!
        deprecationReason: String
      }

      """
      Object and Interface types are described by a list of Fields, each of which has
      a name, potentially a list of arguments, and a return type.
      """
      type __Field {
        name: String!
        description: String
        args: [__InputValue!]!
        type: __Type!
        isDeprecated: Boolean!
        deprecationReason: String
      }

      """
      Arguments provided to Fields or Directives and the input fields of an
      InputObject are represented as Input Values which describe their type and
      optionally a default value.
      """
      type __InputValue {
        name: String!
        description: String
        type: __Type!

        """
        A GraphQL-formatted string representing the default value for this input value.
        """
        defaultValue: String
      }

      """
      A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all
      available types and directives on the server, as well as the entry points for
      query, mutation, and subscription operations.
      """
      type __Schema {
        """A list of all types supported by this server."""
        types: [__Type!]!

        """The type that query operations will be rooted at."""
        queryType: __Type!

        """
        If this server supports mutation, the type that mutation operations will be rooted at.
        """
        mutationType: __Type

        """
        If this server support subscription, the type that subscription operations will be rooted at.
        """
        subscriptionType: __Type

        """A list of all directives supported by this server."""
        directives: [__Directive!]!
      }

      """
      The fundamental unit of any GraphQL Schema is the type. There are many kinds of
      types in GraphQL as represented by the \`__TypeKind\` enum.

      Depending on the kind of a type, certain fields describe information about that
      type. Scalar types provide no information beyond a name and description, while
      Enum types provide their values. Object and Interface types provide the fields
      they describe. Abstract types, Union and Interface, provide the Object types
      possible at runtime. List and NonNull types compose other types.
      """
      type __Type {
        kind: __TypeKind!
        name: String
        description: String
        fields(includeDeprecated: Boolean = false): [__Field!]
        interfaces: [__Type!]
        possibleTypes: [__Type!]
        enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
        inputFields: [__InputValue!]
        ofType: __Type
      }

      """An enum describing what kind of type a given \`__Type\` is."""
      enum __TypeKind {
        """Indicates this type is a scalar."""
        SCALAR

        """
        Indicates this type is an object. \`fields\` and \`interfaces\` are valid fields.
        """
        OBJECT

        """
        Indicates this type is an interface. \`fields\` and \`possibleTypes\` are valid fields.
        """
        INTERFACE

        """Indicates this type is a union. \`possibleTypes\` is a valid field."""
        UNION

        """Indicates this type is an enum. \`enumValues\` is a valid field."""
        ENUM

        """
        Indicates this type is an input object. \`inputFields\` is a valid field.
        """
        INPUT_OBJECT

        """Indicates this type is a list. \`ofType\` is a valid field."""
        LIST

        """Indicates this type is a non-null. \`ofType\` is a valid field."""
        NON_NULL
      }
    `;
    expect(output).to.equal(introspectionSchema);
  });

  it('Print Introspection Schema with comment descriptions', () => {
    const Root = new GraphQLObjectType({
      name: 'Root',
      fields: {
        onlyField: { type: GraphQLString },
      },
    });
    const Schema = new GraphQLSchema({ query: Root });
    const output = printIntrospectionSchema(Schema, {
      commentDescriptions: true,
    });
    const introspectionSchema = dedent`
      schema {
        query: Root
      }

      # Directs the executor to include this field or fragment only when the \`if\` argument is true.
      directive @include(
        # Included when true.
        if: Boolean!
      ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

      # Directs the executor to skip this field or fragment when the \`if\` argument is true.
      directive @skip(
        # Skipped when true.
        if: Boolean!
      ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

      # Marks an element of a GraphQL schema as no longer supported.
      directive @deprecated(
        # Explains why this element was deprecated, usually also including a suggestion
        # for how to access supported similar data. Formatted in
        # [Markdown](https://daringfireball.net/projects/markdown/).
        reason: String = "No longer supported"
      ) on FIELD_DEFINITION | ENUM_VALUE

      # A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
      #
      # In some cases, you need to provide options to alter GraphQL's execution behavior
      # in ways field arguments will not suffice, such as conditionally including or
      # skipping a field. Directives provide this by describing additional information
      # to the executor.
      type __Directive {
        name: String!
        description: String
        locations: [__DirectiveLocation!]!
        args: [__InputValue!]!
        onOperation: Boolean! @deprecated(reason: "Use \`locations\`.")
        onFragment: Boolean! @deprecated(reason: "Use \`locations\`.")
        onField: Boolean! @deprecated(reason: "Use \`locations\`.")
      }

      # A Directive can be adjacent to many parts of the GraphQL language, a
      # __DirectiveLocation describes one such possible adjacencies.
      enum __DirectiveLocation {
        # Location adjacent to a query operation.
        QUERY

        # Location adjacent to a mutation operation.
        MUTATION

        # Location adjacent to a subscription operation.
        SUBSCRIPTION

        # Location adjacent to a field.
        FIELD

        # Location adjacent to a fragment definition.
        FRAGMENT_DEFINITION

        # Location adjacent to a fragment spread.
        FRAGMENT_SPREAD

        # Location adjacent to an inline fragment.
        INLINE_FRAGMENT

        # Location adjacent to a schema definition.
        SCHEMA

        # Location adjacent to a scalar definition.
        SCALAR

        # Location adjacent to an object type definition.
        OBJECT

        # Location adjacent to a field definition.
        FIELD_DEFINITION

        # Location adjacent to an argument definition.
        ARGUMENT_DEFINITION

        # Location adjacent to an interface definition.
        INTERFACE

        # Location adjacent to a union definition.
        UNION

        # Location adjacent to an enum definition.
        ENUM

        # Location adjacent to an enum value definition.
        ENUM_VALUE

        # Location adjacent to an input object type definition.
        INPUT_OBJECT

        # Location adjacent to an input object field definition.
        INPUT_FIELD_DEFINITION
      }

      # One possible value for a given Enum. Enum values are unique values, not a
      # placeholder for a string or numeric value. However an Enum value is returned in
      # a JSON response as a string.
      type __EnumValue {
        name: String!
        description: String
        isDeprecated: Boolean!
        deprecationReason: String
      }

      # Object and Interface types are described by a list of Fields, each of which has
      # a name, potentially a list of arguments, and a return type.
      type __Field {
        name: String!
        description: String
        args: [__InputValue!]!
        type: __Type!
        isDeprecated: Boolean!
        deprecationReason: String
      }

      # Arguments provided to Fields or Directives and the input fields of an
      # InputObject are represented as Input Values which describe their type and
      # optionally a default value.
      type __InputValue {
        name: String!
        description: String
        type: __Type!

        # A GraphQL-formatted string representing the default value for this input value.
        defaultValue: String
      }

      # A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all
      # available types and directives on the server, as well as the entry points for
      # query, mutation, and subscription operations.
      type __Schema {
        # A list of all types supported by this server.
        types: [__Type!]!

        # The type that query operations will be rooted at.
        queryType: __Type!

        # If this server supports mutation, the type that mutation operations will be rooted at.
        mutationType: __Type

        # If this server support subscription, the type that subscription operations will be rooted at.
        subscriptionType: __Type

        # A list of all directives supported by this server.
        directives: [__Directive!]!
      }

      # The fundamental unit of any GraphQL Schema is the type. There are many kinds of
      # types in GraphQL as represented by the \`__TypeKind\` enum.
      #
      # Depending on the kind of a type, certain fields describe information about that
      # type. Scalar types provide no information beyond a name and description, while
      # Enum types provide their values. Object and Interface types provide the fields
      # they describe. Abstract types, Union and Interface, provide the Object types
      # possible at runtime. List and NonNull types compose other types.
      type __Type {
        kind: __TypeKind!
        name: String
        description: String
        fields(includeDeprecated: Boolean = false): [__Field!]
        interfaces: [__Type!]
        possibleTypes: [__Type!]
        enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
        inputFields: [__InputValue!]
        ofType: __Type
      }

      # An enum describing what kind of type a given \`__Type\` is.
      enum __TypeKind {
        # Indicates this type is a scalar.
        SCALAR

        # Indicates this type is an object. \`fields\` and \`interfaces\` are valid fields.
        OBJECT

        # Indicates this type is an interface. \`fields\` and \`possibleTypes\` are valid fields.
        INTERFACE

        # Indicates this type is a union. \`possibleTypes\` is a valid field.
        UNION

        # Indicates this type is an enum. \`enumValues\` is a valid field.
        ENUM

        # Indicates this type is an input object. \`inputFields\` is a valid field.
        INPUT_OBJECT

        # Indicates this type is a list. \`ofType\` is a valid field.
        LIST

        # Indicates this type is a non-null. \`ofType\` is a valid field.
        NON_NULL
      }
    `;
    expect(output).to.equal(introspectionSchema);
  });
});


text:
A stupid quotes tracking platform for myself and you. Every now and then I come across
interesting quotes or text snippets in movies, books, poems, speeches,
discussions, anime etc

I can't count how many files i've created to track these. It is also more
cumbersome to look for any of those files, and then start to try to read them :-)

More inspiration is needed for that than to visit a webpage or webapp and add a given quote or interesting text snippet so I can visit any time and from anywhere.

Also, making it a webapp exposes it to others to contribute too. More awareness
will be created and there will be some sort of sharing and discovery...

## How to Install
Quotos in built in go, html, css and js

A running version is hosted on google appengine:
http://quotos-1322.appspot.com/

To get a local copy:

1. Install the go runtime for google appengine:

redpajama_set_name: RedPajamaGithub


text:
package com.madhu.mr.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import com.madhu.mr.CounterMap;
import com.madhu.mr.MapReduceJob;

public class CounterPanel extends JPanel {
	/**
	 * Create the panel.
	 */
	public CounterPanel(MapReduceJob job) {
		setBorder(new TitledBorder(null, "Counters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setLayout(new BorderLayout(0, 0));

		JTable table = new JTable();
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);

		CounterMap cm = job.getCounterMap();

		ArrayList<String[]> data = new ArrayList<String[]>();
		ArrayList<String> groups = new ArrayList<String>(cm.getGroups());
		Collections.sort(groups);
		for (String group : groups) {
			ArrayList<String> names = new ArrayList<String>(cm.getNames(group));
			Collections.sort(names);
			String gt = group;
			for (String name : names) {
				String value = Long.toString(cm.getCounter(group, name).getValue());
				String[] row = { gt, name, value };
				data.add(row);
				gt = "";
			}
		}

		Object[] columnNames = new String[] { "Group", "Name", "Value" };
		DefaultTableModel model = new DefaultTableModel(columnNames, 0);
		int rowCount = data.size();
		for (int i = 0; i < rowCount; i++) {
			model.addRow(data.get(i));
		}

		table.setPreferredScrollableViewportSize(new Dimension(425, 100));
		table.setModel(model);
	}
}


text:
export enum AutheticationProtocol {
    SAML = "SAML",
    Kerberos = "Kerberos",
    NativeGrafana = "NativeGrafana",
    JWT = "JWT"
}

export enum RequestHeader {
    WEBAUTHUSER = "user",
    AUTH_TOKEN = "Authorization"
}


text:
import 'angular-material';
import 'angular-ui-router';

import angular from 'angular';

import countdownDirectiveModule from 'components/countdown-directive/countdown-module';
import fileInputDirectiveModule from 'components/file-input-directive/file-input-module';
import fileDropDirectiveModule from 'components/file-drop-directive/file-drop-module';
import errorToastServiceModule from 'components/error-toast-service/error-toast-module';
import pageVisibilityServiceModule from 'components/page-visibility-service/page-visibility-module';

import './index-styles.css!';

import playButtonIcon from './assets/ic_play_arrow_24px.svg!text';
import uploadButtonIcon from './assets/ic_file_upload_24px.svg!text';
import shuffleButtonIcon from './assets/ic_shuffle_24px.svg!text';
import cycleButtonIcon from './assets/ic_loop_24px.svg!text';

import configure from './index-config';
import IndexController from './index-controller';

const module = angular.module('app.index', [
  'ngMaterial', 'ui.router',
  countdownDirectiveModule.name,
  fileInputDirectiveModule.name,
  fileDropDirectiveModule.name,
  errorToastServiceModule.name,
  pageVisibilityServiceModule.name
]);

module.run(($templateCache) => {
  $templateCache.put('ic_play_arrow_24px.svg', playButtonIcon);
  $templateCache.put('ic_file_upload_24px.svg', uploadButtonIcon);
  $templateCache.put('ic_shuffle_24px.svg', shuffleButtonIcon);
  $templateCache.put('ic_loop_24px.svg', cycleButtonIcon);
});

configure(module);
IndexController.register(module);

export default module;


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.domain.datasource.ingestion.file;

import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Created by kyungtaak on 2017. 4. 30..
 */
@JsonTypeName("parquet")
public class ParquetFileFormat implements FileFormat {

  String compress;

  public ParquetFileFormat() {
  }

  @Override
  public String getInputFormat() {
    return "io.druid.data.input.parquet.DruidParquetInputFormat";
  }

  public String getCompress() {
    return compress;
  }

  public void setCompress(String compress) {
    this.compress = compress;
  }
}


text:
import { createHash } from "crypto";
import { MessageResponse, Wit, WitContext } from "node-wit";
import CacheAdapter from "./adapters/CacheAdapter";
import MemcachedAdapter from "./adapters/MemcachedAdapter";
import RedisAdapter from "./adapters/RedisAdapter";
import {
    CacheClients,
    IEntity,
    IIntentRecognizerResult,
    IOptions,
    IRecognizeContext,
    IWitResults,
    MessageHandler,
} from "./types";

/**
 * The WitRecognizer class that is used in conjunction with an IntentDialog.
 * Example:
 * const recognizer = new WitRecognizer('Wit.ai_access_token');
 * const dialog = new IntentDialog({recognizers: [recognizer]});
 */
export class WitRecognizer {
    public witClient: Wit;
    public cacheAdapter: CacheAdapter = null;

    /**
     * Creates an instance of WitRecognizer.
     * @param accessToken {string} API token from Wit.ai
     * @param options {IOptions}
     */
    constructor(accessToken: string, options: IOptions = {}) {
        const { cache } = options;

        if (!accessToken || typeof accessToken !== "string") {
            const msg = "Constructor must be invoked with an accessToken of type \"string\"";
            throw new Error(msg);
        }
        this.witClient = new Wit({ accessToken });

        // Evaluate the type of the cache client
        // Instantiate a corresponding adapter
        if (cache) {
            // By default, key's will expire after 3 hours
            const expire = typeof options.expire === "number" ? options.expire : 3 * 3600;
            const clientType = this.getClientType(cache);

            if (clientType !== CacheClients.Unknown) {
                const _message = this.witClient.message;
                // Override the original message function with a new implementation
                // that checks the cache first before sending a request to Wit.ai.
                // The response from Wit.ai is then stored in the cache.
                this.witClient.message = this.witDecorator(_message);
            }

            // Instantiate the client's corresponding adapter
            switch (clientType) {
                case CacheClients.Redis:
                    this.cacheAdapter = new RedisAdapter(cache, expire);
                    break;
                case CacheClients.Memcached:
                    this.cacheAdapter = new MemcachedAdapter(cache, expire);
                    break;
                default: // CacheClients.Unknown
                    const msg = "Invalid cache client. See the module's README.md for more details";
                    throw new Error(msg);
            }
        }
    }

    /**
     * Makes a request to Wit.ai and parses the response in a way the Bot Builder SDK understands.
     * @param {IRecognizeContext} context - contains the message received from the user
     * @param {function} done - the result callback
     */
    public recognize(context: IRecognizeContext, done: (err: Error, result: IIntentRecognizerResult) => void) {
        const result = { score: 0.0, intent: null } as IIntentRecognizerResult;
        if (context && context.message && context.message.text) {
            const utterance = context.message.text;

            // Send a request to Wit.ai
            this.witClient.message(utterance, {} as WitContext)
                .then((response: IWitResults) => {
                    // Check if Wit.ai responded with an error
                    if (response.error) {
                        return done(new Error(response.error), null);
                    }

                    // Wit.ai currently does not support multiple intents.
                    // The intent property is either undefined or an array with a single object.
                    // Also note that, unlike LUIS.ai, Wit.ai treats an intent like a regular entity
                    const { intent, ...entities } = response.entities;
                    const hasOtherEntities = Object.keys(entities).length > 0;

                    // If there no useful response from Wit.ai, trigger the IntentDialog's default handler
                    if (!intent && !hasOtherEntities) {
                        return done(null, result);
                    }

                    if (intent) {
                        const { value, confidence } = intent[0];
                        // Update the default values for intent (null) and score (0.0)
                        result.intent = value;
                        result.score = confidence;
                        result.intents = [{ intent: value, score: confidence }];
                    }

                    if (hasOtherEntities) {
                        // If Wit.ai did not discover any intent, but it did find other entities,
                        // the result's score property must not be left to its default value of null.
                        // Otherwise, the Bot Builder SDK will trigger the dialog's default handler
                        // with a default result object => { score: 0.0, intent: null }.
                        // Any other entities will not be included. The action below prevents this behavior.
                        // Setting score to 0.1 lets the intent still be triggered but keeps it from
                        // stomping on other models.
                        if (!result.intent) {
                            result.intent = "none";
                            result.score = 0.1;
                        }

                        result.entities = [];
                        for (const key of Object.keys(entities)) {
                            for (const entity of entities[key]) {
                                const { type, value, confidence } = entity;
                                const foundEntity = {
                                    type: key,
                                    entity: null, // default value
                                    rawEntity: entity as {[key: string]: any},
                                    score: confidence,
                                } as IEntity;

                                // In most cases the entity's in the response from Wit.ai will be of type "value".
                                // There are other possible types, like "interval", in which case there will be a
                                // "values" property instead. To deal with this variety of structures, there's a
                                // "rawEntity" property to allow for custom entity processing in your own code.
                                if (type === "value") {
                                    // Overwrite the default value null, with a value that must be a string.
                                    foundEntity.entity = value;
                                    // The startIndex and endIndex values will not always be useful.
                                    // For example, a datetime entity of type "value" will get a universal timestamp
                                    // as its value which cannot be found in the original message.
                                    foundEntity.startIndex = response._text.indexOf(value);
                                    foundEntity.endIndex = foundEntity.startIndex + (value.length - 1);
                                }
                                result.entities.push(foundEntity);
                            }
                        }
                    }
                    done(null, result);
                })
                .catch((err: Error) => {
                    done(err, null);
                });
        } else {
            done(null, result);
        }
    }

    /**
     * Determines the type of the provided cache client.
     * @param {*} client - the client with which the results will be saved to the cache.
     * @returns {CacheClients} any of the possible enum values
     */
    public getClientType(client: any): CacheClients {
        let clientType = CacheClients.Unknown;

        if (typeof client === "object" && client.constructor) {
            switch (client.constructor.name) {
                case "RedisClient":
                    clientType = CacheClients.Redis;
                    break;
                case "Client":
                    clientType = CacheClients.Memcached;
            }
        }

        return clientType;
    }

    /**
     * The decorator function that adds caching to the Wit.ai request/response cycle.
     * @param {function} message - the original Wit.message function that will be decorated
     * @returns {function} the decorated function
     */
     private witDecorator(message: MessageHandler): MessageHandler {
        return (utterance, context) => {
            // Create hash from the utterance.
            const hash = createHash("sha256").update(utterance);
            const key = hash.digest("hex");

            return new Promise<MessageResponse>((resolve, reject) => {
                // Check if the key exists
                this.cacheAdapter.get(key, (error, result) => {
                    if (error) {
                        console.error(error);
                        // If something failed while accessing the cache,
                        // it's still possible to continue and access Wit.ai,
                        // so there is no need to invoke reject(error)
                        return resolve(null);
                    }

                    try {
                        resolve(result ? JSON.parse(result) : null);
                    } catch (error) {
                        resolve(null);
                    }
                });
            }).then((result) => {
                if (result) {
                    // Reset expire to initial value
                    this.cacheAdapter.touch(key, (error, result) => {
                        if (error) { console.error(error); }
                    });
                    // Return the result, skip Wit.ai
                    return Promise.resolve(result);
                } else {
                    // No cached result was found, use Wit.ai to parse the utterance
                    const witPromise = message(utterance, context);
                    witPromise.then((result: IWitResults) => {
                        // Cache the result from Wit.ai unless it contains an error message
                        // Possible error would be: "Bad auth, check token/params"
                        if (!result.error) {
                            const value = JSON.stringify(result);
                            this.cacheAdapter.set(key, value, (error, result) => {
                                if (error) { console.error(error); }
                            });
                        }
                    }).catch((error: Error) => {
                        console.error(error);
                    });

                    return witPromise;
                }
            });
        };
    }
}


text:
package ucar.nc2.dataset;

import org.junit.BeforeClass;
import org.junit.Test;
import ucar.nc2.Attribute;
import ucar.nc2.Group;
import ucar.nc2.NetcdfFile;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.dataset.conv.CfSubConvForTest;
import ucar.nc2.dataset.conv.CfSubConvForTestConvList;
import ucar.nc2.internal.dataset.CoordSystemBuilder;
import ucar.nc2.internal.dataset.CoordSystemFactory;
import ucar.nc2.internal.dataset.conv.CF1Convention;

import static com.google.common.truth.Truth.assertThat;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class TestCfSubConventionProvider {

  private static final NetcdfDataset.Builder<?> CF_NCDB = NetcdfDataset.builder();
  private static final NetcdfDataset.Builder<?> YOLO_EXACT_NCDB = NetcdfDataset.builder();
  private static final NetcdfDataset.Builder<?> YOLO_PARTIAL_NCDB = NetcdfDataset.builder();
  private static final NetcdfDataset.Builder<?> HECK_NCDB = NetcdfDataset.builder();

  @BeforeClass
  public static void makeNcdBuilders() throws IOException {
    NetcdfFile.Builder<?> cfNcfb = NetcdfFile.builder();
    NetcdfFile.Builder<?> yoloExactNcfb = NetcdfFile.builder();
    NetcdfFile.Builder<?> yoloPartialNcfb = NetcdfFile.builder();
    NetcdfFile.Builder<?> heckNcfb = NetcdfFile.builder();

    Group.Builder cfRoot = Group.builder().setName("");
    cfNcfb.setRootGroup(cfRoot);
    Attribute cfConvAttr = Attribute.builder(CDM.CONVENTIONS).setStringValue("CF-1.6").build();
    cfRoot.addAttribute(cfConvAttr);
    try (NetcdfFile cfNcf = cfNcfb.build()) {
      CF_NCDB.copyFrom(cfNcf);
      CF_NCDB.setOrgFile(cfNcf);
    } catch (IOException ioe) {
      throw new IOException("Error building NetcdfFile object to mock a CF netCDF file for testing.", ioe);
    }

    Group.Builder yoloExactRoot = Group.builder().setName("");
    yoloExactNcfb.setRootGroup(yoloExactRoot);
    // exactly match the convention name
    Attribute yoloExactConvAttr =
        Attribute.builder(CDM.CONVENTIONS).setStringValue(CfSubConvForTest.CONVENTION_NAME).build();
    yoloExactRoot.addAttribute(yoloExactConvAttr);
    try (NetcdfFile yoloExactNcf = yoloExactNcfb.build()) {
      YOLO_EXACT_NCDB.copyFrom(yoloExactNcf);
      YOLO_EXACT_NCDB.setOrgFile(yoloExactNcf);
    } catch (IOException ioe) {
      throw new IOException("Error building NetcdfFile object to mock a CF/YOLO netCDF file for testing.", ioe);
    }

    Group.Builder yoloPartialRoot = Group.builder().setName("");
    yoloPartialNcfb.setRootGroup(yoloPartialRoot);
    // change up the convention name used so that it is not an exact match with the test convention name
    Attribute yoloPartialConvAttr = Attribute.builder(CDM.CONVENTIONS)
        .setStringValue(
            CfSubConvForTest.CONVENTION_NAME.replaceFirst(CfSubConvForTest.CONVENTAION_NAME_STARTS_WITH, "CF-1.200"))
        .build();
    yoloPartialRoot.addAttribute(yoloPartialConvAttr);
    try (NetcdfFile yoloPartialNcf = yoloPartialNcfb.build()) {
      YOLO_PARTIAL_NCDB.copyFrom(yoloPartialNcf);
      YOLO_PARTIAL_NCDB.setOrgFile(yoloPartialNcf);
    } catch (IOException ioe) {
      throw new IOException("Error building NetcdfFile object to mock a CF/YOLO netCDF file for testing.", ioe);
    }

    Group.Builder heckfRoot = Group.builder().setName("");
    heckNcfb.setRootGroup(heckfRoot);
    // this one will uses a CFSubConventionProvider that checks the conventions list for a match
    Attribute convAttr =
        Attribute.builder(CDM.CONVENTIONS).setStringValue(CfSubConvForTestConvList.CONVENTION_NAME).build();
    heckfRoot.addAttribute(convAttr);
    try (NetcdfFile heckNcf = heckNcfb.build()) {
      HECK_NCDB.copyFrom(heckNcf);
      HECK_NCDB.setOrgFile(heckNcf);
      HECK_NCDB.setEnhanceMode(NetcdfDataset.getDefaultEnhanceMode());
    } catch (IOException ioe) {
      throw new IOException("Error building NetcdfFile object to mock a CF/HECK netCDF file for testing.", ioe);
    }
  }

  @Test
  public void testCfSubLoadOrder() throws IOException {
    Optional<CoordSystemBuilder> cfFacOpt = CoordSystemFactory.factory(CF_NCDB, null);
    assertThat(cfFacOpt.isPresent());
    CoordSystemBuilder cfFac = cfFacOpt.get();
    assertThat(cfFac).isInstanceOf(CF1Convention.class);
    NetcdfDataset ncd = CF_NCDB.build();
    assertThat(ncd).isNotNull();
    Attribute csbAttr = ncd.findGlobalAttribute(_Coordinate._CoordSysBuilder);
    assertThat(csbAttr).isNotNull();
    String csb = csbAttr.getStringValue();
    assertThat(csb).isNotNull();
    assertThat(csb).isEqualTo(CF1Convention.class.getCanonicalName());

    // both datasets (exact and partial matches of the sub-convention name) should result in the
    // sub-convention being used.
    List<NetcdfDataset.Builder<?>> subConvBuilders = Arrays.asList(YOLO_EXACT_NCDB, YOLO_PARTIAL_NCDB);
    for (NetcdfDataset.Builder<?> subConvBuilder : subConvBuilders) {
      Optional<CoordSystemBuilder> yoloFacOpt = CoordSystemFactory.factory(subConvBuilder, null);
      assertThat(yoloFacOpt.isPresent());
      CoordSystemBuilder yoloFac = yoloFacOpt.get();
      assertThat(yoloFac).isInstanceOf(CfSubConvForTest.class);
      assertThat(yoloFac.getConventionUsed()).isEqualTo(CfSubConvForTest.CONVENTION_NAME);
      ncd = subConvBuilder.build();
      assertThat(ncd).isNotNull();
      csbAttr = ncd.findGlobalAttribute(_Coordinate._CoordSysBuilder);
      assertThat(csbAttr).isNotNull();
      csb = csbAttr.getStringValue();
      assertThat(csb).isNotNull();
      assertThat(csb).isEqualTo(CfSubConvForTest.class.getCanonicalName());
    }
  }

  @Test
  public void testCfSubUsingConvList() throws IOException {
    Optional<CoordSystemBuilder> heckFacOpt = CoordSystemFactory.factory(HECK_NCDB, null);
    assertThat(heckFacOpt.isPresent());
    CoordSystemBuilder heckFac = heckFacOpt.get();
    assertThat(heckFac).isInstanceOf(CfSubConvForTestConvList.class);
    assertThat(heckFac.getConventionUsed()).isEqualTo(CfSubConvForTestConvList.CONVENTION_NAME);
    NetcdfDataset ncd = HECK_NCDB.build();
    assertThat(ncd).isNotNull();
    Attribute csbAttr = ncd.findGlobalAttribute(_Coordinate._CoordSysBuilder);
    assertThat(csbAttr).isNotNull();
    String csb = csbAttr.getStringValue();
    assertThat(csb).isNotNull();
    assertThat(csb).isEqualTo(CfSubConvForTestConvList.class.getCanonicalName());
  }
}


text:
(() => {
  'use strict';

  function BettyCardController() {
    this.changeCard = function changeCard() {
      // TODO: Stripe prompt!
    };
  }

  angular.module('betty.home').controller('BettyCardController',
      BettyCardController);
})();


text:
<?php
return array (
  'Installed' => '',
  'No modules found!' => '',
  'No purchased modules found!' => '',
  'Register' => 'Registre',
  'Search' => 'Cerca',
  'Third-party' => '',
  'search for available modules online' => '',
);


text:
package org.steamflake.metamodel.api.structure.relationships;

import org.steamflake.metamodel.api.elements.IRelationship;
import org.steamflake.metamodel.api.structure.entities.IAbstractNamespace;
import org.steamflake.metamodel.api.structure.entities.INamespace;

/**
 * Parent/child relationship from abstract namespaces to namespaces.
 */
public interface INamespaceContainment
    extends IRelationship<INamespaceContainment, IAbstractNamespace, INamespace> {

    /**
     * @return the child namespace of the relationship.
     */
    default INamespace getContainedNamespace() {
        return this.getTo();
    }

    /**
     * @return the parent namespace of the relationship.
     */
    default IAbstractNamespace getContainingNamespace() {
        return this.getFrom();
    }

}


text:
package main

import (
  "../../" // Point this to mango
)

// Our custom middleware
func SilenceErrors(env mango.Env, app mango.App) (mango.Status, mango.Headers, mango.Body) {
	// Call our upstream app
	status, headers, body := app(env)

	// If we got an error
	if status == 500 {
		// Silence it!
		status = 200
		headers = mango.Headers{}
		body = "Silence is golden!"
	}

	// Pass the response back to the client
	return status, headers, body
}

// Our default handler
func Hello(env mango.Env) (mango.Status, mango.Headers, mango.Body) {
  //Return 500 to trigger the silence
	return 500, mango.Headers{}, mango.Body("Hello World!")
}

func main() {
  stack := new(mango.Stack)
  stack.Address = ":3000"

  stack.Middleware(SilenceErrors) // Include our custom middleware

  stack.Run(Hello)
}


text:
<?php

Route::group(array('before' => 'auth'), function()
{
	Route::get('/', ['uses' => 'ReceptionistController@dashboard']);

	/* Property */
	Route::resource('property', 'PropertyController', array('only' => array('index', 'show')));
	Route::post('/property/image', ['uses' => 'PropertyController@add_image']);

	/* Branch */
	Route::resource('branch', 'BranchController', array('only' => array('index', 'show')));

	/* User */
	Route::resource('user', 'UserController', array('only' => array('index')));

	/* Customer */
	Route::resource('customer', 'CustomerController');
	Route::post('/verify-email', ['uses' => 'CustomerController@verify']);

});


text:
class Dhs1426Pdf
  PDF_DIRECTORY = "app/lib/pdfs".freeze
  SOURCE_PDF = "#{PDF_DIRECTORY}/DHS_1426.pdf".freeze
  COVERSHEET_PDF = "#{PDF_DIRECTORY}/DHS_1426_cover_letter.pdf".freeze
  STEP_2_ADDITIONAL_MEMBER_PDF =
    "#{PDF_DIRECTORY}/DHS_1426_step_2_additional_member.pdf".freeze
  MAXIMUM_HOUSEHOLD_MEMBERS = 2

  def initialize(medicaid_application:)
    @medicaid_application = medicaid_application
  end

  def completed_file
    fill_template_pdf_with_client_data
    fill_step_2_pdf_for_additional_members
    assemble_complete_application(temp_pdf_files)
  ensure
    temp_pdf_files.map do |t|
      t.close
      t.unlink
    end
  end

  private

  attr_reader :medicaid_application

  def fill_template_pdf_with_client_data
    PdfForms.new.fill_form(SOURCE_PDF, filled_in_application.path, client_data)
  end

  def fill_step_2_pdf_for_additional_members
    if application_members.length > MAXIMUM_HOUSEHOLD_MEMBERS
      additional_members.each_with_index do |record, index|
        member_data = MedicaidApplicationMemberAttributes.new(record).to_h
        member_tax_data = MedicaidApplicationAdditionalMemberTaxAttributes.
          new(member: record[:member]).to_h
        data = member_data.merge(member_tax_data)
        output_file = additional_member_pdf_output(index)

        PdfForms.new.fill_form(STEP_2_ADDITIONAL_MEMBER_PDF,
                               output_file.path,
                               data)

        additional_household_member_pages << output_file
      end
    end
  end

  def additional_members
    @_additional_members ||= application_members[2..-1].map do |member|
      { member: member, position: "second" }
    end
  end

  def temp_pdf_files
    @_temp_pdf_files ||= [
      filled_in_application,
      additional_household_member_pages,
      verification_documents,
    ].reject(&:blank?).flatten
  end

  def assemble_complete_application(filled_in_pdfs)
    PdfBuilder.new(
      output_file: complete_application,
      files: [File.open(COVERSHEET_PDF)] + filled_in_pdfs,
    ).pdf
  end

  def filled_in_application
    @_filled_in_application ||= Tempfile.new(["medicaid_app", ".pdf"], "tmp/")
  end

  def additional_member_pdf_output(index)
    Tempfile.new(["medicaid_additional_member_#{index}", ".pdf"], "tmp/")
  end

  def additional_household_member_pages
    @_additional_household_member_pages ||= []
  end

  def complete_application
    @_complete_application ||= Tempfile.new(
      ["medicaid_app_complete", ".pdf"],
      "tmp/",
    )
  end

  def client_data
    medicaid_application_attributes.
      merge(member_attributes)
  end

  def medicaid_application_attributes
    MedicaidApplicationAttributes.
      new(medicaid_application: medicaid_application).
      to_h
  end

  def member_attributes
    first_member_attributes.merge(second_member_attributes)
  end

  def first_member_attributes
    MedicaidApplicationMemberAttributes.
      new(member: application_members[0], position: "primary").to_h.merge(
        primary_member_tax_attributes,
      )
  end

  def primary_member_tax_attributes
    MedicaidApplicationPrimaryMemberTaxAttributes.
      new(member: primary_member).to_h
  end

  def second_member_attributes
    if second_member.present?
      MedicaidApplicationMemberAttributes.
        new(member: second_member, position: "second").to_h.merge(
          second_member_tax_attributes,
        )
    else
      {}
    end
  end

  def second_member_tax_attributes
    MedicaidApplicationAdditionalMemberTaxAttributes.
      new(member: second_member).to_h
  end

  def application_members
    @_application_members ||= medicaid_application.members.order(:id)
  end

  def first_two_members
    [
      { member: primary_member, position: "primary" },
      { member: second_member, position: "second" },
    ]
  end

  def primary_member
    application_members[0]
  end

  def second_member
    application_members[1]
  end

  def verification_documents
    verification_paperwork.map do |document|
      VerificationDocument.new(
        url: document,
        benefit_application: medicaid_application,
      ).output_file
    end.reject { |document| document.path.nil? }
  end

  def verification_paperwork
    medicaid_application.paperwork || []
  end
end


text:
package io.cdap.wrangler.utils;

import io.cdap.wrangler.api.annotations.PublicEvolving;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * This class allows one to serialize the object of T into bytes.
 *
 * @param <T> type of object to serialize
 */
@PublicEvolving
public final class ObjectSerDe<T> {

  /**
   * Converts an object of type T into bytes.
   *
   * @param object to be serialized into bytes.
   * @return byte array of serialized object.
   */
  public byte[] toByteArray(T object) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutput out = new ObjectOutputStream(bos)) {
      out.writeObject(object);
    }
    return bos.toByteArray();
  }

  /**
   * Converts a serialized object byte array back into object.
   *
   * @param bytes to be converted to object of type T.
   * @return an instance of object deserialized from the byte array.
   * @see ObjectSerDe#toByteArray(Object)
   */
  public T toObject(byte[] bytes) throws IOException, ClassNotFoundException {
    try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
      return (T) in.readObject();
    }
  }
}


text:
package moe.minori.pgpclipper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.Objects;

import androidx.core.app.NotificationCompat;
import moe.minori.pgpclipper.activities.PGPClipperResultShowActivity;
import moe.minori.pgpclipper.util.PGPBlockDetector;

/**
 * Created by Minori on 2015-09-26.
 */
public class PGPClipperService extends Service {

    private static final String CHANNEL_ID = "PGPCLIPPER_NOTIFICATION";

    ClipboardManager clipboardManager;
    ClipboardManager.OnPrimaryClipChangedListener onPrimaryClipChangedListener;

    public static final String TRY_DECRYPT = "TRY_DECRYPT";
    public static final String DATA = "DATA";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        startClipboardMonitoring();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        stopClipboardMonitoring();

    }

    private void startClipboardMonitoring() {
        clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        if (clipboardManager != null) {
            clipboardManager.addPrimaryClipChangedListener(onPrimaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
                @Override
                public void onPrimaryClipChanged() {
                    Log.d("PGPClipperService", "Clipboard data change detected!");

                    // get current clipboard data to string
                    String currentData;

                    if (clipboardManager.hasPrimaryClip() && Objects.requireNonNull(clipboardManager.getPrimaryClipDescription()).hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                        try {
                            currentData = Objects.requireNonNull(clipboardManager.getPrimaryClip()).getItemAt(0).getText().toString();
                        } catch (NullPointerException e) {
                            // should not happen since clipboard contains text, but returned null.
                            // best effort String parsing

                            try {
                                currentData = clipboardManager.getPrimaryClip().getItemAt(0).coerceToText(PGPClipperService.this).toString();

                            } catch (Exception e2) {
                                // best attempt failed... return this method

                                return;
                            }

                        }
                    } else {
                        return;
                    }

                    // tidy once
                    currentData = PGPBlockDetector.pgpInputTidy(currentData);

                    // check if this contains ASCII armored PGP data

                    if (PGPBlockDetector.isBlockPresent(currentData)) {
                        // notify user

                        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                        Intent intentToLaunchWhenNotificationClicked = new Intent(getApplicationContext(), PGPClipperService.class);
                        intentToLaunchWhenNotificationClicked.putExtra(TRY_DECRYPT, true);
                        intentToLaunchWhenNotificationClicked.putExtra(DATA, currentData);

                        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intentToLaunchWhenNotificationClicked, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_UPDATE_CURRENT);

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                CharSequence name = getString(R.string.channel_name);
                                String description = getString(R.string.channel_description);
                                int importance = NotificationManager.IMPORTANCE_HIGH;
                                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                                channel.setDescription(description);
                                // Register the channel with the system; you can't change the importance
                                // or other notification behaviors after this
                                notificationManager.createNotificationChannel(channel);
                            }

                        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                                .setSmallIcon(R.drawable.ic_noti)
                                .setTicker(getString(R.string.NotificationTickerText))
                                .setContentTitle(getString(R.string.NotificationTitleText))
                                .setContentText(getString(R.string.NotificationContentText))
                                .setDefaults(Notification.DEFAULT_LIGHTS)
                                .setContentIntent(pendingIntent)
                                .setPriority(NotificationCompat.PRIORITY_MAX)
                                .setWhen(System.currentTimeMillis())
                                .setAutoCancel(true);

                        notificationManager.notify(8591274, notificationBuilder.build());
                    }

                }
            });
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("PGPClipperService", "onStartCommand called!");

        if (intent != null) {
            if (intent.getBooleanExtra(TRY_DECRYPT, false)) {
                Log.d("PGPClipperService", "Trying Decryption/Verification");
                Intent launchActivity = new Intent(getApplicationContext(), PGPClipperResultShowActivity.class);
                launchActivity.putExtra(DATA, intent.getStringExtra(DATA));
                launchActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(launchActivity);
            }
        }

        return START_STICKY;
    }

    private void stopClipboardMonitoring() {
        if (onPrimaryClipChangedListener != null) {
            clipboardManager.removePrimaryClipChangedListener(onPrimaryClipChangedListener);
        }
    }

}


text:
<!DOCTYPE HTML>

<title>Uses of Class org.freedesktop.dbus.RemoteObject (dbus-java-parent 4.2.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-05">
<meta name="description" content="use: module: org.freedesktop.dbus, package: org.freedesktop.dbus, class: RemoteObject">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Module

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Uses of Class
org.freedesktop.dbus.RemoteObject

Packages that use RemoteObject

Package

Description

org.freedesktop.dbus

org.freedesktop.dbus.connections

Uses of RemoteObject in org.freedesktop.dbus

Methods in org.freedesktop.dbus with parameters of type RemoteObject

Modifier and Type

Method

Description

static Object

RemoteInvocationHandler.executeRemoteMethod<wbr>(RemoteObject _ro,
 Method _m,
 AbstractConnection _conn,
 int _syncmethod,
 CallbackHandler<?> _callback,
 Object... _args)

Constructors in org.freedesktop.dbus with parameters of type RemoteObject

Modifier

Constructor

Description

RemoteInvocationHandler<wbr>(AbstractConnection _conn,
 RemoteObject _remote)

Uses of RemoteObject in org.freedesktop.dbus.connections

Methods in org.freedesktop.dbus.connections that return types with arguments of type RemoteObject

Modifier and Type

Method

Description

protected Map<DBusInterface,<wbr>RemoteObject>

AbstractConnection.getImportedObjects()

Copyright © 2022. All rights reserved.


text:
import c = require('context');
import s = require('shader');
import b = require('./utils/buffer');

/** A fragment and vertex shader combo */
export interface Shaders {
  vertex:s.Shader;
  fragment:s.Shader;
}

/** Types of buffers that can be bound */
export enum BufferType {
  UNIFORM_SAMPLER,
  UNIFORM_MAT4,
  UNIFORM_FLOAT,
  VERTEX_FLOAT2,
  VERTEX_FLOAT3,
  VERTEX_FLOAT4
}

/** The currently held config for a buffer binding */
interface BufferBinding {
  attribute:string;
  type:BufferType;
  location:any;
  buffer:any;
  dirty:boolean;
  mode:any;
}

/** A shader program */
export class Program {

  /** The actual shader program */
  public program:any = null;

  /** The shaders used */
  public shaders:Shaders;

  /** Attribute binding */
  private _bindings:{[key:string]:BufferBinding} = {};

  /** Keep a copy of the context to work with */
  private _glc:c.Context;

  /** Run this action during bind for custom attributes */
  public extra:{(p:Program):void} = null;

  /**
   * Create a program for a set of shaders
   * @param gl The gl context
   * @param shaders The set of shaders
   */
  constructor(glc:c.Context, shaders:Shaders) {
    this._glc = glc;
    this.shaders = shaders;
    this.reload();
  }

  /**
   * Reload the program from saved values.
   * @param gl The gl context
   */
  public reload():void {

    var gl = this._glc.gl;

    // Remove any old program
    if (this.program != null) {
      gl.deleteProgram(this.program);
      this.program = null;
    }

    // Force shaders to reload for this program
    this.shaders.vertex.reload(this._glc);
    this.shaders.fragment.reload(this._glc);

    // New program
    var program = gl.createProgram();
    gl.attachShader(program, this.shaders.vertex.shader);
    gl.attachShader(program, this.shaders.fragment.shader);
    gl.linkProgram(program);

    // Check the link status
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
      var lastError = gl.getProgramInfoLog(program);
      gl.deleteProgram(program);
      throw new Error('Error linking program:' + lastError);
    }
    this.program = program;
    this.shaders = this.shaders;
  }

  /** Bind a buffer to an attribute for a shader */
  public bind(attribute:string, type:BufferType):void {
    if (this._bindings[attribute]) {
      throw new Error('Invalid attribute name "' + attribute + '" already in use');
    }
    this._bindings[attribute] = {
      attribute: attribute,
      type: type,
      buffer: null,
      location: null,
      dirty: true,
      mode: null
    }
  }

  /** Assign a buffer for this renderer */
  public buffer(attribute:string, buffer:b.Buffer<Float32Array>, mode:any = null):void {
    if (!this._bindings[attribute]) {
      throw new Error('Unable to buffer unknown attribute "' + attribute + '"');
    }
    this._bindings[attribute].buffer = buffer;
    this._bindings[attribute].dirty = true;
    this._bindings[attribute].mode = mode;
    this.update(attribute);
  }

  /**
   * Push the inner data into the gl buffer.
   * Notice this is only required for per-vertex attributes; for uniform values there
   * is no need to invoke this; and if the mode is not specified it does nothing.
   */
  public update(attribute:string):void {
    if (!this._bindings[attribute]) {
      throw new Error('Unable to buffer data for unknown attribute "' + attribute + '"');
    }
    var gl = this._glc.gl;
    var attrib = this._bindings[attribute];
    var buffer = attrib.buffer;
    var mode = attrib.mode;
    if (mode != null) {
      if (buffer.mem.buffer == null) {
        buffer.mem.buffer = gl.createBuffer();
      }
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer.mem.buffer);
      gl.bufferData(gl.ARRAY_BUFFER, buffer.mem.data, mode);
      if (gl.getError() != gl.NO_ERROR) {
        throw new Error("Error buffering data on array");
      }
    }
  }

  /** Release the buffer for a given attribute */
  public release(attribute:string):void {
    if (this._bindings[attribute]) {
      var buffer = this._bindings[attribute].buffer;
      if (buffer.mem.buffer) {
        // gl.DestoryBuffer(buffer['buffer'])
      }
      delete this._bindings[attribute];
    }
  }

  /** Rebind buffers to the program */
  public load():void {

    var gl = this._glc.gl;

    // Load the program
    gl.useProgram(this.program);

    // Bind each additional buffer if required
    if (this.extra != null) {
      this.extra(this);
    }

    // Now bind each buffer to each program location
    for (var key in this._bindings) {

      // Get the attribute binding
      var attrib = this._bindings[key];
      if (attrib.buffer == null) {
        throw new Error('No buffer has been bound to attribute "' + key + '"');
      }

      // Get the location
      switch (attrib.type) {
        case BufferType.UNIFORM_SAMPLER:
        case BufferType.UNIFORM_FLOAT:
        case BufferType.UNIFORM_MAT4:
          attrib.location = gl.getUniformLocation(this.program, attrib.attribute);
          if (attrib.location == null) {
            throw new Error('Invalid attribute: "' + attrib.attribute + '": ' + gl.getError());
          }
          break;

        case BufferType.VERTEX_FLOAT2:
        case BufferType.VERTEX_FLOAT3:
        case BufferType.VERTEX_FLOAT4:
          attrib.location = gl.getAttribLocation(this.program, attrib.attribute);
          if (attrib.location == null) {
            throw new Error('Invalid attribute: "' + attrib.attribute + '": ' + gl.getError());
          }
          break;
      }

      // Bind buffer; must be done every frame.
      switch (attrib.type) {
        case BufferType.UNIFORM_SAMPLER:
          gl.activeTexture(gl.TEXTURE0);
          gl.bindTexture(gl.TEXTURE_2D, attrib.buffer);
          gl.uniform1i(attrib.location, 0);
          break;

        case BufferType.UNIFORM_MAT4:
          gl.uniformMatrix4fv(attrib.location, false, attrib.buffer.data);
          break;

        case BufferType.UNIFORM_FLOAT:
          gl.uniform1fv(attrib.location, attrib.buffer.data);
          break;

        case BufferType.VERTEX_FLOAT2:
          gl.bindBuffer(gl.ARRAY_BUFFER, attrib.buffer.mem.buffer);
          gl.enableVertexAttribArray(attrib.location);
          gl.vertexAttribPointer(attrib.location, 2, gl.FLOAT, false, 0, 0);
          break;

        case BufferType.VERTEX_FLOAT3:
          gl.bindBuffer(gl.ARRAY_BUFFER, attrib.buffer.mem.buffer);
          gl.enableVertexAttribArray(attrib.location);
          gl.vertexAttribPointer(attrib.location, 3, gl.FLOAT, false, 0, 0);
          break;

        case BufferType.VERTEX_FLOAT4:
          gl.bindBuffer(gl.ARRAY_BUFFER, attrib.buffer.mem.buffer);
          gl.enableVertexAttribArray(attrib.location);
          gl.vertexAttribPointer(attrib.location, 4, gl.FLOAT, false, 0, 0);
          break;

        default:
          throw Error('Invalid buffer type: ' + attrib.type);
      }
    }
  }
}


text:
import {
  Addon,
  StoryId,
  StoryName,
  StoryKind,
  ViewMode,
  StoryIdentifier,
  StoryFn,
  Parameters,
  Args,
  ArgTypes,
  StoryApi,
  DecoratorFunction,
  LoaderFunction,
  DecorateStoryFunction,
  StoryContext,
} from '@storybook/addons';
import StoryStore from './story_store';
import { HooksContext } from './hooks';

export interface ErrorLike {
  message: string;
  stack: string;
}

// Metadata about a story that can be set at various levels: global, for a kind, or for a single story.
export interface StoryMetadata {
  parameters?: Parameters;
  decorators?: DecoratorFunction[];
  loaders?: LoaderFunction[];
}
export type ArgTypesEnhancer = (context: StoryContext) => ArgTypes;

type StorySpecifier = StoryId | { name: StoryName; kind: StoryKind } | '*';

export interface StoreSelectionSpecifier {
  storySpecifier: StorySpecifier;
  viewMode: ViewMode;
  args?: Args;
}

export interface StoreSelection {
  storyId: StoryId;
  viewMode: ViewMode;
}

export type AddStoryArgs = StoryIdentifier & {
  storyFn: StoryFn<any>;
  parameters?: Parameters;
  decorators?: DecoratorFunction[];
  loaders?: LoaderFunction[];
};

export type StoreItem = StoryIdentifier & {
  parameters: Parameters;
  getDecorated: () => StoryFn<any>;
  getOriginal: () => StoryFn<any>;
  applyLoaders: () => Promise<StoryContext>;
  storyFn: StoryFn<any>;
  unboundStoryFn: StoryFn<any>;
  hooks: HooksContext;
  args: Args;
  initialArgs: Args;
  argTypes: ArgTypes;
};

export type PublishedStoreItem = StoreItem & {
  globals: Args;
};

export interface StoreData {
  [key: string]: StoreItem;
}

export interface ClientApiParams {
  storyStore: StoryStore;
  decorateStory?: DecorateStoryFunction;
  noStoryModuleAddMethodHotDispose?: boolean;
}

export type ClientApiReturnFn<StoryFnReturnType> = (...args: any[]) => StoryApi<StoryFnReturnType>;

export type { StoryApi, DecoratorFunction };

export interface ClientApiAddon<StoryFnReturnType = unknown> extends Addon {
  apply: (a: StoryApi<StoryFnReturnType>, b: any[]) => any;
}

export interface ClientApiAddons<StoryFnReturnType> {
  [key: string]: ClientApiAddon<StoryFnReturnType>;
}

export interface GetStorybookStory {
  name: string;
  render: StoryFn;
}

export interface GetStorybookKind {
  kind: string;
  fileName: string;
  stories: GetStorybookStory[];
}

// This really belongs in lib/core, but that depends on lib/ui which (dev) depends on app/react
// which needs this type. So we put it here to avoid the circular dependency problem.
export type RenderContextWithoutStoryContext = StoreItem & {
  forceRender: boolean;

  showMain: () => void;
  showError: (error: { title: string; description: string }) => void;
  showException: (err: Error) => void;
};

export type RenderContext = RenderContextWithoutStoryContext & {
  storyContext: StoryContext;
};

interface SBBaseType {
  required?: boolean;
  raw?: string;
}

export type SBScalarType = SBBaseType & {
  name: 'boolean' | 'string' | 'number' | 'function';
};

export type SBArrayType = SBBaseType & {
  name: 'array';
  value: SBType;
};
export type SBObjectType = SBBaseType & {
  name: 'object';
  value: Record<string, SBType>;
};
export type SBEnumType = SBBaseType & {
  name: 'enum';
  value: (string | number)[];
};
export type SBIntersectionType = SBBaseType & {
  name: 'intersection';
  value: SBType[];
};
export type SBUnionType = SBBaseType & {
  name: 'union';
  value: SBType[];
};
export type SBOtherType = SBBaseType & {
  name: 'other';
  value: string;
};

export type SBType =
  | SBScalarType
  | SBEnumType
  | SBArrayType
  | SBObjectType
  | SBIntersectionType
  | SBUnionType
  | SBOtherType;


text:
<component name="libraryTable">
  <library name="Maven: org.apache.directory.server:apacheds-interceptors-exception:2.0.0-M21">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/directory/server/apacheds-interceptors-exception/2.0.0-M21/apacheds-interceptors-exception-2.0.0-M21.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/directory/server/apacheds-interceptors-exception/2.0.0-M21/apacheds-interceptors-exception-2.0.0-M21-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/directory/server/apacheds-interceptors-exception/2.0.0-M21/apacheds-interceptors-exception-2.0.0-M21-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
const discord = require ('discord.js');
var Client    = require('mysql');
var settings  = require('../../settings.js');
var dbclient = '';
var mysqlPool = '';

exports.init = (client) => {
        dbclient = Client.createConnection({
                    host: settings.dbhost,
                    user: settings.dbuser,
                    password: settings.dbpassword,
                    database: settings.dbdatabase,
        });//client = Client.createConnection

        mysqlPool  = Client.createPool({
            host: settings.dbhost,
            user: settings.dbuser,
            password: settings.dbpassword,
            database: settings.dbdatabase,
            port:3306
        }); //my sql pool
};//init

exports.run = (client, msg) => {
	var   validform   = 0;
	var   playeruid   = msg.author.id;
	var   playername  = msg.author.username;
        var mentionedid   = playeruid;
        var mentionedname = playername;
        if (msg.mentions.users.first()){
            mentionedid   = msg.mentions.users.first().id;
            mentionedname = msg.mentions.users.first().username;
        };//if
        const RiderEmbed = new discord.RichEmbed()
	      RiderEmbed.setAuthor('Magic The Wizard', settings.botpic)
	      RiderEmbed.setColor('#C0C0C0')
	      RiderEmbed.setTimestamp()
	      RiderEmbed.setURL('http://www.maskedriders.info/Mee6RP/index.php')
	      RiderEmbed.setThumbnail('http://www.maskedriders.info/Mee6RP/statusPic/Icon-wizard.png')

        mysqlPool.getConnection(function(err, connection) {
        if(err) throw err;
        connection.query("SELECT * FROM " + settings.dbtable + " WHERE ID = '" + playeruid + "'", function(err,rows){
              validform = rows[0].CLASS_ID;
              RiderEmbed.setFooter('Data Card ~' + settings.PlayerClassName(validform), settings.serverpic)

                      if ((validform >= 5000) && (validform < 6000)){
                            if ((validform == 5100) || (validform == 5120) || (validform == 5110)){//wiseman, sorcerer, mage
                                    RiderEmbed.addField('Jewel', 'Now!', true)
                                    RiderEmbed.addField('Summon', 'Creates Earings (and other jewelery).', true)
                            } else if (validform == 5140){//beast in magic land
                                    RiderEmbed.addField('Ear', 'Go!', true)
                                    RiderEmbed.addField('Summon', 'Creates Earings (and other jewelery).', true)
                            } else if (validform == 5000){//wizard
                                    RiderEmbed.addField('Ear', 'Please.', true)
                                    RiderEmbed.addField('Summon', 'Creates Earings (and other jewelery).', true)
                            } else if (validform == 5130){//beast
                                    RiderEmbed.setImage('http://www.maskedriders.info/Mee6RP/statusPic/wrongrider.png')
                            }//if else
                      } else {
                            RiderEmbed.setThumbnail(settings.serverpic)
                            RiderEmbed.setImage('http://www.maskedriders.info/Mee6RP/statusPic/wrongrider.png')
                      };//if ((validform

                      msg.channel.sendEmbed(
                      RiderEmbed, '', { disableEveryone: true }
                      );//message.channel.sendEmbed
                connection.release(); // if error occured closed the connection
        });//querry "SELECT * FROM RP_Users WHERE ID = '" + uid + "'"
        });//get connection
};//exports run

exports.conf = {
  enabled: true,
  runIn: ["text"],
  aliases: [],
  permLevel: 0,
  botPerms: [],
  requiredFuncs: []
};

exports.help = {
  name: "ring-ear",
  description: "",
  usage: "",
  usageDelim: ""
//  extendedHelp: "";
};


text:
var React = require('react');

module.exports = React.createClass({

	displayName: 'InvalidFieldType',

	render () {
		return
Invalid field type {this.props.type} at path {this.props.path}
;
	}

});


text:
<?php
include_once "../root/defaults.php";
include_once "../root/ConnectionManager.php";

    print '

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 Login

                        <form class="form-horizontal" id="modalLoginForm" method="post" action="../authenticate/authenticator.php">
                            <input type="hidden" name="formSource" value="legit">

                                    <input type="text" class="form-control" id="username" name="username" placeholder="Username" value="'._ADMIN.'" required>

                                    <input type="password" class="form-control" id="password" name="password" placeholder="Password" value="" required>

                                    Forgot Password ?

                                    <button type="submit" class="btn btn-lg btn-success btn-block"> Sign in</button>

                        </form>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Password Reset

                    <form class="form-horizontal" id="modalResetForm" method="post" action="../authenticate/authenticator.php">
                        <input type="hidden" name="resetReq" value="legit">

                            Username

                                <input type="text" class="form-control" id="username" name="username" placeholder="Username" value="'._ADMIN.'" readonly required>

                            Email

                                <input type="email" class="form-control" id="email" name="email" placeholder="Email address" value="'._EMAIL.'" required>

                                <button type="submit" class="btn btn-lg btn-warning btn-block" id="resetPassBtn">Reset Password</button>

                    </form>

    ';

    // todo: registration form & handle - abandoned after datalake 2nd status call
    // --susheel 04/11/2017
?>


text:
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMFCAutoClient1DlgAutoProxy

IMPLEMENT_DYNCREATE(CMFCAutoClient1DlgAutoProxy, CCmdTarget)

CMFCAutoClient1DlgAutoProxy::CMFCAutoClient1DlgAutoProxy()
{
	EnableAutomation();

	// Um die Ausführung der Anwendung fortzusetzen, solange ein OLE-Automatisierungsobjekt
	//	aktiv ist, ruft der Konstruktor AfxOleLockApp auf.
	AfxOleLockApp();

	// Greifen Sie über den Hauptfensterzeiger der Anwendung auf das
	//  Dialogfeld zu. Setzen Sie den internen Zeiger des Proxy
	//  auf das Dialogfeld und den Gegenzeiger (Back Pointer) des Dialogfelds
	//  auf diesen Proxy.
	ASSERT (AfxGetApp()->m_pMainWnd != NULL);
	ASSERT_VALID (AfxGetApp()->m_pMainWnd);
	ASSERT_KINDOF(CMFCAutoClient1Dlg, AfxGetApp()->m_pMainWnd);
	m_pDialog = (CMFCAutoClient1Dlg*) AfxGetApp()->m_pMainWnd;
	m_pDialog->m_pAutoProxy = this;
}

CMFCAutoClient1DlgAutoProxy::~CMFCAutoClient1DlgAutoProxy()
{
	// Um die Anwendung zu beenden, sobald alle mit OLE-Automatisierung erstellten
	// Objekte freigegeben sind, ruft der Destruktor AfxOleUnlockApp auf.
	//  Dies zerstört unter anderem das Hauptdialogfeld.
	AfxOleUnlockApp();
}

void CMFCAutoClient1DlgAutoProxy::OnFinalRelease()
{
	// Wird der letzte Verweis auf ein Automatisierungsobjekt freigegeben,
	// wird OnFinalRelease aufgerufen. Die Basisklasse löscht das Objekt
	// automatisch. Fügen Sie zusätzlichen Bereinigungscode für Ihr Objekt
	// hinzu, bevor Sie die Basisklasse aufrufen.

	CCmdTarget::OnFinalRelease();
}

BEGIN_MESSAGE_MAP(CMFCAutoClient1DlgAutoProxy, CCmdTarget)
	//{{AFX_MSG_MAP(CMFCAutoClient1DlgAutoProxy)
		// HINWEIS - Hier werden Mapping-Makros vom Klassen-Assistenten eingefügt und entfernt.
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

BEGIN_DISPATCH_MAP(CMFCAutoClient1DlgAutoProxy, CCmdTarget)
	//{{AFX_DISPATCH_MAP(CMFCAutoClient1DlgAutoProxy)
		// HINWEIS - Hier werden Mapping-Makros vom Klassen-Assistenten eingefügt und entfernt.
	//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()

// Hinweis: Wir stellen Unterstützung für IID_IMFCAutoClient1 zur Verfügung, um typsicheres Binden
//  von VBA zu unterstützen. Diese IID muss mit der GUID übereinstimmen, die bei der
//  Disp-Schnittstelle in der .ODL-Datei angegeben ist.

// {48969665-0A05-11D2-B530-006097A8F69A}
static const IID IID_IMFCAutoClient1 =
{ 0x48969665, 0xa05, 0x11d2, { 0xb5, 0x30, 0x0, 0x60, 0x97, 0xa8, 0xf6, 0x9a } };

BEGIN_INTERFACE_MAP(CMFCAutoClient1DlgAutoProxy, CCmdTarget)
	INTERFACE_PART(CMFCAutoClient1DlgAutoProxy, IID_IMFCAutoClient1, Dispatch)
END_INTERFACE_MAP()

// Das Makro IMPLEMENT_OLECREATE2 ist in der Datei StdAfx.h dieses Projekts definiert
// {48969663-0A05-11D2-B530-006097A8F69A}
IMPLEMENT_OLECREATE2(CMFCAutoClient1DlgAutoProxy, "MFCAutoClient1.Application", 0x48969663, 0xa05, 0x11d2, 0xb5, 0x30, 0x0, 0x60, 0x97, 0xa8, 0xf6, 0x9a)

/////////////////////////////////////////////////////////////////////////////
// CMFCAutoClient1DlgAutoProxy Nachrichten-Handler