text:
module Battleships.GUI (
  main
)

where

import Graphics.UI.Gtk hiding (Boat)
import Graphics.UI.Gtk.Gdk.EventM
import Data.Map hiding (filter, map)
import Data.List hiding (insert)
import Data.IORef
import Control.Monad.Trans
import Control.Monad
import Battleships.Game
import Gtk2hs.Utils
import Battleships.Placement

-- Images & Utils
toImageName :: Cell -> String
toImageName c = (show c) ++ ".png"

pixs :: [(Cell, IO Pixbuf)]
pixs = map (\x -> (x, pixbufNewFromFile $ toImageName x)) cells
        where cells = [Boat, Empty, BoatShot, EmptyShot]

pix :: Cell -> IO Pixbuf
pix c = let (Just (_, img)) = find  (\(cell, _) -> cell == c) pixs
        in img

scale :: Pixbuf -> Int -> Int -> IO Pixbuf
scale p wScale hScale= do w <- pixbufGetWidth p
                          h <- pixbufGetHeight p
                          pixbufScaleSimple p (w*wScale) (h*hScale) InterpNearest

newImageInEventBox :: Pixbuf -> IO EventBox
newImageInEventBox pb = do eb <- eventBoxNew
                           img <- imageNewFromPixbuf pb
                           set eb[containerChild := img, containerBorderWidth := 0 ]
                           return eb

getPlayersImage :: Cell -> IO Image
getPlayersImage cell = pix cell >>= imageNewFromPixbuf

-- hiding
getComputersImage :: Cell -> IO Image
getComputersImage cell = getComputersPixbuf cell >>= imageNewFromPixbuf

-- hiding
getComputersPixbuf :: Cell -> IO Pixbuf
getComputersPixbuf cell = if cell == Boat || cell == Empty
                          then do pix Empty
                          else do pix cell

-- Main function
main :: IO ()
main = do
  initGUI

  -- window
  window <- windowNew
  onDestroy window mainQuit

  -- main vertical box
  vbox       <- vBoxNew False 0
  set window [containerBorderWidth := 10,
              windowTitle := "Ships",
              containerChild := vbox]

  -- box for tables
  hboxTables <- hBoxNew False 0
  boxPackStart vbox hboxTables PackNatural 0

  -- box for ships placement
  vboxShips <- vBoxNew False 0
  boxPackStart hboxTables vboxShips PackNatural 0

  -- ships for placement
  let f n = do q <- newBoatForPlacement n
               boxPackStart vboxShips q PackGrow 0
  mapM_ f boats

  -- players table
  vboxPlayer <- vBoxNew False 0
  boxPackStart hboxTables vboxPlayer PackNatural 0

  labelPlayer <- labelNew (Just "Player")
  boxPackStart vboxPlayer labelPlayer PackNatural 0

  tablePlayer <- tableNew 2 2 True
  containerSetBorderWidth tablePlayer 10
  boxPackStart vboxPlayer tablePlayer PackNatural 0

  pt <- createSynchronizedTable tablePlayer emptyGrid playerImage
  redraw pt

  -- computers table
  vboxComputer <- vBoxNew False 0
  boxPackStart hboxTables vboxComputer PackNatural 0

  labelComputer <- labelNew (Just "Mr. Haskell")
  boxPackStart vboxComputer labelComputer PackNatural 0

  tableComputer <- tableNew 2 2 True
  containerSetBorderWidth tableComputer 10
  boxPackStart vboxComputer tableComputer PackNatural 0

  cg <- computerGrid
  ct <- createSynchronizedTable tableComputer cg (computerImage pt)
  redraw ct

  -- separator
  sep     <- hSeparatorNew
  boxPackStart vbox sep PackNatural 0

  -- box for buttons
  vboxButtons <- vBoxNew False 0
  boxPackStart vbox vboxButtons PackRepel 0
  containerSetBorderWidth vboxButtons 10

  -- new game button
  buttonNewGame <- buttonNewWithLabel "New Game"
  onClicked buttonNewGame (newGame pt ct)
  boxPackStart vboxButtons buttonNewGame PackGrow 0

  -- quit button
  buttonQuit <- buttonNewWithLabel "Quit"
  onClicked buttonQuit mainQuit
  boxPackStart vboxButtons buttonQuit PackGrow 0

  widgetShowAll window
  mainGUI

showPopup :: String -> IO ()
showPopup msg = do
  d <- dialogNew
  b <- dialogAddButton d "Close" ResponseClose
  dvb <- dialogGetUpper d
  l <- labelNew (Just msg)
  boxPackStart dvb l PackGrow 0
  widgetShowAll dvb
  onClicked b (widgetHide d)
  dialogRun d
  return ()

-- creates one boat for placement
newBoatForPlacement size = do
  pbSmall <- pix Boat
  pb <- scale pbSmall size 1

  eb <- newImageInEventBox pb

  -- drag and drop setup
  dragSourceSet eb [Button1] [ActionMove]
  dragSourceAddTextTargets eb
  eb `on` dragDataGet $ \ ctx ii ts -> selectionDataSetText (show size) >> return ()
  eb `on` dragDataDelete $ \ctx -> widgetSetSensitive eb False
  dragSourceSetIconPixbuf eb pb
  return eb

playerImage :: SynchronizedTable Cell  -> Cell -> Int -> Int -> IO Widget
playerImage syncTable cell x y = do
 i <- getPlayersImage cell
 dragDestSet i [DestDefaultAll] [ActionMove]
 dragDestAddTextTargets i
 i `on` dragDataReceived
           $ \ctx p ii ts -> do (Just dataSent) <- selectionDataGetText
                                let size = read dataSent :: Int
                                let coordinates = [(x+xs,y) | xs<-[0..(size-1)] ]
                                let f coord = liftIO (Gtk2hs.Utils.changeCellState syncTable coord Boat)
                                mapM_ f coordinates
                                return ()
 return (toWidget i)

computerImage :: SynchronizedTable Cell -> SynchronizedTable Cell -> Cell -> Int -> Int -> IO Widget
computerImage syncTablePlayer syncTable cell x y = do
 eb <- eventBoxNew
 i <- getComputersImage cell
 set eb[containerChild := i, containerBorderWidth := 0 ]
 onButtonPress eb (shoot i (x,y) syncTable syncTablePlayer)
 return (toWidget eb)

-- called when user press new game button
newGame :: SynchronizedTable Cell -> SynchronizedTable Cell -> IO ()
newGame pt ct = do setState pt emptyGrid
                   cg <- computerGrid
                   setState ct cg

-- called when user shoots
shoot :: Image -> Coord -> SynchronizedTable Cell -> SynchronizedTable Cell -> t -> IO Bool
shoot i coord cSyncTable pSyncTable _ = do
  cgOld <- readIORef (ref cSyncTable)

  let cellOld = look coord cgOld
  if cellOld == EmptyShot ||  cellOld == BoatShot
   then return True -- if user clicks on shot position, nothing happens
   else do
    -- updating grid
    let newCell =  shootToCell coord cgOld

    Gtk2hs.Utils.changeCellState cSyncTable coord newCell

    cg <- readIORef (ref cSyncTable)
    if finished cg then showPopup "Unbelievable! You won!" else return ()

    -- if player hits computer does not shoot
    if newCell == BoatShot
     then return True
     else do
       -- shoooting computer
       shootingComputer pSyncTable
       return True

shootingComputer :: SynchronizedTable Cell -> IO ()
shootingComputer pSyncTable = do
  pg <- readIORef (ref pSyncTable)
  coord <- computeMove pg
  let newCell = shootToCell coord pg
  Gtk2hs.Utils.changeCellState pSyncTable coord newCell

  pg <- readIORef (ref pSyncTable)

  if finished pg then showPopup "Mr Haskell beated you!" else
   when (newCell == BoatShot) (shootingComputer pSyncTable)


text:
import paddle.trainer.PyDataProvider2 as dp2
import collections
import swig_paddle

__all__ = ['DataProviderConverter']

class IScanner(object):
    def __init__(self, input_type, pos):
        self.input_type = input_type
        assert isinstance(self.input_type, dp2.InputType)
        self.pos = pos

    def scan(self, dat):
        pass

    def finish_scan(self, argument):
        pass

class DenseScanner(IScanner):
    def __init__(self, input_type, pos):
        IScanner.__init__(self, input_type, pos)
        self.__mat__ = []
        self.__height__ = 0

    def scan(self, dat):
        self.__mat__.extend(dat)
        self.__height__ += 1

    def finish_scan(self, argument):
        assert isinstance(argument, swig_paddle.Arguments)
        assert isinstance(self.input_type, dp2.InputType)
        m = swig_paddle.Matrix.createDense(self.__mat__,
                                           self.__height__,
                                           self.input_type.dim,
                                           False)
        argument.setSlotValue(self.pos, m)

class SparseBinaryScanner(IScanner):
    def __init__(self, input_type, pos):
        IScanner.__init__(self, input_type, pos)
        self.__rows__ = [0]
        self.__cols__ = []
        self.__height__ = 0
        self.__nnz__ = 0
        self.__value__ = []

    def scan(self, dat):
        self.extend_cols(dat)
        self.__rows__.append(len(dat) + self.__rows__[-1])
        self.__height__ += 1

    def extend_cols(self, dat):
        self.__cols__.extend(dat)

    def finish_scan(self, argument):
        assert isinstance(argument, swig_paddle.Arguments)
        assert isinstance(self.input_type, dp2.InputType)
        m = swig_paddle.Matrix.createSparse(self.__height__,
                                            self.input_type.dim,
                                            len(self.__cols__),
                                            len(self.__value__) == 0)
        assert isinstance(m, swig_paddle.Matrix)
        m.sparseCopyFrom(self.__rows__, self.__cols__, self.__value__)
        argument.setSlotValue(self.pos, m)

class SparseFloatScanner(SparseBinaryScanner):
    def __init__(self, input_type, pos):
        SparseBinaryScanner.__init__(self, input_type, pos)

    def extend_cols(self, dat):
        self.__cols__.extend((x[0] for x in dat))
        self.__value__.extend((x[1] for x in dat))

class IndexScanner(IScanner):
    def __init__(self, input_type, pos):
        IScanner.__init__(self, input_type, pos)
        self.__ids__ = []

    def scan(self, dat):
        self.__ids__.append(dat)

    def finish_scan(self, argument):
        ids = swig_paddle.IVector.create(self.__ids__)
        assert isinstance(argument, swig_paddle.Arguments)
        argument.setSlotIds(self.pos, ids)

class SequenceScanner(IScanner):
    def __init__(self, input_type, pos, inner_scanner, setter):
        IScanner.__init__(self, input_type, pos)
        self.__seq__ = [0]
        self.__inner_scanner__ = inner_scanner
        self.__setter__ = setter

    def scan(self, dat):
        self.__seq__.append(self.__seq__[-1] + self.get_size(dat))
        for each in dat:
            self.__inner_scanner__.scan(each)

    def finish_scan(self, argument):
        seq = swig_paddle.IVector.create(self.__seq__, False)
        self.__setter__(argument, self.pos, seq)
        self.__inner_scanner__.finish_scan(argument)

    def get_size(self, dat):
        if isinstance(self.__inner_scanner__, SequenceScanner):
            return sum(self.__inner_scanner__.get_size(item) for item in dat)
        else:
            return len(dat)

