text:
Twig
====

The *TwigServiceProvider* provides integration with the `Twig
<http://twig.sensiolabs.org/>`_ template engine.

Parameters
----------

* **twig.path** (optional): Path to the directory containing twig template
  files (it can also be an array of paths).

* **twig.templates** (optional): An associative array of template names to
  template contents. Use this if you want to define your templates inline.

* **twig.options** (optional): An associative array of twig
  options. Check out the `twig documentation <http://twig.sensiolabs.org/doc/api.html#environment-options>`_
  for more information.

* **twig.form.templates** (optional): An array of templates used to render
  forms (only available when the ``FormServiceProvider`` is enabled). The
  default theme is ``form_div_layout.html.twig``, but you can use the other
  built-in themes: ``form_table_layout.html.twig``,
  ``bootstrap_3_layout.html.twig``, and
  ``bootstrap_3_horizontal_layout.html.twig``.

Services
--------

* **twig**: The ``Twig_Environment`` instance. The main way of
  interacting with Twig.

* **twig.loader**: The loader for Twig templates which uses the ``twig.path``
  and the ``twig.templates`` options. You can also replace the loader
  completely.

Registering
-----------

.. code-block:: php

    $app->register(new Silex\Provider\TwigServiceProvider(), array(
        'twig.path' => __DIR__.'/views',
    ));

.. note::

    Add Twig as a dependency:

    .. code-block:: bash

        composer require twig/twig

Usage
-----

The Twig provider provides a ``twig`` service that can render templates::

    $app->get('/hello/{name}', function ($name) use ($app) {
        return $app['twig']->render('hello.twig', array(
            'name' => $name,
        ));
    });

Symfony Components Integration
------------------------------

Symfony provides a Twig bridge that provides additional integration between
some Symfony components and Twig. Add it as a dependency:

.. code-block:: bash

    composer require symfony/twig-bridge

When present, the ``TwigServiceProvider`` will provide you with the following
additional capabilities.

