text:
package six.com.crawler.admin.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import six.com.crawler.admin.service.MasterScheduledService;
import six.com.crawler.entity.WorkerSnapshot;

/**
 * @author six
 * @date 2016年1月14日 上午10:10:58 爬虫 调度 api
 */
@Controller
public class MasterScheduledApi extends BaseApi {

	@Autowired
	private MasterScheduledService scheduledService;

	public MasterScheduledService getScheduledService() {
		return scheduledService;
	}

	public void setScheduledService(MasterScheduledService scheduledService) {
		this.scheduledService = scheduledService;
	}

	@RequestMapping(value = "/crawler/master/scheduled/execute/{jobName}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMsg<String> execute(@PathVariable("jobName") String jobName) {
		return scheduledService.execute(jobName);
	}

	@RequestMapping(value = "/crawler/master/scheduled/suspend/{jobName}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMsg<String> suspend(@PathVariable("jobName") String jobName) {
		return scheduledService.suspend(jobName);
	}

	@RequestMapping(value = "/crawler/master/scheduled/goon/{jobName}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMsg<String> goon(@PathVariable("jobName") String jobName) {
		return scheduledService.goOn(jobName);
	}

	@RequestMapping(value = "/crawler/master/scheduled/stop/{jobName}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMsg<String> stop(@PathVariable("jobName") String jobName) {
		return scheduledService.stop(jobName);
	}

	@RequestMapping(value = "/crawler/master/scheduled/getWorkerInfo/{jobName}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMsg<List<WorkerSnapshot>> getWorkerInfo(@PathVariable("jobName") String jobName) {
		return scheduledService.getWorkerInfo(jobName);
	}

}


text:
import { handleInstall, handleActivate, handleMessage, handleFetch } from './handlers';

// Install
self.addEventListener('install', event => handleInstall(event));

// Activate
self.addEventListener('activate', event => handleActivate(event));

// Message
self.addEventListener('message', event => handleMessage(event));

// Fetch
self.addEventListener('fetch', event => handleFetch(event));

redpajama_set_name: RedPajamaGithub


text:
Home

<?php echo $pagetitle ?>

<?php echo $pagetitle ?>

Version 0.4.7 - 2017-07-23

Bug Fix: A duplicate game entry in the database would produce more duplicate entries. #114

Bug Fix: Fixed error when sql_mode=only_full_group_by is set. #115

Version 0.4.6 - 2016-08-21

Change: Upgraded to Ignition 0.5.0. #109

Version 0.4.5 - 2016-05-03

Change: Crawler reborn as "Super Crawler". Now pulls 100 games at a time. #101

Version 0.4.4 - 2016-04-28

Change: Reduced dependencies on Giant Bomb. #57

Change: Cron job now processes search logs to expand game database. #96

Version 0.4.3 - 2016-02-18

Bug Fix: Giant Bomb now require user agent on API requests. #90

Version 0.4.2 - 2015-10-31

Change: Log API requests to database. #57

Version 0.4.1 - 2015-10-25

Change: Crawler to update game data now collects all the platforms a game is on. #57

Version 0.4.0 - 2015-10-24

Feature: Export collection to CSV. #73

Feature: View collection completion by platform. #36

Feature: Forgot your password. #44

Feature: "Who's played this?" show users who have completed / played a game on game pages. #59

Feature: Make Android status bar lemon yellow. #60

Change: Reduce width of profile page side bar. #56

Change: Upgraded to CodeIgniter 2.2.3

Change: Upgraded to Ignition 0.4.0 #72

Version 0.3.2 - 2015-01-17

Change: Upgraded Ignition from v0.1 to v0.3.

Change: Upgraded Bootstrap from v3.2 to v3.3.1.

Version 0.3.1 - 2015-01-02

Bug Fix: Cron job to update game caches got stuck on a game that no longer exists. #53

Version 0.3.0 - 2014-07-17

Feature: You can now follow users. #29

Feature: You can see what you and your followers have done recently in a new homepage feed. #29

Feature: HTTPS is now supported and enforced. #50

Feature: Added comments to blog posts. #12

Feature: Added a blog post archive.

Feature: Added YouTube support to markdown using the format ![youtube](l7iVsdRbhnc).

Change: Uncompletable games are no longer included in the completion percentage. #52

Change: Making a comment on an event will now bump it to the top of the feed.

Change: New look for events.

Change: New look for the blog.

Change: New look site footer with social links.

Change: New logo.

Change: Code restructure for the release of Ignition.

Change: Upgraded CodeIgniter from v2.1.4 to v2.2.0.

Change: Upgraded Bootstrap from v3.0 to v3.2.

Bug Fix: There was a missing "and" when an event contained "is playing" and one status. #51

Bug Fix: Some errors returned no message.

Version 0.2.3 - 2014-06-18

Change: Added meta tags to blog posts.

Version 0.2.2 - 2014-05-24

Bug Fix: Changing a game to no longer playing would produce a blank event.

Bug Fix: Prioritise old game caches in cron job.

Version 0.2.1 - 2014-05-13

Feature: Cron job to update game cache.

Version 0.2.0 - 2014-05-11

Feature: Collection stats now update live as filters are changed. #35

Feature: List and completion filters now have numbers against them. #35

Feature: "Add Games" button added to your collection page. #22

Feature: "What's Happening" box on homepage shows recent user activity. #21

Feature: Custom 404 page added. #43

Change: Wanted games are now excluded from collection total and completion percentage. #37

Change: "View More" button on collection page made more prominent.

Change: Clicking a platform checkbox when logged out now returns a prompt to login rather than being disabled. Clicking the checkbox before a game has been added to a list prompts the user to do so. #39

Change: Errors have been moved to a language file to allow us to add localisation in the future. #40

Change: All urls are now relative paths.

Bug Fix: Added support for unicode in game names and descriptions. #42

Version 0.1.0 - 2014-05-03

Alpha release.


text:
package org.apache.streams.local.test.processors;

import org.apache.streams.core.StreamsDatum;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PassThroughStaticCounterExceptionProcessor extends PassThroughStaticCounterProcessor{
    private final int numErrorsToThrow;
    private final AtomicInteger numErrorsThrown = new AtomicInteger(0);

    public PassThroughStaticCounterExceptionProcessor(int delay, int numErrorsToThrow) {
        super(delay);
        this.numErrorsToThrow = numErrorsToThrow <= 0 ? 1 : numErrorsToThrow;
    }

    @Override
    public List<StreamsDatum> process(StreamsDatum entry) {
        super.sleepSafely();
        super.count.incrementAndGet();
        List<StreamsDatum> result = new LinkedList<StreamsDatum>();

        if (this.numErrorsThrown.getAndIncrement() < this.numErrorsToThrow) {
            throw new RuntimeException();
        } else {
            result.add(entry);
        }

        return result;
    }
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Network.Consensus.Verified.Raft.Runner where

import Prelude hiding (init)
import Data.Map (Map)
import Data.Set (Set)
import Data.Reflection
import qualified Data.Map as Map
import Control.Applicative(Alternative,(<|>))
import Data.ByteString.Lazy.Char8 (ByteString)

import qualified Network.Consensus.Verified.Raft as Raft
import Network.Consensus.Verified.Raft (
  Res(..)
  ,StateMachine(..)
  ,Name(..)
--  ,Term(..)
--  ,LogIndex(..)
  ,RaftOutput(..)
  ,RaftInput(..)
  ,Msg(..)
  ,RaftData(..)
  ,Name(..))

data InputKV k v = PutKV k v
                 | GetKV k
                 | DelKV k
                 | CASKV k (Maybe v) v
                 | CADKV k v
                 deriving (Eq,Ord,Show)

data OutputKV k v = ResponseKV k (Maybe v) (Maybe v)
  deriving (Eq,Ord,Show)

kvHandler :: forall m k v kv. (Eq v, Monad m) => (kv -> k -> m (Maybe v))
      -> (kv -> k -> v -> m kv )
      -> (kv -> k -> m kv)
      -> StateMachine m (InputKV k v) kv (OutputKV k v,kv)
kvHandler get put del =
  StateMachine $ \ kv cmd ->
    case cmd of
      PutKV k v -> do oldV :: (Maybe v) <- get kv k ;
                      newkv <- put kv k v ;
                      return (ResponseKV k (Just v) oldV,newkv)
      GetKV k -> do v <- get kv k ; return (ResponseKV k v v, kv)
      DelKV k -> do old <- get kv k ; newKV<- del kv k ; return (ResponseKV k Nothing old, newKV)
      CASKV k v v' -> do old <- get kv k ;
                         if old == v
                           then do newKV <- put kv k v' ; return (ResponseKV k (Just v') old, newKV)
                           else return (ResponseKV k old old ,kv)
      CADKV k v -> do old <- get kv k  ;
                      if old == Just v
                        then do newKV <- del kv k ; return (ResponseKV k Nothing old, newKV)
                        else return (ResponseKV k old old,kv)

data Arrangement m state input output message request_id = Arrangement {
  init :: Name -> state
  ,reboot :: state -> state
-- note : handleIO and handleNet
-- both asssume state machines do stateful update
-- afaik, wrt extraction
  ,handleIO :: Name -> input -> state ->  m (Res output state message)
  ,handleNet :: Name -> Name -> message -> state -> m (Res output state message)
  ,handleTimeout :: Name -> state -> m (Res output state message)
  ,setTimeout :: Name -> state -> m Double
  ,deserialize ::  ByteString -> Maybe (request_id, input)
  ,serialize :: output -> (request_id, ByteString)
  ,debug :: Bool
  ,debugRecv :: state -> (Name, message) -> m ()
  ,debugSend :: state -> (Name, message) -> m ()
  ,debugTimeout :: state -> m ()
  }

defaultArrangement :: (Monad m
                      ,Reifies k (Set Name)
                      ,Reifies s (StateMachine m input stateMachineData (output, stateMachineData)))
                   => prox s -> prox k
                   -> Arrangement
                        m
                        (RaftData stateMachineData input output)
                        (RaftInput input)
                        (RaftOutput output)
                        (Msg input)
                        request_id
