text:
"""**Pywikibot Exceptions** and warning classes.

This module contains all exception and warning classes used throughout
the framework::

    Exception
     +-- Error
          +-- APIError
          |    +-- APIMWError
          |    +-- UploadError
          +-- AutoblockUserError
          +-- CaptchaError
          +-- InvalidTitleError
          +-- NoUsernameError
          +-- PageInUseError
          +-- PageRelatedError
          |    +-- CircularRedirectError
          |    +-- InterwikiRedirectPageError
          |    +-- IsNotRedirectPageError
          |    +-- IsRedirectPageError
          |    +-- NoMoveTargetError
          |    +-- NoPageError
          |    +-- NotEmailableError
          |    +-- PageLoadRelatedError
          |    |    +-- InconsistentTitleError
          |    |    +-- InvalidPageError
          |    +-- PageSaveRelatedError
          |    |    +-- EditConflictError
          |    |    |    +-- ArticleExistsConflictError
          |    |    |    +-- PageCreatedConflictError
          |    |    |    +-- PageDeletedConflictError
          |    |    +-- LockedPageError
          |    |    |    +-- LockedNoPageError
          |    |    |    +-- CascadeLockedPageError
          |    |    +-- NoCreateError
          |    |    +-- OtherPageSaveError
          |    |    +-- SpamblacklistError
          |    |    +-- TitleblacklistError
          |    |    +-- AbuseFilterDisallowedError
          |    +-- UnsupportedPageError
          +-- SectionError
          +-- ServerError
          |    +-- FatalServerError
          |    +-- Server414Error
          |    +-- Server504Error
          +-- SiteDefinitionError
          |    +-- UnknownFamilyError
          |    +-- UnknownSiteError
          +-- TimeoutError
          |    +-- MaxlagTimeoutError
          +-- TranslationError
          +-- UserRightsError
          |    +-- HiddenKeyError (KeyError)
          +-- UnknownExtensionError (NotImplementedError)
          +-- VersionParseError
          +-- WikiBaseError
               +-- CoordinateGlobeUnknownError (NotImplementedError)
               +-- EntityTypeUnknownError
               +-- NoWikibaseEntityError

    UserWarning
     +-- ArgumentDeprecationWarning (FutureWarning)
     +-- FamilyMaintenanceWarning

    RuntimeWarning
     +-- NotImplementedWarning

Error: Base class, all exceptions should the subclass of this class.

  - NoUsernameError: Username is not in user-config.py, or it is invalid.
  - AutoblockUserError: requested action on a virtual autoblock user not valid
  - TranslationError: no language translation found
  - UserRightsError: insufficient rights for requested action
  - InvalidTitleError: Invalid page title
  - CaptchaError: Captcha is asked and config.solve_captcha == False
  - i18n.TranslationError: i18n/l10n message not available
  - PageInUseError: Page cannot be reserved due to a lock
  - UnknownExtensionError: Extension is not defined for this site
  - VersionParseError: failed to parse version information
  - SectionError: The section specified by # does not exist

APIError: wiki API returned an error

  - APIMWError: MediaWiki internal exception
  - UploadError: upload failed

SiteDefinitionError: Site loading problem

  - UnknownSiteError: Site does not exist in Family
  - UnknownFamilyError: Family is not registered

PageRelatedError: any exception which is caused by an operation on a Page.

  - NoPageError: Page does not exist
  - UnsupportedPageError: Page is not supported due to a namespace restriction
  - IsRedirectPageError: Page is a redirect page
  - IsNotRedirectPageError: Page is not a redirect page
  - CircularRedirectError: Page is a circular redirect
  - InterwikiRedirectPageError: Page is a redirect to another site
  - InvalidPageError: Page is invalid e.g. without history
  - NotEmailableError: The target user has disabled email
  - NoMoveTargetError: An expected move target page does not exist

PageLoadRelatedError: any exception which happens while loading a Page.
  - InconsistentTitleError: Page receives a title inconsistent with query

PageSaveRelatedError: page exceptions within the save operation on a Page

  - AbuseFilterDisallowedError: AbuseFilter disallowed
  - SpamblacklistError: MediaWiki spam filter detected a blacklisted URL
  - TitleblacklistError: MediaWiki detected a blacklisted page title
  - OtherPageSaveError: misc. other save related exception.
  - LockedPageError: Page is locked
      - LockedNoPageError: Title is locked against creation
      - CascadeLockedPageError: Page is locked due to cascading protection
  - EditConflictError: Edit conflict while uploading the page
      - PageDeletedConflictError: Page was deleted since being retrieved
      - PageCreatedConflictError: Page was created by another user
      - ArticleExistsConflictError: Page article already exists
  - NoCreateError: parameter nocreate not allow page creation

ServerError: a problem with the server.

  - FatalServerError: A fatal/non-recoverable server error
  - Server414Error: Server timed out with HTTP 414 code
  - Server504Error: Server timed out with HTTP 504 code

WikiBaseError: any issue specific to Wikibase.

  - NoWikibaseEntityError: entity doesn't exist
  - CoordinateGlobeUnknownError: globe is not implemented yet.
  - EntityTypeUnknownError: entity type is not available on the site.

TimeoutError: request failed with a timeout

  - MaxlagTimeoutError: request failed with a maxlag timeout

DeprecationWarning: old functionality replaced by new functionality

PendingDeprecationWarning: problematic code which has not yet been
fully deprecated, possibly because a replacement is not available

RuntimeWarning: problems developers should have fixed, and users need to
be aware of its status.

  - NotImplementedWarning: functionality not implemented

UserWarning: warnings targeted at users

  - config._ConfigurationDeprecationWarning: user configuration file problems
  - login._PasswordFileWarning: password file problems
  - ArgumentDeprecationWarning: command line argument problems
  - FamilyMaintenanceWarning: missing information in family definition

.. versionchanged:: 6.0
   exceptions were renamed and are ending with "Error".

.. versionchanged:: 7.0
   All Pywikibot Error exceptions must be imported from
   ``pywikibot.exceptions``. Deprecated exceptions identifiers were
   removed.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import re
from typing import Any, Optional, Union

import pywikibot
from pywikibot.tools import issue_deprecation_warning
from pywikibot.tools._deprecate import _NotImplementedWarning

class NotImplementedWarning(_NotImplementedWarning):

    """Feature that is no longer implemented."""

class ArgumentDeprecationWarning(UserWarning, FutureWarning):

    """Command line argument that is no longer supported."""

class FamilyMaintenanceWarning(UserWarning):

    """Family class is missing definitions."""

class Error(Exception):

    """Pywikibot error."""

    def __init__(self, arg: str) -> None:
        """Initializer."""
        self.unicode = arg

    def __str__(self) -> str:
        """Return a string representation."""
        return self.unicode

class APIError(Error):

    """The wiki site returned an error message."""

    def __init__(self, code: str, info: str, **kwargs: Any) -> None:
        """Save error dict returned by MW API."""
        self.code = code
        self.info = info
        self.other = kwargs
        self.unicode = self.__str__()

    def __repr__(self) -> str:
        """Return internal representation."""
        return '{name}("{code}", "{info}", {other})'.format(
            name=self.__class__.__name__, **self.__dict__)

    def __str__(self) -> str:
        """Return a string representation."""
        if self.other:
            return '{}: {}\n[{}]'.format(
                self.code,
                self.info,
                ';\n '.join(
                    '{}: {}'.format(key, val)
                    for key, val in self.other.items()))

        return '{}: {}'.format(self.code, self.info)

class APIMWError(APIError):

    """The API site returned an error about a MediaWiki internal exception."""

    def __init__(self, mediawiki_exception_class_name: str, info: str,
                 **kwargs: Any) -> None:
        """Save error dict returned by MW API."""
        self.mediawiki_exception_class_name = mediawiki_exception_class_name
        code = 'internal_api_error_' + mediawiki_exception_class_name
        super().__init__(code, info, **kwargs)

class UploadError(APIError):

    """Upload failed with a warning message (passed as the argument)."""

    def __init__(self, code: str, message: str,
                 file_key: Optional[str] = None,
                 offset: Union[int, bool] = 0) -> None:
        """
        Create a new UploadError instance.

        :param file_key: The file_key of the uploaded file to reuse it later.
            If no key is known or it is an incomplete file it may be None.
        :param offset: The starting offset for a chunked upload. Is False when
            there is no offset.
        """
        super().__init__(code, message)
        self.file_key = file_key
        self.offset = offset

    @property
    def message(self) -> str:
        """Return warning message."""
        return self.info

class PageRelatedError(Error):

    """
    Abstract Exception, used when the exception concerns a particular Page.

    This class should be used when the Exception concerns a particular
    Page, and when a generic message can be written once for all.
    """

    # Preformatted message where the page title will be inserted.
    # Override this in subclasses.
    message = ''

    def __init__(self, page: 'pywikibot.page.BasePage',
                 message: Optional[str] = None) -> None:
        """
        Initializer.

        :param page: Page that caused the exception
        """
        if message:
            self.message = message

        if self.message is None:
            raise Error("PageRelatedError is abstract. Can't instantiate it!")

        self.page = page
        self.title = page.title(as_link=True)
        self.site = page.site

        if re.search(r'\{\w+\}', self.message):
            msg = self.message.format_map(self.__dict__)
        elif re.search(r'%\(\w+\)s', self.message):
            issue_deprecation_warning("'%' style messages are deprecated, "
                                      'please use str.format() style instead',
                                      since='6.2.0')
            msg = self.message % self.__dict__
        elif '%s' in self.message:
            msg = self.message % page
        else:
            msg = self.message.format(page)

        super().__init__(msg)

class PageSaveRelatedError(PageRelatedError):

    """Saving the page has failed."""

    message = 'Page {} was not saved.'

class OtherPageSaveError(PageSaveRelatedError):

    """Saving the page has failed due to uncatchable error."""

    message = 'Edit to page {title} failed:\n{reason}'

    def __init__(self, page: 'pywikibot.page.Page',
                 reason: Union[str, Exception]) -> None:
        """Initializer.

        :param reason: Details of the problem
        """
        self.reason = reason
        super().__init__(page)

    @property
    def args(self) -> str:  # type: ignore[override]
        """Expose args."""
        return str(self.reason)

class NoUsernameError(Error):

    """Username is not in user-config.py."""

class NoPageError(PageRelatedError):

    """Page does not exist."""

    message = "Page {} doesn't exist."

class UnsupportedPageError(PageRelatedError):

    """Unsupported page due to namespace restriction."""

    # namespaces < 0 aren't supported (T169213)
    message = 'Page {} is not supported due to namespace restriction.'

class NoMoveTargetError(PageRelatedError):

    """Expected move target page not found."""

    message = 'Move target page of {} not found.'

class PageLoadRelatedError(PageRelatedError):

    """Loading the contents of a Page object has failed."""

    message = 'Page {} was not loaded.'

class InconsistentTitleError(PageLoadRelatedError):

    """Page receives a title inconsistent with query."""

    def __init__(self, page: 'pywikibot.page.Page', actual: str) -> None:
        """Initializer.

        :param page: Page that caused the exception
        :param actual: title obtained by query

        """
        self.message = "Query on {{}} returned data on '{}'".format(actual)
        super().__init__(page)

class SiteDefinitionError(Error):

    """Site does not exist."""

class UnknownSiteError(SiteDefinitionError):

    """Site does not exist in Family."""

class UnknownFamilyError(SiteDefinitionError):

    """Family is not registered."""

class UnknownExtensionError(Error, NotImplementedError):

    """Extension is not defined."""

class VersionParseError(Error):

    """Failed to parse version information."""

class IsRedirectPageError(PageRelatedError):

    """Page is a redirect page."""

    message = 'Page {} is a redirect page.'

class IsNotRedirectPageError(PageRelatedError):

    """Page is not a redirect page."""

    message = 'Page {} is not a redirect page.'

class CircularRedirectError(PageRelatedError):

    """Page is a circular redirect.

    Exception argument is the redirect target; this may be the same title
    as this page or a different title (in which case the target page directly
    or indirectly redirects back to this one)

    """

    message = 'Page {} is a circular redirect.'

class InterwikiRedirectPageError(PageRelatedError):

    """
    Page is a redirect to another site.

    This is considered invalid in Pywikibot. See bug T75184.

    """

    message = ('Page redirects to a page on another Site.\n'
               'Page: {page}\n'
               'Target page: {target_page} on {target_site}.')

    def __init__(self, page: 'pywikibot.page.Page',
                 target_page: 'pywikibot.page.Page') -> None:
        """Initializer.

        :param target_page: Target page of the redirect.
        """
        self.target_page = target_page
        self.target_site = target_page.site
        super().__init__(page)

class InvalidPageError(PageLoadRelatedError):

    """Missing page history.

    .. versionadded:: 6.2
    """

    message = 'Page {} is invalid.'

class InvalidTitleError(Error):

    """Invalid page title."""

class LockedPageError(PageSaveRelatedError):

    """Page is locked."""

    message = 'Page {} is locked.'

class LockedNoPageError(LockedPageError):

    """Title is locked against creation."""

    message = 'Page {} does not exist and is locked preventing creation.'

class CascadeLockedPageError(LockedPageError):

    """Page is locked due to cascading protection."""

    message = 'Page {} is locked due to cascading protection.'

class SectionError(Error):

    """The section specified by # does not exist."""