* Access to the ``path()`` and ``url()`` functions. You can find more
  information in the `Symfony Routing documentation
  <http://symfony.com/doc/current/book/routing.html#generating-urls-from-a-template>`_:

  .. code-block:: jinja

      {{ path('homepage') }}
      {{ url('homepage') }} {# generates the absolute url http://example.org/ #}
      {{ path('hello', {name: 'Fabien'}) }}
      {{ url('hello', {name: 'Fabien'}) }} {# generates the absolute url http://example.org/hello/Fabien #}

* Access to the ``absolute_url()`` and ``relative_path()`` Twig functions.

Translations Support
~~~~~~~~~~~~~~~~~~~~

If you are using the ``TranslationServiceProvider``, you will get the
``trans()`` and ``transchoice()`` functions for translation in Twig templates.
You can find more information in the `Symfony Translation documentation
<http://symfony.com/doc/current/book/translation.html#twig-templates>`_.

Form Support
~~~~~~~~~~~~

If you are using the ``FormServiceProvider``, you will get a set of helpers for
working with forms in templates. You can find more information in the `Symfony
Forms reference
<http://symfony.com/doc/current/reference/forms/twig_reference.html>`_.

Security Support
~~~~~~~~~~~~~~~~

If you are using the ``SecurityServiceProvider``, you will have access to the
``is_granted()`` function in templates. You can find more information in the
`Symfony Security documentation
<http://symfony.com/doc/current/book/security.html#access-control-in-templates>`_.

Global Variable
~~~~~~~~~~~~~~~

When the Twig bridge is available, the ``global`` variable refers to an
instance of `AppVariable <http://api.symfony.com/master/Symfony/Bridge/Twig/AppVariable.html>`_.
It gives access to the following methods:

.. code-block:: jinja

    {# The current Request #}
    {{ global.request }}

    {# The current User (when security is enabled) #}
    {{ global.user }}

    {# The current Session #}
    {{ global.session }}

    {# The debug flag #}
    {{ global.debug }}

Rendering a Controller
~~~~~~~~~~~~~~~~~~~~~~

A ``render`` function is also registered to help you render another controller
from a template (available when the :doc:`HttpFragment Service Provider
</providers/http_fragment>` is registered):

.. code-block:: jinja

    {{ render(url('sidebar')) }}

    {# or you can reference a controller directly without defining a route for it #}
    {{ render(controller(controller)) }}

.. note::

    You must prepend the ``app.request.baseUrl`` to render calls to ensure
    that the render works when deployed into a sub-directory of the docroot.

.. note::

    Read the Twig `reference`_ for Symfony document to learn more about the
    various Twig functions.

Traits
------

``Silex\Application\TwigTrait`` adds the following shortcuts:

* **render**: Renders a view with the given parameters and returns a Response
  object.

.. code-block:: php

    return $app->render('index.html', ['name' => 'Fabien']);

    $response = new Response();
    $response->setTtl(10);

    return $app->render('index.html', ['name' => 'Fabien'], $response);

.. code-block:: php

    // stream a view
    use Symfony\Component\HttpFoundation\StreamedResponse;

    return $app->render('index.html', ['name' => 'Fabien'], new StreamedResponse());

* **renderView**: Renders a view with the given parameters and returns a string.

.. code-block:: php

    $content = $app->renderView('index.html', ['name' => 'Fabien']);

Customization
-------------

You can configure the Twig environment before using it by extending the
``twig`` service::

    $app->extend('twig', function($twig, $app) {
        $twig->addGlobal('pi', 3.14);
        $twig->addFilter('levenshtein', new \Twig_Filter_Function('levenshtein'));

        return $twig;
    });

For more information, check out the `official Twig documentation
<http://twig.sensiolabs.org>`_.

.. _reference: https://symfony.com/doc/current/reference/twig_reference.html#controller


text:
import argparse
import logging
from cutlass import iHMPSession

## globals
NAMESPACE = 'ihmp'
NODE_TYPE_ORDER = [
    'annotation', 'abundance_matrix',
    'wgs_assembled_seq_set', '16s_trimmed_seq_set',
    'wgs_raw_seq_set', '16s_raw_seq_set', 'wgs_dna_prep', '16s_dna_prep',
    'sample', 'visit', 'subject', 'study', 'project'
    ]

# input
parser = argparse.ArgumentParser()
parser.add_argument('--username', help='OSDF username')
parser.add_argument('--password', help='OSDF password')
parser.add_argument('--server', help='OSDF server address')
parser.add_argument('--tag', help='Unique tag for uploaded test nodes.')
args = parser.parse_args()

# main program
logging.basicConfig(level=logging.INFO)
session = iHMPSession(args.username, args.password, args.server)
osdf = session.get_osdf()

# query for all nodes with tag args.tag
qstring = "\"" + args.tag + "\"[tags]"
res = osdf.oql_query_all_pages(NAMESPACE, qstring)
print("OQL query=" + qstring + " result_count=" + str(res['result_count']))
results = res['results']

# sort nodes to satisfy dependency order when deleting - delete will fail
# otherwise
node_type_order = {}
nto = 1
for nt in NODE_TYPE_ORDER:
    node_type_order[nt] = nto
    nto = nto + 1
sorted_results = sorted(results, key=lambda k: node_type_order[k["node_type"]])

n_deleted = 0
for result in sorted_results:
    result_id = result['id']
    print("id=" + result_id + " node type=" + result["node_type"])
    tags = result['meta']['tags']

    for tag in tags:
        # double-check that args.tag is present - should be superfluous
        if (tag == args.tag):
            print("deleting " + result_id)
            osdf.delete_node(result_id)
            n_deleted = n_deleted + 1

print("Deleted count: " + str(n_deleted))

redpajama_set_name: RedPajamaGithub


text:
import {getMetadataArgsStorage} from "../../index";
import {EventListenerTypes} from "../../metadata/types/EventListenerTypes";
import {EntityListenerMetadataArgs} from "../../metadata-args/EntityListenerMetadataArgs";

/**
 * Calls a method on which this decorator is applied before this entity update.
 */
export function BeforeUpdate() {
    return function (object: Object, propertyName: string) {
        const args: EntityListenerMetadataArgs = {
            target: object.constructor,
            propertyName: propertyName,
            type: EventListenerTypes.BEFORE_UPDATE
        };
        getMetadataArgsStorage().entityListeners.add(args);
    };
}


text: package me.icymint.sloth;


text:
#ifndef __QSEECOM_KERNEL_H_
#define __QSEECOM_KERNEL_H_

#include <linux/types.h>

#define QSEECOM_ALIGN_SIZE	0x40
#define QSEECOM_ALIGN_MASK	(QSEECOM_ALIGN_SIZE - 1)
#define QSEECOM_ALIGN(x)	\
	((x + QSEECOM_ALIGN_SIZE) & (~QSEECOM_ALIGN_MASK))

/*
 * struct qseecom_handle -
 *      Handle to the qseecom device for kernel clients
 * @sbuf - shared buffer pointer
 * @sbbuf_len - shared buffer size
 */
struct qseecom_handle {
	void *dev; /* in/out */
	unsigned char *sbuf; /* in/out */
	uint32_t sbuf_len; /* in/out */
};

int qseecom_start_app(struct qseecom_handle **handle,
						char *app_name, uint32_t size);
int qseecom_shutdown_app(struct qseecom_handle **handle);
int qseecom_send_command(struct qseecom_handle *handle, void *send_buf,
			uint32_t sbuf_len, void *resp_buf, uint32_t rbuf_len);
int qseecom_set_bandwidth(struct qseecom_handle *handle, bool high);

#endif /* __QSEECOM_KERNEL_H_ */


text:
/**
 * MySQL connect code using Mongo SQL to generate SQL queries.
 */

// var mysql = require('mysql');
var pg = require('pg')
var moQuery = require('mongo-sql');
var Promise = require("bluebird");
var using = Promise.using;

var conf = require('./conf');

Promise.promisifyAll(pg);
Promise.promisifyAll(require("pg/lib/connection").prototype);
Promise.promisifyAll(require("pg/lib/pool"));

// var db = new pg(conf.postgres);

function buildQuery(spec) {
  var query = moQuery.sql(spec);
  return {
    text: query.toString().replace(/"/g, ''),
    values: query.values
  };
};

function getDisposableConn(trxnId) {
  return new Promise(function(resolve, reject) {
    pg.connect(conf.postgres, function(err, conn, done) {
      return err ? reject(err) : resolve(conn);
    });
  })
  .disposer(function(conn) {
    conn.done;
  });
};

function getTranscation(trxnId) {
  return new Promise(function(resolve, reject) {
    pg.connect(conf.postgres, function(err, conn, done) {
      if(err) return reject(err);
      conn.query('BEGIN', function(err) {
        return err ? reject(err) : resolve(conn);
      });
    });
  })
  .disposer(function(conn, promise) {
    if(promise.isFulfilled()) {
      console.log('commit');
      return conn.queryAsync('COMMIT').finally(conn.done);
    }
    else {
      console.log('rollback');
      return conn.queryAsync('ROLLBACK').finally(conn.done);
    }
    function release() {
      done();
    }
  });
};

function execute(spec, conn) {
  var query = buildQuery(spec);
  console.log(query);
  function _queryWithConn(cn) {
    return cn.queryAsync(query).then(function(result){
      return result;
    });
  }
  return conn && 'string' !== typeof conn
    ? _queryWithConn(conn)
    : using(getDisposableConn(conn), _queryWithConn);
};

module.exports = {
  execute: execute,
  getDisposableConn: getDisposableConn,
  getTranscation: getTranscation
};


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>X509CRLSelector - Android SDK | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  android

  android.accessibilityservice

  android.accounts

  android.animation

  android.app

  android.app.admin

  android.app.backup

  android.appwidget

  android.bluetooth

  android.content

  android.content.pm

  android.content.res

  android.database

  android.database.sqlite

  android.drm

  android.gesture

  android.graphics

  android.graphics.drawable

  android.graphics.drawable.shapes

  android.graphics.pdf

  android.hardware

  android.hardware.display

  android.hardware.input

  android.hardware.location

  android.hardware.usb

  android.inputmethodservice

  android.location

  android.media

  android.media.audiofx

  android.media.effect

  android.mtp

  android.net

  android.net.http

  android.net.nsd

  android.net.rtp

  android.net.sip

  android.net.wifi

  android.net.wifi.p2p

  android.net.wifi.p2p.nsd

  android.nfc

  android.nfc.cardemulation

  android.nfc.tech

  android.opengl

  android.os

  android.os.storage

  android.preference

  android.print

  android.print.pdf

  android.printservice

  android.provider

  android.renderscript

  android.sax

  android.security

  android.service.dreams

  android.service.notification

  android.service.textservice

  android.service.wallpaper

  android.speech

  android.speech.tts

  android.support.v13.app

  android.support.v4.accessibilityservice

  android.support.v4.app

  android.support.v4.content

  android.support.v4.content.pm

  android.support.v4.database

  android.support.v4.graphics.drawable

  android.support.v4.hardware.display

  android.support.v4.media

  android.support.v4.net

  android.support.v4.os

  android.support.v4.print

  android.support.v4.text

  android.support.v4.util

  android.support.v4.view

  android.support.v4.view.accessibility

  android.support.v4.widget

  android.support.v7.app

  android.support.v7.appcompat

  android.support.v7.gridlayout

  android.support.v7.media

  android.support.v7.mediarouter

  android.support.v7.view

  android.support.v7.widget

  android.support.v8.renderscript

  android.telephony

  android.telephony.cdma

  android.telephony.gsm

  android.test

  android.test.mock

  android.test.suitebuilder

  android.text

  android.text.format

  android.text.method

  android.text.style

  android.text.util

  android.transition

  android.util

  android.view

  android.view.accessibility

  android.view.animation

  android.view.inputmethod

  android.view.textservice

  android.webkit

  android.widget

  dalvik.bytecode

  dalvik.system

  java.awt.font

  java.beans

  java.io

  java.lang

  java.lang.annotation

  java.lang.ref

  java.lang.reflect

  java.math

  java.net

  java.nio

  java.nio.channels

  java.nio.channels.spi

  java.nio.charset

  java.nio.charset.spi

  java.security

  java.security.acl

  java.security.cert

  java.security.interfaces

  java.security.spec

  java.sql

  java.text

  java.util

  java.util.concurrent

  java.util.concurrent.atomic

  java.util.concurrent.locks

  java.util.jar

  java.util.logging

  java.util.prefs

  java.util.regex

  java.util.zip

  javax.crypto

  javax.crypto.interfaces

  javax.crypto.spec

  javax.microedition.khronos.egl

  javax.microedition.khronos.opengles

  javax.net

  javax.net.ssl

  javax.security.auth

  javax.security.auth.callback

  javax.security.auth.login

  javax.security.auth.x500

  javax.security.cert

  javax.sql

  javax.xml

  javax.xml.datatype

  javax.xml.namespace

  javax.xml.parsers

  javax.xml.transform

  javax.xml.transform.dom

  javax.xml.transform.sax

  javax.xml.transform.stream

  javax.xml.validation

  javax.xml.xpath

  junit.framework

  junit.runner

  org.apache.http

  org.apache.http.auth

  org.apache.http.auth.params

  org.apache.http.client

  org.apache.http.client.entity

  org.apache.http.client.methods

  org.apache.http.client.params

  org.apache.http.client.protocol

  org.apache.http.client.utils

  org.apache.http.conn

  org.apache.http.conn.params

  org.apache.http.conn.routing

  org.apache.http.conn.scheme

  org.apache.http.conn.ssl

  org.apache.http.conn.util

  org.apache.http.cookie

  org.apache.http.cookie.params

  org.apache.http.entity

  org.apache.http.impl

  org.apache.http.impl.auth

  org.apache.http.impl.client

  org.apache.http.impl.conn

  org.apache.http.impl.conn.tsccm

  org.apache.http.impl.cookie

  org.apache.http.impl.entity

  org.apache.http.impl.io

  org.apache.http.io

  org.apache.http.message

  org.apache.http.params

  org.apache.http.protocol

  org.apache.http.util

  org.json

  org.w3c.dom

  org.w3c.dom.ls

  org.xml.sax

  org.xml.sax.ext

  org.xml.sax.helpers

  org.xmlpull.v1

  org.xmlpull.v1.sax2

Interfaces

CertPathBuilderResult

CertPathParameters

CertPathValidatorResult

CertSelector

CertStoreParameters

CRLSelector

PolicyNode

X509Extension

Classes

Certificate

Certificate.CertificateRep

CertificateFactory

CertificateFactorySpi

CertPath

CertPath.CertPathRep

CertPathBuilder

CertPathBuilderSpi

CertPathValidator

CertPathValidatorSpi

CertStore

CertStoreSpi

CollectionCertStoreParameters

CRL

LDAPCertStoreParameters

PKIXBuilderParameters

PKIXCertPathBuilderResult

PKIXCertPathChecker

PKIXCertPathValidatorResult

PKIXParameters

PolicyQualifierInfo

TrustAnchor

X509Certificate

X509CertSelector

X509CRL

X509CRLEntry

X509CRLSelector

Exceptions

CertificateEncodingException

CertificateException

CertificateExpiredException

CertificateNotYetValidException

CertificateParsingException

CertPathBuilderException

CertPathValidatorException

CertStoreException

CRLException

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Ctors

  | Methods

  | Inherited Methods

| [Expand All]

  Added in API level 1

    public

    class

X509CRLSelector

    extends Object

      implements

        CRLSelector

        java.lang.Object

               ↳

        java.security.cert.X509CRLSelector

Class Overview

A CRL selector (CRLSelector for selecting X509CRLs that match the specified criteria.

 When constructed, all criteria are set to default values that will match any
 X509CRL.

Summary

Public Constructors

        <nobr>

            </nobr>

        <nobr>
        X509CRLSelector()</nobr>

Creates a new X509CertSelector.

Public Methods

        <nobr>

            void</nobr>

        <nobr>
        addIssuer(X500Principal issuer)</nobr>

Adds an issuer to the criterion for the issuer distinguished names.

        <nobr>

            void</nobr>

        <nobr>
        addIssuerName(byte[] iss_name)</nobr>

Adds an issuer to the criterion for the issuer distinguished names.

        <nobr>

            void</nobr>

        <nobr>
        addIssuerName(String iss_name)</nobr>

Do not use:, use addIssuer(X500Principal) or
 addIssuerName(byte[]) instead.

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

Clones this X509CRL instance.

        <nobr>

            X509Certificate</nobr>

        <nobr>
        getCertificateChecking()</nobr>

Returns the certificate hint to find CRLs.

        <nobr>

            Date</nobr>

        <nobr>
        getDateAndTime()</nobr>

Returns the criterion for the CRL update period.

        <nobr>

            Collection<Object></nobr>

        <nobr>
        getIssuerNames()</nobr>

Returns the criterion for the issuer distinguished names.

        <nobr>

            Collection<X500Principal></nobr>

        <nobr>
        getIssuers()</nobr>

Returns the criterion for the issuer distinguished names.

        <nobr>

            BigInteger</nobr>

        <nobr>
        getMaxCRL()</nobr>

Returns the criterion for the maximum CRL number.

        <nobr>

            BigInteger</nobr>

        <nobr>
        getMinCRL()</nobr>

Returns the criterion for the minimum CRL number.

        <nobr>

            boolean</nobr>

        <nobr>
        match(CRL crl)</nobr>

Returns whether the specified CRL matches all the criteria collected in
 this instance.

        <nobr>

            void</nobr>

        <nobr>
        setCertificateChecking(X509Certificate cert)</nobr>

Sets a certificate hint to find CRLs.

        <nobr>

            void</nobr>

        <nobr>
        setDateAndTime(Date dateAndTime)</nobr>

Sets the criterion for the CRL update period.

        <nobr>

            void</nobr>

        <nobr>
        <a href="../../../../reference/java/security/cert/X509CRLSelector.html#setIssuerNames(java.util.Collection<?>)">setIssuerNames(Collection<?> names)</nobr>

Do not use: use <a href="../../../../reference/java/security/cert/X509CRLSelector.html#setIssuers(java.util.Collection<javax.security.auth.x500.X500Principal>)">setIssuers(Collection) or one of
 addIssuerName(byte[]) instead.

        <nobr>

            void</nobr>

        <nobr>
        <a href="../../../../reference/java/security/cert/X509CRLSelector.html#setIssuers(java.util.Collection<javax.security.auth.x500.X500Principal>)">setIssuers(Collection<X500Principal> issuers)</nobr>

Sets the criterion for the issuer distinguished names.

        <nobr>

            void</nobr>

        <nobr>
        setMaxCRLNumber(BigInteger maxCRL)</nobr>

Sets the criterion for the maximum CRL number.

        <nobr>

            void</nobr>

        <nobr>
        setMinCRLNumber(BigInteger minCRL)</nobr>

Sets the criterion for the minimum CRL number.

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

Returns a string representation of this X509CRLSelector instance.

  [Expand]

Inherited Methods

From class

  java.lang.Object

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

Creates and returns a copy of this Object.

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object o)</nobr>

Compares this instance with the specified object and indicates if they
 are equal.

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

Invoked when the garbage collector has detected that this instance is no longer reachable.

        <nobr>

            final

            Class<?></nobr>

        <nobr>
        getClass()</nobr>

Returns the unique instance of Class that represents this
 object's class.

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

Returns an integer hash code for this object.

        <nobr>

            final

            void</nobr>

        <nobr>
        notify()</nobr>

Causes a thread which is waiting on this object's monitor (by means of
 calling one of the wait() methods) to be woken up.

        <nobr>

            final

            void</nobr>

        <nobr>
        notifyAll()</nobr>

Causes all threads which are waiting on this object's monitor (by means
 of calling one of the wait() methods) to be woken up.

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

Returns a string containing a concise, human-readable description of this
 object.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait()</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long millis, int nanos)</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
 specified timeout expires.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long millis)</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
 specified timeout expires.

From interface

  java.security.cert.CRLSelector

        <nobr>
            abstract

            Object</nobr>

        <nobr>
        clone()</nobr>

Clones this CRLSelector instance.

        <nobr>
            abstract

            boolean</nobr>

        <nobr>
        match(CRL crl)</nobr>

Checks whether the defined criteria of this instance match the specified
 CRL.

Public Constructors

        public

      X509CRLSelector
      ()

  Added in API level 1

Creates a new X509CertSelector.

Public Methods

        public

        void

      addIssuer
      (X500Principal issuer)

  Added in API level 1

Adds an issuer to the criterion for the issuer distinguished names.

 The CRL issuer must match at least one of the specified distinguished
 names.

Parameters

          issuer
          the issuer to add to the criterion

        public

        void

      addIssuerName
      (byte[] iss_name)

  Added in API level 1

Adds an issuer to the criterion for the issuer distinguished names.

 The CRL issuer must match at least one of the specified distinguished
 names.

Parameters

          iss_name
          the issuer to add to the criterion in ASN.1 DER encoded form.

Throws

            IOException
            if parsing fails.

        public

        void

      addIssuerName
      (String iss_name)

  Added in API level 1

Do not use:, use addIssuer(X500Principal) or
 addIssuerName(byte[]) instead. It can fail to match some CRLs
 because of a loss of encoding information in a RFC 2253 string.

 Adds an issuer to the criterion for the issuer distinguished names. The
 CRK issuer must match at least one of the specified distinguished names.

Parameters

          iss_name
          the RFC 2253 encoded name.

Throws

            IOException
            if parsing fails.

        public

        Object

      clone
      ()

  Added in API level 1

Clones this X509CRL instance.

Returns

the cloned instance.

        public

        X509Certificate

      getCertificateChecking
      ()

  Added in API level 1

Returns the certificate hint to find CRLs. It's not a criterion but may
 help finding relevant CRLs.

Returns

the certificate hint or null if none set.

        public

        Date

      getDateAndTime
      ()

  Added in API level 1

Returns the criterion for the CRL update period.

 The CRL's thisUpdate value must be equal or before the returned
 date and the nextUpdate value must be after the returned date.

Returns

the date to search for valid CRL's or null if the date is
         not checked.

        public

        Collection<Object>

      getIssuerNames
      ()

  Added in API level 1

Returns the criterion for the issuer distinguished names.

 The CRL issuer must match at least one of the distinguished names.

Returns

a copy of the list of issuer distinguished names to
         match, or null if any issuer distinguished name
         will do. The elements may be strings or ASN.1 DER
         encoded byte arrays.

        public

        Collection<X500Principal>

      getIssuers
      ()

  Added in API level 1

Returns the criterion for the issuer distinguished names.

 The CRL issuer must match at least one of the distinguished names.

Returns

the unmodifiable list of issuer distinguished names to match, or
         null if any issuer distinguished name will do.

        public

        BigInteger

      getMaxCRL
      ()

  Added in API level 1

Returns the criterion for the maximum CRL number.

 The CRL must have a number extension with a value less than or equal to
 the returned value.

Returns

the maximum CRL number or null if the maximum CRL number is not
         checked.

        public

        BigInteger

      getMinCRL
      ()

  Added in API level 1

Returns the criterion for the minimum CRL number.

 The CRL must have a number extension with a value greater than or equal
 to the returned value.

Returns

the minimum CRL number or null if the minimum CRL number
         is not to be checked.

        public

        boolean

      match
      (CRL crl)

  Added in API level 1

Returns whether the specified CRL matches all the criteria collected in
 this instance.

Parameters

          crl
          the CRL to check.

Returns

true if the CRL matches all the criteria, otherwise
         false.

        public

        void

      setCertificateChecking
      (X509Certificate cert)

  Added in API level 1

Sets a certificate hint to find CRLs. It's not a criterion but may help
 finding relevant CRLs.

Parameters

          cert
          the certificate hint or null.

        public

        void

      setDateAndTime
      (Date dateAndTime)

  Added in API level 1

Sets the criterion for the CRL update period.

 The CRL's thisUpdate value must be equal or before the specified
 date and the nextUpdate value must be after the specified date.

Parameters

          dateAndTime
          the date to search for valid CRL's or null to not
            check the date.

<A NAME="setIssuerNames(java.util.Collection<?>)">

        public

        void

      setIssuerNames
      (Collection<?> names)

  Added in API level 1

Do not use: use <a href="../../../../reference/java/security/cert/X509CRLSelector.html#setIssuers(java.util.Collection<javax.security.auth.x500.X500Principal>)">setIssuers(Collection) or one of
 addIssuerName(byte[]) instead. Sets the criterion for the issuer
 distinguished names.

 The CRL issuer must match at least one of the specified distinguished
 names.

 The specified parameter names is a collection with an entry for
 each name to be included in the criterion. The name is specified as a
 String or a byte array specifying the name (in RFC 2253 or ASN.1
 DER encoded form)

Parameters

          names
          the list of issuer distinguished names to match, or null if any issuer distinguished name will do.

Throws

            IOException
            if parsing fails.

<A NAME="setIssuers(java.util.Collection<javax.security.auth.x500.X500Principal>)">

        public

        void

      setIssuers
      (Collection<X500Principal> issuers)

  Added in API level 1

Sets the criterion for the issuer distinguished names.

 The CRL issuer must match at least one of the specified distinguished
 names.

Parameters

          issuers
          the list of issuer distinguished names to match, or null if any issuer distinguished name will do.

        public

        void

      setMaxCRLNumber
      (BigInteger maxCRL)

  Added in API level 1

Sets the criterion for the maximum CRL number.

 The CRL must have a number extension with a value less than or equal to
 the specified parameter.

Parameters

          maxCRL
          the maximum CRL number or null to not check the maximum CRL
            number.

        public

        void

      setMinCRLNumber
      (BigInteger minCRL)

  Added in API level 1

Sets the criterion for the minimum CRL number.

 The CRL must have a number extension with a value greater than or equal
 to the specified parameter.

Parameters

          minCRL
          the minimum CRL number or null to not check the minimum CRL
            number

        public

        String

      toString
      ()

  Added in API level 1

Returns a string representation of this X509CRLSelector instance.

Returns

a string representation of this X509CRLSelector instance.

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android 4.4 r1 —

    About Android  |
    Legal  |
    Support


text:
/**
 * Created by fonpah on 18.05.2014.
 */
Ext.define('App.builder.CommentFormBuilder',{
    isReadOnly: false,
    buildForm: function(config){
        if(!config.figure){
            return false;
        }
        if(this.isReadOnly){
            return false;
        }
        return Ext.widget('window', {
            title: App.current.util.shortenString(config.figure.title,11),
            closeAction: 'hide',
            width: 400,
            height: 400,
            minHeight: 400,
            layout: 'fit',
            figure:config.figure,
            resizable: true,
            modal: true,
            listeners:{
                beforeshow:function(cmp){
                    cmp.setTitle(App.current.util.shortenString(cmp.figure.title,11));

                }
            }
            ,
            items: Ext.widget('form',{
                layout:{
                    type:'vbox',
                    align:'stretch'
                },
                border:false,
                bodyPadding:10,
                fieldDefaults:{
                    labelAlign:'top',
                    labelStyle:'font-weight:bold'
                },
                defaults:{
                    margins:'0 0 10 0'
                },
                items:[
                    {
                        xtype: 'htmleditor',
                        name: 'content',
                        height: 300,
                        allowBlank:false,
                        listeners:{
                            change:function(cmp){
                                //cmp.up('window' ).figure.content = cmp.getValue();
                            }
                        }
                    }
                ],
                buttons:[
                    {
                        text: 'Save',
                        handler: function(cmp) {
                            if(this.up('form').getForm().isValid()){
                                var fig =  cmp.up('window' ).figure;
                                var form = cmp.up('form' );
                                fig.comments.add({userId:'me',text:form.down('htmleditor' ).getValue(),activityId:fig.activityId,artifactId:fig.id});
                            }
                        }
                    },{
                        text: 'Cancel',
                        handler: function() {
                            this.up('window').close();
                        }
                    }
                ]
            })
        });

    }
});


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

<title>Class Hierarchy</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-04-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

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

JavaScript is disabled on your browser.

Hierarchy For All Packages

Package Hierarchies:

lejos.robotics.localization,

lejos.robotics.mapping,

lejos.robotics.navigation,

lejos.robotics.objectdetection,

lejos.robotics.pathfinding

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractList<E> (implements java.util.List<E>)

java.util.ArrayList<E> (implements java.lang.Cloneable, java.util.List<E>, java.util.RandomAccess, java.io.Serializable)

lejos.robotics.pathfinding.Path

lejos.robotics.navigation.ArcAlgorithms

lejos.robotics.pathfinding.AstarSearchAlgorithm (implements lejos.robotics.pathfinding.SearchAlgorithm)

lejos.robotics.localization.BeaconPoseProvider (implements lejos.robotics.navigation.MoveListener, lejos.robotics.localization.PoseProvider)

lejos.robotics.localization.BeaconTriangle

lejos.robotics.navigation.DifferentialPilot (implements lejos.robotics.navigation.LineFollowingMoveController)

lejos.robotics.navigation.CompassPilot

lejos.robotics.pathfinding.DijkstraPathFinder (implements lejos.robotics.pathfinding.PathFinder)

lejos.robotics.pathfinding.DijkstraPathFinder.Node

lejos.robotics.objectdetection.FeatureDetectorAdapter (implements lejos.robotics.objectdetection.FeatureDetector)

lejos.robotics.objectdetection.RangeFeatureDetector

lejos.robotics.objectdetection.TouchFeatureDetector

lejos.robotics.pathfinding.FourWayGridMesh (implements lejos.robotics.pathfinding.NavigationMesh)

lejos.robotics.objectdetection.FusorDetector (implements lejos.robotics.objectdetection.FeatureDetector, lejos.robotics.objectdetection.FeatureListener)

lejos.robotics.mapping.LineMap (implements lejos.robotics.mapping.RangeMap)

lejos.robotics.localization.MCLParticle

lejos.robotics.localization.MCLParticleSet

lejos.robotics.localization.MCLPoseProvider (implements lejos.robotics.navigation.MoveListener, lejos.robotics.localization.PoseProvider)

lejos.robotics.navigation.Move

lejos.robotics.navigation.Navigator (implements lejos.robotics.navigation.WaypointListener)

lejos.robotics.pathfinding.Node

lejos.robotics.pathfinding.GridNode

lejos.robotics.pathfinding.RandomSelfGeneratingNode

lejos.robotics.pathfinding.NodePathFinder (implements lejos.robotics.pathfinding.PathFinder)

lejos.robotics.mapping.OccupancyGridMap

lejos.robotics.localization.OdometryPoseProvider (implements lejos.robotics.navigation.MoveListener, lejos.robotics.localization.PoseProvider)

lejos.robotics.localization.CompassPoseProvider

Point

lejos.robotics.navigation.Waypoint

lejos.robotics.navigation.Pose

lejos.robotics.pathfinding.RandomPathFinder (implements lejos.robotics.pathfinding.PathFinder)

lejos.robotics.objectdetection.RangeFeature (implements lejos.robotics.objectdetection.Feature)

lejos.robotics.mapping.ShapefileLoader

lejos.robotics.pathfinding.ShortestPathFinder (implements lejos.robotics.pathfinding.PathFinder)

lejos.robotics.pathfinding.ShortestPathFinder.Node

lejos.robotics.mapping.SVGMapLoader

java.lang.Thread (implements java.lang.Runnable)

lejos.robotics.navigation.CompassPilot.Regulator

lejos.robotics.navigation.DifferentialPilot.Monitor

lejos.robotics.objectdetection.FeatureDetectorAdapter.MonitorThread

lejos.robotics.objectdetection.FusorDetector.NotifyThread

lejos.robotics.localization.MCLPoseProvider.Updater

lejos.robotics.navigation.Navigator.Nav

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

lejos.robotics.navigation.DestinationUnreachableException

Interface Hierarchy

lejos.robotics.localization.BeaconLocator

lejos.robotics.objectdetection.Feature

lejos.robotics.objectdetection.FeatureDetector

lejos.robotics.objectdetection.FeatureListener

lejos.robotics.navigation.MoveListener

lejos.robotics.navigation.MoveProvider

lejos.robotics.navigation.MoveController

lejos.robotics.navigation.ArcMoveController

lejos.robotics.navigation.ArcRotateMoveController (also extends lejos.robotics.navigation.RotateMoveController)

lejos.robotics.navigation.LineFollowingMoveController

lejos.robotics.navigation.RotateMoveController

lejos.robotics.navigation.ArcRotateMoveController (also extends lejos.robotics.navigation.ArcMoveController)

lejos.robotics.navigation.LineFollowingMoveController

lejos.robotics.navigation.NavigationListener

lejos.robotics.pathfinding.NavigationMesh

lejos.robotics.pathfinding.PathFinder

lejos.robotics.localization.PoseProvider

lejos.robotics.mapping.RangeMap

lejos.robotics.pathfinding.SearchAlgorithm

lejos.robotics.navigation.WaypointListener

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

lejos.robotics.navigation.Move.MoveType

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

JavaScript is disabled on your browser.


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.contrib.postgres.fields
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('origin_app', models.CharField(help_text=b'Record on which app the user signed up', max_length=255, choices=[(b'Pollination', b'Pollination'), (b'Beekeepers', b'Beekeepers')])),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
        )
    ]


text:
package org.apache.commons.beanutils;

public interface Child {

    public String getName();
}


text:
class SkBitmap;
struct ANativeWindow;

namespace cc {
class Layer;
class LayerTreeHost;
class OnscreenDisplayClient;
class SurfaceIdAllocator;
class SurfaceManager;
}

namespace content {
class CompositorClient;

// -----------------------------------------------------------------------------
// Browser-side compositor that manages a tree of content and UI layers.
// -----------------------------------------------------------------------------
class CONTENT_EXPORT CompositorImpl
    : public Compositor,
      public cc::LayerTreeHostClient,
      public cc::LayerTreeHostSingleThreadClient,
      public ui::UIResourceProvider,
      public ui::WindowAndroidCompositor {
 public:
  class VSyncObserver {
   public:
    virtual void OnVSync(base::TimeTicks timebase,
                         base::TimeDelta interval) = 0;
  };

  CompositorImpl(CompositorClient* client, gfx::NativeWindow root_window);
  ~CompositorImpl() override;

  static bool IsInitialized();

  static cc::SurfaceManager* GetSurfaceManager();
  static scoped_ptr<cc::SurfaceIdAllocator> CreateSurfaceIdAllocator();

  void PopulateGpuCapabilities(gpu::Capabilities gpu_capabilities);

  void AddObserver(VSyncObserver* observer);
  void RemoveObserver(VSyncObserver* observer);
  void OnNeedsBeginFramesChange(bool needs_begin_frames);

  // ui::ResourceProvider implementation.
  cc::UIResourceId CreateUIResource(cc::UIResourceClient* client) override;
  void DeleteUIResource(cc::UIResourceId resource_id) override;
  bool SupportsETC1NonPowerOfTwo() const override;

 private:
  // Compositor implementation.
  void SetRootLayer(scoped_refptr<cc::Layer> root) override;
  void SetSurface(jobject surface) override;
  void setDeviceScaleFactor(float factor) override;
  void SetWindowBounds(const gfx::Size& size) override;
  void SetHasTransparentBackground(bool flag) override;
  void SetNeedsComposite() override;
  ui::UIResourceProvider& GetUIResourceProvider() override;
  ui::ResourceManager& GetResourceManager() override;

  // LayerTreeHostClient implementation.
  void WillBeginMainFrame() override {}
  void DidBeginMainFrame() override {}
  void BeginMainFrame(const cc::BeginFrameArgs& args) override {}
  void BeginMainFrameNotExpectedSoon() override {}
  void UpdateLayerTreeHost() override;
  void ApplyViewportDeltas(const gfx::Vector2dF& inner_delta,
                           const gfx::Vector2dF& outer_delta,
                           const gfx::Vector2dF& elastic_overscroll_delta,
                           float page_scale,
                           float top_controls_delta) override {}
  void RequestNewOutputSurface() override;
  void DidInitializeOutputSurface() override;
  void DidFailToInitializeOutputSurface() override;
  void WillCommit() override {}
  void DidCommit() override;
  void DidCommitAndDrawFrame() override {}
  void DidCompleteSwapBuffers() override;
  void DidCompletePageScaleAnimation() override {}
  void RecordFrameTimingEvents(
      scoped_ptr<cc::FrameTimingTracker::CompositeTimingSet> composite_events,
      scoped_ptr<cc::FrameTimingTracker::MainFrameTimingSet> main_frame_events)
      override {}

  // LayerTreeHostSingleThreadClient implementation.
  void DidPostSwapBuffers() override;
  void DidAbortSwapBuffers() override;

  // WindowAndroidCompositor implementation.
  void AttachLayerForReadback(scoped_refptr<cc::Layer> layer) override;
  void RequestCopyOfOutputOnRootLayer(
      scoped_ptr<cc::CopyOutputRequest> request) override;
  void OnVSync(base::TimeTicks frame_time,
               base::TimeDelta vsync_period) override;
  void SetNeedsAnimate() override;
  void SetVisible(bool visible);
  void CreateOutputSurface();
  void CreateLayerTreeHost();

  void OnGpuChannelEstablished();
  void OnGpuChannelTimeout();

  // root_layer_ is the persistent internal root layer, while subroot_layer_
  // is the one attached by the compositor client.
  scoped_refptr<cc::Layer> root_layer_;
  scoped_refptr<cc::Layer> subroot_layer_;

  // Destruction order matters here:
  base::ObserverList<VSyncObserver, true> observer_list_;
  scoped_ptr<cc::LayerTreeHost> host_;
  ui::ResourceManagerImpl resource_manager_;

  scoped_ptr<cc::OnscreenDisplayClient> display_client_;
  scoped_ptr<cc::SurfaceIdAllocator> surface_id_allocator_;

  gfx::Size size_;
  bool has_transparent_background_;
  float device_scale_factor_;

  ANativeWindow* window_;
  int surface_id_;

  CompositorClient* client_;

  gfx::NativeWindow root_window_;

  // Whether we need to update animations on the next composite.
  bool needs_animate_;

  // The number of SwapBuffer calls that have not returned and ACK'd from
  // the GPU thread.
  unsigned int pending_swapbuffers_;

  size_t num_successive_context_creation_failures_;

  base::OneShotTimer establish_gpu_channel_timeout_;

  // Whether there is an OutputSurface request pending from the current
  // |host_|. Becomes |true| if RequestNewOutputSurface is called, and |false|
  // if |host_| is deleted or we succeed in creating *and* initializing an
  // OutputSurface (which is essentially the contract with cc).
  bool output_surface_request_pending_;

  gpu::Capabilities gpu_capabilities_;
  bool needs_begin_frames_;
  base::WeakPtrFactory<CompositorImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(CompositorImpl);
};

} // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_COMPOSITOR_IMPL_ANDROID_H_


text:
using System;
using System.Windows;

namespace Rolodex.Silverlight.Core
{
  public static class ErrorHandler
  {
    public static void HandleException(Exception ex)
    {
      MessageBox.Show(string.Format("Error has occurred.{0}{1}", Environment.NewLine, ex.ToString()));
    }
  }
}


text:
<?php

if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );

/**
 * Weixin Class
 * 微信公众平台(因为要交钱给TX,所以不做了)
 *
 * @package LookingGlassSAE
 * @subpackage Controllers
 * @category Controller
 * @author WDLTH
 * @link http://www.wdlth.com/
 */
class Weixin extends CI_Controller {
	function __construct() {
		parent::__construct ();
	}
	public function index() {
		$this->load->library("Weixinlib");
		$get = $this->input->get(NULL, TRUE);

		if (!isset($get) && $get != "") {
			$this->weixinlib->responseMsg();
		}else{
			$this->weixinlib->valid($get);
		}
	}
}


text:
using Meru.Commands.Objects;
using System;
using System.Collections.Generic;
using System.Text;

namespace Meru.Commands.Attributes
{
    public class MultiCommandAttribute : CommandAttribute
    {
		public MultiCommandAttribute()
		{
			Entity = new MultiCommand(Entity);
		}
	}
}


text:
package at.fwd.swagger.spring.demo.user;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import io.swagger.client.ApiException;
import io.swagger.client.api.UsercrudApi;
import io.swagger.client.model.ShowcaseDatatypePrimitives;
import io.swagger.client.model.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

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

public class UserApi_get_Test extends AbstractTestCase {
	/**
	 * Logger for this class
	 */
	private static final Logger log = Logger.getLogger(UserApi_get_Test.class.getName());

	UsercrudApi api;

	@Before
	public void setup() {
		api = new UsercrudApi();
		api.setBasePath("http://localhost:8080/");

	}

	@Test
	public void testSuccess() throws ParseException {

		try {

			User user = api.userGet(new Long(1));
			assertNotNull(user);
			System.out.println ("response: " + user.toString());

			assertEquals("Test", user.getName());

			// TODO Swagger-Springfox (develop-2.0 + 2.1.2-M2 + 2.1.2-M1) with Swagger-1.2: Enum seems not yet supported (https://github.com/springfox/springfox/issues/668)
			//assertEquals(User.StateEnum.ACTIVE, user.getState());

			assertEquals(2, user.getCategories().size());
			assertEquals("Category 1", user.getCategories().get(0).getName());
			assertEquals("Category 2", user.getCategories().get(1).getName());

			assertEquals(1, user.getLocations().size());
			assertEquals(Double.valueOf(-122.40406), user.getLocations().get(0).getLongitude());
			assertEquals(Double.valueOf(37.78199), user.getLocations().get(0).getLatitude());

			// Primitives
			ShowcaseDatatypePrimitives primitives = user.getPrimitives();
			assertEquals(Byte.valueOf(Byte.MAX_VALUE).toString(), primitives.getSingleByte());
			assertEquals(Integer.valueOf((int)Short.MAX_VALUE), primitives.getTinyNumber());
			assertEquals(Integer.valueOf(Integer.MAX_VALUE), primitives.getCounter());
			assertEquals(Long.valueOf(Long.MAX_VALUE), primitives.getId());

			// TODO Swagger-Springfox-1.0.2: primitive type float not working yet here
			// TODO: assertEquals(Float.MAX_VALUE, primitives.getBudgetFloat());

			assertEquals(Double.valueOf(Double.MAX_VALUE), primitives.getBudget());
			assertEquals('\uffff', (char)primitives.getSingleCharacter().charAt(0));
			assertEquals(Boolean.FALSE, primitives.getDeleted());

			// Math
			assertEquals(Long.MAX_VALUE, user.getMath().getBigInteger().longValue());
			assertEquals(Double.valueOf(Double.MAX_VALUE), Double.valueOf(user.getMath().getBigDecimal().doubleValue()));

			// Date
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			assertEquals(format.parse("2015-04-12 16:47:12.123"), user.getDate().getDate());

			Date date = format.parse("2015-04-12 16:47:12.123");
			assertEquals(Long.valueOf(date.getTime()), user.getDate().getCalendar());

		} catch (ApiException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}

	}

	@Test
	public void testNotFound() {

		try {
			api.userGet(new Long(3));
			fail("should fail");

		} catch (ApiException e) {
			assertEquals(404, e.getCode());

			log.info("message: " + e.getMessage());
			// TODO Swagger-Springfox: Currently the message cannot be overridden when throwing an exception
			assertTrue(e.getMessage().indexOf("\"status\":404")>0);
			assertTrue(e.getMessage().indexOf("\"message\":\"Object not found\"")>0);

		}

	}

}


text:
<?php

namespace Propel\Tests\Generator\Behavior\Sortable;

use Propel\Tests\Bookstore\Behavior\SortableTable11Query;
use Propel\Tests\Bookstore\Behavior\Map\SortableTable11TableMap;
use Propel\Tests\Bookstore\Behavior\SortableTable11 as Table11;

/**
 * Tests for SortableBehavior class
 *
 * @author Massimiliano Arione
 */
class SortableBehaviorObjectBuilderModifierTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->populateTable11();
    }

    public function testPreInsert()
    {
         SortableTable11TableMap::doDeleteAll();
        $t1 = new Table11();
        $t1->save();
        $this->assertEquals($t1->getRank(), 1, 'Sortable inserts new line in first position if no row present');
        $t2 = new Table11();
        $t2->setTitle('row2');
        $t2->save();
        $this->assertEquals($t2->getRank(), 2, 'Sortable inserts new line in last position');
    }

    public function testPreDelete()
    {
        $max = SortableTable11Query::create()->getMaxRank();
        $t3 = SortableTable11Query::retrieveByRank(3);
        $t3->delete();
        $this->assertEquals($max - 1, SortableTable11Query::create()->getMaxRank(), 'Sortable rearrange subsequent rows on delete');
        $t4 = SortableTable11Query::create()->filterByTitle('row4')->findOne();
        $this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete');
    }

    public function testIsFirst()
    {
        $first = SortableTable11Query::retrieveByRank(1);
        $middle = SortableTable11Query::retrieveByRank(2);
        $last = SortableTable11Query::retrieveByRank(4);
        $this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank');
        $this->assertFalse($middle->isFirst(), 'isFirst() returns false for a middle rank');
        $this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank');
    }

    public function testIsLast()
    {
        $first = SortableTable11Query::retrieveByRank(1);
        $middle = SortableTable11Query::retrieveByRank(2);
        $last = SortableTable11Query::retrieveByRank(4);
        $this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank');
        $this->assertFalse($middle->isLast(), 'isLast() returns false for a middle rank');
        $this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank');
    }

    public function testGetNext()
    {
        $t = SortableTable11Query::retrieveByRank(3);
        $this->assertEquals(4, $t->getNext()->getRank(), 'getNext() returns the next object in rank');

        $t = SortableTable11Query::retrieveByRank(4);
        $this->assertNull($t->getNext(), 'getNext() returns null for the last object');
    }

    public function testGetPrevious()
    {
        $t = SortableTable11Query::retrieveByRank(3);
        $this->assertEquals(2, $t->getPrevious()->getRank(), 'getPrevious() returns the previous object in rank');

        $t = SortableTable11Query::retrieveByRank(1);
        $this->assertNull($t->getPrevious(), 'getPrevious() returns null for the first object');
    }

    public function testInsertAtRank()
    {
        $t = new Table11();
        $t->setTitle('new');
        $t->insertAtRank(2);
        $this->assertEquals(2, $t->getRank(), 'insertAtRank() sets the position');
        $this->assertTrue($t->isNew(), 'insertAtRank() doesn\'t save the object');
        $t->save();
        $expected = array(1 => 'row1', 2 => 'new', 3 => 'row2', 4 => 'row3', 5 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() shifts the entire suite');
    }

    public function testInsertAtMaxRankPlusOne()
    {
        $t = new Table11();
        $t->setTitle('new');
        $t->insertAtRank(5);
        $this->assertEquals(5, $t->getRank(), 'insertAtRank() sets the position');
        $t->save();
        $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new');
        $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() can insert an object at the end of the list');
    }

    /**
     * @expectedException \Propel\Runtime\Exception\PropelException
     */
    public function testInsertAtNegativeRank()
    {
        $t = new Table11();
        $t->insertAtRank(0);
    }

    /**
     * @expectedException \Propel\Runtime\Exception\PropelException
     */
    public function testInsertAtOverMaxRank()
    {
        $t = new Table11();
        $t->insertAtRank(6);
    }

    public function testInsertAtBottom()
    {
        $t = new Table11();
        $t->setTitle('new');
        $t->insertAtBottom();
        $this->assertEquals(5, $t->getRank(), 'insertAtBottom() sets the position to the last');
        $this->assertTrue($t->isNew(), 'insertAtBottom() doesn\'t save the object');
        $t->save();
        $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new');
        $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtBottom() does not shift the entire suite');
    }

    public function testInsertAtTop()
    {
        $t = new Table11();
        $t->setTitle('new');
        $t->insertAtTop();
        $this->assertEquals(1, $t->getRank(), 'insertAtTop() sets the position to 1');
        $this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object');
        $t->save();
        $expected = array(1 => 'new', 2 => 'row1', 3 => 'row2', 4 => 'row3', 5 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'insertAtTop() shifts the entire suite');
    }

    public function testMoveToRank()
    {
        $t2 = SortableTable11Query::retrieveByRank(2);
        $t2->moveToRank(3);
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move up');
        $t2->moveToRank(1);
        $expected = array(1 => 'row2', 2 => 'row1', 3 => 'row3', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the first rank');
        $t2->moveToRank(4);
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the last rank');
        $t2->moveToRank(2);
        $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move down');
    }

    /**
     * @expectedException \Propel\Runtime\Exception\PropelException
     */
    public function testMoveToNewObject()
    {
        $t = new Table11();
        $t->moveToRank(2);
    }

    /**
     * @expectedException \Propel\Runtime\Exception\PropelException
     */
    public function testMoveToNegativeRank()
    {
        $t = SortableTable11Query::retrieveByRank(2);
        $t->moveToRank(0);
    }

    /**
     * @expectedException \Propel\Runtime\Exception\PropelException
     */
    public function testMoveToOverMaxRank()
    {
        $t = SortableTable11Query::retrieveByRank(2);
        $t->moveToRank(5);
    }

    public function testSwapWith()
    {
        $t2 = SortableTable11Query::retrieveByRank(2);
        $t4 = SortableTable11Query::retrieveByRank(4);
        $t2->swapWith($t4);
        $expected = array(1 => 'row1', 2 => 'row4', 3 => 'row3', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'swapWith() swaps ranks of the two objects and leaves the other ranks unchanged');
    }

    public function testMoveUp()
    {
        $t3 = SortableTable11Query::retrieveByRank(3);
        $res = $t3->moveUp();
        $this->assertEquals($t3, $res, 'moveUp() returns the current object');
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank');
        $t3->moveUp();
        $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank');
        $res = $t3->moveUp();
        $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() changes nothing when called on the object at the top');
    }

    public function testMoveDown()
    {
        $t2 = SortableTable11Query::retrieveByRank(2);
        $res = $t2->moveDown();
        $this->assertEquals($t2, $res, 'moveDown() returns the current object');
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank');
        $t2->moveDown();
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank');
        $res = $t2->moveDown();
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() changes nothing when called on the object at the bottom');
    }

    public function testMoveToTop()
    {
        $t3 = SortableTable11Query::retrieveByRank(3);
        $res = $t3->moveToTop();
        $this->assertEquals($t3, $res, 'moveToTop() returns the current oobject');
        $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() moves to the top');
        $res = $t3->moveToTop();
        $expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() changes nothing when called on the top node');
    }

    public function testMoveToBottom()
    {
        $t2 = SortableTable11Query::retrieveByRank(2);
        $res = $t2->moveToBottom();
        $this->assertEquals($t2, $res, 'moveToBottom() returns the current object');
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() moves to the bottom');
        $res = $t2->moveToBottom();
        $this->assertFalse($res, 'moveToBottom() returns false when called on the bottom node');
        $expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
        $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() changes nothing when called on the bottom node');
    }

    public function testRemoveFromList()
    {
        $t2 = SortableTable11Query::retrieveByRank(2);
        $res = $t2->removeFromList();
        $this->assertTrue($res instanceof Table11, 'removeFromList() returns the current object');
        $this->assertNull($res->getRank(), 'removeFromList() resets the object\'s rank');
         SortableTable11TableMap::clearInstancePool();
        $expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() does not change the list until the object is saved');
        $t2->save();
         SortableTable11TableMap::clearInstancePool();
        $expected = array(null => 'row2', 1 => 'row1', 2 => 'row3', 3 => 'row4');
        $this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() changes the list once the object is saved');
    }
}


text:
require 'spec_helper'

require 'overpass'

describe 'hierarchy of', vcr: true do
  it 'hamburg' do
    json = Overpass.get_geojson(53.5642280, 9.9830910)
    expect(JSON.dump(json).size).to eq 3480761
    expect(json['type']).to eq 'FeatureCollection'
    expect(json['features'].size).to eq 5
    expect(json['features'].first['id']).to eq 51477
    expect(json['features'].last['id']).to eq 179545
    expect(json['features'].first['properties']['translations'].size).to eq 252
  end

  it 'puerto de la cruz' do
    json = Overpass.get_geojson(28.41, -16.54)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 4
  end

  it 'dublin' do
    json = Overpass.get_geojson(53.397187, -6.426769)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 6
  end

  it 'dublin without historic' do
    json = Overpass.get_geojson(53.338893, -6.239656)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].map { |v| v['properties']['name'] }).to eq(["Ireland", "Leinster", "County Dublin", "Dublin", "South Dock ED"])
    expect(json['features'].size).to eq 5
  end

  it 'seychelles' do
    json = Overpass.get_geojson(-4.6261077, 55.446254)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 2
  end

  it 'barcelona' do
    json = Overpass.get_geojson(41.381003,2.146518)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 7
  end

  it 'florianopolis' do
    json = Overpass.get_geojson(-27.677571,-48.503033)
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 7
  end

  it 'booklyn' do
    json = Overpass.get_geojson(40.683038, -73.926095)
    expect(json['features'].map { |v| v['properties']['name'] }).to eq(["United States of America", "New York", "New York City", "Kings County"])
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 4
  end

  it 'palermo' do
    json = Overpass.get_geojson(38.112195, 13.366067)
    expect(json['features'].map { |v| v['properties']['name'] }).to eq(["Italia", "Sicilia", "Palermo", "Palermo", "I Circoscrizione"])
    expect('FeatureCollection').to eq json['type']
    expect(json['features'].size).to eq 5
  end