class DataProviderConverter(object):
    def __init__(self, input_types):
        self.input_types = input_types
        assert isinstance(self.input_types, collections.Sequence)
        for each in self.input_types:
            assert isinstance(each, dp2.InputType)

    def convert(self, dat, argument=None):
        if argument is None:
            argument = swig_paddle.Arguments.createArguments(0)
        assert isinstance(argument, swig_paddle.Arguments)
        argument.resize(len(self.input_types))

        scanners = [DataProviderConverter.create_scanner(i, each_type)
                    for i, each_type in enumerate(self.input_types)]

        for each_sample in dat:
            for each_step, scanner in zip(each_sample, scanners):
                scanner.scan(each_step)

        for scanner in scanners:
            scanner.finish_scan(argument)

        return argument

    def __call__(self, dat, argument=None):
        return self.convert(dat, argument)

    @staticmethod
    def create_scanner(i, each):
        assert isinstance(each, dp2.InputType)
        retv = None
        if each.type == dp2.DataType.Dense:
            retv = DenseScanner(each, i)
        elif each.type == dp2.DataType.Index:
            retv = IndexScanner(each, i)
        elif each.type == dp2.DataType.SparseNonValue:
            retv = SparseBinaryScanner(each, i)
        elif each.type == dp2.DataType.SparseValue:
            retv = SparseFloatScanner(each, i)
        assert retv is not None

        if each.seq_type == dp2.SequenceType.SUB_SEQUENCE:
            retv = SequenceScanner(each, i, retv, lambda a, p, seq:
            a.setSlotSubSequenceStartPositions(p, seq))

        if each.seq_type in [dp2.SequenceType.SUB_SEQUENCE,
                             dp2.SequenceType.SEQUENCE]:
            retv = SequenceScanner(each, i, retv, lambda a, p, seq:
            a.setSlotSequenceStartPositions(p, seq))
        return retv

redpajama_set_name: RedPajamaGithub


text:
package com.spike.giantdataanalysis.akka.commons.persistence

import akka.actor.{ActorRef, ActorSelection, ActorSystem, Props, SupervisorStrategy}
import akka.event.Logging
import akka.persistence.journal.leveldb.{SharedLeveldbJournal, SharedLeveldbStore}
import akka.persistence.{PersistentActor, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotOffer}
import akka.testkit.{ImplicitSender, TestKit}
import com.spike.giantdataanalysis.commons.support.IDs
import org.scalatest.{BeforeAndAfterAll, FunSpecLike, Matchers}

//---------------------------------------------------------------------------
// Events
//---------------------------------------------------------------------------
object Messages {

  case class Cmd(data: String)

  sealed trait ManagementCmd

  case object QueryCmd extends ManagementCmd

  case object EvilCmd extends ManagementCmd

  case class Evt(data: String)

}

object States {

  import Messages._

  case class EventStore(events: List[Evt] = Nil) {
    def update(event: Evt): EventStore = this.copy(event :: events)

    def size: Int = events.size

    override def toString: String = events.reverse.toString
  }

}

//---------------------------------------------------------------------------
// Persistence Actor implementation
//---------------------------------------------------------------------------

class EventPersistenceActor extends PersistentActor {
  val logger = Logging(context.system, this)

  override val supervisorStrategy = SupervisorStrategy.defaultStrategy

  import Messages._
  import States._

  // 内部状态
  private[this] var state = new EventStore
  val snapshotBatchSize = 10

  private[this] def updateState(event: Evt): Unit = state = state.update(event)

  override def persistenceId: String = "EventPersistence-" + IDs.UUID()

  override def receiveCommand: Receive = {
    case Cmd(data) =>
      persist(Evt(s"${data}-${state.size}")) { event =>
        updateState(event)
        // send to event stakeholders
        context.system.eventStream.publish(event)
        // snapshot internal state: faster recover
        if (lastSequenceNr != 0 && lastSequenceNr % snapshotBatchSize == 0) {
          logger.info("Taking snapshot...")
          saveSnapshot(state)
        }
      }

    // snapshot notification
    case SaveSnapshotSuccess(metadata) => logger.info("Snapshot success: {}", metadata)
    case SaveSnapshotFailure(metadata, cause) => logger.error(s"Snapshot failed: ${metadata}", cause)

    // management command
    case QueryCmd => logger.info("State={}", state)
    case EvilCmd => throw new Exception(EvilCmd.toString)
  }

  /// persist edge case handler

  override def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = {
    super.onPersistFailure(cause, event, seqNr)
  }

  override def onPersistRejected(cause: Throwable, event: Any, seqNr: Long): Unit = {
    super.onPersistRejected(cause, event, seqNr)
  }

  override def receiveRecover: Receive = {
    // persisted msg replay
    case evt@Evt(_) => {
      logger.info("Recovering: {}", evt)
      updateState(evt)
    }
    // snapshot offer
    case SnapshotOffer(metadata, snapshot: EventStore) => {
      logger.info("Recovering: metadata={}, snapshot={}", metadata, snapshot)
      state = snapshot
    }
  }

  /// recover edge case handler
  override def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = {
    super.onRecoveryFailure(cause, event)
  }

}

object EventPersistenceActor {
  def props: Props = Props(classOf[EventPersistenceActor])
}

//---------------------------------------------------------------------------
// BDD Test
//---------------------------------------------------------------------------
class PersistenceActorBDDSpec(testSystem: ActorSystem)
  extends TestKit(testSystem)
    with ImplicitSender
    with FunSpecLike with Matchers with BeforeAndAfterAll {

  import Messages._
  import States._

  var persistenceActorRef: ActorSelection = null

  def this() = this(ActorSystem("AS"))

  override def beforeAll(): Unit = {

    // start shared level db journal actor
    val leveldbStoreActorRef = testSystem.actorOf(Props[SharedLeveldbStore], "store")
    SharedLeveldbJournal.setStore(leveldbStoreActorRef, testSystem)

    val name = "pt" // + IDs.UUID()
    testSystem.actorOf(EventPersistenceActor.props, name)
    persistenceActorRef = testSystem.actorSelection("/user/" + name)
  }

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(testSystem)
  }

  describe("Play with persistence actor") {
    it("should save snapshot") {
      for (i <- 1 to 20) {
        persistenceActorRef ! Cmd(IDs.UUID())
        if (i % 10 == 0) {
          persistenceActorRef ! QueryCmd
        }
      }

      // hold on a second
      Thread.sleep(500L)

      // trigger actor restart
      persistenceActorRef ! EvilCmd
      // wait for restart
      Thread.sleep(5000L)

      // TODO(zhoujiagen) well it's: State=List() ???
      // check whether work as usual
      persistenceActorRef ! QueryCmd
      // wait for check
      Thread.sleep(5000L)
    }
  }

}


text:
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from crawl.models import Crawl, PageReference
from crawl.serializers import CrawlSerializer, PageReferenceSerializer

class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def crawl_list(request):
    if request.method == 'GET':
        crawl = Crawl.objects.all()
        serializer = CrawlSerializer(crawl, many=True)
        return JSONResponse(serializer.data)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CrawlSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)

@csrf_exempt
def crawl_detail(request, pk):
    try:
        crawl = Crawl.objects.get(pk=pk)
    except Crawl.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = CrawlSerializer(crawl)
        return JSONResponse(serializer.data)
    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = CrawlSerializer(crawl, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=404)
    elif request.method == 'DELETE':
        crawl.delete()
        return HttpResponse(status=204)

@csrf_exempt
def page_reference(request):
    if request.method == 'GET':
        page = PageReference.objects.all()
        p = Paginator(page, 10)
        serializer = PageReferenceSerializer(p.page(1), many=True)
        response = JSONResponse(serializer.data)
        response['Access-Control-Allow-Origin'] = '*'
        return response


text:
//
//  NSDateFormatter+JEToolkit.h
//  JEToolkit
//
//  Copyright (c) 2013 John Rommel Estropia
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
//

#import <Foundation/Foundation.h>

#import "JECompilerDefines.h"

@interface NSDateFormatter (JEToolkit)

#pragma mark - Shared Formatters

/*! NSDateFormatter for dates in ISO 8601 UTC date format (ex: 2013-03-20T15:30:20Z). Note: only supports UTC
 */
+ (nonnull NSDateFormatter *)ISO8601UTCDateFormatter JE_CONST;

/*! NSDateFormatter for dates in EXIF date format (ex: 2013-03-20 15:30:20). Note: only supports UTC
 */
+ (nonnull NSDateFormatter *)EXIFDateFormatter JE_CONST;

@end


text:
package com.infinities.keystone4j.contrib.oauth1.impl;

import com.infinities.keystone4j.contrib.oauth1.OAuth1Api;

public class OAuth1ApiImpl implements OAuth1Api {

}


text:
Praxyk API Clients
=================

This directory contains all of the various client bindings for the Praxyk API. These bindings simplify the process of interacting with the API and give developers a means of building applications around our services without having to make raw GET and POST requests.

The client bindings provided here include both a command-line utility and modules that can be imported into your existing code. Examples for both of these use cases are demonstrated in the examples section.

#### Requirements
The client scripts are free to download but in order to access the API you will need to provide a set of valid Praxyk account credentials, if you don't have a Praxyk account you can sign-up today at [our website](http://www.praxyk.com) or even through the bindings themselves!

 * **Operating Systems** - Linux, OSX
 * **Python** - Python 2.7

#### Install
To install, simply clone the API branch of the praxyk project and run the client setup process. This will put the client script on your path and make the necessary config directories. Feel free to remove the praxyk folder when you're done with the setup process.
```sh
git clone -b api https://github.com/jhallard/praxyk
cd praxyk/client
./setup.py
```

This will walk your through the steps of installing the various command-line utilities and modules that you choose during the setup process.

#### Client Bindings Status
Language       | Status      | Info
-------------- | ----------- | ----------------------------------------------------
CL Utility     | In Progress | This is an interactive program that can be used to access the entire range of Praxyk services from a terminal.
Python         | In Progress | Python is the first language we plan to make bindings for, v.1 should be done soon.
C++            | Planned     | We would like to make some C++ bindings but it isn't very high on the priority list.

### Commmand-Line Utility
Included with this set of client bindings is an interactive command-line based script called `praxyk_client`. This script, written in Python, wraps around the requests library and provides a simple yet powerful way of programmatically interacting with the Praxyk API.

### Python Bindings
Python is the first language we plan to create client library for, and it is the one we will put the most effort into maintaining.


text:
package jhc.redsniff.internal.predicates;

