text:
{-# LANGUAGE BangPatterns, TypeSynonymInstances, FlexibleInstances, TupleSections #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -O2 #-}
{- Building this module with -O0 causes streams not to fuse and too much
 - memory to be used. -}

-- |
-- Copyright: 2015 Joey Hess <id@joeyh.name>
-- License: BSD-2-clause
--
-- Concurrent output handling, internals.
--
-- May change at any time.

module System.Console.Concurrent.Internal where

import System.IO
#ifndef mingw32_HOST_OS
import System.Posix.IO
#endif
import System.Directory
import System.Exit
import Control.Monad
import Control.Monad.IO.Class (liftIO, MonadIO)
import System.IO.Unsafe (unsafePerformIO)
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.Async
import Data.Maybe
import Data.List
import Data.Monoid
import qualified System.Process as P
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Control.Applicative
import Prelude

import Utility.Monad
import Utility.Exception

data OutputHandle = OutputHandle
	{ outputLock :: TMVar Lock
	, outputBuffer :: TMVar OutputBuffer
	, errorBuffer :: TMVar OutputBuffer
	, outputThreads :: TMVar Integer
	, processWaiters :: TMVar [Async ()]
	, waitForProcessLock :: TMVar ()
	}

data Lock = Locked

-- | A shared global variable for the OutputHandle.
{-# NOINLINE globalOutputHandle #-}
globalOutputHandle :: OutputHandle
globalOutputHandle = unsafePerformIO $ OutputHandle
	<$> newEmptyTMVarIO
	<*> newTMVarIO (OutputBuffer [])
	<*> newTMVarIO (OutputBuffer [])
	<*> newTMVarIO 0
	<*> newTMVarIO []
	<*> newEmptyTMVarIO

-- | Holds a lock while performing an action. This allows the action to
-- perform its own output to the console, without using functions from this
-- module.
--
-- While this is running, other threads that try to lockOutput will block.
-- Any calls to `outputConcurrent` and `createProcessConcurrent` will not
-- block, but the output will be buffered and displayed only once the
-- action is done.
lockOutput :: (MonadIO m, MonadMask m) => m a -> m a
lockOutput = bracket_ (liftIO takeOutputLock) (liftIO dropOutputLock)

-- | Blocks until we have the output lock.
takeOutputLock :: IO ()
takeOutputLock = void $ takeOutputLock' True

-- | Tries to take the output lock, without blocking.
tryTakeOutputLock :: IO Bool
tryTakeOutputLock = takeOutputLock' False

withLock :: (TMVar Lock -> STM a) -> IO a
withLock a = atomically $ a (outputLock globalOutputHandle)

takeOutputLock' :: Bool -> IO Bool
takeOutputLock' block = do
	locked <- withLock $ \l -> do
		v <- tryTakeTMVar l
		case v of
			Just Locked
				| block -> retry
				| otherwise -> do
					-- Restore value we took.
					putTMVar l Locked
					return False
			Nothing -> do
				putTMVar l Locked
				return True
	when locked $ do
		(outbuf, errbuf) <- atomically $ (,)
			<$> swapTMVar (outputBuffer globalOutputHandle) (OutputBuffer [])
			<*> swapTMVar (errorBuffer globalOutputHandle) (OutputBuffer [])
		emitOutputBuffer StdOut outbuf
		emitOutputBuffer StdErr errbuf
	return locked

-- | Only safe to call after taking the output lock.
dropOutputLock :: IO ()
dropOutputLock = withLock $ void . takeTMVar

-- | Use this around any actions that use `outputConcurrent`
-- or `createProcessConcurrent`
--
-- This is necessary to ensure that buffered concurrent output actually
-- gets displayed before the program exits.
withConcurrentOutput :: (MonadIO m, MonadMask m) => m a -> m a
withConcurrentOutput a = a `finally` liftIO flushConcurrentOutput

-- | Blocks until any processes started by `createProcessConcurrent` have
-- finished, and any buffered output is displayed. Also blocks while
-- `lockOutput` is is use.
--
-- `withConcurrentOutput` calls this at the end, so you do not normally
-- need to use this.
flushConcurrentOutput :: IO ()
flushConcurrentOutput = do
	atomically $ do
		r <- takeTMVar (outputThreads globalOutputHandle)
		if r <= 0
			then putTMVar (outputThreads globalOutputHandle) r
			else retry
	-- Take output lock to wait for anything else that might be
	-- currently generating output.
	lockOutput $ return ()

-- | Values that can be output.
class Outputable v where
	toOutput :: v -> T.Text

instance Outputable T.Text where
	toOutput = id

instance Outputable String where
	toOutput = toOutput . T.pack

-- | Displays a value to stdout.
--
-- No newline is appended to the value, so if you want a newline, be sure
-- to include it yourself.
--
-- Uses locking to ensure that the whole output occurs atomically
-- even when other threads are concurrently generating output.
--
-- When something else is writing to the console at the same time, this does
-- not block. It buffers the value, so it will be displayed once the other
-- writer is done.
outputConcurrent :: Outputable v => v -> IO ()
outputConcurrent = outputConcurrent' StdOut

-- | Like `outputConcurrent`, but displays to stderr.
--
-- (Does not throw an exception.)
errorConcurrent :: Outputable v => v -> IO ()
errorConcurrent = outputConcurrent' StdErr

outputConcurrent' :: Outputable v => StdHandle -> v -> IO ()
outputConcurrent' stdh v = bracket setup cleanup go
  where
	setup = tryTakeOutputLock
	cleanup False = return ()
	cleanup True = dropOutputLock
	go True = do
		T.hPutStr h (toOutput v)
		hFlush h
	go False = do
		oldbuf <- atomically $ takeTMVar bv
		newbuf <- addOutputBuffer (Output (toOutput v)) oldbuf
		atomically $ putTMVar bv newbuf
	h = toHandle stdh
	bv = bufferFor stdh

newtype ConcurrentProcessHandle = ConcurrentProcessHandle P.ProcessHandle

toConcurrentProcessHandle :: (Maybe Handle, Maybe Handle, Maybe Handle, P.ProcessHandle) -> (Maybe Handle, Maybe Handle, Maybe Handle, ConcurrentProcessHandle)
toConcurrentProcessHandle (i, o, e, h) = (i, o, e, ConcurrentProcessHandle h)

-- | Use this to wait for processes started with
-- `createProcessConcurrent` and `createProcessForeground`, and get their
-- exit status.
--
-- Note that such processes are actually automatically waited for
-- internally, so not calling this explicitly will not result
-- in zombie processes. This behavior differs from `P.waitForProcess`
waitForProcessConcurrent :: ConcurrentProcessHandle -> IO ExitCode
waitForProcessConcurrent (ConcurrentProcessHandle h) =
	bracket lock unlock checkexit
  where
	lck = waitForProcessLock globalOutputHandle
	lock = atomically $ tryPutTMVar lck ()
	unlock True = atomically $ takeTMVar lck
	unlock False = return ()
	checkexit locked = maybe (waitsome locked) return
		=<< P.getProcessExitCode h
	waitsome True = do
		let v = processWaiters globalOutputHandle
		l <- atomically $ readTMVar v
		if null l
			-- Avoid waitAny [] which blocks forever
			then P.waitForProcess h
			else do
				-- Wait for any of the running
				-- processes to exit. It may or may not
				-- be the one corresponding to the
				-- ProcessHandle. If it is,
				-- getProcessExitCode will succeed.
				void $ tryIO $ waitAny l
				checkexit True
	waitsome False = do
		-- Another thread took the lck first. Wait for that thread to
		-- wait for one of the running processes to exit.
		atomically $ do
			putTMVar lck ()
			takeTMVar lck
		checkexit False

-- Registers an action that waits for a process to exit,
-- adding it to the processWaiters list, and removing it once the action
-- completes.
asyncProcessWaiter :: IO () -> IO ()
asyncProcessWaiter waitaction = do
	regdone <- newEmptyTMVarIO
	waiter <- async $ do
		self <- atomically (takeTMVar regdone)
		waitaction `finally` unregister self
	register waiter regdone
  where
	v = processWaiters globalOutputHandle
  	register waiter regdone = atomically $ do
		l <- takeTMVar v
		putTMVar v (waiter:l)
		putTMVar regdone waiter
	unregister waiter = atomically $ do
		l <- takeTMVar v
		putTMVar v (filter (/= waiter) l)

-- | Wrapper around `System.Process.createProcess` that prevents
-- multiple processes that are running concurrently from writing
-- to stdout/stderr at the same time.
--
-- If the process does not output to stdout or stderr, it's run
-- by createProcess entirely as usual. Only processes that can generate
-- output are handled specially:
--
-- A process is allowed to write to stdout and stderr in the usual
-- way, assuming it can successfully take the output lock.
--
-- When the output lock is held (ie, by another concurrent process,
-- or because `outputConcurrent` is being called at the same time),
-- the process is instead run with its stdout and stderr
-- redirected to a buffer. The buffered output will be displayed as soon
-- as the output lock becomes free.
--
-- Currently only available on Unix systems, not Windows.
#ifndef mingw32_HOST_OS
createProcessConcurrent :: P.CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ConcurrentProcessHandle)
createProcessConcurrent p
	| willOutput (P.std_out p) || willOutput (P.std_err p) =
		ifM tryTakeOutputLock
			( fgProcess p
			, bgProcess p
			)
	| otherwise = do
		r@(_, _, _, h) <- P.createProcess p
		asyncProcessWaiter $
			void $ tryIO $ P.waitForProcess h
		return (toConcurrentProcessHandle r)
#endif

-- | Wrapper around `System.Process.createProcess` that makes sure a process
-- is run in the foreground, with direct access to stdout and stderr.
-- Useful when eg, running an interactive process.
createProcessForeground :: P.CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ConcurrentProcessHandle)
createProcessForeground p = do
	takeOutputLock
	fgProcess p

fgProcess :: P.CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ConcurrentProcessHandle)
fgProcess p = do
	r@(_, _, _, h) <- P.createProcess p
		`onException` dropOutputLock
	registerOutputThread
	-- Wait for the process to exit and drop the lock.
	asyncProcessWaiter $ do
		void $ tryIO $ P.waitForProcess h
		unregisterOutputThread
		dropOutputLock
	return (toConcurrentProcessHandle r)

#ifndef mingw32_HOST_OS
bgProcess :: P.CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ConcurrentProcessHandle)
bgProcess p = do
	(toouth, fromouth) <- pipe
	(toerrh, fromerrh) <- pipe
	let p' = p
		{ P.std_out = rediroutput (P.std_out p) toouth
		, P.std_err = rediroutput (P.std_err p) toerrh
		}
	registerOutputThread
	r@(_, _, _, h) <- P.createProcess p'
		`onException` unregisterOutputThread
	asyncProcessWaiter $ void $ tryIO $ P.waitForProcess h
	outbuf <- setupOutputBuffer StdOut toouth (P.std_out p) fromouth
	errbuf <- setupOutputBuffer StdErr toerrh (P.std_err p) fromerrh
	void $ async $ bufferWriter [outbuf, errbuf]
	return (toConcurrentProcessHandle r)
  where
	pipe = do
		(from, to) <- createPipe
		(,) <$> fdToHandle to <*> fdToHandle from
	rediroutput ss h
		| willOutput ss = P.UseHandle h
		| otherwise = ss
#endif