end


text:
ACCEPTED

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

#### Published in
in Niemelä, Kinnunen, Lindgren, Manninen, Miettinen, Penttilä & Turunen, Karstenia 41(1): 9 (2001)

#### Original name
Oligoporus folliculocystidiatus Kotl. & Vampola, 1993

### Remarks
null


text:
extern crate env_logger;
extern crate rustc_serialize;
extern crate bincode;
extern crate term;
extern crate lea_compiler as compiler;
extern crate lea_parser as parser;
extern crate lea;

use parser::span::DummyTerm;
use compiler::{CompileConfig, FnData};

use rustc_serialize::json;
use bincode::SizeLimit;
use bincode::rustc_serialize::EncodingError;

use std::io::{self, stdin, stderr, stdout, Read, Write};
use std::fs::File;
use std::path::Path;
use std::str::FromStr;

#[derive(Debug)]
#[allow(non_camel_case_types)]
enum Encoding {
    Json,
    Bin,
    Debug,
}

impl Encoding {
    pub fn encode<W: Write>(&self, fndata: &FnData, wr: &mut W)
    -> io::Result<()> {
        use Encoding::*;
        match *self {
            Json => {
                match json::encode(fndata) {
                    Ok(s) => Ok(try!(write!(wr, "{}", &s))),
                    Err(_) => Err(io::Error::new(io::ErrorKind::Other, "json encoding error")),
                }
            }
            Bin => {
                match bincode::rustc_serialize::encode_into(fndata, wr, SizeLimit::Infinite) {
                    Ok(_) => Ok(()),
                    Err(EncodingError::IoError(e)) => Err(e),
                    Err(EncodingError::SizeLimit) => Err(io::Error::new(io::ErrorKind::Other, "size limit reached")),
                }
            }
            Debug => {
                write!(wr, "{:#?}\n", fndata)
            }
        }
    }
}

