text:
package no.ntnu.httpmock.servlet

import com.orbekk.logging.Logger
import java.net.URI
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import no.ntnu.httpmock.http.RequestForwarder

object ProxyServlet {
  def create(baseUri: URI): ProxyServlet = {
    new ProxyServlet(RequestForwarder.create(), baseUri)
  }
}

class ProxyServlet(forwarder: RequestForwarder, baseUri: URI)
    extends HttpServlet with Logger {
  override def service(request: HttpServletRequest, response: HttpServletResponse) {
    forwarder.execute(baseUri, request, response)
    logger.info("Forwarded request " + request.getRequestURI)
  }
}


text:
from __future__ import absolute_import, division, print_function

from ..expr import (Expr, Symbol, Field, Arithmetic, Math,
                    Date, Time, DateTime, Millisecond, Microsecond, broadcast,
                    sin, cos, Map, UTCFromTimestamp, DateTimeTruncate, symbol,
                    USub, Not)
from ..expr import math as expr_math
from ..expr.expressions import valid_identifier
from ..dispatch import dispatch
from . import pydatetime
import datetime
import math
import toolz
import itertools

funcnames = ('func_%d' % i for i in itertools.count())

def parenthesize(s):
    if ' ' in s:
        return '(%s)' % s
    else:
        return s

def print_python(leaves, expr):
    """ Print expression to be evaluated in Python

    >>> from blaze.expr import ceil, sin

    >>> t = symbol('t', '{x: int, y: int, z: int, when: datetime}')
    >>> print_python([t], t.x + t.y)
    ('t[0] + t[1]', {})

    Supports mathematical and datetime access

    >>> print_python([t], sin(t.x) > ceil(t.y))  # doctest: +SKIP
    ('math.sin(t[0]) > math.ceil(t[1])', {'math':<module 'math'>})
    >>> print_python([t], t.when.day + 1)
    ('t[3].day + 1', {})

    Specify leaves of the expression to control level of printing

    >>> print_python([t.x, t.y], t.x + t.y)
    ('x + y', {})

    Returns
    -------

    s: string
       A evalable string
    scope: dict
       A namespace to add to be given to eval
    """
    if isinstance(expr, Expr) and any(expr.isidentical(lf) for lf in leaves):
        return valid_identifier(expr._name), {}
    return _print_python(expr, leaves=leaves)

@dispatch(object)
def _print_python(expr, leaves=None):
    return repr(expr), {}

@dispatch((datetime.datetime, datetime.date))
def _print_python(expr, leaves=None):
    return repr(expr), {'datetime': datetime}

@dispatch(Symbol)
def _print_python(expr, leaves=None):
    return valid_identifier(expr._name), {}

@dispatch(Field)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    index = expr._child.fields.index(expr._name)
    return '%s[%d]' % (parenthesize(child), index), scope

@dispatch(Arithmetic)
def _print_python(expr, leaves=None):
    lhs, left_scope = print_python(leaves, expr.lhs)
    rhs, right_scope = print_python(leaves, expr.rhs)
    return ('%s %s %s' % (parenthesize(lhs),
                         expr.symbol,
                         parenthesize(rhs)),
            toolz.merge(left_scope, right_scope))

@dispatch(USub)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return '%s%s' % (expr.symbol, parenthesize(child)), scope

@dispatch(Not)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return 'not %s' % parenthesize(child), scope

@dispatch(Math)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('math.%s(%s)' % (type(expr).__name__, child),
            toolz.merge(scope, {'math': math}))

@dispatch(expr_math.abs)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('abs(%s)' % child, scope)

@dispatch(Date)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('%s.date()' % parenthesize(child), scope)

@dispatch(Time)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('%s.time()' % parenthesize(child), scope)

@dispatch(Millisecond)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('%s.microsecond // 1000' % parenthesize(child), scope)

@dispatch(UTCFromTimestamp)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    return ('datetime.datetime.utcfromtimestamp(%s)' % parenthesize(child),
            toolz.merge({'datetime': datetime}, scope))

@dispatch(DateTime)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    attr = type(expr).__name__.lower()
    return ('%s.%s' % (parenthesize(child), attr), scope)

@dispatch(DateTimeTruncate)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    scope['truncate'] = pydatetime.truncate
    return ('truncate(%s, %s, "%s")' % (child, expr.measure, expr.unit),
            scope)

@dispatch(Map)
def _print_python(expr, leaves=None):
    child, scope = print_python(leaves, expr._child)
    funcname = next(funcnames)
    return ('%s(%s)' % (funcname, child),
            toolz.assoc(scope, funcname, expr.func))

@dispatch(Expr)
def _print_python(expr, leaves=None):
    raise NotImplementedError("Do not know how to write expressions of type %s"
            " to Python code" % type(expr).__name__)

def funcstr(leaves, expr):
    """ Lambda string for an expresion

    >>> t = symbol('t', '{x: int, y: int, z: int, when: datetime}')

    >>> funcstr([t], t.x + t.y)
    ('lambda t: t[0] + t[1]', {})

    >>> funcstr([t.x, t.y], t.x + t.y)
    ('lambda x, y: x + y', {})

    Also returns scope for libraries like math or datetime

    >>> funcstr([t.x, t.y], sin(t.x) + t.y)  # doctest: +SKIP
    ('lambda x, y: math.sin(x) + y', {'math': <module 'math'>})

    >>> from datetime import date
    >>> funcstr([t.x, t.y, t.when], t.when.date > date(2001, 12, 25)) #doctest: +SKIP
    ('lambda x, y, when: when.day > datetime.date(2001, 12, 25)', {'datetime': <module 'datetime'>})
    """
    result, scope = print_python(leaves, expr)

    leaf_names = [print_python([leaf], leaf)[0] for leaf in leaves]

    return 'lambda %s: %s' % (', '.join(leaf_names),
                              result), scope

def lambdify(leaves, expr):
    """ Lambda for an expresion

    >>> t = symbol('t', '{x: int, y: int, z: int, when: datetime}')
    >>> f = lambdify([t], t.x + t.y)
    >>> f((1, 10, 100, ''))
    11

    >>> f = lambdify([t.x, t.y, t.z, t.when], t.x + cos(t.y))
    >>> f(1, 0, 100, '')
    2.0
    """
    s, scope = funcstr(leaves, expr)
    return eval(s, scope)

redpajama_set_name: RedPajamaGithub


text:
package frdomain.ch4
package patterns

import scala.language.higherKinds

object Syntax {
  implicit class FunctorSyntax[F[_]: Functor, A](a: F[A]) {
    def map[B](f: A => B) = Functor[F].map(a)(f)
  }
}


text:
passwd -l root 2>&1 > /dev/null

yum install -y bzip2 gcc kernel-devel yum-utils 2>&1 > /dev/null
package-cleanup -y --oldkernels --count=1 2>&1 > /dev/null


text:
.table-fixedheader-body {
	height: 350px;
	overflow-y: auto;
}
.table-pag label{
	vertical-align: text-top;
}
.table-fixedheader-body tr td label{
	vertical-align: text-top;
}


text:
<?php

namespace Mapper;

use \ArrayObject;

/**
 * Class ClassFields
 * @package Mapper
 */
class ClassFields extends ArrayObject {

    /**
     * @param ClassField $classField
     * @return ClassFields
     */
    public function add(ClassField $classField): ClassFields {
        $this->append($classField);

        return $this;
    }

