text:
package com.opensymphony.xwork2.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.XWorkConstants;
import com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.security.AcceptedPatternsChecker;
import com.opensymphony.xwork2.security.ExcludedPatternsChecker;
import com.opensymphony.xwork2.util.*;
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * This interceptor sets all parameters on the value stack.
 */
public class ParametersInterceptor extends MethodFilterInterceptor {

    private static final Logger LOG = LogManager.getLogger(ParametersInterceptor.class);

    protected static final int PARAM_NAME_MAX_LENGTH = 100;

    private int paramNameMaxLength = PARAM_NAME_MAX_LENGTH;
    private boolean devMode = false;

    protected boolean ordered = false;

    private ValueStackFactory valueStackFactory;
    private ExcludedPatternsChecker excludedPatterns;
    private AcceptedPatternsChecker acceptedPatterns;

    @Inject
    public void setValueStackFactory(ValueStackFactory valueStackFactory) {
        this.valueStackFactory = valueStackFactory;
    }

    @Inject(XWorkConstants.DEV_MODE)
    public void setDevMode(String mode) {
        this.devMode = BooleanUtils.toBoolean(mode);
    }

    @Inject
    public void setExcludedPatterns(ExcludedPatternsChecker excludedPatterns) {
        this.excludedPatterns = excludedPatterns;
    }

    @Inject
    public void setAcceptedPatterns(AcceptedPatternsChecker acceptedPatterns) {
        this.acceptedPatterns = acceptedPatterns;
    }

    /**
     * If the param name exceeds the configured maximum length it will not be
     * accepted.
     *
     * @param paramNameMaxLength Maximum length of param names
     */
    public void setParamNameMaxLength(int paramNameMaxLength) {
        this.paramNameMaxLength = paramNameMaxLength;
    }

    static private int countOGNLCharacters(String s) {
        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c == '.' || c == '[') count++;
        }
        return count;
    }

    /**
     * Compares based on number of '.' and '[' characters (fewer is higher)
     */
    static final Comparator<String> rbCollator = new Comparator<String>() {
        public int compare(String s1, String s2) {
            int l1 = countOGNLCharacters(s1),
                l2 = countOGNLCharacters(s2);
            return l1 < l2 ? -1 : (l2 < l1 ? 1 : s1.compareTo(s2));
        }

    };

    @Override
    public String doIntercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();
        if (!(action instanceof NoParameters)) {
            ActionContext ac = invocation.getInvocationContext();
            final Map<String, Object> parameters = retrieveParameters(ac);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting params {}", getParameterLogMap(parameters));
            }

            if (parameters != null) {
                Map<String, Object> contextMap = ac.getContextMap();
                try {
                    ReflectionContextState.setCreatingNullObjects(contextMap, true);
                    ReflectionContextState.setDenyMethodExecution(contextMap, true);
                    ReflectionContextState.setReportingConversionErrors(contextMap, true);

                    ValueStack stack = ac.getValueStack();
                    setParameters(action, stack, parameters);
                } finally {
                    ReflectionContextState.setCreatingNullObjects(contextMap, false);
                    ReflectionContextState.setDenyMethodExecution(contextMap, false);
                    ReflectionContextState.setReportingConversionErrors(contextMap, false);
                }
            }
        }
        return invocation.invoke();
    }

    /**
     * Gets the parameter map to apply from wherever appropriate
     *
     * @param ac The action context
     * @return The parameter map to apply
     */
    protected Map<String, Object> retrieveParameters(ActionContext ac) {
        return ac.getParameters();
    }

    /**
     * Adds the parameters into context's ParameterMap
     *
     * @param ac        The action context
     * @param newParams The parameter map to apply
     *

     *                  In this class this is a no-op, since the parameters were fetched from the same location.
     *                  In subclasses both retrieveParameters() and addParametersToContext() should be overridden.
     *

     */
    protected void addParametersToContext(ActionContext ac, Map<String, Object> newParams) {
    }

    protected void setParameters(final Object action, ValueStack stack, final Map<String, Object> parameters) {
        Map<String, Object> params;
        Map<String, Object> acceptableParameters;
        if (ordered) {
            params = new TreeMap<>(getOrderedComparator());
            acceptableParameters = new TreeMap<>(getOrderedComparator());
            params.putAll(parameters);
        } else {
            params = new TreeMap<>(parameters);
            acceptableParameters = new TreeMap<>();
        }

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (isAcceptableParameter(name, action)) {
                acceptableParameters.put(name, entry.getValue());
            }
        }

        ValueStack newStack = valueStackFactory.createValueStack(stack);
        boolean clearableStack = newStack instanceof ClearableValueStack;
        if (clearableStack) {
            //if the stack's context can be cleared, do that to prevent OGNL
            //from having access to objects in the stack, see XW-641
            ((ClearableValueStack)newStack).clearContextValues();
            Map<String, Object> context = newStack.getContext();
            ReflectionContextState.setCreatingNullObjects(context, true);
            ReflectionContextState.setDenyMethodExecution(context, true);
            ReflectionContextState.setReportingConversionErrors(context, true);

            //keep locale from original context
            context.put(ActionContext.LOCALE, stack.getContext().get(ActionContext.LOCALE));
        }

        boolean memberAccessStack = newStack instanceof MemberAccessValueStack;
        if (memberAccessStack) {
            //block or allow access to properties
            //see WW-2761 for more details
            MemberAccessValueStack accessValueStack = (MemberAccessValueStack) newStack;
            accessValueStack.setAcceptProperties(acceptedPatterns.getAcceptedPatterns());
            accessValueStack.setExcludeProperties(excludedPatterns.getExcludedPatterns());
        }

        for (Map.Entry<String, Object> entry : acceptableParameters.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();
            try {
                newStack.setParameter(name, value);
            } catch (RuntimeException e) {
                if (devMode) {
                    notifyDeveloperParameterException(action, name, e.getMessage());
                }
            }
        }

        if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null))
            stack.getContext().put(ActionContext.CONVERSION_ERRORS, newStack.getContext().get(ActionContext.CONVERSION_ERRORS));

        addParametersToContext(ActionContext.getContext(), acceptableParameters);
    }

    protected void notifyDeveloperParameterException(Object action, String property, String message) {
        String developerNotification = LocalizedTextUtil.findText(ParametersInterceptor.class, "devmode.notification",
                ActionContext.getContext().getLocale(), "Developer Notification:\n{0}",
                new Object[]{
                        "Unexpected Exception caught setting '" + property + "' on '" + action.getClass() + ": " + message
                }
        );
        LOG.error(developerNotification);
        // see https://issues.apache.org/jira/browse/WW-4066
        if (action instanceof ValidationAware) {
            Collection<String> messages = ((ValidationAware) action).getActionMessages();
            messages.add(message);
            ((ValidationAware) action).setActionMessages(messages);
        }
    }

    /**
     * Checks if name of parameter can be accepted or thrown away
     *
     * @param name parameter name
     * @param action current action
     * @return true if parameter is accepted
     */
    protected boolean isAcceptableParameter(String name, Object action) {
        ParameterNameAware parameterNameAware = (action instanceof ParameterNameAware) ? (ParameterNameAware) action : null;
        return acceptableName(name) && (parameterNameAware == null || parameterNameAware.acceptableParameterName(name));
    }

    /**
     * Gets an instance of the comparator to use for the ordered sorting.  Override this
     * method to customize the ordering of the parameters as they are set to the
     * action.
     *
     * @return A comparator to sort the parameters
     */
    protected Comparator<String> getOrderedComparator() {
        return rbCollator;
    }

    protected String getParameterLogMap(Map<String, Object> parameters) {
        if (parameters == null) {
            return "NONE";
        }

        StringBuilder logEntry = new StringBuilder();
        for (Map.Entry entry : parameters.entrySet()) {
            logEntry.append(String.valueOf(entry.getKey()));
            logEntry.append(" => ");
            if (entry.getValue() instanceof Object[]) {
                Object[] valueArray = (Object[]) entry.getValue();
                logEntry.append("[ ");
                if (valueArray.length > 0 ) {
                    for (int indexA = 0; indexA < (valueArray.length - 1); indexA++) {
                        Object valueAtIndex = valueArray[indexA];
                        logEntry.append(String.valueOf(valueAtIndex));
                        logEntry.append(", ");
                    }
                    logEntry.append(String.valueOf(valueArray[valueArray.length - 1]));
                }
                logEntry.append(" ] ");
            } else {
                logEntry.append(String.valueOf(entry.getValue()));
            }
        }

        return logEntry.toString();
    }

    protected boolean acceptableName(String name) {
        boolean accepted = isWithinLengthLimit(name) && !isExcluded(name) && isAccepted(name);
        if (devMode && accepted) { // notify only when in devMode
            LOG.debug("Parameter [{}] was accepted and will be appended to action!", name);
        }
        return accepted;
    }

	protected boolean isWithinLengthLimit( String name ) {
        boolean matchLength = name.length() <= paramNameMaxLength;
        if (!matchLength) {
            notifyDeveloper("Parameter [{}] is too long, allowed length is [{}]", name, String.valueOf(paramNameMaxLength));
        }
        return matchLength;
	}

    protected boolean isAccepted(String paramName) {
        AcceptedPatternsChecker.IsAccepted result = acceptedPatterns.isAccepted(paramName);
        if (result.isAccepted()) {
            return true;
        }
        notifyDeveloper("Parameter [{}] didn't match accepted pattern [{}]!", paramName, result.getAcceptedPattern());
        return false;
    }

    protected boolean isExcluded(String paramName) {
        ExcludedPatternsChecker.IsExcluded result = excludedPatterns.isExcluded(paramName);
        if (result.isExcluded()) {
            notifyDeveloper("Parameter [{}] matches excluded pattern [{}]!", paramName, result.getExcludedPattern());
            return true;
        }
        return false;
    }

    private void notifyDeveloper(String message, String... parameters) {
        if (devMode) {
            LOG.warn(message, parameters);
        } else {
            LOG.debug(message, parameters);
        }
    }

    /**
     * Whether to order the parameters or not
     *
     * @return True to order
     */
    public boolean isOrdered() {
        return ordered;
    }

    /**
     * Set whether to order the parameters by object depth or not
     *
     * @param ordered True to order them
     */
    public void setOrdered(boolean ordered) {
        this.ordered = ordered;
    }

    /**
     * Sets a comma-delimited list of regular expressions to match
     * parameters that are allowed in the parameter map (aka whitelist).
     *

     * Don't change the default unless you know what you are doing in terms
     * of security implications.
     *

     *
     * @param commaDelim A comma-delimited list of regular expressions
     */
    public void setAcceptParamNames(String commaDelim) {
        acceptedPatterns.setAcceptedPatterns(commaDelim);
    }

    /**
     * Sets a comma-delimited list of regular expressions to match
     * parameters that should be removed from the parameter map.
     *
     * @param commaDelim A comma-delimited list of regular expressions
     */
    public void setExcludeParams(String commaDelim) {
        excludedPatterns.setExcludedPatterns(commaDelim);
    }

}


