text:
import React, { useState } from "react";

import CheckboxList from "@site/src/components/CheckboxList";
import Heading from "@theme/Heading";
import Link from "@docusaurus/Link";

import _ from "lodash";
import { commitTypeName, sortCommitTypes } from "@site/src/exports/commits";
import pluralize from "pluralize";

const AnchoredH3 = Heading("h3");
const AnchoredH4 = Heading("h4");

function Commit({ commit, setSearchTerm }) {
    return (

                {commit.breaking_change && (

                         breaking

                )}
                {commit.pr_number && (

                        <a
                            href={`https://github.com/apache/incubator-pinot/pull/${commit.pr_number}`}
                            target="_blank"
                        >
                            {" "}
                            {commit.pr_number}

                )}
                {!commit.pr_number && (

                        <a
                            href={`https://github.com/apache/incubator-pinot/commit/${commit.sha}`}
                            target="_blank"
                        >
                            {" "}
                            {commit.sha.slice(0, 5)}

                )}

            <AnchoredH4 id={commit.sha}>
                 setSearchTerm(commit.scope.name)}
                >
                    {commit.scope.name}

                {commit.description}
            </AnchoredH4>

    );
}

function Commits({ commits, groupBy, setSearchTerm }) {
    if (groupBy) {
        const groupedCommits = _(commits)
            .sortBy((commit) => commit.scope.name)
            .groupBy(groupBy)
            .value();
        const groupKeys = sortCommitTypes(Object.keys(groupedCommits));

        return (

                {groupKeys.map((groupKey, catIdx) => (

                        <AnchoredH3 id={groupKey}>
                            {pluralize(
                                commitTypeName(groupKey),
                                groupedCommits[groupKey].length,
                                true
                            )}
                        </AnchoredH3>

                            {groupedCommits[groupKey].map(
                                (commit, commitIdx) => (
                                    <Commit
                                        key={commitIdx}
                                        commit={commit}
                                        setSearchTerm={setSearchTerm}
                                    />
                                )
                            )}

                ))}

        );
    } else {
        return
{commits.length}
;
    }
}

function Changelog(props) {
    const { commits } = props;

    const [groupBy, setGroupBy] = useState("type");
    const [onlyTypes, setOnlyTypes] = useState(
        new Set(["enhancement", "feat", "fix", "perf"])
    );
    const [searchTerm, setSearchTerm] = useState(null);

    let filteredCommits = commits.slice(0);

    if (searchTerm) {
        filteredCommits = filteredCommits.filter((commit) =>
            commit.message.toLowerCase().includes(searchTerm.toLowerCase())
        );
    }

    if (onlyTypes.size > 0) {
        filteredCommits = filteredCommits.filter((commit) =>
            onlyTypes.has(commit.type)
        );

        if (onlyTypes.has("breaking change")) {
            filteredCommits = filteredCommits.filter(
                (commit) => commit.breaking_change
            );
        }
    }

    //
    // Filter Options
    //

    const types = new Set(
        _(commits)
            .map((commit) => commit.group)
            .uniq()
            .compact()
            .sort()
            .value()
    );

    //
    // Render
    //

    return (

            {commits.length > 1 ? (

                            {filteredCommits.length} items

                        <input
                            type="text"
                            onChange={(event) =>
                                setSearchTerm(event.currentTarget.value)
                            }
                            placeholder="🔍 Search..."
                            value={searchTerm || ""}
                        />

                            <CheckboxList
                                values={types}
                                currentState={onlyTypes}
                                setState={setOnlyTypes}
                            />

            ) : null}
            {filteredCommits.length > 0 ? (
                <Commits
                    commits={filteredCommits}
                    groupBy={groupBy}
                    setSearchTerm={setSearchTerm}
                    types={types}
                />
            ) : (

☹

No commits found

            )}

    );
}

export default Changelog;

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Thelotrema leptocarpoides

### Remarks
null