impl FromStr for Encoding {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use Encoding::*;
        match s {
            "json" => Ok(Json),
            "bin" => Ok(Bin),
            "debug" => Ok(Debug),
            _ => Err(()),
        }
    }
}

/// Opens a terminal that writes to stderr. If stderr couldn't be opened as a terminal, creates a
/// `DummyTerm` that writes to stderr instead.
fn stderr_term() -> Box<term::StderrTerminal> {
    term::stderr().unwrap_or_else(|| Box::new(DummyTerm(io::stderr())))
}

/// Compiles a piece of code. Prints all errors / warnings to stderr, using color if stderr is a
/// terminal.
fn compile(code: &str, filename: &str) -> io::Result<Option<FnData>> {
    let mut fmt_target = stderr_term();
    let fmt_target = &mut *fmt_target;

    match compiler::compile_str(code, filename, &CompileConfig::default()) {
        Err(e) => {
            try!(e.format(code, filename, fmt_target));
            Ok(None)
        },
        Ok(output) => {
            let warns = output.warns;
            if !warns.is_empty() {
                for w in warns {
                    try!(w.format(code, filename, fmt_target));
                }
            }

            Ok(Some(output.mainproto))
        }
    }
}

fn read_file(filename: &str) -> io::Result<String> {
    let mut s = String::new();
    let mut file = try!(File::open(&Path::new(filename)));
    try!(file.read_to_string(&mut s));

    Ok(s)
}