willOutput :: P.StdStream -> Bool
willOutput P.Inherit = True
willOutput _ = False

-- | Buffered output.
data OutputBuffer = OutputBuffer [OutputBufferedActivity]
	deriving (Eq)

data StdHandle = StdOut | StdErr

toHandle :: StdHandle -> Handle
toHandle StdOut = stdout
toHandle StdErr = stderr

bufferFor :: StdHandle -> TMVar OutputBuffer
bufferFor StdOut = outputBuffer globalOutputHandle
bufferFor StdErr = errorBuffer globalOutputHandle

data OutputBufferedActivity
	= Output T.Text
	| InTempFile
		{ tempFile :: FilePath
		, endsInNewLine :: Bool
		}
	deriving (Eq)

data AtEnd = AtEnd
	deriving Eq

data BufSig = BufSig

setupOutputBuffer :: StdHandle -> Handle -> P.StdStream -> Handle -> IO (StdHandle, MVar OutputBuffer, TMVar BufSig, TMVar AtEnd)
setupOutputBuffer h toh ss fromh = do
	hClose toh
	buf <- newMVar (OutputBuffer [])
	bufsig <- atomically newEmptyTMVar
	bufend <- atomically newEmptyTMVar
	void $ async $ outputDrainer ss fromh buf bufsig bufend
	return (h, buf, bufsig, bufend)

-- Drain output from the handle, and buffer it.
outputDrainer :: P.StdStream -> Handle -> MVar OutputBuffer -> TMVar BufSig -> TMVar AtEnd -> IO ()
outputDrainer ss fromh buf bufsig bufend
	| willOutput ss = go
	| otherwise = atend
  where
	go = do
		t <- T.hGetChunk fromh
		if T.null t
			then atend
			else do
				modifyMVar_ buf $ addOutputBuffer (Output t)
				changed
				go
	atend = do
		atomically $ putTMVar bufend AtEnd
		hClose fromh
	changed = atomically $ do
		void $ tryTakeTMVar bufsig
		putTMVar bufsig BufSig

registerOutputThread :: IO ()
registerOutputThread = do
	let v = outputThreads globalOutputHandle
	atomically $ putTMVar v . succ =<< takeTMVar v

unregisterOutputThread :: IO ()
unregisterOutputThread = do
	let v = outputThreads globalOutputHandle
	atomically $ putTMVar v . pred =<< takeTMVar v

-- Wait to lock output, and once we can, display everything
-- that's put into the buffers, until the end.
--
-- If end is reached before lock is taken, instead add the command's
-- buffers to the global outputBuffer and errorBuffer.
bufferWriter :: [(StdHandle, MVar OutputBuffer, TMVar BufSig, TMVar AtEnd)] -> IO ()
bufferWriter ts = do
	activitysig <- atomically newEmptyTMVar
	worker1 <- async $ lockOutput $
		ifM (atomically $ tryPutTMVar activitysig ())
			( void $ mapConcurrently displaybuf ts
			, noop -- buffers already moved to global
			)
	worker2 <- async $ void $ globalbuf activitysig worker1
	void $ async $ do
		void $ waitCatch worker1
		void $ waitCatch worker2
		unregisterOutputThread
  where
	displaybuf v@(outh, buf, bufsig, bufend) = do
		change <- atomically $
			(Right <$> takeTMVar bufsig)
				`orElse`
			(Left <$> takeTMVar bufend)
		l <- takeMVar buf
		putMVar buf (OutputBuffer [])
		emitOutputBuffer outh l
		case change of
			Right BufSig -> displaybuf v
			Left AtEnd -> return ()
	globalbuf activitysig worker1 = do
		ok <- atomically $ do
			-- signal we're going to handle it
			-- (returns false if the displaybuf already did)
			ok <- tryPutTMVar activitysig ()
			-- wait for end of all buffers
			when ok $
				mapM_ (\(_outh, _buf, _bufsig, bufend) -> takeTMVar bufend) ts
			return ok
		when ok $ do
			-- add all of the command's buffered output to the
			-- global output buffer, atomically
			bs <- forM ts $ \(outh, buf, _bufsig, _bufend) ->
				(outh,) <$> takeMVar buf
			atomically $
				forM_ bs $ \(outh, b) ->
					bufferOutputSTM' outh b
			-- worker1 might be blocked waiting for the output
			-- lock, and we've already done its job, so cancel it
			cancel worker1

-- Adds a value to the OutputBuffer. When adding Output to a Handle,
-- it's cheaper to combine it with any already buffered Output to that
-- same Handle.
--
-- When the total buffered Output exceeds 1 mb in size, it's moved out of
-- memory, to a temp file. This should only happen rarely, but is done to
-- avoid some verbose process unexpectedly causing excessive memory use.
addOutputBuffer :: OutputBufferedActivity -> OutputBuffer -> IO OutputBuffer
addOutputBuffer (Output t) (OutputBuffer buf)
	| T.length t' <= 1048576 = return $ OutputBuffer (Output t' : other)
	| otherwise = do
		tmpdir <- getTemporaryDirectory
		(tmp, h) <- openTempFile tmpdir "output.tmp"
		let !endnl = endsNewLine t'
		let i = InTempFile
			{ tempFile = tmp
			, endsInNewLine = endnl
			}
		T.hPutStr h t'
		hClose h
		return $ OutputBuffer (i : other)
  where
	!t' = T.concat (mapMaybe getOutput this) <> t
	!(this, other) = partition isOutput buf
	isOutput v = case v of
		Output _ -> True
		_ -> False
	getOutput v = case v of
		Output t'' -> Just t''
		_ -> Nothing
addOutputBuffer v (OutputBuffer buf) = return $ OutputBuffer (v:buf)

-- | Adds a value to the output buffer for later display.
--
-- Note that buffering large quantities of data this way will keep it
-- resident in memory until it can be displayed. While `outputConcurrent`
-- uses temp files if the buffer gets too big, this STM function cannot do
-- so.
bufferOutputSTM :: Outputable v => StdHandle -> v -> STM ()
bufferOutputSTM h v = bufferOutputSTM' h (OutputBuffer [Output (toOutput v)])

bufferOutputSTM' :: StdHandle -> OutputBuffer -> STM ()
bufferOutputSTM' h (OutputBuffer newbuf) = do
	(OutputBuffer buf) <- takeTMVar bv
	putTMVar bv (OutputBuffer (newbuf ++ buf))
  where
	bv = bufferFor h

-- | A STM action that waits for some buffered output to become
-- available, and returns it.
--
-- The function can select a subset of output when only some is desired;
-- the fst part is returned and the snd is left in the buffer.
--
-- This will prevent it from being displayed in the usual way, so you'll
-- need to use `emitOutputBuffer` to display it yourself.
outputBufferWaiterSTM :: (OutputBuffer -> (OutputBuffer, OutputBuffer)) -> STM (StdHandle, OutputBuffer)
outputBufferWaiterSTM selector = waitgetbuf StdOut `orElse` waitgetbuf StdErr
  where
	waitgetbuf h = do
		let bv = bufferFor h
		(selected, rest) <- selector <$> takeTMVar bv
		when (selected == OutputBuffer [])
			retry
		putTMVar bv rest
		return (h, selected)

waitAnyBuffer :: OutputBuffer -> (OutputBuffer, OutputBuffer)
waitAnyBuffer b = (b, OutputBuffer [])

-- | Use with `outputBufferWaiterSTM` to make it only return buffered
-- output that ends with a newline. Anything buffered without a newline
-- is left in the buffer.
waitCompleteLines :: OutputBuffer -> (OutputBuffer, OutputBuffer)
waitCompleteLines (OutputBuffer l) =
	let (selected, rest) = span completeline l
	in (OutputBuffer selected, OutputBuffer rest)
  where
	completeline (v@(InTempFile {})) = endsInNewLine v
	completeline (Output b) = endsNewLine b

endsNewLine :: T.Text -> Bool
endsNewLine t = not (T.null t) && T.last t == '\n'

-- | Emits the content of the OutputBuffer to the Handle
--
-- If you use this, you should use `lockOutput` to ensure you're the only
-- thread writing to the console.
emitOutputBuffer :: StdHandle -> OutputBuffer -> IO ()
emitOutputBuffer stdh (OutputBuffer l) =
	forM_ (reverse l) $ \ba -> case ba of
		Output t -> emit t
		InTempFile tmp _ -> do
			emit =<< T.readFile tmp
			void $ tryWhenExists $ removeFile tmp
  where
	outh = toHandle stdh
	emit t = void $ tryIO $ do
		T.hPutStr outh t
		hFlush outh


text:
export * from './authHelpers';
export * from './checkToken';
export * from './generateToken';
export * from './setUserInfo';

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import {Navbar, Nav, NavItem} from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import Header from './header_view.js'
import BusinessRegistration from '../containers/businessRegistration'
import Notification from "../containers/notification"
import { getUserFromStorage,displayNotification } from "../actions";

class BusinessRegistrationView extends Component {

  componentWillMount()
  {
    this.props.getUserFromStorage();
  }

  render() {
    if(this.props.userAuthentication && this.props.userAuthentication.payload) {
      if(this.props.userAuthentication.payload.authenticationFailure && this.props.userAuthentication.payload.displayMessage) {
        this.props.displayNotification(true,'Error during Authentication - Please register again!','delete-item-notification');
      }
      else {
        return(

        {this.props.history.push(`/businessHomePageView/${this.props.userAuthentication.payload.placeId}`)}

        )
      }

    }
     else {
       return (

         <Notification />

Please register and connect to your Customers instantly

                     <BusinessRegistration />

Our Partners

       );
     }

  }
}

function mapStateToProps({userAuthentication}) {
  return { userAuthentication};
}

export default connect(mapStateToProps, {getUserFromStorage,displayNotification})(BusinessRegistrationView);


text:
from   datetime  import datetime
from   django.db import connection, transaction
import inspect
import threading
from   types     import NoneType
import sys

from satori.ars       import perf
from satori.ars.model import *

deferred_structures = []

class ArsDeferredStructure(ArsStructure):
    def __init__(self, name, fields):
        super(ArsDeferredStructure, self).__init__(name)
        self.python_fields = fields
        deferred_structures.append(self)

    def init_fields(self):
        for (field_name, field_type, field_optional) in self.python_fields:
            self.add_field(name=field_name, type=python_to_ars_type(field_type), optional=field_optional)

class ArsDeferredException(ArsException):
    def __init__(self, name, fields):
        super(ArsDeferredException, self).__init__(name)
        self._fields = fields
        deferred_structures.append(self)

    def init_fields(self):
        for (field_name, field_type, field_optional) in self._fields:
            self.add_field(name=field_name, type=python_to_ars_type(field_type), optional=field_optional)

class TypedList(object):
    def __init__(self, element_type):
        self.element_type = element_type

    def ars_type(self):
        if not hasattr(self, '_ars_type'):
            self._ars_type = ArsList(python_to_ars_type(self.element_type))

        return self._ars_type

class TypedMap(object):
    def __init__(self, key_type, value_type):
        self.key_type = key_type
        self.value_type = value_type

    def ars_type(self):
        if not hasattr(self, '_ars_type'):
            ars_key_type = python_to_ars_type(self.key_type)
            ars_value_type = python_to_ars_type(self.value_type)
            self._ars_type = ArsMap(key_type=ars_key_type, value_type=ars_value_type)

        return self._ars_type

def Struct(name, fields):
    ars_type = ArsDeferredStructure(name, fields)
    return ars_type.get_class()