defaultArrangement ps pk = Arrangement {
  init = Raft.initHandlers
  ,reboot = Raft.reboot
  ,handleIO = Raft.raftInputHandler ps pk
  ,handleNet = Raft.raftNetHandler ps pk
  ,handleTimeout = \nm st -> Raft.handleTimeout pk nm st
  ,setTimeout =  error "setTimeout is an RNG that depends on leadershipness"
  ,deserialize = error "undefined deserialize Arrangement"
  ,serialize = error "undefined serialize Arrangement"
  ,debug = False
  ,debugRecv = error "undefined debugRecv"
  ,debugSend = error "undefined debugSend"
  ,debugTimeout = error "undefined debugTimeout" }

data Env m state out_channel file_descr request_id sockaddr = Env {
  restored_state :: state
  ,snapfile:: String
  ,clog :: out_channel -- this may be spurious type wise
  ,txSocket :: file_descr
  ,rxSocket :: file_descr
--,csocksRead :: m [file_descr] -- think IORef [...]
--,csocksUpdate :: [file_descr] -> m ()
--,outstandingRead :: m (Map request_id file_descr) -- think IORef (Map ...)
--,outstandingUpdate ::  Map request_id file_descr -> m ()
  ,savesRead :: m Int -- think IORef Int
  ,savesWrite :: Int -> m ()
  ,nodes :: m (Map Name sockaddr) -- m [...] to model membership list may change.
                                  -- though verdi proof assumes fixed
  }

data LogStep msg input = LogInput input
                       | LogNet Name msg
                       | LogTimeout
                       deriving (Eq,Ord,Show)

data EnvOps m out_channel state file_descr sockaddr msg request_id input = EnvOps {
-- yieldLogEvents assumes the only newlines are betwee
-- log events
-- yields nothing when reaches end of file
 open :: String -> m file_descr
 ,yieldLogEvents :: file_descr -> m (Maybe (LogStep msg input))
 ,loadSnapShot :: String -> m state
 ,send :: Env m state out_channel file_descr request_id sockaddr -> Name -> msg -> m ()
--  ,receive ::
  }

update_state_from_log_entry :: forall state f output msg input request_id
                             . Functor f
                            => Arrangement f state input output msg request_id
                            -> Name
                            -> state
                            -> LogStep msg input -> f state
update_state_from_log_entry arr nm s op =
    ((\(_,st,_)-> st) . unRes) <$> case op of
                                     LogInput inp -> handleIO arr nm inp s
                                     LogNet src m -> handleNet arr nm src m s
                                     LogTimeout -> handleTimeout arr nm s

get_initial_state :: forall f out_channel file_descr sockaddr state msg input output request_id
                   . Alternative f
                  => EnvOps f out_channel state file_descr sockaddr msg request_id input
                  -> Arrangement f state input output msg request_id
                  -> String
                  -> Name
                  -> f state
get_initial_state eop arr snpfile nm =
  loadSnapShot eop snpfile <|> pure (init arr nm)

restore_from_log :: forall m out_channel state file_descr sockaddr msg input output request_id
                  . Monad m
                 => Arrangement m state input output msg request_id
                 -> EnvOps m out_channel state file_descr sockaddr msg request_id input
                 -> file_descr
                 -> Name
                 -> state
                 -> m state
restore_from_log arr eop fd nm st = go st
  where
    yielder = yieldLogEvents eop fd
    go theState = do
      nextOp <- yielder
      case nextOp of
          Nothing -> return theState
          Just op ->
           do st' <-
                update_state_from_log_entry arr nm st op
              go st'

restore :: forall m state output request_id out_channel file_descr sockaddr msg input
        . (Monad m, Alternative m)
        => Arrangement m state input output msg request_id
        -> EnvOps m out_channel state file_descr sockaddr msg request_id input
        -> String
        -> String
        -> Name
        -> m state
restore arr eop snpfile logfl nm =
   do
    -- this doesn't deal with catching up with
    -- nonlocal update ... i think....
     istate <- get_initial_state eop arr snpfile nm
     logfd <- open eop logfl
     restore_from_log arr eop logfd nm istate

denote :: Monad m
       => Env m state out_channel file_descr request_id sockaddr
       -> Name
       -> m sockaddr
denote env nm =
  do  nds <- nodes env
      maybe
        (fail "bad lookup with denote")
        return
        $  Map.lookup  nm nds


text:
package com.twitter.logging

import com.twitter.util.{TempFolder, Time}
import com.twitter.conversions.time._
import org.specs.SpecificationWithJUnit

class ThrottledHandlerSpec extends SpecificationWithJUnit with TempFolder {
  private var handler: StringHandler = null

  "ThrottledHandler" should {
    doBefore {
      Logger.clearHandlers
      handler = new StringHandler(BareFormatter, None)
    }

    doAfter {
      Logger.clearHandlers
    }

    "throttle keyed log messages" in {
      val log = Logger()
      val throttledLog = new ThrottledHandler(handler, 1.second, 3)
      Time.withCurrentTimeFrozen { timeCtrl =>
        log.addHandler(throttledLog)

        log.error("apple: %s", "help!")
        log.error("apple: %s", "help 2!")
        log.error("orange: %s", "orange!")
        log.error("orange: %s", "orange!")
        log.error("apple: %s", "help 3!")
        log.error("apple: %s", "help 4!")
        log.error("apple: %s", "help 5!")
        timeCtrl.advance(2.seconds)
        log.error("apple: %s", "done.")

        handler.get.split("\n").toList mustEqual List("apple: help!", "apple: help 2!", "orange: orange!", "orange: orange!", "apple: help 3!", "(swallowed 2 repeating messages)", "apple: done.")
      }
    }

    "log the summary even if nothing more is logged with that name" in {
      Time.withCurrentTimeFrozen { time =>
        val log = Logger()
        val throttledLog = new ThrottledHandler(handler, 1.second, 3)
        log.addHandler(throttledLog)
        log.error("apple: %s", "help!")
        log.error("apple: %s", "help!")
        log.error("apple: %s", "help!")
        log.error("apple: %s", "help!")
        log.error("apple: %s", "help!")

        time.advance(2.seconds)
        log.error("hello.")

        handler.get.split("\n").toList mustEqual List("apple: help!", "apple: help!", "apple: help!", "(swallowed 2 repeating messages)", "hello.")
      }
    }
  }
}


text:
@class LCQueueRequest;

@interface LCQueueRequestAgent : NSObject

+ (LCQueueRequestAgent *)sharedInstance;

- (void)addRequest:(LCQueueRequest *)request;
- (void)removeRequest:(LCQueueRequest *)request;

@end


text:
layout: post
microblog: true
audio:
photo:
date: 2009-06-18 18:00:00 -0600
guid: http://craigmcclellan.micro.blog/2009/06/19/t2233717817.html
---
Anyone going to be at the Green Hills Apple Store for 3GS tomorrow? Let me know and we can meet up.


text:
define([
	'./moduleDef',
	'angular',
	'text!./userMenu.tpl.html'
], function (module, angular, tpl) {
	module.directive('userMenu', ['security', function (security) {
		return {
			template: tpl,
			restrict: 'EA',
			replace: true,
			scope: true,

			controller: function ($scope, $rootScope) {
				angular.extend($scope, {
					i18n: $rootScope.i18n,
					isAuthenticated: security.isAuthenticated,
					login: security.showLogin,
					logout: security.logout
				});

				$scope.$watch(function () { return security.currentUser; }, function (currentUser) {
					$scope.currentUser = currentUser;
				});
			}
		};
	}]);
});