fn main() {
    env_logger::init().unwrap();

    let matches = clap_app!(leac =>
        (version: lea::version_str())
        (about: "The Lea byte code compiler")
        (@arg FILE: +required "The file to compile")
        (@arg out: -o --out +takes_value "Write output to <out> (`-` to write to stdout).")
        (@arg enc: -e --encoding +takes_value "The encoding to use for writing the compiled code.")
        (after_help: "By default, leac will write the compiled code to stdout. If stdout is a \
            terminal, leac will print it using the `debug` encoding. Otherwise, leac will encode \
            the compilation result in a binary form (`bin` encoding).\n")
    ).get_matches();

    let encoding = match matches.value_of("enc") {
        None => Encoding::Debug,
        Some(_) => value_t_or_exit!(matches.value_of("enc"), Encoding),
    };

    // Read input
    let file = matches.value_of("FILE").unwrap();
    let mut code = String::new();
    let source_name;
    if file == "-" {
        stdin().read_to_string(&mut code).unwrap();
        source_name = "<stdin>";
    } else {
        source_name = file;
        code = match read_file(&source_name) {
            Ok(content) => content,
            Err(e) => {
                writeln!(stderr(), "{}", e).unwrap();
                return;
            }
        }
    }

    // Open output
    let mut writer: Box<Write>;
    match matches.value_of("out") {
        None | Some("-") => {
            writer = Box::new(stdout()) as Box<Write>;
        }
        Some(s) => {
            let f = match File::create(&Path::new(s)) {
                Ok(f) => f,
                Err(e) => {
                    writeln!(stderr(), "{}", e).unwrap();
                    return;
                }
            };

            writer = Box::new(f) as Box<Write>;
        }
    }

    match compile(&code, &source_name).unwrap() {
        Some(fndata) => {
            // serialize to `out`, except if `out` is a terminal and we defaulted to `-` (TODO)
            if let Err(e) = encoding.encode(&fndata, &mut writer) {
                writeln!(stderr(), "{}", e).unwrap();
                return;
            }
        }
        None => {}
    }
}