def DefineException(name, message, fields=[]):
    ars_exception = ArsDeferredException(name, [('message', str, False)] + fields)

    exception_class = ars_exception.get_class()

    def __init__(self, **kwargs):
        kwargs['message'] = unicode(message).format(**kwargs)
        super(exception_subclass, self).__init__(**kwargs)

    exception_subclass = type(name, (exception_class,), {'__init__': __init__})

    return exception_subclass

class Binary(object):
    @staticmethod
    def ars_type():
        return ArsBinary

python_basic_types = {
    NoneType: ArsVoid,
    int: ArsInt32,
    long: ArsInt64,
    str: ArsString,
    unicode: ArsString,
    basestring: ArsString,
    bool: ArsBoolean,
    datetime: ArsDateTime,
    float: ArsFloat,
}

def python_to_ars_type(type_):
    if type_ in python_basic_types:
        return python_basic_types[type_]

    if hasattr(type_, 'ars_type'):
        return type_.ars_type()

    raise RuntimeError('Cannot convert type {0} to ars type.'.format(type_))

def init():
    for struct in deferred_structures:
        struct.init_fields()


text:
"""An attempt to make an overview visualization. Consumes hamster d-bus API"""

from gi.repository import Gtk as gtk
from lib import graphics

import time, datetime as dt
from collections import defaultdict
import hamster.client

class Scene(graphics.Scene):
    def __init__(self):
        graphics.Scene.__init__(self)

        storage = hamster.client.Storage()

        self.facts = storage.get_facts(dt.date(2009,1,1), dt.date.today())

        self.day_counts = defaultdict(list)
        activities, categories = defaultdict(int), defaultdict(int)

        print len(self.facts)

        for fact in self.facts:
            self.day_counts[fact.start_time.date()].append(fact)
            activities[fact.activity] += 1
            categories[fact.category] += 1

            if fact.end_time and fact.start_time.date() != fact.end_time.date():
                self.day_counts[fact.end_time.date()].append(fact)

        self.activities = [activity[0] for activity in sorted(activities.items(), key=lambda item:item[1], reverse=True)]
        self.categories = categories.keys()

        self.connect("on-enter-frame", self.on_enter_frame)

    def on_enter_frame(self, scene, context):
        if not self.facts:
            return

        g = graphics.Graphics(context)
        g.set_line_style(width=1)

        start_date = self.facts[0].start_time.date()
        end_date = (self.facts[-1].start_time + self.facts[-1].delta).date()

        days = (end_date - start_date).days

        full_days = []
        for day in range(days):
            current_date = start_date + dt.timedelta(days=day)
            if not self.day_counts[current_date]:
                continue
            full_days.append(self.day_counts[current_date])

        day_pixel = float(self.width) / len(full_days)

        cur_x = 0
        pixel_width = max(round(day_pixel), 1)

        for day in full_days:
            cur_x += round(day_pixel)

            for j, fact in enumerate(day):

                #bar per category
                g.rectangle(cur_x, 27 + self.categories.index(fact.category) * 6, pixel_width, 6)

                #bar per activity
                g.rectangle(cur_x, 102 + self.activities.index(fact.activity) * 6, pixel_width, 6)

                #number of activities
                g.rectangle(cur_x, self.height - 3 * j, pixel_width, 3)

            g.fill("#aaa")

class BasicWindow:
    def __init__(self):
        window = gtk.Window()
        window.set_size_request(600, 300)
        window.connect("delete_event", lambda *args: gtk.main_quit())
        window.add(Scene())
        window.show_all()

example = BasicWindow()
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL) # gtk3 screws up ctrl+c
gtk.main()


text:
/*
 * SkipNgram.cc --
 *	N-gram backoff language model with context skips
 *
 */

#ifndef lint
static char Copyright[] = "Copyright (c) 1995-2010 SRI International, 2013 Microsoft Corp.  All Rights Reserved.";
static char RcsId[] = "@(#)$Header: /home/srilm/CVS/srilm/lm/src/SkipNgram.cc,v 1.18 2013-06-21 05:48:53 stolcke Exp $";
#endif

#ifdef PRE_ISO_CXX
# include <iostream.h>
#else
# include <iostream>
using namespace std;
#endif
#include <stdlib.h>
#include <assert.h>

#include "SkipNgram.h"

#include "Array.cc"

#define DEBUG_ESTIMATE_WARNINGS	1	/* from Ngram.cc */
#define DEBUG_PRINT_WORD_PROBS  2       /* from LM.cc */
#define DEBUG_PRINT_LIKELIHOODS	0

SkipNgram::SkipNgram(Vocab &vocab, unsigned order)
    : Ngram(vocab, order),
      maxEMiters(100), minEMdelta(0.0001),
      initialSkipProb(0.5), skipProbs(vocab.numWords())
{
}

void
SkipNgram::memStats(MemStats &stats)
{
    Ngram::memStats(stats);
    skipProbs.memStats(stats);
}

/*
 * LM interface
 */

LogP
SkipNgram::wordProb(VocabIndex word, const VocabIndex *context)
{
    unsigned int clen = Vocab::length(context);

    if (skipOOVs()) {
	/*
	 * Backward compatibility with the old broken perplexity code:
	 * return prob 0 if any of the context-words have an unknown
	 * word.
	 */
	if (word == vocab.unkIndex() ||
	    (order > 1 && context[0] == vocab.unkIndex()) ||
	    (order > 2 && context[2] == vocab.unkIndex()))
	{
	    return LogP_Zero;
	}
    }

    /*
     * If the context is empty we use only the straight Ngram prob.
     * Otherwise, interpolate the regular Ngram prob with the one
     * resulting from skipping the last word.
     */
    if (clen == 0) {
	return Ngram::wordProbBO(word, context, 0);
    } else {
	Prob *skipProb = skipProbs.find(context[0]);

	/*
	 * Avoid useless lookup if skipProb is zero.
	 */
	if (skipProb == 0 || *skipProb == 0.0) {
		return Ngram::wordProbBO(word, context,
				(clen > order - 1) ? order - 1 : clen);
	} else {
	    return MixLogP(Ngram::wordProbBO(word, &context[1],
				(clen - 1 > order - 1) ? order - 1 : clen - 1),
			   Ngram::wordProbBO(word, context,
				(clen > order - 1) ? order - 1 : clen),
			   *skipProb);
	}
    }
}

Boolean
SkipNgram::read(File &file, Boolean limitVocab)
{
    /*
     * First read the ngram data in standard format
     */
    if (!Ngram::read(file, limitVocab)) {
	return false;
    }

    /*
     * Now parse the skipProbs as a two-column list
     */

    char *line;

    while ((line = file.getline())) {

	VocabString words[3];
	VocabIndex wid;

	/*
	 * Parse a line of the form
	 *	<w>	<prob>
	 */
	if (Vocab::parseWords(line, words, 3) != 2) {
	    file.position() << "illegal skip prob line\n";
	    return false;
	}

	wid = vocab.addWord(words[0]);

	Prob prob;
	if (!parseProb(words[1], prob)) {
	    file.position() << "bad skip prob value " << words[1] << endl;
	    return false;
	}

	*skipProbs.insert(wid) = prob;
    }

    return true;
}

Boolean
SkipNgram::write(File &file)
{
    /*
     * First write out the Ngram parameters in the usual format
     */
    if (!Ngram::write(file)) {
	return false;
    }

    file.fprintf("\n");

    LHashIter<VocabIndex, Prob> skipProbsIter(skipProbs, vocab.compareIndex());

    VocabIndex wid;
    Prob *prob;

    while ((prob = skipProbsIter.next(wid))) {
	file.fprintf("%s %lg\n", vocab.getWord(wid), *prob);
    }

    file.fprintf("\n");

    return true;
}

/*
 * Estimation
 */

Boolean
SkipNgram::estimate(NgramStats &stats, Discount **discounts)
{
    /*
     * Initialize undefined skipProbs
     */
    VocabIter vocabIter(vocab);
    VocabIndex wid;

    while (vocabIter.next(wid)) {
	Boolean foundP;
	Prob *skipProb = skipProbs.insert(wid, foundP);

	if (!foundP) {
	    *skipProb = (wid == vocab.ssIndex()) ? 0.0 : initialSkipProb;
	}
    }

    LogP like;

    for (unsigned i = 0; i < maxEMiters; i ++) {
	NgramCounts<FloatCount> ngramExps(vocab, order);
	LHash<VocabIndex, double> skipExps(vocab.numWords());

	LogP newLike = estimateEstep(stats, ngramExps, skipExps);

	//cerr << "ngram stats:\n";
	//ngramExps.write((File)stderr);

	if (debug(DEBUG_PRINT_LIKELIHOODS)) {
	   dout() << "iteration " << i << ": "
		  << "log likelihood = " << newLike
		  << endl;
	}

	if (i > 1 && fabs((newLike - like)/like) < minEMdelta) {
	    break;
	}

	if (!estimateMstep(stats, ngramExps, skipExps, discounts)) {
	    return false;
	}
	like = newLike;
    }

    return true;
}

/*
 * E-step (expected count computation)
 *	returns the log likelihood of the training counts
 */
LogP
SkipNgram::estimateEstepNgram(VocabIndex *ngram, NgramCount ngramCount,
			      NgramStats &stats,
			      NgramCounts<FloatCount> &ngramExps,
			      LHash<VocabIndex, double> &skipExps)
{
    unsigned ngramLength = Vocab::length(ngram);
    assert(ngramLength > 1);

    VocabIndex word = ngram[ngramLength - 1];
    VocabIndex skipped = ngram[ngramLength - 2];

    //cerr << "doing ngram " << (vocab.use(), ngram) << endl;

    Prob *skipProb = skipProbs.find(skipped);
    Prob skipPr = skipProb ? *skipProb : 0.0;

    /*
     * temporarily reverse ngram for wordProb call
     */
    Vocab::reverse(ngram);

    LogP l1 = Ngram::wordProbBO(ngram[0], &ngram[2], ngramLength - 2);
    LogP l2 = Ngram::wordProbBO(ngram[0], &ngram[1], ngramLength - 2);

    /*
     * If both likelihoods are zero the model is not yet initialized,
     * so we provide some dummy values
     */
    if (l1 == LogP_Zero && l2 == LogP_Zero) {
	l1 = l2 = -10.0;
    }

    Prob p1 = skipPr * LogPtoProb(l1);
    Prob p2 = (1.0 - skipPr) * LogPtoProb(l2);

    LogP logSum = ProbToLogP(p1 + p2);

    Vocab::reverse(ngram);

    //cerr << "l1 = " << l1 << " l2 = " << l2 << endl;
    //cerr << "p1 = " << p1 << " p2 = " << p2 << endl;

    /*
     * Increment expected count for ngrams with skip
     * NOTE: Do not add ngrams that weren't observed in the data.
     */
    ngram[ngramLength - 2] = Vocab_None;
    unsigned i;

    for (i = (ngramLength - 1 > order) ? ngramLength - 1 - order : 0;
	 i < ngramLength - 1;
	 i ++)
    {
	if (stats.findCount(&ngram[i], word)) {
	    //cerr << " incrementing " << (vocab.use(), &ngram[i])
	    //     << " " << vocab.getWord(word) << endl;
	    *ngramExps.insertCount(&ngram[i], word) += skipPr * ngramCount;
	}
    }
    ngram[ngramLength - 2] = skipped;

    /*
     * Increment expected count for ngrams without skip
     */
    for (i = (ngramLength > order) ? ngramLength - order : 0;
	 i < ngramLength;
	 i ++)
    {
	//cerr << " incrementing " << (vocab.use(), &ngram[i]) << endl;
	*ngramExps.insertCount(&ngram[i]) += (1.0 - skipPr) * ngramCount;
    }

    /*
     * Increment expected skip count
     */
    *skipExps.insert(skipped) += p1 / (p1 + p2);

    return ngramCount * logSum;
}