import static jhc.redsniff.matchers.numerical.NumericalMatchers.*;
import jhc.redsniff.internal.core.CollectionOf;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;

public class UniqueItem<E> extends SomeNumberOfItems<E> {
    private static final class SingleElementMatcher extends
            TypeSafeMatcher<Integer> implements CustomNumberMatcher {
        @Override
        public void describeTo(Description description) {
            description.appendText("a (unique)");
        }

        @Override
        protected boolean matchesSafely(Integer item) {
            return exactly(1).matches(item);
        }
    }

    protected UniqueItem() {
        super(new SingleElementMatcher());
    }

    @Factory
    public static <E> Predicate<E, CollectionOf<E>> uniqueElement() {
        return new UniqueItem<E>();
    }
}


text:
package put.ci.cevo.util.info;

public class EmptyProgressInfo implements ProgressInfo {

	private static final EmptyProgressInfo INSTANCE = new EmptyProgressInfo();

	private EmptyProgressInfo() {
		// forbid instantiation
	}

	@Override
	public void processed() {
		// nothing to do
	}

	@Override
	public void processed(Object object) {
		// nothing to do
	}

	@Override
	public void multiProcessed(long numElements) {
		// nothing to do
	}

	@Override
	public void finished() {
		// nothing to do
	}

	public static ProgressInfo emptyProgressInfo() {
		return INSTANCE;
	}

}


text:
'use strict';

angular
  .module('fli.search')
  .controller('search.result.places.foursquare.map.ctrl',
  function () {

    var vm = this;
    vm.zoom = 3;
    vm.center = {
      latitude: 40.1451,
      longitude: -99.6680
    };
    vm.window = {
      template: 'components/search/result/places/foursquare/map/window.html'
    };

    vm.click = function (marker, event, place) {
      vm.window.place = place;
    };

  });


text:
using namespace std;
#endif

UT_ADD_TEST_FILE(JTCDeadMonitorTest);

class DMTBaseClass : public JTCMonitor
{
public:

    virtual
    ~DMTBaseClass()
    {

    }
};

class DMTTestThread : public DMTBaseClass, public JTCThread
{
public:

    DMTTestThread()
    {
    }

    virtual
    ~DMTTestThread()
    {
	// cout << "DMTTestThread" << endl;
    }

    virtual void
    run()
    {
	// cout << "Done." << endl;
    }
};

UT_NEW_TEST(JTCDeadMonitorTest)
{
    try
    {
	JTCInitialize boot_jtc;

	JTCThreadHandle t = new DMTTestThread();
	t -> start();
    }
    catch(const JTCException& e)
    {
       UT_FAIL(e.getMessage());
    }
}


text:
'use strict';

const errorData = require('../model/error');

exports.getErros = (req, res, callback) => {
    // Busca todos os Erros existentes na platarforma.
    errorData.find({}, (err, items) => {
        if (err) {
            return callback(({ errorMessage: 'Falha interna do servidor.' }, 500));
        } else {
            // monta um objeto com a quantidade de
            let result = {
                count: items.length
            }
            return callback(null, 200, result)
        }
    });
};

exports.getRotina = (req, res, callback) => {
    // busco todas as rotinas existentes.
    const rotinaArray = ['NGFolhal', 'ERP', 'NGFiscal', 'NGContábil', 'NGTributos', 'NGFaturamento', 'NGFinanceiro']

    errorData.find({ rotina: rotinaArray }, (err, items) => {
        if (err) {
            return callback(({ errorMessage: 'Falha interna do servidor.' }, 500));
        } else {
            // Monto um objeto contendo a quantidade de erros existentes em cada rotina.
            let count = items.map(item => item.rotina)
                .reduce((prev, curr) => {
                    if (typeof prev[curr] !== 'undefined') {
                        prev[curr]++;
                        return prev;
                    } else {
                        prev[curr] = 1;
                        return prev;
                    }
                }, {});
            // Retorno para o front-end
            callback(null, 200, count)
        }
    });
};

exports.getCodigo = (req, res, callback) => {
    // Busco todos os codigos de erros exitntes no produto.
    const codigoArray = ['430', '429', '-2147', '0', '3021', '428', '-11', '13']

    errorData.find({ codigo: codigoArray }, (err, items) => {
        if (err) {
            return callback(({ errorMessage: 'Falha interna do servidor.' }, 500));
        } else {
            // Monto um objeto contendo a quantidade de erros existentes para cada codigo.
            let count = items.map(item => item.codigo)
                .reduce((prev, curr) => {
                    if (typeof prev[curr] !== 'undefined') {
                        prev[curr]++;
                        return prev;
                    } else {
                        prev[curr] = 1;
                        return prev;
                    }
                }, {});

            callback(null, 200, count);
        }
    })
};

exports.getComment = (req, res, callback) => {
    // busco todos os comentarios inseridos na plataforma
    errorData.find({}, (err, items) => {
        if (err) {
            return callback(({ errorMessage: 'Falha interna do servidor.' }, 500));
        } else {
            // crio um objeto com a lista de todos os comentarios existentes.
            let commentList = items.map(item => item.conteudo)
                .reduce((prev, curr) => prev.concat(curr), [])
                .map(x => x.comment);

            callback(null, 200, commentList);
        }
    });
};


text:
<?php

namespace NetSuite\Classes;

class CustomerStatusSearchRowBasic extends SearchRowBasic {
    public $description;
    public $externalId;
    public $includeInLeadReports;
    public $internalId;
    public $isInactive;
    public $name;
    public $probability;
    static $paramtypesmap = array(
        "description" => "SearchColumnStringField[]",
        "externalId" => "SearchColumnSelectField[]",
        "includeInLeadReports" => "SearchColumnBooleanField[]",
        "internalId" => "SearchColumnSelectField[]",
        "isInactive" => "SearchColumnBooleanField[]",
        "name" => "SearchColumnStringField[]",
        "probability" => "SearchColumnStringField[]",
    );
}


text:
package me.hatter.tests.ftp;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;

public final class FTPTest {

    public static void main(String[] args) throws UnknownHostException {
        String username = "caiwy";
        String password = "123";
        String server = "192.168.110.195";
        boolean error = false;

        final FTPClient ftp = new FTPClient();
        ftp.setCharset(Charset.forName("GBK"));
        ftp.setControlEncoding("GBK");
        ftp.setCopyStreamListener(createListener());
        ftp.setListHiddenFiles(true);

        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        try {
            int reply;
            ftp.connect(server);
            System.out.println("Connected to " + server + " on " + ftp.getDefaultPort());

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

        __main: try {
            if (!ftp.login(username, password)) {
                ftp.logout();
                error = true;
                break __main;
            }

            System.out.println("Remote system is " + ftp.getSystemType());

            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            // if (localActive) {
            // ftp.enterLocalActiveMode();
            // } else {
            ftp.enterLocalPassiveMode();
            // }

            ftp.setUseEPSVwithIPv4(true);

            ftp.cwd("/个税系列_1/测试用/个人所得税代扣代缴系统V1.2.150安装包_110/");

            System.out.println(">>>>>>>>>>>>>>>>>> list directories");
            FTPFile[] directories = ftp.listDirectories();
            // System.out.println(Arrays.asList(directories));

            System.out.println(">>>>>>>>>>>>>>>>>> list files");
            FTPFile[] files = ftp.listFiles();
            // System.out.println(Arrays.asList(files));

            System.out.println(">>>>>>>>>>>>>>>>>> list dirs");
            FTPFile[] dirs = ftp.mlistDir();
            // System.out.println(Arrays.asList(dirs));

            System.out.println(">>>>>>>>>>>>>>>>>> list names");
            String[] names = ftp.listNames();
            // System.out.println(Arrays.asList(names));

            System.out.println(">>>>>>>>>>>>>>>>>> do command: LIST");
            // ftp.setFileType(FTP.ASCII_FILE_TYPE);
//            ftp.pasv();
            boolean r = ftp.doCommand("LIST", "");
            // ftp.getReplyString();
            // r = ftp.doCommand("LIST", "");
            System.out.println(r);
            String[] strings = ftp.getReplyStrings();
            // System.out.println(Arrays.asList(strings));

            ftp.doCommand("HELP", null);

            // ftp.store

            // if (storeFile) {
            // InputStream input;
            //
            // input = new FileInputStream(local);
            //
            // ftp.storeFile(remote, input);
            //
            // input.close();
            // } else if (listFiles) {
            // if (lenient) {
            // FTPClientConfig config = new FTPClientConfig();
            // config.setLenientFutureDates(true);
            // ftp.configure(config);
            // }
            //
            // for (FTPFile f : ftp.listFiles(remote)) {
            // System.out.println(f.getRawListing());
            // System.out.println(f.toFormattedString());
            // }
            // } else if (mlsd) {
            // for (FTPFile f : ftp.mlistDir(remote)) {
            // System.out.println(f.getRawListing());
            // System.out.println(f.toFormattedString());
            // }
            // } else if (mlst) {
            // FTPFile f = ftp.mlistFile(remote);
            // if (f != null) {
            // System.out.println(f.toFormattedString());
            // }
            // } else if (listNames) {
            // for (String s : ftp.listNames(remote)) {
            // System.out.println(s);
            // }
            // } else if (feat) {
            // // boolean feature check
            // if (remote != null) { // See if the command is present
            // if (ftp.hasFeature(remote)) {
            // System.out.println("Has feature: " + remote);
            // } else {
            // if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            // System.out.println("FEAT " + remote + " was not detected");
            // } else {
            // System.out.println("Command failed: " + ftp.getReplyString());
            // }
            // }
            //
            // // Strings feature check
            // String[] features = ftp.featureValues(remote);
            // if (features != null) {
            // for (String f : features) {
            // System.out.println("FEAT " + remote + "=" + f + ".");
            // }
            // } else {
            // if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            // System.out.println("FEAT " + remote + " is not present");
            // } else {
            // System.out.println("Command failed: " + ftp.getReplyString());
            // }
            // }
            // } else {
            // if (ftp.features()) {
            // // Command listener has already printed the output
            // } else {
            // System.out.println("Failed: " + ftp.getReplyString());
            // }
            // }
            // } else if (doCommand != null) {
            // if (ftp.doCommand(doCommand, remote)) {
            // // Command listener has already printed the output
            // // for(String s : ftp.getReplyStrings()) {
            // // System.out.println(s);
            // // }
            // } else {
            // System.out.println("Failed: " + ftp.getReplyString());
            // }
            // } else {
            // OutputStream output;
            //
            // output = new FileOutputStream(local);
            //
            // ftp.retrieveFile(remote, output);
            //
            // output.close();
            // }

            ftp.noop(); // check that control connection is working OK

            ftp.logout();
        } catch (FTPConnectionClosedException e) {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
        }

        System.exit(error ? 1 : 0);
    } // end main

    private static CopyStreamListener createListener() {
        return new CopyStreamListener() {

            private long megsTotal = 0;

            // @Override
            public void bytesTransferred(CopyStreamEvent event) {
                bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
            }

            // @Override
            public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
                long megs = totalBytesTransferred / 1000000;
                for (long l = megsTotal; l < megs; l++) {
                    System.err.print("#");
                }
                megsTotal = megs;
            }
        };
    }
}