text:
/**
 * Created by claud on 24/02/2018.
 */
sisKitnetApp.controller('ContaController', function ($scope, $document, $location, $timeout, SiskitnetService) {

    $scope.redefinirSenha = function(){
        var pid = $location.search();
        $scope.formulario.token = pid.pid;
        SiskitnetService.redefinir($scope.formulario);
    };

    $scope.registrarUsuario = function() {
        SiskitnetService.registrar($scope.formulario);
    };

    $scope.verificarUsuario = function() {
        SiskitnetService.verificarCPF($scope.formulario);
    };

    $scope.atualizar = function(){
        SiskitnetService.atualizarUsuario($scope.usuario);
    };

    $scope.alteraSenha = function(){
        SiskitnetService.atualizarSenha($scope.usuario);

    };
});


text:
package com.jworx.labs.atmospherepush;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventListener;

import com.jworx.logfacade.Log;
import com.jworx.logfacade.LogFactory;

public class EventLogger implements AtmosphereResourceEventListener {
    private Log log = LogFactory.getLog(EventLogger.class);

    @Override
    public void onSuspend(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) {
        log.debug("onSuspend [remoteAddr=%s, remotePort=%s]", event.getResource().getRequest().getRemoteAddr(), event
                .getResource().getRequest().getRemotePort());
    }