LogP
SkipNgram::estimateEstep(NgramStats &stats,
			 NgramCounts<FloatCount> &ngramExps,
			 LHash<VocabIndex, double> &skipExps)
{
    LogP totalLikelihood = 0.0;
    makeArray(VocabIndex, ngram, order + 2);
    makeArray(VocabIndex, context, order);

    /*
     * Enumerate all n+1 grams
     */
    NgramsIter ngramIter(stats, ngram, order + 1);
    NgramCount *ngramCount;

    while ((ngramCount = ngramIter.next())) {
	totalLikelihood += estimateEstepNgram(ngram, *ngramCount,
						stats, ngramExps, skipExps);
    }

    /*
     * Enumerate the 2...n grams starting with <s>
     * (they were omitted in the iteration above)
     */
    VocabIndex start[2];
    start[0] = vocab.ssIndex();
    start[1] = Vocab_None;
    ngram[0] = vocab.ssIndex();

    for (unsigned j = order; j > 1; j --) {
	NgramsIter ngramIter(stats, start, &ngram[1], j - 1);

	while ((ngramCount = ngramIter.next())) {
	    totalLikelihood += estimateEstepNgram(ngram, *ngramCount,
						   stats, ngramExps, skipExps);
	}
    }

    return totalLikelihood;
}

/*
 * M-step (likelihood maximization):
 *	This is virtually identical to Ngram::estimate(), except that
 *	the cound are floats.
 *	We also estimate the skip probabilities using ML.
 */
Boolean
SkipNgram::estimateMstep(NgramStats &stats,
		         NgramCounts<FloatCount> &ngramExps,
		         LHash<VocabIndex,double> &skipExps,
		         Discount **discounts)
{
    /*
     * First, estimate the skip probabilities using maximum likelihood
     */
    LHashIter<VocabIndex, double> skipExpsIter(skipExps);

    VocabIndex wid;
    double *skipCount;

    while ((skipCount = skipExpsIter.next(wid))) {
	NgramCount *total = stats.findCount(0, wid);
	assert(total != 0);

	//cerr << "skip(" << vocab.getWord(wid) << ") = "
	//	<< *skipCount << "/"
	//	<< *total << endl;
	*skipProbs.insert(wid) = *skipCount / *total;
    }

    //{
    //    File file("SKIP-NGRAM-EXPECTATIONS", "w");
    //    ngramExps.write(file, 0);
    //}

    /*
     * Reestimate discounting parameters from expected counts
     */
    for (unsigned i = 1; i <= order; i++) {
	if (!discounts[i-1]->estimate(ngramExps, i)) {
	    dout() << "warning: skip-ngram discount estimator for order "
		   << i << " failed -- using old parameters\n";
	}
    }

    /*
     * Reestimate probs from expected counts
     */
    return Ngram::estimate(ngramExps, discounts);
}


text:
import pytest
from thefuck.rules.brew_unknown_command import match, get_new_command
from thefuck.rules.brew_unknown_command import brew_commands
from tests.utils import Command

@pytest.fixture
def brew_unknown_cmd():
    return '''Error: Unknown command: inst'''

@pytest.fixture
def brew_unknown_cmd2():
    return '''Error: Unknown command: instaa'''

def test_match(brew_unknown_cmd):
    assert match(Command('brew inst', stderr=brew_unknown_cmd), None)
    for command in brew_commands:
        assert not match(Command('brew ' + command), None)

def test_get_new_command(brew_unknown_cmd, brew_unknown_cmd2):
    assert get_new_command(Command('brew inst', stderr=brew_unknown_cmd),
                           None) == ['brew list', 'brew install', 'brew uninstall']

    assert get_new_command(Command('brew instaa', stderr=brew_unknown_cmd2),
                           None) == ['brew install', 'brew uninstall', 'brew list']


text:
'use strict';

const express = require('express');
const controller = require('./user.controller');
const auth = require('../../auth/auth.service');

const router = express.Router(); // eslint-disable-line babel/new-cap

router.get('/', auth.hasRole('admin'), controller.index);
router.delete('/:id', auth.hasRole('admin'), controller.destroy);
router.get('/me', auth.isAuthenticated(), controller.me);
router.put('/:id/password', auth.isAuthenticated(), controller.changePassword);
router.get('/:id', auth.isAuthenticated(), controller.show);
router.post('/', controller.create);

module.exports = router;


text:
package org.cmuchimps.gort.api.gort;

import org.netbeans.api.project.Project;
import org.openide.util.Lookup;

/**
 *
 * @author shahriyar
 */
public abstract class ProjectDirectoryServiceFactory {
    public static ProjectDirectoryServiceFactory getDefault() {
        return Lookup.getDefault().lookup(ProjectDirectoryServiceFactory.class);
    }

    public abstract ProjectDirectoryService getInstance(Project project);

}


text:
package org.apache.wicket.markup.html.form.panelBorder;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTestCase;
import org.junit.jupiter.api.Test;

/**
 * Simple test using the WicketTester
 */
class TestHomePage_2134 extends WicketTestCase
{
	/**
	 * WICKET-2134: two forms inside a border throw a ConversionException error
	 */
	@Test
	void testRenderMyPage()
	{
		// start and render the test page
		tester.startPage(CommonModelPage.class);

		// assert rendered page class
		tester.assertRenderedPage(CommonModelPage.class);

		FormTester formTester = tester.newFormTester("border:body:form1");
		formTester.submit();

		CommonModelPage page = (CommonModelPage)tester.getLastRenderedPage();
		assertEquals(0, page.quantity1);
		assertEquals(0, page.quantity2);
	}

	/**
	 * WICKET-2134: two forms inside a border throw a ConversionException error
	 */
	@Test
	void testRenderMyPage2()
	{
		// start and render the test page
		tester.startPage(CommonModelPage.class);

		// assert rendered page class
		tester.assertRenderedPage(CommonModelPage.class);

		FormTester formTester = tester.newFormTester("border:body:form1");
		formTester.setValue("quantity1", "123");
		// formTester.setValue("quantity2", "44");
		formTester.submit();

		CommonModelPage page = (CommonModelPage)tester.getLastRenderedPage();
		assertEquals(123, page.quantity1);
		assertEquals(0, page.quantity2);
	}

	/**
	 * WICKET-2134: two forms inside a border throw a ConversionException error
	 */
	@Test
	void testRenderMyPage3()
	{
		// start and render the test page
		tester.startPage(CommonModelPage.class);

		// assert rendered page class
		tester.assertRenderedPage(CommonModelPage.class);

		FormTester formTester = tester.newFormTester("border:body:form2");
		// formTester.setValue("quantity1", "123");
		formTester.setValue("quantity2", "44");
		formTester.submit();

		CommonModelPage page = (CommonModelPage)tester.getLastRenderedPage();
		assertEquals(0, page.quantity1);
		assertEquals(44, page.quantity2);
	}
}


text:
%% properties
%% globals
lightsQueue
--]]

-- CONST

local powerID = 4; -- Туалет:БП ACDC 24В

local debugMode = true;

-- GET ENVS

if ( fibaro:countScenes() > 1 )
  then
  if ( debugMode ) then fibaro:debug("Double start.. Abort dup!"); end
  fibaro:abort();
end;
--local trigger = fibaro:getSourceTrigger();

local powerValue = fibaro:getValue(powerID, "value");

local nightMode = false;
if ( fibaro:getGlobalValue("nightMode") == "1" )
  then
  nightMode = true;
  if ( debugMode ) then fibaro:debug("_nightMode detected"); end
end

local lightsQueue = fibaro:getGlobalValue("lightsQueue");
local lightActionPos = string.find(lightsQueue, ";");

-- PROCESS

if ( debugMode ) then fibaro:debug("_lightsQueue = <" .. lightsQueue .. ">"); end

while lightActionPos ~= nil do

  if ( debugMode ) then fibaro:debug("FOUND lightAction, end.pos = " .. tostring(lightActionPos)); end

  local lightAction = string.sub(lightsQueue, 1, lightActionPos);
  fibaro:setGlobal("lightsQueue", string.sub(lightsQueue, lightActionPos + 1));

  if ( debugMode ) then fibaro:debug("GET lightAction = <" .. lightAction .. ">"); end

  local nodeID = tonumber(string.sub(lightAction, 1, string.find(lightAction, ",") - 1));
  lightAction = string.sub(lightAction, string.find(lightAction, ",") + 1);
  local nodeValue = string.sub(lightAction, 1, string.find(lightAction, ";") - 1);

--fibaro:debug(tostring(nodeID) .. " / " .. nodeValue); fibaro:abort();

  local nodeName = "<" .. fibaro:getName(nodeID)
    	.. " (" .. fibaro:getRoomNameByDeviceID(nodeID) .. ")>";

  if ( debugMode ) then fibaro:debug("LIGHTACTION: set value for " .. nodeName .. " = " .. nodeValue); end

    if ( nodeValue == "0" )
      then
      -- TURN OFF --

	  --if tonumber(fibaro:getValue(nodeID, "value")) > 0 -- disable check because fails sometimes
      --  then
      if ( debugMode ) then fibaro:debug("TURING OFF " .. nodeName); end

      fibaro:call(nodeID, "turnOff");
      --end

    else
      -- TURN ON --

      --- Check PowerSource ---
      if ( powerValue == "0" )
        then
        if ( debugMode ) then fibaro:debug("PowerSource is OFF! Turning ON"); end

        fibaro:call(powerID, "turnOn");
        fibaro:sleep(3 * 1000);

        powerValue = fibaro:getValue(powerID, "value");
        if ( powerValue == "0" )
          then
          if ( debugMode ) then fibaro:debug("PowerSource turning on was FAIL!"); end
          break;
        end
      else
        if ( debugMode ) then fibaro:debug("PowerSource is on");
      end

      --- Wakeup devices ---
      if ( fibaro:getValue(nodeID, "dead") >= "1" )
        then
        if ( debugMode ) then fibaro:debug("WAKING UP DEAD " .. nodeName); end

        --fibaro:wakeUpDeadDevice(nodeID);
		--new code for HC2 v4+:
		fibaro:call(1, 'wakeUpAllDevices', nodeID);

        fibaro:sleep(2 * 1000);
      end

      if ( nodeValue == "101" )
        then
        if ( nightMode == true )
          then
          nodeValue = "1";
        else
          nodeValue = "99";
        end
      elseif ( tonumber(nodeValue) > 101 )
        then
        nodeValue = tostring(tonumber(nodeValue - 101));
      end

      if (tonumber(nodeValue) >= 99 )
        then -- FULL ON
        if ( debugMode ) then fibaro:debug("Turning ON " .. nodeName); end

        --fibaro:call(nodeID, "turnOn");
        -- непонятная хрень - RGBW в БК не желают включаться по
        -- "turnOn" (в т.ч. через моб.прил-ие!),
        -- выключаются же при этом - без проблем
        fibaro:call(nodeID, "setValue", 100);
      elseif tonumber(nodeValue) <= 3
        then -- MIN
        if ( debugMode ) then fibaro:debug("Setting MIN on " .. nodeName); end

        fibaro:call(nodeID, "setValue", 1);
      else -- EXACT VALUE
        if ( debugMode ) then fibaro:debug("Setting VALUE [" .. nodeValue .. "] on " .. nodeName); end

        fibaro:call(nodeID, "setValue", nodeValue);
      end

      --end
    end

  -- reload queue and research lA
  lightsQueue = fibaro:getGlobalValue("lightsQueue");
  lightActionPos = string.find(lightsQueue, ";");

  if ( debugMode ) then fibaro:debug("__lightsQueue = <" .. lightsQueue .. ">"); end