    /**
     * @param string $field
     * @return bool
     */
    public function hasClassField(string $field): bool {
        /** @var ClassField $classField */
        foreach ($this as $classField) {
            if ($classField->getName() === $field) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param string $field
     * @return ClassField|null
     */
    public function getClassField(string $field): ?ClassField {
        /** @var ClassField $classField */
        foreach ($this as $classField) {
            if ($classField->getName() === $field) {
                return $classField;
            }
        }

        return null;
    }

}


text:
import gensim
import os
from salib.munging.loaders import get_files_paths
from random import shuffle
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
import logging
import cPickle

class MySentences(object):
    def __init__(self, data_root, split='train'):
        self.split = split
        self.files_paths = []
        # if split == 'train':
        #     data_dir = os.path.join(data_root, 'train')
        #     unsup_dir = os.path.join(data_dir, 'unsup')
        #     unsup_paths = [os.path.join(unsup_dir, fn) for fn in os.listdir(unsup_dir)]
        #     self.files_paths.extend(unsup_paths)
        # elif split == 'test':
        #     data_dir = os.path.join(data_root, 'test')
        data_dir = os.path.join(data_root, split)
        pos_paths, neg_paths = get_files_paths(data_dir)
        self.files_paths.extend(pos_paths)
        self.files_paths.extend(neg_paths)
        # pos_paths, neg_paths = get_files_paths(test_dir)
        # self.files_paths.extend(pos_paths)
        # self.files_paths.extend(neg_paths)
        shuffle(self.files_paths)

    def __iter__(self):
        for file_path in self.files_paths:
            with open(file_path) as f:
                content = f.read()
            beautifully_souped = BeautifulSoup(content)
            text = beautifully_souped.get_text()
            text = text.lower()
            words = word_tokenize(text)
            words = [w for w in words if w not in stopwords.words("english")]
            # if self.split == 'test':
            label = file_path.split('/')[-2]
            yield words, label
            # else:
            #     yield words

class PicklesIterator(object):
    def __init__(self, pickles_root):
        self.files_paths = [fn for fn in os.listdir(pickles_root) if fn.endswith('.pkl')]
        shuffle(self.files_paths)

    def __iter__(self):
        for file_path in self.files_paths:
            with open(file_path, 'r') as f:
                words = cPickle.load(f)
            yield words

if __name__ == '__main__':
    imdb_path = '/home/hinton/Development/plazowicz/salib/data/aclImdb'
    early_stopping_path = '/home/hinton/Development/plazowicz/salib/data/imdb_v3_epoch_{0}.word2vec'
    final_path = '/home/hinton/Development/plazowicz/salib/data/imdb_v3_final.word2vec'

    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    sentences = MySentences(imdb_path)

    epochs = 50
    model = gensim.models.Word2Vec(workers=10, window=8, iter=1, size=300, min_count=10, min_alpha=0.025, alpha=0.025)
    model.build_vocab(sentences)

    alpha_dec = model.alpha / float(epochs + 1)

    for epoch in xrange(epochs):
        epoch_nb = epoch + 1
        print "Epoch: {0}".format(epoch_nb)
        model.train(sentences)
        model.alpha -= alpha_dec
        model.min_alpha = model.alpha
        if epoch_nb >= 10 and epoch_nb % 10 == 0:
            model.save(early_stopping_path.format(epoch_nb))

    model.save(final_path)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>YGameFrame: ygame.math.MathUtil类 参考</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

YGameFrame

首页

相关页面

包

类

文件

          <input type="text" id="MSearchField" value="搜索" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

类列表

类索引

类继承关系

类成员

 全部 类 命名空间 文件 函数 变量 页

ygame

math

MathUtil

静态 Public 属性 |
所有成员列表

ygame.math.MathUtil类 参考

静态 Public 属性

static final int 	PRECISION = 0x020000

static final double 	PI = Math.PI

static final double 	TWO_PI = PI * 2

static final double 	HALF_PI = PI * .5

static final double 	PRE_PI_DIV_180 = PI / 180

static final double 	PRE_180_DIV_PI = 180 / PI

类成员变量说明

          final double ygame.math.MathUtil.HALF_PI = PI * .5

static

          final double ygame.math.MathUtil.PI = Math.PI

static

          final double ygame.math.MathUtil.PRE_180_DIV_PI = 180 / PI

static

          final double ygame.math.MathUtil.PRE_PI_DIV_180 = PI / 180

static

          final int ygame.math.MathUtil.PRECISION = 0x020000

static

          final double ygame.math.MathUtil.TWO_PI = PI * 2

static

该类的文档由以下文件生成:

YGameFrame/src/ygame/math/MathUtil.java

<address class="footer">
生成于 2014年 十一月 11日 星期二 22:24:00 , 为 YGameFrame使用

 1.8.8
</address>


text:
<?php
/**
 * Created by PhpStorm.
 * User: dimaninc
 * Date: 24.06.2015
 * Time: 18:18
 */

namespace diCore\Entity\News;

use diCore\Admin\Submit;

/**
 * Class Model
 * Methods list for IDE
 *
 * @method string	getMenuTitle
 * @method string	getTitle
 * @method string	getShortContent
 * @method string	getContent
 * @method string	getHtmlTitle
 * @method string	getHtmlKeywords
 * @method string	getHtmlDescription
 * @method string	getPic
 * @method integer	getPicW
 * @method integer	getPicH
 * @method integer	getPicT
 * @method integer	getPicTnW
 * @method integer	getPicTnH
 * @method string	getDate
 * @method integer	getVisible
 * @method integer	getOrderNum
 * @method integer	getKarma
 * @method integer	getCommentsCount
 * @method string	getCommentsLastDate
 * @method integer	getCommentsEnabled
 *
 * @method bool hasMenuTitle
 * @method bool hasTitle
 * @method bool hasShortContent
 * @method bool hasContent
 * @method bool hasHtmlTitle
 * @method bool hasHtmlKeywords
 * @method bool hasHtmlDescription
 * @method bool hasPic
 * @method bool hasPicW
 * @method bool hasPicH
 * @method bool hasPicT
 * @method bool hasPicTnW
 * @method bool hasPicTnH
 * @method bool hasDate
 * @method bool hasVisible
 * @method bool hasOrderNum
 * @method bool hasKarma
 * @method bool hasCommentsCount
 * @method bool hasCommentsLastDate
 * @method bool hasCommentsEnabled
 *
 * @method $this setMenuTitle($value)
 * @method $this setTitle($value)
 * @method $this setShortContent($value)
 * @method $this setContent($value)
 * @method $this setHtmlTitle($value)
 * @method $this setHtmlKeywords($value)
 * @method $this setHtmlDescription($value)
 * @method $this setPic($value)
 * @method $this setPicW($value)
 * @method $this setPicH($value)
 * @method $this setPicT($value)
 * @method $this setPicTnW($value)
 * @method $this setPicTnH($value)
 * @method $this setDate($value)
 * @method $this setVisible($value)
 * @method $this setOrderNum($value)
 * @method $this setKarma($value)
 * @method $this setCommentsCount($value)
 * @method $this setCommentsLastDate($value)
 * @method $this setCommentsEnabled($value)
 */
class Model extends \diBasePrevNextModel
{
    const type = \diTypes::news;
    const table = 'news';
    protected $table = 'news';

    protected static $picStoreSettings = [
        'pic' => [
            [
                'type' => Submit::IMAGE_TYPE_MAIN,
                'resize' => \diImage::DI_THUMB_FIT,
            ],
            [
                'type' => Submit::IMAGE_TYPE_PREVIEW,
                'resize' => \diImage::DI_THUMB_CROP,
            ],
        ],
    ];

    // prev/next stuff
    protected $customOrderByOptions = [
        'reverse' => true,
    ];

    public function getSourceForSlug()
    {
        return mb_substr($this->getDate(), 0, 10) . ' ' . ($this->getSlugSource() ?: $this->getMenuTitle() ?: $this->getTitle());
    }

    public function getHref()
    {
        return $this->__getPrefixForHref() . '/' . \diCurrentCMS::ct('news') . '/' . $this->getSlug() . '/';
    }
}


text:
import React from 'react'
import Remarkable from 'remarkable'

import './editor.css'

class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    var mdString = '输入 *markdown 语法* 就能看到效果'
    this.state = {
      value: mdString,
    }
  }

  handleChange() {
    this.setState({
      // this.refs 是隐含的对象
      //  input 是 ref=input 的标签
      value: this.refs.input.value
    })
  }

  getRawMarkup() {
    var md = new Remarkable()
    return {
      __html: md.render(this.state.value)
    }
  }

  render() {
    // dangerouslySetInnerHTML 是 innerHTML 在 react 中 jsx 的写法
    // ref 是给 this.ref 用的
    return (

markdown 编辑器

原是文本

        <textarea
          onChange={this.handleChange}
          ref="input"
          defaultValue={this.state.value} />

结果预览

    )
  }
}

export default MarkdownEditor


text:
/**
 * Check if a selector should be whitelisted and / or replaced.
 */
export default function filterSelector({
  ruleSelector,
  ruleParentSelectors,
  filters,
}) {
  let newSelector = ``;

  filters.some((selectorFilter) => {
    const selector = selectorFilter.selector || selectorFilter;
    const replacementSelector = selectorFilter.replacement;
    const parentComparisonSelector = replacementSelector || selector;

    const selectorsAreEqual = selector === ruleSelector;
    const parentSelectorIsEqual = ruleParentSelectors.reduce((bool, ruleParentSelector) => {
      const result = parentComparisonSelector instanceof RegExp ?
        parentComparisonSelector.test(ruleParentSelector) :
        ruleParentSelector === parentComparisonSelector;

      return result;
    }, false);
    const selectorsMatch = selector instanceof RegExp && selector.test(ruleSelector);

    if (selectorsAreEqual || parentSelectorIsEqual || selectorsMatch) {
      newSelector = replacementSelector ?
        ruleSelector.replace(selector, replacementSelector) :
        ruleSelector;

      // Do not stop iterating over the selector filters if the parent selector was matched
      // because child selectors may get replaced in a further iteration.
      if (!parentSelectorIsEqual) {
        return true;
      }
    }
    return false;
  });

  return newSelector;
}


text:
package org.quelea.mobileremote;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.Html;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;

/*
 * Class to handle all types of dialogs
 * Created by Arvid on 2017-11-29.
 */

class Dialogs {
    MobileRemote context;
    private int urlNotFound = 0;

    void setContext(MobileRemote context) {
        this.context = context;
    }