    @Override
    public void onResume(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) {
        log.debug("onResume [remoteAddr=%s, remotePort=%s]", event.getResource().getRequest().getRemoteAddr(), event
                .getResource().getRequest().getRemotePort());
    }

    @Override
    public void onDisconnect(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) {
        log.debug("onDisconnect [remoteAddr=%s, remotePort=%s]", event.getResource().getRequest().getRemoteAddr(),
            event.getResource().getRequest().getRemotePort());
    }

    @Override
    public void onBroadcast(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) {
        log.debug("onBroadcast[remoteAddr=%s, remotePort=%s]", event.getResource().getRequest().getRemoteAddr(), event
                .getResource().getRequest().getRemotePort());
    }

    @Override
    public void onThrowable(AtmosphereResourceEvent<HttpServletRequest, HttpServletResponse> event) {
        log.debug("onThrowable [remoteAddr=%s, remotePort=%s]", event.getResource().getRequest().getRemoteAddr(), event
                .getResource().getRequest().getRemotePort());
    }
}


text:
from __future__ import unicode_literals

import getpass
import os
import json
import subprocess
import threading

from airflow.utils.log.logging_mixin import LoggingMixin

from airflow import configuration as conf
from tempfile import mkstemp

PYTHONPATH_VAR = 'PYTHONPATH'

class BaseTaskRunner(LoggingMixin):
    """
    Runs Airflow task instances by invoking the `airflow run` command with raw
    mode enabled in a subprocess.
    """

    def __init__(self, local_task_job):
        """
        :param local_task_job: The local task job associated with running the
        associated task instance.
        :type local_task_job: airflow.jobs.LocalTaskJob
        """
        # Pass task instance context into log handlers to setup the logger.
        super(BaseTaskRunner, self).__init__(local_task_job.task_instance)
        self._task_instance = local_task_job.task_instance

        popen_prepend = []
        cfg_path = None
        if self._task_instance.run_as_user:
            self.run_as_user = self._task_instance.run_as_user
        else:
            try:
                self.run_as_user = conf.get('core', 'default_impersonation')
            except conf.AirflowConfigException:
                self.run_as_user = None

        # Add sudo commands to change user if we need to. Needed to handle SubDagOperator
        # case using a SequentialExecutor.
        if self.run_as_user and (self.run_as_user != getpass.getuser()):
            self.log.debug("Planning to run as the %s user", self.run_as_user)
            cfg_dict = conf.as_dict(display_sensitive=True)
            cfg_subset = {
                'core': cfg_dict.get('core', {}),
                'smtp': cfg_dict.get('smtp', {}),
                'scheduler': cfg_dict.get('scheduler', {}),
                'webserver': cfg_dict.get('webserver', {}),
                'hive': cfg_dict.get('hive', {}),  # we should probably generalized this
            }
            temp_fd, cfg_path = mkstemp()

            # Give ownership of file to user; only they can read and write
            subprocess.call(
                ['sudo', 'chown', self.run_as_user, cfg_path],
                close_fds=True
            )
            subprocess.call(
                ['sudo', 'chmod', '600', cfg_path],
                close_fds=True
            )

            with os.fdopen(temp_fd, 'w') as temp_file:
                json.dump(cfg_subset, temp_file)

            # propagate PYTHONPATH environment variable
            pythonpath_value = os.environ.get(PYTHONPATH_VAR, '')
            popen_prepend = ['sudo', '-H', '-u', self.run_as_user]

            if pythonpath_value:
                popen_prepend.append('{}={}'.format(PYTHONPATH_VAR, pythonpath_value))

        self._cfg_path = cfg_path
        self._command = popen_prepend + self._task_instance.command_as_list(
            raw=True,
            pickle_id=local_task_job.pickle_id,
            mark_success=local_task_job.mark_success,
            job_id=local_task_job.id,
            pool=local_task_job.pool,
            cfg_path=cfg_path,
        )
        self.process = None

    def _read_task_logs(self, stream):
        while True:
            line = stream.readline()
            if isinstance(line, bytes):
                line = line.decode('utf-8')
            if len(line) == 0:
                break
            self.log.info(u'Job {}: Subtask {} %s'.format(
                self._task_instance.job_id, self._task_instance.task_id),
                line.rstrip('\n'))

    def run_command(self, run_with, join_args=False):
        """
        Run the task command

        :param run_with: list of tokens to run the task command with
        E.g. ['bash', '-c']
        :type run_with: list
        :param join_args: whether to concatenate the list of command tokens
        E.g. ['airflow', 'run'] vs ['airflow run']
        :param join_args: bool
        :return: the process that was run
        :rtype: subprocess.Popen
        """
        cmd = [" ".join(self._command)] if join_args else self._command
        full_cmd = run_with + cmd
        self.log.info('Running: %s', full_cmd)
        proc = subprocess.Popen(
            full_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            close_fds=True,
        )

        # Start daemon thread to read subprocess logging output
        log_reader = threading.Thread(
            target=self._read_task_logs,
            args=(proc.stdout,),
        )
        log_reader.daemon = True
        log_reader.start()
        return proc

    def start(self):
        """
        Start running the task instance in a subprocess.
        """
        raise NotImplementedError()

    def return_code(self):
        """
        :return: The return code associated with running the task instance or
        None if the task is not yet done.
        :rtype int:
        """
        raise NotImplementedError()

    def terminate(self):
        """
        Kill the running task instance.
        """
        raise NotImplementedError()

    def on_finish(self):
        """
        A callback that should be called when this is done running.
        """
        if self._cfg_path and os.path.isfile(self._cfg_path):
            subprocess.call(['sudo', 'rm', self._cfg_path], close_fds=True)


text:
grep-for-papers
===============

Find references to research papers in source code.

Example: http://www.oilshell.org/grep-for-papers/llvm-7.0.1.src.wwz/

Clicking on the links reduces the manual work in finding references.


text:
%PARAMTYPE_INDIR   Called by PARAMTYPE.

% (c)2017, Cris Luengo.
% Based on original DIPimage code: (c)1999-2014, Delft University of Technology.
%
% 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.

function varargout = paramtype_indir(command,param,varargin)

switch command
   case 'control_create'
      fig = varargin{1};   % figure handle
      bh = uicontrol(fig,...
                     'Style','pushbutton',...
                     'String','Browse...',...
                     'Visible','off',...
                     'HorizontalAlignment','center',...
                     'BusyAction','cancel',...
                     'Interruptible','off');
      eh = uicontrol(fig,...
                     'Style','edit',...
                     'String',param.default,...
                     'Visible','off',...
                     'HorizontalAlignment','left',...
                     'BackgroundColor',[1,1,1]);
      set(bh,'Callback',{@do_browse,eh,param.description});
      varargout{1} = [eh,bh];
   case 'control_value'
      varargout{2} = get(varargin{1},'String');
      varargout{1} = varargout{2};
      varargout{2} = mat2str(varargout{2});
   case 'definition_test'
      varargout{1} = '';
      if ~ischar(param.default)
         varargout{1} = 'DEFAULT must be a string for indir';
      end
end

function do_browse(~,~,editbox,title)
   %tmp = getfile(mask,title);
   %tmp = putfile(mask,title);
tmp = getdir(title);
if ~isempty(tmp)
   set(editbox,'String',tmp);
end


text:
@interface OFPushWithReplaceLastSegue : UIStoryboardSegue
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/altspacevr-project-image-searcher-master.iml" filepath="$PROJECT_DIR$/altspacevr-project-image-searcher-master.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
import NativeObject from './NativeObject';

export default class DevTools extends NativeObject {

  get _nativeType() {
    return 'tabris.DevTools';
  }

  /** @override */
  _nativeCreate(param) {
    if (param !== true) {
      throw new Error('DevTools can not be created');
    }
    super._nativeCreate();
  }

  showUi() {
    return this._nativeCall('showUi');
  }

  hideUi() {
    this._nativeCall('hideUi');
  }

  isUiVisible() {
    return this._nativeCall('isUiVisible');
  }

  dispose() {
    throw new Error('Cannot dispose devTools object');
  }

}

export function create() {
  return new DevTools(true);
}


text:
/**
 * @file secure_message.h
 * @brief main Secure Session interface
 */

#ifndef _THEMIS_SECURE_MESSAGE_H_
#define _THEMIS_SECURE_MESSAGE_H_

#include <themis/themis.h>