end

fibaro:setGlobal("lightsQueue", ""); -- clear queue


text:
#ifndef BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP
#define BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP

#if (defined _MSC_VER) && (_MSC_VER >= 1200)
#  pragma once
#endif

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/detail/managed_open_or_create_impl.hpp>
#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
#include <boost/interprocess/sync/shm/named_creation_functor.hpp>
#include <boost/interprocess/permissions.hpp>

//!\file
//!Describes a named shm_named_recursive_mutex class for inter-process synchronization

namespace boost {
namespace interprocess {
namespace ipcdetail {

/// @cond
class interprocess_tester;
/// @endcond

class shm_named_recursive_mutex
{
   /// @cond
   //Non-copyable
   shm_named_recursive_mutex();
   shm_named_recursive_mutex(const shm_named_recursive_mutex &);
   shm_named_recursive_mutex &operator=(const shm_named_recursive_mutex &);
   /// @endcond
   public:

   //!Creates a global recursive_mutex with a name.
   //!If the recursive_mutex can't be created throws interprocess_exception
   shm_named_recursive_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions());

   //!Opens or creates a global recursive_mutex with a name.
   //!If the recursive_mutex is created, this call is equivalent to
   //!shm_named_recursive_mutex(create_only_t, ... )
   //!If the recursive_mutex is already created, this call is equivalent
   //!shm_named_recursive_mutex(open_only_t, ... )
   //!Does not throw
   shm_named_recursive_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions());

   //!Opens a global recursive_mutex with a name if that recursive_mutex is previously
   //!created. If it is not previously created this function throws
   //!interprocess_exception.
   shm_named_recursive_mutex(open_only_t open_only, const char *name);

   //!Destroys *this and indicates that the calling process is finished using
   //!the resource. The destructor function will deallocate
   //!any system resources allocated by the system for use by this process for
   //!this resource. The resource can still be opened again calling
   //!the open constructor overload. To erase the resource from the system
   //!use remove().
   ~shm_named_recursive_mutex();

   //!Unlocks a previously locked
   //!shm_named_recursive_mutex.
   void unlock();

   //!Locks shm_named_recursive_mutex, sleeps when shm_named_recursive_mutex is already locked.
   //!Throws interprocess_exception if a severe error is found.
   void lock();

   //!Tries to lock the shm_named_recursive_mutex, returns false when shm_named_recursive_mutex
   //!is already locked, returns true when success.
   //!Throws interprocess_exception if a severe error is found.
   bool try_lock();

   //!Tries to lock the shm_named_recursive_mutex until time abs_time,
   //!Returns false when timeout expires, returns true when locks.
   //!Throws interprocess_exception if a severe error is found
   bool timed_lock(const boost::posix_time::ptime &abs_time);

   //!Erases a named recursive mutex
   //!from the system
   static bool remove(const char *name);

   /// @cond
   private:
   friend class interprocess_tester;
   void dont_close_on_destruction();

   interprocess_recursive_mutex *mutex() const
   {  return static_cast<interprocess_recursive_mutex*>(m_shmem.get_user_address()); }

   managed_open_or_create_impl<shared_memory_object> m_shmem;
   typedef named_creation_functor<interprocess_recursive_mutex> construct_func_t;
   /// @endcond
};

inline shm_named_recursive_mutex::~shm_named_recursive_mutex()
{}

inline void shm_named_recursive_mutex::dont_close_on_destruction()
{  interprocess_tester::dont_close_on_destruction(m_shmem);  }

inline shm_named_recursive_mutex::shm_named_recursive_mutex(create_only_t, const char *name, const permissions &perm)
   :  m_shmem  (create_only
               ,name
               ,sizeof(interprocess_recursive_mutex) +
                  managed_open_or_create_impl<shared_memory_object>::
                     ManagedOpenOrCreateUserOffset
               ,read_write
               ,0
               ,construct_func_t(DoCreate)
               ,perm)
{}

inline shm_named_recursive_mutex::shm_named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm)
   :  m_shmem  (open_or_create
               ,name
               ,sizeof(interprocess_recursive_mutex) +
                  managed_open_or_create_impl<shared_memory_object>::
                     ManagedOpenOrCreateUserOffset
               ,read_write
               ,0
               ,construct_func_t(DoOpenOrCreate)
               ,perm)
{}

inline shm_named_recursive_mutex::shm_named_recursive_mutex(open_only_t, const char *name)
   :  m_shmem  (open_only
               ,name
               ,read_write
               ,0
               ,construct_func_t(DoOpen))
{}

inline void shm_named_recursive_mutex::lock()
{  this->mutex()->lock();  }

inline void shm_named_recursive_mutex::unlock()
{  this->mutex()->unlock();  }

inline bool shm_named_recursive_mutex::try_lock()
{  return this->mutex()->try_lock();  }

inline bool shm_named_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time)
{
   if(abs_time == boost::posix_time::pos_infin){
      this->lock();
      return true;
   }
   return this->mutex()->timed_lock(abs_time);
}

inline bool shm_named_recursive_mutex::remove(const char *name)
{  return shared_memory_object::remove(name); }

}  //namespace ipcdetail {
}  //namespace interprocess {
}  //namespace boost {

#include <boost/interprocess/detail/config_end.hpp>

#endif   //BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP


text:
import sys
import instance

S,V,P,Q,T = map(int, sys.argv[1:])
instance.instance_generator(S,V,P,Q,T)


text:
package hadoop;

import java.io.IOException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import oracle.kv.Key;
import oracle.kv.hadoop.KVInputFormat;

/**
 * A simple example demonstrating how to use the Oracle NoSQL DB Hadoop
 * oracle.kv.hadoop.KVInputFormat class to read data from NoSQL Database in a
 * Map/Reduce job and count the number of records for each major key in the
 * store.
 *
 * The map() function is passed the Key and Value for each record in the KV
 * Store and outputs k/v pairs containing the major path components as the
 * output key and a value of 1.  The reduce step sums the values for each of
 * the records with the same key.  This M/R task is similar to the ubiquitous
 * Hadoop Map/Reduce WordCount example.
 *
 * The KV Keys passed to the Map function are in the canonical format described
 * in the javadoc for the oracle.kv.Key.toString() method.
 *
 * The KVInputFormat and related classes are located in the lib/kvclient.jar
 * file so this must be included in the Hadoop classpath at runtime.
 *
 * The arguments to the program are the kvstore name, the helperHost:port pair,
 * the HDFS output path and optionally, the login file path.
 *
 * For example, if you build this class (and its subclasses) and put it into
 * myjar.jar, you can invoke with a command similar to this:

 *

 * export HADOOP_CLASSPATH=...:KVHOME/lib/kvclient.jar
 * bin/hadoop jar myjar.jar hadoop.CountMinorKeys \
 *            -libjars KVHOME/lib/kvclient.jar \
 *            mystore myhost:myport /myHDFSoutputdir [mySecurityFilePath]
 *

 *
 * If you are accessing a secured KV Store using Oracle Wallet, additional
 * Oracle PKI jars obtained from EE package need to be added to the class
 * path. The local login file path needs to be specified as the program
 * argument. See example below:
 *
 *

 * export HADOOP_CLASSPATH=...:KVEEHOME/lib/kvclient.jar:\
 * KVEEHOME/lib/oraclepki.jar
 * export LIBJARS=KVEEHOME/lib/kvclient.jar,KVEEHOME/lib/oraclepki.jar,\
 * KVEEHOME/lib/osdt_cert.jar,KVEEHOME/lib/osdt_core.jar
 *
 * bin/hadoop jar myjar.jar hadoop.CountMinorKeys \
 *            -libjars ${LIBJARS} \
 *            mystore myhost:myport /myHDFSoutputdir mySecurityFilePath
 *

 */
public class CountMinorKeys extends Configured implements Tool {

    public static class Map
        extends Mapper<Text, Text, Text, IntWritable> {

        private Text word = new Text();
        private final static IntWritable one = new IntWritable(1);

        @Override
        public void map(Text keyArg, Text valueArg, Context context)
            throws IOException, InterruptedException {

            /*
             * keyArg is in the NoSQL Databse canonical Key format described in
             * the Key.toString() method's javadoc.
             *
             * The Output is the NoSQL Database record's Major Key as the
             * Map/Reduce key and 1 as the Map/Reduce value.
             */
            Key key = Key.fromString(keyArg.toString());
            /* Convert back to canonical format, but only use the major path. */
            word.set(Key.createKey(key.getMajorPath()).toString());
            context.write(word, one);
        }
    }

    public static class Reduce
        extends IntSumReducer<Text> {
    }

    @Override
    public int run(String[] args)
        throws Exception {

        @SuppressWarnings("deprecation")
        Job job = new Job(getConf());
        job.setJarByClass(CountMinorKeys.class);
        job.setJobName("Count Minor Keys");

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);

        job.setInputFormatClass(KVInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        KVInputFormat.setKVStoreName(args[0]);
        KVInputFormat.setKVHelperHosts(new String[] { args[1] });
        FileOutputFormat.setOutputPath(job, new Path(args[2]));

        /*
         * Load KVLoginFile if specified, otherwise try to load via reading
         * system property of oracle.kv.login.
         */
        if (args.length >= 4) {
            KVInputFormat.setKVSecurity(args[3]);
        }

        boolean success = job.waitForCompletion(true);
        return success ? 0 : 1;
    }

    public static void main(String[] args)
        throws Exception {

        int ret = ToolRunner.run(new CountMinorKeys(), args);
        System.exit(ret);
    }
}


text:
package landmaster.landcore.api;

import java.util.*;

import com.google.common.base.*;

import landmaster.landcore.api.packet.*;
import landmaster.landcore.net.*;
import net.minecraft.block.state.*;
import net.minecraft.block.state.pattern.*;
import net.minecraft.entity.*;
import net.minecraft.entity.player.*;
import net.minecraft.init.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;
import net.minecraft.util.*;
import net.minecraft.util.math.*;
import net.minecraft.world.*;
import net.minecraft.world.gen.feature.*;

public class Tools {
	public static ResourceLocation suffix(ResourceLocation original, Object suffix) {
		return new ResourceLocation(original.getNamespace(), original.getPath()+suffix);
	}

	public static ResourceLocation underscoreSuffix(ResourceLocation original, Object suffix) {
		return suffix(original, "_"+suffix);
	}

	public static boolean canTeleportTo(EntityPlayer player, Coord4D dest) {
		if (dest == null || dest.world() == null) return false;
		for (int i=1; i<=2; ++i) {
			if (dest.add(0, i, 0).blockState().getCollisionBoundingBox(dest.world(), dest.pos()) != null) {
				return false;
			}
		}
		return true;
	}