class NoCreateError(PageSaveRelatedError):

    """Parameter nocreate doesn't allow page creation."""

    message = 'Page {} could not be created due to parameter nocreate'

class EditConflictError(PageSaveRelatedError):

    """There has been an edit conflict while uploading the page."""

    message = 'Page {} could not be saved due to an edit conflict'

class PageDeletedConflictError(EditConflictError):

    """Page was deleted since being retrieved."""

    message = 'Page {} has been deleted since last retrieved.'

class PageCreatedConflictError(EditConflictError):

    """Page was created by another user."""

    message = 'Page {} has been created since last retrieved.'

class ArticleExistsConflictError(EditConflictError):

    """Page already exists."""

    message = ('Destination article {} already exists and is not a redirect '
               'to the source article')

class AbuseFilterDisallowedError(PageSaveRelatedError):

    """Page save failed because the AbuseFilter disallowed it."""

    message = ('Edit to page {title} disallowed by the AbuseFilter.\n'
               '{info}')

    def __init__(self, page: 'pywikibot.page.Page', info: str) -> None:
        """Initializer."""
        self.info = info
        super().__init__(page)

class SpamblacklistError(PageSaveRelatedError):

    """Page save failed because MediaWiki detected a blacklisted spam URL."""

    message = ('Edit to page {title} rejected by spam filter due to '
               'content:\n{url}')

    def __init__(self, page: 'pywikibot.page.Page', url: str) -> None:
        """Initializer."""
        self.url = url
        super().__init__(page)

class TitleblacklistError(PageSaveRelatedError):

    """Page save failed because MediaWiki detected a blacklisted page title."""

    message = 'Page {} is title-blacklisted.'

class ServerError(Error):

    """Got unexpected server response."""

class FatalServerError(ServerError):

    """A fatal server error will not be corrected by resending the request."""

class Server504Error(ServerError):

    """Server timed out with HTTP 504 code."""

class Server414Error(ServerError):

    """Server returned with HTTP 414 code."""

class CaptchaError(Error):

    """Captcha is asked and config.solve_captcha == False."""

class AutoblockUserError(Error):

    """Requested action on a virtual autoblock user not valid.

    The class AutoblockUserError is an exception that is raised whenever
    an action is requested on a virtual autoblock user that's not available
    for him (i.e. roughly everything except unblock).
    """

class TranslationError(Error, ImportError):

    """Raised when no correct translation could be found.

    Inherits from ImportError, as this exception is now used
    where previously an ImportError would have been raised,
    and may have been caught by scripts as such.
    """

class UserRightsError(Error):

    """Insufficient user rights to perform an action."""

class HiddenKeyError(UserRightsError, KeyError):

    """Insufficient user rights to view the hidden key."""

class NotEmailableError(PageRelatedError):

    """This user is not emailable."""

    message = '{} is not emailable.'

class PageInUseError(Error):

    """Page cannot be reserved for writing due to existing lock."""

class WikiBaseError(Error):

    """Wikibase related error."""

class NoWikibaseEntityError(WikiBaseError):

    """This entity doesn't exist."""

    def __init__(self, entity: 'pywikibot.page.WikibaseEntity') -> None:
        """
        Initializer.

        :param entity: Wikibase entity
        """
        super().__init__("Entity '{}' doesn't exist on {}"
                         .format(entity.id, entity.repo))
        self.entity = entity

class CoordinateGlobeUnknownError(WikiBaseError, NotImplementedError):

    """This globe is not implemented yet in either WikiBase or pywikibot."""

class EntityTypeUnknownError(WikiBaseError):

    """The requested entity type is not recognised on this site."""

class TimeoutError(Error):

    """Request failed with a timeout error."""

class MaxlagTimeoutError(TimeoutError):

    """Request failed with a maxlag timeout error."""


text:
using namespace v8;

extern "C" void InitAll(Handle<Object> exports) {
  Map::Init(exports);
  MapEntry::Init(exports);
  Set::Init(exports);
  Vector::Init(exports);
  VectorModifier::Init(exports);
}

NODE_MODULE(NativeTypes, InitAll)

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import subprocess
import pickle

if len(sys.argv) < 2:
    print "Missing arguments"
    print "Usage: python %s <file.pcap>" % os.path.basename(sys.argv[0])
    exit(1)

infile = sys.argv[1]

if not os.path.exists(infile):
    print "The specified file does not exist"
    exit(1)

if os.path.splitext(infile)[1] != ".pcap":
    print "The specified file is not a PCAP file"
    exit(1)

fields = {}
fields["frame.number"] = 0
fields["frame.time_epoch"] = 1
fields["ipv6.src"] = 2
fields["ipv6.dst"] = 3
fields["udp"] = 4
fields["data.data"] = 5
fields["http"] = 6
fields["icmpv6"] = 7
fields["icmpv6.type"] = 8
fields["icmpv6.opt.prefix"] = 9
fields["icmpv6.nd.ns.target_address"] = 10
fields["icmpv6.nd.na.target_address"] = 11
fields["icmpv6.opt.linkaddr"] = 12
fields["ipv6.hlim"] = 13
fields["6lowpan"] = 14
fields["6lowpan.src"] = 15
fields["6lowpan.dst"] = 16

tshark_base = "tshark -r %s -R '!dns' -C tshark-6lbr-raw-udp -Tfields -Eseparator='|'"

tshark_export = ""
for k in sorted(fields, key=fields.get):
    tshark_export = tshark_export + " -e%s" % k

tshark_cmd = tshark_base + tshark_export
capdump = subprocess.check_output((tshark_cmd % infile),shell=True)

capture = []

for line in capdump.split('\n'):
    if not line:
        continue
    rawinfo = line.split('|')
    info = {}
    info["number"] = rawinfo[fields["frame.number"]]
    info["time"] = rawinfo[fields["frame.time_epoch"]]
    info["src"] = rawinfo[fields["ipv6.src"]]
    info["dst"] = rawinfo[fields["ipv6.dst"]]
    info["hoplimit"] = rawinfo[fields["ipv6.hlim"]]

    if rawinfo[fields["icmpv6"]] == "icmpv6":
        if rawinfo[fields["icmpv6.type"]] == "133":
            info["type"] = "ndp_rs"
        elif rawinfo[fields["icmpv6.type"]] == "134":
            info["type"] = "ndp_ra"
            info["prefix"] = rawinfo[fields["icmpv6.opt.prefix"]]
        elif rawinfo[fields["icmpv6.type"]] == "135":
            info["type"] = "ndp_ns"
            info["target"] = rawinfo[fields["icmpv6.nd.ns.target_address"]]
        elif rawinfo[fields["icmpv6.type"]] == "136":
            info["type"] = "ndp_na"
            info["target"] = rawinfo[fields["icmpv6.nd.na.target_address"]]
            info["link"] = rawinfo[fields["icmpv6.nd.na.target_address"]]
        elif rawinfo[fields["icmpv6.type"]] == "128":
            info["type"] = "echo_request"
        elif rawinfo[fields["icmpv6.type"]] == "129":
            info["type"] = "echo_reply"
        elif rawinfo[fields["icmpv6.type"]] == "1":
            info["type"] = "unreach"
        else:
            info["type"] = "icmpv6_other"
            info["code"] = rawinfo[fields["icmpv6.type"]]
    elif rawinfo[fields["udp"]].startswith("User Datagram Protocol"):
        info["type"] = "udp"
        info["data"] = rawinfo[fields["data.data"]]
    elif rawinfo[fields["http"]] == "http":
        info["type"] = "http"
    else:
        info["type"] = "other"

    capture.append(info)

outfile = infile.replace(".pcap",".pkl")
pickle.dump(capture,open(outfile,"wb"))


text:
package com.summer.portal.controller;

import com.summer.common.pojo.SummerResult;
import com.summer.common.utils.ExceptionUtil;
import com.summer.portal.service.StaticPageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by toy on 7/16/16.
 */
@Controller
public class StaticPageController {
    @Autowired
    private StaticPageService staticPageService;

    @RequestMapping("/gen/item/{itemId}")
    @ResponseBody
    public SummerResult genItemPage(@PathVariable Long itemId) {
        try {
            SummerResult result = staticPageService.genItemHtml(itemId);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return SummerResult.build(500, ExceptionUtil.getStackTrace(e));
        }
    }
}