    // Show dialog for info
    void infoDialog(final String message) {
        if (!context.isShown()) {
            context.setShown(true);
            final CustomDialog dialog = new CustomDialog(context, message, "", "", "", context.getResources().getString(R.string.ok_label), false, false);
            dialog.getNeutral().setText(context.getResources().getString(R.string.ok_label));
            dialog.getNeutral().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.getAlertDialog().dismiss();
                    context.setShown(false);
                    if (message.equals(context.getString(R.string.auto_connect_info))) {
                        context.startAutoConnect();
                    }
                }
            });
        }
    }

    // Show dialog telling user to enter URL
    void enterURLDialog(String message, String prefill) {
        urlNotFound++;
        context.setShown(true);
        CustomDialog alert = new CustomDialog(context, message, prefill, context.getResources().getString(R.string.ok_label), context.getResources().getString(R.string.action_exit), context.getResources().getString(R.string.search_server), true, true);
        final EditText input = alert.getInput();
        final AlertDialog dialog = alert.getAlertDialog();

        alert.getYes().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Editable value = input.getText();
                String ip = value.toString();
                checkUserInput(ip);
                context.setShown(false);
                dialog.dismiss();
            }
        });

        alert.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Exit the app
                closeApp();
            }
        });

        alert.getNeutral().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                context.setShown(false);
                context.startAutoConnect();
            }
        });

        if (urlNotFound > 1) {
            Animation scale = AnimationUtils.loadAnimation(context, R.anim.pop);
            alert.getHelp().startAnimation(scale);
            urlNotFound = 0;
        }

        alert.getHelp().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, Troubleshooting.class));
            }
        });

        // Listen for enter/return press on input
        TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView input, int actionId,
                                          KeyEvent event) {
                if (((actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN))
                        || (actionId == EditorInfo.IME_ACTION_DONE)) {
                    Editable value = input.getEditableText();
                    String ip = value.toString();
                    checkUserInput(ip);
                    dialog.dismiss();
                }
                return true;
            }
        };

        input.setOnEditorActionListener(exampleListener);
    }

    void checkUserInput(String ip) {
        // Check if input is empty or contains less than 7 characters
        // (which both is the smallest potential IP with port
        // number and the amount of characters needed to check if "http://"
        // is added or not)
        if ((ip.equals("")) || (ip.length() < 7)
                || (!(ip.contains(":")))) {
            if (!context.isShown())
                enterURLDialog(
                        context.getResources().getString(
                                R.string.incorrect_url_mr), "");

        } else {
            // Check if http:// needs to be added
            if (ip.length() > 7 && !(ip.substring(0, 7).equals("http://")))
                ip = "http://" + ip;
            ip = ip.replaceAll(" ", "");
            String match = Utils.matchIP(ip);
            switch (match) {
                case "true":
                    context.getSettings().saveSetting("urlMR", ip);
                    break;
                case "ipv6":
                    enterURLDialog(
                            context.getResources().getString(
                                    R.string.cant_use_ipv6), "");
                    return;
                default:
                    enterURLDialog(context.getString(R.string.url_incorrect), ip);
                    return;
            }

            // Check if login is needed
            if (Patterns.WEB_URL.matcher(ip).matches()) {
                context.getSettings().setIp(ip);
                context.checkIP(ip);
            } else {
                enterURLDialog(context.getString(R.string.url_incorrect), ip);
            }

            // Download lyrics if already logged in
            if (context.isLoggedIn())
                context.downloadLyrics();
            context.setShown(false);
        }
    }

    // Show dialog for logging in to Mobile Remote server
    void loginDialog() {
        context.setShown(true);
        CustomDialog alert = new CustomDialog(context, context.getResources().getString(R.string.enter_password), "", context.getResources().getString(R.string.ok_label), context.getResources().getString(R.string.action_exit), "", false, true);
        final EditText input = alert.getInput();
        final AlertDialog alertText = alert.getAlertDialog();

        alert.getYes().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Editable value = input.getText();
                String password = value.toString();
                alertText.dismiss();

                // Log in
                context.sendPassword(password);
                context.setShown(false);
            }
        });

        alert.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Exit app
                closeApp();
            }
        });

        // Listen for enter/return press on input
        TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView input, int actionId,
                                          KeyEvent event) {
                if (((actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN))
                        || (actionId == EditorInfo.IME_ACTION_DONE)) {
                    alertText.getButton(Dialog.BUTTON_POSITIVE).performClick();
                    if (alertText.isShowing()) {
                        context.setShown(false);
                        Editable value = input.getEditableText();
                        String password = value.toString();

                        // Log in
                        context.sendPassword(password);
                        alertText.dismiss();
                    }
                }
                return true;
            }
        };

        input.setOnEditorActionListener(exampleListener);

    }

    void scheduleLongClickDialog(final int i) {
        context.setShown(true);
        CustomSelectionDialog csd = new CustomSelectionDialog(context, String.format(context.getString(R.string.choose_action), context.getScheduleList().get(i)), "", "", "");
        String[] options = {context.getString(R.string.remove_item), context.getString(R.string.move_up), context.getString(R.string.move_down)};
        final AlertDialog dialog = csd.getAlertDialog();
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                context.setShown(false);
            }
        });
        ListView list = csd.getListView();
        ListAdapter adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_list_item_1, options);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                if (which == 0) {
                    String url = context.getSettings().getIp() + "/remove/" + i;
                    context.checkSupported(url);
                } else if (which == 1) {
                    String url = context.getSettings().getIp() + "/moveup/" + i;
                    context.checkSupported(url);
                } else if (which == 2) {
                    String url = context.getSettings().getIp() + "/movedown/" + i;
                    context.checkSupported(url);
                }
                context.setShown(false);
                dialog.dismiss();
            }
        });
    }

    void selectThemeDialog(String line) {
        if (!context.isShown()) {
            context.setShown(true);
            if (!line.contains("<!DOCTYPE html>")) {
                CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getString(R.string.select_theme), "", "", context.getString(R.string.cancel_label));
                final String[] options = line.split("\n");
                final AlertDialog dialog = csd.getAlertDialog();
                dialog.setCancelable(true);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        context.setShown(false);
                    }
                });
                ListView list = csd.getListView();
                ThemeAdapter adapter = new ThemeAdapter(context, Arrays.asList(options));
                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                        Toast.makeText(context, String.format(context.getString(R.string.setting_theme), options[which]), Toast.LENGTH_SHORT).show();
                        context.setTheme(options[which].replaceAll(" ", "%20"));
                        dialog.dismiss();
                        context.setShown(false);
                    }
                });
                csd.getNeutral().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        context.setShown(false);
                    }
                });
            } else {
                context.setShown(false);
                infoDialog(context.getString(R.string.not_supported));
            }
        }
    }

    void exitDialog() {
        CustomDialog cd = new CustomDialog(context, context.getResources().getString(R.string.want_to_exit), "", context.getResources().getString(R.string.yes_label), context.getResources().getString(R.string.no_label), "", false, false);
        final AlertDialog dialog = cd.getAlertDialog();

        cd.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        cd.getYes().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Exit the app
                context.getLyricsAdapter().imageLoader.clearCache();
                closeApp();
                dialog.dismiss();
            }
        });
    }

    // Dialog for selecting what to search for
    void searchDialog(boolean newSearch) {
        if (newSearch)
            newSearchDialog();
        else {
            bibleSearchDialog();
        }
    }

    private void newSearchDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        LayoutInflater factory = LayoutInflater.from(context);
        @SuppressLint("InflateParams") final View customDialog = factory.inflate(
                R.layout.custom_search_dialog, null);
        builder.setView(customDialog);
        TextView t = customDialog.findViewById(R.id.bibleSearch);
        t.setText(context.getResources().getString(R.string.add_bible));
        TextView t2 = customDialog.findViewById(R.id.songSearch);
        t2.setText(context.getResources().getString(R.string.search_song));
        builder.setCancelable(false);
        final AlertDialog alertText = builder.show();
        customDialog.findViewById(R.id.songButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MenuItem searchMenuItem = context.getSearchViewMenu()
                        .findItem(R.id.action_search);
                SearchView searchView = (SearchView) searchMenuItem.getActionView();
                searchView.setQueryHint(context.getResources()
                        .getString(R.string.enter_song));
                context.setBibleSearch(false);
                alertText.dismiss();

            }
        });
        customDialog.findViewById(R.id.bibleButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.setBibleSearch(true);
                context.getTranslations();
                alertText.dismiss();
            }
        });
        customDialog.findViewById(R.id.btn_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertText.dismiss();
                final MenuItem searchMenuItem = context.getSearchViewMenu()
                        .findItem(R.id.action_search);
                searchMenuItem.collapseActionView();
                context.getHelp().setVisible(false);
                context.getEdit_book().setVisible(false);
            }
        });
    }

    // Dialog for bible searches
    private void bibleSearchDialog() {
        // Check if no translation is selected (= new search)
        if (!context.isSelectedTranslations()) {
            bibleTranslationSelectionDialog();
        } else {
            // If translation already is selected, show the books that are already downloaded
            bibleBookSelectionDialog();
        }
    }

    private void bibleBookSelectionDialog() {
        if (!(context.getBibleBooks()[0].isEmpty())) {
            CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_book), "", context.getResources().getString(R.string.change_translation), context.getResources().getString(R.string.cancel_label));
            final AlertDialog dialog = csd.getAlertDialog();
            ListView list = csd.getListView();
            ListAdapter adapter = new ArrayAdapter<>(context,
                    android.R.layout.simple_list_item_1, context.getBibleBooks());
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                    // The 'which' argument contains the
                    // index position of the selected item
                    context.setBibleBook(context.getBibleBooks()[which]);
                    final MenuItem searchMenuItem = context.getSearchViewMenu()
                            .findItem(R.id.action_search);
                    final SearchView search = (SearchView) searchMenuItem.getActionView();
                    search.setQueryHint(context.getResources()
                            .getString(
                                    R.string.bible_query_hint)
                            + " "
                            + context.getBibleBook()
                            + " ("
                            + context.getBibleTranslation().replaceAll(
                            "%20", " ") + ")");
                    context.getEdit_book().setVisible(true);
                    StringBuilder sb = Utils.readAssets("chapter_lengths.txt", context);
                    int chapters = 0;
                    for (String s : sb.toString().split("\n")) {
                        if (s.startsWith((which + 1) + ",")) {
                            String[] val = s.split(",");
                            chapters = Integer.valueOf(val[1]);
                        }
                    }
                    bibleChapterSelectionDialog(chapters, (which + 1));
                    dialog.dismiss();
                }
            });
            csd.getNeutral().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Close dialog and hide buttons
                    dialog.dismiss();
                    // Hide buttons and search bar
                    final MenuItem searchMenuItem = context.getSearchViewMenu()
                            .findItem(R.id.action_search);
                    searchMenuItem.collapseActionView();
                    context.getHelp().setVisible(false);
                    context.getEdit_book().setVisible(false);
                }
            });
            csd.getNo().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    context.setSelectedTranslations(false);
                    searchDialog(false);
                    dialog.dismiss();
                }
            });
        }
    }

    private void bibleChapterSelectionDialog(int chapters, final int bookNum) {
//        if (!(context.getBibleBook().isEmpty())) {
        final MenuItem searchMenuItem = context.getSearchViewMenu()
                .findItem(R.id.action_search);
        final SearchView search = (SearchView) searchMenuItem.getActionView();
        CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_chapter) + " (" + context.getBibleBook() + ")", "", context.getResources().getString(R.string.change_book), context.getResources().getString(R.string.cancel_label));
        final AlertDialog dialog = csd.getAlertDialog();
        ListView list = csd.getListView();

        final String[] strings = new String[chapters];
        for (int i = 0; i < chapters; i++) {
            strings[i] = "" + (i + 1);
        }

        ListAdapter adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_list_item_1, strings);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                // The 'which' argument contains the
                // index position of the selected item
                search.setQuery(strings[which], false);
                StringBuilder sb = Utils.readAssets("chapter_lengths.txt", context);
                int verses = 0;
                for (String s : sb.toString().split("\n")) {
                    if (s.startsWith(bookNum + "," + strings[which] + ",")) {
                        String[] val = s.split(",");
                        verses = Integer.valueOf(val[2]);
                    }
                }
                bibleVerseSelectionDialog(verses);
                dialog.dismiss();
            }
        });
        csd.getNeutral().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Close dialog
                dialog.dismiss();
            }
        });
        csd.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.setSelectedTranslations(false);
                bibleBookSelectionDialog();
                dialog.dismiss();
            }
        });