text:
/**
 * @overview
 * This file contains a dialog.
 *
 */

/**
 * Creates a dialog.
 * @class
 * This class is a base class for miscellaneous organizer-related dialogs. An instance
 * of this class can be re-used to show different overviews.
 *
 * @author Conrad Damon
 *
 * @param {Hash}	params		a hash of parameters
 * @param	{DwtControl}	params.parent		the parent widget
 * @param	{DwtMsgDialog}	params.msgDialog		the message dialog
 * @param	{String}	params.className		the CSS class name
 * @param	{String}	params.title		the dialog title
 * @param	{Array|constant}	params.standardButtons		an array of standard buttons to include. Defaults to {@link DwtDialog.OK_BUTTON} and {@link DwtDialog.CANCEL_BUTTON}.
 * @param	{Array}	params.extraButtons		a list of {@link DwtDialog_ButtonDescriptor} objects describing custom buttons to add to the dialog
 * @param	{DwtControl}	params.view				the dialog contents
 *
 * @extends	DwtDialog
 */
ZmDialog = function(params) {
	if (arguments.length == 0) { return; }

	DwtDialog.call(this, params);

	if (!params.view) {
		this.setContent(this._contentHtml());
	}

	if (this._button[DwtDialog.OK_BUTTON]) {
		this.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._okButtonListener));
	}

	this._overview = {};
	this._opc = appCtxt.getOverviewController();

	this._baseTabGroupSize = this._tabGroup.size();
};

ZmDialog.prototype = new DwtDialog;
ZmDialog.prototype.constructor = ZmDialog;

ZmDialog.prototype.isZmDialog = true;
ZmDialog.prototype.toString = function() { return "ZmDialog"; };

/**
 * @private
 */
ZmDialog.prototype._contentHtml =
function() {
	return "";
};

/**
 * Sets the view for this dialog.
 *
 * @param	{DwtComposite}		newView		the view
 * @param	{Boolean}		noReset		if true, do not reset the dialog; false otherwise
 */
ZmDialog.prototype.setView =
function(newView, noReset) {
	this.reset();
	if (newView) {
        var contentDiv = this._getContentDiv();
        var el = newView.getHtmlElement();
		contentDiv.parentNode.replaceChild(el, contentDiv);
		this._contentDiv = el;
	}
};

ZmDialog.prototype.popup =
function() {
	// Bug 38281: for multiuse dialogs, we need to re-add the discretionary
	// tab stops to the base list (the dialog buttons)
	this._tabGroup.__members._array.splice(this._baseTabGroupSize);
	this._tabGroup.addMember(this._getTabGroupMembers());

	DwtDialog.prototype.popup.call(this);
	if (this._focusElement) {
		appCtxt.getKeyboardMgr().grabFocus(this._focusElement);
	}
};

ZmDialog.prototype.reset =
function() {
	if (this._nameField) {
		this._nameField.value = "";
	}
	DwtDialog.prototype.reset.call(this);
};

/**
 * @private
 */
ZmDialog.prototype._okButtonListener =
function() {
	this.popdown();
};

/**
 * @private
 */
ZmDialog.prototype._setNameField =
function(fieldId) {
	this._nameField = this._focusElement = document.getElementById(fieldId);
	if (this._enterListener) {
		this.addEnterListener(new AjxListener(this, this._enterListener));
	}
};

/**
 * Displays the given list of tree views in an overview, creating it if
 * necessary, and appends the overview to an element in the dialog. Since
 * dialogs may be reused, it is possible that it will display different
 * overviews. That is handled by making sure that only the current overview is
 * visible.
 *
 * @param params		[hash]				hash of params:
 *        treeIds		[array]				list of tree views to show
 *        omit			[hash]				IDs of organizers to exclude
 *        fieldId		[string]			DOM ID of element that contains overview
 *        overviewId	[string]*			ID for the overview
 *        noRootSelect	[boolean]*			if true, don't make root tree item(s) selectable
 * @param forceSingle	[boolean]*			if true, don't make multi-account overviews
 * @private
 */
ZmDialog.prototype._setOverview =
function(params, forceSingle) {

	// when in multi-account mode, hide the old overview since we don't know
	// whether we want to show an overview container or just a single-account overview.
	if (appCtxt.multiAccounts) {
		var oldOverview = this._opc.getOverviewContainer(this._curOverviewId) ||
						  this._opc.getOverview(this._curOverviewId);

		if (oldOverview) {
			oldOverview.setVisible(false);
		}
	}

	// multi-account uses overview container
	if (appCtxt.multiAccounts && !forceSingle) {
		// use overviewId as the containerId; container will assign overviewId's
		var containerId = this._curOverviewId = params.overviewId;
		var ovContainer = this._opc.getOverviewContainer(containerId);
		if (!ovContainer) {
			var overviewParams = {
				overviewClass:	"dialogOverviewContainer",
				headerClass:	"DwtTreeItem",
				noTooltips:		true,
				treeStyle:		params.treeStyle,
				treeIds:		params.treeIds,
				overviewTrees:	params.overviewTrees,
				omit:			params.omit,
				omitPerAcct:	params.omitPerAcct,
				selectable:		params.selectable
			};
			var containerParams = {
				appName: params.appName,
				containerId: containerId
			};
			ovContainer = this._opc.createOverviewContainer(containerParams, overviewParams);
			ovContainer.setSize(Dwt.DEFAULT, "200");
			document.getElementById(params.fieldId).appendChild(ovContainer.getHtmlElement());
		}

		// make overview container visible
		ovContainer.setVisible(true);

		return ovContainer;
	}

	// single-account overview handling
	var overviewId = this._curOverviewId = params.overviewId;
	var overview = this._opc.getOverview(overviewId);
	if (!overview) {
		var ovParams = {
			overviewId:		overviewId,
			overviewClass:	params.overviewClass || "dialogOverview",
			headerClass:	"DwtTreeItem",
			noTooltips:		true,
			treeStyle:		params.treeStyle,
			treeIds:		params.treeIds,
			account:		((appCtxt.multiAccounts && params.forceSingle) ? appCtxt.getActiveAccount() : (params.account || appCtxt.getActiveAccount())),
			skipImplicit: 	true
		};
		overview = this._overview[overviewId] = this._opc.createOverview(ovParams);
		this._renderOverview(overview, params.treeIds, params.omit, params.noRootSelect);
		document.getElementById(params.fieldId).appendChild(overview.getHtmlElement());
	}

	this._makeOverviewVisible(overviewId);

	return overview;
};

/**
 * @private
 */
ZmDialog.prototype._makeOverviewVisible =
function(overviewId) {
	for (var id in this._overview) {
		this._overview[id].setVisible(id == overviewId);
	}
};

/**
 * Renders the tree views in the overview, and makes the header items
 * selectable (since they can generally be targets of whatever action the dialog
 * is facilitating).
 *
 * @param overview		[ZmOverview]		the overview
 * @param treeIds		[array]				list of tree views to show
 * @param omit			[hash]*				IDs of organizers to exclude
 * @param noRootSelect	[boolean]*			if true, don't make root tree item(s) selectable
 * @private
 */
ZmDialog.prototype._renderOverview =
function(overview, treeIds, omit, noRootSelect) {
	overview.set(treeIds, omit);
	if (!noRootSelect) {
		for (var i = 0; i < treeIds.length; i++) {
			var treeView = overview.getTreeView(treeIds[i]);
			var hi = treeView && treeView.getHeaderItem();
			if (hi) hi.enableSelection(true);
		}
	}
};

/**
 * @private
 */
ZmDialog.prototype._getOverview =
function() {
	return this._overview[this._curOverviewId];
};

/**
 * @private
 */
ZmDialog.prototype._getInputFields =
function() {
	return (this._nameField) ? [this._nameField] : null;
};

/**
 * @private
 */
ZmDialog.prototype._showError =
function(msg, loc) {
	var nLoc = loc || (new DwtPoint(this.getLocation().x + 50, this.getLocation().y + 100));
	var msgDialog = appCtxt.getMsgDialog();

	msgDialog.reset();
    msgDialog.setMessage(AjxStringUtil.htmlEncode(msg), DwtMessageDialog.CRITICAL_STYLE);
	msgDialog.popup(nLoc);
};

/**
 * @private
 */
ZmDialog.prototype._getTabGroupMembers =
function() {
	return [this._nameField];
};


text:
<?php

namespace Cake\Test\TestCase\View\Widget;

use Cake\TestSuite\TestCase;
use Cake\View\StringTemplate;
use Cake\View\Widget\ButtonWidget;

/**
 * Basic input test.
 */
class ButtonWidgetTest extends TestCase
{

    public function setUp()
    {
        parent::setUp();
        $templates = [
            'button' => '<button{{attrs}}>{{text}}</button>',
        ];
        $this->templates = new StringTemplate($templates);
        $this->context = $this->getMockBuilder('Cake\View\Form\ContextInterface')->getMock();
    }

    /**
     * Test render in a simple case.
     *
     * @return void
     */
    public function testRenderSimple()
    {
        $button = new ButtonWidget($this->templates);
        $result = $button->render(['name' => 'my_input'], $this->context);
        $expected = [
            'button' => ['type' => 'submit', 'name' => 'my_input'],
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with custom type
     *
     * @return void
     */
    public function testRenderType()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'name' => 'my_input',
            'type' => 'button',
            'text' => 'Some button'
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'button', 'name' => 'my_input'],
            'Some button',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with a text
     *
     * @return void
     */
    public function testRenderWithText()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'text' => 'Some <value>'
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'submit'],
            'Some <value>',
            '/button'
        ];
        $this->assertHtml($expected, $result);

        $data['escape'] = true;
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => ['type' => 'submit'],
            'Some <value>',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Test render with additional attributes.
     *
     * @return void
     */
    public function testRenderAttributes()
    {
        $button = new ButtonWidget($this->templates);
        $data = [
            'name' => 'my_input',
            'text' => 'Go',
            'class' => 'btn',
            'required' => true
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => [
                'type' => 'submit',
                'name' => 'my_input',
                'class' => 'btn',
                'required' => 'required'
            ],
            'Go',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }

    /**
     * Ensure templateVars option is hooked up.
     *
     * @return void
     */
    public function testRenderTemplateVars()
    {
        $this->templates->add([
            'button' => '<button {{attrs}} custom="{{custom}}">{{text}}</button>',
        ]);

        $button = new ButtonWidget($this->templates);
        $data = [
            'templateVars' => ['custom' => 'value'],
            'text' => 'Go',
        ];
        $result = $button->render($data, $this->context);
        $expected = [
            'button' => [
                'type' => 'submit',
                'custom' => 'value'
            ],
            'Go',
            '/button'
        ];
        $this->assertHtml($expected, $result);
    }
}


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