text:
require "oo/haunted_house"

describe 'climb command' do
  context "blasted tree" do
    before { @house = Oo::HauntedHouse.new(7) }

    specify "should have correct description" do
      @house.rooms.current_room.description.should eql("Blasted Tree")
    end

    context "climb up rope" do
      before { climb }
      specify { @message.should eql("You see a thick forest and a cliff south.") }
    end

    context "climb down rope" do
      before { climb; climb }
      specify { @message.should eql("Going down!") }
    end
  end

  context "other room" do
    before { @house = Oo::HauntedHouse.new(0) }

    context "climb rope" do
      before do
        @house.rooms.inventory.carry(Oo::Things::ROPE)
        climb
      end
      specify { @message.should eql("It isn't attached to anything!") }
    end
  end

  def climb
    parser = Oo::Command::Parser.new(@house)
    @message = parser.parse_input("climb rope")
  end
end


text:
<?php

namespace Satooshi\Bundle\PersonBundle\Tests\Entity;

use Satooshi\Bundle\PersonBundle\Entity\Person;

/**
 * @covers \Satooshi\Bundle\PersonBundle\Entity\Person
 *
 * @group unit
 * @group entity
 */
class PersonAccessorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Satooshi\Bundle\PersonBundle\Entity\Person
     */
    protected $obj;

    protected function setUp()
    {
        $this->obj = new Person();
    }

    public function testConstruction()
    {
        $this->assertNull($this->obj->getId());
        $this->assertNull($this->obj->getName());
        $this->assertNull($this->obj->getEmail());
        $this->assertFalse($this->obj->getIsMarried());
        $this->assertCount(0, $this->obj->getFriends());
    }

    public function testSetName()
    {
        $expected = 'name';

        $self = $this->obj->setName($expected);

        $this->assertEquals($this->obj->getName(), $expected);
        $this->assertSame($self, $this->obj);
    }

    public function testSetEmail()
    {
        $expected = 'email@example.com';

        $self = $this->obj->setEmail($expected);

        $this->assertEquals($this->obj->getEmail(), $expected);
        $this->assertSame($self, $this->obj);
    }

    public function testSetIsMarriedTrue()
    {
        $self = $this->obj->setIsMarried(true);

        $this->assertTrue($this->obj->getIsMarried());
        $this->assertSame($self, $this->obj);
    }

    public function testSetIsMarriedFalse()
    {
        $self = $this->obj->setIsMarried(false);

        $this->assertFalse($this->obj->getIsMarried());
        $this->assertSame($self, $this->obj);
    }

    public function testAddFriend()
    {
        $expected = new Person();

        $self = $this->obj->addFriend($expected);

        $this->assertCount(1, $this->obj->getFriends());

        $friends = $this->obj->getFriends();
        $this->assertSame($expected, $friends[0]);

        $this->assertSame($self, $this->obj);
    }

    public function testRemoveFriend()
    {
        $expected = new Person();

        $this->obj->addFriend($expected);
        $this->obj->removeFriend($expected);

        $this->assertCount(0, $this->obj->getFriends());
    }
}


text:
package org.wiztools.restclient.ui;

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.inject.Inject;
import javax.swing.*;
import org.wiztools.restclient.MessageI18N;
import org.wiztools.restclient.RCConstants;

/**
 *
 * @author schandran
 */
class AboutDialog extends EscapableDialog {

    private AboutDialog me = this;

    @Inject
    public AboutDialog(RESTUserInterface ui){
        super(ui.getFrame(), true);
    }

    @Inject
    protected void init(){
        // Title
        setTitle("About");

        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createEmptyBorder(
                RESTViewImpl.BORDER_WIDTH,
                RESTViewImpl.BORDER_WIDTH,
                RESTViewImpl.BORDER_WIDTH,
                RESTViewImpl.BORDER_WIDTH));
        jp.setLayout(new BorderLayout());

        JPanel jp_north = new JPanel();
        jp_north.setLayout(new FlowLayout(FlowLayout.CENTER));
        JLabel jl_title = new JLabel(
                "
" +
                RCConstants.TITLE + RCConstants.VERSION +
                "
");
        jp_north.add(jl_title);
        jp.add(jp_north, BorderLayout.NORTH);

        JPanel jp_center = new JPanel();
        jp_center.setLayout(new GridLayout(1, 1));
        JTextPane jtp = new JTextPane();
        jtp.setEditable(false);
        jtp.setContentType("text/html");
        jtp.setText(MessageI18N.getMessage("menu.help.about"));
        jp_center.add(new JScrollPane(jtp));
        jp.add(jp_center, BorderLayout.CENTER);

        JPanel jp_south = new JPanel();
        jp_south.setLayout(new FlowLayout(FlowLayout.CENTER));
        JButton jb_ok = new JButton("Ok");
        jb_ok.setMnemonic('o');
        jb_ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                hideMe();
            }
        });
        getRootPane().setDefaultButton(jb_ok);
        jp_south.add(jb_ok);
        jp.add(jp_south, BorderLayout.SOUTH);

        setContentPane(jp);

        pack();

        jb_ok.requestFocus();
    }

    @Override
    public void doEscape(AWTEvent event) {
        hideMe();
    }

    public void hideMe(){
        me.setVisible(false);
    }

}


text:
<!DOCTYPE html>

    <title>Peripheral Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

 Docs (44% documented)

         Reference

        Peripheral Class Reference

            Classes

                Bluejay

                Peripheral

                SynchronizedPeripheral

            Enums

                BackgroundRestoreMode

                ConnectionResult

                DisconnectionResult

                DiscoveryResult

                ListenAction

                ReadResult

                RunResult

                ScanAction

                WriteResult

            Extensions

                CBManagerState

                CBPeripheral

                CBPeripheralState

                CBService

                Data

                Integer

                Notification

                String

            Protocols

                ConnectionObserver

                ListenRestorer

                RSSIObserver

                Receivable

                Sendable

            Structs

                CharacteristicIdentifier

                DataPadding

                PeripheralIdentifier

                ScanDiscovery

                ServiceIdentifier

Peripheral

Undocumented

Attributes

                    uuid

Undocumented

                    name

Undocumented

RSSI Event

                    readRSSI()

Undocumented

                    register(observer:)

Undocumented

                    unregister(observer:)

Undocumented

Actions

                    read(from:completion:)

Read from a specified characteristic.

Declaration

Swift