//        }
    }

    private void bibleVerseSelectionDialog(int verses) {
        final MenuItem searchMenuItem = context.getSearchViewMenu()
                .findItem(R.id.action_search);
        final SearchView search = (SearchView) searchMenuItem.getActionView();
        CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_verse) + " (" + context.getBibleBook() + " " + search.getQuery() + ")", "", "", context.getResources().getString(R.string.cancel_label));
        final AlertDialog dialog = csd.getAlertDialog();
        ListView list = csd.getListView();

        final String[] strings = new String[verses];
        for (int i = 0; i < verses; i++) {
            strings[i] = "" + (i + 1);
        }

        ListAdapter adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_list_item_1, strings);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                // The 'which' argument contains the
                // index position of the selected item
                search.setQuery(search.getQuery() + ":" + strings[which], false);
                StringBuilder remaining = new StringBuilder();
                for (int i = (which + 1); i < strings.length; i++) {
                    remaining.append(strings[i]).append("\n");
                }
                if (!remaining.toString().isEmpty())
                    bibleVerseToSelectionDialog(remaining.toString().split("\n"));
                dialog.dismiss();
            }
        });
        csd.getNeutral().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Close dialog
                dialog.dismiss();
            }
        });
    }

    private void bibleVerseToSelectionDialog(final String[] remainingVerses) {
        final MenuItem searchMenuItem = context.getSearchViewMenu()
                .findItem(R.id.action_search);
        final SearchView search = (SearchView) searchMenuItem.getActionView();
        CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_verse_ending) + " (" + context.getBibleBook() + " " + search.getQuery() + ")?", "", context.getResources().getString(R.string.add), context.getResources().getString(R.string.cancel_label));
        final AlertDialog dialog = csd.getAlertDialog();
        ListView list = csd.getListView();

        ListAdapter adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_list_item_1, remainingVerses);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                search.setQuery(search.getQuery() + "-" + remainingVerses[which], true);
                dialog.dismiss();
            }
        });
        csd.getNeutral().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Close dialog
                dialog.dismiss();
            }
        });
        csd.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search.setQuery(search.getQuery(), true);
                dialog.dismiss();
            }
        });
    }

    private void bibleTranslationSelectionDialog() {
        if (!(context.getBibleTranslations()[0].isEmpty())) {
            CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_translation), "", "", context.getResources().getString(R.string.cancel_label));
            final AlertDialog dialog = csd.getAlertDialog();
            ListView list = csd.getListView();
            ListAdapter adapter = new ArrayAdapter<>(context,
                    android.R.layout.simple_list_item_1, context.getBibleTranslations());
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                    context.getParseDownloadedText().downloadBooks(which);
                    dialog.dismiss();
                }
            });
            csd.getNeutral().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Close dialog and hide buttons
                    dialog.dismiss();
                    final MenuItem searchMenuItem = context.getSearchViewMenu()
                            .findItem(R.id.action_search);
                    searchMenuItem.collapseActionView();
                    context.getHelp().setVisible(false);
                    context.getEdit_book().setVisible(false);
                }
            });
        }
    }

    void showResultInDialog() {
//         Show the results of the songs found
        if (!(context.getSearchResult()[0].isEmpty())) {
            CustomSelectionDialog csd = new CustomSelectionDialog(context, context.getResources().getString(R.string.select_song), "", "", context.getResources().getString(R.string.cancel_label));
            final AlertDialog dialog = csd.getAlertDialog();
            ListView list = csd.getListView();
            ListAdapter adapter = new ArrayAdapter<>(context,
                    android.R.layout.simple_list_item_1, context.getSearchResult());
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int which, long l) {
                    // The 'which' argument contains the
                    // index position of the selected item
                    if (context.getLine().contains("=\"") && context.getLine().contains("=\"") && context.getLine().contains("\">")) {
                        context.getSong(context.getTempResult()[which].substring(
                                context.getTempResult()[which]
                                        .lastIndexOf("=\"") + 2,
                                context.getTempResult()[which]
                                        .lastIndexOf("\">")));
                        context.setSongSelected(true);
                    } else {
                        infoDialog("Something went wrong when trying to add the song.");
                    }
                    dialog.dismiss();
                }
            });
            csd.getNeutral().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Close dialog
                    dialog.dismiss();
                }
            });
        } else {
            // Show message is no songs were found
            infoDialog(context.getResources().getString(R.string.no_songs_message));
        }
    }

    // Dialog to ask if the user wants to add the selected song to the schedule
    void addSongToScheduleDialog(String string, final String songNumber) {
        CustomDialog alert = new CustomDialog(context, Html.fromHtml(string).toString(), "", context.getResources().getString(R.string.yes_label), context.getResources().getString(R.string.no_label), context.getResources().getString(R.string.add_go_live), false, false);
        alert.setTitle(context.getResources().getString(R.string.add_song));
        final AlertDialog dialog = alert.getAlertDialog();
        final MenuItem searchMenuItem = context.getSearchViewMenu()
                .findItem(R.id.action_search);
        final SearchView sv = (SearchView) searchMenuItem.getActionView();
        context.setResultIsOpen(true);

        alert.getNo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (context.getResultView().getVisibility() == View.GONE)
                    showResultInDialog();
                dialog.dismiss();
                context.setResultIsOpen(false);
            }
        });

        alert.getNeutral().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.loadSong(songNumber);

                if (!context.isCanJump()) {
                    for (int i = context.getActiveItem(); i < (context.getScheduleList().size()); i++)
                        context.nextItem();
                } else {
                    context.gotoItem(context.getScheduleList().size(), context.getActiveItem());
                }

                final Animation nextAnim = AnimationUtils.loadAnimation(context, R.anim.next);
                context.getLyricsListView().startAnimation(nextAnim);
                context.setSlide(true);
                context.getLyricsListView().setAdapter(context.getLyricsAdapter());
                searchMenuItem.collapseActionView();
                sv.setQuery("", false);
                context.setResultIsOpen(false);
                context.getResultView().setVisibility(View.GONE);
                dialog.dismiss();
            }
        });

        alert.getYes().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.loadSong(songNumber);
                dialog.dismiss();
                searchMenuItem.collapseActionView();
                sv.setQuery("", false);
                context.setResultIsOpen(false);
                context.getResultView().setVisibility(View.GONE);
            }
        });
    }

    private void closeApp() {
        context.finish();
        context.getSync().stopSync();
        System.exit(0);
    }

}


text:
/**
 * @file
 * Abstraction of a device, which is typically an I2C device but may be local. It's made
 * up of registers.
 *
 */

#ifndef __DEVICE_H
#define __DEVICE_H

#include "../../common/regs.h"

#define E_NOSUCHREG 1
#define E_READONLY 2

class Device {
protected:
    /// static copy of register definition
    static Register reg;
    /// register table in program memory
    MAYBEPROGMEM Register *table;

    /// internal method to check register correct,
    /// will load it into SRAM.
    int checkAndLoadRegister(int r,bool writeRequested){
        if(r>=numRegs)
            return E_NOSUCHREG;
        else {
            loadReg(r);
            if(writeRequested && !reg.writable())
                return E_READONLY;
            else
                return 0;
        }
    }

    /// load a register definition from the table
    void loadReg(int n){
        memcpy_P(&reg,table+n,sizeof(Register));
    }

    /// read set used by protocol - these are
    /// SHARED BY ALL DEVICES
    static uint8_t readSet[READSETS][READSETSIZE];
    static uint8_t readSetCt[READSETS];

public:
    uint8_t numRegs; //!< highest register number

    Device(MAYBEPROGMEM Register *r){
        table = r;
        // count registers - the terminator is a silly register size
        numRegs=0;
        for(;;){
            loadReg(numRegs); // load in each register
            if(reg.getSize()>30)break;
            numRegs++;
        }
    }

    /// initialise the read set
    static void clearReadSet(uint8_t s){
        readSetCt[s]=0;
    }

    /// add a register to the read set
    static void addReadSet(uint8_t s,uint8_t r){
        readSet[s][readSetCt[s]++]=r;
    }

    /// get s read set and its count
    static const uint8_t *getReadSet(uint8_t s,uint8_t *ct){
        *ct = readSetCt[s];
        return readSet[s];
    }

    /// get the size of a register from the register
    /// table
    int getRegisterSize(int r){
        loadReg(r);
        return reg.getSize();
    }

    /// override this method to provide register write semantics
    virtual int writeRegister(byte reg,uint16_t val)=0;
    /// override this method to provide register read semantics
    virtual int readRegister(byte reg,uint16_t *readValue)=0;
};

#endif /* __DEVICE_H */


text:
package com.netflix.spinnaker.orca.clouddriver.pipeline;

import com.netflix.spinnaker.orca.clouddriver.tasks.MonitorKatoTask;
import com.netflix.spinnaker.orca.clouddriver.tasks.pipeline.MigratePipelineClustersTask;
import com.netflix.spinnaker.orca.clouddriver.tasks.pipeline.UpdateMigratedPipelineTask;
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder;
import com.netflix.spinnaker.orca.pipeline.TaskNode;
import com.netflix.spinnaker.orca.pipeline.model.Stage;
import org.springframework.stereotype.Component;

@Component
public class MigratePipelineStage implements StageDefinitionBuilder {

  public static final String PIPELINE_CONFIG_TYPE = "migratePipeline";

  @Override
  public void taskGraph(Stage stage, TaskNode.Builder builder) {
    builder
      .withTask("migratePipelineClusters", MigratePipelineClustersTask.class)
      .withTask("monitorMigration", MonitorKatoTask.class);
    if (!Boolean.TRUE.equals(stage.getContext().get("dryRun"))) {
      builder.withTask("updateMigratedPipeline", UpdateMigratedPipelineTask.class);
    }
  }
}


text:
<?php

/**
 * Default presenter loader.
 *
 * @author     David Grudl
 * @package Nette\Application
 */
class NPresenterFactory implements IPresenterFactory
{
	/** @var bool */
	public $caseSensitive = FALSE;

	/** @var string */
	private $baseDir;

	/** @var array */
	private $cache = array();

	/** @var IDIContainer */
	private $context;

	/**
	 * @param  string
	 */
	public function __construct($baseDir, IDIContainer $context)
	{
		$this->baseDir = $baseDir;
		$this->context = $context;
	}

	/**
	 * Create new presenter instance.
	 * @param  string  presenter name
	 * @return IPresenter
	 */
	public function createPresenter($name)
	{
		$presenter = $this->context->createInstance($this->getPresenterClass($name));
		if (method_exists($presenter, 'setContext')) {
			$this->context->callMethod(array($presenter, 'setContext'));
		}
		return $presenter;
	}

	/**
	 * @param  string  presenter name
	 * @return string  class name
	 * @throws NInvalidPresenterException
	 */
	public function getPresenterClass(& $name)
	{
		if (isset($this->cache[$name])) {
			list($class, $name) = $this->cache[$name];
			return $class;
		}

		if (!is_string($name) || !NStrings::match($name, "#^[a-zA-Z\x7f-\xff][a-zA-Z0-9\x7f-\xff:]*$#")) {
			throw new NInvalidPresenterException("Presenter name must be alphanumeric string, '$name' is invalid.");
		}

		$class = $this->formatPresenterClass($name);

		if (!class_exists($class)) {
			// internal autoloading
			$file = $this->formatPresenterFile($name);
			if (is_file($file) && is_readable($file)) {
				NLimitedScope::load($file, TRUE);
			}

			if (!class_exists($class)) {
				throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");
			}
		}

		$reflection = new NClassReflection($class);
		$class = $reflection->getName();

		if (!$reflection->implementsInterface('IPresenter')) {
			throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is not IPresenter implementor.");
		}

		if ($reflection->isAbstract()) {
			throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");
		}

		// canonicalize presenter name
		$realName = $this->unformatPresenterClass($class);
		if ($name !== $realName) {
			if ($this->caseSensitive) {
				throw new NInvalidPresenterException("Cannot load presenter '$name', case mismatch. Real name is '$realName'.");
			} else {
				$this->cache[$name] = array($class, $realName);
				$name = $realName;
			}
		} else {
			$this->cache[$name] = array($class, $realName);
		}

		return $class;
	}