<TITLE>
ch.unifr.pai.twice.comm.serverPush.server
</TITLE>

<META NAME="date" CONTENT="2013-03-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

ch.unifr.pai.twice.comm.serverPush.server

Classes

AtmosphereHandler

AtmosphereServlet3

EventProcessing

ServerRemoteEvent


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Azure.SqlDatabase.ElasticScale
{
    using System;

    internal partial class TransientFaultHandling
    {
        /// <summary>
        /// A retry strategy with backoff parameters for calculating the exponential delay between retries.
        /// </summary>
        internal class ExponentialBackoff : RetryStrategy
        {
            private readonly int _retryCount;
            private readonly TimeSpan _minBackoff;
            private readonly TimeSpan _maxBackoff;
            private readonly TimeSpan _deltaBackoff;

            /// <summary>
            /// Initializes a new instance of the <see cref="ExponentialBackoff"/> class.
            /// </summary>
            public ExponentialBackoff()
                : this(DefaultClientRetryCount, DefaultMinBackoff, DefaultMaxBackoff, DefaultClientBackoff)
            {
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="ExponentialBackoff"/> class with the specified retry settings.
            /// </summary>
            /// <param name="retryCount">The maximum number of retry attempts.</param>
            /// <param name="minBackoff">The minimum backoff time</param>
            /// <param name="maxBackoff">The maximum backoff time.</param>
            /// <param name="deltaBackoff">The value that will be used to calculate a random delta in the exponential delay between retries.</param>
            public ExponentialBackoff(int retryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff)
                : this(null, retryCount, minBackoff, maxBackoff, deltaBackoff, DefaultFirstFastRetry)
            {
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="ExponentialBackoff"/> class with the specified name and retry settings.
            /// </summary>
            /// <param name="name">The name of the retry strategy.</param>
            /// <param name="retryCount">The maximum number of retry attempts.</param>
            /// <param name="minBackoff">The minimum backoff time</param>
            /// <param name="maxBackoff">The maximum backoff time.</param>
            /// <param name="deltaBackoff">The value that will be used to calculate a random delta in the exponential delay between retries.</param>
            public ExponentialBackoff(string name, int retryCount, TimeSpan minBackoff, TimeSpan maxBackoff,
                TimeSpan deltaBackoff)
                : this(name, retryCount, minBackoff, maxBackoff, deltaBackoff, DefaultFirstFastRetry)
            {
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="ExponentialBackoff"/> class with the specified name, retry settings, and fast retry option.
            /// </summary>
            /// <param name="name">The name of the retry strategy.</param>
            /// <param name="retryCount">The maximum number of retry attempts.</param>
            /// <param name="minBackoff">The minimum backoff time</param>
            /// <param name="maxBackoff">The maximum backoff time.</param>
            /// <param name="deltaBackoff">The value that will be used to calculate a random delta in the exponential delay between retries.</param>
            /// <param name="firstFastRetry">true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval.</param>
            public ExponentialBackoff(string name, int retryCount, TimeSpan minBackoff, TimeSpan maxBackoff,
                TimeSpan deltaBackoff, bool firstFastRetry)
                : base(name, firstFastRetry)
            {
                Guard.ArgumentNotNegativeValue(retryCount, "retryCount");
                Guard.ArgumentNotNegativeValue(minBackoff.Ticks, "minBackoff");
                Guard.ArgumentNotNegativeValue(maxBackoff.Ticks, "maxBackoff");
                Guard.ArgumentNotNegativeValue(deltaBackoff.Ticks, "deltaBackoff");
                Guard.ArgumentNotGreaterThan(minBackoff.TotalMilliseconds, maxBackoff.TotalMilliseconds, "minBackoff");

                _retryCount = retryCount;
                _minBackoff = minBackoff;
                _maxBackoff = maxBackoff;
                _deltaBackoff = deltaBackoff;
            }

            /// <summary>
            /// Returns the corresponding ShouldRetry delegate.
            /// </summary>
            /// <returns>The ShouldRetry delegate.</returns>
            public override ShouldRetry GetShouldRetry()
            {
                return delegate (int currentRetryCount, Exception lastException, out TimeSpan retryInterval)
                {
                    if (currentRetryCount < _retryCount)
                    {
                        var random = new Random();

                        var delta =
                            (int)
                                ((Math.Pow(2.0, currentRetryCount) - 1.0) *
                                 random.Next((int)(_deltaBackoff.TotalMilliseconds * 0.8),
                                     (int)(_deltaBackoff.TotalMilliseconds * 1.2)));
                        var interval =
                            (int)
                                Math.Min(checked(_minBackoff.TotalMilliseconds + delta),
                                    _maxBackoff.TotalMilliseconds);

                        retryInterval = TimeSpan.FromMilliseconds(interval);

                        return true;
                    }

                    retryInterval = TimeSpan.Zero;
                    return false;
                };
            }
        }
    }
}


text:
import { HashRouter as Router, Route, Switch }
  from 'react-router-dom';
import React from 'react';
import Signin from '../js/components/authentication/Signin';
import NavBar from './components/common/NavBar';
import Signup from './components/authentication/Signup';
import UserPage from '../js/components/user/UserPage';

// user PageAccessHelper here on UserPage and remove from other components
export default (
  <Router >
    <Switch>
      <div>
        <NavBar />
        <Route exact path="/signup" component={Signup} />
        <Route exact path="/signin" component={Signin} />
        <UserPage />
      </div>
    </Switch>
  </Router>
);


text:
include ../Makefile-examples-base.mk

.PHONY: image
image:
	docker build image -t gcr.io/kustomize-functions/example-validator:v0.1.0
	docker push gcr.io/kustomize-functions/example-validator:v0.1.0


text:
%{
MIT License

Copyright (c) [2016] [Mallory Ann Jensen, jensenma@alum.mit.edu]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
%}

function [tau_SRH,deltanq] = calculate_SRH(measured_file,SRV_file,deltanq,N_dop,T,type,W,D,saveFile,saveStart,sample_no)
%[tau_SRH,deltan1] =
%calculate_SRH(measured_file,SRV_file,deltanq,N_dop,T,type,W,D). Measured
%file and SRV file should be of the format: 'filename.mat.' deltanq is
%logspace injection range targeted. N_dop is the doping level of the sample
%of interest in cm^-3. T is the temperature of the measured in K. type is
%either 'n' or 'p'. W is the thickness of the sample in cm. D is the
%diffusivity of the minority carrier in this sample in cm/s which can be
%obtained from PVCDROM.

load(SRV_file);
deltan_SRV = deltan;

% Interpolate the SRV so that it matches the measured lifetime
SRVq = interp1(deltan_SRV,SRV,deltanq);

tau_surf =(W./(2.*SRVq))+((1/D).*((W/pi)^2)); %cm/s

for i = 1:length(deltanq)
    tau_intr(i,1) = Richter(T,deltanq(i),N_dop,type);
end

load(measured_file);
for i = 1:length(dataSave)
    % deltan = data.deltanq;
    % tau = data.tau_mean;
    % tau = tau';
    data = dataSave{i};
    deltan = data(:,1);
    tau = data(:,2);

    tauq = interp1(deltan,tau,deltanq);
%     tauq = tau;

    h=figure;
    loglog(deltanq,tauq.*1e6);
    hold all;
    loglog(deltanq,tau_surf.*1e6);
    hold all;
    loglog(deltanq,tau_intr.*1e6);

    xlabel('Excess carrier density (cm^-^3)','FontSize',30);
    ylabel('Lifetime (\mus)','FontSize',30);
    axis([5e13 1e17 0 25000]);

    tau_SRH_hold = ((1./tauq)-(1./tau_intr)-(1./tau_surf)).^(-1);
    hold all;
    loglog(deltanq,tau_SRH_hold.*1e6);
    legend('Measured','Surface','Intrinsic','SRH');
    title(['Sample ' sample_no],'FontSize',30);

    hgsave(h,[saveStart 'LifetimeBreakdown_' num2str(i)]);
    print(h,'-dpng','-r0',[saveStart 'LifetimeBreakdown_' num2str(i) '.png']);
    tau_SRH(i,:) = tau_SRH_hold;
end
save(saveFile,'tau_SRH','tau_intr','tauq','tau_surf','deltanq');


text:
#include "apt_text_message.h"
#include "apt_log.h"

/** Stage of text message processing (parsing/generation) */
typedef enum {
	APT_MESSAGE_STAGE_START_LINE,
	APT_MESSAGE_STAGE_HEADER,
	APT_MESSAGE_STAGE_BODY
} apt_message_stage_e;

/** Text message parser */
struct apt_message_parser_t {
	const apt_message_parser_vtable_t *vtable;
	void                              *obj;
	apr_pool_t                        *pool;
	apt_message_context_t              context;
	apr_size_t                         content_length;
	apt_message_stage_e                stage;
	apt_bool_t                         skip_lf;
	apt_bool_t                         verbose;
};

/** Text message generator */
struct apt_message_generator_t {
	const apt_message_generator_vtable_t *vtable;
	void                                 *obj;
	apr_pool_t                           *pool;
	apt_message_context_t                 context;
	apr_size_t                            content_length;
	apt_message_stage_e                   stage;
	apt_bool_t                            verbose;
};

/** Parse individual header field (name-value pair) */
APT_DECLARE(apt_header_field_t*) apt_header_field_parse(apt_text_stream_t *stream, apr_pool_t *pool)
{
	apr_size_t folding_length = 0;
	apr_array_header_t *folded_lines = NULL;
	apt_header_field_t *header_field;
	apt_str_t temp_line;
	apt_str_t *line;
	apt_pair_t pair;
	/* read name-value pair */
	if(apt_text_header_read(stream,&pair) == FALSE) {
		return NULL;
	}

	/* check folding lines (value spanning multiple lines) */
	while(stream->pos < stream->end) {
		if(apt_text_is_wsp(*stream->pos) == FALSE) {
			break;
		}

		stream->pos++;

		/* skip further white spaces (if any) */
		apt_text_white_spaces_skip(stream);

		if(!folded_lines) {
			folded_lines = apr_array_make(pool,1,sizeof(apt_str_t));
		}
		if(apt_text_line_read(stream,&temp_line) == TRUE) {
			line = apr_array_push(folded_lines);
			*line = temp_line;
			folding_length += line->length;
		}
	};

	header_field = apt_header_field_alloc(pool);
	/* copy parsed name of the header field */
	header_field->name.length = pair.name.length;
	header_field->name.buf = apr_palloc(pool, pair.name.length + 1);
	if(pair.name.length) {
		memcpy(header_field->name.buf, pair.name.buf, pair.name.length);
	}
	header_field->name.buf[header_field->name.length] = '\0';

	/* copy parsed value of the header field */
	header_field->value.length = pair.value.length + folding_length;
	header_field->value.buf = apr_palloc(pool, header_field->value.length + 1);
	if(pair.value.length) {
		memcpy(header_field->value.buf, pair.value.buf, pair.value.length);
	}

	if(folding_length) {
		int i;
		char *pos = header_field->value.buf + pair.value.length;
		/* copy parsed folding lines */
		for(i=0; i<folded_lines->nelts; i++) {
			line = &APR_ARRAY_IDX(folded_lines,i,apt_str_t);

			memcpy(pos,line->buf,line->length);
			pos += line->length;
		}
	}
	header_field->value.buf[header_field->value.length] = '\0';

	return header_field;
}

/** Generate individual header field (name-value pair) */
APT_DECLARE(apt_bool_t) apt_header_field_generate(const apt_header_field_t *header_field, apt_text_stream_t *stream)
{
	return apt_text_name_value_insert(stream,&header_field->name,&header_field->value);
}

/** Parse header section */
APT_DECLARE(apt_bool_t) apt_header_section_parse(apt_header_section_t *header, apt_text_stream_t *stream, apr_pool_t *pool)
{
	apt_header_field_t *header_field;
	apt_bool_t result = FALSE;

	do {
		header_field = apt_header_field_parse(stream,pool);
		if(header_field) {
			if(apt_string_is_empty(&header_field->name) == FALSE) {
				/* normal header */
				apt_header_section_field_add(header,header_field);
			}
			else {
				/* empty header => exit */
				result = TRUE;
				break;
			}
		}
		else {
			/* malformed header => skip to the next one */
		}
	}
	while(apt_text_is_eos(stream) == FALSE);

	return result;
}

/** Generate header section */
APT_DECLARE(apt_bool_t) apt_header_section_generate(const apt_header_section_t *header, apt_text_stream_t *stream)
{
	apt_header_field_t *header_field;
	for(header_field = APR_RING_FIRST(&header->ring);
			header_field != APR_RING_SENTINEL(&header->ring, apt_header_field_t, link);
				header_field = APR_RING_NEXT(header_field, link)) {
		apt_header_field_generate(header_field,stream);
	}

	return apt_text_eol_insert(stream);
}

static apt_bool_t apt_message_body_read(apt_message_parser_t *parser, apt_text_stream_t *stream)
{
	apt_bool_t status = TRUE;
	apt_str_t *body = parser->context.body;
	if(body->buf) {
		/* stream length available to read */
		apr_size_t stream_length = stream->text.length - (stream->pos - stream->text.buf);
		/* required/remaining length to read */
		apr_size_t required_length = parser->content_length - body->length;
		if(required_length > stream_length) {
			required_length = stream_length;
			/* incomplete */
			status = FALSE;
		}
		memcpy(body->buf + body->length, stream->pos, required_length);
		body->length += required_length;
		stream->pos += required_length;
		if(parser->verbose == TRUE) {
			apr_size_t length = required_length;
			const char *masked_data = apt_log_data_mask(stream->pos,&length,parser->pool);
			apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Parsed Message Body [%"APR_SIZE_T_FMT" bytes]\n%.*s",
					required_length, length, masked_data);
		}
	}

	return status;
}

static apt_bool_t apt_message_body_write(apt_message_generator_t *generator, apt_text_stream_t *stream)
{
	apt_bool_t status = TRUE;
	apt_str_t *body = generator->context.body;
	if(body && body->length < generator->content_length) {
		/* stream length available to write */
		apr_size_t stream_length = stream->text.length - (stream->pos - stream->text.buf);
		/* required/remaining length to write */
		apr_size_t required_length = generator->content_length - body->length;
		if(required_length > stream_length) {
			required_length = stream_length;
			/* incomplete */
			status = FALSE;
		}

		memcpy(stream->pos, body->buf + body->length, required_length);

		if(generator->verbose == TRUE) {
			apr_size_t length = required_length;
			const char *masked_data = apt_log_data_mask(stream->pos,&length,generator->pool);
			apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Generated Message Body [%"APR_SIZE_T_FMT" bytes]\n%.*s",
					required_length, length, masked_data);
		}

		body->length += required_length;
		stream->pos += required_length;
	}

	return status;
}

/** Create message parser */
APT_DECLARE(apt_message_parser_t*) apt_message_parser_create(void *obj, const apt_message_parser_vtable_t *vtable, apr_pool_t *pool)
{
	apt_message_parser_t *parser = apr_palloc(pool,sizeof(apt_message_parser_t));
	parser->obj = obj;
	parser->vtable = vtable;
	parser->pool = pool;
	parser->context.message = NULL;
	parser->context.body = NULL;
	parser->context.header = NULL;
	parser->content_length = 0;
	parser->stage = APT_MESSAGE_STAGE_START_LINE;
	parser->skip_lf = FALSE;
	parser->verbose = FALSE;
	return parser;
}

static APR_INLINE void apt_crlf_segmentation_test(apt_message_parser_t *parser, apt_text_stream_t *stream)
{
	/* in the worst case message segmentation may occur between <CR> and <LF> */
	if(stream->pos == stream->end && *(stream->pos-1)== APT_TOKEN_CR) {
		/* if this is the case be prepared to skip <LF> with the next attempt */
		parser->skip_lf = TRUE;
	}
}

/** Parse message by raising corresponding event handlers */
APT_DECLARE(apt_message_status_e) apt_message_parser_run(apt_message_parser_t *parser, apt_text_stream_t *stream, void **message)
{
	const char *pos;
	apt_message_status_e status = APT_MESSAGE_STATUS_INCOMPLETE;
	if(parser->skip_lf == TRUE) {
		/* skip <LF> occurred as a result of message segmentation between <CR> and <LF> */
		apt_text_char_skip(stream,APT_TOKEN_LF);
		parser->skip_lf = FALSE;
	}
	if(message) {
		*message = NULL;
	}

	do {
		pos = stream->pos;
		if(parser->stage == APT_MESSAGE_STAGE_START_LINE) {
			if(parser->vtable->on_start(parser,&parser->context,stream,parser->pool) == FALSE) {
				if(apt_text_is_eos(stream) == FALSE) {
					status = APT_MESSAGE_STATUS_INVALID;
				}
				break;
			}

			apt_crlf_segmentation_test(parser,stream);

			parser->stage = APT_MESSAGE_STAGE_HEADER;
		}

		if(parser->stage == APT_MESSAGE_STAGE_HEADER) {
			/* read header section */
			apt_bool_t res = apt_header_section_parse(parser->context.header,stream,parser->pool);
			if(parser->verbose == TRUE) {
				apr_size_t length = stream->pos - pos;
				apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Parsed Message Header [%"APR_SIZE_T_FMT" bytes]\n%.*s",
						length, length, pos);
			}

			apt_crlf_segmentation_test(parser,stream);

			if(res == FALSE) {
				break;
			}

			if(parser->vtable->on_header_complete) {
				if(parser->vtable->on_header_complete(parser,&parser->context) == FALSE) {
					status = APT_MESSAGE_STATUS_INVALID;
					break;
				}
			}

			if(parser->context.body && parser->context.body->length) {
				apt_str_t *body = parser->context.body;
				parser->content_length = body->length;
				body->buf = apr_palloc(parser->pool,parser->content_length+1);
				body->buf[parser->content_length] = '\0';
				body->length = 0;
				parser->stage = APT_MESSAGE_STAGE_BODY;
			}
			else {
				status = APT_MESSAGE_STATUS_COMPLETE;
				if(message) {
					*message = parser->context.message;
				}
				parser->stage = APT_MESSAGE_STAGE_START_LINE;
				break;
			}
		}

		if(parser->stage == APT_MESSAGE_STAGE_BODY) {
			if(apt_message_body_read(parser,stream) == FALSE) {
				break;
			}

			if(parser->vtable->on_body_complete) {
				parser->vtable->on_body_complete(parser,&parser->context);
			}
			status = APT_MESSAGE_STATUS_COMPLETE;
			if(message) {
				*message = parser->context.message;
			}
			parser->stage = APT_MESSAGE_STAGE_START_LINE;
			break;
		}
	}
	while(apt_text_is_eos(stream) == FALSE);

	return status;
}