public func read<R: Receivable>(from characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

                    write(to:value:completion:)

Write to a specified characteristic.

Declaration

Swift

public func write<S: Sendable>(to characteristicIdentifier: CharacteristicIdentifier, value: S, completion: @escaping (WriteResult) -> Void)

                    isListening(to:)

Undocumented

                    listen(to:completion:)

Listen for notifications on a specified characterstic.

Declaration

Swift

public func listen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

                    endListen(to:error:completion:)

End listening on a specified characteristic.

Provides the ability to suppress the failure message to the listen callback. This is useful in the internal implimentation of some of the listening logic, since we want to be able to share the clear logic on a .done exit, but don’t need to send a failure in that case.

Note

    Note
Currently this can also cancel a regular in-progress read as well, but that behaviour may change down the road.

Declaration

Swift

public func endListen(to characteristicIdentifier: CharacteristicIdentifier, error: Swift.Error? = nil, completion: ((WriteResult) -> Void)? = nil)

                    restoreListen(to:completion:)

Restore a (believed to be) active listening session, so if we start up in response to a notification, we can receive it.

Declaration

Swift

public func restoreListen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

                    peripheral(_:didDiscoverServices:)

Undocumented

                    peripheral(_:didDiscoverCharacteristicsFor:error:)

Undocumented

                    peripheral(_:didWriteValueFor:error:)

Undocumented

                    peripheral(_:didUpdateValueFor:error:)

Undocumented

                    peripheral(_:didUpdateNotificationStateFor:error:)

Undocumented

                    peripheral(_:didReadRSSI:error:)

Undocumented

© 2017 . All rights reserved. (Last updated: 2017-06-02)

Generated by jazzy ♪♫ v0.8.2, a Realm project.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using HtmlAgilityPack;

namespace EasySense.Helpers
{
    sealed class HtmlFilter
    {
        private static volatile HtmlFilter _instance;
        private static object _root = new object();

        private HtmlFilter() { }

        public static HtmlFilter Instance
        {
            get
            {
                if (_instance == null)
                    lock (_root)
                        if (_instance == null)
                            _instance = new HtmlFilter();

                return _instance;
            }
        }

        // Original list courtesy of Robert Beal :
        // http://www.robertbeal.com/

        private static readonly Dictionary<string, string[]> ValidHtmlTags =
            new Dictionary<string, string[]>
        {
            {"p", new string[]          {"style", "class", "align"}},
            {"div", new string[]        {"style", "class", "align"}},
            {"span", new string[]       {"style", "class"}},
            {"br", new string[]         {"style", "class"}},
            {"hr", new string[]         {"style", "class"}},
            {"label", new string[]      {"style", "class"}},

            {"small", new string[]      {"style", "class"}},
            {"big", new string[]      {"style", "class"}},
            {"center", new string[]      {"style", "class"}},

            {"h1", new string[]         {"style", "class"}},
            {"h2", new string[]         {"style", "class"}},
            {"h3", new string[]         {"style", "class"}},
            {"h4", new string[]         {"style", "class"}},
            {"h5", new string[]         {"style", "class"}},
            {"h6", new string[]         {"style", "class"}},

            {"font", new string[]       {"style", "class",
				"color", "face", "size"}},
            {"strong", new string[]     {"style", "class"}},
            {"b", new string[]          {"style", "class"}},
            {"em", new string[]         {"style", "class"}},
            {"i", new string[]          {"style", "class"}},
            {"u", new string[]          {"style", "class"}},
            {"strike", new string[]     {"style", "class"}},
            {"ol", new string[]         {"style", "class"}},
            {"ul", new string[]         {"style", "class"}},
            {"li", new string[]         {"style", "class"}},
            {"blockquote", new string[] {"style", "class"}},
            {"code", new string[]       {"style", "class"}},
			{"pre", new string[]       {"style", "class"}},
            {"sub",new string[]{"style","class"}},
            {"sup",new string[]{"style","class"}},

            {"a", new string[]          {"style", "class", "href", "title","name","target"}},
            {"img", new string[]        {"style", "class", "src", "height",
				"width", "alt", "title", "hspace", "vspace", "border"}},

            {"table", new string[]      {"style", "class","align","border","cellpadding","cellspacing","summary"}},
            {"caption",new string[]{"style","class"}},
            {"thead", new string[]      {"style", "class"}},
            {"tbody", new string[]      {"style", "class"}},
            {"tfoot", new string[]      {"style", "class"}},
            {"th", new string[]         {"style", "class", "scope"}},
            {"tr", new string[]         {"style", "class"}},
            {"td", new string[]         {"style", "class", "colspan"}},

            {"q", new string[]          {"style", "class", "cite"}},
            {"cite", new string[]       {"style", "class"}},
            {"abbr", new string[]       {"style", "class"}},
            {"acronym", new string[]    {"style", "class"}},
            {"del", new string[]        {"style", "class"}},
            {"ins", new string[]        {"style", "class"}},
            {"address",new string[]{"style","class"}}
        };

        /// <summary>
        /// Takes raw HTML input and cleans against a whitelist
        /// </summary>
        /// <param name="source">Html source</param>
        /// <returns>Clean output</returns>
        public string SanitizeHtml(string source)
        {
            HtmlDocument html = GetHtml(source);
            if (html == null) return string.Empty;

            // All the nodes
            HtmlNode allNodes = html.DocumentNode;

            // Select whitelist tag names
            string[] whitelist = (from kv in ValidHtmlTags
                                  select kv.Key).ToArray();

            // Scrub tags not in whitelist
            CleanNodes(allNodes, whitelist);

            // Filter the attributes of the remaining
            foreach (KeyValuePair<string, string[]> tag in ValidHtmlTags)
            {
                IEnumerable<HtmlNode> nodes = (from n in allNodes.DescendantsAndSelf()
                                               where n.Name == tag.Key
                                               select n);

                // No nodes? Skip.
                if (nodes == null) continue;

                foreach (var n in nodes)
                {
                    // No attributes? Skip.
                    if (!n.HasAttributes) continue;

                    // Get all the allowed attributes for this tag
                    HtmlAttribute[] attr = n.Attributes.ToArray();
                    foreach (HtmlAttribute a in attr)
                    {
                        if (!tag.Value.Contains(a.Name))
                        {
                            a.Remove(); // Attribute wasn't in the whitelist
                        }
                        else
                        {
                            // *** New workaround. This wasn't necessary with the old library
                            if (a.Name == "href" || a.Name == "src")
                            {
                                a.Value = (!string.IsNullOrEmpty(a.Value)) ? a.Value.Replace("\r", "").Replace("\n", "") : "";
                                a.Value =
                                    (!string.IsNullOrEmpty(a.Value) &&
                                    (a.Value.IndexOf("javascript") < 10 || a.Value.IndexOf("eval") < 10)) ?
                                    a.Value.Replace("javascript", "").Replace("eval", "") : a.Value;
                            }
                            /*
                        else if (a.Name == "class" || a.Name == "style")
                        {
                            a.Value =
                                Microsoft.Security.Application.Encoder.CssEncode(a.Value);
                        }
                             * */
                            else
                            {
                                a.Value =
                                    Microsoft.Security.Application.Encoder.HtmlAttributeEncode(a.Value);
                            }
                        }
                    }
                }
            }

            // *** New workaround (DO NOTHING HAHAHA! Fingers crossed)
            return allNodes.InnerHtml;

            // *** Original code below

            /*
            // Anything we missed will get stripped out
            return
                Microsoft.<span class="goog_qs-tidbit goog_qs-tidbit-0">Security.Application.Sanitizer.GetSafeHtmlFragment(allNodes.InnerHtml);
             */
        }

        /// <summary>
        /// Takes a raw source and removes all HTML tags
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public string StripHtml(string source)
        {
            source = SanitizeHtml(source);

            // No need to continue if we have no clean Html
            if (string.IsNullOrEmpty(source))
                return string.Empty;

            HtmlDocument html = GetHtml(source);
            StringBuilder result = new StringBuilder();

            // For each node, extract only the innerText
            foreach (HtmlNode node in html.DocumentNode.ChildNodes)
                result.Append(node.InnerText);

            return result.ToString();
        }

        /// <summary>
        /// Recursively delete nodes not in the whitelist
        /// </summary>
        private static void CleanNodes(HtmlNode node, string[] whitelist)
        {
            if (node.NodeType == HtmlNodeType.Element)
            {
                if (!whitelist.Contains(node.Name))
                {
                    node.ParentNode.RemoveChild(node);
                    return; // We're done
                }
            }

            if (node.HasChildNodes)
                CleanChildren(node, whitelist);
        }

        /// <summary>
        /// Apply CleanNodes to each of the child nodes
        /// </summary>
        private static void CleanChildren(HtmlNode parent, string[] whitelist)
        {
            for (int i = parent.ChildNodes.Count - 1; i >= 0; i--)
                CleanNodes(parent.ChildNodes[i], whitelist);
        }

        /// <summary>
        /// Helper function that returns an HTML document from text
        /// </summary>
        private static HtmlDocument GetHtml(string source)
        {
            HtmlDocument html = new HtmlDocument();
            html.OptionFixNestedTags = true;
            html.OptionAutoCloseOnEnd = true;
            html.OptionDefaultStreamEncoding = Encoding.UTF8;

            html.LoadHtml(source??"");

            // Encode any code blocks independently so they won't
            // be stripped out completely when we do a final cleanup
            foreach (var n in html.DocumentNode.DescendantsAndSelf())
            {
                if (n.Name == "code")
                {
                    //** Code tag attribute vulnerability fix 28-9-12 (thanks to Natd)
                    HtmlAttribute[] attr = n.Attributes.ToArray();
                    foreach (HtmlAttribute a in attr)
                    {
                        if (a.Name != "style" && a.Name != "class") { a.Remove(); }
                    } //** End fix
                    n.InnerHtml = Microsoft.Security.Application.Encoder.HtmlEncode(n.InnerHtml);
                }
            }

            return html;
        }
    }
}


text:
import React from 'react';
import {Route, IndexRoute} from 'react-router';

import MainLayout from './layouts/mainLayout';
//import HomeLayout from './layouts/homeLayout';
import Home from './views/home';
import Projects from './views/projects';

export default(
	<Route path="/" component={MainLayout}>
		<IndexRoute component={Home} />
		<Route path={'/projects'} component={Projects} />
		<Route path={'/projects/finished'} component={Projects} />
	</Route>
);


text:
<?php

namespace Omnipay\AuthorizeNet;

use Omnipay\Tests\GatewayTestCase;
//use Omnipay\AuthorizeNet\SIMGatewayTest;

class DPMGatewayTest extends GatewayTestCase //SIMGatewayTest
{
    public function setUp()
    {
        parent::setUp();

        $this->gateway = new DPMGateway($this->getHttpClient(), $this->getHttpRequest());
        $this->gateway->setApiLoginId('example');
        $this->gateway->setTransactionKey('keykey');
        $this->gateway->setHashSecret('elpmaxe');

        $this->options = array(
            'amount' => '10.00',
            'transactionId' => '99',
            'returnUrl' => 'https://www.example.com/return',
        );
    }

    public function testAuthorize()
    {
        $response = $this->gateway->authorize($this->options)->send();

        $this->assertFalse($response->isSuccessful());
        $this->assertTrue($response->isRedirect());
        $this->assertNotEmpty($response->getRedirectUrl());

        $redirectData = $response->getRedirectData();
        $this->assertSame('https://www.example.com/return', $redirectData['x_relay_url']);
    }

    /**
     * The MD4 Hash consists of the shared secret, the login ID, the transaction *reference* (as
     * generated on the remote gateway for the transaction) and the amount.
     */
    public function testCompleteAuthorize()
    {
        $this->getHttpRequest()->request->replace(
            array(
                'x_response_code' => '1',
                'x_trans_id' => '12345',
                'x_amount' => '10.00',
                'x_MD5_Hash' => md5('elpmaxe' . 'example' . '12345' . '10.00'),
            )
        );

        $response = $this->gateway->completeAuthorize($this->options)->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertSame('12345', $response->getTransactionReference());
        $this->assertNull($response->getMessage());
    }

    /**
     * @expectedException Omnipay\Common\Exception\InvalidRequestException
     * @expectedExceptionMessage Incorrect amount
     *
     * The hash is correct, so the sender knows the shared secret, but the amount
     * is not what we expected, i.e. what we had requested to be authorized.
     */
    public function testCompleteAuthorizeWrongAmount()
    {
        $this->getHttpRequest()->request->replace(
            array(
                'x_response_code' => '1',
                'x_trans_id' => '12345',
                'x_amount' => '20.00',
                'x_MD5_Hash' => md5('elpmaxe' . 'example' . '12345' . '20.00'),
            )
        );

        $response = $this->gateway->completeAuthorize($this->options)->send();
    }

    public function testPurchase()
    {
        $response = $this->gateway->purchase($this->options)->send();

        $this->assertFalse($response->isSuccessful());
        $this->assertTrue($response->isRedirect());
        $this->assertNotEmpty($response->getRedirectUrl());

        $redirectData = $response->getRedirectData();
        $this->assertSame('https://www.example.com/return', $redirectData['x_relay_url']);
    }

    public function testCompletePurchase()
    {
        $this->getHttpRequest()->request->replace(
            array(
                'x_response_code' => '1',
                'x_trans_id' => '12345',
                'x_amount' => '10.00',
                'x_MD5_Hash' => md5('elpmaxe' . 'example' . '12345' . '10.00'),
            )
        );

        $response = $this->gateway->completePurchase($this->options)->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertSame('12345', $response->getTransactionReference());
        $this->assertNull($response->getMessage());
    }
}


text:
import scala.reflect.runtime.universe._

object Test extends dotty.runtime.LegacyApp {
  val tree = reify{trait C { private[this] val x = 2; var y = x; lazy val z = y }}
  println(showRaw(tree.tree))
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/bigquery/storage/v1beta2/storage.proto

package com.google.cloud.bigquery.storage.v1beta2;

public interface GetWriteStreamRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Name of the stream to get, in the form of
   * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. Name of the stream to get, in the form of
   * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}


text:
import React from 'react'

import PropTypes from '../../prop-types'

export default class HtmlRenderer extends React.Component {
    static propTypes = PropTypes.Renderer

    static isBinary = false
    static description = 'Renders HTML inline (rich text)'
    static type = 'html'
    static fileExtension = 'html'

    static getName() {
        return 'HtmlRenderer'
    }

    render() {
        const {content} = this.props
        return <div dangerouslySetInnerHTML={{__html: content}} />
    }
}


text:
package com.viesis.viescraft;

import java.io.File;

import com.viesis.viescraft.api.Reference;
import com.viesis.viescraft.api.creative.VCTabAirshipsV1;
import com.viesis.viescraft.api.creative.VCTabAirshipsV2;
import com.viesis.viescraft.api.creative.VCTabAirshipsV3;
import com.viesis.viescraft.api.creative.VCTabAirshipsV4;
import com.viesis.viescraft.api.creative.VCTabAirshipsV5;
import com.viesis.viescraft.api.creative.VCTabAirshipsV6;
import com.viesis.viescraft.api.creative.VCTabBlocks;
import com.viesis.viescraft.api.creative.VCTabItems;
import com.viesis.viescraft.api.util.LogHelper;
import com.viesis.viescraft.configs.ViesCraftConfig;
import com.viesis.viescraft.proxy.CommonProxy;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;

@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.CONFIG_GUI)
public class ViesCraft {