	public static NBTTagCompound getTagSafe(ItemStack is, boolean set) {
		if (is.isEmpty()) {
			return new NBTTagCompound();
		}
		NBTTagCompound nbt = is.getTagCompound();
		if (nbt == null) {
			nbt = new NBTTagCompound();
			if (set) is.setTagCompound(nbt);
		}
		return nbt;
	}

	// thanks Mekanism
	public static void teleportPlayerTo(EntityPlayerMP player, Coord4D coord) {
		if (player.dimension != coord.dimensionId) {
			player.changeDimension(coord.dimensionId, (world, entity, yaw) -> entity.setPositionAndUpdate(coord.xCoord +0.5, coord.yCoord +1, coord.zCoord +0.5));
		} else {
			player.setPositionAndUpdate(coord.xCoord +0.5, coord.yCoord +1, coord.zCoord +0.5);
		}
		player.world.updateEntityWithOptionalForce(player, true);
	}

	public static void teleportEntityTo(Entity entity, Coord4D coord) {
		if(entity.world.provider.getDimension() != coord.dimensionId) {
			entity.changeDimension(coord.dimensionId, (world, entity2, yaw) -> entity2.setPositionAndUpdate(coord.xCoord +0.5, coord.yCoord +1, coord.zCoord +0.5));
		} else {
			entity.setPositionAndUpdate(coord.xCoord +0.5, coord.yCoord +1, coord.zCoord +0.5);
			PacketHandler.INSTANCE.sendToAllTracking(new PacketEntityMove(entity.getEntityId(), entity.getPositionVector()), entity);
		}
	}

	public static void generateOre(IBlockState ore, World world, Random random, int x, int z, int minY, int maxY, int minSize, int maxSize, int chances) {
		Tools.generateOre(ore, world, BlockMatcher.forBlock(Blocks.STONE), random, x, z, minY, maxY, minSize, maxSize, chances);
	}

	public static void generateOre(IBlockState ore, World world, Predicate<IBlockState> matcher, Random random, int x, int z, int minY, int maxY, int minSize, int maxSize, int chances) {
		int deltaY = maxY - minY;
		int deltaSize = maxSize - minSize;
		for (int i = 0; i < chances; i++) {
			BlockPos pos = new BlockPos(x + random.nextInt(16), minY + random.nextInt(deltaY), z + random.nextInt(16));
			WorldGenMinable generator = new WorldGenMinable(ore, minSize + random.nextInt(deltaSize+1), matcher);
			generator.generate(world, random, pos);
		}
	}
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://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.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(name, inputConfig, outputConfig) {
  // [START automl_v1_generated_PredictionService_BatchPredict_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. Name of the model requested to serve the batch prediction.
   */
  // const name = 'abc123'
  /**
   *  Required. The input configuration for batch prediction.
   */
  // const inputConfig = {}
  /**
   *  Required. The Configuration specifying where output predictions should
   *  be written.
   */
  // const outputConfig = {}
  /**
   *  Additional domain-specific parameters for the predictions, any string must
   *  be up to 25000 characters long.
   *  AutoML Natural Language Classification
   *  `score_threshold`
   *  : (float) A value from 0.0 to 1.0. When the model
   *    makes predictions for a text snippet, it will only produce results
   *    that have at least this confidence score. The default is 0.5.
   *  AutoML Vision Classification
   *  `score_threshold`
   *  : (float) A value from 0.0 to 1.0. When the model
   *    makes predictions for an image, it will only produce results that
   *    have at least this confidence score. The default is 0.5.
   *  AutoML Vision Object Detection
   *  `score_threshold`
   *  : (float) When Model detects objects on the image,
   *    it will only produce bounding boxes which have at least this
   *    confidence score. Value in 0 to 1 range, default is 0.5.
   *  `max_bounding_box_count`
   *  : (int64) The maximum number of bounding
   *    boxes returned per image. The default is 100, the
   *    number of bounding boxes returned might be limited by the server.
   *  AutoML Video Intelligence Classification
   *  `score_threshold`
   *  : (float) A value from 0.0 to 1.0. When the model
   *    makes predictions for a video, it will only produce results that
   *    have at least this confidence score. The default is 0.5.
   *  `segment_classification`
   *  : (boolean) Set to true to request
   *    segment-level classification. AutoML Video Intelligence returns
   *    labels and their confidence scores for the entire segment of the
   *    video that user specified in the request configuration.
   *    The default is true.
   *  `shot_classification`
   *  : (boolean) Set to true to request shot-level
   *    classification. AutoML Video Intelligence determines the boundaries
   *    for each camera shot in the entire segment of the video that user
   *    specified in the request configuration. AutoML Video Intelligence
   *    then returns labels and their confidence scores for each detected
   *    shot, along with the start and end time of the shot.
   *    The default is false.
   *    WARNING: Model evaluation is not done for this classification type,
   *    the quality of it depends on training data, but there are no metrics
   *    provided to describe that quality.
   *  `1s_interval_classification`
   *  : (boolean) Set to true to request
   *    classification for a video at one-second intervals. AutoML Video
   *    Intelligence returns labels and their confidence scores for each
   *    second of the entire segment of the video that user specified in the
   *    request configuration. The default is false.
   *    WARNING: Model evaluation is not done for this classification
   *    type, the quality of it depends on training data, but there are no
   *    metrics provided to describe that quality.
   *  AutoML Video Intelligence Object Tracking
   *  `score_threshold`
   *  : (float) When Model detects objects on video frames,
   *    it will only produce bounding boxes which have at least this
   *    confidence score. Value in 0 to 1 range, default is 0.5.
   *  `max_bounding_box_count`
   *  : (int64) The maximum number of bounding
   *    boxes returned per image. The default is 100, the
   *    number of bounding boxes returned might be limited by the server.
   *  `min_bounding_box_size`
   *  : (float) Only bounding boxes with shortest edge
   *    at least that long as a relative value of video frame size are
   *    returned. Value in 0 to 1 range. Default is 0.
   */
  // const params = 1234

  // Imports the Automl library
  const {PredictionServiceClient} = require('@google-cloud/automl').v1;

  // Instantiates a client
  const automlClient = new PredictionServiceClient();