/** Get external object associated with parser */
APT_DECLARE(void*) apt_message_parser_object_get(apt_message_parser_t *parser)
{
	return parser->obj;
}

/** Set verbose mode for the parser */
APT_DECLARE(void) apt_message_parser_verbose_set(apt_message_parser_t *parser, apt_bool_t verbose)
{
	parser->verbose = verbose;
}

/** Create message generator */
APT_DECLARE(apt_message_generator_t*) apt_message_generator_create(void *obj, const apt_message_generator_vtable_t *vtable, apr_pool_t *pool)
{
	apt_message_generator_t *generator = apr_palloc(pool,sizeof(apt_message_generator_t));
	generator->obj = obj;
	generator->vtable = vtable;
	generator->pool = pool;
	generator->context.message = NULL;
	generator->context.header = NULL;
	generator->context.body = NULL;
	generator->content_length = 0;
	generator->stage = APT_MESSAGE_STAGE_START_LINE;
	generator->verbose = FALSE;
	return generator;
}

static apt_message_status_e apt_message_generator_break(apt_message_generator_t *generator, apt_text_stream_t *stream)
{
	/* failed to generate message */
	if(apt_text_is_eos(stream) == TRUE) {
		/* end of stream reached */
		return APT_MESSAGE_STATUS_INCOMPLETE;
	}

	/* error case */
	return APT_MESSAGE_STATUS_INVALID;
}

/** Generate message */
APT_DECLARE(apt_message_status_e) apt_message_generator_run(apt_message_generator_t *generator, void *message, apt_text_stream_t *stream)
{
	if(!message) {
		return APT_MESSAGE_STATUS_INVALID;
	}

	if(message != generator->context.message) {
		generator->stage = APT_MESSAGE_STAGE_START_LINE;
		generator->context.message = message;
		generator->context.header = NULL;
		generator->context.body = NULL;
	}

	if(generator->stage == APT_MESSAGE_STAGE_START_LINE) {
		/* generate start-line */
		if(generator->vtable->on_start(generator,&generator->context,stream) == FALSE) {
			return apt_message_generator_break(generator,stream);
		}

		if(!generator->context.header || !generator->context.body) {
			return APT_MESSAGE_STATUS_INVALID;
		}

		/* generate header */
		if(apt_header_section_generate(generator->context.header,stream) == FALSE) {
			return apt_message_generator_break(generator,stream);
		}

		if(generator->vtable->on_header_complete) {
			generator->vtable->on_header_complete(generator,&generator->context,stream);
		}
		if(generator->verbose == TRUE) {
			apr_size_t length = stream->pos - stream->text.buf;
			apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Generated Message Header [%"APR_SIZE_T_FMT" bytes]\n%.*s",
					length, length, stream->text.buf);
		}

		generator->stage = APT_MESSAGE_STAGE_START_LINE;
		generator->content_length = generator->context.body->length;
		if(generator->content_length) {
			generator->context.body->length = 0;
			generator->stage = APT_MESSAGE_STAGE_BODY;
		}
	}

	if(generator->stage == APT_MESSAGE_STAGE_BODY) {
		if(apt_message_body_write(generator,stream) == FALSE) {
			return apt_message_generator_break(generator,stream);
		}

		generator->stage = APT_MESSAGE_STAGE_START_LINE;
	}

	return APT_MESSAGE_STATUS_COMPLETE;
}