text:
[![Build Status](https://travis-ci.org/panda3d/panda3d.svg?branch=master)](https://travis-ci.org/panda3d/panda3d)

<img src="https://avatars2.githubusercontent.com/u/590956?v=3&s=200" align="right" />

Panda3D
=======

Panda3D is a game engine, a framework for 3D rendering and game development for
Python and C++ programs.  Panda3D is open-source and free for any purpose,
including commercial ventures, thanks to its
[liberal license](https://www.panda3d.org/license.php).  To learn more about
Panda3D's capabilities, visit the [gallery](https://www.panda3d.org/gallery.php)
and the [feature list](https://www.panda3d.org/features.php).  To learn how to
use Panda3D, check the [documentation](https://www.panda3d.org/documentation.php)
resources. If you get stuck, ask for help from our active
[community](https://www.panda3d.org/community.php).

Panda3D is licensed under the Modified BSD License.  See the LICENSE file for
more details.

Building Panda3D
================

Windows
-------

We currently build using the Microsoft Visual C++ 2010 compiler.  You do not
need Microsoft Visual Studio to build Panda3D, though - the relevant compilers
are included as part of the Windows 7.1 SDK.

You will also need to have the third-party dependency libraries available for
the build scripts to use.  These are available from one of these two URLs,
depending on whether you are on a 32-bit or 64-bit system:
https://www.panda3d.org/download/panda3d-1.9.1/panda3d-1.9.1-tools-win32.zip
https://www.panda3d.org/download/panda3d-1.9.1/panda3d-1.9.1-tools-win64.zip

After acquiring these dependencies, you may simply build Panda3D from the
command prompt using the following command:

```bash
makepanda\makepanda.bat --everything --installer --no-eigen
```

When the build succeeds, it will produce an .exe file that you can use to
install Panda3D on your system.

Note: you may choose to remove --no-eigen and build with Eigen support in
order to improve runtime performance.  However, this will cause the build to
take hours to complete, as Eigen is a heavily template-based library, and the
the MSVC compiler does not perform well under these circumstances.

Linux
-----

Building Panda3D on Linux is easy.  All you need is to invoke the makepanda
script using the version of Python that you want Panda3D to be built against.

Run makepanda.py with the --help option to see which options are available.
Usually, you will want to specify the --everything option (which builds with
support for all features for which it detects the prerequisite dependencies)
and the --installer option (which produces an installable .deb or .rpm file
for you to install, depending on your distribution).

The following command illustrates how to build Panda3D with some common
options:
```bash
python2.7 makepanda/makepanda.py --everything --installer --no-egl --no-gles --no-gles2
```

You will probably see some warnings saying that it's unable to find several
dependency packages.  You should determine which ones you want to include in
your build and install the respective development packages.  You may visit
[this manual page](https://www.panda3d.org/manual/index.php/Dependencies)
for an overview of the various dependencies.

If you are on Ubuntu, this command should cover the most frequently
used third-party packages:

```bash
sudo apt-get install build-essential pkg-config python-dev libpng-dev libjpeg-dev libtiff-dev zlib1g-dev libssl-dev libx11-dev libgl1-mesa-dev libxrandr-dev libxxf86dga-dev libxcursor-dev bison flex libfreetype6-dev libvorbis-dev libeigen3-dev libopenal-dev libode-dev libbullet-dev nvidia-cg-toolkit libgtk2.0-dev
```

Once Panda3D has built, you can either install the .deb or .rpm package that
it produced, depending on which Linux distribution you are using.  For example,
to install the package on Debian or Ubuntu, use this:

```bash
sudo dpkg -i panda3d*.deb
```

If you are not using a Linux distribution that supports .deb or .rpm packages, you
may have to use the installpanda.py script instead, which will directly copy the
files into the appropriate locations on your computer.  You may have to run the
`ldconfig` tool in order to update your library cache after installing Panda3D.

Mac OS X
--------

On Mac OS X, you will need to download a set of precompiled thirdparty packages in order to
compile Panda3D, which can be acquired from [here](https://www.panda3d.org/download/panda3d-1.9.1/panda3d-1.9.1-tools-mac.tar.gz).

After placing the thirdparty directory inside the panda3d source directory,
you may build Panda3D using a command like the following:

```bash
python makepanda/makepanda.py --everything --installer
```

In order to make a universal build, pass the --universal flag.  You may also
target a specific minimum Mac OS X version using the --osxtarget flag followed
by the release number, eg. 10.6 or 10.7.

If the build was successful, makepanda will have generated a .dmg file in
the source directory containing the installer.  Simply open it and run the
package file in order to install the SDK onto your system.

Reporting Issues
================

If you encounter any bugs when using Panda3D, please report them in the bug
tracker.  This is hosted at:

  https://bugs.launchpad.net/panda3d

Make sure to first use the search function to see if the bug has already been
reported.  When filling out a bug report, make sure that you include as much
information as possible to help the developers track down the issue, such as
your version of Panda3D, operating system, architecture, and any code and
models that are necessary for the developers to reproduce the issue.

If you're not sure whether you've encountered a bug, feel free to ask about
it in the forums or the IRC channel first.


text:
/*
* This software was developed as part of the
* EC FP7 funded project Adept (Project ID: 610490)
* www.adept-project.eu
*/

/* 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. */

/*
 * Utility functions for sparse matrices.
 *
 * Currently focusses on reading in a sparse matrix file in
 * Matrix Market Format (http://math.nist.gov/MatrixMarket)
 * converting this to CSR.
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*
 *
 * reads matrix market file header and get number of rows,
 * number of columns, and number of non-zero elements.
 *
 */

void get_matrix_size(char *fn, int *rows, int *cols, int *nonzeros){
  FILE *f;
  char header[64];
  char *rv = NULL;

  if ((f = fopen(fn, "r")) == NULL) {
    printf ("can't open file <%s> \n", fn);
    exit(1);
  }

  rv = fgets(header, sizeof(header), f);
  if (*rv==EOF){
    printf("Error reading file.\n");
    exit(1);
  }
  rv = fgets(header, sizeof(header), f);
  if (*rv==EOF){
    printf("Error reading file.\n");
    exit(1);
  }else{
    sscanf(header, "%d %d %d", rows, cols, nonzeros);
  }

  printf("Rows: %d, Columns: %d, Non-zeros: %d\n", *rows, *cols, *nonzeros);
  fclose(f);

}

/*
 *
 * convert a matrix in Matrix Market Format (COO) to CSR
 *
 */
void  mm_to_csr (char *fn, int m, int n, int nz, int *row_idx, int *col_idx, double *values)
{

  FILE *fin, *fout;
  int i,j;
  int base;
  char body[64];
  int  row_idx_current, inc;
  char *rv = NULL;

  int *new_row_idx, *new_col_idx;
  double *new_values;

  if ((fin = fopen(fn, "r")) == NULL) {
    printf ("can't open input file <%s> \n", fn);
    exit(1);
  }

  printf("here\n");

  if((fout = fopen("matrix_in.csr","w")) == NULL) {
    printf ("can't open output file <%s> \n", fn);
    exit(1);
  }

  /* discard first two lines */
  rv = fgets(body, sizeof(body), fin);
  if (*rv==EOF){
    printf("Error reading file.\n");
    exit(1);
  }
  rv = fgets(body, sizeof(body), fin);
  if (*rv==EOF){
    printf("Error reading file.\n");
    exit(1);
  }

  base = 1;
  i = 0;

  /* walk through the file line by line */
  while (fgets(body, sizeof(body), fin)){
    sscanf(body, "%d %d %lf", &row_idx[i], &col_idx[i], &values[i]);
    row_idx[i] -= base;  /* adjust from 1-based to 0-based */
    col_idx[i] -= base;
    i++;
  }

  fclose(fin);

  /* allocate space for new arrays which will hold the    */
  /* newly ordered values, and the column and row indices */
  new_row_idx = malloc(nz * sizeof(int));
  new_col_idx = malloc(nz * sizeof(int));
  new_values = malloc(nz * sizeof(double));

  /* set first values for all three arrays   */
  /* as there is nothing to be done for them */
  row_idx_current=row_idx[0];
  new_row_idx[0]=row_idx[0];
  new_col_idx[0]=col_idx[0];
  new_values[0]=values[0];

  inc=1;

  /* this is where the arrays are being reordered */
  for(j=1; j<nz; j++){
    for(i=1; i<nz; i++){
      if(row_idx[i] == row_idx_current){
        new_values[inc]=values[i];
        new_col_idx[inc]=col_idx[i];
        inc++;
      }
    }
    new_row_idx[j]=inc;
    row_idx_current++;
  }

  fprintf(fout, "%d %d %d\n", nz, nz, m+1);

  /* fprintf(fout, "Values:\n"); */
  /* copy the new colum indices and values into the old arrays */
  for (i=0; i<nz; i++)  {
    values[i]=new_values[i];
    fprintf(fout, "%f\n", new_values[i]);
  }

  /* fprintf(fout, "\nColumn indices:\n"); */
  /* copy the new colum indices and values into the old arrays */
  for (i=0; i<nz; i++)  {
    col_idx[i]=new_col_idx[i];
    fprintf(fout, "%d\n", new_col_idx[i]);
  }

  /* fprintf(fout, "\nRow pointers:\n"); */
  /* copy the new row indices into the old array */
  for (i=0; i<=m; i++)  {
    row_idx[i]=new_row_idx[i];
    fprintf(fout, "%d\n", new_row_idx[i]);
  }

  /* free memory for the temporary new arrays */
  free(new_row_idx);
  free(new_col_idx);
  free(new_values);

  fclose(fout);

}


text:
.class public final Lcom/airbnb/lottie/model/animatable/AnimatablePointValue$Factory;
.super Ljava/lang/Object;
.source "AnimatablePointValue.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/airbnb/lottie/model/animatable/AnimatablePointValue;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Factory"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static newInstance(Lorg/json/JSONObject;Lcom/airbnb/lottie/LottieComposition;)Lcom/airbnb/lottie/model/animatable/AnimatablePointValue;
    .locals 5

    invoke-virtual {p1}, Lcom/airbnb/lottie/LottieComposition;->getDpScale()F

    move-result v1

    sget-object v2, Lcom/airbnb/lottie/model/PointFFactory;->INSTANCE:Lcom/airbnb/lottie/model/PointFFactory;

    invoke-static {p0, v1, p1, v2}, Lcom/airbnb/lottie/model/animatable/AnimatableValueParser;->newInstance(Lorg/json/JSONObject;FLcom/airbnb/lottie/LottieComposition;Lcom/airbnb/lottie/model/animatable/AnimatableValue$Factory;)Lcom/airbnb/lottie/model/animatable/AnimatableValueParser;

    move-result-object v1

    invoke-virtual {v1}, Lcom/airbnb/lottie/model/animatable/AnimatableValueParser;->parseJson()Lcom/airbnb/lottie/model/animatable/AnimatableValueParser$Result;

    move-result-object v0

    new-instance v2, Lcom/airbnb/lottie/model/animatable/AnimatablePointValue;

    iget-object v3, v0, Lcom/airbnb/lottie/model/animatable/AnimatableValueParser$Result;->keyframes:Ljava/util/List;

    iget-object v1, v0, Lcom/airbnb/lottie/model/animatable/AnimatableValueParser$Result;->initialValue:Ljava/lang/Object;

    check-cast v1, Landroid/graphics/PointF;

    const/4 v4, 0x0

    invoke-direct {v2, v3, v1, v4}, Lcom/airbnb/lottie/model/animatable/AnimatablePointValue;-><init>(Ljava/util/List;Landroid/graphics/PointF;Lcom/airbnb/lottie/model/animatable/AnimatablePointValue$1;)V

    return-object v2
.end method


text:
<!--
    Awesome, your propel set up is nearly done! You just have to describe how you want your database to look like.

    You can let propel set up your mysql database by running `vendor/bin/propel database:create && vendor/bin/propel database:insert-sql`.
    This will create your database including all the tables.
-->

<!--
    The root tag of the XML schema is the <database> tag.

    The `name` attribute defines the name of the connection that Propel uses for the tables in this schema. It is not
    necessarily the name of the actual database. In fact, Propel uses some configuration properties to link a connection
    name with real connection settings (like database name, user and password).

    The `defaultIdMethod` attribute indicates that the tables in this schema use the database's "native"
    auto-increment/sequence features to handle id columns that are set to auto-increment.

   [TIP]: You can define several schemas for a single project. Just make sure that each of the schema
          filenames end with schema.xml.
-->
<database name="pst-stack" defaultIdMethod="native"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="http://xsd.propelorm.org/1.6/database.xsd"
          namespace=""
        >

    <behavior name="timestampable"/>

    <!-- Within the <database> tag, Propel expects one <table> tag for each table -->

    <!--
        Each table element should have a `name` attribute. It will be used for naming the sql table.

        The `phpName` is the name that Propel will use for the generated PHP class. By default, Propel uses a
        CamelCase version of the table name as its phpName - that means that you could omit the `phpName` attribute
        on our `book` table.
    -->
    <table name="user" phpName="User">
        <!--
            Each column has a `name` (the one used by the database), and an optional `phpName` attribute. Once again,
            the Propel default behavior is to use a CamelCase version of the name as `phpName` when not specified.

            Each column also requires a `type`. The XML schema is database agnostic, so the column types and attributes
            are probably not exactly the same as the one you use in your own database. But Propel knows how to map the
            schema types with SQL types for many database vendors. Existing Propel column types are:
            `boolean`, `tinyint`, `smallint`, `integer`, `bigint`, `double`, `float`, `real`, `decimal`, `char`,
            `varchar`, `longvarchar`, `date`, `time`, `timestamp`, `blob`, `clob`, `object`, and `array`.

            Some column types use a size (like `varchar` and `int`), some have unlimited size (`longvarchar`, `clob`,
            `blob`).

            Check the (schema reference)[http://propelorm.org/reference/schema.html] for more details
            on each column type.

            As for the other column attributes, `required`, `primaryKey`, and `autoIncrement`, they mean exactly
            what their names imply.
        -->
        <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
        <column name="first_name" type="varchar" size="255" required="true" phpName="FirstName"/>
        <column name="last_name" type="varchar" size="255" required="true" phpName="LastName"/>
        <column name="email" type="varchar" size="255" required="true" phpName="Email"/>
        <column name="password" type="varchar" size="255" required="true" phpName="Password"/>
        <column name="uuid" type="varchar" size="255" required="true" phpName="UUID"/>

        <!--
            A foreign key represents a relationship. Just like a table or a column, a relationship has a `phpName`.
            By default, Propel uses the `phpName` of the foreign table as the `phpName` of the relation.

            The `refPhpName` defines the name of the relation as seen from the foreign table.
        -->
    </table>

    <!--
        When you're done with editing, open a terminal and run
            `$ cd /var/www/pst-stack/propel`
            `$ vendor/bin/propel build`
        to generate the model classes.

        You should now be able to perform basic crud operations with your models. To learn how to use these models
        please look into our documentation: http://propelorm.org/documentation/03-basic-crud.html
    -->
</database>


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

namespace MetroTrilithon.Serialization;

public interface ISerializationProvider
{
    bool IsLoaded { get; }

    void Save();

    void Load();

    /// <summary>
    /// Occurs when the provider side has reloaded due.
    /// </summary>
    event EventHandler Reloaded;

    void SetValue<T>(string key, T value);

    bool TryGetValue<T>(string key, out T value);

    bool RemoveValue(string key);
}


text:
/**
 * Utilities for programmatic Makefile genetation.
 *
 * @flow
 */

const outdent = require('outdent');

export type Env = {
  [name: string]: ?string;
};

export type MakeRule = {
  type: 'rule';
  target: string;
  command?: ?string | Array<void | null | string | Env>;
  phony?: boolean;
  dependencies?: Array<string>;
  env?: Env;
  exportEnv?: Array<string>;
  shell?: string
};

export type MakeDefine = {
  type: 'define';
  name: string;
  value: string | Array<void | null | string | Env>;
};

export type MakeFile = {
  type: 'file';
  target?: string;
  filename: string;
  dependencies?: Array<string>;
  value: string;
};

export type MakeRawItem = {|
  type: 'raw';
  value: string;
|};

export type MakeItem =
  | MakeRule
  | MakeFile
  | MakeDefine
  | MakeRawItem;

function renderMakefile(items: Array<MakeItem>) {
  return items
    .map(item => {
      if (item.type === 'rule') {
        return renderMakeRule(item);
      } else if (item.type === 'define') {
        return renderMakeDefine(item);
      } else if (item.type === 'raw') {
        return renderMakeRawItem(item);
      } else if (item.type === 'file') {
        return renderMakeFile(item);
      } else {
        throw new Error('Unknown make item:' + JSON.stringify(item));
      }
    })
    .join('\n\n');
}

function renderMakeDefine({name, value}) {
  return `define ${name}\n${escapeEnvVar(renderMakeRuleCommand(value))}\nendef`;
}

function renderMakeFile({filename, value, target, dependencies = []}) {
  let id = escapeName(filename);
  let output = outdent`
    define ${id}__CONTENTS
    ${escapeEnvVar(value)}
    endef

    export ${id}__CONTENTS

    .PHONY: ${filename}
    ${filename}: SHELL=/bin/bash
    ${filename}: ${dependencies.join(' ')}
    \tmkdir -p $(@D)
    \tprintenv "${id}__CONTENTS" > $(@)
  `;
  if (target) {
    output = output + `\n${target}: ${filename}`;
  }
  return output;
}

function renderMakeRawItem({value}) {
  return value;
}

function renderMakeRule(rule) {
  let {
    target,
    dependencies = [],
    command,
    phony,
    env,
    exportEnv,
    shell
  } = rule;
  let header = `${target}: ${dependencies.join(' ')}`;

  let prelude = '';
  if (exportEnv) {
    exportEnv.forEach(name => {
      prelude = prelude + `export ${name}\n`;
    });
  }

  if (phony) {
    prelude = prelude + `.PHONY: ${target}\n`;
  }

  if (shell != null) {
    prelude = prelude = `${target}: SHELL=${shell}\n`;
  }

  if (command != null) {
    let recipe = escapeEnvVar(renderMakeRuleCommand(command));
    if (env) {
      let envString = renderMakeRuleEnv(env);
      return `${prelude}${header}\n${envString}\\\n${recipe}`;
    } else {
      return `${prelude}${header}\n${recipe}`;
    }
  } else {
    return prelude + header;
  }
}

function renderMakeRuleEnv(env) {
  let lines = [];
  for (let k in env) {
    if (env[k] != null) {
      lines.push(`\texport ${k}="${env[k]}";`);
    }
  }
  return lines.join('\\\n');
}

function renderMakeRuleCommand(command) {
  if (Array.isArray(command)) {
    return command
      .filter(item => item != null)
      .map(item =>
        typeof item === 'string'
        ? renderMakeRuleCommand(item)
        : renderMakeRuleEnv(item))
      .join('\\\n');
  } else {
    return command.split('\n').map(line => `\t${line};`).join('\\\n');
  }
}

function escapeEnvVar(command) {
  return command.replace(/\$([^\(])/g, '$$$$$1');
}

function escapeName(name) {
  return name.replace(/[^a-zA-Z0-9]/g, '_').replace(/_+/g, '_');
}

module.exports = {
  renderMakefile
};


text:
module Spree
  module Admin
    ResourceController.class_eval do

      private
        def get_eventable_object(object_name = {})
          unless object_name[:eventable_type].nil?
            eventable = "#{object_name[:eventable_type]}".constantize.find_by_name(object_name[:eventable_name])
            object_name.delete(:eventable_name)
            unless eventable.nil?
              object_name.merge!(:eventable_id => eventable.id, :permalink => eventable.friendly_id)
            else
              object_name.merge!(:eventable_id => nil)
            end
          end
        end
    end
  end
end


text:
package play.db.jpa;

import org.junit.Rule;
import org.junit.rules.ExternalResource;
import play.db.Database;
import play.db.Databases;

import org.junit.Test;

import javax.persistence.EntityManager;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

public class JPAApiTest {

    @Rule
    public TestDatabase db = new TestDatabase();

    @Test
    public void shouldBeAbleToGetAnEntityManagerWithAGivenName() {
        EntityManager em = db.jpa.em("default");
        assertThat(em, notNullValue());
    }

    @Test
    public void shouldExecuteAFunctionBlockUsingAEntityManager() {
        db.jpa.withTransaction(entityManager -> {
            TestEntity entity = createTestEntity();
            entityManager.persist(entity);
            return entity;
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(1L);
            assertThat(entity.name, equalTo("alice"));
        });
    }

    @Test
    public void shouldReuseEntityManagerWhenExecutingTransaction() {
        JPAApi api = db.jpa;
        boolean reused = api.withTransaction(entityManager -> {
            EntityManager fromContext = api.em();
            return fromContext == entityManager;
        });

        assertThat(reused, is(true));
    }

    @Test
    public void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() {
        db.jpa.withTransaction("default", entityManager -> {
            TestEntity entity = createTestEntity();
            entityManager.persist(entity);
            return entity;
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(1L);
            assertThat(entity.name, equalTo("alice"));
        });
    }

    @Test
    public void shouldExecuteAFunctionBlockAsAReadOnlyTransaction() {
        db.jpa.withTransaction("default", true, entityManager -> {
            TestEntity entity = createTestEntity();
            entityManager.persist(entity);
            return entity;
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(1L);
            assertThat(entity, nullValue());
        });
    }

    private TestEntity createTestEntity() {
        return createTestEntity(1L);
    }

    private TestEntity createTestEntity(Long id) {
        TestEntity entity = new TestEntity();
        entity.id = id;
        entity.name = "alice";
        return entity;
    }

    @Test
    public void shouldExecuteASupplierBlockInsideATransaction() throws Exception {
        db.jpa.withTransaction(() -> {
            TestEntity entity = createTestEntity();
            entity.save();
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(1L);
            assertThat(entity.name, equalTo("alice"));
        });
    }

    @Test
    public void shouldNestTransactions() {
        db.jpa.withTransaction(() -> {
            TestEntity entity = new TestEntity();
            entity.id = 2L;
            entity.name = "test2";
            entity.save();

            db.jpa.withTransaction(() -> {
                TestEntity entity2 = TestEntity.find(2L);
                assertThat(entity2, nullValue());
            });

            // Verify that we can still access the EntityManager
            TestEntity entity3 = TestEntity.find(2L);
            assertThat(entity3, equalTo(entity));
        });
    }

    @Test
    public void shouldRollbackInnerTransactionOnly() {
        db.jpa.withTransaction(() -> {
            // Parent transaction creates entity 2
            TestEntity entity = createTestEntity(2L);
            entity.save();

            db.jpa.withTransaction(() -> {
                // Nested transaction creates entity 3, but rolls back
                TestEntity entity2 = createTestEntity(3L);
                entity2.save();

                JPA.em().getTransaction().setRollbackOnly();
            });

            // Verify that we can still access the EntityManager
            TestEntity entity3 = TestEntity.find(2L);
            assertThat(entity3, equalTo(entity));
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(3L);
            assertThat(entity, nullValue());

            TestEntity entity2 = TestEntity.find(2L);
            assertThat(entity2.name, equalTo("alice"));
        });
    }

    @Test
    public void shouldRollbackOuterTransactionOnly() {
        db.jpa.withTransaction(() -> {
            // Parent transaction creates entity 2, but rolls back
            TestEntity entity = createTestEntity(2L);
            entity.save();

            db.jpa.withTransaction(() -> {
                // Nested transaction creates entity 3
                TestEntity entity2 = createTestEntity(3L);
                entity2.save();
            });

            // Verify that we can still access the EntityManager
            TestEntity entity3 = TestEntity.find(2L);
            assertThat(entity3, equalTo(entity));

            db.jpa.em().getTransaction().setRollbackOnly();
        });

        db.jpa.withTransaction(() -> {
            TestEntity entity = TestEntity.find(3L);
            assertThat(entity.name, equalTo("alice"));

            TestEntity entity2 = TestEntity.find(2L);
            assertThat(entity2, nullValue());
        });
    }

    public static class TestDatabase extends ExternalResource {
        Database database;
        JPAApi jpa;

        public void execute(final String sql) {
            database.withConnection(connection -> {
                connection.createStatement().execute(sql);
            });
        }

        @Override
        public void before() {
            database = Databases.inMemoryWith("jndiName", "DefaultDS");
            execute("create table TestEntity (id bigint not null, name varchar(255));");
            jpa = JPA.createFor("defaultPersistenceUnit");
        }

        @Override
        public void after() {
            jpa.shutdown();
            database.shutdown();
        }
    }

}


text:
package com.intellij.openapi.wm.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.wm.impl.commands.FinalizableCommand;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import org.jetbrains.annotations.Nullable;

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

public final class CommandProcessor implements Runnable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.CommandProcessor");
  private final Object myLock = new Object();

  private final List<CommandGroup> myCommandGroupList = new ArrayList<CommandGroup>();
  private int myCommandCount;

  public final int getCommandCount() {
    synchronized (myLock) {
      return myCommandCount;
    }
  }

  /**
   * Executes passed batch of commands. Note, that the processor surround the
   * commands with BlockFocusEventsCmd - UnbockFocusEventsCmd. It's required to
   * prevent focus handling of events which is caused by the commands to be executed.
   */
  public final void execute(final List<FinalizableCommand> commandList, Condition expired) {
    synchronized (myLock) {
      final boolean isBusy = myCommandCount > 0;

      final CommandGroup commandGroup = new CommandGroup(commandList, expired);
      myCommandGroupList.add(commandGroup);
      myCommandCount += commandList.size();

      if (!isBusy) {
        run();
      }
    }
  }

  public final void run() {
    synchronized (myLock) {
      final CommandGroup commandGroup = getNextCommandGroup();
      if (commandGroup == null) {
        return;
      }

      final Condition conditionForGroup = commandGroup.getExpireCondition();

      if (!commandGroup.isEmpty()) {
        final FinalizableCommand command = commandGroup.takeNextCommand();
        myCommandCount--;

        final Condition expire = command.getExpireCondition() != null ? command.getExpireCondition() : conditionForGroup;

        if (LOG.isDebugEnabled()) {
          LOG.debug("CommandProcessor.run " + command);
        }
        // max. I'm not actually quite sure this should have NON_MODAL modality but it should
        // definitely have some since runnables in command list may (and do) request some PSI activity
        final boolean queueNext = myCommandCount > 0;
        ApplicationManager.getApplication().getInvokator().invokeLater(command, ModalityState.NON_MODAL, expire == null ? Condition.FALSE : expire).doWhenDone(new Runnable() {
          public void run() {
            if (queueNext) {
              CommandProcessor.this.run();
            }
          }
        });
      }
    }
  }

  @Nullable
  private CommandGroup getNextCommandGroup() {
    while (!myCommandGroupList.isEmpty()) {
      final CommandGroup candidate = myCommandGroupList.get(0);
      if (!candidate.isEmpty()) {
        return candidate;
      }
      myCommandGroupList.remove(candidate);
    }

    return null;
  }

  private static class CommandGroup {
    private final List<FinalizableCommand> myList;
    private final Condition myExpireCondition;

    private CommandGroup(final List<FinalizableCommand> list, final Condition expireCondition) {
      myList = list;
      myExpireCondition = expireCondition;
    }

    public Condition getExpireCondition() {
      return myExpireCondition;
    }

    public boolean isEmpty() {
      return myList.isEmpty();
    }

    public FinalizableCommand takeNextCommand() {
      return myList.remove(0);
    }
  }
}


text:
module MongoMapper
  module Plugins
    module DynamicQuerying
      class DynamicFinder
        attr_reader :method, :attributes, :finder, :bang, :instantiator

        def initialize(method)
          @method = method
          @finder = :first
          @bang   = false
          match
        end

        def found?
          @finder.present?
        end

        def raise?
          bang == true
        end

      protected

        def match
          case method.to_s
            when /^find_(all_by|by)_([_a-zA-Z]\w*)$/
              @finder = :all if $1 == 'all_by'
              names = $2
            when /^find_by_([_a-zA-Z]\w*)\!$/
              @bang = true
              names = $1
            when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
              @instantiator = $1 == 'initialize' ? :new : :create
              names = $2
            else
              @finder = nil
          end

          @attributes = names && names.split('_and_')
        end
      end
    end
  end
end


text:
//@@author A0121621Y

package jfdi.storage.entities;

/**
 * This is the Alias entity class.
 *
 * @author Thng Kai Yuan
 *
 */
public class Alias {

    private String alias;
    private String command;

    public Alias(String alias, String command) {
        this.alias = alias;
        this.command = command;
    }

    public String getAlias() {
        return alias;
    }

    public String getCommand() {
        return command;
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="wring">
        <note>
            Frames file for 'wring' based on sentences in wsj.  Verbnet entries
            40.3.2, 10.4.1, 9.3; Framenet entry Manipulation.
        </note>

        <roleset id="wring.01" name="twist" vncls="40.3.2">
            <roles>
                <role descr="twister" n="0">
                    <vnrole vncls="40.3.2" vntheta="Agent"/>
                </role>
                <role descr="twisted" n="1">
                    <vnrole vncls="40.3.2" vntheta="Patient"/>
                </role>
            </roles>

            <example name="both args">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/>
                <text>
                    Tuesday's earthquake brought the San Francisco ad scene to a
                    screeching halt yesterday, with [only a few staffers]-1 showing up at
                    their offices, [*-1] mainly to survey the damage or to wring their
                    hands about imminent new-business presentations.
                </text>
                <arg n="0">[*-1]</arg>
                <arg f="MNR" n="M">mainly</arg>
                <rel>wring</rel>
                <arg n="1">their hands</arg>
                <arg f="CAU" n="M">about imminent new-business presentations</arg>
            </example>

            <note>
            </note>

        </roleset>

        <roleset id="wring.02" name="remove liquid from, by   twisting" vncls="10.4.1 9.3">
            <roles>
                <role descr="remover" n="0">
                    <vnrole vncls="9.3" vntheta="Agent"/><vnrole vncls="10.4.1" vntheta="Agent"/>
                </role>
                <role descr="liquid" n="1">
                    <vnrole vncls="9.3" vntheta="Theme"/><vnrole vncls="10.4.1" vntheta="Theme"/>
                </role>
                <role descr="source; rag etc" n="2">
                    <vnrole vncls="9.3" vntheta="Destination"/><vnrole vncls="10.4.1" vntheta="Source"/>
                </role>
            </roles>

            <example name="badly parsed">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/>
                <text>
                    In a speech prepared for delivery to London's financial community,
                    Mr. Lawson summed up current economic policy as a battle [*] to
                    wring inflation out of the British economy, using high interest
                    rates as ``the essential instrument'' to carry out the campaign.
                </text>
                <arg n="0">[*]</arg>
                <rel>wring</rel>
                <arg n="1">inflation</arg>
                <arg n="2">out of the British economy</arg>
                <arg f="MNR" n="M">using high interest rates as ``the
                    essential instrument'' to carry out the campaign
                </arg>
            </example>

            <note>
                There are a variety of ways to handle the 'out of'; Treebank chooses
                among them, almost always incorrectly.  Do what you have to do.
                (Really, it should be a PP.)
            </note>

        </roleset>
    </predicate>

    <predicate lemma="wring_out">

        <roleset id="wring.03" name="drain completely" vncls="-">
            <roles>
                <role descr="wringer" n="0"/>
                <role descr="wrung" n="1"/>
            </roles>

            <example name="bell wringer">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    Cleaning the garage really wrung John out.
                </text>
                <arg n="0">Cleaning the garage</arg>
                <arg f="ADV" n="m">really</arg>
                <rel>wrung out</rel>
                <arg n="1">John</arg>
            </example>

            <note>
                Be careful between this phrasal and wring.02 'remove' above.  The best
                distinction is to see if the 'out' can move around--if it can, then
                you're dealing with a phrasal.  If not, it's a PP.
            </note>

        </roleset>
    </predicate>
</frameset>


text:
Provides read-only access to Azure Mobile Services configuration settings.

## Example ##

    var config = require('mobileservice-config');
	var twitterConsumerKey = config.twitterConsumerKey;
	var mySetting = config.appSettings.MY_SETTING;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Notiser 116 (1907)

#### Original name
Botrytis capsularum Bres. & Vestergr.

### Remarks
null


text:
Spree::Core::Engine.routes.append do
  get 'about/index'
  match 'about', :to => "about#index"

  get 'return/index'
  match 'return', :to => "return#index"

  get 'tandc/index'
  match 'tandc', :to => "tandc#index"

  get 'faq/index'
  match 'faq', :to => "faq#index"

  get 'news_letter/index'
  match 'news_letter', :to => "news_letter#index"

  get 'contact_us/index'
  match 'contact_us', :to => "contact_us#index"

  get 'delivery/index'
  match 'delivery', :to => "delivery#index"

  get 'cupcake_decorations/index'
  match 'cupcake_decorations', :to => "cupcake_decorations#index"

  get 'site/index'
  match 'site', :to => "site#index"

  get 'sitemap/index'
  match 'sitemap', :to => "sitemap#index"

  namespace :admin do
    resource :google_merchants
  end

end


text:
package org.kaaproject.kaa.server.control;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.kaaproject.kaa.common.dto.ApplicationDto;
import org.kaaproject.kaa.common.dto.EndpointGroupDto;

/**
 * The Class ControlServerEndpointGroupIT.
 */
public class ControlServerEndpointGroupIT extends AbstractTestControlServer {

    /**
     * Test create endpoint group.
     *
     * @throws Exception the exception
     */
    @Test
    public void testCreateEndpointGroup() throws Exception {
        EndpointGroupDto endpointGroup = createEndpointGroup();
        Assert.assertFalse(strIsEmpty(endpointGroup.getId()));
    }

    /**
     * Test get endpoint group.
     *
     * @throws Exception the exception
     */
    @Test
    public void testGetEndpointGroup() throws Exception {
        EndpointGroupDto endpointGroup = createEndpointGroup();

        EndpointGroupDto storedEndpointGroup = client.getEndpointGroup(endpointGroup.getId());

        Assert.assertNotNull(storedEndpointGroup);
        assertEndpointGroupsEquals(endpointGroup, storedEndpointGroup);
    }

    /**
     * Test get endpoint groups by application id.
     *
     * @throws Exception the exception
     */
    @Test
    public void testGetEndpointGroupsByApplicationId() throws Exception {

        List<EndpointGroupDto> endpointGroups  = new ArrayList<>(11);

        ApplicationDto application = createApplication(tenantAdminDto);
        loginTenantDeveloper(tenantDeveloperDto.getUsername());

        List<EndpointGroupDto> defaultEndpointGroups = client.getEndpointGroups(application.getId());
        endpointGroups.addAll(defaultEndpointGroups);

        for (int i = 0; i < 10; i++) {
            EndpointGroupDto endpointGroup = createEndpointGroup(application.getId());
            endpointGroups.add(endpointGroup);
        }

        Collections.sort(endpointGroups, new IdComparator());

        List<EndpointGroupDto> storedEndpointGroups = client.getEndpointGroups(application.getId());

        Collections.sort(storedEndpointGroups, new IdComparator());

        Assert.assertEquals(endpointGroups.size(), storedEndpointGroups.size());
        for (int i=0;i<endpointGroups.size();i++) {
            EndpointGroupDto endpointGroup = endpointGroups.get(i);
            EndpointGroupDto storedEndpointGroup = storedEndpointGroups.get(i);
            assertEndpointGroupsEquals(endpointGroup, storedEndpointGroup);
        }
    }

    /**
     * Test get endpoint groups by application token.
     *
     * @throws Exception the exception
     */
    @Test
    public void testGetEndpointGroupsByApplicationToken() throws Exception {

        List<EndpointGroupDto> endpointGroups  = new ArrayList<>(11);

        ApplicationDto application = createApplication(tenantAdminDto);
        loginTenantDeveloper(tenantDeveloperDto.getUsername());

        List<EndpointGroupDto> defaultEndpointGroups = client.getEndpointGroupsByAppToken(application.getApplicationToken());
        endpointGroups.addAll(defaultEndpointGroups);

        for (int i = 0; i < 10; i++) {
            EndpointGroupDto endpointGroup = createEndpointGroup(application.getId());
            endpointGroups.add(endpointGroup);
        }

        Collections.sort(endpointGroups, new IdComparator());

        List<EndpointGroupDto> storedEndpointGroups = client.getEndpointGroupsByAppToken(application.getApplicationToken());

        Collections.sort(storedEndpointGroups, new IdComparator());

        Assert.assertEquals(endpointGroups.size(), storedEndpointGroups.size());
        for (int i=0;i<endpointGroups.size();i++) {
            EndpointGroupDto endpointGroup = endpointGroups.get(i);
            EndpointGroupDto storedEndpointGroup = storedEndpointGroups.get(i);
            assertEndpointGroupsEquals(endpointGroup, storedEndpointGroup);
        }
    }

    /**
     * Test delete endpoint group.
     *
     * @throws Exception the exception
     */
    @Test
    public void testDeleteEndpointGroup() throws Exception {
        final EndpointGroupDto endpointGroup = createEndpointGroup();
        client.deleteEndpointGroup(endpointGroup.getId());
        checkNotFound(new TestRestCall() {
            @Override
            public void executeRestCall() throws Exception {
                client.getEndpointGroup(endpointGroup.getId());
            }
        });
   }

    /**
     * Assert endpoint groups equals.
     *
     * @param endpointGroup the endpoint group
     * @param storedEndpointGroup the stored endpoint group
     */
    private void assertEndpointGroupsEquals(EndpointGroupDto endpointGroup, EndpointGroupDto storedEndpointGroup) {
        Assert.assertEquals(endpointGroup.getId(), storedEndpointGroup.getId());
        Assert.assertEquals(endpointGroup.getApplicationId(), storedEndpointGroup.getApplicationId());
        Assert.assertEquals(endpointGroup.getName(), storedEndpointGroup.getName());
        Assert.assertEquals(endpointGroup.getWeight(), storedEndpointGroup.getWeight());
    }

}


text:
.class Landroid/telecom/Call$9;
.super Ljava/lang/Object;
.source "Call.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/telecom/Call;->fireConferenceableCallsChanged()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/telecom/Call;

.field final synthetic val$call:Landroid/telecom/Call;

.field final synthetic val$callback:Landroid/telecom/Call$Callback;

# direct methods
.method constructor <init>(Landroid/telecom/Call;Landroid/telecom/Call$Callback;Landroid/telecom/Call;)V
    .locals 0
    .param p1, "this$0"    # Landroid/telecom/Call;
    .param p2, "val$callback"    # Landroid/telecom/Call$Callback;
    .param p3, "val$call"    # Landroid/telecom/Call;

    .prologue
    .line 1253
    iput-object p1, p0, Landroid/telecom/Call$9;->this$0:Landroid/telecom/Call;

    iput-object p2, p0, Landroid/telecom/Call$9;->val$callback:Landroid/telecom/Call$Callback;

    iput-object p3, p0, Landroid/telecom/Call$9;->val$call:Landroid/telecom/Call;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 3

    .prologue
    .line 1256
    iget-object v0, p0, Landroid/telecom/Call$9;->val$callback:Landroid/telecom/Call$Callback;

    iget-object v1, p0, Landroid/telecom/Call$9;->val$call:Landroid/telecom/Call;

    iget-object v2, p0, Landroid/telecom/Call$9;->this$0:Landroid/telecom/Call;

    invoke-static {v2}, Landroid/telecom/Call;->-get2(Landroid/telecom/Call;)Ljava/util/List;

    move-result-object v2

    invoke-virtual {v0, v1, v2}, Landroid/telecom/Call$Callback;->onConferenceableCallsChanged(Landroid/telecom/Call;Ljava/util/List;)V

    .line 1255
    return-void
.end method


text:
from base import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG

INSTALLED_APPS += (
    )

ROOT_URLCONF = 'bytenod.urls.dev'


text:
using ProxySwarm.Domain.Isolation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProxySwarm.Domain
{
    public class Coordinator : IDisposable
    {
        private readonly Isolated<IsolatedSwarmCoordinator> isolatedCoordinator;

        private IsolatedSwarmCoordinator CoordinatorValue
        {
            get
            {
                return this.isolatedCoordinator.Value;
            }
        }

        public Coordinator(CoordinatorCreateOptions options)
        {
            this.isolatedCoordinator = new Isolated<IsolatedSwarmCoordinator>();
            this.CoordinatorValue.Initialize(options);
        }

        public void Start()
        {
            this.CoordinatorValue.Start();
        }

        public void Pause()
        {
            this.CoordinatorValue.Pause();
        }

        public void ReadProxiesFromFiles(string[] fileNames)
        {
            this.CoordinatorValue.ReadProxiesFromFiles(fileNames);
        }

        public Task<CounterChangeInfo> GetCounterChangeAsync()
        {
            var callback = new MarshaledResultSetter<CounterChangeInfo>();
            this.CoordinatorValue.NotifyOnCounterChange(callback);
            return callback.Task;
        }

        #region IDisposable
        public void Dispose()
        {
            if (this.isolatedCoordinator != null)
            {
                this.isolatedCoordinator.Dispose();
            }
        }
        #endregion //IDisposable
    }
}


text:
#include "motor_api.h"

/************************
 * Non public functions *
 ************************/
int32_t base_motor_get_degrees(Base_Motor *motor)
{
    int32_t res;

    // Mark reading as true, so no race conditions occur
    motor->reading = true;
    res = motor->degrees;

    // Just to make sure motor->degrees never changes when reading = true
    ASSERT(res == motor->degrees);
    motor->reading = false;

    return res * motor->degree_ratio;
}

void base_motor_init(Base_Motor* motor, float degree_ratio,
                uint8_t interrupt_pin1, uint8_t interrupt_pin2,
                void (*interrupt_handler)(void))
{
    motor->interrupt_pin1 = interrupt_pin1;
    motor->interrupt_pin2 = interrupt_pin2;
    motor->degree_ratio = degree_ratio;
    motor->buffer = 0;
    motor->degrees = 0;
    motor->reading = false;

    pinMode(interrupt_pin1, INPUT_PULLUP);
    pinMode(interrupt_pin2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interrupt_pin1),
                    interrupt_handler, CHANGE);
}

void base_motor_update_degrees(Base_Motor *motor)
{
    byte pattern = digitalRead(motor->interrupt_pin1);
    pattern |= (digitalRead(motor->interrupt_pin2) << 1);

    // We determin the direction by a pattern formed by the values
    // read from pin1 and pin2
    // LOW = 0, HIGH = 1
    switch (pattern)
    {
    case 0b11:
    case 0b00:
        motor->direction = FORWARD;
        break;
    case 0b10:
    case 0b01:
        motor->direction = BACKWARD;
        break;
    default:
        ASSERT(false);
        break;
    }

    // If degrees are being read, update a buffer instead to avoid race condtions
    if (motor->reading)
    {
        motor->buffer += motor->direction;
    }
    else
    {
        // We need to add and reset the buffer when we are allowed to
        // write to the degrees
        motor->degrees += motor->direction + motor->buffer;
        motor->buffer = 0;
    }
}

/********************
 * Public functions *
 ********************/
void motor_init(Motor *motor, float degree_ratio, uint8_t pin,
                uint8_t interrupt_pin1, uint8_t interrupt_pin2,
                void (*interrupt_handler)(void))
{
    base_motor_init(&motor->base, degree_ratio, interrupt_pin1,
                    interrupt_pin2, interrupt_handler);

    motor->pin = pin;
    pinMode(pin, OUTPUT);
}

void advanced_motor_init(Advanced_Motor *motor, float degree_ratio,
                         uint8_t pin1, uint8_t pin2, uint8_t interrupt_pin1,
                         uint8_t interrupt_pin2,
                         void (*interrupt_handler)(void))
{
    base_motor_init(&motor->base, degree_ratio, interrupt_pin1,
                    interrupt_pin2, interrupt_handler);

    motor->pin1 = pin1;
    motor->pin2 = pin2;

    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
}

bool advanced_motor_turn_to_degree(Advanced_Motor *motor, uint16_t degree)
{
    // Turn to degree should only accept a degree value between
    // 0 and 359 inclusive
    ASSERT(degree < 360);

    int32_t current_pos = advanced_motor_get_degrees(motor);

    // We need to floor, because default casting rounds towards 0, and
    // we always wants it to round down for these calculations to work.
    int32_t turns = floor(current_pos / 360.0);

    // We need to choose two goal, one above and one below our current_pos.
    // These goal needs to be the full number representaion of the degree number
    // that has to be reached.
    int32_t goal2, goal1 = 360 * turns + degree;
    int32_t distance_forward, distance_backward;

    if (goal1 > current_pos)
    {
        goal2 = 360 * (turns - 1) + degree;
        distance_forward = current_pos - goal2;
        distance_backward = goal1 - current_pos;
    }
    else if (goal1 < current_pos)
    {
        goal2 = 360 * (turns + 1) + degree;
        distance_forward = current_pos - goal1;
        distance_backward = goal2 - current_pos;
    }
    // If goal and current_pos are equal, the motor doesn't need to turn, so
    // we just return
    else
    {
        return;
    }

    ASSERT(distance_forward >= 0);
    ASSERT(distance_backward >= 0);

    // Choose which direction to turn based on which distance is shortest
    if (distance_forward < distance_backward)
        return advanced_motor_turn_degrees(motor, distance_forward, FORWARD);
    else
        return advanced_motor_turn_degrees(motor, distance_backward, BACKWARD);
}

bool motor_turn_to_degree(Motor *motor, uint16_t degree)
{
    // Turn to degree should only accept a degree value between
    // 0 and 359 inclusive
    ASSERT(degree < 360);

    int32_t current_pos = motor_get_degrees(motor);
    int32_t turns = (current_pos / 360);
    int32_t goal = 360 * turns + degree;

    // If goal is lower than current_pos, then we need to choose a new goal,
    // 360 degrees bigger
    if (goal < current_pos)
        goal = 360 * (turns + 1) + degree;

    // Turn motor by the distance to the goal
    return motor_turn_degrees(motor, goal - current_pos);
}

bool lesser_than(int32_t value1, int32_t value2)
{
    return value1 < value2;
}

bool greater_than(int32_t value1, int32_t value2)
{
    return value1 > value2;
}

bool advanced_motor_turn_degrees(Advanced_Motor *motor, uint16_t degrees,
                                 int8_t direction)
{
    // Calculate the goal that the motor should reach
    int32_t read_degrees = advanced_motor_get_degrees(motor);
    int32_t goal = read_degrees + ((int32_t)degrees * direction);
    bool (*compare_to)(int32_t, int32_t);

    advanced_motor_turn(motor, direction);

    // Wait for the motor to reach the goal
    switch (direction)
    {
    case FORWARD:
        compare_to = lesser_than;
        break;
    case BACKWARD:
        compare_to = greater_than;
        break;
    default:
        ASSERT(false);
        break;
    }

    int32_t previouse_read_degrees;
    uint32_t error_timeout = millis() + 500;

    bool retval = true;
    do
    {
        previouse_read_degrees = read_degrees;
        read_degrees = advanced_motor_get_degrees(motor);

        if (previouse_read_degrees != read_degrees)
            error_timeout = millis() + 500;
        else if (error_timeout < millis())
        {
            retval = false;
            break;
        }
    } while (compare_to(goal, read_degrees));

    advanced_motor_stop(motor);
    return retval;
}

bool motor_turn_degrees(Motor *motor, uint16_t degrees)
{
    // Calculate the goal that the motor should reach
    int32_t read_degrees = motor_get_degrees(motor);
    int32_t goal = read_degrees + degrees;
    int32_t previouse_read_degrees;
    uint32_t error_timeout = millis() + 500;

    motor_turn(motor);

    bool retval = true;
    do
    {
        previouse_read_degrees = read_degrees;
        read_degrees = motor_get_degrees(motor);

        if (previouse_read_degrees != read_degrees)
            error_timeout = millis() + 500;
        else if (error_timeout < millis())
        {
            retval = false;
            break;
        }
    } while (goal > read_degrees);

    // Wait for the motor to reach the goal

    motor_stop(motor);
    return retval;
}

void advanced_motor_stop(Advanced_Motor *motor)
{
    // HACK: To break, we turn the motor in the other direction for a
    // fix amount of time.
    // It is not perfect, but it does reduce the coasting by a lot
    if (motor->base.direction == FORWARD)
        advanced_motor_turn(motor, BACKWARD);
    else
        advanced_motor_turn(motor, FORWARD);

    delay(60); // 60ms seems like a good delay
    digitalWrite(motor->pin1, LOW);
    digitalWrite(motor->pin2, LOW);
    delay(100); // give the motor time to stop coasting
}

void motor_stop(Motor *motor)
{
    digitalWrite(motor->pin, LOW);
}

void advanced_motor_turn(Advanced_Motor *motor, int8_t direction)
{
    switch (direction)
    {
    case FORWARD:
        digitalWrite(motor->pin1, HIGH);
        digitalWrite(motor->pin2, LOW);
        break;
    case BACKWARD:
        digitalWrite(motor->pin1, LOW);
        digitalWrite(motor->pin2, HIGH);
        break;
    default:
        ASSERT(false);
        break;
    }
}

void motor_turn(Motor *motor)
{
    digitalWrite(motor->pin, HIGH);
}

int32_t motor_get_degrees(Motor *motor)
{
    return base_motor_get_degrees(&motor->base);
}

int32_t advanced_motor_get_degrees(Advanced_Motor *motor)
{
    return base_motor_get_degrees(&motor->base);
}

void motor_update_degrees(Motor *motor)
{
    base_motor_update_degrees(&motor->base);
}

void advanced_motor_update_degrees(Advanced_Motor *motor)
{
    base_motor_update_degrees(&motor->base);
}


text:
// The MIT License (MIT)

// Copyright (c) 2016 Reid Levenick

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "statemachine.h"

#include <stdint.h>

#include "../controller.h"
#include "color.h"
#include "constants.h"

static uint8_t Exit_fulfilled(Exit *exit, uint8_t anim_frac, Controller *controller) {
    uint8_t successes = 0;
    // Not sure if the processor supports popcount. On the other hand, I'd be surprised if it didn't.
    successes += __builtin_popcount(exit->button_mask & controller->button_states);

    successes += (exit->analog_mask >> 0) == 1 ? Direction_inside(exit->joy_dir, controller->joy_x, controller->joy_y) : 0;
    successes += (exit->analog_mask >> 1) == 1 ? Direction_inside(exit->c_dir, controller->c_x, controller->c_y) : 0;
    successes += (exit->analog_mask >> 2) & (controller->analog_l > exit->l_min);
    successes += (exit->analog_mask >> 3) & (controller->analog_l < exit->l_max);
    successes += (exit->analog_mask >> 4) & (controller->analog_r > exit->l_min);
    successes += (exit->analog_mask >> 5) & (controller->analog_r < exit->l_max);
    successes += (exit->analog_mask >> 6) & (anim_frac >= exit->frac_limit);

    switch(exit->method) {
        default:
        case SELECTION_ANY:
            return successes > 0;
        case SELECTION_ALL:
            return successes >= __builtin_popcount(exit->button_mask) + __builtin_popcount(exit->analog_mask);
    }
}

Machine Machine_deserialize(uint8_t *data) {
    Machine machine;
    machine.num_anims = data[0];
    machine.num_exits = data[1];
    machine.num_states = data[2];

    uint16_t cursor = 3;

    machine.anims = (Animation*)&data[cursor];
    cursor += machine.num_anims * sizeof(Animation);
    machine.exits = (Exit*)&data[cursor];
    cursor += machine.num_exits * sizeof(Exit);
    machine.states = (State*)&data[cursor];
    cursor += machine.num_states * sizeof(State);
    machine.exit_arrs = (p_Exit*)&data[cursor];

    machine.current = 0;
    machine.current_exitp = 0;
    machine.anim_frac = 0;
    machine.anim_looping = 0;

    return machine;
}
void Machine_advance(Machine *machine, Controller *controller) {
    State *current_state = &machine->states[machine->current];
    Animation *current_anim = &machine->anims[current_state->anim];

    switch(current_anim->looping) {
        default:
        case LOOP_STICK:
            if(machine->anim_frac >= 255 - current_anim->speed) {
                machine->anim_frac = 255;
            } else {
                machine->anim_frac += current_anim->speed;
            }
            break;
        case LOOP_WRAP:
            machine->anim_frac += current_anim->speed;
            break;
        case LOOP_BOUNCE:
            if(machine->anim_looping == 0) {
                if(machine->anim_frac >= 255 - current_anim->speed) {
                    machine->anim_frac = 255;
                    machine->anim_looping = 1;
                } else {
                    machine->anim_frac += current_anim->speed;
                }
            } else /* anim_looping != 0 */ {
                if(machine->anim_frac <= 0 + current_anim->speed) {
                    machine->anim_frac = 0;
                    machine->anim_looping = 0;
                } else {
                    machine->anim_frac -= current_anim->speed;
                }
            }
            break;
    }

    // Test each exit
    p_Exit exitp = machine->current_exitp;
    for(int i = 0; i < current_state->num_exits; ++i, ++exitp) {
        Exit *current_exit = &machine->exits[machine->exit_arrs[exitp]];

        if(Exit_fulfilled(current_exit, machine->anim_frac, controller)) {
            machine->current = current_exit->next;
            machine->anim_frac = 0;
            machine->anim_looping = 0;

            machine->current_exitp = 0;
            for(int j = 0; j < machine->current; ++j) {
                machine->current_exitp += machine->states[j].num_exits;
            }

            break;
        }
    }
}
// Expects 5 colors to be available at the output location.
void Machine_color(Machine *machine, Color *output) {
    Animation *current_anim = &machine->anims[machine->states[machine->current].anim];

    for(int i = 0; i < 5; ++i) {
        if(PATTERN_LIGHT_ON(current_anim->pattern, i)) {
            uint8_t anim_frac;

            if(PATTERN_LIGHT_REVERSE(current_anim->pattern, i)) {
                anim_frac = ~machine->anim_frac;
            } else {
                anim_frac = machine->anim_frac;
            }

            Color_interpolate(output + i, current_anim->start, current_anim->finish, current_anim->method, anim_frac);
        }
    }
}


text:
package io.novaordis.gld.api;

import org.junit.Test;

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

/**
 * @author Ovidiu Feodorov <ovidiu@novaordis.com>
 * @since 12/7/16
 */
public class UtilTest {

    // Constants -------------------------------------------------------------------------------------------------------

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    // Constructors ----------------------------------------------------------------------------------------------------

    // Public ----------------------------------------------------------------------------------------------------------

    // Tests -----------------------------------------------------------------------------------------------------------

    @Test
    public void firstCharacters_StringEquals() throws Exception {

        assertEquals("abc", Util.firstCharacters("abc", 3));
    }

    @Test
    public void firstCharacters_StringLonger() throws Exception {

        assertEquals("abc...", Util.firstCharacters("abcd", 3));
    }

    @Test
    public void firstCharacters_null() throws Exception {

        assertNull(Util.firstCharacters(null, 3));
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>X-Index</title>
<meta name="date" content="2015-03-27">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I L M N P Q R S T U V W X

X

XIOParserValidator - Class in venice.hub.utils

Provides validation of a command line argument for XIO parser name.

XIOParserValidator() - Constructor for class venice.hub.utils.XIOParserValidator

A C D E F G I L M N P Q R S T U V W X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package features.sectionlevel;

import tutorial.Tutorial;

public class IsOnlyAPIFeature {

	public static boolean eval(Tutorial fulltutorial, Tutorial tutorial, int currentSection)
	{
		String titleKey = tutorial.sectionElements.get(currentSection).getSection().getTitle() + tutorial.sectionElements.get(currentSection).getSection().getSubTitle();

		return fulltutorial.sectionElementsPerSection.get(titleKey).size() == 1;
	}
}


text:
class WXDLLIMPEXP_FWD_ADV wxTaskBarIconEvent;

// ----------------------------------------------------------------------------
// wxTaskBarIconBase: define wxTaskBarIcon interface
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_ADV wxTaskBarIconBase : public wxEvtHandler
{
public:
    wxTaskBarIconBase() { }

    // Operations:
    virtual bool SetIcon(const wxIcon& icon,
                         const wxString& tooltip = wxEmptyString) = 0;
    virtual bool RemoveIcon() = 0;
    virtual bool PopupMenu(wxMenu *menu) = 0;

protected:
    // creates menu to be displayed when user clicks on the icon
    virtual wxMenu *CreatePopupMenu() { return NULL; }

private:
    // default events handling, calls CreatePopupMenu:
    void OnRightButtonDown(wxTaskBarIconEvent& event);

    DECLARE_EVENT_TABLE()
    DECLARE_NO_COPY_CLASS(wxTaskBarIconBase)
};

// ----------------------------------------------------------------------------
// now include the actual class declaration
// ----------------------------------------------------------------------------

#if defined(__WXPALMOS__)
    #include "wx/palmos/taskbar.h"
#elif defined(__WXMSW__)
    #include "wx/msw/taskbar.h"
#elif defined(__WXGTK__) || defined(__WXX11__) || defined(__WXMOTIF__)
    #include "wx/unix/taskbarx11.h"
#elif defined (__WXMAC__) && defined(__WXMAC_OSX__)
    #include "wx/mac/taskbarosx.h"
#elif defined (__WXCOCOA__)
    #include "wx/cocoa/taskbar.h"
#endif

// ----------------------------------------------------------------------------
// wxTaskBarIcon events
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_ADV wxTaskBarIconEvent : public wxEvent
{
public:
    wxTaskBarIconEvent(wxEventType evtType, wxTaskBarIcon *tbIcon)
        : wxEvent(wxID_ANY, evtType)
    {
        SetEventObject(tbIcon);
    }

    virtual wxEvent *Clone() const { return new wxTaskBarIconEvent(*this); }

private:
    DECLARE_NO_ASSIGN_CLASS(wxTaskBarIconEvent)
};

typedef void (wxEvtHandler::*wxTaskBarIconEventFunction)(wxTaskBarIconEvent&);

BEGIN_DECLARE_EVENT_TYPES()
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_MOVE,1550)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_LEFT_DOWN,1551)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_LEFT_UP,1552)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_RIGHT_DOWN,1553)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_RIGHT_UP,1554)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_LEFT_DCLICK,1555)
    DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_ADV,wxEVT_TASKBAR_RIGHT_DCLICK,1556)
END_DECLARE_EVENT_TYPES()

#define wxTaskBarIconEventHandler(func) \
    (wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxTaskBarIconEventFunction, &func)

#define wx__DECLARE_TASKBAREVT(evt, fn) \
    wx__DECLARE_EVT0(wxEVT_TASKBAR_ ## evt, wxTaskBarIconEventHandler(fn))

#define EVT_TASKBAR_MOVE(fn)         wx__DECLARE_TASKBAREVT(MOVE, fn)
#define EVT_TASKBAR_LEFT_DOWN(fn)    wx__DECLARE_TASKBAREVT(LEFT_DOWN, fn)
#define EVT_TASKBAR_LEFT_UP(fn)      wx__DECLARE_TASKBAREVT(LEFT_UP, fn)
#define EVT_TASKBAR_RIGHT_DOWN(fn)   wx__DECLARE_TASKBAREVT(RIGHT_DOWN, fn)
#define EVT_TASKBAR_RIGHT_UP(fn)     wx__DECLARE_TASKBAREVT(RIGHT_UP, fn)
#define EVT_TASKBAR_LEFT_DCLICK(fn)  wx__DECLARE_TASKBAREVT(LEFT_DCLICK, fn)
#define EVT_TASKBAR_RIGHT_DCLICK(fn) wx__DECLARE_TASKBAREVT(RIGHT_DCLICK, fn)

// taskbar menu is shown on right button press under all platforms except MSW
// where it's shown on right button release, using this event type and macro
// allows to write code which works correctly on all platforms
#ifdef __WXMSW__
    #define wxEVT_TASKBAR_CLICK wxEVT_TASKBAR_RIGHT_UP
#else
    #define wxEVT_TASKBAR_CLICK wxEVT_TASKBAR_RIGHT_DOWN
#endif
#define EVT_TASKBAR_CLICK(fn)        wx__DECLARE_TASKBAREVT(CLICK, fn)

#endif // wxHAS_TASK_BAR_ICON

#endif // _WX_TASKBAR_H_BASE_


text:
.tooltip {
    background: #fff;
    border-radius: 4px;
    position: relative;
    width: 280px;
    transform: translateX(-50%);
    left: 50%;
    z-index: 200;
    top: 24px;
}

.tooltip:before {
    position: absolute;
    content: '';
    border-bottom: 8px solid #fff;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    top: -8px;
    left: 50%;
    transform: translateX(-50%);
}

.content {
    padding: 8px 8px 8px 12px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
}

.appendix {
    margin-top: 4px;
}

.close-icon {
    flex: 0 0 auto;
    cursor: pointer;
    margin-left: 8px;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record id="action_my_expense" model="ir.actions.act_window">
            <field name="name">My Expenses</field>
            <field name="res_model">hr.expense.expense</field>
            <field name="view_type">form</field>
            <field name="domain">[('state','in',('confirm', 'accepted')),('user_id','=',uid)]</field>
            <field name="context">{'default_user_id': uid}</field>
            <field name="view_id" ref="hr_expense.view_editable_expenses_tree"/>
        </record>

        <record id="board_hr_expense_form" model="ir.ui.view">
            <field name="name">board.hr.expense.form</field>
            <field name="model">board.board</field>
            <field name="inherit_id" ref="hr.board_hr_form"/>
            <field name="arch" type="xml">
                <xpath expr="/form/board/column[1]" position="inside">
                     <action name="%(action_my_expense)d" string="My Expenses"/>
                </xpath>
            </field>
        </record>

    </data>
</openerp>


text:
**Goal is a set of tools for high productivity web development in Go language.**

Goal, being mostly inspired by [Revel Framework](https://github.com/revel/revel)
and its discussions, is built around the concept of controllers and actions.
However, as opposed to Revel and other high level frameworks Goal does not use runtime
reflection and does not require your app to import monolithic dependencies.

Instead Goal is implemented in a form of independent tools that
may be used with [`go generate`](https://blog.golang.org/generate).
That allows us to achieve type safety, minimalism of dependencies,
compatability with the standard library, and productivity for the end-developers.
At the same time Goal is very customizable (you can bring your own router, template system,
and any other component). But that's without prejudice to the easiness and seamless of experience
thanks to good defaults.

### Getting Started

1. Install Goal:

        go get -u github.com/colegion/goal

2. Create a [new skeleton application](https://colegion.github.io/goal/manual/new/index.html):

        goal new github.com/$username/$project

3. Start a [watcher / task runner](https://colegion.github.io/goal/manual/run/index.html):

        goal run github.com/$username/$project

### Documentation

* **[colegion.github.io/goal](https://colegion.github.io/goal)**
  * [Introduction](https://colegion.github.io/goal/manual/index.html)
  * [`goal new`](https://colegion.github.io/goal/manual/new/index.html) - generate skeleton application
  * [`goal run`](https://colegion.github.io/goal/manual/run/index.html) - start watcher / task runner
  * [`goal generate handlers`](https://colegion.github.io/goal/manual/handlers/index.html) - generate HTTP handler functions
    * [Actions](https://colegion.github.io/goal/manual/handlers/actions.html)
    * [Controllers](https://colegion.github.io/goal/manual/handlers/controllers.html)
  * `goal generate listing` - generate a list of file paths

All `goal generate *` tools may be used with [`go generate`](https://blog.golang.org/generate).

### Status

**Proof of Concept**: not ready for use in the wild.

[![GoDoc](https://godoc.org/github.com/colegion/goal?status.svg)](https://godoc.org/github.com/colegion/goal)
[![Build Status](https://travis-ci.org/colegion/goal.svg?branch=master)](https://travis-ci.org/colegion/goal)
[![Coverage Status](https://coveralls.io/repos/colegion/goal/badge.svg?branch=master)](https://coveralls.io/r/colegion/goal?branch=master)
[![Go Report Card](http://goreportcard.com/badge/colegion/goal?t=3)](http:/goreportcard.com/report/colegion/goal)

### License
Distributed under the BSD 2-clause "Simplified" License unless otherwise noted.


text:
<!--
  Copyright 2015 The AMP HTML 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.
-->
<!--
  Test Description:

  This test demonstrates an error message selected via dispatch_key rules.

  The <script> tag in the body is invalid only in it's location in the document.
  Other forms of <script> tags are allowed in the body, but not the runtime tag.
  We want to verify that the error message generated suggests a different
  parent, not different attribute values.
-->
<!doctype html>
<html ⚡>
<head>
  <meta charset="utf-8">
  <link rel="canonical" href="./regular-html-version.html" />
  <meta name="viewport" content="width=device-width,minimum-scale=1">
  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
</head>
<body>

  <!-- This is a valid runtime script tag ag, but it's invalid because it is
       found outside the <head>. The test demonstrates that the error message
       is useful, suggesting placement in the document head. -->

  <script async src="https://cdn.ampproject.org/v0.js"></script>

</body>
</html>


text:
/**
 * Use the sieve of eratosthenes to find all the prime numbers up to a certain limit.
 *
 * <p>Time Complexity: O(nloglogn)
 *
 * @author William Fiset, william.alexandre.fiset@gmail.com
 */
package com.williamfiset.algorithms.math;

public class SieveOfEratosthenes {

  // Gets all primes up to, but NOT including limit (returned as a list of primes)
  public static int[] sieve(int limit) {

    if (limit <= 2) return new int[0];

    // Find an upper bound on the number of prime numbers up to our limit.
    // https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
    final int numPrimes = (int) (1.25506 * limit / Math.log((double) limit));
    int[] primes = new int[numPrimes];
    int index = 0;

    boolean[] isComposite = new boolean[limit];
    final int sqrtLimit = (int) Math.sqrt(limit);
    for (int i = 2; i <= sqrtLimit; i++) {
      if (!isComposite[i]) {
        primes[index++] = i;
        for (int j = i * i; j < limit; j += i) isComposite[j] = true;
      }
    }
    for (int i = sqrtLimit + 1; i < limit; i++) if (!isComposite[i]) primes[index++] = i;
    return java.util.Arrays.copyOf(primes, index);
  }

  public static void main(String[] args) {

    // Generate all the primes up to 29 not inclusive
    int[] primes = sieve(29);

    // Prints [2, 3, 5, 7, 11, 13, 17, 19, 23]
    System.out.println(java.util.Arrays.toString(primes));
  }
}


text:
package messenger

import (
	"net/http"
	"net/url"
	"strings"
)

// UserProfile represents the profile information for a user.
type UserProfile struct {
	UserID    string `json:"id"`
	Name      string `json:"name"`
	FirstName string `json:"firstName"`
	Vanity    string `json:"vanity"`
	IsFriend  bool   `json:"is_friend"`
}

type singleUserResponse struct {
	Payload struct {
		Profiles map[string]UserProfile `json:"profiles"`
	} `json:"payload"`
	Error int `json:"error"`
}

// UserProfileInfo returns the user's profile given their ID.
func (s *Session) UserProfileInfo(userID string) (UserProfile, error) {
	form := make(url.Values)
	form.Set("ids[0]", userID)
	form = s.addFormMeta(form)

	req, _ := http.NewRequest(http.MethodPost, profileURL,
		strings.NewReader(form.Encode()))
	req.Header = defaultHeader()
	req.Header.Set("Content-Type", formURLEncoded)

	resp, err := s.doRequest(req)
	if err != nil {
		return UserProfile{}, err
	}

	defer resp.Body.Close()

	var singleUserResp singleUserResponse
	err = unmarshalPullData(resp.Body, &singleUserResp)
	if err != nil {
		return UserProfile{}, err
	}

	if singleUserResp.Error == loggedOutError {
		return UserProfile{}, ErrLoggedOut
	} else if singleUserResp.Error > 0 {
		return UserProfile{}, ErrUnknown
	}

	profile, found := singleUserResp.Payload.Profiles[userID]
	if !found {
		return UserProfile{}, ParseError{"could not find userID in response"}
	}

	return profile, nil
}

type allUsersResponse struct {
	Payload map[string]UserProfile `json:"payload"`
	Error   int                    `json:"error"`
}

// AllUserProfileInfo returns all the users' profiles in the session's friend
// list as a map indexed by the user's ID.
func (s *Session) AllUserProfileInfo() (map[string]UserProfile, error) {
	form := make(url.Values)
	form.Set("viewer", s.userID)
	form = s.addFormMeta(form)

	req, _ := http.NewRequest(http.MethodPost, allProfileURL,
		strings.NewReader(form.Encode()))
	req.Header = defaultHeader()

	resp, err := s.doRequest(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	var allUsersResp allUsersResponse
	err = unmarshalPullData(resp.Body, &allUsersResp)
	if err != nil {
		return nil, err
	}

	if allUsersResp.Error == loggedOutError {
		return nil, ErrLoggedOut
	} else if allUsersResp.Error > 0 {
		return nil, ErrUnknown
	}

	return allUsersResp.Payload, nil
}


text:
/**
 * This is lumtify router.
 */

import VueRouter from 'vue-router'

const Home = resolve => require(['./Views/Home.vue'], resolve)
const About = resolve => require(['./Views/About.vue'], resolve)
const Article = resolve => require(['./Views/Article.vue'], resolve)
const Articles = resolve => require(['./Views/Articles.vue'], resolve)
const Login = resolve => require(['./Views/Login.vue'], resolve)
const Register = resolve => require(['./Views/Register.vue'], resolve)
const Profile = resolve => require(['./Views/Profile.vue'], resolve)
const Setting = resolve => require(['./Views/Setting.vue'], resolve)
const UpdateArticle = resolve => require(['./Views/UpdateArticle.vue'], resolve)
const CreateArticle = resolve => require(['./Views/CreateArticle.vue'], resolve)
const Users = resolve => require(['./Views/Users.vue'], resolve)
const NotFound = resolve => require(['./Views/NotFound.vue'], resolve)

export default new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: [
        {
            name: 'home',
            path: '/',
            component: Home
        }, {
            name: 'about',
            path: '/about',
            component: About
        }, {
            name: 'login',
            path: '/login',
            component: Login
        }, {
            name: 'register',
            path: '/register',
            component: Register
        }, {
            name: 'profile',
            path: '/users/:uid/profile',
            meta: {
                auth: { required: true }
            },
            component: Profile
        }, {
            name: 'setting',
            path: '/users/:uid/setting',
            meta: {
                auth: { required: true }
            },
            component: Setting
        }, {
            name: 'articles',
            path: '/articles',
            component: Articles
        }, {
            name: 'article',
            path: '/articles/:link/read',
            component: Article
        }, {
            name: 'updateArticle',
            path: '/articles/:link/update',
            meta: {
                auth: {
                    required: true,
                    roles: ['admin', 'editor']
                },
            },
            component: UpdateArticle
        }, {
            name: 'createArticle',
            path: '/articles/create',
            meta: {
                auth: {
                    required: true,
                    roles: ['admin', 'editor']
                },
            },
            component: CreateArticle
        }, {
            name: 'users',
            path: '/users',
            meta: {
                auth: {
                    required: true,
                    roles: ['admin']
                }
            },
            component: Users
        }, {
            name: '404',
            path: '*',
            component: NotFound
        }
    ],
    linkActiveClass: 'active'
})


text:
module Regulator
  class ActiveAdminAdapter < ActiveAdmin::AuthorizationAdapter
    def authorized?(action, subject = nil)
      policy = retrieve_policy(subject)
      action = format_action(action, subject)
      policy.respond_to?(action) && policy.public_send(action)
    end

    def scope_collection(collection, action = Auth::READ)
      # scoping is appliable only to read/index action
      # which means there is no way how to scope other actions
      Regulator.policy_scope!(user, collection, self.resource.controller)
    end

    def retrieve_policy(subject)
      case subject
      when nil   then Regulator.policy!(user, resource, self.resource.controller)
      when Class then Regulator.policy!(user, subject.new, self.resource.controller)
      else Regulator.policy!(user, subject, self.resource.controller)
      end
    end

    def format_action(action, subject)
      # https://github.com/elabs/regulator/blob/master/lib/generators/regulator/install/templates/application_policy.rb
      case action
      when ActiveAdmin::Auth::CREATE  then :create?
      when ActiveAdmin::Auth::UPDATE  then :update?
      when ActiveAdmin::Auth::READ    then subject.is_a?(Class) ? :index? : :show?
      when ActiveAdmin::Auth::DESTROY then subject.is_a?(Class) ? :destroy_all? : :destroy?
      else "#{action}?"
      end
    end
  end
end


text:
module Fog
  module Compute
    class VcloudDirector
      class Real
        # Retrieve the owner of a vApp.
        #
        # @param [String] id Object identifier of the vApp.
        # @return [Excon::Response]
        #   * body<~Hash>:
        #
        # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppOwner.html
        # @since vCloud API version 1.5
        def get_vapp_owner(id)
          request(
            :expects    => 200,
            :idempotent => true,
            :method     => 'GET',
            :parser     => Fog::ToHashDocument.new,
            :path       => "vApp/#{id}/owner"
          )
        end
      end
    end
  end
end


text:
package Paws::OpsWorksCM::DescribeNodeAssociationStatus;
  use Moose;
  has NodeAssociationStatusToken => (is => 'ro', isa => 'Str', required => 1);
  has ServerName => (is => 'ro', isa => 'Str', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeNodeAssociationStatus');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::OpsWorksCM::DescribeNodeAssociationStatusResponse');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::OpsWorksCM::DescribeNodeAssociationStatus - Arguments for method DescribeNodeAssociationStatus on Paws::OpsWorksCM

=head1 DESCRIPTION

This class represents the parameters used for calling the method DescribeNodeAssociationStatus on the
AWS OpsWorks for Chef Automate service. Use the attributes of this class
as arguments to method DescribeNodeAssociationStatus.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeNodeAssociationStatus.

As an example:

  $service_obj->DescribeNodeAssociationStatus(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 B<REQUIRED> NodeAssociationStatusToken => Str

=head2 B<REQUIRED> ServerName => Str

The name of the server from which to disassociate the node.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method DescribeNodeAssociationStatus in L<Paws::OpsWorksCM>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
bool CheckServiceProcessReady() {
  NOTIMPLEMENTED();
  return false;
}

IPC::ChannelHandle GetServiceProcessChannel() {
  NOTIMPLEMENTED();
  return NULL;
}

bool ServiceProcessState::TakeSingletonLock() {
  NOTIMPLEMENTED();
  return false;
}

bool ForceServiceProcessShutdown(const std::string& version,
                                 base::ProcessId process_id) {
  if (kill(process_id, SIGTERM) < 0) {
    PLOG(ERROR) << "kill";
    return false;
  }
  return true;
}

bool ServiceProcessState::AddToAutoRun() {
  NOTIMPLEMENTED();
  return false;
}

bool ServiceProcessState::RemoveFromAutoRun() {
  NOTIMPLEMENTED();
  return false;
}


text:
<?php

namespace Helmelar\GameBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Helmelar\GameBundle\Entity\HelmKnowledge
 *
 * @ORM\Table(name="HELM_KNOWLEDGE")
 * @ORM\Entity
 */
class Knowledge
{
    /**
     * @var integer $helmKnowledgeId
     *
     * @ORM\Column(name="HELM_KNOWLEDGE_ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $helmKnowledgeId;

    /**
     * @var string $helmKnowledgeName
     *
     * @ORM\Column(name="HELM_KNOWLEDGE_NAME", type="string", length=255, nullable=false)
     */
    private $helmKnowledgeName;

    /**
     * @var boolean $helmKnowledgeType
     *
     * @ORM\Column(name="HELM_KNOWLEDGE_TYPE", type="boolean", nullable=false)
     */
    private $helmKnowledgeType;

    /**
     * Get helmKnowledgeId
     *
     * @return integer
     */
    public function getHelmKnowledgeId()
    {
        return $this->helmKnowledgeId;
    }

    /**
     * Set helmKnowledgeName
     *
     * @param string $helmKnowledgeName
     * @return HelmKnowledge
     */
    public function setHelmKnowledgeName($helmKnowledgeName)
    {
        $this->helmKnowledgeName = $helmKnowledgeName;

        return $this;
    }

    /**
     * Get helmKnowledgeName
     *
     * @return string
     */
    public function getHelmKnowledgeName()
    {
        return $this->helmKnowledgeName;
    }

    /**
     * Set helmKnowledgeType
     *
     * @param boolean $helmKnowledgeType
     * @return HelmKnowledge
     */
    public function setHelmKnowledgeType($helmKnowledgeType)
    {
        $this->helmKnowledgeType = $helmKnowledgeType;

        return $this;
    }

    /**
     * Get helmKnowledgeType
     *
     * @return boolean
     */
    public function getHelmKnowledgeType()
    {
        return $this->helmKnowledgeType;
    }
}


text:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using static Indy.Sdk.Dotnet.IndyNativeMethods;

namespace Indy.Sdk.Dotnet.Wrapper
{
    /// <summary>
    /// Base class for all asynchronous wrapper classes.
    /// </summary>
    public abstract class AsyncWrapperBase
    {
        /// <summary>
        /// The next command handle to use.
        /// </summary>
        private static int _nextCommandHandle = 0;

        /// <summary>
        /// Gets the map of command handles and their task completion sources.
        /// </summary>
        private static IDictionary<int, object> _taskCompletionSources = new ConcurrentDictionary<int, object>();

        /// <summary>
        /// Gets the callback to use for functions that don't return a value.
        /// </summary>
        internal static NoValueDelegate _noValueCallback = (xcommand_handle, err) =>
        {
            var taskCompletionSource = RemoveTaskCompletionSource<bool>(xcommand_handle);

            if (!CheckCallback(taskCompletionSource, err))
                return;

            taskCompletionSource.SetResult(true);
        };

        /// <summary>
        /// Checks the result from a Sovrin function call.
        /// </summary>
        /// <exception cref="IndyException">If the result is not a success result a SovrinException will be thrown.</exception>
        /// <param name="result">The result to check.</param>
        protected static void CheckResult(int result)
        {
            if (result != (int)ErrorCode.Success)
                throw IndyException.fromErrorCode(result);
        }

        /// <summary>
        /// Checks the result of a callback made by the Sovrin library.
        /// </summary>
        /// <typeparam name="T">The type the promise will return.</typeparam>
        /// <param name="taskCompletionSource">The source controlling the async result.</param>
        /// <param name="errorCode">The error code returned to the callback by the sovrin function.</param>
        /// <returns>true if the error code was success, otherwise false.</returns>
        /// <exception cref="IndyException">If the errorCode is not a success result a SovrinException will be thrown.</exception>
        protected static bool CheckCallback<T>(TaskCompletionSource<T> taskCompletionSource, int errorCode)
        {
            if (errorCode != (int)ErrorCode.Success)
            {
                taskCompletionSource.SetException(IndyException.fromErrorCode(errorCode));
                return false;
            }

            return true;
        }

        /// <summary>
        /// Checks the result of a callback made by the Sovrin library.
        /// </summary>
        /// <param name="errorCode">The error code returned to the callback by the sovrin function.</param>
        /// <exception cref="IndyException">If the errorCode is not a success result a SovrinException will be thrown.</exception>
        protected static void CheckCallback(int errorCode)
        {
            if (errorCode != (int)ErrorCode.Success)
                throw IndyException.fromErrorCode(errorCode);
        }

        /// <summary>
        /// Gets the next command handle.
        /// </summary>
        /// <returns>The next command handle.</returns>
        protected static int GetNextCommandHandle()
        {
            return Interlocked.Increment(ref _nextCommandHandle);
        }

        /// <summary>
        /// Adds a new TaskCompletionSource to track.
        /// </summary>
        /// <typeparam name="T">The type of the TaskCompletionSource result.</typeparam>
        /// <param name="taskCompletionSource">The TaskCompletionSource to track.</param>
        /// <returns>The command handle to use for tracking the task completion source.</returns>
        protected static int AddTaskCompletionSource<T>(TaskCompletionSource<T> taskCompletionSource)
        {
            var commandHandle = GetNextCommandHandle();
            _taskCompletionSources.Add(commandHandle, taskCompletionSource);
            return commandHandle;
        }

        /// <summary>
        /// Gets and temoves a TaskCompletionResult from tracking.
        /// </summary>
        /// <typeparam name="T">The type of the TaskCompletionResult that was tracked.</typeparam>
        /// <param name="commandHandle">The command handle used for tracking the TaskCompletionResult.</param>
        /// <returns>The TaskCompletionResult associated with the command handle.</returns>
        protected static TaskCompletionSource<T> RemoveTaskCompletionSource<T>(int commandHandle)
        {
            Debug.Assert(_taskCompletionSources.ContainsKey(commandHandle), string.Format("No task completion source is currently registered for the command with the handle '{0}'.", commandHandle));

            var taskCompletionSource = _taskCompletionSources[commandHandle];
            _taskCompletionSources.Remove(commandHandle);
            var result = taskCompletionSource as TaskCompletionSource<T>;

            Debug.Assert(result != null, string.Format("No  task completion source of the specified type is registered for the command with the handle '{0}'.", commandHandle));

            return result;
        }

    }
}