	@Mod.Instance(Reference.MOD_ID)
	public static ViesCraft instance;

    @SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.SERVER_PROXY_CLASS)
	public static CommonProxy proxy;

	public static final VCTabBlocks tabViesCraftBlocks = new VCTabBlocks("tabViesCraftBlocks");
	public static final VCTabItems tabViesCraftItems = new VCTabItems("tabViesCraftItems");
	public static final VCTabAirshipsV1 tabViesCraftAirshipsV1 = new VCTabAirshipsV1("tabViesCraftAirshipsV1");
	public static final VCTabAirshipsV2 tabViesCraftAirshipsV2 = new VCTabAirshipsV2("tabViesCraftAirshipsV2");
	public static final VCTabAirshipsV3 tabViesCraftAirshipsV3 = new VCTabAirshipsV3("tabViesCraftAirshipsV3");
	public static final VCTabAirshipsV4 tabViesCraftAirshipsV4 = new VCTabAirshipsV4("tabViesCraftAirshipsV4");
	public static final VCTabAirshipsV5 tabViesCraftAirshipsV5 = new VCTabAirshipsV5("tabViesCraftAirshipsV5");
	public static final VCTabAirshipsV6 tabViesCraftAirshipsV6 = new VCTabAirshipsV6("tabViesCraftAirshipsV6");

	private static File configDir;

	public static boolean isViesisGemstonesModLoaded;

	@EventHandler
	public void preInit(FMLPreInitializationEvent event)
	{
		MinecraftForge.EVENT_BUS.register(instance);

		configDir = new File(event.getModConfigurationDirectory() + "/" + Reference.MOD_ID);
		configDir.mkdirs();
		ViesCraftConfig.init(new File(configDir.getPath(), Reference.MOD_ID + ".cfg"));

		isViesisGemstonesModLoaded = Loader.isModLoaded("vg");

		this.proxy.preInit(event);
		LogHelper.info("<<==============================>>");
		LogHelper.info("        Pre Init Complete.        ");
		LogHelper.info("<<==============================>>");
	}

	@EventHandler
	public void init(FMLInitializationEvent event)
	{
		this.proxy.init(event);
		LogHelper.info("<<==============================>>");
		LogHelper.info("          Init Complete.          ");
		LogHelper.info("<<==============================>>");
	}

	@EventHandler
	public void postInit(FMLPostInitializationEvent event)
	{
		this.proxy.postInit(event);
		LogHelper.info("<<==============================>>");
		LogHelper.info("   Enforcing Brannigan's Law...   ");
		LogHelper.info("<<==============================>>");
	}
}


text:
"Evernote REST Webapp" provides restful APIs for evernote.