/** Get external object associated with generator */
APT_DECLARE(void*) apt_message_generator_object_get(apt_message_generator_t *generator)
{
	return generator->obj;
}

/** Set verbose mode for the parser */
APT_DECLARE(void) apt_message_generator_verbose_set(apt_message_generator_t *generator, apt_bool_t verbose)
{
	generator->verbose = verbose;
}


text:
/*---------------------- Syntax Highlighting -----------------------------*/
td.linenos { background-color: #f0f0f0; padding-right: 10px; }
span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }
body .hll { background-color: #ffffcc }
body .c { color: #408080; font-style: italic }  /* Comment */
body .err { border: 1px solid #FF0000 }         /* Error */
body .k { color: #954121 }                      /* Keyword */
body .o { color: #666666 }                      /* Operator */
body .cm { color: #408080; font-style: italic } /* Comment.Multiline */
body .cp { color: #BC7A00 }                     /* Comment.Preproc */
body .c1 { color: #408080; font-style: italic } /* Comment.Single */
body .cs { color: #408080; font-style: italic } /* Comment.Special */
body .gd { color: #A00000 }                     /* Generic.Deleted */
body .ge { font-style: italic }                 /* Generic.Emph */
body .gr { color: #FF0000 }                     /* Generic.Error */
body .gh { color: #000080; font-weight: bold }  /* Generic.Heading */
body .gi { color: #00A000 }                     /* Generic.Inserted */
body .go { color: #808080 }                     /* Generic.Output */
body .gp { color: #000080; font-weight: bold }  /* Generic.Prompt */
body .gs { font-weight: bold }                  /* Generic.Strong */
body .gu { color: #800080; font-weight: bold }  /* Generic.Subheading */
body .gt { color: #0040D0 }                     /* Generic.Traceback */
body .kc { color: #954121 }                     /* Keyword.Constant */
body .kd { color: #954121; font-weight: bold }  /* Keyword.Declaration */
body .kn { color: #954121; font-weight: bold }  /* Keyword.Namespace */
body .kp { color: #954121 }                     /* Keyword.Pseudo */
body .kr { color: #954121; font-weight: bold }  /* Keyword.Reserved */
body .kt { color: #B00040 }                     /* Keyword.Type */
body .m { color: #666666 }                      /* Literal.Number */
body .s { color: #219161 }                      /* Literal.String */
body .na { color: #7D9029 }                     /* Name.Attribute */
body .nb { color: #954121 }                     /* Name.Builtin */
body .nc { color: #0000FF; font-weight: bold }  /* Name.Class */
body .no { color: #880000 }                     /* Name.Constant */
body .nd { color: #AA22FF }                     /* Name.Decorator */
body .ni { color: #999999; font-weight: bold }  /* Name.Entity */
body .ne { color: #D2413A; font-weight: bold }  /* Name.Exception */
body .nf { color: #0000FF }                     /* Name.Function */
body .nl { color: #A0A000 }                     /* Name.Label */
body .nn { color: #0000FF; font-weight: bold }  /* Name.Namespace */
body .nt { color: #954121; font-weight: bold }  /* Name.Tag */
body .nv { color: #19469D }                     /* Name.Variable */
body .ow { color: #AA22FF; font-weight: bold }  /* Operator.Word */
body .w { color: #bbbbbb }                      /* Text.Whitespace */
body .mf { color: #666666 }                     /* Literal.Number.Float */
body .mh { color: #666666 }                     /* Literal.Number.Hex */
body .mi { color: #666666 }                     /* Literal.Number.Integer */
body .mo { color: #666666 }                     /* Literal.Number.Oct */
body .sb { color: #219161 }                     /* Literal.String.Backtick */
body .sc { color: #219161 }                     /* Literal.String.Char */
body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */
body .s2 { color: #219161 }                     /* Literal.String.Double */
body .se { color: #BB6622; font-weight: bold }  /* Literal.String.Escape */
body .sh { color: #219161 }                     /* Literal.String.Heredoc */
body .si { color: #BB6688; font-weight: bold }  /* Literal.String.Interpol */
body .sx { color: #954121 }                     /* Literal.String.Other */
body .sr { color: #BB6688 }                     /* Literal.String.Regex */
body .s1 { color: #219161 }                     /* Literal.String.Single */
body .ss { color: #19469D }                     /* Literal.String.Symbol */
body .bp { color: #954121 }                     /* Name.Builtin.Pseudo */
body .vc { color: #19469D }                     /* Name.Variable.Class */
body .vg { color: #19469D }                     /* Name.Variable.Global */
body .vi { color: #19469D }                     /* Name.Variable.Instance */
body .il { color: #666666 }                     /* Literal.Number.Integer.Long */


text:
package com.github.inspektr.audit.spi.support;

import org.aspectj.lang.JoinPoint;
import com.github.inspektr.common.spi.PrincipalResolver;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Resolves the principal name to the one provided by Spring Security.
 *
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 0.7.0
 *
 */
public final class SpringSecurityAuditablePrincipalResolver implements PrincipalResolver {

	public String resolveFrom(final JoinPoint auditableTarget, final Object retval) {
		return getFromSecurityContext();
	}

	public String resolveFrom(final JoinPoint auditableTarget, final Exception exception) {
		return getFromSecurityContext();
	}

    public String resolve() {
        return getFromSecurityContext();
    }

    private String getFromSecurityContext() {
		final SecurityContext securityContext = SecurityContextHolder.getContext();

		if (securityContext == null) {
			return null;
		}

		return securityContext.getAuthentication().getName();
	}

}


text:
package com.bingoogol.frogcare.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.bingoogol.frogcare.R;
import com.bingoogol.frogcare.db.dao.AddressDao;
import com.bingoogol.frogcare.util.Constants;
import com.bingoogol.frogcare.util.Logger;
import com.bingoogol.frogcare.util.SpUtil;

/**
 * 来电归属地显示服务
 *
 * @author bingoogol@sina.com
 *
 */
public class AttributionService extends Service {
	private static final String TAG = "AttributionService";
	private TelephonyManager mTelephonyManager;
	private AttributionPhoneListener mAttributionPhoneListener;
	private OutgoingCallReceiver mOutgoingCallReceiver;
	private WindowManager mWindowManager;
	/**
	 * 全局的显示在界面上的归属地组件
	 */
	private View mView;
	private LayoutParams mLayoutParams;

	@Override
	public void onCreate() {
		super.onCreate();
		mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		// 采用代码的方式注册广播接收者
		mOutgoingCallReceiver = new OutgoingCallReceiver();
		registerReceiver(mOutgoingCallReceiver, new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL));
		// 注册一个监听器监听电话的状态
		mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		mAttributionPhoneListener = new AttributionPhoneListener();
		mTelephonyManager.listen(mAttributionPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mTelephonyManager.listen(mAttributionPhoneListener, PhoneStateListener.LISTEN_NONE);
		mAttributionPhoneListener = null;
		unregisterReceiver(mOutgoingCallReceiver);
		mOutgoingCallReceiver = null;
	}

	/**
	 * 外拨电话广播接收者,在开启归属地显示服务时注册该广播接收者,关闭归属地显示服务时取消注册该广播接收者
	 *
	 * @author bingoogol@sina.com
	 *
	 */
	private class OutgoingCallReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Logger.i(TAG, "监听到外拨电话");
			showAddress(AddressDao.getAddress(getApplicationContext(), getResultData()));
		}
	}

	/**
	 * 归属地电话监听器
	 *
	 * @author bingoogol@sina.com
	 *
	 */
	private class AttributionPhoneListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				// 电话到来,显示归属地组件
				showAddress(AddressDao.getAddress(getApplicationContext(), incomingNumber));
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				// 空闲状态 电话挂断,移除归属地组件
				if (mView != null) {
					mWindowManager.removeView(mView);
					mView = null;
				}
				break;
			}
		}
	}

	private void showAddress(String address) {
		mView = View.inflate(this, R.layout.view_attribution, null);
		mView.setOnTouchListener(new View.OnTouchListener() {
			int startX = 0;
			int startY = 0;

			@SuppressWarnings("deprecation")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();
					break;
				case MotionEvent.ACTION_MOVE:
					int newX = (int) event.getRawX();
					int newY = (int) event.getRawY();
					int dx = newX - startX;
					int dy = newY - startY;
					mLayoutParams.x += dx;
					mLayoutParams.y += dy;
					if (mLayoutParams.x < 0) {
						mLayoutParams.x = 0;
					}
					if (mLayoutParams.y < 0) {
						mLayoutParams.y = 0;
					}
					if (mLayoutParams.x > mWindowManager.getDefaultDisplay().getWidth()) {
						mLayoutParams.x = mWindowManager.getDefaultDisplay().getWidth();
					}
					if (mLayoutParams.y > mWindowManager.getDefaultDisplay().getHeight()) {
						mLayoutParams.y = mWindowManager.getDefaultDisplay().getHeight();
					}
					mWindowManager.updateViewLayout(mView, mLayoutParams);
					startX = newX;
					startY = newY;
					break;
				case MotionEvent.ACTION_UP:
					SpUtil.putInt(Constants.spkey.ATTRIBUTION_LAST_X, mLayoutParams.x);
					SpUtil.putInt(Constants.spkey.ATTRIBUTION_LAST_Y, mLayoutParams.y);
					break;
				}
				return true;
			}
		});

		TextView tv_attribution = (TextView) mView.findViewById(R.id.tv_attribution);
		tv_attribution.setText(address);
		mLayoutParams = new LayoutParams();
		mLayoutParams.gravity = Gravity.LEFT + Gravity.TOP;
		mLayoutParams.x = SpUtil.getInt(Constants.spkey.ATTRIBUTION_LAST_X, 300);
		mLayoutParams.y = SpUtil.getInt(Constants.spkey.ATTRIBUTION_LAST_Y, 300);
		mLayoutParams.height = LayoutParams.WRAP_CONTENT;
		mLayoutParams.width = LayoutParams.WRAP_CONTENT;
		mLayoutParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_KEEP_SCREEN_ON;
		mLayoutParams.format = PixelFormat.TRANSLUCENT;
		mLayoutParams.type = LayoutParams.TYPE_PRIORITY_PHONE;
		mWindowManager.addView(mView, mLayoutParams);
	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var snapshot_version_1 = require("../core/snapshot_version");
var timestamp_1 = require("../core/timestamp");
var document_1 = require("../model/document");
var document_key_1 = require("../model/document_key");
var mutation_batch_1 = require("../model/mutation_batch");
var assert_1 = require("../util/assert");
var indexeddb_schema_1 = require("./indexeddb_schema");
var query_data_1 = require("./query_data");
/** Serializer for values stored in the LocalStore. */
var LocalSerializer = /** @class */ (function () {
    function LocalSerializer(remoteSerializer) {
        this.remoteSerializer = remoteSerializer;
    }
    /** Decodes a remote document from storage locally to a Document. */
    LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {
        if (remoteDoc.document) {
            return this.remoteSerializer.fromDocument(remoteDoc.document);
        }
        else if (remoteDoc.noDocument) {
            var key = document_key_1.DocumentKey.fromSegments(remoteDoc.noDocument.path);
            var readTime = remoteDoc.noDocument.readTime;
            var timestamp = new timestamp_1.Timestamp(readTime.seconds, readTime.nanos);
            return new document_1.NoDocument(key, snapshot_version_1.SnapshotVersion.fromTimestamp(timestamp));
        }
        else {
            return assert_1.fail('Unexpected DbRemoteDocument');
        }
    };
    /** Encodes a document for storage locally. */
    LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {
        if (maybeDoc instanceof document_1.Document) {
            var doc = this.remoteSerializer.toDocument(maybeDoc);
            return new indexeddb_schema_1.DbRemoteDocument(null, doc);
        }
        else {
            var path = maybeDoc.key.path.toArray();
            var timestamp = maybeDoc.version.toTimestamp();
            var readTime = new indexeddb_schema_1.DbTimestamp(timestamp.seconds, timestamp.nanos);
            return new indexeddb_schema_1.DbRemoteDocument(new indexeddb_schema_1.DbNoDocument(path, readTime), null);
        }
    };
    /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
    LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {
        var _this = this;
        var serializedMutations = batch.mutations.map(function (m) {
            return _this.remoteSerializer.toMutation(m);
        });
        return new indexeddb_schema_1.DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);
    };
    /** Decodes a DbMutationBatch into a MutationBatch */
    LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {
        var _this = this;
        var mutations = dbBatch.mutations.map(function (m) {
            return _this.remoteSerializer.fromMutation(m);
        });
        var timestamp = timestamp_1.Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);
        return new mutation_batch_1.MutationBatch(dbBatch.batchId, timestamp, mutations);
    };
    /** Decodes a DbTarget into QueryData */
    LocalSerializer.prototype.fromDbTarget = function (dbTarget) {
        var readTime = new timestamp_1.Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);
        var version = snapshot_version_1.SnapshotVersion.fromTimestamp(readTime);
        var query;
        if (isDocumentQuery(dbTarget.query)) {
            query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);
        }
        else {
            query = this.remoteSerializer.fromQueryTarget(dbTarget.query);
        }
        return new query_data_1.QueryData(query, dbTarget.targetId, query_data_1.QueryPurpose.Listen, version, dbTarget.resumeToken);
    };
    /** Encodes QueryData into a DbTarget for storage locally. */
    LocalSerializer.prototype.toDbTarget = function (queryData) {
        assert_1.assert(query_data_1.QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +
            query_data_1.QueryPurpose.Listen +
            ' may be stored, got ' +
            queryData.purpose);
        var timestamp = queryData.snapshotVersion.toTimestamp();
        var dbTimestamp = new indexeddb_schema_1.DbTimestamp(timestamp.seconds, timestamp.nanos);
        var queryProto;
        if (queryData.query.isDocumentQuery()) {
            queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);
        }
        else {
            queryProto = this.remoteSerializer.toQueryTarget(queryData.query);
        }
        assert_1.assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');
        var resumeToken = queryData.resumeToken;
        // lastListenSequenceNumber is always 0 until we do real GC.
        return new indexeddb_schema_1.DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);
    };
    return LocalSerializer;
}());
exports.LocalSerializer = LocalSerializer;
/**
 * A helper function for figuring out what kind of query has been stored.
 */
function isDocumentQuery(dbQuery) {
    return dbQuery.documents !== undefined;
}

//# sourceMappingURL=local_serializer.js.map


text:
set -e # Abort on first error

mkdir -p tmp

# Convert proto files into intermediate JSON
`npm bin`/pbjs proto/POGOProtos.proto > tmp/POGOProtos.json

# Create definition file from intermediate JSON
`npm bin`/npp2ts -f tmp/POGOProtos.json > pogo-protos.d.ts

# Format definition file
`npm bin`/tsfmt -r pogo-protos.d.ts


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-commons" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-commons" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-http" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-http" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-logic" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-logic" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-platform" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/simplify-platform" charset="UTF-8" />
  </component>
</project>


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

import java.io.IOException;
import java.util.Date;

import db.*;
import ghidra.util.UniversalID;
import ghidra.util.exception.VersionException;

/**
 * Version 2 implementation for accessing the Typedef database table.
 */
class TypedefDBAdapterV2 extends TypedefDBAdapter {
	static final int VERSION = 2;
	static final int V2_TYPEDEF_DT_ID_COL = 0;
	static final int V2_TYPEDEF_FLAGS_COL = 1;
	static final int V2_TYPEDEF_NAME_COL = 2;
	static final int V2_TYPEDEF_CAT_COL = 3;
	static final int V2_TYPEDEF_SOURCE_ARCHIVE_ID_COL = 4;
	static final int V2_TYPEDEF_UNIVERSAL_DT_ID_COL = 5;
	static final int V2_TYPEDEF_SOURCE_SYNC_TIME_COL = 6;
	static final int V2_TYPEDEF_LAST_CHANGE_TIME_COL = 7;
	static final Schema V2_SCHEMA = new Schema(VERSION, "Typedef ID",
		new Field[] { LongField.INSTANCE, ShortField.INSTANCE, StringField.INSTANCE,
			LongField.INSTANCE, LongField.INSTANCE, LongField.INSTANCE, LongField.INSTANCE,
			LongField.INSTANCE },
		new String[] { "Data Type ID", "Flags", "Name", "Category ID", "Source Archive ID",
			"Universal Data Type ID", "Source Sync Time", "Last Change Time" });
	private Table table;

	/**
	 * Gets a version 1 adapter for the Typedef database table.
	 * @param handle handle to the database containing the table.
	 * @param create true if this constructor should create the table.
	 * @throws VersionException if the the table's version does not match the expected version
	 * for this adapter.
	 * @throws IOException if IO error occurs
	 */
	public TypedefDBAdapterV2(DBHandle handle, boolean create)
			throws VersionException, IOException {

		if (create) {
			table = handle.createTable(TYPEDEF_TABLE_NAME, V2_SCHEMA,
				new int[] { V2_TYPEDEF_CAT_COL, V2_TYPEDEF_UNIVERSAL_DT_ID_COL });
		}
		else {
			table = handle.getTable(TYPEDEF_TABLE_NAME);
			if (table == null) {
				throw new VersionException("Missing Table: " + TYPEDEF_TABLE_NAME);
			}
			int version = table.getSchema().getVersion();
			if (version != VERSION) {
				String msg = "Expected version " + VERSION + " for table " + TYPEDEF_TABLE_NAME +
					" but got " + table.getSchema().getVersion();
				if (version < VERSION) {
					throw new VersionException(msg, VersionException.OLDER_VERSION, true);
				}
				throw new VersionException(msg, VersionException.NEWER_VERSION, false);
			}
		}
	}

	@Override
	void deleteTable(DBHandle handle) throws IOException {
		handle.deleteTable(TYPEDEF_TABLE_NAME);
	}

	@Override
	public DBRecord createRecord(long dataTypeID, String name, short flags, long categoryID,
			long sourceArchiveID, long sourceDataTypeID, long lastChangeTime) throws IOException {

		long tableKey = table.getKey();
//		if (tableKey <= DataManager.VOID_DATATYPE_ID) {
//			tableKey = DataManager.VOID_DATATYPE_ID +1;
//		}
		long key = DataTypeManagerDB.createKey(DataTypeManagerDB.TYPEDEF, tableKey);

		DBRecord record = V2_SCHEMA.createRecord(key);
		record.setLongValue(V2_TYPEDEF_DT_ID_COL, dataTypeID);
		record.setShortValue(V2_TYPEDEF_FLAGS_COL, flags);
		record.setString(V2_TYPEDEF_NAME_COL, name);
		record.setLongValue(V2_TYPEDEF_CAT_COL, categoryID);
		record.setLongValue(V2_TYPEDEF_SOURCE_ARCHIVE_ID_COL, sourceArchiveID);
		record.setLongValue(V2_TYPEDEF_UNIVERSAL_DT_ID_COL, sourceDataTypeID);
		record.setLongValue(V2_TYPEDEF_SOURCE_SYNC_TIME_COL, lastChangeTime);
		record.setLongValue(V2_TYPEDEF_LAST_CHANGE_TIME_COL, lastChangeTime);
		table.putRecord(record);
		return record;
	}

	@Override
	public DBRecord getRecord(long typedefID) throws IOException {
		return table.getRecord(typedefID);
	}

	@Override
	public RecordIterator getRecords() throws IOException {
		return table.iterator();
	}

	@Override
	public void updateRecord(DBRecord record, boolean setLastChangeTime) throws IOException {
		if (setLastChangeTime) {
			record.setLongValue(TypedefDBAdapter.TYPEDEF_LAST_CHANGE_TIME_COL,
				(new Date()).getTime());
		}
		table.putRecord(record);
	}

	@Override
	public boolean removeRecord(long dataID) throws IOException {
		return table.deleteRecord(dataID);
	}

	@Override
	public Field[] getRecordIdsInCategory(long categoryID) throws IOException {
		return table.findRecords(new LongField(categoryID), V2_TYPEDEF_CAT_COL);
	}

	@Override
	Field[] getRecordIdsForSourceArchive(long archiveID) throws IOException {
		return table.findRecords(new LongField(archiveID), V2_TYPEDEF_SOURCE_ARCHIVE_ID_COL);
	}

	@Override
	DBRecord getRecordWithIDs(UniversalID sourceID, UniversalID datatypeID) throws IOException {
		Field[] keys =
			table.findRecords(new LongField(datatypeID.getValue()), V2_TYPEDEF_UNIVERSAL_DT_ID_COL);

		for (int i = 0; i < keys.length; i++) {
			DBRecord record = table.getRecord(keys[i]);
			if (record.getLongValue(V2_TYPEDEF_SOURCE_ARCHIVE_ID_COL) == sourceID.getValue()) {
				return record;
			}
		}
		return null;
	}

}


text:
extern crate gl;
extern crate libc;
#[macro_use]
extern crate log;
extern crate num;

pub mod gl_context;
pub mod framebuffer;
pub mod shader;
pub mod texture;
pub mod vertex_buffer;


text:
package com.facebook.buck.core.rules.actions;

/** An interface for which rule analysis can register their {@link ActionAnalysisData} */
public interface ActionAnalysisDataRegistry {
  void registerAction(ActionAnalysisData actionAnalysisData);
}