	/**
	 * Formats presenter class name from its name.
	 * @param  string
	 * @return string
	 */
	public function formatPresenterClass($presenter)
	{
		return strtr($presenter, ':', '_') . 'Presenter';
		return str_replace(':', 'Module\\', $presenter) . 'Presenter';
	}

	/**
	 * Formats presenter name from class name.
	 * @param  string
	 * @return string
	 */
	public function unformatPresenterClass($class)
	{
		return strtr(substr($class, 0, -9), '_', ':');
		return str_replace('Module\\', ':', substr($class, 0, -9));
	}

	/**
	 * Formats presenter class file name.
	 * @param  string
	 * @return string
	 */
	public function formatPresenterFile($presenter)
	{
		$path = '/' . str_replace(':', 'Module/', $presenter);
		return $this->baseDir . substr_replace($path, '/presenters', strrpos($path, '/'), 0) . 'Presenter.php';
	}

}


text:
<?php

namespace Seat\EveApi\Api;

use Seat\EveApi\BaseApi;
use Pheal\Pheal;

class Calllist extends BaseApi
{

    public static function Update()
    {
        BaseApi::bootstrap();

        $pheal = new Pheal();
        $calllist = $pheal->apiScope->calllist();

        return $calllist;
    }
}


text:
var assert = require('assert'),
  proxyquire = require('proxyquire'),
  requester = proxyquire('../../lib/requester.js', {
    'request' : function(){}
  }),
  requestFixture = require('../fixtures/fixture-example-request.js');

exports.it_should_skip_raw_for_non_debug = function(done){
  requester(requestFixture, function(err, requestResult){
    assert.ok(!requestResult.request.raw);
    assert.ok(!requestResult.response.raw);
    return done();
  });
};

exports.it_should_send_get_requests = function(done){
  requester(requestFixture, true, function(err, requestResult){
    assert.ok(!err, 'Error on sending request to requester');
    assert.ok(requestResult, 'Expected a requestResult');
    assert.ok(requestResult.response, 'Expected requestResult to have a response');
    assert.ok(requestResult.request, 'Expected requestResult to have request data');

    assert.ok(requestResult.request.raw);
    assert.ok(requestResult.response.raw);
    assert.ok(requestResult.request.raw.indexOf('GET')>-1, 'Raw should have HTTP Method');
    assert.ok(requestResult.request.raw.indexOf('foo')>-1, 'Raw should have header key');
    assert.ok(requestResult.request.raw.indexOf('foo')>-1, 'Raw should have header value');
    assert.ok(requestResult.request.raw.indexOf('UPCASE')>-1, 'Should not convert header values to lowercase');
    return done();
  });
};

exports.it_should_send_post_requests = function(done){
  requestFixture.method = 'post';
  requestFixture.body = { message :'Hello world' };
  requester(requestFixture, true, function(err, requestResult){
    assert.ok(requestResult.request.raw.indexOf('POST')>-1, 'Raw should have HTTP Method');
    assert.ok(requestResult.request.raw.indexOf('message')>-1, 'Raw should have request key');
    assert.ok(requestResult.request.raw.indexOf('Hello world')>-1, 'Raw should have request value');
    return done();
  });
};

exports.it_should_send_post_requests_with_valid_json = function(done){
  requestFixture.method = 'post';
  requestFixture.headers = [
    { key : 'content-type', value : 'application/json' },
    { key : 'accept', value : 'application/json' }
  ];
  requestFixture.body = { "barcode" : "077924004971" };
  requestFixture.url = 'http://jsonplaceholder.typicode.com/posts';
  requester(requestFixture, true, function(err, requestResult){
    assert.ok(requestResult.request.raw.indexOf('POST')>-1, 'Raw should have HTTP Method');
    assert.ok(requestResult.request.raw.indexOf('barcode')>-1, 'Raw should have json key name in the body');
    assert.ok(requestResult.request.raw.indexOf('077924004971')>-1, 'Raw should have json value in the body');
    assert.ok(requestResult.request.headers.accept === "application/json");
    assert.ok(requestResult.request.headers["content-type"] === "application/json");
    return done();
  });
};

exports.it_should_throw_error_on_invalid_url = function(done){
  requester({url : 'invalid', method : 'get'}, function(err){
    assert.ok(err, 'Expected error on invalid url');
    return done();
  });
};

exports.it_should_throw_error_on_invalid_method = function(done){
  requester({url : 'http://www.google.ie', method : 'invalid'}, function(err){
    assert.ok(err, 'Expected error on invalid method');
    return done();
  });
};

exports.it_should_throw_error_on_invalid_params = function(done){
  requester({}, function(err){
    assert.ok(err, 'Expected error on invalid params');
    return done();
  });
};


text:
package org.apache.druid.query.aggregation.datasketches.tuple;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch;
import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.Druids;
import org.apache.druid.query.aggregation.CountAggregatorFactory;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.aggregation.post.ConstantPostAggregator;
import org.apache.druid.query.timeseries.TimeseriesQuery;
import org.apache.druid.query.timeseries.TimeseriesQueryQueryToolChest;
import org.apache.druid.segment.column.ColumnType;
import org.apache.druid.segment.column.RowSignature;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Arrays;
import java.util.Map;

public class ArrayOfDoublesSketchTTestPostAggregatorTest
{
  @Rule
  public ExpectedException expectedException = ExpectedException.none();

  @Test
  public void testConstructorTooFewPostAggInputs()
  {
    expectedException.expect(IAE.class);
    expectedException.expectMessage("Illegal number of fields[1], must be 2");
    new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        ImmutableList.of(new ConstantPostAggregator("", 0))
    );
  }

  @Test
  public void testConstructorTooManyPostAggInputs()
  {
    expectedException.expect(IAE.class);
    expectedException.expectMessage("Illegal number of fields[3], must be 2");
    new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        Arrays.asList(
            new ConstantPostAggregator("", 0),
            new ConstantPostAggregator("", 0),
            new ConstantPostAggregator("", 0)
        )
    );
  }

  @Test
  public void testSerde() throws JsonProcessingException
  {
    final PostAggregator there = new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        Arrays.asList(new ConstantPostAggregator("", 0), new ConstantPostAggregator("", 0))
    );
    DefaultObjectMapper mapper = new DefaultObjectMapper();
    ArrayOfDoublesSketchTTestPostAggregator andBackAgain = mapper.readValue(
        mapper.writeValueAsString(there),
        ArrayOfDoublesSketchTTestPostAggregator.class
    );

    Assert.assertEquals(there, andBackAgain);
    Assert.assertArrayEquals(there.getCacheKey(), andBackAgain.getCacheKey());
  }

  @Test
  public void testToString()
  {
    final PostAggregator postAgg = new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        Arrays.asList(new ConstantPostAggregator("", 0), new ConstantPostAggregator("", 0))
    );

    Assert.assertEquals(
        "ArrayOfDoublesSketchTTestPostAggregator{name='a', fields=[ConstantPostAggregator{name='', constantValue=0}, ConstantPostAggregator{name='', constantValue=0}]}",
        postAgg.toString()
    );
  }

  @Test
  public void testComparator()
  {
    expectedException.expect(IAE.class);
    expectedException.expectMessage("Comparing arrays of p values is not supported");
    PostAggregator postAgg = new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        Arrays.asList(new ConstantPostAggregator("", 0), new ConstantPostAggregator("", 0))
    );
    postAgg.getComparator();
  }

  @Test
  public void testEqualsAndHashCode()
  {
    EqualsVerifier.forClass(ArrayOfDoublesSketchTTestPostAggregator.class)
                  .withNonnullFields("name", "fields")
                  .withIgnoredFields("dependentFields")
                  .usingGetClass()
                  .verify();
  }

  @Test
  public void testComputeMismatchedSketches()
  {
    expectedException.expect(IAE.class);
    expectedException.expectMessage("Sketches have different number of values: 2 and 100");
    ArrayOfDoublesUpdatableSketch s1 = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16)
                                                                                .setNumberOfValues(2)
                                                                                .build();
    ArrayOfDoublesUpdatableSketch s2 = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(16)
                                                                                .setNumberOfValues(100)
                                                                                .build();
    PostAggregator field1 = EasyMock.createMock(PostAggregator.class);
    EasyMock.expect(field1.compute(EasyMock.anyObject(Map.class))).andReturn(s1).anyTimes();
    PostAggregator field2 = EasyMock.createMock(PostAggregator.class);
    EasyMock.expect(field2.compute(EasyMock.anyObject(Map.class))).andReturn(s2).anyTimes();
    EasyMock.replay(field1, field2);
    new ArrayOfDoublesSketchTTestPostAggregator(
        "a",
        Arrays.asList(field1, field2)
    ).compute(ImmutableMap.of());
  }

  @Test
  public void testResultArraySignature()
  {
    final TimeseriesQuery query =
        Druids.newTimeseriesQueryBuilder()
              .dataSource("dummy")
              .intervals("2000/3000")
              .granularity(Granularities.HOUR)
              .aggregators(
                  new CountAggregatorFactory("count")
              )
              .postAggregators(
                  new ArrayOfDoublesSketchTTestPostAggregator(
                      "a",
                      ImmutableList.of(
                          new ConstantPostAggregator("", 0),
                          new ConstantPostAggregator("", 0)
                      )
                  )
              )
              .build();

    Assert.assertEquals(
        RowSignature.builder()
                    .addTimeColumn()
                    .add("count", ColumnType.LONG)
                    .add("a", ColumnType.DOUBLE_ARRAY)
                    .build(),
        new TimeseriesQueryQueryToolChest().resultArraySignature(query)
    );
  }
}


text:
class Node {
  static cloneArray(arr) {
    let clone = [];
    for (let i = 0; i < arr.length; i++) {
      clone.push( arr[i].slice(0) )
    }
    return clone;
  }

