text:
Applescripts.
============

###Overview
A collection of various applescripts I have created. I try to keep them general (rather than application specific) so that they could be useful to as many people as possible, though many of them are specific to my personal needs.

Note: This collection isn't updated much anymore, but I'll add to it as needed. I may also create a Javascript for Automation section in the near future. Stay tuned.

###Script Categories

Application Services
Display Settings
File and Folder Actions
Location Helper Scripts
Mail-and-Messaging
Markdown Tools
Notational Velocity
Pandoc and Textutils
Snippets
Sound Scripts
Temperature Conversion
Terminal
Time and Date

###Links/Dependencies

- [Caffeine App](http://lightheadsw.com/caffeine/) (or [here](http://macdownload.informer.com/caffeine)) - a menu bar application that prevents your monitor from sleeping. (If you don't want an extra application in your menubar, here is [a different way](http://lifehacker.com/5767991/how-to-force-your-mac-to-stay-awake-indefinitely-via-the-command-line), and if you're on 10.8+ [you can go ahead and use this command](https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man8/caffeinate.8.html). Both work via ```do shell script```.)

- [Location Helper](http://www.mousedown.net/mouseware/LocationHelper.html) - use core location in applescripts.

- [Twitter Scripter](http://www.mousedown.net/mouseware/TwitterScripter.html) - interact with twitter via applescript.

- [Pandoc](http://johnmacfarlane.net/pandoc/) and [Textutil](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/textutil.1.html) - document conversion via the command line.

- `Youtube-Post.scpt` requires [GoogleCL](https://code.google.com/p/googlecl/), which is also useful for blogger, google calendar, and contacts.

- I have also created a few [Gists](https://gist.github.com/unforswearing) for more specific applescript/bash related tasks, with a growing list of shell scripts also [located here](https://github.com/unforswearing/Shell).

- Also, check out my [Alfred Workflows](https://github.com/unforswearing/alfredWorkflows), including [dued](https://github.com/unforswearing/dued), which may be my favorite creation.

### License

MIT

Take the plunge.


text:
package com.action.shejizhichan.chapter07;

/**
 * @Description 臣子类
 * @Author wuyunfeng
 * @Date 2020-05-23 19:03
 * @Version 1.0
 */
public class Minister {

    public static void main(String[] args) {
        for (int day = 0; day < 3; day++) {
            Emperor emperor = Emperor.getInstance();
            emperor.say();
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TrackerChecker;

use Rych\Bencode\Bencode;
use Rych\Bencode\Exception\RuntimeException;
use LibUtil\Helper\OutputHelper;

define('HTTP_URL_STRIP_FOR_HTTP', HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_AUTH | HTTP_URL_STRIP_FRAGMENT);
define('HTTP_URL_STRIP_FOR_UDP', HTTP_URL_STRIP_PATH | HTTP_URL_STRIP_QUERY | HTTP_URL_STRIP_AUTH | HTTP_URL_STRIP_FRAGMENT);

/**
 *
 */
class CheckerUnit extends \Thread
{
    const HTTP_URL_QUERY_PART = 'info_hash=%c7%8a%7b%e0%60%93%4e%28%6b%b0%69%fc%b9%49%65%6b%c6%5d%48%11&peer_id=-SU2291-SOVIETRUSSIA&port=0&downloaded=0&uploaded=0&left=0';
    const BT_DEFAULT_TRACKER_PORT = 80;
    const BT_UDP_CONNECTION_ID_H = 0x417;
    const BT_UDP_CONNECTION_ID_L = 0x27101980;
    const BT_UDP_TRANSACTION_ID = 42;

    protected $inputFileStream;
    protected $outputFileStream;

    /**
     *
     * @param \SplFileObject $inputFileStream
     * @param \SplFileObject $outputFileStream
     */
    public function __construct(\SplFileObject $inputFileStream, \SplFileObject $outputFileStream)
    {
        $this->inputFileStream = $inputFileStream;
        $this->outputFileStream = $outputFileStream;
    }

    /**
     *
     */
    public function run()
    {
        while (!$this->inputFileStream->eof()) {
            try {
                $line = $this->inputFileStream->fgets();
                $tracker = $this->process($line);
                $this->outputFileStream->fwrite($tracker . PHP_EOL);
            } catch (InvalidTrackerException $e) {
                OutputHelper::printException($e);
            }
        }
    }

    /**
     *
     * @param array $parsedUrl
     * @return ressource
     * @throws InvalidTrackerException
     */
    protected function openStream(array $parsedUrl)
    {
        switch ($parsedUrl['scheme']) {
            case 'http':
            case 'https':
                $parsedUrl['query'] = self::HTTP_URL_QUERY_PART;
                $streamUrl = http_build_url($parsedUrl, [], HTTP_URL_STRIP_FOR_HTTP);
                $handle = @fopen($streamUrl, 'r');

                break;
            case 'udp':
                $streamUrl = preg_replace('/\/$/', '', http_build_url($parsedUrl, [], HTTP_URL_STRIP_FOR_UDP | HTTP_URL_STRIP_PORT));
                $handle = @fsockopen($streamUrl, $parsedUrl['port']);

                if ($handle) {
                    fwrite($handle, pack('N2l2', self::BT_UDP_CONNECTION_ID_H, self::BT_UDP_CONNECTION_ID_L, 0, self::BT_UDP_TRANSACTION_ID));
                }

                break;
            default:
                throw new InvalidTrackerException("Invalid url scheme used.");
        }

        if (!$handle) {
            throw new InvalidTrackerException("Stream creation failure.");
        }

        return $handle;
    }

    /**
     *
     * @param string $url
     * @return array
     * @throws InvalidTrackerException
     */
    protected function parseUrl($url)
    {
        $parsedUrl = parse_url(trim($url));

        if (!$parsedUrl || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) {
            throw new InvalidTrackerException("Invalid url given.");
        }

        if (empty($parsedUrl['port'])) {
            $parsedUrl['port'] = self::BT_DEFAULT_TRACKER_PORT;
        }

        return $parsedUrl;
    }

    /**
     *
     * @param string $line
     * @return string
     * @throws InvalidTrackerException
     */
    protected function process($line)
    {
        $parsedUrl = $this->parseUrl($line);
        $trackerStream = $this->openStream($parsedUrl);
        $data = fread($trackerStream, 8192);
        fclose($trackerStream);

        if (!$data) {
            throw new InvalidTrackerException("Remote host replied with no data.");
        }

        switch ($parsedUrl['scheme']) {
            case 'http':
            case 'https':
                // Handle namespaces here DAMMIT!!1
                try {
                    Bencode::decode($data);
                } catch (RuntimeException $e) {
                    throw new InvalidTrackerException("Invalid HTTP response from remote host.");
                }

                $tracker = http_build_url($parsedUrl, [], HTTP_URL_STRIP_FOR_HTTP | HTTP_URL_STRIP_QUERY);

                break;
            case 'udp':
                if (strlen($data) != 16) {
                    throw new InvalidTrackerException("Invalid UDP response from remote host.");
                }

                $parsedData = unpack('l2part', $data);

                if ($parsedData['part1'] != 0 || $parsedData['part2'] != BT_UDP_TRANSACTION_ID) {
                    throw new InvalidTrackerException("Invalid UDP response from remote host.");
                }

                $tracker = http_build_url($parsedUrl, [], HTTP_URL_STRIP_FOR_UDP);

                break;
            default:
                throw new InvalidTrackerException("Invalid url scheme used.");
        }

        return $tracker;
    }
}


text:
package com.sun.tools.jdi;

import java.io.IOException;
import java.util.Map;

import com.sun.jdi.Bootstrap;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.*;
import com.sun.jdi.connect.spi.*;

/*
 * An AttachingConnector to attach to a running VM using any
 * TransportService.
 */

public class GenericAttachingConnector
        extends ConnectorImpl implements AttachingConnector
{
    /*
     * The arguments that this connector supports
     */
    static final String ARG_ADDRESS = "address";
    static final String ARG_TIMEOUT = "timeout";

    TransportService transportService;
    Transport transport;

    /*
     * Initialize a new instance of this connector. The connector
     * encapsulates a transport service and optionally has an
     * "address" connector argument.
     */
    private GenericAttachingConnector(TransportService ts,
                                      boolean addAddressArgument)
    {
        transportService = ts;
        transport = new Transport() {
                public String name() {
                    // delegate name to the transport service
                    return transportService.name();
                }
            };

        if (addAddressArgument) {
            addStringArgument(
                ARG_ADDRESS,
                getString("generic_attaching.address.label"),
                getString("generic_attaching.address"),
                "",
                true);
        }

        addIntegerArgument(
                ARG_TIMEOUT,
                getString("generic_attaching.timeout.label"),
                getString("generic_attaching.timeout"),
                "",
                false,
                0, Integer.MAX_VALUE);
    }

    /**
     * Initializes a new instance of this connector. This constructor
     * is used when sub-classing - the resulting connector will have
     * a "timeout" connector argument.
     */
    protected GenericAttachingConnector(TransportService ts) {
        this(ts, false);
    }

    /*
     * Create an instance of this connector. The resulting AttachingConnector
     * will have address and timeout connector arguments.
     */
    public static GenericAttachingConnector create(TransportService ts) {
        return new GenericAttachingConnector(ts, true);
    }

    /**
     * Attach to a target VM using the specified address and Connector arguments.
     */
    public VirtualMachine attach(String address, Map<String, ? extends Connector.Argument> args)
        throws IOException, IllegalConnectorArgumentsException
    {
        String ts  = argument(ARG_TIMEOUT, args).value();
        int timeout = 0;
        if (ts.length() > 0) {
            timeout = Integer.decode(ts).intValue();
        }
        Connection connection = transportService.attach(address, timeout, 0);
        return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
    }

    /**
     * Attach to a target VM using the specified arguments - the address
     * of the target VM is specified by the address connector
     * argument.
     */
    public VirtualMachine
        attach(Map<String,? extends Connector.Argument> args)
        throws IOException, IllegalConnectorArgumentsException
    {
        String address = argument(ARG_ADDRESS, args).value();
        return attach(address, args);
    }

    public String name() {
        return transport.name() + "Attach";
    }

    public String description() {
        return transportService.description();
    }

    public Transport transport() {
        return transport;
    }

}


text:
{-# LANGUAGE DeriveDataTypeable #-}
import Control.Lens
import Control.Monad                   (forM, liftM)
import Data.Char                       (chr)
import Data.Monoid                     (mappend, mempty)
import System.Console.CmdArgs.Implicit
import System.IO                       (hFlush, stdout)
import Text.PrettyPrint.Leijen

import Myopia.AST
import Myopia.Builtins
import Myopia.Eval
import Myopia.Parser                   (parseFile)
import Myopia.Pretty
import Myopia.REPL
import Myopia.TypeCheck                (TypeError, typeCheck)

data Myopia = Run { file           :: FilePath
                  , function       :: FunName
                  , enableBuiltins :: Bool
                  , enableIO       :: Bool
                  }
            | Repl deriving (Show, Data, Typeable)

myopia = modes [run &= auto, repl]
         &= summary "Myopia v. 0.1.0.0 <https://github.com/miikka/myopia/>"
  where
    run = Run
          { file = def &= argPos 0 &= typ "FILE"
          , function = def &= argPos 1 &= typ "FUNCTION" &= opt "main"
          , enableBuiltins = False &= explicit &= name "builtins"
            &= help "Enable Haskell implementations of some functions."
          , enableIO = False &= explicit &= name "io"
            &= help "Enable IO mode."
          } &= details ["Evaluate a function from a file."]
    repl = Repl &= details ["Start an interactive Myopia session."]

main :: IO ()
main = do
    mode <- cmdArgs myopia
    case mode of
        Repl -> repl
        opts@(Run {}) -> runFile opts

printError :: TypeError -> IO ()
printError (ctx, e, msg) = do
    putStrLn $ "Context: " ++ ctx
    putStrLn $ "Message: " ++ msg
    putStrLn $ "Node:\n" ++ show (indent 4 $ pretty e)

runFile :: Myopia -> IO ()
runFile opts = do
    let name = function opts
    prog <- parseFile (file opts)
    case prog ^. funDefs.at name of
        Nothing -> error $ "No such function: " ++ name
        Just def -> do
            let mainArity = runMyopiaM (arityM def) prog
            case typeCheck prog of
                Left e   -> printError e
                Right () -> do
                    case enableIO opts of
                        True -> do
                            ioBm <- ioBuiltins
                            let bm = ioBm `mappend` if enableBuiltins opts then pureBuiltins else mempty
                            runIO opts prog bm 0
                        False -> do
                            let bm = if enableBuiltins opts then pureBuiltins else emptyBuiltins
                            putStrLn $ "Expecting " ++ show mainArity ++ " parameters."
                            params <- forM [1..mainArity] (\_ -> liftM read getLine)
                            print $ runProgram' bm prog name params

runIO :: Myopia -> Program -> BuiltinMap IO -> Integer -> IO ()
runIO opts prog bm n = do
    v <- runProgram'' bm prog (function opts) [n]
    case v of
        0 -> return ()
        v -> do
            putChar $ chr (fromIntegral v)
            hFlush stdout
            runIO opts prog bm (succ n)

-- vim: set ts=4 sw=4 et


text:
#ifndef _IOKIT_HID_IOHIDTRANSACTION_USER_H
#define _IOKIT_HID_IOHIDTRANSACTION_USER_H

#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/hid/IOHIDBase.h>

/*!
	@header IOHIDTransaction
    IOHIDTransaction defines an object used to manipulate multiple parsed items
    (IOHIDElement) contained within a Human Interface Device (HID) object.  It
    is used to minimize device communication when interacting with feature and
    output type elements that are grouped by their report IDs.  IOHIDTransaction
    is a CFType object and as such conforms to all the conventions expected such
    object.

    This documentation assumes that you have a basic understanding of the material contained in Accessing Hardware From Applications
    For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts
    in the "Device Access and the I/O Kit" chapter of Accessing Hardware From Applications.

    This documentation also assumes you have read Human Interface Device & Force Feedback.
    Please review documentation before using this reference.

    All of the information described in this document is contained in the header file IOHIDTransaction.h found at
    /System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDTransaction.h.
*/

__BEGIN_DECLS

CF_ASSUME_NONNULL_BEGIN
CF_IMPLICIT_BRIDGING_ENABLED

/*! @typedef IOHIDTransactionRef
	This is the type of a reference to the IOHIDTransaction.
*/
typedef struct CF_BRIDGED_TYPE(id) __IOHIDTransaction * IOHIDTransactionRef;

/*!
	@function   IOHIDTransactionGetTypeID
	@abstract   Returns the type identifier of all IOHIDTransaction instances.
*/
CF_EXPORT
CFTypeID IOHIDTransactionGetTypeID(void)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionCreate
	@abstract   Creates an IOHIDTransaction object for the specified device.
    @discussion IOHIDTransaction objects can be used to either send or receive
                multiple element values.  As such the direction used should
                represent they type of objects added to the transaction.
    @param      allocator Allocator to be used during creation.
    @param      device IOHIDDevice object
    @param      direction The direction, either in or out, for the transaction.
    @param      options Reserved for future use.
    @result     Returns a new IOHIDTransactionRef.
*/
CF_EXPORT
IOHIDTransactionRef _Nullable IOHIDTransactionCreate(
                                CFAllocatorRef _Nullable        allocator,
                                IOHIDDeviceRef                  device,
                                IOHIDTransactionDirectionType   direction,
                                IOOptionBits                    options)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionGetDevice
	@abstract   Obtain the device associated with the transaction.
    @param      transaction IOHIDTransaction to be queried.
    @result     Returns the a reference to the device.
*/
CF_EXPORT
IOHIDDeviceRef IOHIDTransactionGetDevice(
                                IOHIDTransactionRef             transaction)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionGetDirection
	@abstract   Obtain the direction of the transaction.
    @param      transaction IOHIDTransaction to be queried.
    @result     Returns the transaction direction.
*/
CF_EXPORT
IOHIDTransactionDirectionType IOHIDTransactionGetDirection(
                                IOHIDTransactionRef             transaction)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionSetDirection
	@abstract   Sets the direction of the transaction
    @disussion  This method is useful for manipulating bi-direction (feature)
                elements such that you can set or get element values without
                creating an additional transaction object.
    @param      transaction IOHIDTransaction object to be modified.
    @param      direction The new transaction direction.
*/
CF_EXPORT
void IOHIDTransactionSetDirection(
                                IOHIDTransactionRef             transaction,
                                IOHIDTransactionDirectionType   direction)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionAddElement
	@abstract   Adds an element to the transaction
    @disussion  To minimize device traffic it is important to add elements that
                share a common report type and report id.
    @param      transaction IOHIDTransaction object to be modified.
    @param      element Element to be added to the transaction.
*/
CF_EXPORT
void IOHIDTransactionAddElement(
                                IOHIDTransactionRef             transaction,
                                IOHIDElementRef                 element)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionRemoveElement
	@abstract   Removes an element to the transaction
    @param      transaction IOHIDTransaction object to be modified.
    @param      element Element to be removed to the transaction.
*/
CF_EXPORT
void IOHIDTransactionRemoveElement(
                                IOHIDTransactionRef             transaction,
                                IOHIDElementRef                 element)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionContainsElement
	@abstract   Queries the transaction to determine if elemement has been added.
    @param      transaction IOHIDTransaction object to be queried.
    @param      element Element to be queried.
    @result     Returns true or false depending if element is present.
*/
CF_EXPORT
Boolean IOHIDTransactionContainsElement(
                                IOHIDTransactionRef             transaction,
                                IOHIDElementRef                 element)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionScheduleWithRunLoop
	@abstract   Schedules transaction with run loop.
    @discussion Formally associates transaction with client's run loop.
                Scheduling this transaction with the run loop is necessary
                before making use of any asynchronous APIs.
    @param      transaction IOHIDTransaction object to be modified.
    @param      runLoop RunLoop to be used when scheduling any asynchronous
                activity.
    @param      runLoopMode Run loop mode to be used when scheduling any
                asynchronous activity.
*/
CF_EXPORT
void IOHIDTransactionScheduleWithRunLoop(
                                IOHIDTransactionRef             transaction,
                                CFRunLoopRef                    runLoop,
                                CFStringRef                     runLoopMode)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionUnscheduleFromRunLoop
	@abstract   Unschedules transaction with run loop.
    @discussion Formally disassociates transaction with client's run loop.
    @param      transaction IOHIDTransaction object to be modified.
    @param      runLoop RunLoop to be used when scheduling any asynchronous
                activity.
    @param      runLoopMode Run loop mode to be used when scheduling any
                asynchronous activity.
*/
CF_EXPORT
void IOHIDTransactionUnscheduleFromRunLoop(
                                IOHIDTransactionRef             transaction,
                                CFRunLoopRef                    runLoop,
                                CFStringRef                     runLoopMode)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionSetValue
	@abstract   Sets the value for a transaction element.
    @discussion The value set is pended until the transaction is committed and
                is only used if the transaction direction is
                kIOHIDTransactionDirectionTypeOutput.  Use the
                kIOHIDTransactionOptionDefaultOutputValue option to set the
                default element value.
    @param      transaction IOHIDTransaction object to be modified.
    @param      element Element to be modified after a commit.
    @param      value Value to be set for the given element.
    @param      options See IOHIDTransactionOption.
*/
CF_EXPORT
void IOHIDTransactionSetValue(
                                IOHIDTransactionRef             transaction,
                                IOHIDElementRef                 element,
                                IOHIDValueRef                   value,
                                IOOptionBits                    options)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionGetValue
	@abstract   Obtains the value for a transaction element.
    @discussion If the transaction direction is
                kIOHIDTransactionDirectionTypeInput the value represents what
                was obtained from the device from the transaction.  Otherwise,
                if the transaction direction is
                kIOHIDTransactionDirectionTypeOutput the value represents the
                pending value to be sent to the device.  Use the
                kIOHIDTransactionOptionDefaultOutputValue option to get the
                default element value.
    @param      transaction IOHIDTransaction object to be queried.
    @param      element Element to be queried.
    @param      options See IOHIDTransactionOption.
    @result     Returns IOHIDValueRef for the given element.
*/
CF_EXPORT
IOHIDValueRef _Nullable IOHIDTransactionGetValue(
                                IOHIDTransactionRef             transaction,
                                IOHIDElementRef                 element,
                                IOOptionBits                    options)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionCommit
	@abstract   Synchronously commits element transaction to the device.
    @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction,
                default element values will be used if element values are not
                set.  If neither are set, that element will be omitted from the
                commit. After a transaction is committed, transaction element
                values will be cleared and default values preserved.
    @param      transaction IOHIDTransaction object to be modified.
    @result     Returns kIOReturnSuccess if successful or a kern_return_t if
                unsuccessful.
*/
CF_EXPORT
IOReturn IOHIDTransactionCommit(
                                IOHIDTransactionRef             transaction)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
	@function   IOHIDTransactionCommitWithCallback
	@abstract   Commits element transaction to the device.
    @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction,
                default element values will be used if element values are not
                set.  If neither are set, that element will be omitted from the
                commit. After a transaction is committed, transaction element
                values will be cleared and default values preserved.

                Note: It is possible for elements from different reports
                to be present in a given transaction causing a commit to
                transcend multiple reports. Keep this in mind when setting a
                appropriate timeout.
    @param      transaction IOHIDTransaction object to be modified.
    @param      timeout Timeout for issuing the transaction.
    @param      callback Callback of type IOHIDCallback to be used when
                transaction has been completed.  If null, this method will
                behave synchronously.
    @param      context Pointer to data to be passed to the callback.
    @result     Returns kIOReturnSuccess if successful or a kern_return_t if
                unsuccessful.
*/
CF_EXPORT
IOReturn IOHIDTransactionCommitWithCallback(
                                IOHIDTransactionRef             transaction,
                                CFTimeInterval                  timeout,
                                IOHIDCallback _Nullable         callback,
                                void * _Nullable                context)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

/*!
    @function   IOHIDTransactionClear
    @abstract   Clears element transaction values.
    @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction,
                default element values will be preserved.
    @param      transaction IOHIDTransaction object to be modified.
*/
CF_EXPORT
void IOHIDTransactionClear(
                                IOHIDTransactionRef             transaction)
AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER;

CF_IMPLICIT_BRIDGING_DISABLED
CF_ASSUME_NONNULL_END

__END_DECLS

#endif /* _IOKIT_HID_IOHIDTRANSACTION_USER_H */


text:
<?php
namespace Flowcode\FinancialBundle\Tests\Service;

use Flowcode\FinancialBundle\Tests\BaseTestCase;
use Flowcode\FinancialBundle\Service\FinanceService;
use Flowcode\FinancialBundle\Service\TransactionService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Flowcode\FinancialBundle\Entity\Core\JournalEntry;
use Flowcode\FinancialBundle\Entity\Core\Transaction;
use Flowcode\FinancialBundle\Entity\Core\Account;
use Flowcode\FinancialBundle\Entity\Payment\Payment;
use Flowcode\FinancialBundle\Entity\Payment\PaymentDocument;
use Flowcode\FinancialBundle\Entity\Payment\Income;
use Flowcode\FinancialBundle\Entity\Payment\Expense;
use Flowcode\FinancialBundle\Entity\Currency\Currency;
use Flowcode\FinancialBundle\Entity\Payment\PaymentMethod;
use Flowcode\FinancialBundle\Service\InstanceService;
use Flowcode\FinancialBundle\Service\AccountService;
use Flowcode\FinancialBundle\Service\JournalEntityService;
use Flowcode\FinancialBundle\Entity\Document\Document;
use Flowcode\FinancialBundle\Service\PaymentService;
use Flowcode\FinancialBundle\Service\DocumentService;
use Flowcode\FinancialBundle\Service\PaymentDocumentService;
use Flowcode\FinancialBundle\Model\Core\JournalEntryInterface;
use Flowcode\FinancialBundle\Model\Payment\PaymentInterface;
use Flowcode\FinancialBundle\Model\Payment\PaymentDocumentInterface;
use Flowcode\FinancialBundle\Model\Core\TransactionInterface;
use Flowcode\FinancialBundle\Tests\Mocks\DocumentMock;
use Flowcode\FinancialBundle\Repository\Core\TransactionRepository;

class FinanceServiceTest extends BaseTestCase
{

    /**
     * Probamos que al enviar un documento con un amount, un income y el metodo de pago se creen
     * correctamente toda la informacion relacionado a el documento de a una venta instantanea.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateInstantSale_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $income = $this->getMockBuilder(Income::class)
            ->getMockForAbstractClass();
        $incomeFinantialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();
        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);
        $incomeFinantialAccount->setCurrency($currency);
        $income->addAccount($incomeFinantialAccount);

        $paymentMethod = $this->getMockBuilder(PaymentMethod::class)
            ->getMockForAbstractClass();
        $paymentMethodFinancialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $paymentMethodFinancialAccount->setCurrency($currency);
        $paymentMethod->addAccount($paymentMethodFinancialAccount);

        $paymentService = $this->getPaymentService();
        $paymentDocumentService = $this->getPaymentDocumentService();

        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $document->setCurrency($currency);
        $document->setTotal($amount);
        $document = $financeService->createInstantSale($document, $income, $paymentMethod);

        $this->assertEquals($amount, $document->getTotalPayed());
        // No debe haber nada pendiente de pago
        $this->assertEquals(0, $document->getBalance());
        $this->assertEquals(Document::STATUS_PAID, $document->getStatus());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];

        $this->assertEquals(2, count($transaction->getJournalEntries()));

        $this->assertEquals(1, count($document->getPaymentsDocuments()));
        $this->assertEquals($amount, $document->getPaymentsDocuments()[0]->getAmount());

        $this->assertEquals($amount, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($incomeFinantialAccount, $transaction->getJournalEntries()[0]->getAccount());
        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getDebit());

        $this->assertEquals($amount, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($paymentMethodFinancialAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    /**
     * Probamos que al enviar un documento con un amount, un income y una cuenta cree el documento con toda la informacion
     * correcta.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateSaleOrder_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $income = $this->getMockBuilder(Income::class)
            ->getMockForAbstractClass();
        $incomeFinantialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);
        $incomeFinantialAccount->setCurrency($currency);
        $income->addAccount($incomeFinantialAccount);

        $clientAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();
        $paymentService = $this->getPaymentService();
        $paymentDocumentService = $this->getPaymentDocumentService();
        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $document->setCurrency($currency);
        $document->setTotal($amount);
        $document = $financeService->createSaleOrder($document, $income, $clientAccount);

        $this->assertEquals(0, $document->getTotalPayed());
        $this->assertEquals(0, $document->getBalance());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];

        $this->assertEquals(2, count($transaction->getJournalEntries()));

        $this->assertEquals(0, count($document->getPaymentsDocuments()));

        $this->assertEquals($amount, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($incomeFinantialAccount, $transaction->getJournalEntries()[0]->getAccount());
        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getDebit());

        $this->assertEquals($amount, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($clientAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    /**
     * Dado un documento probamos agregar un pago al mismo por el monto total y que toda la informacion se actualize correctamente.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateSaleOrderPayment_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $paymentMethod = $this->getMockBuilder(PaymentMethod::class)
            ->getMockForAbstractClass();
        $paymentMethodFinancialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);

        $paymentMethodFinancialAccount->setCurrency($currency);
        $paymentMethod->addAccount($paymentMethodFinancialAccount);

        $clientAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();
        $paymentService = $this->getPaymentService();
        $paymentDocumentService = $this->getPaymentDocumentService();
        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $document->setTotal($amount);
        $document->setCurrency($currency);

        $document = $financeService->createSaleOrderPayment($document, $clientAccount, $paymentMethod, $amount);

        $this->assertEquals($amount, $document->getTotalPayed());
        // No debe haber nada pendiente de pago
        $this->assertEquals(0, $document->getBalance());
        $this->assertEquals(Document::STATUS_PAID, $document->getStatus());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];

        $this->assertEquals(2, count($transaction->getJournalEntries()));

        $this->assertEquals(1, count($document->getPaymentsDocuments()));
        $this->assertEquals($amount, $document->getPaymentsDocuments()[0]->getAmount());

        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[0]->getDebit());
        $this->assertEquals($paymentMethodFinancialAccount, $transaction->getJournalEntries()[0]->getAccount());

        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($clientAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    /**
     * Dado un documento probamos agregar un pago a el mismo y que toda la informacion se actualize correctamente.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateSaleOrderPartialPayment_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $paymentMethod = $this->getMockBuilder(PaymentMethod::class)
            ->getMockForAbstractClass();
        $paymentMethodFinancialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);
        $paymentMethodFinancialAccount->setCurrency($currency);
        $paymentMethod->addAccount($paymentMethodFinancialAccount);

        $clientAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();
        $paymentService = $this->getPaymentService();
        $paymentDocumentService = $this->getPaymentDocumentService();
        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $paymentAmount = 100;
        $document->setTotal($amount);
        $document->setCurrency($currency);
        $document = $financeService->createSaleOrderPayment($document, $clientAccount, $paymentMethod, $paymentAmount);

        $this->assertEquals($paymentAmount, $document->getTotalPayed());
        // Debe haber nada pendiente de pago
        $this->assertEquals($amount - $paymentAmount, $document->getBalance());
        $this->assertNotEquals(Document::STATUS_PAID, $document->getStatus());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];

        $this->assertEquals(2, count($transaction->getJournalEntries()));

        $this->assertEquals(1, count($document->getPaymentsDocuments()));
        $this->assertEquals($paymentAmount, $document->getPaymentsDocuments()[0]->getAmount());

        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($paymentAmount, $transaction->getJournalEntries()[0]->getDebit());
        $this->assertEquals($paymentMethodFinancialAccount, $transaction->getJournalEntries()[0]->getAccount());

        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals($paymentAmount, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($clientAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    /**
     * Probamos que al enviar un documento con un amount, un expense y el metodo de pago se creen
     * correctamente toda la informacion relacionado a el documento de un gasto instantanea.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateInstantExpense_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $expense = $this->getMockBuilder(Expense::class)
            ->getMockForAbstractClass();
        $expenseFinantialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);
        $expenseFinantialAccount->setCurrency($currency);
        $expense->addAccount($expenseFinantialAccount);

        $paymentMethod = $this->getMockBuilder(PaymentMethod::class)
            ->getMockForAbstractClass();
        $paymentMethodFinancialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $paymentMethodFinancialAccount->setCurrency($currency);
        $paymentMethod->addAccount($paymentMethodFinancialAccount);

        $paymentService = $this->getPaymentService();

        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');
        $paymentDocumentService = $this->getPaymentDocumentService();

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $document->setCurrency($currency);
        $document->setTotal($amount);
        $document = $financeService->createInstantExpense($document, $expense, $paymentMethod);

        $this->assertEquals($amount, $document->getTotalPayed());
        // No debe haber nada pendiente de pago
        $this->assertEquals(0, $document->getBalance());
        $this->assertEquals(Document::STATUS_PAID, $document->getStatus());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];
        $this->assertEquals(2, count($transaction->getJournalEntries()));
        $this->assertEquals(1, count($document->getPaymentsDocuments()));
        $this->assertEquals($amount, $document->getPaymentsDocuments()[0]->getAmount());

        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[0]->getDebit());
        $this->assertEquals($expenseFinantialAccount, $transaction->getJournalEntries()[0]->getAccount());

        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($paymentMethodFinancialAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    /**
     * Probamos que al enviar un documento con un amount, un cuenta del cliente y el metodo de pago se creen
     * correctamente toda la informacion relacionado a el documento de un gasto instantanea.
     * @fecha   2017-04-04
     * @author Francisco Memoli Olmos
     * @email   fmemoli@flowcode.com.ar
     * @version [version]
     * @return  [type]                  [description]
     */
    public function testCreateExpenseClient_returnDocumentWithCorrectInformation()
    {
        $document = new DocumentMock();
        $clientFinantialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $currency = $this->getMockBuilder(Currency::class)
            ->setMethods(['getId'])
            ->getMockForAbstractClass();
        $currency
            ->method('getId')
            ->willReturn(1);
        $clientFinantialAccount->setCurrency($currency);

        $paymentMethod = $this->getMockBuilder(PaymentMethod::class)
            ->getMockForAbstractClass();
        $paymentMethodFinancialAccount = $this->getMockBuilder(Account::class)
            ->getMockForAbstractClass();

        $paymentMethodFinancialAccount->setCurrency($currency);
        $paymentMethod->addAccount($paymentMethodFinancialAccount);

        $paymentService = $this->getPaymentService();

        $documentService = $this->getMockBuilder(DocumentService::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $transactionService = $this->getTransactionService();
        $this->journalEntityManagerInterface->expects($this->exactly(2))->method('updateBalance');
        $paymentDocumentService = $this->getPaymentDocumentService();

        $transactionRepository = $this->getMockBuilder(TransactionRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $financeService = new FinanceService(
            $transactionService, $documentService, $paymentService, $paymentDocumentService, $transactionRepository
        );
        $amount = 1000;
        $document->setCurrency($currency);
        $document->setTotal($amount);
        $document = $financeService->createExpenseAccount($document, $clientFinantialAccount, $paymentMethod);

        $this->assertEquals($amount, $document->getTotalPayed());
        $this->assertEquals(0, $document->getBalance());
        $this->assertEquals(Document::STATUS_PAID, $document->getStatus());

        $transactions = $document->getTransactions();
        $this->assertEquals(1, count($transactions));
        $transaction = $transactions[0];
        $this->assertEquals(2, count($transaction->getJournalEntries()));
        $this->assertEquals(1, count($document->getPaymentsDocuments()));
        $this->assertEquals($amount, $document->getPaymentsDocuments()[0]->getAmount());

        $this->assertEquals(0, $transaction->getJournalEntries()[0]->getCredit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[0]->getDebit());
        $this->assertEquals($clientFinantialAccount, $transaction->getJournalEntries()[0]->getAccount());

        $this->assertEquals(0, $transaction->getJournalEntries()[1]->getDebit());
        $this->assertEquals($amount, $transaction->getJournalEntries()[1]->getCredit());
        $this->assertEquals($paymentMethodFinancialAccount, $transaction->getJournalEntries()[1]->getAccount());
    }

    private function getTransactionService()
    {
        $instanceManagerInterface = $this->getMockBuilder(InstanceService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->accountManagerInterface = $this->getMockBuilder(AccountService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->journalEntityManagerInterface = $this->getMockBuilder(JournalEntityService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $callBack = $this->getMockCallbackForGetInstanceFromInterface();
        $instanceManagerInterface
            ->method('getInstanceFromInterface')
            ->will($this->returnCallback($callBack));
        return new TransactionService($instanceManagerInterface, $this->accountManagerInterface, $this->journalEntityManagerInterface);
    }

    private function getPaymentService()
    {
        $instanceManagerInterface = $this->getMockBuilder(InstanceService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $callBack = $this->getMockCallbackForGetInstanceFromInterface();
        $instanceManagerInterface
            ->method('getInstanceFromInterface')
            ->will($this->returnCallback($callBack));
        return new PaymentService($instanceManagerInterface);
    }

    private function getPaymentDocumentService()
    {
        $instanceManagerInterface = $this->getMockBuilder(InstanceService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $callBack = $this->getMockCallbackForGetInstanceFromInterface();
        $instanceManagerInterface
            ->method('getInstanceFromInterface')
            ->will($this->returnCallback($callBack));
        return new PaymentDocumentService($instanceManagerInterface);
    }

    private function getMockCallbackForGetInstanceFromInterface()
    {
        return (
            function ($class) {
                $entity = null;
                switch ($class) {
                    case PaymentInterface::class:
                        $entity = $this->getMockBuilder(Payment::class)
                            ->getMockForAbstractClass();
                        break;
                    case JournalEntryInterface::class:
                        $entity = $this->getMockBuilder(JournalEntry::class)
                            ->getMockForAbstractClass();
                        break;
                    case TransactionInterface::class:
                        $entity = $this->getMockBuilder(Transaction::class)
                            ->getMockForAbstractClass();
                        break;
                    case PaymentDocumentInterface::class:
                        $entity = $this->getMockBuilder(PaymentDocument::class)
                            ->getMockForAbstractClass();
                        break;
                    default:
                        $entity = $this->getMockBuilder('Flowcode\FinancialBundle\Entity\Core\Transaction')
                            ->getMockForAbstractClass();
                        break;
                }
                return $entity;
            }
            );
    }
}


text:
bool LoadFile(const std::string& filename, std::string* result) {
  std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
  if (file.is_open()) {
    size_t size = file.tellg();
    std::vector<char> buffer(size);
    file.seekg(0, std::ios::beg);
    file.read(buffer.data(), size);
    file.close();
    if (!file) return false;  // file reading error (failbit or badbit).
    result->assign(buffer.begin(), buffer.end());
    return true;
  }
  return false;
}

void ShowHelp(int argc, char** argv) {
  std::cerr << "Shows whether the given user_agent and URI combination"
            << " is allowed or disallowed by the given robots.txt file. "
            << std::endl
            << std::endl;
  std::cerr << "Usage: " << std::endl
            << "  " << argv[0] << " <robots.txt filename> <user_agent> <URI>"
            << std::endl
            << std::endl;
  std::cerr << "The URI must be %-encoded according to RFC3986." << std::endl
            << std::endl;
  std::cerr << "Example: " << std::endl
            << "  " << argv[0] << " robots.txt FooBot http://example.com/foo"
            << std::endl;
}

int main(int argc, char** argv) {
  std::string filename = argc >= 2 ? argv[1] : "";
  if (filename == "-h" || filename == "-help" || filename == "--help") {
    ShowHelp(argc, argv);
    return 2;
  }
  if (argc != 4) {
    std::cerr << "Invalid amount of arguments. Showing help." << std::endl
              << std::endl;
    ShowHelp(argc, argv);
    return 2;
  }
  std::string robots_content;
  if (!(LoadFile(filename, &robots_content))) {
    std::cerr << "failed to read file \"" << filename << "\"" << std::endl;
    return 2;
  }

  std::string user_agent = argv[2];
  std::vector<std::string> user_agents(1, user_agent);
  googlebot::RobotsMatcher matcher;
  std::string url = argv[3];
  bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url);

  std::cout << "user-agent '" << user_agent << "' with URI '" << argv[3]
            << "': " << (allowed ? "ALLOWED" : "DISALLOWED") << std::endl;
  if (robots_content.empty()) {
    std::cout << "notice: robots file is empty so all user-agents are allowed"
              << std::endl;
  }

  return allowed ? 0 : 1;
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Practices.Unity.InterceptionExtension;
using ServiceBridge.Interception;
using IMethodInvocation = Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation;
using IMethodReturn = Microsoft.Practices.Unity.InterceptionExtension.IMethodReturn;
using PipelineManager = ServiceBridge.Interception.PipelineManager;

namespace ServiceBridge.Unity.Interception
{
    internal class UnityInjectionBehavior : IInterceptionBehavior
    {
        private readonly PipelineManager _pipelineManager;

        /// <summary>
        ///     Initializes a new instance of the <see cref="UnityInjectionBehavior" /> with a pipeline manager.
        /// </summary>
        /// <param name="pipelineManager">
        ///     The <see cref="PipelineManager" /> for
        ///     the new instance.
        /// </param>
        internal UnityInjectionBehavior(PipelineManager pipelineManager)
        {
            _pipelineManager = pipelineManager;
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="UnityInjectionBehavior" /> with the given information
        ///     about what's being intercepted and the current set of injection policies.
        /// </summary>
        /// <param name="interceptionRequest">Information about what will be injected.</param>
        /// <param name="container">Service container that can be used to resolve interceptors.</param>
        public UnityInjectionBehavior(CurrentInterceptionRequest interceptionRequest, IServiceContainer container)
        {
            if (interceptionRequest == null)
            {
                throw new ArgumentNullException(nameof(interceptionRequest));
            }
            var hasHandlers = false;

            var manager = new PipelineManager(container.GetInstance<IInterceptorFactory>());
            foreach (
                var method in
                    interceptionRequest.Interceptor.GetInterceptableMethods(interceptionRequest.TypeToIntercept,
                        interceptionRequest.ImplementationType))
            {
                var hasNewHandlers = manager.InitializePipeline(method.InterfaceMethodInfo, method.ImplementationMethodInfo, container);
                hasHandlers = hasHandlers || hasNewHandlers;
            }
            foreach (var constructor in interceptionRequest.ImplementationType.GetConstructors())
            {
                var hasNewHandlers = manager.InitializePipeline(constructor, container);
                hasHandlers = hasHandlers || hasNewHandlers;
            }
            _pipelineManager = hasHandlers ? manager : null;
        }

        /// <summary>
        ///     Execute behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>Return value from the target.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Func<IMethodInvocation, IMethodReturn> defaultInvoke = invocation =>
            {
                try
                {
                    return getNext()(invocation, getNext);
                }
                catch (TargetInvocationException ex)
                {
                    // The outer exception will always be a reflection exception; we want the inner, which is
                    // the underlying exception.
                    return invocation.CreateExceptionMethodReturn(ex.InnerException);
                }
            };
            if (_pipelineManager == null) return defaultInvoke(input);
            var methodReturn = _pipelineManager.GetPipeline(input.MethodBase).Invoke(new UnityMethodInvocation(input),
                (injectionInvocation, injectionGetNext) =>
                    new UnityMethodReturn(defaultInvoke(((UnityMethodInvocation) injectionInvocation).Unwrap())));
            return ((UnityMethodReturn) methodReturn).Unwrap();
        }

        /// <summary>
        ///     Returns the interfaces required by the behavior for the objects it intercepts.
        /// </summary>
        /// <returns>The required interfaces.</returns>
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        /// <summary>
        ///     Returns a flag indicating if this behavior will actually do anything when invoked.
        /// </summary>
        /// <remarks>
        ///     This is used to optimize interception. If the behaviors won't actually
        ///     do anything (for example, PIAB where no policies match) then the interception
        ///     mechanism can be skipped completely.
        /// </remarks>
        public bool WillExecute => true;
    }
}


text:
<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
  <mime-type type="text/wiki">
    <comment>WikidPad File</comment>
    <glob pattern="*.wiki"/>
  </mime-type>
</mime-info>


text:
<?php
namespace Cerad\Bundle\PersonBundle\Entity;

//  Doctrine\Common\Collections\ArrayCollection;

use Cerad\Bundle\PersonBundle\Model\PersonPerson as PersonPersonModel;;

class PersonPerson extends PersonPersonModel
{
    public function __construct()
    {
        parent::__construct();
    }
}
?>


text:
package org.neo4j.kernel.impl.transaction.state;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.neo4j.kernel.impl.store.record.DynamicRecord;
import org.neo4j.kernel.impl.store.record.LabelTokenRecord;
import org.neo4j.kernel.impl.store.record.NodeRecord;
import org.neo4j.kernel.impl.store.record.PrimitiveRecord;
import org.neo4j.kernel.impl.store.record.PropertyKeyTokenRecord;
import org.neo4j.kernel.impl.store.record.PropertyRecord;
import org.neo4j.kernel.impl.store.record.RelationshipGroupRecord;
import org.neo4j.kernel.impl.store.record.RelationshipRecord;
import org.neo4j.kernel.impl.store.record.RelationshipTypeTokenRecord;
import org.neo4j.kernel.impl.store.record.SchemaRule;
import org.neo4j.kernel.impl.transaction.state.RecordAccess.Loader;

/**
 * Can be used to mimic a store with use in a {@link RecordChangeSet}.
 */
public class ControlledLoaders
{
    private final ControlledLoader<Long,NodeRecord,Void> nodes = new ControlledLoader<>();
    private final ControlledLoader<Long,PropertyRecord,PrimitiveRecord> properties = new ControlledLoader<>();
    private final ControlledLoader<Long,RelationshipRecord,Void> relationships = new ControlledLoader<>();
    private final ControlledLoader<Long,RelationshipGroupRecord,Integer> relationshipGroups = new ControlledLoader<>();
    private final ControlledLoader<Long,Collection<DynamicRecord>,SchemaRule> schemaRules = new ControlledLoader<>();
    private final ControlledLoader<Integer,PropertyKeyTokenRecord,Void> propertyKeyTokens = new ControlledLoader<>();
    private final ControlledLoader<Integer,LabelTokenRecord,Void> labelTokens = new ControlledLoader<>();
    private final ControlledLoader<Integer,RelationshipTypeTokenRecord,Void> relationshipTypeTokens = new ControlledLoader<>();

    public Map<Long,NodeRecord> getNodes()
    {
        return nodes.data;
    }

    public Map<Long,PropertyRecord> getProperties()
    {
        return properties.data;
    }

    public Map<Long,RelationshipRecord> getRelationships()
    {
        return relationships.data;
    }

    public Map<Long,RelationshipGroupRecord> getRelationshipGroups()
    {
        return relationshipGroups.data;
    }

    public RecordAccessSet newAccessSet()
    {
        return new RecordChangeSet( false, nodes, properties, relationships, relationshipGroups, schemaRules,
                propertyKeyTokens, labelTokens, relationshipTypeTokens );
    }

    private static class ControlledLoader<KEY,RECORD,ADDITIONAL> implements Loader<KEY,RECORD,ADDITIONAL>
    {
        private final Map<KEY,RECORD> data = new HashMap<>();

        @Override
        public RECORD newUnused( KEY key, ADDITIONAL additionalData )
        {
            throw new UnsupportedOperationException( "Please implement" );
        }

        @Override
        public RECORD load( KEY key, ADDITIONAL additionalData )
        {
            return data.get( key );
        }

        @Override
        public void ensureHeavy( RECORD record )
        {
            // Just assume everything is heavy already
        }

        @Override
        public RECORD clone( RECORD record )
        {
            throw new UnsupportedOperationException( "Please implement" );
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;

namespace Cake.Common.Tools.OctopusDeploy
{
    /// <summary>
    /// The Octopus Deploy Promote Release runner. This class facilitates promoting existing releases in Octopus Deploy.
    /// </summary>
    public sealed class OctopusDeployReleasePromoter : Tool<OctopusDeployPromoteReleaseSettings>
    {
        private readonly ICakeEnvironment _environment;

        /// <summary>
        /// Initializes a new instance of the <see cref="OctopusDeployReleasePromoter"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="processRunner">The process runner.</param>
        /// <param name="tools">The tool locator.</param>
        public OctopusDeployReleasePromoter(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools)
            : base(fileSystem, environment, processRunner, tools)
        {
            _environment = environment;
        }

        /// <summary>
        /// Requests a promotion of a specified release to an environment.
        /// </summary>
        /// <param name="server">Octopus Server URL</param>
        /// <param name="apiKey">The user's API key</param>
        /// <param name="projectName">Name of the target project</param>
        /// <param name="deployFrom">Environment to promote from, e.g., Staging</param>
        /// <param name="deployTo">Environment to promote to, e.g., Production</param>
        /// <param name="settings">Settings for the deployment</param>
        public void PromoteRelease(string server, string apiKey, string projectName, string deployFrom, string deployTo, OctopusDeployPromoteReleaseSettings settings)
        {
            if (String.IsNullOrEmpty(server))
            {
                throw new ArgumentNullException(nameof(server));
            }

            if (String.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            if (String.IsNullOrEmpty(projectName))
            {
                throw new ArgumentNullException(nameof(projectName));
            }

            if (String.IsNullOrEmpty(deployFrom))
            {
                throw new ArgumentNullException(nameof(deployFrom));
            }

            if (String.IsNullOrEmpty(deployTo))
            {
                throw new ArgumentNullException(nameof(deployTo));
            }

            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var argumentBuilder = new PromoteReleaseArgumentBuilder(server, apiKey, projectName, deployFrom, deployTo, settings, _environment);
            Run(settings, argumentBuilder.Get());
        }

        /// <summary>
        /// Gets the name of the tool.
        /// </summary>
        /// <returns>The name of the tool.</returns>
        protected override string GetToolName()
        {
            return "Octo";
        }

        /// <summary>
        /// Gets the possible names of the tool executable.
        /// </summary>
        /// <returns>The tool executable name.</returns>
        protected override IEnumerable<string> GetToolExecutableNames()
        {
            return new[] { "Octo.exe" };
        }
    }
}


text:
<!doctype html>

    <title>Code coverage report for thinkjs/lib/Lib/Util/Cache.js</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../../../../prettify.css">

Code coverage report for thinkjs/lib/Lib/Util/Cache.js

        Statements: 100% (58 / 58)

        Branches: 100% (51 / 51)

        Functions: 100% (8 / 8)

        Lines: 100% (58 / 58)

        Ignored: none

All files » thinkjs/lib/Lib/Util/ » Cache.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

2

2

2

115
40

75
73
73
72

1

2

2

115
115
115
1

115
96

115

115

115
115

11
11
2

9
9
3
3

6
3

6

6
3
3
1

6

13
1

13

13
6
7
1

13
5

8

13

4
4
2
1

2

4

4
5
5
1

/**
 * 缓存基类
 * @return {[type]} [description]
 */
/**
 * 缓存数据
 * @type {Object}
 */
var cacheData = {};
/**
 * 定时器
 * @type {Number}
 */
var gcTimer = {};
/**
 * 清除已经过期的Cache
 * @return {[type]} [description]
 */
var gc = function(instance){
  'use strict';
  if (APP_DEBUG || APP_MODE === 'cli' || gcTimer[instance.gcType]) {
    return;
  }
  gcTimer[instance.gcType] = setInterval(function(){
    var hour = (new Date()).getHours();
    if (C('cache_gc_hour').indexOf(hour) === -1) {
      return;
    }
    return instance.gc && instance.gc(Date.now());
  }, 3600 * 1000);
};

module.exports = Class(function(){
  'use strict';
  return {
    /**
     * gc的类型,用于定时器类型判断
     * @type {String}
     */
    gcType: 'Cache',
    /**
     * 初始化
     * @param  {[type]} options [description]
     * @return {[type]}         [description]
     */
    init: function(options){
      options = options || {};
      this.cacheData = options.cacheData || cacheData;
      if (options.gcType) {
        this.gcType = options.gcType;
      }
      if (!options.timeout) {
        options.timeout = C('cache_timeout')
      }
      this.options = options;
      //操作的key
      this.key = '';
      //是否更新expire值
      this.updateExpire = this.options.updateExpire || false;
      gc(this);
    },
    /**
     * 获取缓存值,返回一个promise
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    get: function(name){
      var key = this.key || name;
      if (!(key in this.cacheData)) {
        return getPromise();
      }
      var value = this.cacheData[key];
      if (Date.now() > value.expire) {
        delete this.cacheData[key];
        return getPromise();
      }
      if (this.updateExpire) {
        this.cacheData[key].expire = Date.now() + value.timeout * 1000;
      }
      var data = value.data[name];
      //如果data是个对象或者数组,需要深度拷贝
      if (isObject(data)) {
        data = extend({}, data);
      }else if (isArray(data)) {
        data = extend([], data);
      }
      return getPromise(data);
    },
    /**
     * 设置缓存值
     * @param {[type]} name   [description]
     * @param {[type]} value  [description]
     */
    set: function(name, value, timeout){
      if (timeout === undefined) {
        timeout = this.options.timeout;
      }
      var key = this.key || name;
      //如果value是个对象或者数组,这里需要深度拷贝,防止程序里修改值导致缓存值被修改
      if (isObject(value)) {
        value = extend({}, value);
      }else if (isArray(value)) {
        value = extend([], value);
      }
      if (key in this.cacheData) {
        this.cacheData[key].data[name] = value;
      }else{
        this.cacheData[key] = {
          data: getObject(name, value),
          timeout: timeout,
          expire: Date.now() + timeout * 1000
        };
      }
      return getPromise();
    },
    /**
     * 移除缓存值
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    rm: function(name){
      var key = this.key || name;
      if (this.key) {
        if (key in this.cacheData) {
          delete this.cacheData[key].data[name];
        }
      }else{
        delete this.cacheData[name];
      }
      return getPromise();
    },
    /**
     * gc
     * @param  {[type]} now [description]
     * @return {[type]}     [description]
     */
    gc: function(now){
      for(var key in this.cacheData){
        var item = this.cacheData[key];
        if (item && now > item.expire) {
          delete this.cacheData[key];
        }
      }
    }
  };
});

Generated by istanbul at Tue Sep 23 2014 16:53:49 GMT+0800 (CST)


text:
import { normalize, schema } from 'normalizr';

export default class Normalizer {
    private idOption: object;
    private job: schema.Entity;
    private task: schema.Entity;
    // tslint:disable-next-line
    private provider_task: schema.Entity;
    // tslint:disable-next-line
    private provider_tasks: schema.Array;
    private run: schema.Entity;
    private runs: schema.Array;
    private user: schema.Entity;
    private userData: schema.Entity;

    public constructor() {
        this.idOption = { idAttribute: 'uid' };

        // run schemas
        this.job = new schema.Entity('jobs', {}, this.idOption);
        this.task = new schema.Entity('tasks', {}, this.idOption);
        this.provider_task = new schema.Entity('provider_tasks', { tasks: new schema.Array(this.task) }, this.idOption);
        this.provider_tasks = new schema.Array(this.provider_task);
        this.run = new schema.Entity('runs', { job: this.job, provider_tasks: this.provider_tasks }, this.idOption);
        this.runs = new schema.Array(this.run);
    }

    public normalizeRun(run) {
        return normalize(run, this.run);
    }
}


text:
<?php
$rootDir = dirname(dirname(__FILE__));

if (!(include __DIR__ . '/../vendor/autoload.php')) {
    error_log('Dependencies are not installed!', E_USER_ERROR);
    header("HTTP/1.1 500 Internal Server Error");
    die();
}

if (php_sapi_name() !== 'cli') {
    error_log('Script must be called from cli', \E_USER_ERROR);
    die('Script must be called from cli');
}

use OptimusCrime\Site\Generator\Generator;

try {
    $generator = new Generator(dirname(__DIR__));
    $generator->run();
}
catch (Exception $e) {
    echo 'Uncaught exception' . PHP_EOL;
    var_dump($e->getMessage());
    var_dump($e->getTraceAsString());
    die();
}


text:
{% extends "account/base.html" %}
{% load crispy_forms_tags %}

{% block title %}Register{% endblock %}

{% block content %}

{{ state }}

<form action='' method="post">
    {% csrf_token %}
    {{ reg_form | crispy }}
    {{ pass_form | crispy }}

            <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>

            <button class="btn btn-lg btn-block" type="reset">Reset</button>

</form>
{% endblock %}


text:
	This package provides classes with numerical algorithm for optimization of
	an objective function and a factory to easy construction of the optimizers.

Why a package for optimization algorithms?

	Given that there are a variety of numerical libraries featuring optimization algorithms
	(e.g., Apache Commons Math), why do we provide a package inside finmath lib?
	This packages provides a unified interface for passing optimizers to other classes
	via an OptimizationFactoryInterface and an OptimizerInterface
	and an OptimizerInterface.ObjectiveFunction.
	This allows use of different optimization frameworks without bothering with the
	framework specific constructors and framework specific definitions of objective functions.

	A class implementing the OptimizationFactoryInterface allows the
	specification of parameters specific to the optimizer, but leave the specification
	of the initial values and the objective function still open. It provides a factory
	method which takes the objective function and initial values as parameters and
	constructs the specific optimizer by returning an object implementing
	OptimizerInterface.

Example

The following code is an example of an optimization problem using an OptimizerFactoryInterface
as argument.

	public void testOptimizerWithRosenbrockFunction(OptimizerFactoryInterface optimizerFactory) throws SolverException {
		OptimizerInterface.ObjectiveFunction objectiveFunction = new OptimizerInterface.ObjectiveFunction() {
				@Override
				public void setValues(double[] parameters, double[] values) {
					values[0] = 10.0 * (parameters[1] - parameters[0]*parameters[0]);
					values[1] = 1.0 - parameters[0];
				}
		};

		OptimizerInterface optimizer = optimizerFactory.getOptimizer(
				objectiveFunction,
				new double[] { 0.5, 0.5 } /* initialParameters */,
				new double[] { Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY } /* lowerBound */,
				new double[] { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY } /* upperBound */,
				new double[] { 0.5, 0.5 } /* parameterStep */,
				new double[] { 0.0, 0.0 } /* targetValues */);

		optimizer.run();

		double[] bestParameters = optimizer.getBestFitParameters();
		System.out.println("The solver " + optimizer.getClass() + " for problem 'Rosebrock' required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:");
		for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]);

		System.out.println();

		Assert.assertTrue(Math.abs(bestParameters[0] - 1.0) < 1E-10);
		Assert.assertTrue(Math.abs(bestParameters[1] - 1.0) < 1E-10);
	}

Now, we may pass different optimizers to the optimization problem. For example the CMA-ES solver from commons math:

	public void testRosenbrockFunctionWithCMAES() throws SolverException {

		OptimizerFactoryInterface optimizerFactory = new OptimizerFactoryCMAES(0.0 /* accuracy */, 200 /* maxIterations */);
		this.testOptimizerWithRosenbrockFunction(optimizerFactory);
	}

Or the multi-threadded Levenberg Marquardt solver (using two threads) from finmath-lib:

	@Test
	public void testRosenbrockFunctionWithLevenbergMarquard() throws SolverException {

		OptimizerFactoryInterface optimizerFactory = new OptimizerFactoryLevenbergMarquardt(200 /* maxIterations */, 2 /* maxThreads */);
		this.testOptimizerWithRosenbrockFunction(optimizerFactory);
	}

Optimization algorithms

	The package also contains an implementation of the Levenberg Marquardt optimizer,
	a multi-dimensional non-linear least-square.
	In addition we provide wrappers (via specific OptimizationFactoryInterface
	implementations) to some optimizers from Apache commons-math.


text:
package np.com.rupak.connector.service.entity;

/**
 * Created by Rupak on 9/20/2017
 */
public class Permission {
}


text:
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	RegistrationWizard rw("C:/Users/jieji/Desktop/work/IADE/T2propeller&MRA", 2);
	rw.setImageModalityNames(0, "T2 image ");
	rw.setImageModalityNames(1, "MRA image");

	if (QWizard::Accepted == rw.exec()) {

		qDebug() << *rw.getFileNames(0);
		qDebug() << *rw.getFileNames(1);
		qDebug() << rw.getDirectory();

	}
	return a.exec();
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'observed-gauge'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install observed-gauge

You might also need to install rrdtool:

    (CentOS or Ubuntu)
    $ sudo apt-get install librrd-dev

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'stadium', 'stadiums'
end


text:
package org.elasticsearch.index.field.data.doubles;

import gnu.trove.list.array.TDoubleArrayList;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.FieldCache;
import org.elasticsearch.common.RamUsage;
import org.elasticsearch.index.field.data.FieldDataType;
import org.elasticsearch.index.field.data.NumericFieldData;
import org.elasticsearch.index.field.data.support.FieldDataLoader;

import java.io.IOException;

/**
 *
 */
public abstract class DoubleFieldData extends NumericFieldData<DoubleDocFieldData> {

    public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];

    protected final double[] values;

    protected DoubleFieldData(String fieldName, double[] values) {
        super(fieldName);
        this.values = values;
    }

    @Override
    protected long computeSizeInBytes() {
        return RamUsage.NUM_BYTES_DOUBLE * values.length + RamUsage.NUM_BYTES_ARRAY_HEADER;
    }

    public final double[] values() {
        return this.values;
    }

    abstract public double value(int docId);

    abstract public double[] values(int docId);

    @Override
    public DoubleDocFieldData docFieldData(int docId) {
        return super.docFieldData(docId);
    }

    @Override
    protected DoubleDocFieldData createFieldData() {
        return new DoubleDocFieldData(this);
    }

    @Override
    public String stringValue(int docId) {
        return Double.toString(value(docId));
    }

    @Override
    public void forEachValue(StringValueProc proc) {
        for (int i = 1; i < values.length; i++) {
            proc.onValue(Double.toString(values[i]));
        }
    }

    @Override
    public byte byteValue(int docId) {
        return (byte) value(docId);
    }

    @Override
    public short shortValue(int docId) {
        return (short) value(docId);
    }

    @Override
    public int intValue(int docId) {
        return (int) value(docId);
    }

    @Override
    public long longValue(int docId) {
        return (long) value(docId);
    }

    @Override
    public float floatValue(int docId) {
        return (float) value(docId);
    }

    @Override
    public double doubleValue(int docId) {
        return value(docId);
    }

    @Override
    public FieldDataType type() {
        return FieldDataType.DefaultTypes.DOUBLE;
    }

    public void forEachValue(ValueProc proc) {
        for (int i = 1; i < values.length; i++) {
            proc.onValue(values[i]);
        }
    }

    public static interface ValueProc {
        void onValue(double value);
    }

    public abstract void forEachValueInDoc(int docId, ValueInDocProc proc);

    public static interface ValueInDocProc {
        void onValue(int docId, double value);

        void onMissing(int docId);
    }

    public static DoubleFieldData load(IndexReader reader, String field) throws IOException {
        return FieldDataLoader.load(reader, field, new DoubleTypeLoader());
    }

    static class DoubleTypeLoader extends FieldDataLoader.FreqsTypeLoader<DoubleFieldData> {

        private final TDoubleArrayList terms = new TDoubleArrayList();

        DoubleTypeLoader() {
            super();
            // the first one indicates null value
            terms.add(0);
        }

        @Override
        public void collectTerm(String term) {
            terms.add(FieldCache.NUMERIC_UTILS_DOUBLE_PARSER.parseDouble(term));
        }

        @Override
        public DoubleFieldData buildSingleValue(String field, int[] ordinals) {
            return new SingleValueDoubleFieldData(field, ordinals, terms.toArray());
        }

        @Override
        public DoubleFieldData buildMultiValue(String field, int[][] ordinals) {
            return new MultiValueDoubleFieldData(field, ordinals, terms.toArray());
        }
    }
}


text:
/**************************************************************************/
/*!
    @file     main.c
    @author   K. Townsend (microBuilder.eu)

    @section LICENSE

    Software License Agreement (BSD License)

    Copyright (c) 2011, microBuilder SARL
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holders nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "projectconfig.h"
#include "sysinit.h"

#include "core/gpio/gpio.h"
#include "core/systick/systick.h"

#ifdef CFG_INTERFACE
  #include "core/cmd/cmd.h"
#endif

/**************************************************************************/
/*!
    Approximates a 1 millisecond delay using "nop".  This is less
    accurate than a dedicated timer, but is useful in certain situations.

    The number of ticks to delay depends on the optimisation level set
    when compiling (-O).  Depending on the compiler settings, one of the
    two defined values for 'delay' should be used.
*/
/**************************************************************************/
void delayms(uint32_t ms)
{
  uint32_t delay = ms * ((CFG_CPU_CCLK / 100) / 45);      // Release Mode (-Os)
  // uint32_t delay = ms * ((CFG_CPU_CCLK / 100) / 120);  // Debug Mode (No optimisations)

  while (delay > 0)
  {
    __asm volatile ("nop");
    delay--;
  }
}

/**************************************************************************/
/*!
    Main program entry point.  After reset, normal code execution will
    begin here.
*/
/**************************************************************************/
int main(void)
{
  // Configure cpu and mandatory peripherals
  systemInit();

  uint32_t currentSecond, lastSecond;
  currentSecond = lastSecond = 0;

  while (1)
  {
    // Toggle LED once per second ... rollover = 136 years :)
    currentSecond = systickGetSecondsActive();
    if (currentSecond != lastSecond)
    {
      lastSecond = currentSecond;
      if (gpioGetValue(CFG_LED_PORT, CFG_LED_PIN) == CFG_LED_OFF)
      {
        gpioSetValue (CFG_LED_PORT, CFG_LED_PIN, CFG_LED_ON);
      }
      else
      {
        gpioSetValue (CFG_LED_PORT, CFG_LED_PIN, CFG_LED_OFF);
      }
    }

    // Poll for CLI input if CFG_INTERFACE is enabled in projectconfig.h
    #ifdef CFG_INTERFACE
      cmdPoll();
    #endif
  }

  return 0;
}


text:
FusionTable-Map-2-layers
========================

Use this template if you wish to create a Search-and-Filter map that turns on/off at least 2 layers (points and polygons), displays results in a sortable list, and draws data from Google Fusion Tables. The default point map displays a textual legend (A, B, C), with option to switch to numeric (0-100) values. Also, thematic polygon layers may be turned on/off in the background. Based on template customized by Derek Eder http://derekeder.com/searchable_map_template/

##Demos
Toggle display between map view and sortable list view
- http://jackdougherty.github.io/FusionTable-Map-2-layers

Display both map view and sortable list
- http://jackdougherty.github.io/FusionTable-Map-2-layers/index_both.html

##Create your own with this template:

1) Use Google Fusion Tables to create your point layer (all types in one table), and set the feature styles (set ranges, colors, etc.) and info windows.

2) Use Google Fusion Tables to create your polygon layers (each layer in its own table), and set feature styles (thematic shading, etc.) and info windows

3) Make your own copy of this template: either Fork to your own GitHub account, or Clone in Desktop, or Download a ZIP compressed version to your desktop.

4) Modify two files, following instructions in the code comments, to match your Google Fusion Tables:

- index.html (to toggle between map and sortable list) or index_both.html (to display both at same time)
- maps_lib.js (located inside the js folder)

Carefully read comments to display table results, which will be fully documented later. (ToDo)

3) Host everything on the web (such as a GitHub repository gh-pages branch)

Learn more in an open-access Data Visualization book-in-progress by Jack Dougherty at Trinity College CT
http://epress.trincoll.edu/dataviz

Coming soon: display dynamic polygon legend, similar to http://chicagobuildings.org/


text:
var express = require('express');
var mongoose = require('mongoose');
var path = require('path');
var main = require('./routes/main');
var api = require('./routes/api');

var bodyParser = require('body-parser');

console.log(__dirname);

// Connection URL
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
mongoose.connect(url);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

var app = express();
exports.app = app;

app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'pug');

app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', main);

app.use('/api', api);

app.use("/static", express.static(path.join(__dirname, '/public')));

app.listen(8080, '127.0.0.1', () => {
  console.log('Server listening on port 8080');
});


text:
<splashscreen>
    <item image="chameleon/splashscreen/first.png" duration="1000"/>
    <item image="chameleon/splashscreen/second.png" duration="2000"/>
</splashscreen>


text:
class AvatarAdapter
  attr_accessor :user, :client

  def initialize(user)
    @user = user
  end

  def client
    @client ||= Twitter::REST::Client.new(
        consumer_key: Rails.application.secrets.twitter_api,
        consumer_secret: Rails.application.secrets.twitter_secret)
  end

  def image_url
    client.user(user.twitter_handle).profile_image_uri(:bigger).to_s
  end
end


text:
using System;
using System.Globalization;
using System.Web.Mvc;

namespace Cats.Web.Hub.Helpers
{
    public static class DateHelpers
    {
        public static string ToCTSPreferedDateFormat(this DateTime date, string lang)
        {
            if(lang == "en")
            {
                IFormatProvider provider = new CultureInfo("en-GB");
                return date.ToString("dd-MMM-yyyy", provider);

            }else
            {
                Infrastructure.EthiopianDate ethiopianDate = new Infrastructure.EthiopianDate(date);
                return ethiopianDate.ToLongDateString();
            }

        }
        public static string FormatDateFromString(this HtmlHelper helper,string dateAsString)
        {
            DateTime theRealDate = Convert.ToDateTime((dateAsString));
            return ToCTSPreferedDateFormat(theRealDate,"am");
        }
        public static Decimal ToPreferedWeightMeasurment(this Decimal quantity, string weightMeasurment)
        {

            if (weightMeasurment.Equals("qn"))
            {
                return quantity*10;
            }
            return quantity;

        }

    }
}


text:
package org.jpmml.model.filters;

import java.util.List;

import org.dmg.pmml.PMML;
import org.dmg.pmml.Version;
import org.jpmml.model.ExtensionUtil;
import org.jpmml.model.ResourceUtil;
import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import static org.junit.Assert.assertEquals;

public class ExtensionFilterTest {

	@Test
	public void filter() throws Exception {
		PMML pmml = ResourceUtil.unmarshal(ExtensionFilterTest.class, new ImportFilter());

		assertEquals("4.0", pmml.getBaseVersion());

		List<?> content = ExtensionUtil.getContent(pmml);

		assertEquals(5, content.size());

		String whitespace = (String)content.get(0);

		assertEquals("", whitespace.trim());

		Element parentElement = (Element)content.get(1);

		assertEquals(Version.PMML_4_4.getNamespaceURI(), parentElement.getNamespaceURI());
		assertEquals("X-Parent", parentElement.getLocalName());

		NodeList children = parentElement.getChildNodes();

		assertEquals(3, children.getLength());

		Element childElement = (Element)children.item(1);

		assertEquals(Version.PMML_4_4.getNamespaceURI(), childElement.getNamespaceURI());
		assertEquals("X-Child", childElement.getLocalName());

		whitespace = (String)content.get(2);

		assertEquals("", whitespace.trim());

		Element testElement = (Element)content.get(3);

		assertEquals("http://localhost/test", testElement.getNamespaceURI());
		assertEquals("X-Test", testElement.getLocalName());

		whitespace = (String)content.get(4);

		assertEquals("", whitespace.trim());

		pmml = ResourceUtil.unmarshal(ExtensionFilterTest.class, new ImportFilter(false));

		assertEquals(null, pmml.getBaseVersion());

		pmml = ResourceUtil.unmarshal(ExtensionFilterTest.class, new ImportFilter(), new ExtensionFilter());

		assertEquals(null, pmml.getBaseVersion());

		content = ExtensionUtil.getContent(pmml);

		assertEquals(3, content.size());

		testElement = (Element)content.get(1);

		assertEquals("http://localhost/test", testElement.getNamespaceURI());
		assertEquals("X-Test", testElement.getLocalName());
	}
}