#ifdef __cplusplus
extern "C"{
#endif

/**
 * @addtogroup THEMIS
 * @{
 * @defgroup THEMIS_SECURE_MESSAGE secure message
 * @brief Secure message is a lightweight service which can help to deliver some message or data to your peer in a secure manner.
 * @{
 */

/**
 * @brief generate RSA key pair
 * @param [out] private_key buffer for private key to store. May be set to NULL for private key length determination
 * @param [in, out] private_key_length length of private_key
 * @param [out] public_key buffer for public key to store. May be set to NULL for public key length determination
 * @param [in, out] public_key_length length of public key
 * @return THEMIS_SUCCESS on success or THEMIS_FAIL on failure
 * @note If private_key==NULL or public_key==NULL or private_key_length is not enought for private key storage or public_key_length is not enought for public key storage then THEMIS_BUFFER_TOO_SMALL will return and private_key_length and public_key_length will store lengths of buffers needed for private key and public key store respectively
 */
themis_status_t themis_gen_rsa_key_pair(uint8_t* private_key,
					size_t* private_key_length,
					uint8_t* public_key,
					size_t* public_key_length);

/**
 * @brief generate EC key pair
 * @param [out] private_key buffer for private key to store. May be set to NULL for private key length determination
 * @param [in, out] private_key_length length of private_key
 * @param [out] public_key buffer for public key to store. May be set to NULL for public key length determination
 * @param [in, out] public_key_length length of public key
 * @return THEMIS_SUCCESS on success or THEMIS_FAIL on failure
 * @note If private_key==NULL or public_key==NULL or private_key_length is not enought for private key storage or public_key_length is not enought for public key storage then THEMIS_BUFFER_TOO_SMALL will return and private_key_length and public_key_length will store lengths of buffers needed for private key and public key store respectively
 */
themis_status_t themis_gen_ec_key_pair(uint8_t* private_key,
				       size_t* private_key_length,
				       uint8_t* public_key,
				       size_t* public_key_length);

/**
 * @brief wrap message to secure message
 * @param [in] private_key private key
 * @param [in] pribate_key_length length of private_key
 * @param [in] public_key peer public key
 * @param [in] public_key_length length of public_key
 * @param [in] message message to wrap
 * @param [in] message_length length of message
 * @param [out] wrapped_message buffer for wrapped message store. May be set to NULL for wrapped message length determination
 * @param [in, out] wrapped_message_length length of wrapped_message
 * @return THEMIS_SUCCESS on success or THEMIS_FAIL on failure
 * @note If wrapped_message==NULL or wrapped_message_length is not enought for wrapped message storage then THEMIS_BUFFER_TOO_SMALL will return and wrapped_message_length will store length of buffer needed for wrapped message store
 */
themis_status_t themis_secure_message_wrap(const uint8_t* private_key,
					   const size_t private_key_length,
					   const uint8_t* public_key,
					   const size_t public_key_length,
					   const uint8_t* message,
					   const size_t message_length,
					   uint8_t* wrapped_message,
					   size_t* wrapped_message_length);

/**
 * @brief unwrap secure message to plain message
 * @param [in] private_key private key
 * @param [in] pribate_key_length length of private_key
 * @param [in] public_key peer public key
 * @param [in] public_key_length length of public_key
 * @param [in] wrapped_message wrapped message to unwrap
 * @param [in] wrapped_message_length length of wrapped_message
 * @param [out] message buffer for plain message store. May be set to NULL for plain message length determination
 * @param [in, out] message_length length of message
 * @return THEMIS_SUCCESS on success or THEMIS_FAIL on failure
 * @note If message==NULL or message_length is not enought for plain message storage then THEMIS_BUFFER_TOO_SMALL will return and message_length will store length of buffer needed for plain message store
 */
themis_status_t themis_secure_message_unwrap(const uint8_t* private_key,
					   const size_t private_key_length,
					   const uint8_t* public_key,
					   const size_t public_key_length,
					   const uint8_t* wrapped_message,
					   const size_t wrapped_message_length,
					   uint8_t* message,
					   size_t* message_length);
/** @} */
/** @} */

#ifdef __cplusplus
}
#endif

#endif /* _THEMIS_SECURE_MESSAGE_H_ */


text:
GRAD_COST=1 # For dataaccess only
EPOCH_LIMIT=0 # Not really used right now
TIME_LIMIT=100 # Not reall used right now

N_EPOCHS=150
BATCH_SIZE=200
NTHREAD=8
RLENGTH=10
SHOULD_SYNC=0
SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=0
HOG=0
CYC=1

cyc_movielens_hog_regularize_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_hog_regularize \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DHOG=1 -DCYC=0 -DMOD_REP_CYC=0 -DREGULARIZE=1
cyc_movielens_hog_regularize_run:
	@./movielens_hog_regularize

cyc_movielens_hog_regularize_crimp_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_hog_regularize \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DCRIMP=1 -DHOG=1 -DCYC=0 -DMOD_REP_CYC=0 -DREGULARIZE=1
cyc_movielens_hog_regularize_crimp_run:
	@./movielens_hog_regularize

cyc_movielens_cyc_regularize_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_cyc_regularize \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DHOG=0 -DCYC=1 -DMOD_REP_CYC=0 -DREGULARIZE=1
cyc_movielens_cyc_regularize_run:
	@./movielens_cyc_regularize

cyc_movielens_cyc_bcs_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_cyc_bcs \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DHOG=0 -DCYC=0 -DMOD_REP_CYC=1
cyc_movielens_cyc_bcs_run:
	@./movielens_cyc_bcs

cyc_movielens_hog_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_hog \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DHOG=1 -DCYC=0

cyc_movielens_hog_run:
	@./movielens_hog

cyc_movielens_cyc_compile:
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -o movielens_cyc \
	-DN_EPOCHS=$(N_EPOCHS) -DBATCH_SIZE=$(BATCH_SIZE) -DNTHREAD=$(NTHREAD) -DRLENGTH=$(RLENGTH) \
	-DSHOULD_SYNC=$(SHOULD_SYNC) -DSHOULD_PRINT_LOSS_TIME_EVERY_EPOCH=$(SHOULD_PRINT_LOSS_TIME_EVERY_EPOCH) -DHOG=0 -DCYC=1
cyc_movielens_cyc_run:
	@./movielens_cyc

cyc_movielens_completion_hog:
	rm -rf movielens_completion_hog
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -DHOG=1 -o movielens_completion_hog
	./movielens_completion_hog
cyc_movielens_completion_cyc:
	rm -rf movielens_completion_cyc
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -DCYC=1 -o movielens_completion_cyc
	./movielens_completion_cyc
cyc_movielens_completion_cyc_bcs:
	rm -rf movielens_completion_cyc_mod_rep
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -DMOD_REP_CYC=1 -o movielens_completion_cyc_mod_rep
	./movielens_completion_cyc_mod_rep
cyc_movielens_completion_cyc_regularize:
	rm -rf movielens_completion_cyc
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -DCYC=1 -DREGULARIZE=1 -o movielens_completion_cyc_regularize
	./movielens_completion_cyc_regularize

cyc_movielens_completion_hog_regularize:
	rm -rf movielens_completion_cyc
	g++ -Ofast -fopenmp -std=c++11 cyclades_movielens_completion.cpp -lnuma -lpthread -DHOG=1 -DREGULARIZE=1 -o movielens_completion_hog_regularize
	./movielens_completion_hog_regularize


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

package com.facebook.presto.cost;

import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.planner.plan.SampleNode;
import org.testng.annotations.Test;

import static com.facebook.presto.common.type.BigintType.BIGINT;

public class TestSampleStatsRule
        extends BaseStatsCalculatorTest
{
    @Test
    public void testSample()
    {
        tester().assertStatsFor(pb ->
                pb.sample(0.5, SampleNode.Type.BERNOULLI, pb.values(
                        pb.variable("i1", BIGINT), pb.variable("i2", BIGINT))))
                .withSourceStats(0, PlanNodeStatsEstimate.builder()
                        .setOutputRowCount(100)
                        .addVariableStatistics(new VariableReferenceExpression("i1", BIGINT), VariableStatsEstimate.builder()
                                .setLowValue(1)
                                .setHighValue(100)
                                .setDistinctValuesCount(5)
                                .setNullsFraction(0)
                                .build())
                        .addVariableStatistics(new VariableReferenceExpression("i2", BIGINT), VariableStatsEstimate.builder()
                                .setLowValue(1)
                                .setHighValue(20)
                                .setDistinctValuesCount(20)
                                .setNullsFraction(0.2)
                                .build())
                        .build())
                .check(check ->
                        check.outputRowsCount(50)
                                .variableStats(new VariableReferenceExpression("i1", BIGINT), assertion -> assertion
                                        .lowValue(1)
                                        .highValue(100)
                                        .distinctValuesCount(5)
                                        .nullsFraction(0))
                                .variableStats(new VariableReferenceExpression("i2", BIGINT), assertion -> assertion
                                        .lowValue(1)
                                        .highValue(20)
                                        .distinctValuesCount(20)
                                        .nullsFraction(0.2)));

        tester().assertStatsFor(pb ->
                pb.sample(0.2, SampleNode.Type.SYSTEM, pb.values(
                        pb.variable("i1", BIGINT), pb.variable("i2", BIGINT))))
                .withSourceStats(0, PlanNodeStatsEstimate.builder()
                        .setOutputRowCount(100)
                        .addVariableStatistics(new VariableReferenceExpression("i1", BIGINT), VariableStatsEstimate.builder()
                                .setLowValue(1)
                                .setHighValue(100)
                                .setDistinctValuesCount(5)
                                .setNullsFraction(0)
                                .build())
                        .addVariableStatistics(new VariableReferenceExpression("i2", BIGINT), VariableStatsEstimate.builder()
                                .setLowValue(1)
                                .setHighValue(20)
                                .setDistinctValuesCount(20)
                                .setNullsFraction(0)
                                .build())
                        .build())
                .check(check ->
                        check.outputRowsCount(20)
                                .variableStats(new VariableReferenceExpression("i1", BIGINT), assertion -> assertion
                                        .lowValue(1)
                                        .highValue(100)
                                        .distinctValuesCount(5)
                                        .nullsFraction(0))
                                .variableStats(new VariableReferenceExpression("i2", BIGINT), assertion -> assertion
                                        .lowValue(1)
                                        .highValue(20)
                                        .distinctValuesCount(20)
                                        .nullsFraction(0)));
    }
}