text:
class Container {
public :
	int size; // maximum number of actors. 0=unlimited
	TCODList<Actor *> inventory;

	Container(int size);
	~Container();
	bool add(Actor *actor);
	void remove(Actor *actor);
};

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var async_1 = require('../scheduler/async');
var isDate_1 = require('../util/isDate');
var Subscriber_1 = require('../Subscriber');
var TimeoutError_1 = require('../util/TimeoutError');
/**
 *
 * Errors if Observable does not emit a value in given time span.
 *
 * Timeouts on Observable that doesn't emit values fast enough.
 *
 *
 *
 * `timeout` operator accepts as an argument either a number or a Date.
 *
 * If number was provided, it returns an Observable that behaves like a source
 * Observable, unless there is a period of time where there is no value emitted.
 * So if you provide `100` as argument and first value comes after 50ms from
 * the moment of subscription, this value will be simply re-emitted by the resulting
 * Observable. If however after that 100ms passes without a second value being emitted,
 * stream will end with an error and source Observable will be unsubscribed.
 * These checks are performed throughout whole lifecycle of Observable - from the moment
 * it was subscribed to, until it completes or errors itself. Thus every value must be
 * emitted within specified period since previous value.
 *
 * If provided argument was Date, returned Observable behaves differently. It throws
 * if Observable did not complete before provided Date. This means that periods between
 * emission of particular values do not matter in this case. If Observable did not complete
 * before provided Date, source Observable will be unsubscribed. Other than that, resulting
 * stream behaves just as source Observable.
 *
 * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
 * when returned Observable will check if source stream emitted value or completed.
 *
 * @example
Check if ticks are emitted within certain timespan

 * const seconds = Rx.Observable.interval(1000);
 *
 * seconds.timeout(1100) // Let's use bigger timespan to be safe,
 *                       // since `interval` might fire a bit later then scheduled.
 * .subscribe(
 *     value => console.log(value), // Will emit numbers just as regular `interval` would.
 *     err => console.log(err) // Will never be called.
 * );
 *
 * seconds.timeout(900).subscribe(
 *     value => console.log(value), // Will never be called.
 *     err => console.log(err) // Will emit error before even first value is emitted,
 *                             // since it did not arrive within 900ms period.
 * );
 *
 * @example
Use Date to check if Observable completed

 * const seconds = Rx.Observable.interval(1000);
 *
 * seconds.timeout(new Date("December 17, 2020 03:24:00"))
 * .subscribe(
 *     value => console.log(value), // Will emit values as regular `interval` would
 *                                  // until December 17, 2020 at 03:24:00.
 *     err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
 *                             // since Observable did not complete by then.
 * );
 *
 * @see {@link timeoutWith}
 *
 * @param {number|Date} due Number specifying period within which Observable must emit values
 *                          or Date specifying before when Observable should complete
 * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
 * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
 * @method timeout
 * @owner Observable
 */