text:
{-# OPTIONS  -Wall #-}
{-# LANGUAGE ForeignFunctionInterface #-}

{- |
Module      :  $Header$
Description :  Architecture-dependent settings.
Copyright   :  (c) Galois, Inc.
License     :  see the file LICENSE

Maintainer  :  Rogan Creswick
Stability   :  provisional
Portability :  undetermined

The name of this module is mostly due to historic reasons.
-}

module ExtTools
	( getInstallDataFileName_
	, getInstallDataFileName
	) where

import System.Directory(getCurrentDirectory, findExecutable, doesFileExist,canonicalizePath)
import System.FilePath((</>), takeDirectory,splitDirectories,joinPath)
import System.Posix.Files(readSymbolicLink)
import Paths_lviz

import Foreign(alloca, peek, peekElemOff, Ptr)
import Foreign.C(peekCString, CInt, CString)

getInstallDataFileName_ :: FilePath -> IO FilePath
getInstallDataFileName_ s = do
  mfn <- getInstallDataFileName s
  case mfn of
    Nothing -> error $ "missing data file:" ++ s
    Just fn -> return fn

getInstallDataFileName :: FilePath -> IO (Maybe FilePath)
getInstallDataFileName fn0 = do
  mdir <- getInstallDir
--   putStrLn $ "original install dir:" ++ show mdir
  case mdir of
    Nothing -> error "can't find executable installation directory"
    Just dir -> do
      fn1 <- getDataFileName fn0
      let fn = joinPath $ [dir] ++ (dropWhile (/= "share") $ splitDirectories fn1)
--       putStrLn $ "original data filename:" ++ show fn1
--       putStrLn $ "effective data filename:" ++ show fn
      b <- doesFileExist fn
      if b
        then return $ Just fn
        else return Nothing

getInstallDir :: IO (Maybe String)
getInstallDir = do
  s <- getFullProgName
  mb <- if '/' `elem` s then do x <- getCurrentDirectory
                                return $ Just $ x </> s
                        else findExecutable s
  case mb of
    Nothing -> return Nothing
    Just p -> do
      p1 <- readSymbolicLinks p >>= canonicalizePath
      return $ Just $ takeDirectory $ takeDirectory p1

readSymbolicLinks :: FilePath -> IO FilePath
readSymbolicLinks f =
  catch (do f' <- (takeDirectory f </>) `fmap` readSymbolicLink f
            if f == f' then return f
                       else readSymbolicLinks f')
        (const (return f))

-- System.Environment.getProgName doesn't do what we want
getFullProgName :: IO String
getFullProgName =
  alloca $ \ p_argc ->
  alloca $ \ p_argv -> do
     getProgArgv p_argc p_argv
     peek p_argv >>= flip peekElemOff 0 >>= peekCString

foreign import ccall unsafe "getProgArgv"
  getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()


text:
namespace ChilliSource
{
    //---------------------------------------------------------------
    /// A state system for presenting the user with an email
    /// composition view.
    ///
    /// @author S McGaw
    //---------------------------------------------------------------
    class EmailComposer : public StateSystem
    {
    public:
        CS_DECLARE_NAMEDTYPE(EmailComposer);
        //-------------------------------------------------------
        /// An enum describing the result of the email intent.
        ///
        /// @author S McGaw
        //-------------------------------------------------------
        enum class SendResult
        {
            k_succeed,
            k_failed,
            k_cancelled
        };
        //-------------------------------------------------------
        /// Describes the format of the email contents.
        ///
        /// @author Ian Copland
        //-------------------------------------------------------
        enum class ContentFormat
        {
            k_plainText,
            k_html
        };
        //-------------------------------------------------------
        /// A container for information describing a single
        /// attachment file.
        ///
        /// @author Ian Copland
        //-------------------------------------------------------
        struct Attachment
        {
            StorageLocation m_storageLocation;
            std::string m_filename;
            std::string m_mimeType;
        };
        //-------------------------------------------------------
        /// A delegate that is called when the email view is
        /// dismissed, returning the result.
        ///
        /// @author S McGaw
        ///
        /// @param The result of the email composition.
        //-------------------------------------------------------
        typedef std::function<void(SendResult)> SendResultDelegate;
        //-------------------------------------------------------
        /// Displays the email activity with the given recipients,
        /// subject and contents.
        ///
        /// @author S Downie
        ///
        /// @param A list of recipients (UTF8).
        /// @param The subject (UTF8).
        /// @param The body of the email (UTF8).
        /// @param The format of the body of the email.
        /// @param The callback describing the result of the email.
        //-------------------------------------------------------
        virtual void Present(const std::vector<std::string>& in_recipientAddresses, const std::string& in_subject, const std::string& in_contents, ContentFormat in_contentFormat,
                             const SendResultDelegate& in_callback) = 0;
        //-------------------------------------------------------
        /// Displays the email activity with the given recipients,
        /// subject and contents, and adds a list of attachments
        /// to the email.
        ///
        /// @author Ian Copland
        ///
        /// @param A list of recipients (UTF8).
        /// @param The subject (UTF8).
        /// @param The body of the email (UTF8).
        /// @param The format of the body of the email.
        /// @param The attachment.
        /// @param The callback describing the result of the email.
        //-------------------------------------------------------
        virtual void PresentWithAttachment(const std::vector<std::string>& in_recipientAddresses, const std::string& in_subject, const std::string& in_contents, ContentFormat in_contentFormat,
                                           const Attachment& in_attachment, const SendResultDelegate& in_callback) = 0;
        //-------------------------------------------------------
        /// Determines whether or not the composer is presented.
        ///
        /// @author Jordan Brown
        //-------------------------------------------------------
        virtual bool IsPresented() = 0;
        //-------------------------------------------------------
        /// Destructor
        //-------------------------------------------------------
        virtual ~EmailComposer() {};
    protected:
        friend class State;
        //-------------------------------------------------------
        /// Creates a new instance of the email composition
        /// activity.
        ///
        /// @author Ian Copland
        ///
        /// @return the new activity instance.
        //-------------------------------------------------------
        static EmailComposerUPtr Create();
        //-------------------------------------------------------
        /// Protected constructor to force use of the factory
        /// method.
        ///
        /// @author Ian Copland.
        //-------------------------------------------------------
        EmailComposer() = default;
    };
}

#endif


text:
<?php

namespace Core42\View\Model;

use Zend\View\Model\JsonModel as ZendJsonModel;

class JsonModel extends ZendJsonModel
{
    /**
     * The encoded JSON string
     *
     * @var string
     */
    protected $jsonString = null;

    /**
     * Set the already encoded JSON string
     *
     * @param  string    $json
     * @return JsonModel
     */
    public function setJsonString($json)
    {
        $this->jsonString = $json;

        return $this;
    }

    /**
     * Serialize to JSON
     *
     * @return string
     */
    public function serialize()
    {
        //todo: merge
        if ($this->jsonString !== null) {
            return $this->jsonString;
        }

        return parent::serialize();
    }
}


text:
class EffectManager
{
public:
	static EffectManager* getInstance();
	static void			  destoryInstance();

	// 播放爆炸特效
	void playBombEffect(cocos2d::Node* pSender);

	// 播放分数特效
	void playFlyScore(cocos2d::Node* pSender, int iScore);

protected:
	void init();

private:
	static EffectManager* s_instance;
};

#endif


text:
require 'rails_helper'

RSpec.describe "TrendingMonthlyNewsItems", type: :request do
  describe "GET /trending_monthly_news_items" do
    it "works! (now write some real specs)" do
      get trending_monthly_news_items_path
      expect(response).to have_http_status(200)
    end
  end
end


text:
/** @constructor */
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor = (function() {
  ScalaJS.c.scala_collection_mutable_AbstractMap.call(this);
  this.imap$5 = null
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype = new ScalaJS.inheritable.scala_collection_mutable_AbstractMap();
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.constructor = ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor;
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.imap__Lscala_collection_immutable_Map = (function() {
  return this.imap$5
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.imap$und$eq__Lscala_collection_immutable_Map__V = (function(x$1) {
  this.imap$5 = x$1
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.size__I = (function() {
  return this.imap__Lscala_collection_immutable_Map().size__I()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.get__O__Lscala_Option = (function(key) {
  return this.imap__Lscala_collection_immutable_Map().get__O__Lscala_Option(key)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.isEmpty__Z = (function() {
  return this.imap__Lscala_collection_immutable_Map().isEmpty__Z()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.apply__O__O = (function(key) {
  return this.imap__Lscala_collection_immutable_Map().apply__O__O(key)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.contains__O__Z = (function(key) {
  return this.imap__Lscala_collection_immutable_Map().contains__O__Z(key)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.isDefinedAt__O__Z = (function(key) {
  return this.imap__Lscala_collection_immutable_Map().isDefinedAt__O__Z(key)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.keySet__Lscala_collection_Set = (function() {
  return this.imap__Lscala_collection_immutable_Map().keySet__Lscala_collection_immutable_Set()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.keysIterator__Lscala_collection_Iterator = (function() {
  return this.imap__Lscala_collection_immutable_Map().keysIterator__Lscala_collection_Iterator()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.keys__Lscala_collection_Iterable = (function() {
  return this.imap__Lscala_collection_immutable_Map().keys__Lscala_collection_Iterable()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.valuesIterator__Lscala_collection_Iterator = (function() {
  return this.imap__Lscala_collection_immutable_Map().valuesIterator__Lscala_collection_Iterator()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.values__Lscala_collection_Iterable = (function() {
  return this.imap__Lscala_collection_immutable_Map().values__Lscala_collection_Iterable()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.iterator__Lscala_collection_Iterator = (function() {
  return this.imap__Lscala_collection_immutable_Map().iterator__Lscala_collection_Iterator()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.toList__Lscala_collection_immutable_List = (function() {
  return this.imap__Lscala_collection_immutable_Map().toList__Lscala_collection_immutable_List()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.update__O__O__V = (function(key, value) {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(this.imap__Lscala_collection_immutable_Map().updated__O__O__Lscala_collection_immutable_Map(key, value))
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$minus$eq__O__Lscala_collection_mutable_ImmutableMapAdaptor = (function(key) {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(ScalaJS.as.scala_collection_immutable_Map(this.imap__Lscala_collection_immutable_Map().$$minus__O__Lscala_collection_Map(key)));
  return this
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_ImmutableMapAdaptor = (function(kv) {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(this.imap__Lscala_collection_immutable_Map().$$plus__Lscala_Tuple2__Lscala_collection_immutable_Map(kv));
  return this
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.clear__V = (function() {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(this.imap__Lscala_collection_immutable_Map().empty__Lscala_collection_immutable_Map())
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.transform__Lscala_Function2__Lscala_collection_mutable_ImmutableMapAdaptor = (function(f) {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(ScalaJS.as.scala_collection_immutable_Map(this.imap__Lscala_collection_immutable_Map().transform__Lscala_Function2__Lscala_collection_generic_CanBuildFrom__O(f, ScalaJS.modules.scala_collection_immutable_Map().canBuildFrom__Lscala_collection_generic_CanBuildFrom())));
  return this
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.retain__Lscala_Function2__Lscala_collection_mutable_ImmutableMapAdaptor = (function(p) {
  this.imap$und$eq__Lscala_collection_immutable_Map__V(ScalaJS.as.scala_collection_immutable_Map(this.imap__Lscala_collection_immutable_Map().filter__Lscala_Function1__O(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(p$1) {
    return (function(xy) {
      return ScalaJS.bZ(ScalaJS.uZ(p$1.apply__O__O__O(xy.$$und1__O(), xy.$$und2__O())))
    })
  })(p)))));
  return this
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.toString__T = (function() {
  return this.imap__Lscala_collection_immutable_Map().toString__T()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.retain__Lscala_Function2__Lscala_collection_mutable_MapLike = (function(p) {
  return this.retain__Lscala_Function2__Lscala_collection_mutable_ImmutableMapAdaptor(p)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.transform__Lscala_Function2__Lscala_collection_mutable_MapLike = (function(f) {
  return this.transform__Lscala_Function2__Lscala_collection_mutable_ImmutableMapAdaptor(f)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$plus$eq__O__Lscala_collection_generic_Growable = (function(elem) {
  return this.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_ImmutableMapAdaptor(ScalaJS.as.scala_Tuple2(elem))
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$plus$eq__O__Lscala_collection_mutable_Builder = (function(elem) {
  return this.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_ImmutableMapAdaptor(ScalaJS.as.scala_Tuple2(elem))
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_MapLike = (function(kv) {
  return this.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_ImmutableMapAdaptor(kv)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$minus$eq__O__Lscala_collection_generic_Shrinkable = (function(elem) {
  return this.$$minus$eq__O__Lscala_collection_mutable_ImmutableMapAdaptor(elem)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$$minus$eq__O__Lscala_collection_mutable_MapLike = (function(key) {
  return this.$$minus$eq__O__Lscala_collection_mutable_ImmutableMapAdaptor(key)
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.values__Lscala_collection_GenIterable = (function() {
  return this.values__Lscala_collection_Iterable()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.keys__Lscala_collection_GenIterable = (function() {
  return this.keys__Lscala_collection_Iterable()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.keySet__Lscala_collection_GenSet = (function() {
  return this.keySet__Lscala_collection_Set()
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.init___Lscala_collection_immutable_Map = (function(imap) {
  this.imap$5 = imap;
  ScalaJS.c.scala_collection_mutable_AbstractMap.prototype.init___.call(this);
  return this
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.imap$und$eq__Lscala_collection_immutable_Map__ = (function(x$1) {
  return ScalaJS.bV(this.imap$und$eq__Lscala_collection_immutable_Map__V(x$1))
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.imap__ = (function() {
  return this.imap__Lscala_collection_immutable_Map()
});
/** @constructor */
ScalaJS.inheritable.scala_collection_mutable_ImmutableMapAdaptor = (function() {
  /*<skip>*/
});
ScalaJS.inheritable.scala_collection_mutable_ImmutableMapAdaptor.prototype = ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype;
ScalaJS.is.scala_collection_mutable_ImmutableMapAdaptor = (function(obj) {
  return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_mutable_ImmutableMapAdaptor)))
});
ScalaJS.as.scala_collection_mutable_ImmutableMapAdaptor = (function(obj) {
  if ((ScalaJS.is.scala_collection_mutable_ImmutableMapAdaptor(obj) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwClassCastException(obj, "scala.collection.mutable.ImmutableMapAdaptor")
  }
});
ScalaJS.isArrayOf.scala_collection_mutable_ImmutableMapAdaptor = (function(obj, depth) {
  return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_mutable_ImmutableMapAdaptor)))
});
ScalaJS.asArrayOf.scala_collection_mutable_ImmutableMapAdaptor = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.scala_collection_mutable_ImmutableMapAdaptor(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Lscala.collection.mutable.ImmutableMapAdaptor;", depth)
  }
});
ScalaJS.data.scala_collection_mutable_ImmutableMapAdaptor = new ScalaJS.ClassTypeData({
  scala_collection_mutable_ImmutableMapAdaptor: 0
}, false, "scala.collection.mutable.ImmutableMapAdaptor", ScalaJS.data.scala_collection_mutable_AbstractMap, {
  scala_collection_mutable_ImmutableMapAdaptor: 1,
  scala_Serializable: 1,
  java_io_Serializable: 1,
  scala_collection_mutable_AbstractMap: 1,
  scala_collection_mutable_Map: 1,
  scala_collection_mutable_MapLike: 1,
  scala_collection_mutable_Cloneable: 1,
  scala_Cloneable: 1,
  java_lang_Cloneable: 1,
  scala_collection_generic_Shrinkable: 1,
  scala_collection_mutable_Builder: 1,
  scala_collection_generic_Growable: 1,
  scala_collection_generic_Clearable: 1,
  scala_collection_mutable_Iterable: 1,
  scala_collection_mutable_Traversable: 1,
  scala_Mutable: 1,
  scala_collection_AbstractMap: 1,
  scala_collection_Map: 1,
  scala_collection_MapLike: 1,
  scala_collection_generic_Subtractable: 1,
  scala_PartialFunction: 1,
  scala_Function1: 1,
  scala_collection_GenMap: 1,
  scala_collection_GenMapLike: 1,
  scala_collection_AbstractIterable: 1,
  scala_collection_Iterable: 1,
  scala_collection_IterableLike: 1,
  scala_Equals: 1,
  scala_collection_GenIterable: 1,
  scala_collection_GenIterableLike: 1,
  scala_collection_AbstractTraversable: 1,
  scala_collection_Traversable: 1,
  scala_collection_GenTraversable: 1,
  scala_collection_generic_GenericTraversableTemplate: 1,
  scala_collection_TraversableLike: 1,
  scala_collection_GenTraversableLike: 1,
  scala_collection_Parallelizable: 1,
  scala_collection_TraversableOnce: 1,
  scala_collection_GenTraversableOnce: 1,
  scala_collection_generic_FilterMonadic: 1,
  scala_collection_generic_HasNewBuilder: 1,
  java_lang_Object: 1
});
ScalaJS.c.scala_collection_mutable_ImmutableMapAdaptor.prototype.$classData = ScalaJS.data.scala_collection_mutable_ImmutableMapAdaptor;
//@ sourceMappingURL=ImmutableMapAdaptor.js.map


text:
FROM hone/mruby-cli
RUN apt-get update && apt-get install -y gdb libssl-dev


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="2dp"
    android:theme="@style/AppTheme.AppBarOverlay"
    >

    <com.home.rxtwitch.ui.widget.RxToolbar
        android:id="@+id/general_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:contentInsetStart="0dp">

    </com.home.rxtwitch.ui.widget.RxToolbar>

</android.support.design.widget.AppBarLayout>


text:
<pagination
        class="pagination-sm"
        ng-model="filterable.pageNumber"
        items-per-page="filterable.pageSize"
        total-items="filterable.totalElements"
        rotate="filterable.rotate"
        max-size="filterable.maxSize"
        boundary-links="filterable.boundaryLinks"
        direction-links="filterable.directionLinks"
        ng-change="filterable.filter(filterable.pageNumber)">
</pagination>


text:
package test.expression;

import parser.Token;
import parser.Tokenizer;

/*
 * Created on 7 Apr 2010
 */

/**
 * @author Anthony Bryant
 *
 */
public class ExpressionTokenizer extends Tokenizer<ExpressionType>
{

  private int state = 0;

  @SuppressWarnings("rawtypes")
  private static final Token[] TEST1 =
  {
    new Token<ExpressionType>(ExpressionType.NUMBER, new Number(1)),
    new Token<ExpressionType>(ExpressionType.TIMES, ExpressionType.TIMES),
    new Token<ExpressionType>(ExpressionType.NUMBER, new Number(2)),
    new Token<ExpressionType>(ExpressionType.PLUS, ExpressionType.PLUS),
    new Token<ExpressionType>(ExpressionType.NUMBER, new Number(3)),
    new Token<ExpressionType>(ExpressionType.MINUS, ExpressionType.MINUS),
    new Token<ExpressionType>(ExpressionType.LPAREN, ExpressionType.LPAREN),
    new Token<ExpressionType>(ExpressionType.NUMBER, new Number(12)),
    new Token<ExpressionType>(ExpressionType.MINUS, ExpressionType.MINUS),
    new Token<ExpressionType>(ExpressionType.NUMBER, new Number(6)),
    new Token<ExpressionType>(ExpressionType.RPAREN, ExpressionType.RPAREN)
  };

  @SuppressWarnings("unchecked")
  private Token<ExpressionType>[] tokens = TEST1;

  /**
   * @see parser.Tokenizer#generateToken()
   */
  @Override
  protected Token<ExpressionType> generateToken()
  {
    if (state < tokens.length)
    {
      state++;
      return tokens[state - 1];
    }

    return null;
  }

}


text:
namespace Telerik.ILS.Common
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// Class for managing strings in a custom way
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// Create encrypted string from input
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Hexadecimal string</returns>
        public static string ToMd5Hash(this string input)
        {
            var md5Hash = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new StringBuilder to collect the bytes
            // and create a string.
            var builder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return builder.ToString();
        }

        /// <summary>
        /// Check if input value contains a boolean value
        /// </summary>
        /// <param name="input">input text</param>
        /// <returns>True if a boolean value is contained or false if not</returns>
        public static bool ToBoolean(this string input)
        {
            var stringTrueValues = new[] { "true", "ok", "yes", "1", "äà" };
            return stringTrueValues.Contains(input.ToLower());
        }

        /// <summary>
        /// Check and parse input text to short value if it is a correct number
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Short number value</returns>
        public static short ToShort(this string input)
        {
            short shortValue;
            short.TryParse(input, out shortValue);
            return shortValue;
        }

        /// <summary>
        /// Check and parse input text to Integer value if it is a correct number
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Integer number value</returns>
        public static int ToInteger(this string input)
        {
            int integerValue;
            int.TryParse(input, out integerValue);
            return integerValue;
        }

        /// <summary>
        /// Check and parse input text to a Long value if it is a correct number
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Long number value</returns>
        public static long ToLong(this string input)
        {
            long longValue;
            long.TryParse(input, out longValue);
            return longValue;
        }

        /// <summary>
        /// Check and parse input text to a Date time value if it is given the correct format
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Date time value</returns>
        public static DateTime ToDateTime(this string input)
        {
            DateTime dateTimeValue;
            DateTime.TryParse(input, out dateTimeValue);
            return dateTimeValue;
        }

        /// <summary>
        /// Converts the first letter of the input string to capital
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>The string with capitalized first letter</returns>
        public static string CapitalizeFirstLetter(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1, input.Length - 1);
        }

        /// <summary>
        /// Returns a substring within the given positions of the original string,
        /// </summary>
        /// <param name="input">Input text</param>
        /// <param name="startString">String that indicates start position</param>
        /// <param name="endString">String that indicates end position</param>
        /// <param name="startFrom">Starting symbol</param>
        /// <returns>New string created from input between start and end position</returns>
        public static string GetStringBetween(this string input, string startString, string endString, int startFrom = 0)
        {
            input = input.Substring(startFrom);
            startFrom = 0;
            if (!input.Contains(startString) || !input.Contains(endString))
            {
                return string.Empty;
            }

            var startPosition = input.IndexOf(startString, startFrom, StringComparison.Ordinal) + startString.Length;
            if (startPosition == -1)
            {
                return string.Empty;
            }

            var endPosition = input.IndexOf(endString, startPosition, StringComparison.Ordinal);
            if (endPosition == -1)
            {
                return string.Empty;
            }

            return input.Substring(startPosition, endPosition - startPosition);
        }

        /// <summary>
        /// Converts Bulgarian letters to their latin representation
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>String output with converted letters to latin</returns>
        public static string ConvertCyrillicToLatinLetters(this string input)
        {
            var bulgarianLetters = new[]
                                       {
                                           "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
                                           "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "ü", "þ", "ÿ"
                                       };
            var latinRepresentationsOfBulgarianLetters = new[]
                                                             {
                                                                 "a", "b", "v", "g", "d", "e", "j", "z", "i", "y", "k",
                                                                 "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h",
                                                                 "c", "ch", "sh", "sht", "u", "i", "yu", "ya"
                                                             };
            for (var i = 0; i < bulgarianLetters.Length; i++)
            {
                input = input.Replace(bulgarianLetters[i], latinRepresentationsOfBulgarianLetters[i]);
                input = input.Replace(bulgarianLetters[i].ToUpper(), latinRepresentationsOfBulgarianLetters[i].CapitalizeFirstLetter());
            }

            return input;
        }

        /// <summary>
        /// Converts latin letters to their Cyrillic representation
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>String output with converted letters to cyrillic</returns>
        public static string ConvertLatinToCyrillicKeyboard(this string input)
        {
            var latinLetters = new[]
                                   {
                                       "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                                       "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
                                   };

            var bulgarianRepresentationOfLatinKeyboard = new[]
                                                             {
                                                                 "à", "á", "ö", "ä", "å", "ô", "ã", "õ", "è", "é", "ê",
                                                                 "ë", "ì", "í", "î", "ï", "ÿ", "ð", "ñ", "ò", "ó", "æ",
                                                                 "â", "ü", "ú", "ç"
                                                             };

            for (int i = 0; i < latinLetters.Length; i++)
            {
                input = input.Replace(latinLetters[i], bulgarianRepresentationOfLatinKeyboard[i]);
                input = input.Replace(latinLetters[i].ToUpper(), bulgarianRepresentationOfLatinKeyboard[i].ToUpper());
            }

            return input;
        }

        /// <summary>
        /// Converts the input to a valid Username value
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Converted string</returns>
        public static string ToValidUsername(this string input)
        {
            input = input.ConvertCyrillicToLatinLetters();
            return Regex.Replace(input, @"[^a-zA-z0-9_\.]+", string.Empty);
        }

        /// <summary>
        /// Converts input to a valid latin filename value
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>Converted string</returns>
        public static string ToValidLatinFileName(this string input)
        {
            input = input.Replace(" ", "-").ConvertCyrillicToLatinLetters();
            return Regex.Replace(input, @"[^a-zA-z0-9_\.\-]+", string.Empty);
        }

        /// <summary>
        /// Returns a string containing a specified number of characters from start of input
        /// </summary>
        /// <param name="input">Input text</param>
        /// <param name="charsCount">number of characters</param>
        /// <returns>New string with the specified length and value</returns>
        public static string GetFirstCharacters(this string input, int charsCount)
        {
            return input.Substring(0, Math.Min(input.Length, charsCount));
        }

        /// <summary>
        /// Returns the extension of a filename string
        /// </summary>
        /// <param name="fileName">Input string containing a filename</param>
        /// <returns>String containing the filenames extension</returns>
        public static string GetFileExtension(this string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return string.Empty;
            }

            string[] fileParts = fileName.Split(new[] { "." }, StringSplitOptions.None);
            if (fileParts.Count() == 1 || string.IsNullOrEmpty(fileParts.Last()))
            {
                return string.Empty;
            }

            return fileParts.Last().Trim().ToLower();
        }

        /// <summary>
        /// Returns the content type based on the file extension
        /// </summary>
        /// <param name="fileExtension">String file extension</param>
        /// <returns>String indicating the file type</returns>
        public static string ToContentType(this string fileExtension)
        {
            var fileExtensionToContentType = new Dictionary<string, string>
                                                 {
                                                     { "jpg", "image/jpeg" },
                                                     { "jpeg", "image/jpeg" },
                                                     { "png", "image/x-png" },
                                                     {
                                                         "docx",
                                                         "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                                                     },
                                                     { "doc", "application/msword" },
                                                     { "pdf", "application/pdf" },
                                                     { "txt", "text/plain" },
                                                     { "rtf", "application/rtf" }
                                                 };
            if (fileExtensionToContentType.ContainsKey(fileExtension.Trim()))
            {
                return fileExtensionToContentType[fileExtension.Trim()];
            }

            return "application/octet-stream";
        }

        /// <summary>
        /// Creates a byte array from string
        /// </summary>
        /// <param name="input">Input text</param>
        /// <returns>a new array of bytes</returns>
        public static byte[] ToByteArray(this string input)
        {
            var bytesArray = new byte[input.Length * sizeof(char)];
            Buffer.BlockCopy(input.ToCharArray(), 0, bytesArray, 0, bytesArray.Length);
            return bytesArray;
        }
    }
}


text:
package org.hbird.business.api.impl;

import org.hbird.business.api.IPublisher;
import org.hbird.business.api.IStartableEntityManager;
import org.hbird.exchange.configurator.StartComponent;
import org.hbird.exchange.configurator.StopComponent;
import org.hbird.exchange.interfaces.IStartableEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StartableEntityManager implements IStartableEntityManager {

    private static final String DEFAULT_DESTINATION = "Configurator";

    private final Logger LOG = LoggerFactory.getLogger(StartableEntityManager.class);

    protected IPublisher publisher;

    protected String issuedBy;
    protected String destination;

    public StartableEntityManager(String issuedBy, IPublisher publisher) {
        this(issuedBy, DEFAULT_DESTINATION, publisher);
    }

    public StartableEntityManager(String issuedBy, String destination, IPublisher publisher) {
        this.issuedBy = issuedBy;
        this.destination = destination;
        this.publisher = publisher;
    }

    @Override
    public void start(IStartableEntity part) {
        StartComponent request = new StartComponent(issuedBy);
        request.setIssuedBy(issuedBy);
        request.setEntity(part);
        request.setDestination(destination);

        try {
            publisher.publish(request);
        }
        catch (Exception e) {
            LOG.error("Error sending start command for StartableEntity '{}'", part.getID(), e);
        }
    }

    @Override
    public void stop(String entityId) {
        StopComponent request = new StopComponent(issuedBy);
        request.setIssuedBy(issuedBy);
        request.setEntityID(entityId);
        request.setDestination(destination);

        try {
            publisher.publish(request);
        }
        catch (Exception e) {
            LOG.error("Error sending stop command for StartableEntity '{}'", entityId, e);
        }
    }
}


text:
package net.riotopsys.json_patch.operation;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import net.riotopsys.json_patch.JsonPath;

import java.util.List;
import java.util.Map;

/**
 * Created by afitzgerald on 8/5/14.
 */
public class RemoveOperation extends AbsOperation{

    public RemoveOperation( JsonPath path ) {
        this.path = path;
    }

    @Override
    public String getOperationName() {
        return "remove";
    }

    @Override
    public JsonElement apply(JsonElement original) {
        JsonElement result = duplicate( original );

        JsonElement item = path.head().navigate(result);

        if ( item.isJsonObject() ){
//            Map<String, JsonElement> map = getBackingMap(item.getAsJsonObject());

//            map.remove(path.tail());

            item.getAsJsonObject().remove(path.tail());

        } else if ( item.isJsonArray() ){

            JsonArray array = item.getAsJsonArray();

            int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail());

           array.remove(index);

        }

        return result;
    }
}


text:
<TITLE>xiph.org: Ogg Vorbis documentation</TITLE>

<nobr></nobr>

Ogg logical bitstream framing

Last update to this document: July 14, 2002

Ogg bitstreams

The Ogg transport bitstream is designed to provide framing, error
protection and seeking structure for higher-level codec streams that
consist of raw, unencapsulated data packets, such as the Vorbis audio
codec or Tarkin video codec.

Application example: Vorbis

Vorbis encodes short-time blocks of PCM data into raw packets of
bit-packed data.  These raw packets may be used directly by transport
mechanisms that provide their own framing and packet-separation
mechanisms (such as UDP datagrams).  For stream based storage (such as
files) and transport (such as TCP streams or pipes), Vorbis uses the
Ogg bitstream format to provide framing/sync, sync recapture
after error, landmarks during seeking, and enough information to
properly separate data back into packets at the original packet
boundaries without relying on decoding to find packet boundaries.

Design constraints for Ogg bitstreams

True streaming; we must not need to seek to build a 100%
   complete bitstream.

 Use no more than approximately 1-2% of bitstream bandwidth for
   packet boundary marking, high-level framing, sync and seeking.

 Specification of absolute position within the original sample
   stream.

 Simple mechanism to ease limited editing, such as a simplified
   concatenation mechanism.

 Detection of corruption, recapture after error and direct, random
   access to data at arbitrary positions in the bitstream.

Logical and Physical Bitstreams

A logical Ogg bitstream is a contiguous stream of
sequential pages belonging only to the logical bitstream.  A
physical Ogg bitstream is constructed from one or more
than one logical Ogg bitstream (the simplest physical bitstream
is simply a single logical bitstream).  We describe below the exact
formatting of an Ogg logical bitstream.  Combining logical
bitstreams into more complex physical bitstreams is described in the
Ogg bitstream overview.  The exact
mapping of raw Vorbis packets into a valid Ogg Vorbis physical
bitstream is described in Vorbis
bitstream mapping.

Bitstream structure

An Ogg stream is structured by dividing incoming packets into
segments of up to 255 bytes and then wrapping a group of contiguous
packet segments into a variable length page preceded by a page
header.  Both the header size and page size are variable; the page
header contains sizing information and checksum data to determine
header/page size and data integrity.

The bitstream is captured (or recaptured) by looking for the beginning
of a page, specifically the capture pattern.  Once the capture pattern
is found, the decoder verifies page sync and integrity by computing
and comparing the checksum. At that point, the decoder can extract the
packets themselves.

Packet segmentation

Packets are logically divided into multiple segments before encoding
into a page. Note that the segmentation and fragmentation process is a
logical one; it's used to compute page header values and the original
page data need not be disturbed, even when a packet spans page
boundaries.

The raw packet is logically divided into [n] 255 byte segments and a
last fractional segment of < 255 bytes.  A packet size may well
consist only of the trailing fractional segment, and a fractional
segment may be zero length.  These values, called "lacing values" are
then saved and placed into the header segment table.

An example should make the basic concept clear:

<tt>
raw packet:
  ___________________________________________
 |______________packet data__________________| 753 bytes

lacing values for page header segment table: 255,255,243
</tt>

We simply add the lacing values for the total size; the last lacing
value for a packet is always the value that is less than 255. Note
that this encoding both avoids imposing a maximum packet size as well
as imposing minimum overhead on small packets (as opposed to, eg,
simply using two bytes at the head of every packet and having a max
packet size of 32k.  Small packets (<255, the typical case) are
penalized with twice the segmentation overhead). Using the lacing
values as suggested, small packets see the minimum possible
byte-aligned overheade (1 byte) and large packets, over 512 bytes or
so, see a fairly constant ~.5% overhead on encoding space.

Note that a lacing value of 255 implies that a second lacing value
follows in the packet, and a value of < 255 marks the end of the
packet after that many additional bytes.  A packet of 255 bytes (or a
multiple of 255 bytes) is terminated by a lacing value of 0:

<tt>
raw packet:
  _______________________________
 |________packet data____________|          255 bytes

lacing values: 255, 0
</tt>

Note also that a 'nil' (zero length) packet is not an error; it
consists of nothing more than a lacing value of zero in the header.

Packets spanning pages

Packets are not restricted to beginning and ending within a page,
although individual segments are, by definition, required to do so.
Packets are not restricted to a maximum size, although excessively
large packets in the data stream are discouraged; the Ogg
bitstream specification strongly recommends nominal page size of
approximately 4-8kB (large packets are foreseen as being useful for
initialization data at the beginning of a logical bitstream).

After segmenting a packet, the encoder may decide not to place all the
resulting segments into the current page; to do so, the encoder places
the lacing values of the segments it wishes to belong to the current
page into the current segment table, then finishes the page.  The next
page is begun with the first value in the segment table belonging to
the next packet segment, thus continuing the packet (data in the
packet body must also correspond properly to the lacing values in the
spanned pages. The segment data in the first packet corresponding to
the lacing values of the first page belong in that page; packet
segments listed in the segment table of the following page must begin
the page body of the subsequent page).

The last mechanic to spanning a page boundary is to set the header
flag in the new page to indicate that the first lacing value in the
segment table continues rather than begins a packet; a header flag of
0x01 is set to indicate a continued packet.  Although mandatory, it
is not actually algorithmically necessary; one could inspect the
preceding segment table to determine if the packet is new or
continued.  Adding the information to the packet_header flag allows a
simpler design (with no overhead) that needs only inspect the current
page header after frame capture.  This also allows faster error
recovery in the event that the packet originates in a corrupt
preceding page, implying that the previous page's segment table
cannot be trusted.

Note that a packet can span an arbitrary number of pages; the above
spanning process is repeated for each spanned page boundary.  Also a
'zero termination' on a packet size that is an even multiple of 255
must appear even if the lacing value appears in the next page as a
zero-length continuation of the current packet.  The header flag
should be set to 0x01 to indicate that the packet spanned, even though
the span is a nil case as far as data is concerned.

The encoding looks odd, but is properly optimized for speed and the
expected case of the majority of packets being between 50 and 200
bytes (note that it is designed such that packets of wildly different
sizes can be handled within the model; placing packet size
restrictions on the encoder would have only slightly simplified design
in page generation and increased overall encoder complexity).

The main point behind tracking individual packets (and packet
segments) is to allow more flexible encoding tricks that requiring
explicit knowledge of packet size. An example is simple bandwidth
limiting, implemented by simply truncating packets in the nominal case
if the packet is arranged so that the least sensitive portion of the
data comes last.

Page header

The headering mechanism is designed to avoid copying and re-assembly
of the packet data (ie, making the packet segmentation process a
logical one); the header can be generated directly from incoming
packet data.  The encoder buffers packet data until it finishes a
complete page at which point it writes the header followed by the
buffered packet segments.

capture_pattern

 A header begins with a capture pattern that simplifies identifying
 pages; once the decoder has found the capture pattern it can do a more
 intensive job of verifying that it has in fact found a page boundary
 (as opposed to an inadvertent coincidence in the byte stream).

<tt>
 byte value

  0  0x4f 'O'
  1  0x67 'g'
  2  0x67 'g'
  3  0x53 'S'
</tt>

stream_structure_version

 The capture pattern is followed by the stream structure revision:

<tt>
 byte value

  4  0x00
</tt>

header_type_flag

 The header type flag identifies this page's context in the bitstream:

<tt>
 byte value

  5  bitflags: 0x01: unset = fresh packet
	               set = continued packet
	       0x02: unset = not first page of logical bitstream
                       set = first page of logical bitstream (bos)
	       0x04: unset = not last page of logical bitstream
                       set = last page of logical bitstream (eos)
</tt>

absolute granule position

 (This is packed in the same way the rest of Ogg data is packed; LSb
 of LSB first.  Note that the 'position' data specifies a 'sample'
 number (eg, in a CD quality sample is four octets, 16 bits for left
 and 16 bits for right; in video it would likely be the frame number.
 It is up to the specific codec in use to define the semantic meaning
 of the granule position value).  The position specified is the total
 samples encoded after including all packets finished on this page
 (packets begun on this page but continuing on to the next page do not
 count).  The rationale here is that the position specified in the
 frame header of the last page tells how long the data coded by the
 bitstream is.  A truncated stream will still return the proper number
 of samples that can be decoded fully.

 A special value of '-1' (in two's complement) indicates that no packets
 finish on this page.

<tt>
 byte value

  6  0xXX LSB
  7  0xXX
  8  0xXX
  9  0xXX
 10  0xXX
 11  0xXX
 12  0xXX
 13  0xXX MSB
</tt>

stream serial number

 Ogg allows for separate logical bitstreams to be mixed at page
 granularity in a physical bitstream.  The most common case would be
 sequential arrangement, but it is possible to interleave pages for
 two separate bitstreams to be decoded concurrently.  The serial
 number is the means by which pages physical pages are associated with
 a particular logical stream.  Each logical stream must have a unique
 serial number within a physical stream:

<tt>
 byte value

 14  0xXX LSB
 15  0xXX
 16  0xXX
 17  0xXX MSB
</tt>

page sequence no

 Page counter; lets us know if a page is lost (useful where packets
 span page boundaries).

<tt>
 byte value

 18  0xXX LSB
 19  0xXX
 20  0xXX
 21  0xXX MSB
</tt>

page checksum

 32 bit CRC value (direct algorithm, initial val and final XOR = 0,
 generator polynomial=0x04c11db7).  The value is computed over the
 entire header (with the CRC field in the header set to zero) and then
 continued over the page.  The CRC field is then filled with the
 computed value.

 (A thorough discussion of CRC algorithms can be found in "A
 Painless Guide to CRC Error Detection Algorithms" by Ross
 Williams ross@guest.adelaide.edu.au.)

<tt>
 byte value

 22  0xXX LSB
 23  0xXX
 24  0xXX
 25  0xXX MSB
</tt>

page_segments

 The number of segment entries to appear in the segment table. The
 maximum number of 255 segments (255 bytes each) sets the maximum
 possible physical page size at 65307 bytes or just under 64kB (thus
 we know that a header corrupted so as destroy sizing/alignment
 information will not cause a runaway bitstream.  We'll read in the
 page according to the corrupted size information that's guaranteed to
 be a reasonable size regardless, notice the checksum mismatch, drop
 sync and then look for recapture).

<tt>
 byte value

 26 0x00-0xff (0-255)
</tt>

segment_table (containing packet lacing values)

 The lacing values for each packet segment physically appearing in
 this page are listed in contiguous order.

<tt>
 byte value

 27 0x00-0xff (0-255)
 [...]
 n  0x00-0xff (0-255, n=page_segments+26)
</tt>

Total page size is calculated directly from the known header size and
lacing values in the segment table. Packet data segments follow
immediately after the header.

Page headers typically impose a flat .25-.5% space overhead assuming
nominal ~8k page sizes.  The segmentation table needed for exact
packet recovery in the streaming layer adds approximately .5-1%
nominal assuming expected encoder behavior in the 44.1kHz, 128kbps
stereo encodings.

Ogg is a Xiph.org Foundation effort
to protect essential tenets of Internet multimedia from corporate
hostage-taking; Open Source is the net's greatest tool to keep
everyone honest. See About
the Xiph.org Foundation for details.

Ogg Vorbis is the first Ogg audio CODEC.  Anyone may freely use and
distribute the Ogg and Vorbis specification, whether in a private,
public or corporate capacity.  However, the Xiph.org Foundation and
the Ogg project (xiph.org) reserve the right to set the Ogg Vorbis
specification and certify specification compliance.

Xiph.org's Vorbis software CODEC implementation is distributed under a
BSD-like license.  This does not restrict third parties from
distributing independent implementations of Vorbis software under
other licenses.

Ogg, Vorbis, Xiph.org Foundation and their logos are trademarks (tm)
of the Xiph.org Foundation.  These
pages are copyright (C) 1994-2002 Xiph.org Foundation. All rights
reserved.


text:
import { NgModule } from '@angular/core';
import 'firebase/auth';
import { FirebaseApp, AngularFireModule } from 'angularfire2';
import { AngularFireAuth } from './auth';
export function _getAngularFireAuth(app) {
    return new AngularFireAuth(app);
}
export const AngularFireAuthProvider = {
    provide: AngularFireAuth,
    useFactory: _getAngularFireAuth,
    deps: [FirebaseApp]
};
export const AUTH_PROVIDERS = [
    AngularFireAuthProvider,
];
export class AngularFireAuthModule {
}
AngularFireAuthModule.decorators = [
    { type: NgModule, args: [{
                imports: [AngularFireModule],
                providers: [AUTH_PROVIDERS]
            },] },
];
AngularFireAuthModule.ctorParameters = () => [];
//# sourceMappingURL=auth.module.js.map


text:
#ifndef	_MACHINE_MD_VAR_H_
#define	_MACHINE_MD_VAR_H_

typedef void cpu_block_copy_t(const void *src, void *dst, size_t len);
typedef void cpu_block_zero_t(void *dst, size_t len);

extern	char	tl0_base[];
extern	char	_end[];

extern	long	Maxmem;

extern	vm_offset_t kstack0;
extern	vm_paddr_t kstack0_phys;

struct	pcpu;
struct	md_utrap;

const char *cpu_cpuid_prop(u_int cpu_impl);
uint32_t cpu_get_mid(u_int cpu_impl);
void	cpu_identify(u_long vers, u_int clock, u_int id);
void	cpu_setregs(struct pcpu *pc);
int	is_physical_memory(vm_paddr_t addr);
struct md_utrap *utrap_alloc(void);
void	utrap_free(struct md_utrap *ut);
struct md_utrap *utrap_hold(struct md_utrap *ut);

cpu_block_copy_t spitfire_block_copy;
cpu_block_zero_t spitfire_block_zero;
cpu_block_copy_t zeus_block_copy;
cpu_block_zero_t zeus_block_zero;

extern	cpu_block_copy_t *cpu_block_copy;
extern	cpu_block_zero_t *cpu_block_zero;

/*
 * Given that the VTOC8 disk label only uses 16-bit fields for cylinders,
 * heads and sectors we might need to adjust the geometry of large disks.
 */
struct ccb_calc_geometry;
int scsi_da_bios_params(struct ccb_calc_geometry *ccg);
struct disk;
void sparc64_ata_disk_firmware_geom_adjust(struct disk *disk);
#define	ata_disk_firmware_geom_adjust(disk)				\
	sparc64_ata_disk_firmware_geom_adjust(disk)

#endif /* !_MACHINE_MD_VAR_H_ */


text:
{% extends "simple_gallery_base.html" %}
{% load static wagtailcore_tags wagtailimages_tags wagtailsimplegallery_tags %}

{% block title %}{{ page.seo_title }}{% endblock %}
{% block metadesc %}{{ page.search_description }}{% endblock %}

{% block content %}

{{ page.title }}

            {% if page.intro_title %}
{{ page.intro_title }}
{% endif %}
            {% if page.intro_text %}{{ page.intro_text|richtext }}{% endif %}
            {% if current_tag %}
#{{ current_tag }}
{% endif %}
            {% if gallery_tags %}

              Tags:
              {% for tag in gallery_tags %}
              #{{ tag }}
              {% endfor %}

            {% endif %}

    {% include 'wagtail_simple_gallery/simple_gallery.html' %}

    {% if gallery_images.has_next or gallery_images.has_previous %}

          {% if gallery_images.has_previous %}
          << Previous
          {% endif %}

          {% for page in gallery_images.paginator.page_range %}

              {{ page }}

          {% endfor %}

          {% if gallery_images.has_next %}
          Next >>
          {% endif %}

    {% endif %}

{% endblock %}

{% block extra_js %}{% endblock %}


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Components, registerComponent } from '../../lib/vulcan-core';

export class AccountsForm extends PureComponent<any> {
  form: any

  componentDidMount() {
    let form = this.form;
    if (form) {
      form.addEventListener('submit', (e) => {
        e.preventDefault();
      });
    }
  }

  render() {
    const {
      // hasPasswordService,
      oauthServices,
      fields,
      buttons,
      // error,
      messages,
      ready = true,
      className,
    } = this.props;
    const _className = classnames('accounts-ui', { ready }, className);
    return (
      <form
        ref={(ref) => this.form = ref}
        className={_className}
        noValidate
      >
        <Components.AccountsFields fields={ fields } />
        <Components.AccountsButtons buttons={ buttons } />
        <Components.AccountsPasswordOrService oauthServices={ oauthServices } />
        <Components.AccountsSocialButtons oauthServices={ oauthServices } />
        <Components.AccountsFormMessages messages={messages} />

            This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

      </form>
    );
  }
}
(AccountsForm as any).propTypes = {
  oauthServices: PropTypes.object,
  fields: PropTypes.object.isRequired,
  buttons: PropTypes.object.isRequired,
  error: PropTypes.string,
  ready: PropTypes.bool
};

const AccountsFormComponent = registerComponent('AccountsForm', AccountsForm);

declare global {
  interface ComponentTypes {
    AccountsForm: typeof AccountsFormComponent
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package web;

import entity.Airplane;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

/**
 *
 * @author Simon
 */
@WebServlet(name="AddServlet", urlPatterns={"/AddServlet"})
public class AddServlet extends HttpServlet {
    @PersistenceContext EntityManager em;
    @Resource UserTransaction utx;

    /**
     * Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            assert em != null;
            String id = request.getParameter("id");
            String type = request.getParameter("type");
            int engines = Integer.parseInt(request.getParameter("engines"));
            Airplane a = new Airplane();
            a.setId(id);
            a.setType(type);
            a.setEngines(engines);

            utx.begin();
            em.persist(a);
            utx.commit();

            List <Airplane> l = em.createQuery("select a from Airplane a").getResultList();
            request.setAttribute("airplaneList", l);
            RequestDispatcher rd = request.getRequestDispatcher("ListView.jsp");
            rd.forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("exception", ex);
            RequestDispatcher rd = request.getRequestDispatcher("ExceptionView.jsp");
            rd.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
'use strict';

var assert = require('assert');
var DBOutputFormat = require('hadoop-output').DBOutputFormat;
var Job = require('hadoop-job').Job;

function testSetOutput () {
  var job = new Job();
  var tableName = 'USERS';

  // Test wrong arguments
  try {
    DBOutputFormat.setOutput();
  } catch (err) {
    assert.equal('Three arguments expected', err.message);
  }

  try {
    DBOutputFormat.setOutput(job);
  } catch (err) {
    assert.equal('Three arguments expected', err.message);
  }

  try {
    DBOutputFormat.setOutput(job, tableName);
  } catch (err) {
    assert.equal('Three arguments expected', err.message);
  }

  try {
    DBOutputFormat.setOutput('job', tableName, 1);
  } catch (err) {
    assert.equal('First argument must be a Job object', err.message);
  }

  try {
    DBOutputFormat.setOutput(job, tableName, '1');
  } catch (err) {
    assert.equal('Third argument must be an array or a number', err.message);
  }

  // Test
  DBOutputFormat.setOutput(job, tableName, 1);

  DBOutputFormat.setOutput(job, tableName, ['name', 'email']);
}

module.exports.testDBOutputFormat = function (cb) {

  try {
    testSetOutput();
  } catch (err) {
    if (err.stack) {
      console.error(err.stack);
    }
    throw new Error(err.message);
  }

  cb();

};


text:
namespace OpenSofa {
namespace io {

class Server {
public:
  typedef std::function<void(unsigned int id, const Connection::Ptr&)> OnConnectedCallback;
  typedef std::function<void(unsigned int id)> OnDisconnectedCallback;

  //! Start server and associated components
  virtual void start() = 0;

  //! Stop server and associated components
  virtual void stop() = 0;

  //! Set a listener for new connections
  virtual void setConnectionListener(const OnConnectedCallback& onConnected, const OnDisconnectedCallback& onDisconnected) = 0;

  virtual std::map<unsigned int, Connection::Ptr> getConnections() const = 0;
};
}}


text:
function [obj,nObj] = vcGetObjects(objType)
%Retrieve cell larray of objects of objType
%
%  [obj,nObj] = vcGetObjects(objType)
%
%   Return the cell array of a particular type of object.  Optionally, the
%   total number of objects of this type is returned, too.
%
%  See Also:  vcGetObject, vcGetSelectedObject
%
% Examples:
%  obj = vcGetObjects('PIXEL');
%  [obj, nObj] = vcGetObjects('SCENE');
%
% Copyright ImagEval Consultants, LLC, 2005.

global vcSESSION;

% Translate various names into the proper name used in vcSESSION.
% This routine also forces upper case on the object type, as required.
objType = vcEquivalentObjtype(objType);

if checkfields(vcSESSION,objType),  eval(['obj = vcSESSION.',objType,';']);
else                                obj{1} = [];
end

if nargout == 2, nObj = length(obj); end

return


text:
from __future__ import absolute_import
import os

from pychron.core.helpers.filetools import unique_path

# ============= standard library imports ========================
# ============= local library imports  ==========================
root = os.path.join(os.path.expanduser("~"), "Desktop", "filelog")
if not os.path.isdir(root):
    os.mkdir(root)
p, _ = unique_path(root, "mem")

def file_log(msg):
    with open(os.path.join(root, p), "a") as wfile:
        wfile.write("{}\n".format(msg))

# ============= EOF =============================================


text:
package http2

import (
	"compress/gzip"
	"io"
	"net/http"
	"strings"
)

// ResponseWriter is required for Header/WriteHeader methods
type gzipResponseWriter struct {
	io.Writer
	http.ResponseWriter
}

// Writer and ResponseWriter both have Write method, make sure we invoke Write on
// the gzip wrapped writer
func (w gzipResponseWriter) Write(b []byte) (int, error) {
	return w.Writer.Write(b)
}

// inspired by https://gist.github.com/the42/1956518
func GzipHandler(w http.ResponseWriter, r *http.Request, inner http.HandlerFunc) {
	if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
		inner(w, r)
		return
	}
	w.Header().Set("Content-Encoding", "gzip")
	gz := gzip.NewWriter(w)
	defer gz.Close()
	gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
	inner(gzr, r)
}


text:
import React from 'react';
import styled from '../../styles/styled-components';
import RecentFile from './RecentFile';

const Wrapper = styled.div`
  flex: 1;
`;

const Title = styled.p`
  color: ${props => props.theme.pallete.gray[5]};
  line-height: 1;
  margin: 0;
  margin-bottom: 24px;
`;

const List = styled.div`
  display: flex;
  flex-wrap: wrap;
  margin: -16px;
`;

const RecentFileList = () => (
  <Wrapper>
    <Title>Recent files</Title>
    <List />
  </Wrapper>
);

export default RecentFileList;


text:
package org.apache.camel.component.cxf;

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

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxp.XmlConverter;
import org.apache.camel.language.xpath.XPathBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.BusFactory;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.frontend.ClientFactoryBean;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.junit.Test;

public class CxfConsumerPayloadXPathClientServerTest extends CamelTestSupport {
    private static final String ECHO_RESPONSE = "<ns1:echoResponse xmlns:ns1=\"http://cxf.component.camel.apache.org/\">"
        + "<return xmlns=\"http://cxf.component.camel.apache.org/\">echo Hello World!</return>"
        + "</ns1:echoResponse>";

    protected final String simpleEndpointAddress = "http://localhost:"
            + CXFTestSupport.getPort1() + "/" + getClass().getSimpleName() + "/test";
    protected final String simpleEndpointURI = "cxf://" + simpleEndpointAddress
            + "?serviceClass=org.apache.camel.component.cxf.HelloService";

    private String testMessage;
    private String receivedMessageCxfPayloadApplyingXPath;
    private String receivedMessageByDom;
    private String receivedMessageStringApplyingXPath;

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from(simpleEndpointURI + "&dataFormat=PAYLOAD").to("log:info").process(new Processor() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void process(final Exchange exchange) throws Exception {
                        Object request = exchange.getIn().getBody();
                        assertIsInstanceOf(CxfPayload.class, request);

                        //attempt 1) applying XPath to exchange.getIn().getBody()
                        receivedMessageCxfPayloadApplyingXPath = XPathBuilder.xpath("//*[name()='arg0']/text()").evaluate(context, request, String.class);

                        //attempt 2) in stead of XPATH, browse the DOM-tree
                        CxfPayload<SoapHeader> payload = (CxfPayload<SoapHeader>) request;
                        Element el = payload.getBody().get(0);
                        Element el2 = (Element) el.getFirstChild();
                        Text textnode = (Text) el2.getFirstChild();
                        receivedMessageByDom = textnode.getNodeValue();

                        textnode = (Text) textnode.getNextSibling();
                        while (textnode != null) {
                        //the textnode appears to have siblings!
                            receivedMessageByDom = receivedMessageByDom + textnode.getNodeValue();
                            textnode = (Text) textnode.getNextSibling();
                        }

                        //attempt 3) apply XPATH after converting CxfPayload to String
                        request = exchange.getIn().getBody(String.class);
                        assertIsInstanceOf(String.class, request);
                        receivedMessageStringApplyingXPath = XPathBuilder.xpath("//*[name()='arg0']/text()").evaluate(context, request, String.class);

                        //build some dummy response
                        XmlConverter converter = new XmlConverter();
                        Document outDocument = converter.toDOMDocument(ECHO_RESPONSE, exchange);
                        List<Source> outElements = new ArrayList<>();
                        outElements.add(new DOMSource(outDocument.getDocumentElement()));
                        // set the payload header with null
                        CxfPayload<SoapHeader> responsePayload = new CxfPayload<>(null, outElements, null);
                        exchange.getOut().setBody(responsePayload);
                    }
                });
            }
        };
    }

    private void buildTestMessage(int size) {
        testMessage = StringUtils.repeat("x", size);
    }

    @Test
    public void testMessageWithIncreasingSize() throws Exception {

        execTest(1);
        execTest(10);
        execTest(100);
        execTest(1000);
        execTest(10000);
        execTest(100000);

    }

    private void execTest(int size) throws Exception {
        buildTestMessage(size);

        ClientProxyFactoryBean proxyFactory = new ClientProxyFactoryBean();
        ClientFactoryBean clientBean = proxyFactory.getClientFactoryBean();
        clientBean.setAddress(simpleEndpointAddress);
        clientBean.setServiceClass(HelloService.class);
        clientBean.setBus(BusFactory.getDefaultBus());

        HelloService client = (HelloService) proxyFactory.create();

        String result = client.echo(testMessage);
        assertEquals("We should get the echo string result from router", "echo Hello World!", result);

        //check received requests
        assertEquals("Lengths of testMessage and receiveMessage should be equal (conversion body to String),", testMessage.length(), receivedMessageStringApplyingXPath.length());
        assertEquals("Lengths of receivedMessageByDom and receivedMessageCxfPayloadApplyingXPath should be equal", receivedMessageCxfPayloadApplyingXPath.length(), receivedMessageByDom.length());
        assertEquals("Lengths of testMessage and receiveMessage should be equal (body is CxfPayload),", testMessage.length(), receivedMessageCxfPayloadApplyingXPath.length());
    }
}


text:
import { expect } from 'chai';
import Router5 from 'router5';
import persistentParamsPlugin from '../modules';

const createRouter = () => new Router5([
    { name: 'route1', path: '/route1/:id' },
    { name: 'route2', path: '/route2/:id' }
]);

describe('router5 persistent params plugin', () => {
    let router;

    describe('with an array', () => {
        before(() => {
            router = createRouter();
        });

        it('should be registered with params', () => {
            router.usePlugin(persistentParamsPlugin(['mode']));
        });

        it('should persist specified parameters', (done) => {
            router.start();
            router.navigate('route2', { id: '2' }, {}, (err, state) => {
                expect(state.path).to.equal('/route2/2');
                router.navigate('route1', { id: '1', mode: 'dev' }, {}, (err, state) => {
                    expect(state.path).to.equal('/route1/1?mode=dev');

                    router.navigate('route2', { id: '2' }, {}, (err, state) => {
                        expect(state.path).to.equal('/route2/2?mode=dev');
                        done();
                    });
                });
            });
        });

        it('should save value on start', (done) => {
            router.stop();
            router.start('/route2/1?mode=dev', (err, state) => {
                expect(state.params).to.eql({ mode: 'dev', id: '1' });

                router.navigate('route2', { id: '2' }, {}, (err, state) => {
                    expect(state.path).to.equal('/route2/2?mode=dev');
                    done();
                });
            });
        });
    });

    describe('with an object', () => {
        before(() => {
            router.stop();
            router = createRouter();
        });

        it('should be registered with params', () => {
            router.usePlugin(persistentParamsPlugin({'mode': 'dev'}));
        });

        it('should persist specified parameters', (done) => {
            router.start();
            router.navigate('route1', { id: '1' }, {}, (err, state) => {
                expect(state.path).to.equal('/route1/1?mode=dev');
                done();
            });
        });
    });
});


text:
template<typename BASE>
class PropertyLoaderBase;
class ComponentLoaderFactory : public platform::Factory<PropertyLoaderBase<Component> >, public platform::Singleton<ComponentLoaderFactory>
{
    friend class platform::Singleton<ComponentLoaderFactory>;
    ComponentLoaderFactory();
    template<typename Elem_T>
    static std::auto_ptr<PropertyLoaderBase<Component> > CreateComponentLoader( int32_t Id );
};
template<typename Elem_T>
std::auto_ptr<PropertyLoaderBase<Component> > ComponentLoaderFactory::CreateComponentLoader( int32_t Id )
{
    return std::auto_ptr<PropertyLoaderBase<Component> >( new Elem_T() );
}

class DefaultComponentLoader: public ComponentLoader<DefaultComponent>
{
public:
    virtual void BindValues();
protected:
    DefaultComponentLoader();
    friend class ComponentLoaderFactory;
};

#endif//INCLUDED_CORE_COMPONENT_LOADER_FACTORY_H


text:
define(function(require) {
    /**
     * @ngInject
     */
    function Controller($scope) {
        $scope.ctrl = this;

        this.activity = $scope.activity;
    }

    Controller.prototype = {
        constructor: Controller,
        getMediaAttachment: function() {
            var index = -1;

            this.activity.object.attachments.forEach(function(item, idx) {
                if (item.fullImage) {
                    index = idx;
                }
            });

            if (index == -1) {
                return null;
            }

            return this.activity.object.attachments[index];
        },

        getMediaAttachments: function() {
            return this.activity.object.attachments.filter(function(item) {
                return !!item.image;
            });
        },
    };

    return Controller;
});


text:
from .manager import Manager

class LiquidPlanner(object):
    """An ORM-like interface to the LiquidPlanner API"""

    # (name, url, options)
    MANAGERS = (
            # The special two that don't require a workspace id
            ('account', '/account', {}),
            ('workspaces', '/workspaces', {}),

            # The rest in the same order as listed at
            # https://app.liquidplanner.com/api/help/types
            ('activities', '/workspaces/{workspace_id}/activities', {}),
            ('members', '/workspaces/{workspace_id}/members', {}),
            ('checklist_items', '/workspaces/{workspace_id}/checklist_items', {}),
            ('clients', '/workspaces/{workspace_id}/clients', {}),
            ('comments', '/workspaces/{workspace_id}/comments', {}),
            ('custom_fields', '/workspaces/{workspace_id}/custom_fields', {}),
            ('documents', '/workspaces/{workspace_id}/documents', {}),
            ('events', '/workspaces/{workspace_id}/events', {}),
            ('folders', '/workspaces/{workspace_id}/folders', {}),
            ('links', '/workspaces/{workspace_id}/links', {}),
            ('milestones', '/workspaces/{workspace_id}/milestones', {}),
            ('packages', '/workspaces/{workspace_id}/packages', {}),
            ('partial_day_events', '/workspaces/{workspace_id}/partial_day_events', {}),
            ('projects', '/workspaces/{workspace_id}/projects', {}),
            ('tags', '/workspaces/{workspace_id}/tags', {}),
            ('tasks', '/workspaces/{workspace_id}/tasks', {}),
            ('teams', '/workspaces/{workspace_id}/teams', {}),
            ('timesheet_entries', '/workspaces/{workspace_id}/timesheet_entries', {}),
            ('timesheets', '/workspaces/{workspace_id}/timesheets', {}),
            ('webhooks', '/workspaces/{workspace_id}/webhooks', {}),
            ('treeitems', '/workspaces/{workspace_id}/treeitems', {}),
    )

    # Valid options for the include parameter. Not enforced, but here as
    # a reference (and can be passed if you want to include everything)
    ASSOCIATED_RECORDS = [
            'activities', 'comments', 'dependencies', 'dependents',
            'documents', 'estimates', 'links', 'note', 'snapshots',
            'tags', 'timer'
    ]

    def __init__(self, credentials, use_first_workspace=True):
        self.workspace_id = None
        self.credentials = credentials

        for manager in self.MANAGERS:
            setattr(self, manager[0], Manager(self, *manager[0:2]))

        if use_first_workspace:
            self.workspace_id = self.workspaces.all()[0]['id']