  constructor(parentMatrix, path, level, i, j){
    // stores ancestors edges of state space tree
    this.path = Node.cloneArray(path);
    // skip for root node
    if (level != 0)
        // add current edge to path
        this.path.push([i, j]);

    // copy data from parent node to current node

    this.reducedMatrix = Node.cloneArray(parentMatrix);

    // Change all entries of row i and column j to infinity
    // skip for root node
    for (let k = 0; level != 0 && k < this.reducedMatrix.length; k++){
        // set outgoing edges for city i to infinity
        this.reducedMatrix[i][k] = Infinity;

        // set incoming edges to city j to infinity
        this.reducedMatrix[k][j] = Infinity;
    }

    // Set (j, 0) to infinity
    // here start node is 0
    this.reducedMatrix[j][0] = Infinity;

    // set number of cities visited so far
    this.level = level;

    // assign current city number
    this.vertex = j;

    this.calculateCost();
  }

  // Function to get the lower bound on
  // on the path starting at current min node
  calculateCost(){
      // initialize cost to 0
      this.cost = 0;

      // Row Reduction
      let row = this.rowReduction();
      // Column Reduction
      let col = this.columnReduction();

      // the total expected cost
      // is the sum of all reductions
      for (let i = 0; i < this.reducedMatrix.length; i++){
        this.cost += (row[i] != Infinity) ? row[i] : 0;
        this.cost += (col[i] != Infinity) ? col[i] : 0;
      }
  }

  // Function to reduce each row in such a way that
  // there must be at least one zero in each row
  rowReduction(){
      // initialize row array to Infinity
      let row = new Array(this.reducedMatrix.length).fill(Infinity);

      // row[i] contains minimum in row i
      for (let r = 0; r < this.reducedMatrix.length; r++){
        row[r] = Math.min.apply(null, this.reducedMatrix[r]);
        // reduce the minimum value from each element in each row
        this.reducedMatrix[r] = this.reducedMatrix[r].map(elem=>
          (elem != Infinity && row[r] != Infinity) ? elem - row[r] : elem
        )
      }

      return row;
  }

  // Function to reduce each column in such a way that
  // there must be at least one zero in each column
  columnReduction(){
      // initialize col array to Infinity
      let col = new Array(this.reducedMatrix.length).fill(Infinity);

      // col[j] contains minimum in col j
      for (let i = 0; i < this.reducedMatrix.length; i++)
          for (let j = 0; j < this.reducedMatrix[i].length; j++)
              if (this.reducedMatrix[i][j] < col[j])
                  col[j] = this.reducedMatrix[i][j];

      // reduce the minimum value from each element in each column
      for (let i = 0; i < this.reducedMatrix.length; i++){
        for (let j = 0; j < this.reducedMatrix[i].length; j++){
          if (this.reducedMatrix[i][j] != Infinity && col[j] != Infinity)
            this.reducedMatrix[i][j] -= col[j];
        }
      }
      return col;
  }

};

module.exports = Node;


text:
<?php

class Revision33_IndexCommunityMemberPosition extends Doctrine_Migration_Base
{
  public function migrate($direction)
  {
    $this->foreignKey($direction, 'community_member_position', 'community_member_position_member_id_member_id', array(
      'name' => 'community_member_position_member_id_member_id',
      'local' => 'member_id',
      'foreign' => 'id',
      'foreignTable' => 'member',
      'onDelete' => 'CASCADE',
    ));

    $this->foreignKey($direction, 'community_member_position', 'community_member_position_community_id_community_id', array(
      'name' => 'community_member_position_community_id_community_id',
      'local' => 'community_id',
      'foreign' => 'id',
      'foreignTable' => 'community',
      'onDelete' => 'CASCADE',
    ));

    $this->foreignKey($direction, 'community_member_position', 'ccci', array(
      'name' => 'ccci',
      'local' => 'community_member_id',
      'foreign' => 'id',
      'foreignTable' => 'community_member',
      'onDelete' => 'CASCADE',
    ));
  }
}


text:
django-memorycms
================


text:
package org.filestore.ejb.store;

import java.io.InputStream;

public interface BinaryStoreService {

	public boolean exists(String key) throws BinaryStoreServiceException;

	public String put(InputStream is) throws BinaryStoreServiceException;

	public InputStream get(String key) throws BinaryStoreServiceException, BinaryStreamNotFoundException;

}


text:
<!doctype html>

    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta charset="utf-8">
    <meta content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">

    <title>Dan Malarkey is a design leader in Northeast Florida.</title>

    <link href='//fonts.googleapis.com/css?family=Lato:300,400' rel='stylesheet' type='text/css'>

    <link href="/stylesheets/site.css" rel="stylesheet" />

            Malarkey.

              journal
              about
              booklist
              speaking
              mentoring
              contact

Middleman is Running

        Read Documentation Online
        Journal


text:
var anyfile = require(__dirname + '/..')();
var fromFile = "https://docs.uproc.io/pdf/resumen_del_servicio_ES.pdf";
var toFile = "resumen_del_servicio_ES.pdf";

try {
  anyfile.from(fromFile).to(toFile, function(err, res) {
    console.log(res);
    process.exit();
  });
} catch (e) {
  console.log(e);
}


text:
Sequel.migration do
  change do

    create_table :manage_name_id_services do
      primary_key :id
    end

  end
end


text:
package microsoft.exchange.webservices.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.concurrent.*;

class GetStream implements Callable {
	HttpWebRequest request;
	String mName = "";

	public GetStream(HttpWebRequest request, String method) {
		this.request = request;
		this.mName = method;
	}

	public Object call() throws java.io.IOException, EWSHttpException,
			HttpErrorException {

		if (this.mName.equalsIgnoreCase("getOutputStream"))
			return (Object) this.getOutputStream();
		return null;
	}

	public ByteArrayOutputStream getOutputStream() throws EWSHttpException {
		return (ByteArrayOutputStream) request.getOutputStream();

	}

	/*
	 * public ByteArrayOutputStream getOutputStream() throws Exception { return
	 * (ByteArrayOutputStream)request.getOutputStream();
	 *
	 * }
	 */

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   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.
 */
#include "generator_module.h"
#include "auditevent_generator.h"
#include "generator_event.h"
#include "generator_utilities.h"

#include <nlohmann/json.hpp>
#include <utilities/json_utilities.h>

#include <fstream>
#include <gsl/gsl>
#include <memory>
#include <sstream>
#include <system_error>

Module::Module(const nlohmann::json& object,
               const std::string& srcRoot,
               const std::string& objRoot) {
    /*
     * https://github.com/nlohmann/json/issues/67
     * There is no way for a JSON value to "know" whether it is stored in an
     * object, and if so under which key Use an iterator to get the first (and
     * only) object and extract the key and data from it
     */
    auto it = object.begin();
    name = it.key();
    auto data = it.value();

    // Expect a single item in the dictionary, if this is not the case, throw an
    // exception
    if (object.size() > 1) {
        std::stringstream ss;
        ss << "Module::Module expected single item dictionary, got: " << object;
        throw std::runtime_error(ss.str());
    }

    // Each module contains:
    //   startid - mandatory
    //   file - mandatory
    //   header - optional
    size_t expected = 2;
    start = data.at("startid");

    file.assign(srcRoot);
    file.append("/");
    file.append(cb::jsonGet<std::string>(data, "file"));
    file = cb::io::sanitizePath(file);

    auto hfile = data.value("header", "");
    if (!hfile.empty()) {
        header.assign(objRoot);
        header.append("/");
        header.append(hfile);
        header = cb::io::sanitizePath(header);
        ++expected;
    }

    auto ent = data.value("enterprise", -1);
    if (ent != -1) {
        enterprise = gsl::narrow_cast<bool>(ent);
        ++expected;
    }

    if (data.size() != expected) {
        std::stringstream ss;
        ss << "Unknown elements for " << name << ": " << std::endl
           << data << std::endl;
        throw std::runtime_error(ss.str());
    }

    parseEventDescriptorFile();
}

void Module::addEvent(std::unique_ptr<Event> event) {
    if (event->id >= start && event->id < (start + max_events_per_module)) {
        events.push_back(std::move(event));
    } else {
        std::stringstream ss;
        ss << "Event identifier " << event->id
           << " outside the legal range for "
           << "module " << name << "s legal range: " << start << " - "
           << start + max_events_per_module;
        throw std::invalid_argument(ss.str());
    }
}

void Module::createHeaderFile() {
    if (header.empty()) {
        return;
    }

    std::ofstream headerfile;
    headerfile.open(header);
    if (!headerfile.is_open()) {
        throw std::system_error(
                errno, std::system_category(), "Failed to open " + header);
    }

    headerfile << "// This is a generated file, do not edit" << std::endl
               << "#pragma once" << std::endl;

    for (const auto& ev : events) {
        std::string nm(name);
        nm.append("_AUDIT_");
        nm.append(ev->name);
        std::replace(nm.begin(), nm.end(), ' ', '_');
        std::transform(nm.begin(), nm.end(), nm.begin(), toupper);

        headerfile << "#define " << nm << " " << ev->id << std::endl;
    }

    headerfile.close();
}
void Module::parseEventDescriptorFile() {
    if (!is_enterprise_edition() && enterprise) {
        // enterprise files should only be loaded for enterprise builds
        return;
    }

    json = load_file(file);
    auto v = cb::jsonGet<int32_t>(json, "version");
    if (v != 1 && v != 2) {
        throw std::runtime_error("Invalid version in " + file + ": " +
                                 std::to_string(v));
    }

    auto n = cb::jsonGet<std::string>(json, "module");
    if (n != name) {
        throw std::runtime_error(name + " can't load a module named " + n);
    }

    // Parse all of the individual events
    auto e = json["events"];
    assert(e.is_array());
    auto it = e.begin();
    while (it != e.end()) {
        auto event = std::make_unique<Event>(*it);
        addEvent(std::move(event));
        ++it;
    }
}


text:
package net.java.cargotracker.interfaces.handling.rest;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Transfer object for handling reports.
 */
// TODO Add internationalized messages for constraints.
@XmlRootElement
public class HandlingReport {

    @NotNull
    @Size(min = 16, max = 16)
    private String completionTime;
    @NotNull
    @Size(min = 4)
    private String trackingId;
    @NotNull
    @Size(min = 4, max = 7)
    private String eventType;
    @NotNull
    @Size(min = 5, max = 5)
    private String unLocode;
    @Size(min = 4, max = 5)
    private String voyageNumber;