  async function callBatchPredict() {
    // Construct request
    const request = {
      name,
      inputConfig,
      outputConfig,
    };

    // Run request
    const [operation] = await automlClient.batchPredict(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callBatchPredict();
  // [END automl_v1_generated_PredictionService_BatchPredict_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
// .NAME vtkMinimalStandardRandomSequence - Park and Miller Sequence of pseudo random numbers
// .SECTION Description
// vtkMinimalStandardRandomSequence is a sequence of statistically independent
// pseudo random numbers uniformly distributed  between 0.0 and 1.0.
//
// The sequence is generated by a prime modulus multiplicative linear
// congruential generator (PMMLCG) or "Lehmer generator" with multiplier 16807
// and prime modulus 2^(31)-1. The authors calls it
// "minimal standard random number generator"
//
// ref: "Random Number Generators: Good Ones are Hard to Find,"
// by Stephen K. Park and Keith W. Miller in Communications of the ACM,
// 31, 10 (Oct. 1988) pp. 1192-1201.
// Code is at page 1195, "Integer version 2"
//
// Correctness test is described in first column, page 1195:
// A seed of 1 at step 1 should give a seed of 1043618065 at step 10001.

#ifndef __vtkMinimalStandardRandomSequence_h
#define __vtkMinimalStandardRandomSequence_h

#include "vtkCommonCoreExport.h" // For export macro
#include "vtkRandomSequence.h"

class VTKCOMMONCORE_EXPORT vtkMinimalStandardRandomSequence
  : public vtkRandomSequence
{
public:
  vtkTypeMacro(vtkMinimalStandardRandomSequence,vtkRandomSequence);
  void PrintSelf(ostream& os, vtkIndent indent);

  static vtkMinimalStandardRandomSequence* New();

  // Description:
  // Set the seed of the random sequence.
  // The following pre-condition is stated page 1197, second column:
  // valid_seed: value>=1 && value<=2147483646
  // 2147483646=(2^31)-2
  // This method does not have this criterium as a pre-condition (ie it will
  // not fail if an incorrect seed value is passed) but the value is silently
  // changed to fit in the valid range [1,2147483646].
  // 2147483646 is added to a null or negative value.
  // 2147483647 is changed to be 1 (ie 2147483646 is substracted).
  // Implementation note: it also performs 3 calls to Next() to avoid the
  // bad property that the first random number is proportional to the seed
  // value.
  void SetSeed(int value);

  // Description:
  // Set the seed of the random sequence. There is no extra internal
  // ajustment. Only useful for writing correctness test.
  // The following pre-condition is stated page 1197, second column
  // 2147483646=(2^31)-2
  // This method does not have this criterium as a pre-condition (ie it will
  // not fail if an incorrect seed value is passed) but the value is silently
  // changed to fit in the valid range [1,2147483646].
  // 2147483646 is added to a null or negative value.
  // 2147483647 is changed to be 1 (ie 2147483646 is substracted).
  void SetSeedOnly(int value);

  // Description:
  // Get the seed of the random sequence.
  // Only useful for writing correctness test.
  int GetSeed();

  // Description:
  // Current value
  // \post unit_range: result>=0.0 && result<=1.0
  virtual double GetValue();

  // Description:
  // Move to the next number in the random sequence.
  virtual void Next();

  // Description:
  // Convenient method to return a value in a specific range from the
  // range [0,1. There is an initial implementation that can be overridden
  // by a subclass.
  // There is no pre-condition on the range:
  // - it can be in increasing order: rangeMin<rangeMax
  // - it can be empty: rangeMin=rangeMax
  // - it can be in decreasing order: rangeMin>rangeMax
  // \post result_in_range:
  // (rangeMin<=rangeMax && result>=rangeMin && result<=rangeMax)
  // || (rangeMax<=rangeMin && result>=rangeMax && result<=rangeMin)
  virtual double GetRangeValue(double rangeMin,
                               double rangeMax);

protected:
  vtkMinimalStandardRandomSequence();
  virtual ~vtkMinimalStandardRandomSequence();
  int Seed;
private:
  vtkMinimalStandardRandomSequence(const vtkMinimalStandardRandomSequence&);  // Not implemented.
  void operator=(const vtkMinimalStandardRandomSequence&);  // Not implemented.
};

#endif // #ifndef __vtkMinimalStandardRandomSequence_h


text:
Starting point for working on SeedCode projects. This includes SeedCode's dev environment.

Core Dev Software
=======================

Download and install the following applications
------------

**VirtualBox:**
https://www.virtualbox.org/wiki/Downloads

**Vagrant:**
https://www.vagrantup.com/downloads.html

**SourceTree:**
https://www.sourcetreeapp.com

**MonoSnap (for screencasts):**
https://www.monosnap.com

Configuration and cleanup using the terminal
------------
**Launch Terminal app:**

**Create a global git ignore file:**
```shell
git config --global core.excludesfile ~/.gitignore_global
touch ~/.gitignore_global
nano ~/.gitignore_global
```

Then paste the following:
```
## Begin ignore list ##
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

# Vagrant generated files #
######################
.vagrant
## End ignore list ##
```

press "ctl" + "x" to exit, then "y" to save and "enter" to confirm.

**Add user email and name to git config file:**
```shell
nano ~/.gitconfig
```

Fill in name and email. When done "ctrl" + "x" to exit, then "y" to save and "enter" to confirm.

Once you have the project repo URL from Kiln add the repo to SourceTree and pull the project:

Click "New Repository"

Then "Clone from URL"

Paste in the repo URL and choose a folder on your computer to clone the repo to

Then click "Clone"

Navigate back to the Terminal App and excecute the following commands:

**Vagrant plugins:**
```shell
vagrant plugin install vagrant-hostsupdater
vagrant plugin install vagrant-vbguest
```

**How to start vagrant:**

Navigate to your project repo, then navigate to the vagrant folder within that. Then run the command vagrant up...
```shell
cd yourproject/vagrant
vagrant up
```
This may take several minutes as it will download the base image and install everything. This will only take this long the first time.

If you need to activate SSL for the development environment run the following commands from the context of the vagrant folder replace the email and domain placeholders with your specific data...
```shell
vagrant ssh
cd /vagrant
grunt ssl:YourEmail:YourDomain
```

Once complete you can exit out of your vagrant ssh session by executing the command
```shell
exit
```

Vagrant can be stopped by typing
```shell
vagrant halt
```

To start vagrant again (and the dev environment) simply navigate to the vagrant folder in the terminal and type
```shell
vagrant up
```


text:
class AddUpcToSpreeVariants < ActiveRecord::Migration
  def change
    add_column :spree_variants, :upc, :string
  end
end


text:
package org.ojalgo.matrix;

import org.ojalgo.TestUtils;
import org.ojalgo.matrix.decomposition.SingularValue;
import org.ojalgo.matrix.store.MatrixStore;
import org.ojalgo.matrix.store.PhysicalStore;
import org.ojalgo.type.context.NumberContext;

/**
 * Gilbert Strang, Linear Algebra and its Applications III, Example 1 in Appendix A
 *
 * @author apete
 */
public class SimpleSingularValueCase extends BasicMatrixTest {

    public static BigMatrix getMatrixD() {
        final BigMatrix tmpMtrx = BigMatrix.FACTORY.rows(new double[][] { { 2.0, 0.0 }, { 0.0, 3.0 }, { 0.0, 0.0 } });
        return tmpMtrx.enforce(DEFINITION);
    }

    public static BigMatrix getMatrixQ1() {
        final BigMatrix tmpMtrx = BigMatrix.FACTORY.rows(new double[][] { { 1.0, 0.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, 1.0 } });
        return tmpMtrx.enforce(DEFINITION);
    }

    public static BigMatrix getMatrixQ2() {
        final BigMatrix tmpMtrx = BigMatrix.FACTORY.rows(new double[][] { { 1.0, 0.0 }, { 0.0, 1.0 } });
        return tmpMtrx.enforce(DEFINITION);
    }

    public static BigMatrix getOriginal() {
        final BigMatrix tmpMtrx = BigMatrix.FACTORY.rows(new double[][] { { 2.0, 0.0 }, { 0.0, -3.0 }, { 0.0, 0.0 } });
        return tmpMtrx.enforce(DEFINITION);
    }

    public SimpleSingularValueCase() {
        super();
    }

    public SimpleSingularValueCase(final String arg0) {
        super(arg0);
    }

    @Override
    public void testData() {

        final PhysicalStore<Double> tmpExp = SimpleSingularValueCase.getOriginal().toPrimitiveStore()
                .multiply(SimpleSingularValueCase.getMatrixQ2().toPrimitiveStore()).copy();
        final PhysicalStore<Double> tmpAct = SimpleSingularValueCase.getMatrixD().toPrimitiveStore()
                .multiplyLeft(SimpleSingularValueCase.getMatrixQ1().toPrimitiveStore()).copy();

        TestUtils.assertEquals(tmpExp, tmpAct, EVALUATION);
    }

    @Override
    public void testProblem() {

        final MatrixStore<Double> tmpA = SimpleSingularValueCase.getOriginal().toPrimitiveStore();

        final SingularValue<Double> tmpSVD = SingularValue.make(tmpA);
        tmpSVD.decompose(tmpA);

        tmpSVD.equals(tmpA, EVALUATION);
    }

    @Override
    protected void setUp() throws Exception {

        DEFINITION = new NumberContext(7, 1);
        EVALUATION = new NumberContext(7, 9);

        myBigAA = SimpleSingularValueCase.getMatrixQ1();
        myBigAX = SimpleSingularValueCase.getMatrixD();
        myBigAB = SimpleSingularValueCase.getOriginal();

        myBigI = BasicMatrixTest.getIdentity(myBigAA.countRows(), myBigAA.countColumns(), DEFINITION);
        myBigSafe = BasicMatrixTest.getSafe(myBigAA.countRows(), myBigAA.countColumns(), DEFINITION);

        super.setUp();
    }

}


text:
package commands.etc;

import commands.Command;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import utils.MSGS;
import utils.STATICS;

import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

/**
 * Created by zekro on 01.07.2017 / 10:50
 * DiscordBot.commands.etc
 * dev.zekro.de - github.zekro.de
 * © zekro 2017
 */

public class Bug implements Command {

    public static User AUTHOR;
    public static Message MESSAGE;
    public static EmbedBuilder FINAL_MESSAGE;
    public static TextChannel CHANNEL;
    public static Timer TIMER = new Timer();

    public static void sendConfMessage() {
        MESSAGE.getTextChannel().sendMessage(MSGS.success().setDescription("Submit sucesfully send!").build()).queue();
    }

    @Override
    public boolean called(String[] args, MessageReceivedEvent event) {
        return false;
    }

    @Override
    public void action(String[] args, MessageReceivedEvent event) throws ParseException, IOException {

        try {

            CHANNEL = event.getJDA().getGuildById("307084334198816769").getTextChannelById("330636155668135936");

        } catch (Exception e) {

            if (args.length < 1) {
                event.getTextChannel().sendMessage(new EmbedBuilder().setDescription(
                        "If you want to submit a bug or a suggestion, please use the public **[google sheet](https://s.zekro.de/botsubs)**."
                ).build()).queue();
                return;
            }
            event.getTextChannel().sendMessage(MSGS.error().setDescription(
                    "Sorry, the expandet version of this command is only available on the public version of the bot!\n\n" +
                    "If you want to submit a bug or a suggestion, please use the public **[google sheet](https://s.zekro.de/botsubs)**."
            ).build()).queue();
            return;
        }

        if (args.length < 1)
            event.getTextChannel().sendMessage(new EmbedBuilder().setDescription(
                    "You can submit a bug report or suggestion right with the command using like this:\n" +
                    "```-bug <сообщение>```\n\n" +
                    "You can use following modifiers to embed better details:\n" +
                    "```-bug <title>\n" +
                    "<bug/gussestion>\n" +
                    "<сообщение>```\n\n" +
                    "Otherwise you can also just use the public **[google sheet](https://s.zekro.de/botsubs)** to submit a bug or suggestion."
            ).build()).queue();
        else {

            String title = "Bug report / Suggestion";
            String type = "unspecified";
            String message = "";

            String argsString = Arrays.stream(args).collect(Collectors.joining(" "));

            title = argsString.split("\n").length > 3 ? argsString.split("\n")[0] : title;
            type = argsString.split("\n").length > 3 ? argsString.split("\n")[1] : type;
            message = argsString.split("\n").length > 3 ? Arrays.stream(argsString.split("\n")).skip(2).collect(Collectors.joining("\n")) : argsString;

            MESSAGE = event.getTextChannel().sendMessage(new EmbedBuilder()
                    .setTitle("MESSAGE PREVIEW", null)
                    .addField("Title", title, true)
                    .addField("Type", type, true)
                    .addField("Message", message, false)
                    .setFooter("Click on the reaction \uD83D\uDC4D to send the message. Else just dont klick ;)", null)
                    .build()
            ).complete();
            MESSAGE.addReaction("\uD83D\uDC4D").queue();
            AUTHOR = event.getMessage().getAuthor();

            FINAL_MESSAGE = new EmbedBuilder()
                    .addField("Message ID", event.getMessage().getId(), false)
                    .addField("Author", event.getAuthor().getName(), false)
                    .addField("Title", title, true)
                    .addField("Type", type, true)
                    .addField("Message", message, false);

            TIMER = new Timer();
            TIMER.schedule(new TimerTask() {
                @Override
                public void run() {
                    AUTHOR = null;
                    MESSAGE = null;
                    FINAL_MESSAGE = null;
                    CHANNEL = null;
                    TIMER = null;
                    event.getTextChannel().sendMessage(new EmbedBuilder().setDescription("Confirmation time expired.").build()).queue();
                }
            }, 20000);

        }

    }

    @Override
    public void executed(boolean success, MessageReceivedEvent event) {

    }

    @Override
    public String help() {
        return null;
    }

    @Override
    public String description() {
        return "Send a bug report or a suggestion";
    }

    @Override
    public String commandType() {
        return STATICS.CMDTYPE.etc;
    }

    @Override
    public int permission() {
        return 1;
    }
}


text:
<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>
	<groupId>za.co.paulscott.musicgraph</groupId>
	<artifactId>MusicGraph</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>MusicGraph</name>

	<properties>

		<!-- Generic properties -->
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

		<!-- Spring -->
		<spring-framework.version>3.2.3.RELEASE</spring-framework.version>

		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>

		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>

		<!-- Test -->
		<junit.version>4.11</junit.version>

		<spring-data-neo4j.version>2.3.2.RELEASE</spring-data-neo4j.version>

	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- JavaConfig needs this library -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Neo4j -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
			<version>1.0.1.Final</version>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j-aspects</artifactId>
            <version>${spring-data-neo4j.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate.javax.persistence</groupId>
                    <artifactId>hibernate-jpa-2.0-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-neo4j-rest</artifactId>
			<version>${spring-data-neo4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>aspectj-maven-plugin</artifactId>
			<version>1.2</version>
			<type>maven-plugin</type>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-maven-release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</repository>
		<repository>
			<id>spring-maven-snapshot</id>
			<name>Spring Maven Snapshot Repository</name>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
			<url>http://maven.springframework.org/snapshot</url>
		</repository>
		<repository>
			<id>spring-maven-milestone</id>
			<name>Spring Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</repository>
		<repository>
			<id>neo4j-release-repository</id>
			<name>Neo4j Maven 2 release repository</name>
			<url>http://m2.neo4j.org/releases</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>neo4j-snapshot-repository</id>
			<name>Neo4j Maven 2 snapshot repository</name>
			<url>http://m2.neo4j.org/snapshots</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
			<releases>
				<enabled>false</enabled>
			</releases>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>spring-maven-release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</pluginRepository>
		<pluginRepository>
			<id>spring-maven-milestone</id>
			<name>Spring Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</pluginRepository>
	</pluginRepositories>

	<build>
		<plugins>
			<plugin>
				<!-- Must use java 1.5 or higher for annotations -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>

			<plugin>
				<!-- IntelliJ Idea Support -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-idea-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<dependenciesAsLibraries>true</dependenciesAsLibraries>
				</configuration>
			</plugin>

			<plugin>
				<!-- Execute the main class -->
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2</version>
				<executions>
					<execution>
						<goals>
							<goal>exec</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<mainClass>za.co.paulscott.musicgraph.core.App</mainClass>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<finalName>musicgraph-${project.version}</finalName>
					<appendAssemblyId>false</appendAssemblyId>
					<attach>false</attach>
					<archive>
						<manifest>
							<mainClass>za.co.paulscott.musicgraph.core.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id> <!-- this is used for inheritance merges -->
						<phase>package</phase> <!-- bind to the packaging phase -->
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<executions>
					<execution>
						<phase>initialize</phase>
						<goals>
							<goal>resources</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>

	<profiles>
		<profile>
			<id>plain</id>
			<dependencies>
				<dependency>
					<groupId>org.springframework.data</groupId>
					<artifactId>spring-data-neo4j</artifactId>
					<version>${spring-data-neo4j.version}</version>
				</dependency>
			</dependencies>

			<build>
				<resources>
					<resource>
						<directory>${project.basedir}/src/main/resources/spring/plain</directory>
						<targetPath>${project.build.directory}/classes/spring</targetPath>
						<filtering>true</filtering>
						<includes>
							<include>helloWorldContext.xml</include>
						</includes>
					</resource>
				</resources>
			</build>
		</profile>
		<profile>
			<id>aspects</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>

			<dependencies>
				<dependency>
					<groupId>org.springframework.data</groupId>
					<artifactId>spring-data-neo4j-aspects</artifactId>
					<version>${spring-data-neo4j.version}</version>
				</dependency>
			</dependencies>

			<build>
				<plugins>
					<plugin>
						<!-- required to resolve aspectj-enhanced class features -->
						<groupId>org.codehaus.mojo</groupId>
						<artifactId>aspectj-maven-plugin</artifactId>
						<version>1.2</version>
						<configuration>
							<outxml>true</outxml>
							<aspectLibraries>
								<aspectLibrary>
									<groupId>org.springframework</groupId>
									<artifactId>spring-aspects</artifactId>
								</aspectLibrary>
								<aspectLibrary>
									<groupId>org.springframework.data</groupId>
									<artifactId>spring-data-neo4j-aspects</artifactId>
								</aspectLibrary>
							</aspectLibraries>
							<source>1.6</source>
							<target>1.6</target>
						</configuration>
						<executions>
							<execution>
								<goals>
									<goal>compile</goal>
									<goal>test-compile</goal>
								</goals>
							</execution>
						</executions>
						<dependencies>
							<dependency>
								<groupId>org.aspectj</groupId>
								<artifactId>aspectjrt</artifactId>
								<version>${aspectj.version}</version>
							</dependency>
							<dependency>
								<groupId>org.aspectj</groupId>
								<artifactId>aspectjtools</artifactId>
								<version>${aspectj.version}</version>
							</dependency>
						</dependencies>
					</plugin>

					<!-- the eclipse plugin interacts with the aspectj-maven-plugin BUT
						ONLY if the ajdtVersion config value is set (remove it and it won't) -->
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-eclipse-plugin</artifactId>
						<version>2.8</version>
						<configuration>
							<!-- The ajdtVersion configuration parameter is optional. The valid
								values are none, 1.4, and 1.5. none indicates that AJDT should not be enabled
								even though Aspectj is enabled in maven. 1.4 generates the org.eclipse.ajdt.ui.prefs
								file in the .settings directory. 1.5 (or later) includes the configuration
								into the .classpath file and is the default value. -->
							<ajdtVersion>1.5</ajdtVersion>
							<additionalProjectnatures>
								<projectnature>org.eclipse.ajdt.ui.ajnature</projectnature>
								<projectnature>org.eclipse.jdt.core.javanature</projectnature>
								<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
							</additionalProjectnatures>
						</configuration>
					</plugin>
				</plugins>
				<resources>
					<resource>
						<directory>${project.basedir}/src/main/resources/spring/aspects</directory>
						<targetPath>${project.build.directory}/classes/spring</targetPath>
						<filtering>true</filtering>
						<includes>
							<include>musicgraphContext.xml</include>
						</includes>
					</resource>
				</resources>
			</build>
		</profile>
	</profiles>

</project>


text:
  <modal-close></modal-close>

Edit {{isStrategy === true ? 'Strategy' : 'Pipeline'}} JSON

          The JSON below represents the {{isStrategy === true ? 'strategy' : 'pipeline'}} configuration in its persisted state.
          You can change it here or use this to quickly copy a {{isStrategy === true ? 'strategy' : 'pipeline'}}.

    <form role="form" name="form" class="form-horizontal">

        <textarea class="code form-control" rows=20 ng-model="command.pipelineJSON"></textarea>

    </form>

          Note: Clicking "Update {{isStrategy === true ? 'Strategy' : 'Pipeline'}}" below will not save your changes to the server - it only
          updates the configuration within the browser, so you'll want to verify your changes and click "Save Changes"
          when you're ready.

        Error: {{command.errorMessage}}

    <button class="btn btn-default" ng-click="editPipelineJsonModalCtrl.cancel()">Cancel</button>
    <button class="btn btn-primary"
            ng-click="editPipelineJsonModalCtrl.updatePipeline()">
       Update {{isStrategy === true ? 'Strategy' : 'Pipeline'}}
    </button>


text:
package org.ofbiz.entity.condition;

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

import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericModelException;
import org.ofbiz.entity.config.model.Datasource;
import org.ofbiz.entity.model.ModelEntity;

/**
 *
Encapsulates SQL expressions used for where clause snippets.
 *  NOTE: This is UNSAFE and BREAKS the idea behind the Entity Engine where
 *  you avoid directly specifying SQL. So, KEEP IT MINIMAL and preferably replace
 *  it when the feature you are getting at is implemented in a more automatic way for you.

 *
 *
By minimal I mean use this in conjunction with other EntityConditions like the
 *  EntityExpr, EntityConditionList and EntityFieldMap objects which more cleanly
 *  encapsulate where conditions and don't require you to directly write SQL.

 *
 */
@SuppressWarnings("serial")
public final class EntityWhereString extends EntityCondition {

    protected final String sqlString;

    public EntityWhereString(String sqlString) {
        this.sqlString = sqlString;
    }

    @Override
    public boolean isEmpty() {
        return UtilValidate.isEmpty(sqlString);
    }

    @Override
    public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
        return sqlString;
    }

    @Override
    public void checkCondition(ModelEntity modelEntity) throws GenericModelException {// no nothing, this is always assumed to be fine... could do funky SQL syntax checking, but hey this is a HACK anyway
    }

    @Override
    public boolean entityMatches(GenericEntity entity) {
        throw new UnsupportedOperationException("Cannot do entityMatches on a WhereString, ie no SQL evaluation in EE; Where String is: " + sqlString);
    }

    @Override
    public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
        throw new UnsupportedOperationException("Cannot do mapMatches on a WhereString, ie no SQL evaluation in EE; Where String is: " + sqlString);
    }

    public String getWhereString() {
        return sqlString;
    }

    @Override
    public EntityCondition freeze() {
        return this;
    }

    @Override
    public void visit(EntityConditionVisitor visitor) {
        visitor.acceptEntityWhereString(this);
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof EntityWhereString)) return false;
        EntityWhereString other = (EntityWhereString) obj;
        return equals(sqlString, other.sqlString);
    }

    @Override
    public int hashCode() {
        return hashCode(sqlString);
    }
}


text:
import { Device } from './..';
import { RootDescription } from './../root-descriptions/RootDescription';

/**
 * Maps a root description to a device.
 */
export function mapFromRootDescription(rootDescription: RootDescription): Device | null {
    if (rootDescription.macAddress === undefined) {
        return null;
    }

    return new Device(
        rootDescription.remoteAddress,
        parsePortFromPresentationUrl(rootDescription.presentationUrl),
        rootDescription.macAddress,
        rootDescription.friendlyName,
        rootDescription.modelName,
        rootDescription.modelDescription,
        rootDescription.modelNumber,
        rootDescription.presentationUrl
    );
}

const portFromPresentationUrlRegExp = /:(\d+)\/?$/i;

function parsePortFromPresentationUrl(presentationUrl: string | undefined): number | undefined {
    if (presentationUrl === undefined) {
        return undefined;
    }

    const portMatch = portFromPresentationUrlRegExp.exec(presentationUrl);
    if (portMatch == null) {
        return undefined;
    }

    return Number(portMatch[1]);
}


text:
package org.gradle.api.plugins;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.type.ArtifactTypeDefinition;
import org.gradle.api.attributes.AttributesSchema;
import org.gradle.api.attributes.LibraryElements;
import org.gradle.api.attributes.Usage;
import org.gradle.api.internal.artifacts.JavaEcosystemSupport;
import org.gradle.api.internal.artifacts.dsl.ComponentMetadataHandlerInternal;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.jvm.internal.JvmPluginServices;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.internal.component.external.model.JavaEcosystemVariantDerivationStrategy;

import javax.inject.Inject;

/**
 * A base plugin for projects working in a JVM world. This plugin
 * will configure the JVM attributes schema, setup resolution rules
 * and create the source set container.
 *
 * @since 6.7
 * @see Java plugin reference
 */
public class JvmEcosystemPlugin implements Plugin<Project> {
    private final ObjectFactory objectFactory;
    private final JvmPluginServices jvmPluginServices;
    private final SourceSetContainer sourceSets;

    @Inject
    public JvmEcosystemPlugin(ObjectFactory objectFactory, JvmPluginServices jvmPluginServices, SourceSetContainer sourceSets) {
        this.objectFactory = objectFactory;
        this.jvmPluginServices = jvmPluginServices;
        this.sourceSets = sourceSets;
    }

    @Override
    public void apply(Project project) {
        ProjectInternal p = (ProjectInternal) project;
        project.getExtensions().add(SourceSetContainer.class, "sourceSets", sourceSets);
        configureVariantDerivationStrategy(p);
        configureSchema(p);
        jvmPluginServices.inject(p, sourceSets);
    }

    private void configureVariantDerivationStrategy(ProjectInternal project) {
        ComponentMetadataHandlerInternal metadataHandler = (ComponentMetadataHandlerInternal) project.getDependencies().getComponents();
        metadataHandler.setVariantDerivationStrategy(JavaEcosystemVariantDerivationStrategy.getInstance());
    }

    private void configureSchema(ProjectInternal project) {
        AttributesSchema attributesSchema = project.getDependencies().getAttributesSchema();
        JavaEcosystemSupport.configureSchema(attributesSchema, objectFactory);
        project.getDependencies().getArtifactTypes().create(ArtifactTypeDefinition.JAR_TYPE).getAttributes()
            .attribute(Usage.USAGE_ATTRIBUTE, objectFactory.named(Usage.class, Usage.JAVA_RUNTIME))
            .attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objectFactory.named(LibraryElements.class, LibraryElements.JAR));
    }

}


text:
package eu.modernmt.processing.tokenizer.impl;

import eu.modernmt.processing.tokenizer.BaseTokenizer;
import eu.modernmt.processing.tokenizer.jflex.annotators.CommonTermsTokenAnnotator;

import java.io.Reader;

public class DefaultTokenizer extends BaseTokenizer {

    public DefaultTokenizer() {
        super.annotators.add(new CommonTermsTokenAnnotator((Reader) null));
    }
}


text:
require './test/test_base.rb'

class RingCentralSdkHelperRequestTest < Test::Unit::TestCase
  def test_setup
    req = RingCentralSdk::REST::Request::Base.new

    assert_equal 'get', req.method
    assert_equal '', req.url
    assert_equal 'Hash', req.params.class.name
    assert_equal 'Hash', req.headers.class.name
    assert_equal '', req.content_type
    assert_equal '', req.body
  end
end