function timeout(due, scheduler) {
    if (scheduler === void 0) { scheduler = async_1.async; }
    var absoluteTimeout = isDate_1.isDate(due);
    var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
    return this.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError()));
}
exports.timeout = timeout;
var TimeoutOperator = (function () {
    function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
        this.waitFor = waitFor;
        this.absoluteTimeout = absoluteTimeout;
        this.scheduler = scheduler;
        this.errorInstance = errorInstance;
    }
    TimeoutOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
    };
    return TimeoutOperator;
}());
/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
var TimeoutSubscriber = (function (_super) {
    __extends(TimeoutSubscriber, _super);
    function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
        _super.call(this, destination);
        this.absoluteTimeout = absoluteTimeout;
        this.waitFor = waitFor;
        this.scheduler = scheduler;
        this.errorInstance = errorInstance;
        this.action = null;
        this.scheduleTimeout();
    }
    TimeoutSubscriber.dispatchTimeout = function (subscriber) {
        subscriber.error(subscriber.errorInstance);
    };
    TimeoutSubscriber.prototype.scheduleTimeout = function () {
        var action = this.action;
        if (action) {
            // Recycle the action if we've already scheduled one. All the production
            // Scheduler Actions mutate their state/delay time and return themeselves.
            // VirtualActions are immutable, so they create and return a clone. In this
            // case, we need to set the action reference to the most recent VirtualAction,
            // to ensure that's the one we clone from next time.
            this.action = action.schedule(this, this.waitFor);
        }
        else {
            this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
        }
    };
    TimeoutSubscriber.prototype._next = function (value) {
        if (!this.absoluteTimeout) {
            this.scheduleTimeout();
        }
        _super.prototype._next.call(this, value);
    };
    TimeoutSubscriber.prototype._unsubscribe = function () {
        this.action = null;
        this.scheduler = null;
        this.errorInstance = null;
    };
    return TimeoutSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=timeout.js.map


text:
{-# LANGUAGE EmptyDataDecls #-}
module Network.Transport.TCP.Mock.Socket
  ( -- * Types
    HostName
  , ServiceName
  , Socket
  , SocketType(..)
  , SocketOption(..)
  , AddrInfo(..)
  , Family
  , SockAddr
  , ProtocolNumber
  , ShutdownCmd(..)
    -- * Functions
  , getAddrInfo
  , socket
  , bindSocket
  , listen
  , setSocketOption
  , accept
  , sClose
  , connect
  , shutdown
    -- * Constants
  , defaultHints
  , defaultProtocol
  , sOMAXCONN
    -- * Debugging API
  , scheduleReadAction
    -- * Internal API
  , writeSocket
  , readSocket
  , Message(..)
  ) where

import Data.Word (Word8)
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Exception (throwIO)
import Control.Category ((>>>))
import Control.Concurrent.MVar
import Control.Concurrent.Chan
import System.IO.Unsafe (unsafePerformIO)
import Data.Accessor (Accessor, accessor, (^=), (^.), (^:))
import qualified Data.Accessor.Container as DAC (mapMaybe)
import System.Timeout (timeout)

--------------------------------------------------------------------------------
-- Mock state                                                                 --
--------------------------------------------------------------------------------

data MockState = MockState {
    _boundSockets   :: !(Map SockAddr Socket)
  , _nextSocketId   :: !Int
  , _validHostnames ::  [HostName]
  }

initialMockState :: MockState
initialMockState = MockState {
    _boundSockets   = Map.empty
  , _nextSocketId   = 0
  , _validHostnames = ["localhost", "127.0.0.1"]
  }

mockState :: MVar MockState
{-# NOINLINE mockState #-}
mockState = unsafePerformIO $ newMVar initialMockState

get :: Accessor MockState a -> IO a
get acc = timeoutThrow mvarThreshold $ withMVar mockState $ return . (^. acc)

set :: Accessor MockState a -> a -> IO ()
set acc val = timeoutThrow mvarThreshold $ modifyMVar_ mockState $ return . (acc ^= val)

boundSockets :: Accessor MockState (Map SockAddr Socket)
boundSockets = accessor _boundSockets (\bs st -> st { _boundSockets = bs })

boundSocketAt :: SockAddr -> Accessor MockState (Maybe Socket)
boundSocketAt addr = boundSockets >>> DAC.mapMaybe addr

nextSocketId :: Accessor MockState Int
nextSocketId = accessor _nextSocketId (\sid st -> st { _nextSocketId = sid })

validHostnames :: Accessor MockState [HostName]
validHostnames = accessor _validHostnames (\ns st -> st { _validHostnames = ns })

--------------------------------------------------------------------------------
-- The public API (mirroring Network.Socket)                                  --
--------------------------------------------------------------------------------

type HostName    = String
type ServiceName = String
type PortNumber  = String
type HostAddress = String

data SocketType   = Stream
data SocketOption = ReuseAddr
data ShutdownCmd  = ShutdownSend

data Family
data ProtocolNumber

data Socket = Socket {
    socketState       :: MVar SocketState
  , socketDescription :: String
  }

data SocketState =
    Uninit
  | BoundSocket {
        socketBacklog :: Chan (Socket, SockAddr, MVar Socket)
      }
  | Connected {
         socketBuff :: Chan Message
      , _socketPeer :: Maybe Socket
      , _scheduledReadActions :: [(Int, IO ())]
      }
  | Closed

data Message =
    Payload Word8
  | CloseSocket

data AddrInfo = AddrInfo {
    addrFamily  :: Family
  , addrAddress :: SockAddr
  }

data SockAddr = SockAddrInet PortNumber HostAddress
  deriving (Eq, Ord, Show)

instance Show AddrInfo where
  show = show . addrAddress

instance Show Socket where
  show sock = "<<socket " ++ socketDescription sock ++ ">>"

socketPeer :: Accessor SocketState (Maybe Socket)
socketPeer = accessor _socketPeer (\peer st -> st { _socketPeer = peer })

scheduledReadActions :: Accessor SocketState [(Int, IO ())]
scheduledReadActions = accessor _scheduledReadActions (\acts st -> st { _scheduledReadActions = acts })

getAddrInfo :: Maybe AddrInfo -> Maybe HostName -> Maybe ServiceName -> IO [AddrInfo]
getAddrInfo _ (Just host) (Just port) = do
  validHosts <- get validHostnames
  if host `elem` validHosts
    then return . return $ AddrInfo {
             addrFamily  = error "Family unused"
           , addrAddress = SockAddrInet port host
           }
    else throwSocketError $ "getAddrInfo: invalid hostname '" ++ host ++ "'"
getAddrInfo _ _ _ = error "getAddrInfo: unsupported arguments"

defaultHints :: AddrInfo
defaultHints = error "defaultHints not implemented"

socket :: Family -> SocketType -> ProtocolNumber -> IO Socket
socket _ Stream _ = do
  state <- newMVar Uninit
  sid   <- get nextSocketId
  set nextSocketId (sid + 1)
  return Socket {
      socketState       = state
    , socketDescription = show sid
    }

bindSocket :: Socket -> SockAddr -> IO ()
bindSocket sock addr = do
  timeoutThrow mvarThreshold $ modifyMVar_ (socketState sock) $ \st -> case st of
    Uninit -> do
      backlog <- newChan
      return BoundSocket {
          socketBacklog = backlog
        }
    _ ->
      throwSocketError "bind: socket already initialized"
  set (boundSocketAt addr) (Just sock)

listen :: Socket -> Int -> IO ()
listen _ _ = return ()

defaultProtocol :: ProtocolNumber
defaultProtocol = error "defaultProtocol not implemented"

setSocketOption :: Socket -> SocketOption -> Int -> IO ()
setSocketOption _ ReuseAddr 1 = return ()
setSocketOption _ _ _ = error "setSocketOption: unsupported arguments"

accept :: Socket -> IO (Socket, SockAddr)
accept serverSock = do
  backlog <- timeoutThrow mvarThreshold $ withMVar (socketState serverSock) $ \st -> case st of
    BoundSocket {} ->
      return (socketBacklog st)
    _ ->
      throwSocketError "accept: socket not bound"
  (theirSocket, theirAddress, reply) <- readChan backlog
  ourBuff  <- newChan
  ourState <- newMVar Connected {
       socketBuff = ourBuff
    , _socketPeer = Just theirSocket
    , _scheduledReadActions = []
    }
  let ourSocket = Socket {
      socketState       = ourState
    , socketDescription = ""
    }
  timeoutThrow mvarThreshold $ putMVar reply ourSocket
  return (ourSocket, theirAddress)

sClose :: Socket -> IO ()
sClose sock = do
  -- Close the peer socket
  writeSocket sock CloseSocket

  -- Close our socket
  timeoutThrow mvarThreshold $ modifyMVar_ (socketState sock) $ \st ->
    case st of
      Connected {} -> do
        -- In case there is a parallel read stuck on a readChan
        writeChan (socketBuff st) CloseSocket
        return Closed
      _ ->
        return Closed

connect :: Socket -> SockAddr -> IO ()
connect us serverAddr = do
  mServer <- get (boundSocketAt serverAddr)
  case mServer of
    Just server -> do
      serverBacklog <- timeoutThrow mvarThreshold $ withMVar (socketState server) $ \st -> case st of
        BoundSocket {} ->
          return (socketBacklog st)
        _ ->
          throwSocketError "connect: server socket not bound"
      reply <- newEmptyMVar
      writeChan serverBacklog (us, SockAddrInet "" "", reply)
      them <- timeoutThrow mvarThreshold $ readMVar reply
      timeoutThrow mvarThreshold $ modifyMVar_ (socketState us) $ \st -> case st of
        Uninit -> do
          buff <- newChan
          return Connected {
               socketBuff = buff
            , _socketPeer = Just them
            , _scheduledReadActions = []
            }
        _ ->
          throwSocketError "connect: already connected"
    Nothing -> throwSocketError "connect: unknown address"

sOMAXCONN :: Int
sOMAXCONN = error "sOMAXCONN not implemented"

shutdown :: Socket -> ShutdownCmd -> IO ()
shutdown sock ShutdownSend = do
  writeSocket sock CloseSocket
  timeoutThrow mvarThreshold $ modifyMVar_ (socketState sock) $ \st -> case st of
    Connected {} ->
      return (socketPeer ^= Nothing $ st)
    _ ->
      return st

--------------------------------------------------------------------------------
-- Functions with no direct public counterpart                                --
--------------------------------------------------------------------------------

peerBuffer :: Socket -> IO (Either String (Chan Message))
peerBuffer sock = do
  mPeer <- timeoutThrow mvarThreshold $ withMVar (socketState sock) $ \st -> case st of
    Connected {} ->
      return (st ^. socketPeer)
    _ ->
      return Nothing
  case mPeer of
    Just peer -> timeoutThrow mvarThreshold $ withMVar (socketState peer) $ \st -> case st of
      Connected {} ->
        return (Right (socketBuff st))
      _ ->
        return (Left "Peer socket closed")
    Nothing ->
      return (Left "Socket closed")

throwSocketError :: String -> IO a
throwSocketError = throwIO . userError

writeSocket :: Socket -> Message -> IO ()
writeSocket sock msg = do
  theirBuff <- peerBuffer sock
  case theirBuff of
    Right buff -> writeChan buff msg
    Left err   -> case msg of Payload _   -> throwSocketError $ "writeSocket: " ++ err
                              CloseSocket -> return ()

readSocket :: Socket -> IO (Maybe Word8)
readSocket sock = do
  mBuff <- timeoutThrow mvarThreshold $ modifyMVar (socketState sock) $ \st -> case st of
    Connected {} -> do
      let (later, now) = tick $ st ^. scheduledReadActions
      return ( scheduledReadActions ^= later $ st
             , Just (socketBuff st, now)
             )
    _ ->
      return (st, Nothing)
  case mBuff of
    Just (buff, actions) -> do
      sequence actions
      msg <- timeoutThrow readSocketThreshold $ readChan buff
      case msg of
        Payload w -> return (Just w)
        CloseSocket -> timeoutThrow mvarThreshold $ modifyMVar (socketState sock) $ \st -> case st of
          Connected {} ->
            return (Closed, Nothing)
          _ ->
            throwSocketError "readSocket: socket in unexpected state"
    Nothing ->
      return Nothing

-- | Given a list of scheduled actions, reduce all delays by 1, and return the
-- actions that should be executed now.
tick :: [(Int, IO ())] -> ([(Int, IO ())], [IO ()])
tick = go [] []
  where
    go later now [] = (reverse later, reverse now)
    go later now ((n, action) : actions)
      | n == 0    = go later (action : now) actions
      | otherwise = go ((n - 1, action) : later) now actions

--------------------------------------------------------------------------------
-- Debugging API                                                              --
--------------------------------------------------------------------------------

-- | Schedule an action to be executed after /n/ reads on this socket
--
-- If /n/ is zero we execute the action immediately.
scheduleReadAction :: Socket -> Int -> IO () -> IO ()
scheduleReadAction _    0 action = action
scheduleReadAction sock n action =
  modifyMVar_ (socketState sock) $ \st -> case st of
    Connected {} ->
      return (scheduledReadActions ^: ((n, action) :) $ st)
    _ ->
      throwSocketError "scheduleReadAction: socket not connected"

--------------------------------------------------------------------------------
-- Util                                                                       --
--------------------------------------------------------------------------------

mvarThreshold :: Int
mvarThreshold = 1000000

readSocketThreshold :: Int
readSocketThreshold = 10000000

timeoutThrow :: Int -> IO a -> IO a
timeoutThrow n p = do
  ma <- timeout n p
  case ma of
    Just a  -> return a
    Nothing -> throwIO (userError "timeout")


text:
package net.saga.aeroconf.app.data.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.net.Uri;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import net.saga.aeroconf.app.R;
import net.saga.aeroconf.app.data.provider.contract.ConfContract;
import net.saga.aeroconf.app.data.provider.operations.Operation;
import net.saga.aeroconf.app.data.vo.Presentation;
import net.saga.aeroconf.app.data.vo.Room;
import net.saga.aeroconf.app.data.vo.Schedule;
import net.saga.aeroconf.app.data.vo.Speaker;
import net.saga.aeroconf.app.util.GsonUtils;

import org.jboss.aerogear.android.Callback;
import org.jboss.aerogear.android.DataManager;
import org.jboss.aerogear.android.impl.datamanager.SQLStore;
import org.jboss.aerogear.android.impl.datamanager.StoreConfig;
import org.jboss.aerogear.android.impl.datamanager.StoreTypes;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public abstract class AbstractAeroConfProvider extends ContentProvider implements ConfContract {

    public static final String AUTHORITY = "org.jboss.aeroconf";

    private static final DataManager MANAGER = new DataManager();
    private static final String TAG = "ContentProvider";

    static final UriMatcher MATCHER = new UriMatcher(0);

    static {
        MATCHER.addURI(AUTHORITY, "Room", RoomContract.ROOM);
        MATCHER.addURI(AUTHORITY, "Room/#", RoomContract.ROOM_ID);

        MATCHER.addURI(AUTHORITY, "Speaker", SpeakerContract.SPEAKER);
        MATCHER.addURI(AUTHORITY, "Speaker/#", SpeakerContract.SPEAKER_ID);

        MATCHER.addURI(AUTHORITY, "Presentation", PresentationContract.PRESENTATION);
        MATCHER.addURI(AUTHORITY, "Presentation/#", PresentationContract.PRESENTATION_ID);

        MATCHER.addURI(AUTHORITY, "Schedule", ScheduleContract.SCHEDULE);
        MATCHER.addURI(AUTHORITY, "Schedule/#", ScheduleContract.SCHEDULE_ID);
    }

    private final CountDownLatch storeLatch = new CountDownLatch(4);
    SQLStore<Room> roomStore;
    SQLStore<Speaker> speakerStore;
    SQLStore<Presentation> presentationStore;
    SQLStore<Schedule> scheduleStore;

    private void loadSchedulesFromFile() {
        InputStream schedule = getContext().getResources().openRawResource(R.raw.schedule);
        JsonReader reader = new JsonReader(new InputStreamReader(schedule));
        JsonElement root = new JsonParser().parse(reader);
        JsonArray array = root.getAsJsonArray();

        JsonElement element;
        Gson gson = GsonUtils.GSON;

        for (int i = 0; i < array.size(); i++) {
            element = array.get(i);
            Schedule scheduleItem = gson.fromJson(element, Schedule.class);
            scheduleStore.save(scheduleItem);
        }
    }

    private void loadPresentationsFromFile() {
        InputStream presentations = getContext().getResources().openRawResource(R.raw.presentations);
        JsonReader reader = new JsonReader(new InputStreamReader(presentations));
        JsonElement root = new JsonParser().parse(reader);
        JsonArray array = root.getAsJsonObject().get("presentations").getAsJsonArray();

        JsonElement element;
        Gson gson = GsonUtils.GSON;

        for (int i = 0; i < array.size(); i++) {
            element = array.get(i);
            Presentation presentation = gson.fromJson(element, Presentation.class);
            presentationStore.save(presentation);
        }

    }

    private void loadSpeakersFromFile() {
        InputStream rooms = getContext().getResources().openRawResource(R.raw.speakers);
        JsonReader reader = new JsonReader(new InputStreamReader(rooms));
        JsonElement root = new JsonParser().parse(reader);
        JsonArray array = root.getAsJsonObject().get("speakerList").getAsJsonObject().get("speaker").getAsJsonArray();

        JsonElement element;
        Gson gson = GsonUtils.GSON;

        for (int i = 0; i < array.size(); i++) {
            element = array.get(i);
            Speaker speaker = gson.fromJson(element, Speaker.class);
            speakerStore.save(speaker);
        }

    }

    private void loadRoomsFromFile() {
        InputStream rooms = getContext().getResources().openRawResource(R.raw.rooms);
        JsonReader reader = new JsonReader(new InputStreamReader(rooms));
        JsonElement root = new JsonParser().parse(reader);
        JsonArray array = root.getAsJsonObject().get("roomList").getAsJsonObject().get("room").getAsJsonArray();

        JsonElement element;
        Gson gson = GsonUtils.GSON;

        for (int i = 0; i < array.size(); i++) {
            element = array.get(i);
            Room room = gson.fromJson(element, Room.class);
            roomStore.save(room);
        }

    }

    <T> SQLStore<T> registerAndOpenStore(Class<T> storeClass) {

        StoreConfig config = new StoreConfig(storeClass);
        config.setContext(getContext().getApplicationContext());
        config.setType(StoreTypes.SQL);

        SQLStore<T> store = (SQLStore<T>) MANAGER.store(config.getName(), config);

        store.open(new Callback<SQLStore<T>>() {
            @Override
            public void onSuccess(SQLStore<T> tsqlStore) {
                storeLatch.countDown();
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("StoreOpen", e.getMessage(), e);
                storeLatch.countDown();
            }
        });

        return store;

    }

    /**
     * Called before all operations to ensure that the datastores are set up.
     */
    private void confirm() {
        try {
            storeLatch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (roomStore.isEmpty()) {
            loadRoomsFromFile();
        }

        if (speakerStore.isEmpty()) {
            loadSpeakersFromFile();
        }

        if (presentationStore.isEmpty()) {
            loadPresentationsFromFile();
        }

        if (scheduleStore.isEmpty()) {
            loadSchedulesFromFile();
        }
    }

    <T> T execute(final Uri uri, final ContentValues[] values, final String selection, final String[] selectionArgs, final Operation<T> op) {
        final AtomicReference<T> returnRef = new AtomicReference<T>();

        confirm();

        SQLStore tempStore;

        int match = MATCHER.match(uri);
        switch (match) {
            case PresentationContract.PRESENTATION:
            case PresentationContract.PRESENTATION_ID:
                tempStore = presentationStore;
                break;
            case SpeakerContract.SPEAKER:
            case SpeakerContract.SPEAKER_ID:
                tempStore = speakerStore;
                break;
            case RoomContract.ROOM:
            case RoomContract.ROOM_ID:
                tempStore = roomStore;
                break;
            case ScheduleContract.SCHEDULE:
            case ScheduleContract.SCHEDULE_ID:
                tempStore = scheduleStore;
                break;
            default:
                throw new IllegalArgumentException(String.format("%s not supported", uri.toString()));
        }

        final SQLStore store = tempStore;

        synchronized (TAG) {
            returnRef.set(op.exec(store, uri, values, selection, selectionArgs));
        }
        return returnRef.get();
    }

}


text:
layout: single
title: "Even more Random links: psql"
date: '2009-03-23T19:48:00.000+09:00'

tags:
- HowTo
modified_time: '2016-06-07T19:34:20.081+09:00'
blogger_id: tag:blogger.com,1999:blog-2701259639305045003.single-3154618650637477470
blogger_orig_url: https://DFIR.Science/2009/03/even-more-random-links-psql.html
---

PSQL on Mac
http://www.entropy.ch/software/macosx/singlegresql/

Enable psql remote access over tcp/ip
http://www.cyberciti.biz/tips/singlegres-allow-remote-access-tcp-connection.html

*Also in pg_hda.conf make sure to keep an entry  'local all all trust' to allow location connections as well.


text:
title: JOINT PHD CALL WITH UNIVERSITY OF BOLZANO, ITALY
layout: default
topic: Food Engineering and Biotechnology
number_of_positions: 1
phdschool: Food Engineering and Biotechnology
website: https://www.unibz.it/en/faculties/sciencetechnology/phd-in-food-engineering-and-biotechnology
closing_date: 8th July, 2019
tag: call_uni
subtag: call_unibolzanobiotechnology
---


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Feestdagen per regio
	Feestdagen verbergen
</labels>


text:
@interface XGWMainTabBarController ()

@property(nonatomic,strong)UIButton *tianjia;
@end

@implementation XGWMainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    //当图片的选中颜色和文字的选中颜色一样的时候可以这样设置
    self.tabBar.tintColor = [UIColor orangeColor];
    [self addController];

}
///添加控制器的方法
-(void)addController
{
    //添加主页控制器
    XGWHomeControll *home = [[XGWHomeControll alloc]init];
    [self setControllerWithControll:home text:@"首页"imageName:@"tabbar_home"];
    //消息控制器
    XGWMessageController *home2 = [[XGWMessageController alloc]init];
    [self setControllerWithControll:home2 text:@"消息"imageName:@"tabbar_message_center"];
    //占位控制器
    UITableViewController *cont = [[UITableViewController alloc]init];
    [self setControllerWithControll:cont text:nil imageName:@"d"];
    //发现控制器
    XGWDiscoverController *discover = [[XGWDiscoverController alloc]init];
    [self setControllerWithControll:discover text:@"发现" imageName:@"tabbar_discover"];
    //我 控制器
    XGWPersonallyController *home3 = [[XGWPersonallyController alloc]init];
    [self setControllerWithControll:home3 text:@"我"imageName:@"tabbar_profile"];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
      //在View已经加载完成的时候添加一个按钮遮挡住中间的控制器按钮
      [self.tabBar addSubview:self.tianjia];
}
//创建控制器
-(void)setControllerWithControll:(UITableViewController *)cont text:(NSString *)text imageName:(NSString *)imageName{

    UINavigationController *vc = [[UINavigationController alloc]initWithRootViewController:cont];
    cont.title = text;
    cont.tabBarItem.image = [UIImage imageNamed:imageName];
    [self addChildViewController:vc];
}
//创建中间按钮
-(UIButton *)tianjia{
    if (_tianjia == nil)
    {
        _tianjia = [[UIButton alloc]init];
        [_tianjia setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [_tianjia setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [_tianjia addTarget:self action:@selector(clickTianJia) forControlEvents:UIControlEventTouchUpInside];
        [_tianjia setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        [_tianjia setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        CGRect rect = [UIScreen mainScreen].bounds;
        CGFloat buttonW = rect.size.width / 5;
        _tianjia.frame = CGRectMake(2 * buttonW,0, buttonW,self.tabBar.frame.size.height);
    }
    return _tianjia;
}
//中间添加按钮的响应方法
-(void)clickTianJia
{

}
@end


text:
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.*;

/**
 * Canvas es una clase para realizar dibujos gráficos de una forma simple sobre el
 * Canvas, el lienzo
 * @autor: Bruce Quig
 * @autor: Michael Kolling (mik)
 */

public class Canvas
{
    // La implementación de esta clase (el manejo de la identidad de la figura y colores)
    // es un poco más complejo de lo necesario. Se ha hecho así con el propósito de mantener
    // la interfaz y los atributos de instancia de los objetos figura claros y simples para
    // propósitos educacionales

    private static Canvas canvasSingleton;

    /**
     * Factory method to get the canvas singleton object.
     */
    public static Canvas getCanvas()
    {
        if  (canvasSingleton == null)
		{
            canvasSingleton = new Canvas("BlueJ Figuras Demo", 300, 300,
                                         Color.white);
        }
        canvasSingleton.setVisible(true);
        return canvasSingleton;
    }

    //  ----- parte de atributos de instancia -----

    private JFrame marco;
    private CanvasPane canvas;
    private Graphics2D grafico;
    private Color fondoColor;
    private Image canvasImagen;
    private List<Object> objetos;
    private HashMap<Object, DescripcionFigura> figuras;

    /**
     * Crea el Canvas
     * @param titulo título que aparece en el marco del canvas
     * @param ancho el ancho deseado para el canvas
     * @param alto el alto deseado para el canvas
     * @param bgColor el color de fondo deseado para el canvas
     */
    private Canvas(String titulo, int ancho, int alto, Color bgColor)
    {
        marco = new JFrame();
        canvas = new CanvasPane();
        marco.setContentPane(canvas);
        marco.setTitle(titulo);
        canvas.setPreferredSize(new Dimension(ancho, alto));
        fondoColor = bgColor;
        marco.pack();
        objetos = new ArrayList<Object>();
        figuras = new HashMap<Object, DescripcionFigura>();
    }

    /**
     * Establece la visibilidad del canvas y trae el canvas al frente de la pantalla
     * cuando se hace visible. Este método puede ser utilizado también para traer delante
     * de otras ventanas a un canvas ya visible.
     * @param visible  valor booleano que representa la visibilidad deseada del canvas true
     * o false
     */
    public void setVisible(boolean visible)
    {
        if (grafico == null)
		{
            // primera vez: instanciar la imagen fuera de la ventana
            // y rellenarla con el color de fondo
            Dimension tamano = canvas.getSize();
            canvasImagen = canvas.createImage(tamano.width, tamano.height);
            grafico = (Graphics2D)canvasImagen.getGraphics();
            grafico.setColor(fondoColor);
            grafico.fillRect(0, 0, tamano.width, tamano.height);
            grafico.setColor(Color.black);
        }
        marco.setVisible(visible);
    }

    /**
     * Dibuja una determinada figura en el canvas
     * @param  referenciaObjeto un objeto para definir la identidad de la figura
     * @param  color            el color de la figura
     * @param  figura         el objeto figura a ser dibujado en el canvas
     */

     // Esta es una manera un poco "atrasada" de mantener los objetos figura.
     // Se ha hecho así para mantener los interfaces de figura claros y simples
     // para propósitos educacionales

     public void dibujar(Object referenciaObjeto, String color, Shape figura)
    {
        objetos.remove(referenciaObjeto);   // solo en caso de que ya esté
        objetos.add(referenciaObjeto);      // añadir al final
        figuras.put(referenciaObjeto, new DescripcionFigura(figura, color));
        redibujar();
    }

    /**
     * Borra una determinada figura de la pantalla
     * @param  referenciaObjeto  el objeto figura a ser borrado
     */
    public void borrar(Object referenciaObjeto)
    {
        objetos.remove(referenciaObjeto);   // just in case it was already there
        figuras.remove(referenciaObjeto);
        redibujar();
    }

    /**
     * Establecer el color de fondo del Canvas
     * @param  nuevoColor el nuevo color para el fondo del canvas
     */
    public void setFondoColor(String colorString)
    {
        if  (colorString.equals("red"))
            grafico.setColor(Color.red);
        else if ( colorString.equals("black"))
            grafico.setColor(Color.black);
        else if (colorString.equals("blue"))
            grafico.setColor(Color.blue);
        else if  (colorString.equals("yellow"))
            grafico.setColor(Color.yellow);
        else if  (colorString.equals("green"))
            grafico.setColor(Color.green);
        else if (colorString.equals("magenta"))
            grafico.setColor(Color.magenta);
        else if (colorString.equals("white"))
            grafico.setColor(Color.white);
        else
            grafico.setColor(Color.black);
    }

    /**
     *Esperar un núemro determinado de milisegundos antes de acabar.
     *Esto proporciona una manera de especificar un pequeño retraso
     *que puede ser utilizado para producir animaciones
     * @param  milisegundos  tiempo de espera
     */

    public void esperar(int milisegundos)
    {
        try
        {
            Thread.sleep(milisegundos);
        }
        catch (Exception e)
        {
            // ignorar la excepción en este momento
        }
    }

    /**
     * Redibujar todas las figuras que están actualmente en el canvas
     */
    private void redibujar()
    {
        borrar();
        for (Object figura : objetos)
        {
            figuras.get(figura).dibujar(grafico);
        }

        canvas.repaint();
    }

    /**
     * Borrar todo el canvas
     */
    private void borrar()
    {
        Color original = grafico.getColor();
        grafico.setColor(fondoColor);
        Dimension tamano = canvas.getSize();
        grafico.fill(new Rectangle(0, 0, tamano.width, tamano.height));
        grafico.setColor(original);
    }

    /************************************************************************
     * Clase interna, anidada, Canvaspane - El actual componente canvas
     * contenido en el marco Canvas. Es esencialmente un JPanel con capacidad
     * añadida para refrescar la imagen dibujada en el
     */

    private class CanvasPane extends JPanel
    {
        public void paint(Graphics g)
        {
            g.drawImage(canvasImagen, 0, 0, null);
        }
    }

    /************************************************************************
     * Clase anidada DescripcionFigura -
     */

    private class DescripcionFigura
    {
        private Shape figura;
        private String colorString;

        public DescripcionFigura(Shape figura, String color)
        {
            this.figura = figura;
            colorString = color;
        }

        public void dibujar(Graphics2D grafico)
        {
            setFondoColor(colorString);
            grafico.fill(figura);
        }
    }

}


text:
from django import forms
from rango.models import Category, Page, User, UserProfile

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text='Please enter a category name')
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        model = Category

class PageForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text='Please enter the title of the page.')
    url = forms.URLField(max_length=200, help_text='Please enter the URL of the page.')
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    def clean(self):
        cleaned_data = self.cleaned_data
        url = cleaned_data.get('url')

        if url and not url.startswith('http://'):
            url = 'http://' + url
            cleaned_data['url'] = url

        return cleaned_data

    class Meta:
        model = Page
        fields = ('title', 'url', 'views')

class UserForm(forms.ModelForm):
    username = forms.CharField(help_text="Please enter a username.")
    email = forms.CharField(help_text="Please enter your email.")
    password = forms.CharField(widget=forms.PasswordInput(), help_text="Please enter a password.")

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class UserProfileForm(forms.ModelForm):
    website = forms.URLField(help_text="Please enter your website.", required=False)
    picture = forms.ImageField(help_text="Select a profile image to upload.", required=False)

    class Meta:
        model = UserProfile
        fields = ('website', 'picture')


text:
#ifndef __WATCHDOG_H__
#define __WATCHDOG_H__

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef __cplusplus
extern "C"
{
#endif

//*****************************************************************************
//
// Prototypes for the APIs.
//
//*****************************************************************************
extern tBoolean WatchdogRunning(unsigned long ulBase);
extern void WatchdogEnable(unsigned long ulBase);
extern void WatchdogLock(unsigned long ulBase);
extern void WatchdogUnlock(unsigned long ulBase);
extern tBoolean WatchdogLockState(unsigned long ulBase);
extern void WatchdogReloadSet(unsigned long ulBase, unsigned long ulLoadVal);
extern unsigned long WatchdogReloadGet(unsigned long ulBase);
extern unsigned long WatchdogValueGet(unsigned long ulBase);
extern void WatchdogIntRegister(unsigned long ulBase, void(*pfnHandler)(void));
extern void WatchdogIntUnregister(unsigned long ulBase);
extern unsigned long WatchdogIntStatus(unsigned long ulBase, tBoolean bMasked);
extern void WatchdogIntClear(unsigned long ulBase);
extern void WatchdogStallEnable(unsigned long ulBase);
extern void WatchdogStallDisable(unsigned long ulBase);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif // __WATCHDOG_H__


text:
            Previous

            {{page.pageNumber}}

            Next


text:
from exchange import Exchange
from ..api.btce import BTCEClient

class BTCEExchange(Exchange):

    def __init__(self, settings):
        super(BTCEExchange, self).__init__(settings)
        self._trading = BTCEClient(settings['BTCE'])

    '''
        How much can you buy a coin for, fee included for the exchange
    '''
    def _buy_price(self):
        prices = self._trading.get_prices()
        fees = self._trading.get_fees()
        base_sell = prices['ticker']['buy']
        fee = float(fees['trade'])
        return base_sell + ((fee / 100) * base_sell)

    '''
        How much can you get if you sell a coin, fee subtracted
    '''
    def _sell_price(self):
        prices = self._trading.get_prices()
        fees = self._trading.get_fees()
        base_sell = prices['ticker']['sell']
        fee = float(fees['trade'])
        return base_sell - ((fee / 100) * base_sell)


text:
  Amance est
       un village
       localisé dans le département de Haute-Saône en Franche-Comté. Elle totalisait 697 habitants en 2008.

Si vous pensez demenager à Amance, vous pourrez facilement trouver une maison à acheter.

Le nombre d'habitations, à Amance, se décomposait en 2011 en 51 appartements et 320 maisons soit
 un marché relativement équilibré.

À coté de Amance sont situées les communes de
Saint-Remy située à 4 km, 692 habitants,
Contréglise à 3 km, 101 habitants,
Cubry-lès-Faverney à 5 km, 97 habitants,
Buffignécourt localisée à 3 km, 118 habitants,
Baulay située à 4 km, 317 habitants,
Menoux à 3 km, 268 habitants,
 entre autres. De plus, Amance est située à seulement 21 km de Vesoul.

À Amance, la valorisation moyenne à l'achat d'un appartement s'évalue à 980 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 894 € du m². À la location la valorisation moyenne se situe à 0 € du m² mensuel.

La ville compte quelques  aménagements, elle dispose, entre autres, de un terrain de sport.


text:
# $Id: filetransfer.py,v 1.6 2004/12/25 20:06:59 snakeru Exp $

"""
This module contains IBB class that is the simple implementation of JEP-0047.
Note that this is just a transport for data. You have to negotiate data transfer before
(via StreamInitiation most probably). Unfortunately SI is not implemented yet.
"""

from protocol import *
from dispatcher import PlugIn
import base64

class IBB(PlugIn):
    """ IBB used to transfer small-sized data chunk over estabilished xmpp connection.
        Data is split into small blocks (by default 3000 bytes each), encoded as base 64
        and sent to another entity that compiles these blocks back into the data chunk.
        This is very inefficiend but should work under any circumstances. Note that
        using IBB normally should be the last resort.
    """
    def __init__(self):
        """ Initialise internal variables. """
        PlugIn.__init__(self)
        self.DBG_LINE='ibb'
        self._exported_methods=[self.OpenStream]
        self._streams={}
        self._ampnode=Node(NS_AMP+' amp',payload=[Node('rule',{'condition':'deliver-at','value':'stored','action':'error'}),Node('rule',{'condition':'match-resource','value':'exact','action':'error'})])

    def plugin(self,owner):
        """ Register handlers for receiving incoming datastreams. Used internally. """
        self._owner.RegisterHandlerOnce('iq',self.StreamOpenReplyHandler) # Move to StreamOpen and specify stanza id
        self._owner.RegisterHandler('iq',self.IqHandler,ns=NS_IBB)
        self._owner.RegisterHandler('message',self.ReceiveHandler,ns=NS_IBB)

    def IqHandler(self,conn,stanza):
        """ Handles streams state change. Used internally. """
        typ=stanza.getType()
        self.DEBUG('IqHandler called typ->%s'%typ,'info')
        if typ=='set' and stanza.getTag('open',namespace=NS_IBB): self.StreamOpenHandler(conn,stanza)
        elif typ=='set' and stanza.getTag('close',namespace=NS_IBB): self.StreamCloseHandler(conn,stanza)
        elif typ=='result': self.StreamCommitHandler(conn,stanza)
        elif typ=='error': self.StreamOpenReplyHandler(conn,stanza)
        else: conn.send(Error(stanza,ERR_BAD_REQUEST))
        raise NodeProcessed

    def StreamOpenHandler(self,conn,stanza):
        """ Handles opening of new incoming stream. Used internally. """
        """
<iq type='set'
    from='romeo@montague.net/orchard'
    to='juliet@capulet.com/balcony'
    id='inband_1'>
  <open sid='mySID'
        block-size='4096'
        xmlns='http://jabber.org/protocol/ibb'/>
</iq>
"""
        err=None
        sid,blocksize=stanza.getTagAttr('open','sid'),stanza.getTagAttr('open','block-size')
        self.DEBUG('StreamOpenHandler called sid->%s blocksize->%s'%(sid,blocksize),'info')
        try: blocksize=int(blocksize)
        except: err=ERR_BAD_REQUEST
        if not sid or not blocksize: err=ERR_BAD_REQUEST
        elif sid in self._streams.keys(): err=ERR_UNEXPECTED_REQUEST
        if err: rep=Error(stanza,err)
        else:
            self.DEBUG("Opening stream: id %s, block-size %s"%(sid,blocksize),'info')
            rep=Protocol('iq',stanza.getFrom(),'result',stanza.getTo(),{'id':stanza.getID()})
            self._streams[sid]={'direction':'<'+str(stanza.getFrom()),'block-size':blocksize,'fp':open('/tmp/xmpp_file_'+sid,'w'),'seq':0,'syn_id':stanza.getID()}
        conn.send(rep)

    def OpenStream(self,sid,to,fp,blocksize=3000):
        """ Start new stream. You should provide stream id 'sid', the endpoind jid 'to',
            the file object containing info for send 'fp'. Also the desired blocksize can be specified.
            Take into account that recommended stanza size is 4k and IBB uses base64 encoding
            that increases size of data by 1/3."""
        if sid in self._streams.keys(): return
        if not JID(to).getResource(): return
        self._streams[sid]={'direction':'|>'+to,'block-size':blocksize,'fp':fp,'seq':0}
        self._owner.RegisterCycleHandler(self.SendHandler)
        syn=Protocol('iq',to,'set',payload=[Node(NS_IBB+' open',{'sid':sid,'block-size':blocksize})])
        self._owner.send(syn)
        self._streams[sid]['syn_id']=syn.getID()
        return self._streams[sid]

    def SendHandler(self,conn):
        """ Send next portion of data if it is time to do it. Used internally. """
        self.DEBUG('SendHandler called','info')
        for sid in self._streams.keys():
            stream=self._streams[sid]
            if stream['direction'][:2]=='|>': cont=1
            elif stream['direction'][0]=='>':
                chunk=stream['fp'].read(stream['block-size'])
                if chunk:
                    datanode=Node(NS_IBB+' data',{'sid':sid,'seq':stream['seq']},base64.encodestring(chunk))
                    stream['seq']+=1
                    if stream['seq']==65536: stream['seq']=0
                    conn.send(Protocol('message',stream['direction'][1:],payload=[datanode,self._ampnode]))
                else:
                    """ notify the other side about stream closing
                        notify the local user about sucessfull send
                        delete the local stream"""
                    conn.send(Protocol('iq',stream['direction'][1:],'set',payload=[Node(NS_IBB+' close',{'sid':sid})]))
                    conn.Event(self.DBG_LINE,'SUCCESSFULL SEND',stream)
                    del self._streams[sid]
                    self._owner.UnregisterCycleHandler(self.SendHandler)

                    """
<message from='romeo@montague.net/orchard' to='juliet@capulet.com/balcony' id='msg1'>
  <data xmlns='http://jabber.org/protocol/ibb' sid='mySID' seq='0'>
    qANQR1DBwU4DX7jmYZnncmUQB/9KuKBddzQH+tZ1ZywKK0yHKnq57kWq+RFtQdCJ
    WpdWpR0uQsuJe7+vh3NWn59/gTc5MDlX8dS9p0ovStmNcyLhxVgmqS8ZKhsblVeu
    IpQ0JgavABqibJolc3BKrVtVV1igKiX/N7Pi8RtY1K18toaMDhdEfhBRzO/XB0+P
    AQhYlRjNacGcslkhXqNjK5Va4tuOAPy2n1Q8UUrHbUd0g+xJ9Bm0G0LZXyvCWyKH
    kuNEHFQiLuCY6Iv0myq6iX6tjuHehZlFSh80b5BVV9tNLwNR5Eqz1klxMhoghJOA
  </data>
  <amp xmlns='http://jabber.org/protocol/amp'>
    <rule condition='deliver-at' value='stored' action='error'/>
    <rule condition='match-resource' value='exact' action='error'/>
  </amp>
</message>
"""

    def ReceiveHandler(self,conn,stanza):
        """ Receive next portion of incoming datastream and store it write
            it to temporary file. Used internally.
        """
        sid,seq,data=stanza.getTagAttr('data','sid'),stanza.getTagAttr('data','seq'),stanza.getTagData('data')
        self.DEBUG('ReceiveHandler called sid->%s seq->%s'%(sid,seq),'info')
        try: seq=int(seq); data=base64.decodestring(data)
        except: seq=''; data=''
        err=None
        if not sid in self._streams.keys(): err=ERR_ITEM_NOT_FOUND
        else:
            stream=self._streams[sid]
            if not data: err=ERR_BAD_REQUEST
            elif seq<>stream['seq']: err=ERR_UNEXPECTED_REQUEST
            else:
                self.DEBUG('Successfull receive sid->%s %s+%s bytes'%(sid,stream['fp'].tell(),len(data)),'ok')
                stream['seq']+=1
                stream['fp'].write(data)
        if err:
            self.DEBUG('Error on receive: %s'%err,'error')
            conn.send(Error(Iq(to=stanza.getFrom(),frm=stanza.getTo(),payload=[Node(NS_IBB+' close')]),err,reply=0))

    def StreamCloseHandler(self,conn,stanza):
        """ Handle stream closure due to all data transmitted.
            Raise xmpppy event specifying successfull data receive. """
        sid=stanza.getTagAttr('close','sid')
        self.DEBUG('StreamCloseHandler called sid->%s'%sid,'info')
        if sid in self._streams.keys():
            conn.send(stanza.buildReply('result'))
            conn.Event(self.DBG_LINE,'SUCCESSFULL RECEIVE',self._streams[sid])
            del self._streams[sid]
        else: conn.send(Error(stanza,ERR_ITEM_NOT_FOUND))

    def StreamBrokenHandler(self,conn,stanza):
        """ Handle stream closure due to all some error while receiving data.
            Raise xmpppy event specifying unsuccessfull data receive. """
        syn_id=stanza.getID()
        self.DEBUG('StreamBrokenHandler called syn_id->%s'%syn_id,'info')
        for sid in self._streams.keys():
            stream=self._streams[sid]
            if stream['syn_id']==syn_id:
                if stream['direction'][0]=='<': conn.Event(self.DBG_LINE,'ERROR ON RECEIVE',stream)
                else: conn.Event(self.DBG_LINE,'ERROR ON SEND',stream)
                del self._streams[sid]

    def StreamOpenReplyHandler(self,conn,stanza):
        """ Handle remote side reply about is it agree or not to receive our datastream.
            Used internally. Raises xmpppy event specfiying if the data transfer
            is agreed upon."""
        syn_id=stanza.getID()
        self.DEBUG('StreamOpenReplyHandler called syn_id->%s'%syn_id,'info')
        for sid in self._streams.keys():
            stream=self._streams[sid]
            if stream['syn_id']==syn_id:
                if stanza.getType()=='error':
                    if stream['direction'][0]=='<': conn.Event(self.DBG_LINE,'ERROR ON RECEIVE',stream)
                    else: conn.Event(self.DBG_LINE,'ERROR ON SEND',stream)
                    del self._streams[sid]
                elif stanza.getType()=='result':
                    if stream['direction'][0]=='|':
                        stream['direction']=stream['direction'][1:]
                        conn.Event(self.DBG_LINE,'STREAM COMMITTED',stream)
                    else: conn.send(Error(stanza,ERR_UNEXPECTED_REQUEST))


text:
namespace ProductShop.Data.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    public class Product
    {
        public int ProductId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public decimal Price { get; set; }

        public int? BuyerId { get; set; }

        public User Buyer { get; set; }

        [Required]
        public int SellerId { get; set; }

        [Required]
        public User Seller { get; set; }

        public List<CategoryProduct> Categories { get; set; } = new List<CategoryProduct>();
    }
}


text:
import pytest
from pytest_embedded import Dut

@pytest.mark.supported_targets
@pytest.mark.generic
def test_pthread(dut: Dut) -> None:

    # Note: this test doesn't really confirm anything, except that threads are created
    # and stdout is not being corrupted by multiple threads printing ot it.
    dut.expect(r'Created thread 0x[\da-f]+')
    dut.expect(r'Created larger stack thread 0x[\da-f]+')
    dut.expect(r'Threads have exited')
    dut.expect(r'Created thread 0x[\da-f]+ with new default config')
    dut.expect('Thread has exited')


text:
Parameters=-

fontmark=blue

AGT.Title={b-}OutBound Non-Disclosure Agreement{-b}

b-=

bcolor=blue

-b=

DP.-={b-}{P1.Handle}{-b}

DP.The={b-}{P1.Handle}{-b}

DP.the={b-}{P1.Handle}{-b}

RP.-={b-}{P2.Handle}{-b}

RP.The={b-}{P2.Handle}{-b}

RP.the={b-}{P2.Handle}{-b}

Purpose.Roles={b-}{P1.Handle} disclosing confidential information to {P2.Handle}{-b}

Therefore.Roles={b-}{P1.Handle} making confidential information available to {P2.Handle}{-b}

Conf.Roles={b-}{P1.Handle} to {P2.Handle}{-b}

Contact.Roles._cl={b-}disclosing confidential information for {DP.the} or receiving confidential information for {RP.the}{-b}

Conf.Impart.List={b-}relates to (i) the Purpose and/or (ii) unpublished research, invention disclosures, or unpublished patent applications{-b}

CC.Persons={b-}directors (or, if applicable, members), officers, employees, consultants, and/or advisors{-b}

Compelled.Cond._cl={b-}{Compelled.Cond.Note-Coop-Min}{-b}

No Export Control Provision=Section 9.1 is deleted in the OutBound.

Export._Sec={b-}{_delete_}{-b}


text:
module.exports = function (module) {
    "use strict";

    let async = require('async');

    let header = [];

    if (module.library) header.push('LIBRARY NAME: ' + module.library.name);
    header.push('MODULE: ' + module.path);

    // how many chars has the bigger line in the header
    // used to write the asterisks of the comment
    let maxLine;
    for (let i in header) {
        if (!maxLine) {
            maxLine = header[i].length;
        }

        if (maxLine < header[i].length) {
            maxLine = header[i].length;
        }
    }

    header = header.join('\n');

    let output = '';
    output += '/';
    output += (new Array(maxLine).join('*'));
    output += '\n' + header;
    output += '\n';
    output += (new Array(maxLine + 1).join('*'));
    output += '/\n\n';

    return output;

};


text:
/*****************************************************************************/
/* CascLib.h                              Copyright (c) Ladislav Zezula 2014 */
/*---------------------------------------------------------------------------*/
/* CascLib library v 1.00                                                    */
/*                                                                           */
/* Author : Ladislav Zezula                                                  */
/* E-mail : ladik@zezula.net                                                 */
/* WWW    : http://www.zezula.net                                            */
/*---------------------------------------------------------------------------*/
/*   Date    Ver   Who  Comment                                              */
/* --------  ----  ---  -------                                              */
/* 29.04.14  1.00  Lad  Created                                              */
/*****************************************************************************/

#ifndef __CASCLIB_H__
#define __CASCLIB_H__

#ifdef _MSC_VER
#pragma warning(disable:4668)       // 'XXX' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
#pragma warning(disable:4820)       // 'XXX' : '2' bytes padding added after data member 'XXX::yyy'
#endif

#include "CascPort.h"

#ifdef __cplusplus
extern "C" {
#endif

//-----------------------------------------------------------------------------
// Use the apropriate library
//
// The library type is encoded in the library name as the following
// CascLibXYZ.lib
//
//  X - D for Debug version, R for Release version
//  Y - A for ANSI version, U for Unicode version
//  Z - S for static-linked CRT library, D for multithreaded DLL CRT library
//
#if defined(_MSC_VER) && !defined(__CASCLIB_SELF__)

  #ifdef _DEBUG                                 // DEBUG VERSIONS
    #ifndef _UNICODE
      #ifdef _DLL
        #pragma comment(lib, "CascLibDAD.lib") // Debug Ansi CRT-DLL version
      #else
        #pragma comment(lib, "CascLibDAS.lib") // Debug Ansi CRT-LIB version
      #endif
    #else
      #ifdef _DLL
        #pragma comment(lib, "CascLibDUD.lib") // Debug Unicode CRT-DLL version
      #else
        #pragma comment(lib, "CascLibDUS.lib") // Debug Unicode CRT-LIB version
      #endif
    #endif
  #else                                         // RELEASE VERSIONS
    #ifndef _UNICODE
      #ifdef _DLL
        #pragma comment(lib, "CascLibRAD.lib") // Release Ansi CRT-DLL version
      #else
        #pragma comment(lib, "CascLibRAS.lib") // Release Ansi CRT-LIB version
      #endif
    #else
      #ifdef _DLL
        #pragma comment(lib, "CascLibRUD.lib") // Release Unicode CRT-DLL version
      #else
        #pragma comment(lib, "CascLibRUS.lib") // Release Unicode CRT-LIB version
      #endif
    #endif
  #endif

#endif
//-----------------------------------------------------------------------------
// Defines

#define CASCLIB_VERSION                 0x010B  // Current version of CascLib (1.11)
#define CASCLIB_VERSION_STRING          "1.11"  // String version of CascLib version

// Values for CascOpenStorage
#define CASC_STOR_XXXXX             0x00000001  // Not used

// Values for CascOpenFile
#define CASC_OPEN_BY_NAME           0x00000000  // Open the file by name. This is the default value
#define CASC_OPEN_BY_CKEY           0x00000001  // The name is just the content key; skip ROOT file processing
#define CASC_OPEN_BY_EKEY           0x00000002  // The name is just the encoded key; skip ROOT file processing
#define CASC_OPEN_TYPE_MASK         0x0000000F  // The mask which gets open type from the dwFlags
#define CASC_STRICT_DATA_CHECK      0x00000010  // Verify all data read from a file

#define CASC_LOCALE_ALL             0xFFFFFFFF
#define CASC_LOCALE_NONE            0x00000000
#define CASC_LOCALE_UNKNOWN1        0x00000001
#define CASC_LOCALE_ENUS            0x00000002
#define CASC_LOCALE_KOKR            0x00000004
#define CASC_LOCALE_RESERVED        0x00000008
#define CASC_LOCALE_FRFR            0x00000010
#define CASC_LOCALE_DEDE            0x00000020
#define CASC_LOCALE_ZHCN            0x00000040
#define CASC_LOCALE_ESES            0x00000080
#define CASC_LOCALE_ZHTW            0x00000100
#define CASC_LOCALE_ENGB            0x00000200
#define CASC_LOCALE_ENCN            0x00000400
#define CASC_LOCALE_ENTW            0x00000800
#define CASC_LOCALE_ESMX            0x00001000
#define CASC_LOCALE_RURU            0x00002000
#define CASC_LOCALE_PTBR            0x00004000
#define CASC_LOCALE_ITIT            0x00008000
#define CASC_LOCALE_PTPT            0x00010000

#define CASC_LOCALE_BIT_ENUS        0x01
#define CASC_LOCALE_BIT_KOKR        0x02
#define CASC_LOCALE_BIT_RESERVED    0x03
#define CASC_LOCALE_BIT_FRFR        0x04
#define CASC_LOCALE_BIT_DEDE        0x05
#define CASC_LOCALE_BIT_ZHCN        0x06
#define CASC_LOCALE_BIT_ESES        0x07
#define CASC_LOCALE_BIT_ZHTW        0x08
#define CASC_LOCALE_BIT_ENGB        0x09
#define CASC_LOCALE_BIT_ENCN        0x0A
#define CASC_LOCALE_BIT_ENTW        0x0B
#define CASC_LOCALE_BIT_ESMX        0x0C
#define CASC_LOCALE_BIT_RURU        0x0D
#define CASC_LOCALE_BIT_PTBR        0x0E
#define CASC_LOCALE_BIT_ITIT        0x0F
#define CASC_LOCALE_BIT_PTPT        0x10

#define MAX_CASC_KEY_LENGTH               0x10  // Maximum length of the key (equal to MD5 hash)

#ifndef MD5_HASH_SIZE
#define MD5_HASH_SIZE                     0x10
#define MD5_STRING_SIZE                   0x20
#endif

#ifndef SHA1_DIGEST_SIZE
#define SHA1_DIGEST_SIZE                  0x14  // 160 bits
#endif

#ifndef LANG_NEUTRAL
#define LANG_NEUTRAL                      0x00  // Neutral locale
#endif

// Return value for CascGetFileSize and CascSetFilePointer
#define CASC_INVALID_INDEX          0xFFFFFFFF
#define CASC_INVALID_SIZE           0xFFFFFFFF
#define CASC_INVALID_POS            0xFFFFFFFF
#define CASC_INVALID_ID             0xFFFFFFFF

// Flags for CascGetStorageInfo
#define CASC_FEATURE_HAS_NAMES      0x00000001  // The storage contains file names

//-----------------------------------------------------------------------------
// Structures

typedef enum _CASC_STORAGE_INFO_CLASS
{
    // Return the total number of unique files in the storage. Note that files
    // can exist under different names, so the total number of files in the archive
    // can be higher than the value returned by this info class
    CascStorageFileCount,

    CascStorageFeatures,
    CascStorageGameInfo,
    CascStorageGameBuild,
    CascStorageInstalledLocales,
    CascStorageInfoClassMax

} CASC_STORAGE_INFO_CLASS, *PCASC_STORAGE_INFO_CLASS;

typedef enum _CASC_FILE_INFO_CLASS
{
    CascFileContentKey,
    CascFileEncodedKey,
    CascFileInfoClassMax
} CASC_FILE_INFO_CLASS, *PCASC_FILE_INFO_CLASS;

// Query key for a file. Contains CKey [+EKey]
typedef struct _QUERY_KEY
{
    LPBYTE pbData;
    size_t cbData;
} QUERY_KEY, *PQUERY_KEY;

// Query size for a file. Contains CSize + ESize
typedef struct _QUERY_SIZE
{
    DWORD ContentSize;
    DWORD EncodedSize;
} QUERY_SIZE, *PQUERY_SIZE;

// Structure for SFileFindFirstFile and SFileFindNextFile
typedef struct _CASC_FIND_DATA
{
    // Full name of the found file. In case when this is CKey/EKey,
    // this will be just string representation of the key stored in 'FileKey'
    char   szFileName[MAX_PATH];

    // Plain name of the found file. Pointing inside the 'szFileName' array
    char * szPlainName;

    // Content/Encoded key. The type can be determined by dwOpenFlags
    // (CASC_OPEN_BY_CKEY vs CASC_OPEN_BY_EKEY)
    BYTE   FileKey[MD5_HASH_SIZE];

    // Locale flags. Only for games that support locale flags (WoW)
    DWORD  dwLocaleFlags;

    // File data ID. Only for games that support File data ID (WoW)
    DWORD  dwFileDataId;

    // Size of the file, as retrieved from encoding entry or index entry
    DWORD  dwFileSize;

    // It is recommended to use this value for subsequent CascOpenFile
    // Contains valid value if the 'szFileName' contains file key.
    DWORD  dwOpenFlags;

} CASC_FIND_DATA, *PCASC_FIND_DATA;

//-----------------------------------------------------------------------------
// Callback functions

typedef struct TFileStream TFileStream;
typedef void (WINAPI * STREAM_DOWNLOAD_CALLBACK)(void * pvUserData, ULONGLONG ByteOffset, DWORD dwTotalBytes);

//-----------------------------------------------------------------------------
// We have our own qsort implementation, optimized for sorting array of pointers

void qsort_pointer_array(void ** base, size_t num, int (*compare)(const void *, const void *, const void *), const void * context);

//-----------------------------------------------------------------------------
// Functions for storage manipulation

bool  WINAPI CascOpenStorage(const TCHAR * szDataPath, DWORD dwLocaleMask, HANDLE * phStorage);
bool  WINAPI CascGetStorageInfo(HANDLE hStorage, CASC_STORAGE_INFO_CLASS InfoClass, void * pvStorageInfo, size_t cbStorageInfo, size_t * pcbLengthNeeded);
bool  WINAPI CascCloseStorage(HANDLE hStorage);

bool  WINAPI CascOpenFileByEKey(HANDLE hStorage, PQUERY_KEY pCKey, PQUERY_KEY pEKey, DWORD dwOpenFlags, DWORD dwEncodedSize, HANDLE * phFile);
bool  WINAPI CascOpenFileByCKey(HANDLE hStorage, PQUERY_KEY pCKey, DWORD dwOpenFlags, HANDLE * phFile);
bool  WINAPI CascOpenFile(HANDLE hStorage, const char * szFileName, DWORD dwLocaleFlags, DWORD dwOpenFlags, HANDLE * phFile);
bool  WINAPI CascGetFileInfo(HANDLE hFile, CASC_FILE_INFO_CLASS InfoClass, void * pvFileInfo, size_t cbFileInfo, size_t * pcbLengthNeeded);
DWORD WINAPI CascGetFileSize(HANDLE hFile, PDWORD pdwFileSizeHigh);
DWORD WINAPI CascGetFileId(HANDLE hStorage, const char * szFileName);
DWORD WINAPI CascSetFilePointer(HANDLE hFile, LONG lFilePos, LONG * plFilePosHigh, DWORD dwMoveMethod);
bool  WINAPI CascReadFile(HANDLE hFile, void * lpBuffer, DWORD dwToRead, PDWORD pdwRead);
bool  WINAPI CascCloseFile(HANDLE hFile);

HANDLE WINAPI CascFindFirstFile(HANDLE hStorage, const char * szMask, PCASC_FIND_DATA pFindData, const TCHAR * szListFile);
bool  WINAPI CascFindNextFile(HANDLE hFind, PCASC_FIND_DATA pFindData);
bool  WINAPI CascFindClose(HANDLE hFind);

//-----------------------------------------------------------------------------
// GetLastError/SetLastError support for non-Windows platform

#ifndef PLATFORM_WINDOWS

DWORD GetLastError();
void SetLastError(DWORD dwErrCode);

#endif  // PLATFORM_WINDOWS

#ifdef __cplusplus
}   // extern "C"
#endif

#endif  // __CASCLIB_H__


text:
package ai.nitro.bot4j.middle.domain.send.payload;

import ai.nitro.bot4j.middle.domain.send.SendMessage;
import ai.nitro.bot4j.middle.domain.send.payload.type.SendPayloadTypeEnum;

public class TypingSendPayload extends AbstractSendPayload {

	public enum Typing {
		OFF, ON
	}

	protected Typing typing;

	public TypingSendPayload(final SendMessage sendMessage) {
		super(SendPayloadTypeEnum.TYPING, sendMessage);
	}

	public Typing getTyping() {
		return typing;
	}

	public void setTyping(final Typing typing) {
		this.typing = typing;
	}

	@Override
	public String toString() {
		return "type=[" + sendPayloadType + "], typing=[" + typing + "]";
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-test-parent</artifactId>
        <version>3.12.0-SNAPSHOT</version>
    </parent>

    <artifactId>camel-testcontainers-spring-junit5</artifactId>
    <packaging>jar</packaging>

    <name>Camel :: Testcontainers :: Spring :: JUnit5</name>
    <description>Camel unit testing with Spring, testcontainers and JUnit 5</description>

    <properties>
        <firstVersion>3.0.0</firstVersion>
        <label>testing,java,docker</label>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-spring-junit5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-testcontainers-junit5</artifactId>
        </dependency>
        <!-- optional dependencies for running tests -->
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <profiles>
        <profile>
            <id>testcontainers-spring-skip-tests</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <skipTests>true</skipTests>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <!-- activate integration test if the docker socket file is accessible -->
        <profile>
            <id>testcontainers-spring-integration-tests-docker-file</id>
            <activation>
                <file>
                    <exists>/var/run/docker.sock</exists>
                </file>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <configuration>
                            <skipTests>${skipTests}</skipTests>
                            <systemPropertyVariables>
                                <visibleassertions.silence>true</visibleassertions.silence>
                            </systemPropertyVariables>
                        </configuration>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- activate integration test if the DOCKER_HOST env var is set -->
        <profile>
            <id>testcontainers-spring-integration-tests-docker-env</id>
            <activation>
                <property>
                    <name>env.DOCKER_HOST</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <configuration>
                            <skipTests>${skipTests}</skipTests>
                            <systemPropertyVariables>
                                <visibleassertions.silence>true</visibleassertions.silence>
                            </systemPropertyVariables>
                        </configuration>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

    </profiles>
</project>


text:
import { expect } from 'chai';
import I18n, { DEFAULT_LOCALE, RUNTIME } from './';
import toPseudoString from '../toPseudoString';

/* global describe it */

describe('I18n', () => {
  const data = {
    'en-US': {
      foo: 'bar',
    },
    'zh-TW': {
      foo: '霸',
    },
  };
  const loader = async (locale) => {
    if (data[locale]) return data[locale];
    throw new Error('locale not found');
  };
  it('should be a function', () => {
    expect(I18n).to.be.a('function');
  });
  it('should be a constructor function', () => {
    const instance = new I18n(loader);
    expect(instance).to.be.a('object');
    expect(instance instanceof I18n).to.equal(true);
  });
  it('should throw error if loadLocale is not a function', () => {
    expect(() => new I18n()).to.throw();
    expect(() => new I18n({})).to.throw();
    expect(() => new I18n('test')).to.throw();
    expect(() => new I18n(0)).to.throw();
  });
  it('should have static setLocale function', () => {
    expect(I18n.setLocale).to.be.a('function');
  });
  it('should have currentLocale property', () => {
    expect(I18n.currentLocale).to.be.a('string');
  });
  describe('I18n instance', () => {
    const instance = new I18n(loader);
    it('should have currentLocale property', () => {
      expect(instance.currentLocale).to.be.a('string');
    });
    it('should have function getString', () => {
      expect(instance.getString).to.be.a('function');
    });
    it('should have function setLocale', () => {
      expect(instance.setLocale).to.be.a('function');
    });
    describe('currentLocale', () => {
      it('should return the current runtime Locale', () => {
        expect(instance.currentLocale).to.equal(RUNTIME.locale);
      });
    });
    describe('setLocale', async () => {
      it('should set new locale and load the data for the locale', async () => {
        await instance.setLocale('zh-TW');
        expect(instance.currentLocale).to.equal('zh-TW');
        expect(instance.getString('foo')).to.equal(data['zh-TW'].foo);
      });
      it('should not throw even when no data is available for new locale', async () => {
        try {
          await instance.setLocale('fo-BA');
          expect(instance.currentLocale).to.equal('fo-BA');
          await instance.setLocale(DEFAULT_LOCALE);
        } catch (error) {
          await instance.setLocale(DEFAULT_LOCALE);
          throw error;
        }
      });
      it('should set locale to all existing instances of I18n', async () => {
        const inst2 = new I18n(loader);
        const inst3 = new I18n(loader);
        await instance.setLocale('fo-BA');
        expect(inst2.currentLocale).to.equal('fo-BA');
        expect(inst3.currentLocale).to.equal('fo-BA');
        await instance.setLocale(DEFAULT_LOCALE);
      });
    });
    describe('getString', () => {
      it('should return locale string', () => {
        expect(instance.getString('foo')).to.equal(data[RUNTIME.locale].foo);
      });
      it('should allow specific locale to be passed as parameter', () => {
        expect(instance.getString('foo', 'en-US')).to.equal(data['en-US'].foo);
      });
      it('should return the key if locale string is not found', () => {
        expect(instance.getString('baz')).to.equal('baz');
      });
      it('should fallback to DEFAULT_LOCALE', () => {
        expect(instance.getString('foo', 'fr')).to.equal(data[DEFAULT_LOCALE].foo);
      });
      it('should return accented string when locale is set to en-ZZ', () => {
        expect(instance.getString('foo', 'en-ZZ'))
          .to.equal(toPseudoString(data['en-US'].foo));
      });
    });
  });
});


text:
Make it easier to do front end dev with AEM

##How To use Zebra AEM Gulp Slang
1) Clone this repo into a seperate directory from you AEM working directory
```
    git clone https://github.com/benwestrate/zebra-aem-gulp-slang.git
```
2) Find the absolute path to your working jcr_root folder put that in the config.json file
```json
    {
        "jcr_location" : "/path/to/your/jcr_root"
    }
```
3) Install all dependencies
```javascript
    npm install
```
4) Run the default gulp task
```javascript
    gulp
```


text:
// Type definitions for metisMenu
// Project: https://github.com/onokumus/metisMenu

/// <reference path="../jquery/jquery.d.ts" />
declare module jquery.metisMenu {
    interface metisMenu {
        (): void;
    }
}

interface JQuery {
    metisMenu: jquery.metisMenu.metisMenu;
}


text:
Septa golang client and command line executable for getting the next regional rail train to arrive.  This project uses https://www3.septa.org/api/

## Build

[![Go Report Card](https://goreportcard.com/badge/github.com/dherbst/septa?style=flat-square)](https://goreportcard.com/report/github.com/dherbst/septa)
![golint](https://github.com/dherbst/septa/workflows/golint/badge.svg)

To build the command, clone this repo, then type `make`.  The septa executable will be copied to `$HOME/bin`.   Prerequisite is that you have `docker` installed, and `$HOME/bin` is on your `$PATH`.

    git clone https://github.com/dherbst/septa
    cd septa
    make

You can create a bash alias to make looking up the next to arrive for your favorite stations:

    alias nta="septa next Narberth \"Suburban Station\""

Alternatively, you can use the `go install` command which should install the `septa` binary to `$HOME/go/bin`:

    git clone https://github.com/dherbst/septa
    cd septa
    make install-local

### Download the binary
> **_NOTE:_** If you use OSX Catalina, this binary is not currently signed.  See #2 for progress.

You can download the latest osx binary `septa` at https://github.com/dherbst/septa/releases.  If you need a windows version please open an issue.

## Commands

### Next to Arrive - `septa next <src> <dest>`
Returns the next to arrive between the `src` and `dest` stations.

    $ septa next Narberth "Suburban Station"

    Paoli/Thorndale Train 5340 Departs  4:57PM Arrives  5:16PM On time
    Paoli/Thorndale Train 1542 Departs  5:27PM Arrives  5:45PM On time
    Paoli/Thorndale Train 5344 Departs  5:57PM Arrives  6:16PM On time
    Paoli/Thorndale Train 5348 Departs  6:57PM Arrives  7:16PM On time
    Paoli/Thorndale Train 5352 Departs  7:57PM Arrives  8:16PM On time

### List of stations - `septa stations`
Returns the list of stations that are used as arguments in the `next` command.

    $ septa stations

    9th St
    30th Street Station
    49th St
    Airport Terminal A
    Airport Terminal B
    ...

### Alerts - `septa alerts [route]`
Returns the alerts for all routes if no `route` specified, or just for the `route` specified.

    $ septa alerts generic

    Generic All SEPTA service will operate on a Sunday schedule on Friday, December 25 (Christmas Day). All SEPTA passengers are required to wear a face mask or covering. Regular service schedules are in effect, however, the Cynwyd and Chestnut Hill West Lines are suspended. The 12th & Filbert doors at Jefferson Station and the 16th & JFK doors at Suburban Station will be open during the following hours: 6:30 a.m. to 9:30 a.m. and 3:30 p.m. to 6:30 p.m. (Monday-Friday only). During all other hours these doors will be locked. We appreciate your patience during this time. With the launch of the SEPTA Key Card Travel Wallet feature for Regional Rail, the sale of paper tickets, single trip, and 10 trip strips ended October 2, 2020. Paper tickets will continue to be accepted through the valid date stamped on the back and valid for 180 days from the purchase date.