    public String getCompletionTime() {
        return completionTime;
    }

    public void setCompletionTime(String value) {
        this.completionTime = value;
    }

    public String getTrackingId() {
        return trackingId;
    }

    public void setTrackingId(String trackingId) {
        this.trackingId = trackingId;
    }

    public String getEventType() {
        return eventType;
    }

    public void setEventType(String value) {
        this.eventType = value;
    }

    public String getUnLocode() {
        return unLocode;
    }

    public void setUnLocode(String value) {
        this.unLocode = value;
    }

    public String getVoyageNumber() {
        return voyageNumber;
    }

    public void setVoyageNumber(String value) {
        this.voyageNumber = value;
    }
}


text:
<?php

defined('_JEXEC') or die;

$input = JFactory::getApplication()->input;
$task = $input->get('task');
if ($task != 'login' && $task != 'logout')
{
	$input->set('task', '');
	$task = '';
}

$controller = JControllerLegacy::getInstance('Login');
$controller->execute($task);
$controller->redirect();


text:
=====================
salt.modules.boto_elb
=====================

.. automodule:: salt.modules.boto_elb
    :members:


text:
import Debug from 'debug'
import program from 'commander'
import chalk from 'chalk'
import request from 'request'
// Feathers
import feathers from 'feathers/client'
import hooks from 'feathers-hooks'
import rest from 'feathers-rest/client'
import authentication from 'feathers-authentication/client'
// Commands
import rootCheck from 'root-check'
import create from './commands/create'
import list from './commands/list'
import login from './commands/login'
import logout from './commands/logout'
import help from './commands/help'
import version from './commands/version'
import authCheck from './utils/auth-check'
import configApp from './utils/config-app'

const debug = Debug('feathers-cli')

export default function () {
  let args = process.argv
  program.debug = debug

  // Check to see if command was run as root and try to downgrade permissions.
  // If that fails show an error and exit out. We don't want to create files as root.
  rootCheck(`
    ${chalk.red("Easy with the 'sudo'.")}

    Since feathers is a user command, there is no need to execute it with root permissions.
    If you're having permission errors when using feathers without sudo, please spend a few
    minutes learning more about how your system should work and make any necessary repairs.

    Two quick solutions are to change where npm stores global packages by putting ~/npm/bin
    in your PATH and running: ${chalk.bold('npm config set prefix ~/npm')} or simply using NVM to manage
    your node environment. See https://github.com/creationix/nvm.
    `)

  authCheck().then(data => {
    program.authToken = data.toString()
  }).catch((err) => {
    if (err) {
      program.authToken = null
    }
  }).then(()=>{
    const app = configApp(program);
    create(program, app)
    list(program, app)
    login(program, app)
    logout(program)
    help(program)
    version(program)
    run()
  })

  const run = () => {
    program.parse(args)
    // Show help if no other command was called
    if (!program.args.length) {
      program.help()
    }
  }

  // Add some extra padding
  process.on('exit', function () {
    console.log()
  })
}


text:
import _ from 'lodash'
import * as axios from 'axios';

export const STAGING_BASE_URL = 'http://localhost:8080/api'
export const PROD_BASE_URL = 'http://localhost:8080/api'
export const VERSION = '1.0.0'
//TODO: add localhost?

//TODO: figure out how to determine staging, prod, dev...
let baseUrl = STAGING_BASE_URL //PROD_BASE_URL
let version = VERSION
let accessToken = null

export function assignAccessToken(token) {
  accessToken = token
}

export function post(path, data) {
  return axios.post(baseUrl + path, data);
}

export function get(path) {
  return axios.get(baseUrl + path);
}

export function delete(path) {
  return axios.delete(baseUrl + path);
}

export function put(path, data) {
  return axios.put(baseUrl + path, data);
}

axios.interceptors.request.use(
  function (config) {
    var headers = { 'Content-Type': 'application/json', 'Accept-Version': version}
    if(accessToken)
      headers['Authorization'] = 'Bearer ' + accessToken
    config['headers'] = headers
    return config
  },
  function (error) {
    return Promise.reject(error);
  });


text:
package ru.job4j;

/**
 * Реализация коллекции Set на связном списке
 * @param <E>
 */
public class SimpleSetOnList<E> extends MyLinkedList<E> {

    /**
     * Проверка наличия данного элемента в коллекции
     * @param e
     * @return true if the collection has the element e
     */
    public boolean contains(E e) {
        boolean findElement = false;

        int index = 0;
        if (e == null) {
            for (Element<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    findElement = true;
                    break;
                }
                index++;
            }
        } else {
            for (Element<E> x = first; x != null; x = x.next) {
                if (e.equals(x.item)) {
                    findElement = true;
                    break;
                }
                index++;
            }
        }
        return findElement;
    }

    /**
     * Добавление элемента в коллекцию, если элемента еще нет в коллекции
     * @param e
     * @return true if element e add the collection
     */
    @Override
    public boolean add(E e) {
        boolean markerGoodAdd;
        if (contains(e)) {
            markerGoodAdd = false;
        } else {
            super.add(e);
            markerGoodAdd = true;
        }
        return markerGoodAdd;
    }

}


text:
<?php

require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

abstract class ControllerTestCase extends
Zend_Test_PHPUnit_ControllerTestCase
{
    protected function setUp()
    {
        $this->bootstrap =
            new Zend_Application(APPLICATION_ENV,
                                 APPLICATION_PATH . '/configs/application.ini');
        parent::setUp();
    }
}


text:
package it.unibz.inf.ontop.answering.reformulation;

import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.answering.OntopQueryEngine;
import it.unibz.inf.ontop.answering.connection.OntopConnection;
import it.unibz.inf.ontop.answering.connection.OntopStatement;
import it.unibz.inf.ontop.answering.reformulation.input.InputQueryFactory;
import it.unibz.inf.ontop.answering.reformulation.input.SelectQuery;
import it.unibz.inf.ontop.answering.resultset.OntopBinding;
import it.unibz.inf.ontop.answering.resultset.OntopBindingSet;
import it.unibz.inf.ontop.answering.resultset.TupleResultSet;
import it.unibz.inf.ontop.exception.*;
import it.unibz.inf.ontop.injection.OntopMappingSQLAllConfiguration;
import it.unibz.inf.ontop.injection.OntopReformulationSQLConfiguration;
import it.unibz.inf.ontop.injection.OntopSystemSQLConfiguration;
import it.unibz.inf.ontop.iq.IQ;
import it.unibz.inf.ontop.iq.UnaryIQTree;
import it.unibz.inf.ontop.iq.node.NativeNode;
import it.unibz.inf.ontop.spec.OBDASpecification;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Optional;

import static java.util.stream.Collectors.joining;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;

/**
 * Examples showing how to separate the offline (OBDA specification extraction) from the online stage
 * (query reformulation or full query answering)
 */
public class OfflineOnlineMarriageTest {

    private static final String OBDA_FILE = "src/test/resources/marriage/marriage.obda";
    private static final String CREATE_DB_FILE = "src/test/resources/marriage/create-db.sql";
    private static final String JDBC_URL = "jdbc:h2:mem:questjunitdb";
    private static final String JDBC_USER = "sa";
    private static final String JDBC_PASSWORD = "";
    private static final Logger LOGGER = LoggerFactory.getLogger(OfflineOnlineMarriageTest.class);
    private static final String PERSON_QUERY_STRING = "PREFIX : <http://example.org/marriage/voc#>\n\n" +
            "SELECT DISTINCT ?x \n" +
            "WHERE {\n" +
            "  ?x a :Person .\n" +
            "}";
    private static final String VAR = "x";
    private static final String PERSON_PREFIX = "http://example.com/person/";

    /*
     * DB connection (keeps it alive)
     */
    private static Connection CONN;

    @BeforeClass
    public static void setUp() throws Exception {

        CONN = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);

        try (Statement st = CONN.createStatement()) {
            String s = Files.lines(Paths.get(CREATE_DB_FILE)).collect(joining());
            st.executeUpdate(s);
            CONN.commit();
        }
    }

    @AfterClass
    public static void tearDown() throws Exception {
        CONN.close();
    }

    @Test
    public void testQueryReformulator() throws OBDASpecificationException, OntopReformulationException {
        QueryReformulator queryReformulator = createReformulator();
        InputQueryFactory inputQueryFactory = queryReformulator.getInputQueryFactory();

        SelectQuery query = inputQueryFactory.createSelectQuery(PERSON_QUERY_STRING);

        IQ executableQuery = queryReformulator.reformulateIntoNativeQuery(query,
                queryReformulator.getQueryLoggerFactory().create(ImmutableMultimap.of()));
        String sqlQuery = Optional.of(executableQuery.getTree())
                .filter(t -> t instanceof UnaryIQTree)
                .map(t -> ((UnaryIQTree) t).getChild().getRootNode())
                .filter(n -> n instanceof NativeNode)
                .map(n -> ((NativeNode) n).getNativeQueryString())
                .orElseThrow(() -> new RuntimeException("Cannot extract the SQL query from\n" + executableQuery));

        assertFalse(sqlQuery.isEmpty());
        LOGGER.info(sqlQuery);
    }

    /**
     * Instantiation of the query reformulator
     */
    private static QueryReformulator createReformulator() throws OBDASpecificationException {

        OBDASpecification obdaSpecification = loadOBDASpecification();

        OntopReformulationSQLConfiguration reformulationConfiguration = OntopReformulationSQLConfiguration.defaultBuilder()
                .obdaSpecification(obdaSpecification)
                .jdbcUrl(JDBC_URL)
                .enableTestMode()
                .build();

        return reformulationConfiguration.loadQueryReformulator();
    }

    private static OBDASpecification loadOBDASpecification() throws OBDASpecificationException {
        OntopMappingSQLAllConfiguration mappingConfiguration = OntopMappingSQLAllConfiguration.defaultBuilder()
                .nativeOntopMappingFile(OBDA_FILE)
                .jdbcUser(JDBC_USER)
                .jdbcPassword(JDBC_PASSWORD)
                .jdbcUrl(JDBC_URL)
                .enableTestMode()
                .build();

        return mappingConfiguration.loadSpecification();
    }

    @Test
    public void testQueryEngine() throws OBDASpecificationException, OntopConnectionException,
            OntopReformulationException, OntopResultConversionException, OntopQueryEvaluationException {
        try (OntopQueryEngine queryEngine = createQueryEngine()) {
            queryEngine.connect();

            try (OntopConnection connection = queryEngine.getConnection();
                 OntopStatement statement = connection.createStatement()) {
                InputQueryFactory inputQueryFactory = connection.getInputQueryFactory();

                SelectQuery query = inputQueryFactory.createSelectQuery(PERSON_QUERY_STRING);
                TupleResultSet resultSet = statement.execute(query);

                ImmutableSet.Builder<String> answerBuilder = ImmutableSet.builder();
                while (resultSet.hasNext()) {
                    OntopBindingSet bindingSet = resultSet.next();
                    OntopBinding binding = bindingSet.getBinding(VAR);
                    if (binding != null)
                        answerBuilder.add(binding.getValue().getValue());
                }

                assertEquals(
                        ImmutableSet.of(PERSON_PREFIX + 1, PERSON_PREFIX + 2, PERSON_PREFIX + 3),
                        answerBuilder.build());
            }
        }
    }

    /**
     * Instantiation of the query engine
     */
    private static OntopQueryEngine createQueryEngine() throws OBDASpecificationException {
        OBDASpecification obdaSpecification = loadOBDASpecification();

        OntopSystemSQLConfiguration systemConfiguration = OntopSystemSQLConfiguration.defaultBuilder()
                .obdaSpecification(obdaSpecification)
                .jdbcUser(JDBC_USER)
                .jdbcPassword(JDBC_PASSWORD)
                .jdbcUrl(JDBC_URL)
                .enableTestMode()
                .build();

        return systemConfiguration.loadQueryEngine();
    }
}