The API covers evernote OAuth and all of thrift based operations. Input and output parameters are represented
as JSON. "Evernote REST Webapp" is a java based web application that behaves like a proxy between evernote thrift
servers and your applications.
It is built on top of [Spring Boot](http://projects.spring.io/spring-boot/),
[Sprnig Social Evernote](https://github.com/ttddyy/spring-social-evernote/), and
[evernote-java-sdk](https://github.com/evernote/evernote-sdk-java).

![System Overview](https://docs.google.com/drawings/d/1mX9zJ_zKJy86XPvTFg1XIQRJTknj-bpyb6dKxsBs2ZQ/pub?w=960&h=720 "system overview")

\* As long as OAuth token has handled, *YOUR APPLICATION can be anything*, such as javascript, ios, android, or an application server.

## REST API Sample

### OAuth

Step1: Request temporal credential and redirect url for authorization
```shell
$ curl -X POST -d "callbackUrl=http://myapp/oauth-callback" http://localhost:8080/oauth/auth
```

Response:
```json
{ "authorizeUrl":"https://sandbox.evernote.com/OAuth.action?oauth_token=...",
  "requestTokenValue":"…", "requestTokenSecret":"…" }
```

Step2: Request access token
```shell
$ curl -X POST -d "oauthToken=..." -d "requestTokenSecret=..." -d "oauthVerifier=..."
    http://localhost:8080/oauth/accessToken
```

Response:
```json
{ "value":"…", "secret":"", "edamShard":"s…", "edamUserId":"...", "edamExpires":"...",
  "edamNoteStoreUrl":"https://...evernote.com/shard/...",
  "edamWebApiUrlPrefix":"https://...evernote.com/shard/..." }
```

---

### UserStore operations

```shell
$ curl -X POST -H "Content-Type: application/json"
   -H "evernote-rest-accesstoken: ..."
   -d '{"clientName": "foo", "edamVersionMajor": 10, "edamVersionMinor": 20}'
   http://localhost:8080/userStore/checkVersion
```

---
### NoteStore operations

```shell
$ curl -X POST -H "Content-Type: application/json"
   -H "evernote-rest-accesstoken: ..."
   -d '{
          "filter":{
              "order": 2,
              "ascending": true,
              "words": "[NOTE_FILTER_WORDS]",
              "notebookGuid": "[NOTEBOOK_GUID]",
              "tagGuids": ["TAG_GUID1", "TAG_GUID2"],
              "timeZone": "",
              "inactive": true
          },
          "offset": 2,
          "maxNotes": 30
      }'
   http://localhost:8080/noteStore/findNotes
```

# What's New

see [CHANGELOG.md](CHANGELOG.md)

# How To Get

- [Download From Bintray](https://bintray.com/ttddyy/maven/evernote-rest-webapp/view)
  - Get war file.
- Or, build from sourcecode
```
 $ git clone git@github.com:ttddyy/evernote-rest-webapp.git
 $ cd evernote-rest-webapp
 $ mvn package    # war file is generated under target directory
```

# Documentation

- [Evernote REST Webapp Reference](https://github.com/ttddyy/evernote-rest-webapp/wiki)
- [Quick Start Guide](https://github.com/ttddyy/evernote-rest-webapp/wiki/QuickStart)

# Development

## library versions

| evernote-rest-webapp |    spring-boot | spring-social-evernote | evernote-sdk-java |
| --------------------:| --------------:| ----------------------:| -----------------:|
|                1.1.2 |  1.1.5.RELEASE |                  1.0.3 |            1.25.1 |
|           1.1, 1.1.1 |  1.1.4.RELEASE |                  1.0.2 |            1.25.1 |
|                  1.0 |  1.0.0.RELEASE |                  1.0.1 |            1.25.1 |

## Continuous Integration

- [BuildHive Jenkins](https://buildhive.cloudbees.com/job/ttddyy/job/evernote-rest-webapp/)
[![Build Status](https://buildhive.cloudbees.com/job/ttddyy/job/evernote-rest-webapp/badge/icon)](https://buildhive.cloudbees.com/job/ttddyy/job/evernote-rest-webapp/)


text:
package main

import (
	"bytes"
	"fmt"
	"strings"
)

// semanticAlphabet
const semanticAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"

// These constants define the application version and follow the semantic
// versioning 2.0.0 spec (http://semver.org/).
const (
	appMajor uint = 0
	appMinor uint = 9
	appPatch uint = 0

	// appPreRelease MUST only contain characters from semanticAlphabet
	// per the semantic versioning spec.
	appPreRelease = "beta"
)

// appBuild is defined as a variable so it can be overridden during the build
// process with '-ldflags "-X main.appBuild foo' if needed.  It MUST only
// contain characters from semanticAlphabet per the semantic versioning spec.
var appBuild string

// version returns the application version as a properly formed string per the
// semantic versioning 2.0.0 spec (http://semver.org/).
func version() string {
	// Start with the major, minor, and patch versions.
	version := fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch)

	// Append pre-release version if there is one.  The hyphen called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the pre-release string.  The pre-release version
	// is not appended if it contains invalid characters.
	preRelease := normalizeVerString(appPreRelease)
	if preRelease != "" {
		version = fmt.Sprintf("%s-%s", version, preRelease)
	}

	// Append build metadata if there is any.  The plus called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the build metadata string.  The build metadata
	// string is not appended if it contains invalid characters.
	build := normalizeVerString(appBuild)
	if build != "" {
		version = fmt.Sprintf("%s+%s", version, build)
	}

	return version
}

// normalizeVerString returns the passed string stripped of all characters which
// are not valid according to the semantic versioning guidelines for pre-release
// version and build metadata strings.  In particular they MUST only contain
// characters in semanticAlphabet.
func normalizeVerString(str string) string {
	var result bytes.Buffer
	for _, r := range str {
		if strings.ContainsRune(semanticAlphabet, r) {
			// Ignoring the error here since it can only fail if
			// the the system is out of memory and there are much
			// bigger issues at that point.
			_, _ = result.WriteRune(r)
		}
	}
	return result.String()
}


text:
package com.cardpay.pccredit.riskControl.constant;

public enum CollectionTypeEnum {
	age,//账龄
	date,//逾期
}


text:
package com.taxisurfr.client.util;

import java.math.BigInteger;
import java.security.SecureRandom;

public final class BookingIdentifierGenerator
{
    private static final SecureRandom random = new SecureRandom();

    public static String nextBookingId()
    {
        return new BigInteger(130, random).toString(6);
    }
}


text:
package editor;

import editor.util.EditorUtilities;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.util.function.Consumer;

public class GotoExceptionTypePopup extends GotoTypePopup
{
  public static void display()
  {
    GotoExceptionTypePopup valuePopup = new GotoExceptionTypePopup( "" );
    valuePopup.addNodeChangeListener(
      e -> {
        String strQualifedType = (String)e.getSource();
        doGoTo( strQualifedType );
      } );
    Component host = LabFrame.instance().getRootPane();
    valuePopup.show( host, 0, 0 );
  }

  public static void display( JTextComponent host, String prefix, Consumer<String> consumer )
  {
    GotoExceptionTypePopup valuePopup = new GotoExceptionTypePopup( prefix );
    valuePopup.addNodeChangeListener(
      e -> {
        String strQualifedType = (String)e.getSource();
        consumer.accept( strQualifedType );
        host.requestFocus();
      } );
    valuePopup.getNameField().setText( prefix );
    valuePopup.show( EditorUtilities.rootPaneForComponent( host ), 0, 0 );
  }

  public static void display( JComponent host, int x, int y, Consumer<String> consumer )
  {
    GotoExceptionTypePopup valuePopup = new GotoExceptionTypePopup( "" );
    valuePopup.addNodeChangeListener(
      e -> {
        String strQualifedType = (String)e.getSource();
        consumer.accept( strQualifedType );
        host.requestFocus();
      } );
    valuePopup.show( host, x, y );
  }

  public GotoExceptionTypePopup( String strPrefix )
  {
    super( "Enter an Exception type", strPrefix );
  }
}


text:
title: Game Commander
date: 2016-06-21 17:46:46
tags:
- Other function
- Alternative Access
- Other need

---

{% alert info no-icon %}
Game Commander is a voice recognition program designed for games commands, but which can be used for general voice commands.
{% endalert %}

<!-- more -->

What the authors say:

------------------------

Game Commander is a voice control application for games. Many of today's games have a lot of keyboard commands that can be hard to remember. Game Commander takes you to the next level of gaming by enabling you to control most Windows<sup>®</sup> 98/Me/2000/XP games with verbal commands instead of or in tandem with keyboard, joystick, and mouse controls. For example, instead of remembering that Alt+Shift+F8 is the command for lock missiles, you can just say ""Lock Missiles.""

OATS Comments:
--------------

Most of the versions of this software are commerical, however the free trial listed here is actually quite useful!  It is not time limited, but limits the number of keystrokes sent per command to one and the number of commands in a list to 5.  This might be OK for some people!

### Links:

### Download: http://www.tucows.com/preview/364262


text:
using System;
using Lucene.Net.Documents;

namespace Lucene.Net.Search
{
    using NUnit.Framework;
    using Directory = Lucene.Net.Store.Directory;

    using Document = Documents.Document;
    using Field = Field;
    using IndexReader = Lucene.Net.Index.IndexReader;
    using IOUtils = Lucene.Net.Util.IOUtils;
    using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
    using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;

    [TestFixture]
    public class TestIndexSearcher : LuceneTestCase
    {
        internal Directory Dir;
        internal IndexReader Reader;

        [SetUp]
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            RandomIndexWriter iw = new RandomIndexWriter(Random(), Dir);
            for (int i = 0; i < 100; i++)
            {
                Document doc = new Document();
                doc.Add(NewStringField("field", Convert.ToString(i), Field.Store.NO));
                doc.Add(NewStringField("field2", Convert.ToString(i % 2 == 0), Field.Store.NO));
                iw.AddDocument(doc);
            }
            Reader = iw.Reader;
            iw.Dispose();
        }

        [TearDown]
        public override void TearDown()
        {
            base.TearDown();
            Reader.Dispose();
            Dir.Dispose();
        }

        //LUCENE TODO: Compilation problems
        /*
        // should not throw exception
        [Test]
        public virtual void TestHugeN()
        {
            TaskScheduler service = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("TestIndexSearcher"));

            IndexSearcher[] searchers = new IndexSearcher[] { new IndexSearcher(Reader), new IndexSearcher(Reader, service) };
            Query[] queries = new Query[] { new MatchAllDocsQuery(), new TermQuery(new Term("field", "1")) };
            Sort[] sorts = new Sort[] { null, new Sort(new SortField("field2", SortField.Type_e.STRING)) };
            Filter[] filters = new Filter[] { null, new QueryWrapperFilter(new TermQuery(new Term("field2", "true"))) };
            ScoreDoc[] afters = new ScoreDoc[] { null, new FieldDoc(0, 0f, new object[] { new BytesRef("boo!") }) };

            foreach (IndexSearcher searcher in searchers)
            {
                foreach (ScoreDoc after in afters)
                {
                    foreach (Query query in queries)
                    {
                        foreach (Sort sort in sorts)
                        {
                            foreach (Filter filter in filters)
                            {
                                searcher.Search(query, int.MaxValue);
                                searcher.SearchAfter(after, query, int.MaxValue);
                                searcher.Search(query, filter, int.MaxValue);
                                searcher.SearchAfter(after, query, filter, int.MaxValue);
                                if (sort != null)
                                {
                                    searcher.Search(query, int.MaxValue, sort);
                                    searcher.Search(query, filter, int.MaxValue, sort);
                                    searcher.Search(query, filter, int.MaxValue, sort, true, true);
                                    searcher.Search(query, filter, int.MaxValue, sort, true, false);
                                    searcher.Search(query, filter, int.MaxValue, sort, false, true);
                                    searcher.Search(query, filter, int.MaxValue, sort, false, false);
                                    searcher.SearchAfter(after, query, filter, int.MaxValue, sort);
                                    searcher.SearchAfter(after, query, filter, int.MaxValue, sort, true, true);
                                    searcher.SearchAfter(after, query, filter, int.MaxValue, sort, true, false);
                                    searcher.SearchAfter(after, query, filter, int.MaxValue, sort, false, true);
                                    searcher.SearchAfter(after, query, filter, int.MaxValue, sort, false, false);
                                }
                            }
                        }
                    }
                }
            }

            TestUtil.ShutdownExecutorService(service);
        }*/

        [Test]
        public virtual void TestSearchAfterPassedMaxDoc()
        {
            // LUCENE-5128: ensure we get a meaningful message if searchAfter exceeds maxDoc
            Directory dir = NewDirectory();
            RandomIndexWriter w = new RandomIndexWriter(Random(), dir);
            w.AddDocument(new Document());
            IndexReader r = w.Reader;
            w.Dispose();

            IndexSearcher s = new IndexSearcher(r);
            try
            {
                s.SearchAfter(new ScoreDoc(r.MaxDoc, 0.54f), new MatchAllDocsQuery(), 10);
                Assert.Fail("should have hit IllegalArgumentException when searchAfter exceeds maxDoc");
            }
            catch (System.ArgumentException e)
            {
                // ok
            }
            finally
            {
                IOUtils.Close(r, dir);
            }
        }
    }
}


text:
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You 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.
  -->

<suite name="Gobblin" verbose="1" >
<test name="GobblinMetricsPerformance" >
    <groups>
        <run>
            <include name="performance"/>
        </run>
    </groups>
    <packages>
        <package name="org.apache.gobblin.metrics.*" />
    </packages>
</test>
</suite>


text:
let hashWithoutHash = () => {
  return location.hash.replace("#", "");
};

Session.setDefault("urlHash", hashWithoutHash());

$(window).on("hashchange", () => Session.set("urlHash", hashWithoutHash()));

Session.setDefault("showAllTypes", false);

Template.nav.events({
  "change .show-all-types input"(event) {
    Session.set("showAllTypes", event.target.checked);
  }
});

Template.nav.helpers({
  current() {
    return Session.get("urlHash") === this.id ? "current" : "";
  },
  showAllTypes() {
    return Session.get("showAllTypes");
  },
});


text:
<!DOCTYPE html>

Photo Album Viewer


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Net;
using System.Web;
using System.Web.Mvc;

using System.Data.Entity;
using System.Data.Entity.Infrastructure;

using AutoMapper;
using AutoMapper.QueryableExtensions;

using PagedList;

using CarService.Data;
using CarService.Models;
using CarService.Web.ViewModels;
using CarService.Web.Infrastructure.ExtensionMethods;

namespace CarService.Web.Controllers
{
    [OutputCache(NoStore=true, Duration=0, VaryByParam="*")]
    public class AjaxController : BaseController
    {
        public AjaxController(ICarServiceData data)
            : base(data)
        {
        }

        public ActionResult CategoryDetails(int id, int? page)
        {
            if (Request.IsAjaxRequest())
            {
                var category = Data
                .Categories
                .All()
                .Where(c => c.Id == id)
                .Project()
                .To<CategoryIndexExtended>()
                .FirstOrDefault();

                var parts = Data
                    .ReplacementParts
                    .All()
                    .Where(p => p.CategoryId == id)
                    .Project()
                    .To<PartInCategoryDetails>()
                    .OrderBy(p => p.Name)
                    .ToPagedList(page ?? 1, 10);

                category.Parts = parts;

                return PartialView("_CategoryDetails", category);
            }

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        public ActionResult FindCatalogNumber(string term)
        {
            if (Request.IsAjaxRequest())
            {
                var catalogNumbers = Data
                    .ReplacementParts
                    .All()
                    .Where(p => p.CatalogNumber.Contains(term))
                    .Select(p => p.CatalogNumber);
                return Json(catalogNumbers, JsonRequestBehavior.AllowGet);
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        [HttpGet]
        public ActionResult GetCategoryParts(int catId)
        {
            if (Request.IsAjaxRequest())
            {
                var parts = Data
                    .ReplacementParts
                    .All()
                    .Where(p => p.CategoryId == catId)
                    .OrderBy(p => p.Name)
                    .Project()
                    .To<PartInRepairDocumentDetails>()
                    .AsEnumerable();

                if (parts != null)
                {
                    return PartialView("_PartsInEditRepairDocumentAdd", parts);
                }
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        public ActionResult GetCar(int? id)
        {
            if (Request.IsAjaxRequest() && id.HasValue)
            {
                var car = Data.Cars.GetById(id.Value);
                if (car == null)
                {
                    return HttpNotFound();
                }
                var carModel = Mapper.Map<CarInRepairDocumentDetails>(car);

                return PartialView("/Views/Shared/DisplayTemplates/CarInRepairDocumentDetails.cshtml", carModel);
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        [HttpGet]
        public ActionResult EditCar(int? id)
        {
            if (Request.IsAjaxRequest() && id.HasValue)
            {
                var car = Data.Cars.GetById(id);
                if (car == null)
                {
                    return HttpNotFound();
                }
                var carModel = Mapper.Map<CarEdit>(car);
                return PartialView("/Views/RepairDocuments/CarEdit.cshtml", carModel);
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditCar(CarEdit car)
        {
            if (ModelState.IsValid)
            {
                var carEdited = Mapper.Map<Car>(car);
                Data.Cars.Attach(carEdited);
                Data.Cars.Update(carEdited, c => c.RegNumber, c => c.ChassisNumber, c => c.EngineNumber);
                try
                {
                    Data.SaveChanges();
                    return Json(new { cssClass = "text-success", message = "Changes saved successfully" });
                }
                catch(DbUpdateException ex)
                {
                    HandleDbUpdateException(ex);
                }
                catch (Exception)
                {
                    return Json(new { cssClass = "text-danger", message = "Some error occurred while saving" });
                }
            }
            return Json(new { cssClass = "text-danger", message = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage)) });
        }

        public ActionResult FindCar(string term)
        {
            if (Request.IsAjaxRequest())
            {
                string searchTerm = term.CyrillicToLatinToUpper();
                var cars = Data
                    .Cars
                    .All()
                    .Where(c => c.RegNumber.Contains(searchTerm))
                    .OrderBy(c => c.RegNumber)
                    .Select(c => new
                    {
                        value = c.Id,
                        label = c.RegNumber
                    })
                    .ToList();
                return Json(cars, JsonRequestBehavior.AllowGet);
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        [HttpGet]
        public ActionResult CreateCar()
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView("/Views/RepairDocuments/CarCreate.cshtml", new CarCreate());
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateCar(CarCreate car)
        {
            if (ModelState.IsValid)
            {
                var carCreated = Mapper.Map<Car>(car);
                Data.Cars.Add(carCreated);
                try
                {
                    Data.SaveChanges();
                    var id = carCreated.Id;
                    var number = carCreated.RegNumber;
                    return Json(new { cssClass = "text-success", message = number + " saved successfully", id = id, number = number });
                }
                catch (DbUpdateException ex)
                {
                    HandleDbUpdateException(ex);
                }
                catch (Exception)
                {
                    return Json(new { cssClass = "text-danger", message = "Some error occurred while saving" });
                }
            }
            return Json(new { cssClass = "text-danger", message = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage)) });
        }

        public ActionResult FindDocumentByNumber(string term)
        {
            if (Request.IsAjaxRequest())
            {
                int id;
                if (int.TryParse(term, out id))
                {
                    var result = Data
                        .RepairDocuments
                        .All()
                        .Where(d => d.Id == id)
                        .Select(d => new
                        {
                            value = d.Id,
                            label = d.Id
                        })
                        .ToList();
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { }, JsonRequestBehavior.AllowGet);
                }
            }
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
    }
}


text:
package org.apereo.cas.configuration.support;

import org.apereo.cas.CipherExecutor;

import lombok.Getter;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.springframework.core.env.Environment;

import java.security.Security;

/**
 * This is {@link CasConfigurationJasyptCipherExecutor}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */

public class CasConfigurationJasyptCipherExecutor implements CipherExecutor<String, String> {
    /**
     * Prefix inserted at the beginning of a value to indicate it's encrypted.
     */
    public static final String ENCRYPTED_VALUE_PREFIX = "{cipher}";
    /**
     * The Jasypt instance.
     */
    private final StandardPBEStringEncryptor jasyptInstance;

    /**
     * Instantiates a new CAS configuration jasypt cipher executor.
     *
     * @param environment the environment
     */
    public CasConfigurationJasyptCipherExecutor(final Environment environment) {
        Security.addProvider(new BouncyCastleProvider());
        this.jasyptInstance = new StandardPBEStringEncryptor();

        val alg = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ALGORITHM);
        setAlgorithm(alg);
        val psw = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PASSWORD);
        setPassword(psw);
        val pName = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PROVIDER);
        setProviderName(pName);
        val iter = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ITERATIONS);
        setKeyObtentionIterations(iter);
    }

    /**
     * Gets jasypt param from env.
     *
     * @param environment the environment
     * @param param       the param
     * @return the jasypt param from env
     */
    private static String getJasyptParamFromEnv(final Environment environment, final JasyptEncryptionParameters param) {
        return environment.getProperty(param.getPropertyName(), param.getDefaultValue());
    }

    /**
     * Sets algorithm.
     *
     * @param alg the alg
     */
    public void setAlgorithm(final String alg) {
        if (StringUtils.isNotBlank(alg)) {
            LOGGER.debug("Configured Jasypt algorithm [{}]", alg);
            jasyptInstance.setAlgorithm(alg);
        }
    }

    /**
     * Sets password.
     *
     * @param psw the psw
     */
    public void setPassword(final String psw) {
        if (StringUtils.isNotBlank(psw)) {
            LOGGER.debug("Configured Jasypt password");
            jasyptInstance.setPassword(psw);
        }
    }

    /**
     * Sets key obtention iterations.
     *
     * @param iter the iter
     */
    public void setKeyObtentionIterations(final String iter) {
        if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) {
            LOGGER.debug("Configured Jasypt iterations");
            jasyptInstance.setKeyObtentionIterations(Integer.parseInt(iter));
        }
    }

    /**
     * Sets provider name.
     *
     * @param pName the p name
     */
    public void setProviderName(final String pName) {
        if (StringUtils.isNotBlank(pName)) {
            LOGGER.debug("Configured Jasypt provider");
            this.jasyptInstance.setProviderName(pName);
        }
    }

    @Override
    public String encode(final String value, final Object[] parameters) {
        return encryptValue(value);
    }

    @Override
    public String decode(final String value, final Object[] parameters) {
        return decryptValue(value);
    }

    @Override
    public String getName() {
        return "CAS Configuration Jasypt Encryption";
    }

    /**
     * Encrypt value string.
     *
     * @param value the value
     * @return the string
     */
    public String encryptValue(final String value) {
        try {
            return encryptValuePropagateExceptions(value);
        } catch (final Exception e) {
            LOGGER.error("Could not encrypt value [{}]", value, e);
        }
        return null;
    }

    /**
     * Encrypt value string (but don't log error, for use in shell).
     *
     * @param value the value
     * @return the string
     */
    public String encryptValuePropagateExceptions(final String value) {
        initializeJasyptInstanceIfNecessary();
        return ENCRYPTED_VALUE_PREFIX + this.jasyptInstance.encrypt(value);
    }

    /**
     * Decrypt value string.
     *
     * @param value the value
     * @return the string
     */
    public String decryptValue(final String value) {
        try {
            return decryptValuePropagateExceptions(value);
        } catch (final Exception e) {
            LOGGER.error("Could not decrypt value [{}]", value, e);
        }
        return null;
    }

    /**
     * Decrypt value string. (but don't log error, for use in shell).
     *
     * @param value the value
     * @return the string
     */
    public String decryptValuePropagateExceptions(final String value) {
        if (StringUtils.isNotBlank(value) && value.startsWith(ENCRYPTED_VALUE_PREFIX)) {
            initializeJasyptInstanceIfNecessary();

            val encValue = value.substring(ENCRYPTED_VALUE_PREFIX.length());
            LOGGER.trace("Decrypting value [{}]...", encValue);
            val result = this.jasyptInstance.decrypt(encValue);

            if (StringUtils.isNotBlank(result)) {
                LOGGER.debug("Decrypted value [{}] successfully.", encValue);
                return result;
            }
            LOGGER.warn("Encrypted value [{}] has no values.", encValue);
        }
        return value;
    }

    /**
     * Initialize jasypt instance if necessary.
     */
    private void initializeJasyptInstanceIfNecessary() {
        if (!this.jasyptInstance.isInitialized()) {
            LOGGER.debug("Initializing Jasypt...");
            this.jasyptInstance.initialize();
        }
    }

    /**
     * The Jasypt encryption parameters.
     */
    public enum JasyptEncryptionParameters {

        /**
         * Jasypt algorithm name to use.
         */
        ALGORITHM("cas.standalone.configurationSecurity.alg", "PBEWithMD5AndTripleDES"),
        /**
         * Jasypt provider name to use.
         */
        PROVIDER("cas.standalone.configurationSecurity.provider", null),
        /**
         * Jasypt number of iterations to use.
         */
        ITERATIONS("cas.standalone.configurationSecurity.iteration", null),
        /**
         * Jasypt password to use.
         */
        PASSWORD("cas.standalone.configurationSecurity.psw", null);

        /**
         * The Name.
         */
        @Getter
        private final String propertyName;
        /**
         * The Default value.
         */
        @Getter
        private final String defaultValue;

        /**
         * Instantiates a new Jasypt encryption parameters.
         *
         * @param name         the name
         * @param defaultValue the default value
         */
        JasyptEncryptionParameters(final String name, final String defaultValue) {
            this.propertyName = name;
            this.defaultValue = defaultValue;
        }
    }
}


text:
env.modules.Add20 = function () {
  var self = this;
  this.state = 0;
  this.interval = 800;
  this.interval_id = null;
  this.next_func = null;
  this.tries = 0;
  this.run = function (start_url) {
    if (start_url != "") {
      self.view.load(start_url);
    }
    self.interval_id = setInterval(self.event_loop,self.interval);
    return self;
  } // end run
  this.next = function (next_func) {
    self.next_func = next_func;
  }

  this.event_loop = function () {
    print("Add20 Beginning. State: " + self.state + "\n");
    switch(self.state) {
      /////////////////////////////////////////////
      //  Add an item of 20
      ////////////////////////////////////////////
      case 0:
        self.tries = 0;
        var complete_order_popup = self.view.getElement("#complete_order");
        if (complete_order_popup.isVisible == true) {
          if (self.tries < 3) {
            fatal("xxx Complete order popup needs to be hidden");
          } else {
            self.tries++;
            return;
          }
        }
        self.tries = 0;
        var input = self.view.getElement("#keyboard_input");
        self.view.fill(input,"20.00");
        sendKey(self.view,"Enter");
        var complete_button = self.view.getElement("#print_receipt_button");
        self.view.click(complete_button);
        self.state++;
        break;
      case 1:
        var complete_order_popup = self.view.getElement("#complete_order");
        if (complete_order_popup.isVisible == true) {
          var button = self.view.getElement("#payment_amount_0_kbd");
          self.view.click(button);
          self.state++;
          self.tries = 0;
        } else {
          var complete_button = self.view.getElement("#print_receipt_button");
          self.view.click(complete_button);
          print("Waiting to click on kdb when complete_order_popup is shown");
        }
        break;
      case 2:

       var kbd = self.view.getElement(".ui-keyboard");
       if (kbd.isVisible == false) {
          if (self.tries > 4) {
            fatal("keyboard never showed up");
          } else {
            self.tries++;
          }
       } else {
        self.state++;
       }
       break;
      case 3:
        keys = ['2_1','3_1','3_2','3_1','3_1','accept'];
        for (var i = 0; i < keys.length; i++) {
          //var key = self.view.getElement("input[name='key_"+keys[i]+"']");
          self.view.executeJS("$(\"input[name='key_"+keys[i]+"']\").trigger('mousedown');");
          //print("$(\"input[name='key_"+keys[i]+"']\").trigger('mousedown');");
        }
        self.state++;
        break;
      case 4:
        var button = self.view.getElement("#add_payment_method_button");
        self.view.click(button);
        self.state++;
      break;
      case 5:
        var newpm = self.view.getContentOfElement("#select_widget_button_for_payment_type_1");
        if (newpm.indexOf("Debit") == -1) {
          fail("New payment method is expected to be Debit");
        }
        var button = self.view.getElement("#payment_amount_1_kbd");
        self.view.click(button);
        self.state++;
        self.tries = 0;
      case 6:
        var kbd = self.view.getElement(".ui-keyboard");
        if (kbd.isVisible == false) {
          if (self.tries > 5) {
            fatal("keyboard never showed up");
          } else {
            self.tries++;
          }
        } else {
          self.state++;
        }
        break;
      case 7:
        keys = ['2_0','3_1','3_2','3_1','3_1','accept'];
        for (var i = 0; i < keys.length; i++) {
          //var key = self.view.getElement("input[name='key_"+keys[i]+"']");
          self.view.executeJS("$(\"input[name='key_"+keys[i]+"']\").trigger('mousedown');");
          //print("$(\"input[name='key_"+keys[i]+"']\").trigger('mousedown');");
        }
        self.state++;
        break;
      case 8:
        var total = self.view.getContentOfElement("#complete_order_total");
        var change = self.view.getContentOfElement("#complete_order_change");
        if (total.indexOf("20.00") == -1) {
          fatal("Order Total should be 20.00");
        } else if (change.indexOf("10.00") == -1) {
          fatal("Change should be 10.00 at case 8");
          self.state++;
        } else {
          var button = self.view.getElement("#confirm_complete_order_button");
          self.view.click(button);
          self.state++;
        }
        break;
      case 9:
        var button = self.view.getElement("#confirm_complete_order_button");
        self.view.click(button);
        self.state++;
        break;
      case 10:
        var drawer_amount = self.view.getContentOfElement("#header_drawer_amount");
        if (drawer_amount.indexOf("125.00") == -1) {
          // It may take some time for the element to update...
          if (self.tries < 3) {
            self.tries++;
          } else {
            fatal("Add item of $20.00 failed or cash drawer failed to update to value 125.00");
          }
        } else {
          var button = self.view.getElement("#cancel_complete_order_button");
          self.view.click(button);
          self.state++;
        }
        break;
      default:
        clearInterval(self.interval_id);
        if (self.next_func) {
          setTimeout(self.next_func,100);
        }
        break;
    } // end switch self.state
  } // end event_loop
}


text:
namespace wm {

class WM_EXPORT VisibilityController
    : public aura::client::VisibilityClient {
 public:
  VisibilityController();
  ~VisibilityController() override;

 protected:
  // Subclasses override if they want to call a different implementation of
  // this function.
  // TODO(beng): potentially replace by an actual window animator class in
  //             window_animations.h.
  virtual bool CallAnimateOnChildWindowVisibilityChanged(aura::Window* window,
                                                         bool visible);

 private:
  // Overridden from aura::client::VisibilityClient:
  void UpdateLayerVisibility(aura::Window* window, bool visible) override;

  DISALLOW_COPY_AND_ASSIGN(VisibilityController);
};

// Suspends the animations for visibility changes during the lifetime of an
// instance of this class.
//
// Example:
//
// void ViewName::UnanimatedAction() {
//   SuspendChildWindowVisibilityAnimations suspend(parent);
//   // Perform unanimated action here.
//   // ...
//   // When the method finishes, visibility animations will return to their
//   // previous state.
// }
//
class WM_EXPORT SuspendChildWindowVisibilityAnimations {
 public:
  // Suspend visibility animations of child windows.
  explicit SuspendChildWindowVisibilityAnimations(aura::Window* window);

  // Restore visibility animations to their original state.
  ~SuspendChildWindowVisibilityAnimations();

 private:
  // The window to manage.
  aura::Window* window_;

  // Whether the visibility animations on child windows were originally enabled.
  const bool original_enabled_;

  DISALLOW_COPY_AND_ASSIGN(SuspendChildWindowVisibilityAnimations);
};

// Enable visibility change animation for specific |window|. Use this if
// you want to enable visibility change animation on a specific window without
// affecting other windows in the same container. Calling this on a window
// whose animation is already enabled either by this function, or
// via SetChildWindowVisibilityChangesAnimatedbelow below is allowed and
// the animation stays enabled.
void WM_EXPORT SetWindowVisibilityChangesAnimated(aura::Window* window);

// Enable visibiilty change animation for all children of the |window|.
// Tyically applied to a container whose child windows should be animated
// when their visibility changes.
void WM_EXPORT SetChildWindowVisibilityChangesAnimated(
    aura::Window* window);

}  // namespace wm

#endif  // UI_WM_CORE_VISIBILITY_CONTROLLER_H_


text:
#include <boost/program_options.hpp>

#include "cyber/common/log.h"
#include "modules/localization/msf/local_tool/map_creation/poses_interpolation/poses_interpolation.h"

int main(int argc, char **argv) {
  boost::program_options::options_description boost_desc("Allowed options");
  boost_desc.add_options()("help", "produce help message")(
      "input_poses_path", boost::program_options::value<std::string>(),
      "provide input poses path")("ref_timestamps_path",
                                  boost::program_options::value<std::string>(),
                                  "provide reference timestamp path")(
      "extrinsic_path", boost::program_options::value<std::string>(),
      "provide velodyne extrinsic path")(
      "output_poses_path", boost::program_options::value<std::string>(),
      "provide output poses path");

  boost::program_options::variables_map boost_args;
  boost::program_options::store(
      boost::program_options::parse_command_line(argc, argv, boost_desc),
      boost_args);
  boost::program_options::notify(boost_args);

  if (boost_args.count("help") || !boost_args.count("input_poses_path") ||
      !boost_args.count("ref_timestamps_path") ||
      !boost_args.count("extrinsic_path") ||
      !boost_args.count("output_poses_path")) {
    AERROR << boost_desc;
    return 0;
  }

  std::string input_poses_path =
      boost_args["input_poses_path"].as<std::string>();
  std::string ref_timestamps_path =
      boost_args["ref_timestamps_path"].as<std::string>();
  std::string extrinsic_path = boost_args["extrinsic_path"].as<std::string>();
  std::string out_poses_path =
      boost_args["output_poses_path"].as<std::string>();

  apollo::localization::msf::PosesInterpolation pose_interpolation;
  bool success = pose_interpolation.Init(input_poses_path, ref_timestamps_path,
                                         out_poses_path, extrinsic_path);

  if (success) {
    pose_interpolation.DoInterpolation();
  }

  return 0;
}


text:
package org.zerosign.requesto.impl.responses;

import org.zerosign.requesto.annotations.Response;
import org.zerosign.requesto.ifaces.IResponse;
import org.zerosign.requesto.impl.formatter.StringConverter;

/**
 * The actual Response class that map the raw response.
 *
 * This just an example that showing what you should
 * do in creating a model for response class. It may not
 * need any constructor, since it depends on how you create
 * your implementation of
 * {@link org.zerosign.requesto.ifaces.IConverter} interface.
 *
 * @author zerosign
 * @since 20 April 2014
 * @version 1.0
 */
@Response(formatter = StringConverter.class)
public class StringResponse implements IResponse {

    private final String response;

    public StringResponse(final String response) {
        this.response = response;
    }

    @Override
    public String toString() {
        return "StringResponse{" + "response=" + response + '}';
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Core.Provider.Tests
    ( tests
    ) where

--------------------------------------------------------------------------------
import qualified Data.Map                       as M
import           Test.Framework                 (Test, testGroup)
import           Test.Framework.Providers.HUnit (testCase)
import           Test.HUnit                     (Assertion, assert, (@=?))

--------------------------------------------------------------------------------
import           Hakyll.Core.Provider
import           TestSuite.Util

--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Hakyll.Core.Provider.Tests"
    [ testCase "case01" case01
    ]

--------------------------------------------------------------------------------
case01 :: Assertion
case01 = do
    store    <- newTestStore
    provider <- newTestProvider store
    assert $ resourceExists provider "example.md"

    metadata <- resourceMetadata provider "example.md"
    Just "An example"    @=? M.lookup "title"    metadata
    Just "External data" @=? M.lookup "external" metadata

    doesntExist <- resourceMetadata provider "doesntexist.md"
    M.empty @=? doesntExist
    cleanTestEnv


text:
<component name="libraryTable">
  <library name="Gradle: se.callista.microservises.core.review:review-service:0.0.1-SNAPSHOT">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/se/callista/microservises/core/review/review-service/0.0.1-SNAPSHOT/review-service-0.0.1-SNAPSHOT.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
from unittest import mock

from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils

from nova import objects
from nova.tests.unit.objects import test_objects

NOW = timeutils.utcnow().replace(microsecond=0)

fake_vol_usage = {
    'created_at': NOW,
    'updated_at': None,
    'deleted_at': None,
    'deleted': 0,
    'id': 1,
    'volume_id': uuids.volume_id,
    'instance_uuid': uuids.instance,
    'project_id': 'fake-project-id',
    'user_id': 'fake-user-id',
    'availability_zone': None,
    'tot_last_refreshed': None,
    'tot_reads': 0,
    'tot_read_bytes': 0,
    'tot_writes': 0,
    'tot_write_bytes': 0,
    'curr_last_refreshed': NOW,
    'curr_reads': 10,
    'curr_read_bytes': 20,
    'curr_writes': 30,
    'curr_write_bytes': 40,
    }

class _TestVolumeUsage(object):
    @mock.patch(
        'nova.db.main.api.vol_usage_update', return_value=fake_vol_usage)
    def test_save(self, mock_upd):
        vol_usage = objects.VolumeUsage(self.context)
        vol_usage.volume_id = uuids.volume_id
        vol_usage.instance_uuid = uuids.instance
        vol_usage.project_id = 'fake-project-id'
        vol_usage.user_id = 'fake-user-id'
        vol_usage.availability_zone = None
        vol_usage.curr_reads = 10
        vol_usage.curr_read_bytes = 20
        vol_usage.curr_writes = 30
        vol_usage.curr_write_bytes = 40
        vol_usage.save()
        mock_upd.assert_called_once_with(
            self.context, uuids.volume_id, 10, 20, 30, 40, uuids.instance,
            'fake-project-id', 'fake-user-id', None, update_totals=False)
        self.compare_obj(vol_usage, fake_vol_usage)

    @mock.patch(
        'nova.db.main.api.vol_usage_update', return_value=fake_vol_usage)
    def test_save_update_totals(self, mock_upd):
        vol_usage = objects.VolumeUsage(self.context)
        vol_usage.volume_id = uuids.volume_id
        vol_usage.instance_uuid = uuids.instance
        vol_usage.project_id = 'fake-project-id'
        vol_usage.user_id = 'fake-user-id'
        vol_usage.availability_zone = None
        vol_usage.curr_reads = 10
        vol_usage.curr_read_bytes = 20
        vol_usage.curr_writes = 30
        vol_usage.curr_write_bytes = 40
        vol_usage.save(update_totals=True)
        mock_upd.assert_called_once_with(
            self.context, uuids.volume_id, 10, 20, 30, 40, uuids.instance,
            'fake-project-id', 'fake-user-id', None, update_totals=True)
        self.compare_obj(vol_usage, fake_vol_usage)

class TestVolumeUsage(test_objects._LocalTest, _TestVolumeUsage):
    pass

class TestRemoteVolumeUsage(test_objects._RemoteTest, _TestVolumeUsage):
    pass