text:
1调整/dev/shm的大小
2iptables:
vi /etc/sysconfig/iptables
-A INPUT -p tcp -m tcp --dport 1521 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 1158 -j ACCEPT
3修改HOSTNAME
vi /etc/hosts
vi /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=centos-oracle
改完,重启一下

依赖包
cd /etc/yum.repos.d
wget http://yum.oracle.com/public-yum-ol6.repo
vi public-yum-ol6.repo
[ol6_latest]
name=Oracle Linux $releasever Latest ($basearch)
baseurl=http://yum.oracle.com/repo/OracleLinux/OL6/latest/$basearch/
gpgkey=http://yum.oracle.com/RPM-GPG-KEY-oracle-ol6
gpgcheck=1
enabled=1

[ol6_UEK_latest]
name=Latest Unbreakable Enterprise Kernel for Oracle Linux $releasever ($basearch)
baseurl=http://yum.oracle.com/repo/OracleLinux/OL6/UEK/latest/$basearch/
gpgkey=http://yum.oracle.com/RPM-GPG-KEY-oracle-ol6
gpgcheck=1
enabled=1

yum install oracle-rdbms-server-11gR2-preinstall

给oracle用户设个密码
passwd oracle
切换到oracle用户,执行一下操作
su oracle
准备
mkdir -p /home/oracle/oradata /home/oracle/fast_recovery_area /home/oracle/etc/ /home/oracle/app /home/oracle/app/oracle/product/11.2.0/dbhome_1 /home/oracle/inventory

http://download.oracle.com/otn/linux/oracle11g/R2/linux.x64_11gR2_database_1of2.zip
http://download.oracle.com/otn/linux/oracle11g/R2/linux.x64_11gR2_database_2of2.zip

解压到/home/oracle/database
提取配置文件
cp /home/oracle/database/response/* /home/oracle/etc/

添加环境变量
vi /etc/profile
umask 022
export ORACLE_BASE=/home/oracle/app
export ORACLE_HOME=$ORACLE_BASE/oracle/product/11.2.0/dbhome_1
export ORACLE_SID=orcl
export PATH=$PATH:$HOME/bin:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib
# NLS_LANG=AMERICAN_AMERICA.ZHS16GBK #中文-系统语言
NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P15
export NLS_LANG

准备安装
vi /home/oracle/etc/db_install.rsp
oracle.install.option=INSTALL_DB_SWONLY // 安装类型
ORACLE_HOSTNAME=centos-oracle // 主机名称(hostname查询)
UNIX_GROUP_NAME=oinstall // 安装组
INVENTORY_LOCATION=/home/oracle/inventory //INVENTORY目录(不填就是默认值)
SELECTED_LANGUAGES=en,zh_CN // 选择语言
ORACLE_HOME=/home/oracle/app/oracle/product/11.2.0/dbhome_1 // oracle_home
ORACLE_BASE==/home/oracle/app // oracle_base
oracle.install.db.InstallEdition=EE // oracle版本
oracle.install.db.isCustomInstall=false //自定义安装,否,使用默认组件
oracle.install.db.DBA_GROUP=dba // dba用户组
oracle.install.db.OPER_GROUP=oinstall // oper用户组
oracle.install.db.config.starterdb.type=GENERAL_PURPOSE //数据库类型
oracle.install.db.config.starterdb.globalDBName=orcl //globalDBName
oracle.install.db.config.starterdb.SID=orcl //SID
oracle.install.db.config.starterdb.memoryLimit=81920 //自动管理内存的内存(M)
oracle.install.db.config.starterdb.password.ALL=oracle //设定所有数据库用户使用同一个密码
SECURITY_UPDATES_VIA_MYORACLESUPPORT=false
DECLINE_SECURITY_UPDATES=true

开始安装
cd database
chmod +x runInstaller install/.oui install/*.sh install/lsnodes  install/unzip
./runInstaller -ignorePrereq -silent -responseFile /home/oracle/etc/db_install.rsp
su root
/home/oracle/inventory/orainstRoot.sh
/home/oracle/app/oracle/product/11.2.0/dbhome_1/root.sh
su oracle
实例基本参数
cd /home/oracle/app/oracle/product/11.2.0/dbhome_1/dbs
cp init.ora  initorcl.ora (init{SID}.ora)
vi initorcl.ora
audit_file_dest='/home/oracle/app/admin/orcl/adump'
db_recovery_file_dest='/home/oracle/app/flash_recovery_area'
diagnostic_dest='/home/oracle/app'

建库
vi /home/oracle/etc/dbca.rsp
GDBNAME = "orcl"
SID = "orcl"
SYSPASSWORD = "oracle"
SYSTEMPASSWORD = "oracle"
SYSMANPASSWORD = "oracle"
DBSNMPPASSWORD = "oracle"
DATAFILEDESTINATION =/home/oracle/oradata
RECOVERYAREADESTINATION=/home/oracle/fast_recovery_area
CHARACTERSET = "AL32UTF8"
TOTALMEMORY = "1638"

执行建库
dbca -silent -responseFile /home/oracle/etc/dbca.rsp
查看oracle实例进程
ps -ef | grep ora_ | grep -v grep
启动监听
lsnrctl start
监听状态
lsnrctl status

登录sqlplus
sqlplus / as sysdba (正常免密码,有密码提示就错了)
startup
查看数据库版本信息
select * from v$version;
查看服务名(Oracle的实例名)
select instance_name from v$instance;
表结构:
desc "SCOTT"."test1";
表数据:
SELECT * FROM "SCOTT"."test1";

激活scott用户
alter user scott account unlock;
alter user scott identified by tiger;
查看所有表:
select table_name from dba_tables where owner='SCOTT';

PL/SQL
select * from "test1" where "id"=2;

退出sql,安装企业管理器:
emca -config dbcontrol db
Database SID: orcl
Listener port number: 1521
Listener ORACLE_HOME [ /home/oracle/app/oracle/product/11.2.0/dbhome_1 ]: 回车
Password for SYS user: oracle
Password for DBSNMP user: oracle
Password for SYSMAN user: oracle
Email address for notifications (optional): 11@qq.com
Outgoing Mail (SMTP) server for notifications (optional): 回车

然后
https://localhost:1158/em/
用户名 sys
口令 oracle
连接身份 sysdba

启动脚本
cd /home/oracle/app/oracle/product/11.2.0/dbhome_1
vi bin/dbstart
#ORACLE_HOME_LISTNER=$1
ORACLE_HOME_LISTNER=$ORACLE_HOME
vi bin/dbshut
#ORACLE_HOME_LISTNER=$1
ORACLE_HOME_LISTNER=$ORACLE_HOME
vi /etc/oratab
orcl:/home/oracle/app/oracle/product/11.2.0/dbhome_1:Y
vi /etc/init.d/oracle
chmod +x /etc/init.d/oracle
详见oracle
chmod +x /etc/rc.d/init.d/oracle
开机启动:
chkconfig --level 345 oracle on
取消开机启动
chkconfig --level 345 oracle off
其他
一.启动
1.#su oracle              切换到oracle用户且切换到它的环境
2.$lsnrctl status           查看监听及数据库状态
3.$lsnrctl start            启动监听
$emctl start dbconsole 启动企业管理器
4.$sqlplus / as sysdba       以DBA身份进入sqlplus
5.SQL>startup                启动db
二.停止
1.#su - oracle              切换到oracle用户且切换到它的环境
2.$lsnrctl stop             停止监听
$emctl stop dbconsole 关闭企业管理器
3.$sqlplus / as sysdba      以DBA身份进入sqlplus
4.SQL>SHUTDOWN IMMEDIATE    关闭db

参考:
http://blog.itpub.net/29510932/viewspace-1135313/
http://blog.csdn.net/Kenny1993/article/details/75038670
解决依赖包
http://www.oracle.com/technetwork/cn/articles/servers-storage-admin/ginnydbinstallonlinux-488779.html
使用脚本自启动oracle
http://blog.csdn.net/u010884123/article/details/55657674
调整/dev/shm的大小
http://blog.51cto.com/2358205/1001537
调整/dev/shm的大小。
修改/etc/fstab,重新mount /dev/shm,然后就可以启动数据库了。

(1)查看/dev/shm 大小
df -k /dev/shm
Filesystem 1K-blocks Used Available Use% Mounted on
tmpfs 4089416 0 4089416 0% /dev/shm
(2)调整/dev/shm大小
vi /etc/fstab
#tmpfs /dev/shm tmpfs defaults 0 0
tmpfs /dev/shm tmpfs defaults,size=10240M 0 0
(3)重新加载
umount /dev/shm
mount /dev/shm
df -k /dev/shm
(4)登陆测试
sqlplus / as sysdba
PL/SQL如何远程连接ORACLE
https://www.cnblogs.com/milantgh/p/4286716.html
企业管理器
http://www.jb51.net/article/53838.htm
在linux上安装完oracle数据库后,如何修改ORACLE_HOSTNAME
https://www.2cto.com/database/201404/291378.html