text:
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "NSString+Inlineobjc.h"

@interface NSString_Inlineobjc : XCTestCase

@end

@implementation NSString_Inlineobjc

- (void)setUp
{
	[super setUp];
	// Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
	// Put teardown code here. This method is called after the invocation of each test method in the class.
	[super tearDown];
}

- (void) testPaths
{
	XCTAssertNotNil(NSStringGetStorageDirFullPathForClass([NSString class]), @"ERROR NSStringIsEmpty");
}

- (void) testExample
{
	XCTAssert(NSStringIsEmpty(nil), @"ERROR NSStringIsEmpty");
	XCTAssert(NSStringIsEmpty(@""), @"ERROR NSStringIsEmpty");
	XCTAssert(!NSStringIsEmpty(@"a"), @"ERROR NSStringIsEmpty");

	XCTAssert(NSStringIsNotEmpty(@"a"), @"ERROR NSStringIsNotEmpty");
	XCTAssert(!NSStringIsNotEmpty(nil), @"ERROR NSStringIsNotEmpty");
	XCTAssert(!NSStringIsNotEmpty(@""), @"ERROR NSStringIsNotEmpty");

	XCTAssert(NSStringIsContainesSubstring(@"This is an example", @"This"), @"ERROR NSStringIsContainesSubstring");
	XCTAssert(NSStringIsContainesSubstring(@"This is an example", @"THIS"), @"ERROR NSStringIsContainesSubstring");
	XCTAssert(NSStringIsContainesSubstring(@"This is an example", @"this"), @"ERROR NSStringIsContainesSubstring");

	XCTAssert(!NSStringIsContainesSubstring(nil, nil), @"ERROR NSStringIsContainesSubstring");
	XCTAssert(!NSStringIsContainesSubstring(@"", @""), @"ERROR NSStringIsContainesSubstring");
	XCTAssert(!NSStringIsContainesSubstring(@"This is an example", nil), @"ERROR NSStringIsContainesSubstring");
	XCTAssert(!NSStringIsContainesSubstring(@"This is an example", @""), @"ERROR NSStringIsContainesSubstring");

	XCTAssert(NSStringsAreEqual(@"", @""), @"ERROR NSStringsAreEqual");
	XCTAssert(NSStringsAreEqual(@"a", @"a"), @"ERROR NSStringsAreEqual");
	XCTAssert(!NSStringsAreEqual(@"a", @"b"), @"ERROR NSStringsAreEqual");
	XCTAssert(!NSStringsAreEqual(@"", @"a"), @"ERROR NSStringsAreEqual");
	XCTAssert(!NSStringsAreEqual(@"", nil), @"ERROR NSStringsAreEqual");
	XCTAssert(!NSStringsAreEqual(nil, @""), @"ERROR NSStringsAreEqual");

	XCTAssert(!NSStringIsUppercase(nil), @"ERROR NSStringIsUppercase");
	XCTAssert(!NSStringIsUppercase(@""), @"ERROR NSStringIsUppercase");
	XCTAssert(NSStringIsUppercase(@"ABR"), @"ERROR NSStringIsUppercase");
	XCTAssert(NSStringIsUppercase(@"АБР"), @"ERROR NSStringIsUppercase");
	XCTAssert(!NSStringIsUppercase(@"AbR"), @"ERROR NSStringIsUppercase");
	XCTAssert(!NSStringIsUppercase(@"АРвф"), @"ERROR NSStringIsUppercase");
	XCTAssert(NSStringIsUppercase(@"MÜN"), @"ERROR NSStringIsUppercase");
	XCTAssert(!NSStringIsUppercase(@"MüN"), @"ERROR NSStringIsUppercase");

	XCTAssert(!NSStringIsLowercase(nil), @"ERROR NSStringIsLowercase");
	XCTAssert(!NSStringIsLowercase(@""), @"ERROR NSStringIsLowercase");
	XCTAssert(NSStringIsLowercase(@"abr"), @"ERROR NSStringIsLowercase");
	XCTAssert(NSStringIsLowercase(@"абр"), @"ERROR NSStringIsLowercase");
	XCTAssert(!NSStringIsLowercase(@"aBr"), @"ERROR NSStringIsLowercase");
	XCTAssert(!NSStringIsLowercase(@"абвФ"), @"ERROR NSStringIsLowercase");
	XCTAssert(NSStringIsLowercase(@"mün"), @"ERROR NSStringIsLowercase");
	XCTAssert(!NSStringIsLowercase(@"mÜn"), @"ERROR NSStringIsLowercase");
}

- (void)testPerformanceExample
{
	// This is an example of a performance test case.
	[self measureBlock:^{
		// Put the code you want to measure the time of here.
	}];
}

@end


text:
package com.suscipio_solutions.consecro_mud.Behaviors;
import java.util.Enumeration;

import com.suscipio_solutions.consecro_mud.Areas.interfaces.Area;
import com.suscipio_solutions.consecro_mud.Behaviors.interfaces.Behavior;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Wearable;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.interfaces.Rideable;
import com.suscipio_solutions.consecro_mud.core.interfaces.Rider;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class FasterRecovery extends StdBehavior
{
	@Override public String ID(){return "FasterRecovery";}
	@Override protected int canImproveCode(){return Behavior.CAN_ROOMS|Behavior.CAN_AREAS|Behavior.CAN_ITEMS;}
	protected int burst=0;
	protected int health=0;
	protected int hits=0;
	protected int mana=0;
	protected int move=0;

	@Override
	public String accountForYourself()
	{
		return "faster recovering";
	}

	@Override
	public void setParms(String parameters)
	{
		super.setParms(parameters);
		burst=getVal(parameters,"BURST",0)-1;
		health=getVal(parameters,"HEALTH",0)-1;
		hits=getVal(parameters,"HITS",0)-1;
		mana=getVal(parameters,"MANA",0)-1;
		move=getVal(parameters,"MOVE",0)-1;
	}
	public static int getVal(String text, String key, int defaultValue)
	{
		text=text.toUpperCase();
		key=key.toUpperCase();
		int x=text.indexOf(key);
		while(x>=0)
		{
			if((x==0)||(!Character.isLetter(text.charAt(x-1))))
			{
				while((x<text.length())&&(text.charAt(x)!='=')&&(!Character.isDigit(text.charAt(x))))
					x++;
				if((x<text.length())&&(text.charAt(x)=='='))
				{
					while((x<text.length())&&(!Character.isDigit(text.charAt(x))))
						x++;
					if(x<text.length())
					{
						text=text.substring(x);
						x=0;
						while((x<text.length())&&(Character.isDigit(text.charAt(x))))
							x++;
						return CMath.s_int(text.substring(0,x));
					}
				}
				x=-1;
			}
			else
				x=text.toUpperCase().indexOf(key.toUpperCase(),x+1);
		}
		return defaultValue;
	}

	public void doBe(MOB M, int burst, int health, int hits, int mana, int move)
	{
		if(M==null) return;
		for(int i2=0;i2<burst;i2++)
			M.tick(M,Tickable.TICKID_MOB);
		for(int i2=0;i2<health;i2++)
			CMLib.combat().recoverTick(M);
		if(hits!=0)
		{
			final int oldMana=M.curState().getMana();
			final int oldMove=M.curState().getMovement();
			for(int i2=0;i2<hits;i2++)
				CMLib.combat().recoverTick(M);
			M.curState().setMana(oldMana);
			M.curState().setMovement(oldMove);
		}
		if(mana!=0)
		{
			final int oldHP=M.curState().getHitPoints();
			final int oldMove=M.curState().getMovement();
			for(int i2=0;i2<mana;i2++)
				CMLib.combat().recoverTick(M);
			M.curState().setHitPoints(oldHP);
			M.curState().setMovement(oldMove);
		}
		if(move!=0)
		{
			final int oldMana=M.curState().getMana();
			final int oldHP=M.curState().getHitPoints();
			for(int i2=0;i2<mana;i2++)
				CMLib.combat().recoverTick(M);
			M.curState().setMana(oldMana);
			M.curState().setHitPoints(oldHP);
		}
	}
	public void doBe(Room room, int burst, int health, int hits, int mana, int move)
	{
		if(room==null) return;
		for(int i=0;i<room.numInhabitants();i++)
		{
			final MOB M=room.fetchInhabitant(i);
			if(M!=null)
				doBe(M,burst,health,hits,mana,move);
		}
	}
	public void doBe(Area area, int burst, int health, int hits, int mana, int move)
	{
		if(area==null) return;
		for(final Enumeration r=area.getMetroMap();r.hasMoreElements();)
		{
			final Room R=(Room)r.nextElement();
			doBe(R,burst,health,hits,mana,move);
		}
	}
	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(ticking instanceof Room)
			doBe((Room)ticking,burst,health,hits,mana,move);
		else
		if(ticking instanceof Area)
			doBe((Area)ticking,burst,health,hits,mana,move);
		else
		if(ticking instanceof Rideable)
		{
			Rider R=null;
			for(int r=0;r<((Rideable)ticking).numRiders();r++)
			{
				R=((Rideable)ticking).fetchRider(r);
				if(R instanceof MOB)
					doBe((MOB)R,burst,health,hits,mana,move);
			}
		}
		else
		if(ticking instanceof MOB)
			doBe((MOB)ticking,burst,health,hits,mana,move);
		else
		if(ticking instanceof Item)
		{
			if(CMLib.flags().isGettable((Item)ticking)
			&&(((Item)ticking).owner() instanceof MOB)
			&&(!((Item)ticking).amWearingAt(Wearable.IN_INVENTORY)))
				doBe((MOB)((Item)ticking).owner(),burst,health,hits,mana,move);
			else
			if(!CMLib.flags().isGettable((Item)ticking)
			&&(((Item)ticking).owner() instanceof Room))
				doBe((Room)((Item)ticking).owner(),burst,health,hits,mana,move);
		}
		return true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'minitest/autorun'
require 'notepadqq_api/stubs'

class StubsTest < Minitest::Test

  def test_comparison

    # Different class

    assert_equal NotepadqqApi::Stubs::Notepadqq.new(nil, 7),
             NotepadqqApi::Stubs::Stub.new(nil, 7)

    assert_equal NotepadqqApi::Stubs::Stub.new(nil, 7),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 7)

    assert_equal NotepadqqApi::Stubs::Stub.new(nil, 7),
             NotepadqqApi::Stubs::Stub.new(nil, 7)

    assert_equal NotepadqqApi::Stubs::Notepadqq.new(nil, 7),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 7)

    # Different id

    refute_equal NotepadqqApi::Stubs::Notepadqq.new(nil, 1),
             NotepadqqApi::Stubs::Stub.new(nil, 2)

    refute_equal NotepadqqApi::Stubs::Stub.new(nil, 1),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 2)

    refute_equal NotepadqqApi::Stubs::Stub.new(nil, 1),
             NotepadqqApi::Stubs::Stub.new(nil, 2)

    refute_equal NotepadqqApi::Stubs::Notepadqq.new(nil, 1),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 2)

    # Different channel

    refute_equal NotepadqqApi::Stubs::Notepadqq.new("test", 7),
             NotepadqqApi::Stubs::Stub.new(nil, 7)

    refute_equal NotepadqqApi::Stubs::Stub.new("test", 7),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 7)

    refute_equal NotepadqqApi::Stubs::Stub.new("test", 7),
             NotepadqqApi::Stubs::Stub.new(nil, 7)

    refute_equal NotepadqqApi::Stubs::Notepadqq.new("test", 7),
             NotepadqqApi::Stubs::Notepadqq.new(nil, 7)

  end

end


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns
    -fno-warn-name-shadowing
    -fno-warn-unused-imports
    -fno-warn-unused-matches #-}

{-
  Copyright 2020 The CodeWorld Authors. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

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

import CodeWorld.Account (UserId)
import CodeWorld.Auth
  ( AuthConfig,
    authMethod,
    authRoutes,
    authenticated,
    getAuthConfig,
  )
import CodeWorld.Compile
import CodeWorld.Compile.Base
import Control.Applicative
import Control.Concurrent (forkIO)
import Control.Concurrent.MSem (MSem)
import qualified Control.Concurrent.MSem as MSem
import Control.Exception (bracket_)
import Control.Exception.Lifted (catch)
import Control.Monad
import Control.Monad.Trans
import Data.Aeson
import qualified Data.ByteString as B
import Data.ByteString.Builder (toLazyByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Char (isSpace)
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Vector as V
import Model
import Network.HTTP.Simple
import Ormolu (OrmoluException, defaultConfig, ormolu)
import Snap.Core
import Snap.Http.Server (quickHttpServe)
import Snap.Util.FileServe
import Snap.Util.FileUploads
import System.Directory
import System.FileLock
import System.FilePath
import System.IO.Temp
import Util

maxSimultaneousCompiles :: Int
maxSimultaneousCompiles = 4

maxSimultaneousErrorChecks :: Int
maxSimultaneousErrorChecks = 2

data Context = Context
  { authConfig :: AuthConfig,
    compileSem :: MSem Int,
    errorSem :: MSem Int,
    baseSem :: MSem Int
  }

main :: IO ()
main = do
  ctx <- makeContext
  forkIO $ baseVersion >>= buildBaseIfNeeded ctx >> return ()
  quickHttpServe $ (processBody >> site ctx) <|> site ctx

makeContext :: IO Context
makeContext = do
  ctx <-
    Context <$> (getAuthConfig =<< getCurrentDirectory)
      <*> MSem.new maxSimultaneousCompiles
      <*> MSem.new maxSimultaneousErrorChecks
      <*> MSem.new 1
  putStrLn $ "Authentication method: " ++ authMethod (authConfig ctx)
  return ctx

-- | A CodeWorld Snap API action
type CodeWorldHandler = Context -> Snap ()

-- | A public handler that can be called from both authenticated and
--  unauthenticated clients and that does not need access to the user
--  ID.
public :: CodeWorldHandler -> CodeWorldHandler
public = id

-- | A private handler that can only be called from authenticated
--  clients and needs access to the user ID.
private :: (UserId -> CodeWorldHandler) -> CodeWorldHandler
private handler ctx = authenticated (flip handler ctx) (authConfig ctx)

-- A revised upload policy that allows up to 8 MB of uploaded data in a
-- request.  This is needed to handle uploads of projects including editor
-- history.
codeworldUploadPolicy :: UploadPolicy
codeworldUploadPolicy =
  setMaximumFormInputSize (2 ^ (23 :: Int)) defaultUploadPolicy

-- Processes the body of a multipart request.
#if MIN_VERSION_snap_core(1,0,0)
processBody :: Snap ()
processBody = do
    handleMultipart codeworldUploadPolicy (\x y -> return ())
    return ()
#else
processBody :: Snap ()
processBody = do
    handleMultipart codeworldUploadPolicy (\x -> return ())
    return ()
#endif

getBuildMode :: Snap BuildMode
getBuildMode =
  getParam "mode" >>= \case
    Just "haskell" -> return (BuildMode "haskell")
    Just "blocklyXML" -> return (BuildMode "blocklyXML")
    _ -> return (BuildMode "codeworld")

site :: CodeWorldHandler
site ctx =
  let routes =
        [ ("loadProject", loadProjectHandler ctx),
          ("saveProject", saveProjectHandler ctx),
          ("deleteProject", deleteProjectHandler ctx),
          ("createFolder", createFolderHandler ctx),
          ("deleteFolder", deleteFolderHandler ctx),
          ("listFolder", listFolderHandler False ctx),
          ("listFolders", listFolderHandler True ctx),
          ("updateChildrenIndexes", updateChildrenIndexesHandler ctx),
          ("shareFolder", shareFolderHandler ctx),
          ("shareContent", shareContentHandler ctx),
          ("moveProject", moveProjectHandler ctx),
          ("compile", compileHandler ctx),
          ("errorCheck", errorCheckHandler ctx),
          ("saveXMLhash", saveXMLHashHandler ctx),
          ("loadXML", loadXMLHandler ctx),
          ("loadSource", loadSourceHandler ctx),
          ("run", runHandler ctx),
          ("runJS", runHandler ctx),
          ("runBaseJS", runBaseHandler ctx),
          ("runMsg", runMessageHandler ctx),
          ("haskell", serveFile "web/env.html"),
          ("blocks", serveFile "web/blocks.html"),
          ("funblocks", serveFile "web/blocks.html"),
          ("indent", indentHandler ctx),
          ("gallery/:shareHash", galleryHandler ctx),
          ("log", logHandler ctx)
        ]
          ++ authRoutes (authConfig ctx)
   in route routes <|> serveDirectory "web"

-- A DirectoryConfig that sets the cache-control header to avoid errors when new
-- changes are made to JavaScript.
dirConfig :: DirectoryConfig Snap
dirConfig = defaultDirectoryConfig {preServeHook = disableCache}
  where
    disableCache _ = modifyRequest (addHeader "Cache-control" "no-cache")

createFolderHandler :: CodeWorldHandler
createFolderHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let pathText = map T.pack path
      dirIds = map nameToDirId pathText
      finalDir = joinPath $ map dirBase dirIds
      name = last pathText
  liftIO $ ensureUserBaseDir mode userId finalDir
  liftIO $ createDirectory $ userProjectDir mode userId </> finalDir
  modifyResponse $ setContentType "text/plain"
  liftIO $
    T.writeFile
      (userProjectDir mode userId </> finalDir </> "dir.info")
      name

deleteFolderHandler :: CodeWorldHandler
deleteFolderHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  liftIO $ ensureUserDir mode userId finalDir
  let dir = userProjectDir mode userId </> finalDir
  liftIO $ removeDirectoryIfExists dir

loadProjectHandler :: CodeWorldHandler
loadProjectHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just name <- getParam "name"
  let projectName = T.decodeUtf8 name
  let projectId = nameToProjectId projectName
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  liftIO $ ensureProjectDir mode userId finalDir projectId
  let file =
        userProjectDir mode userId </> finalDir
          </> projectFile projectId
  modifyResponse $ setContentType "application/json"
  serveFile file

saveProjectHandler :: CodeWorldHandler
saveProjectHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  Just project <- decode . LB.fromStrict . fromJust <$> getParam "project"
  let projectId = nameToProjectId (projectName project)
  liftIO $ ensureProjectDir mode userId finalDir projectId
  let file =
        userProjectDir mode userId </> finalDir
          </> projectFile projectId
  liftIO $ LB.writeFile file $ encode project

deleteProjectHandler :: CodeWorldHandler
deleteProjectHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just name <- getParam "name"
  let projectName = T.decodeUtf8 name
  let projectId = nameToProjectId projectName
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  liftIO $ ensureProjectDir mode userId finalDir projectId
  let file =
        userProjectDir mode userId </> finalDir
          </> projectFile projectId
  liftIO $ removeFileIfExists file

listFolderHandler :: Bool -> CodeWorldHandler
listFolderHandler recurse = private $ \userId ctx -> do
  mode <- getBuildMode
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  liftIO $ ensureUserBaseDir mode userId finalDir
  liftIO $ ensureUserDir mode userId finalDir
  let projectDir = userProjectDir mode userId
  entries <- liftIO $ fsEntries recurse (projectDir </> finalDir)
  modifyResponse $ setContentType "application/json"
  writeLBS (encode entries)

-- | Update order of elements inside of given directory
updateChildrenIndexesHandler :: CodeWorldHandler
updateChildrenIndexesHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  let projectDir = userProjectDir mode userId
  Just path <-
    fmap
      ( (\p -> projectDir </> p </> "order.info")
          . joinPath
          . (map (dirBase . nameToDirId . T.pack))
          . splitDirectories
          . T.unpack
          . T.decodeUtf8
      )
      <$> getParam "path"
  param <- getParam "entries"
  -- Encoding just to check if request param is correct
  Just entries <- decodeStrict . fromJust <$> getParam "entries" :: Snap (Maybe [FileSystemEntry])
  liftIO $ LB.writeFile path $ encode entries

shareFolderHandler :: CodeWorldHandler
shareFolderHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
  let dirIds = map (nameToDirId . T.pack) path
  let finalDir = joinPath $ map dirBase dirIds
  checkSum <-
    liftIO $ dirToCheckSum $ userProjectDir mode userId </> finalDir
  liftIO $ ensureShareDir mode $ ShareId checkSum
  liftIO
    $ B.writeFile (shareRootDir mode </> shareLink (ShareId checkSum))
    $ T.encodeUtf8 (T.pack (userProjectDir mode userId </> finalDir))
  modifyResponse $ setContentType "text/plain"
  writeBS $ T.encodeUtf8 checkSum

shareContentHandler :: CodeWorldHandler
shareContentHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just shash <- getParam "shash"
  sharingFolder <-
    liftIO $
      B.readFile
        (shareRootDir mode </> shareLink (ShareId $ T.decodeUtf8 shash))
  Just name <- fmap T.decodeUtf8 <$> getParam "name"
  let dirPath = dirBase $ nameToDirId name
  liftIO $ ensureUserBaseDir mode userId dirPath
  liftIO
    $ copyDirIfExists (T.unpack (T.decodeUtf8 sharingFolder))
    $ userProjectDir mode userId </> dirPath
  liftIO $
    T.writeFile
      (userProjectDir mode userId </> dirPath </> "dir.info")
      name

moveProjectHandler :: CodeWorldHandler
moveProjectHandler = private $ \userId ctx -> do
  mode <- getBuildMode
  Just moveTo <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "moveTo"
  let moveToDir = joinPath $ map (dirBase . nameToDirId . T.pack) moveTo
  Just moveFrom <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "moveFrom"
  let projectDir = userProjectDir mode userId
  let moveFromDir =
        projectDir
          </> joinPath (map (dirBase . nameToDirId . T.pack) moveFrom)
  let parentFrom =
        if moveFrom == []
          then []
          else init moveFrom
  Just isFile <- getParam "isFile"
  case (moveTo == moveFrom, moveTo == parentFrom, isFile) of
    (False, _, "true") -> do
      Just name <- getParam "name"
      let projectId = nameToProjectId $ T.decodeUtf8 name
          file = moveFromDir </> projectFile projectId
          toFile = projectDir </> moveToDir </> projectFile projectId
      liftIO $ ensureProjectDir mode userId moveToDir projectId
      liftIO $ copyFile file toFile
      liftIO $ removeFileIfExists file
    (_, False, "false") -> do
      let dirName = last $ splitDirectories moveFromDir
      let dir = moveToDir </> dirName
      liftIO $ ensureUserBaseDir mode userId dir
      liftIO $ copyDirIfExists moveFromDir $ projectDir </> dir
      liftIO $ removeDirectoryIfExists moveFromDir
    (_, _, _) -> return ()

withProgramLock :: BuildMode -> ProgramId -> IO a -> IO a
withProgramLock (BuildMode mode) (ProgramId hash) action = do
  tmpDir <- getTemporaryDirectory
  let tmpFile = tmpDir </> "codeworld" <.> T.unpack hash <.> mode
  withFileLock tmpFile Exclusive (const action)

saveXMLHashHandler :: CodeWorldHandler
saveXMLHashHandler = public $ \ctx -> do
  mode <- getBuildMode
  unless (mode == BuildMode "blocklyXML")
    $ modifyResponse
    $ setResponseCode 500
  Just source <- getParam "source"
  let programId = sourceToProgramId source
  liftIO $ withProgramLock mode programId $ do
    ensureSourceDir mode programId
    B.writeFile (sourceRootDir mode </> sourceXML programId) source
  modifyResponse $ setContentType "text/plain"
  writeBS (T.encodeUtf8 (unProgramId programId))

compileHandler :: CodeWorldHandler
compileHandler = public $ \ctx -> do
  mode <- getBuildMode
  Just source <- getParam "source"
  let programId = sourceToProgramId source
      deployId = sourceToDeployId source
  status <- liftIO $ withProgramLock mode programId $ do
    ensureSourceDir mode programId
    B.writeFile (sourceRootDir mode </> sourceFile programId) source
    writeDeployLink mode deployId programId
    compileIfNeeded ctx mode programId
  modifyResponse $ setResponseCode (responseCodeFromCompileStatus status)
  modifyResponse $ setContentType "text/plain"
  let result = CompileResult (unProgramId programId) (unDeployId deployId)
  writeLBS (encode result)

errorCheckHandler :: CodeWorldHandler
errorCheckHandler = public $ \ctx -> do
  mode <- getBuildMode
  Just source <- getParam "source"
  (status, output) <- liftIO $ errorCheck ctx mode source
  modifyResponse $ setResponseCode (responseCodeFromCompileStatus status)
  modifyResponse $ setContentType "text/plain"
  writeBS output

getHashParam :: Bool -> BuildMode -> Snap ProgramId
getHashParam allowDeploy mode = do
  maybeHash <- getParam "hash"
  case maybeHash of
    Just h -> return (ProgramId (T.decodeUtf8 h))
    Nothing
      | allowDeploy -> do
        Just dh <- getParam "dhash"
        let deployId = DeployId (T.decodeUtf8 dh)
        liftIO $ resolveDeployId mode deployId
      | otherwise -> pass

loadXMLHandler :: CodeWorldHandler
loadXMLHandler = public $ \ctx -> do
  mode <- getBuildMode
  unless (mode == BuildMode "blocklyXML")
    $ modifyResponse
    $ setResponseCode 500
  programId <- getHashParam False mode
  modifyResponse $ setContentType "text/plain"
  serveFile (sourceRootDir mode </> sourceXML programId)

loadSourceHandler :: CodeWorldHandler
loadSourceHandler = public $ \ctx -> do
  mode <- getBuildMode
  programId <- getHashParam False mode
  modifyResponse $ setContentType "text/x-haskell"
  serveFile (sourceRootDir mode </> sourceFile programId)

runHandler :: CodeWorldHandler
runHandler = public $ \ctx -> do
  mode <- getBuildMode
  programId <- getHashParam True mode
  result <-
    liftIO
      $ withProgramLock mode programId
      $ compileIfNeeded ctx mode programId
  modifyResponse $ setResponseCode (responseCodeFromCompileStatus result)
  when (result == CompileSuccess) $ do
    modifyResponse $ setContentType "text/javascript"
    serveFile (buildRootDir mode </> targetFile programId)

runBaseHandler :: CodeWorldHandler
runBaseHandler = public $ \ctx -> do
  maybeVer <- fmap T.decodeUtf8 <$> getParam "version"
  hasProgram <-
    (\mode hash dhash -> mode && (hash || dhash))
      <$> hasParam "mode" <*> hasParam "hash" <*> hasParam "dhash"
  case maybeVer of
    Just ver -> serveFile (baseCodeFile ver)
    Nothing | hasProgram -> do
      mode <- getBuildMode
      programId <- getHashParam True mode
      result <-
        liftIO
          $ withProgramLock mode programId
          $ compileIfNeeded ctx mode programId
      modifyResponse $ setResponseCode (responseCodeFromCompileStatus result)
      when (result == CompileSuccess) $ do
        ver <-
          liftIO $
            B.readFile (buildRootDir mode </> baseVersionFile programId)
        impliedVersion ver
    _ -> do
      ver <- liftIO baseVersion
      liftIO $ buildBaseIfNeeded ctx ver
      impliedVersion (T.encodeUtf8 ver)
  where
    impliedVersion ver = redirect $ "/runBaseJS?version=" <> ver
    hasParam name = (/= Nothing) <$> getParam name

runMessageHandler :: CodeWorldHandler
runMessageHandler = public $ \ctx -> do
  mode <- getBuildMode
  programId <- getHashParam False mode
  modifyResponse $ setContentType "text/plain"
  serveFile (buildRootDir mode </> resultFile programId)

indentHandler :: CodeWorldHandler
indentHandler = public $ \ctx -> do
  mode <- getBuildMode
  Just source <- getParam "source"
  reformat source `catch` handleError
  where
    reformat source = do
      result <- ormolu defaultConfig "program.hs" (T.unpack (T.decodeUtf8 source))
      modifyResponse $ setContentType "text/x-haskell"
      writeBS $ T.encodeUtf8 result
    handleError (e :: OrmoluException) = do
      modifyResponse $ setResponseCode 500 . setContentType "text/plain"
      writeLBS $ LB.fromStrict $ T.encodeUtf8 $ T.pack (show e)

galleryHandler :: CodeWorldHandler
galleryHandler = public $ const $ do
  mode <- getBuildMode
  Just shareHash <- getParam "shareHash"
  let shareId = ShareId (T.decodeUtf8 shareHash)
  gallery <- liftIO $ do
    folder <- T.unpack . T.decodeUtf8 <$> B.readFile (shareRootDir mode </> shareLink shareId)
    files <- sort <$> projectFileNames folder
    Gallery <$> mapM (galleryItemFromProject mode folder) files
  writeLBS $ encode gallery

galleryItemFromProject :: BuildMode -> FilePath -> Text -> IO GalleryItem
galleryItemFromProject mode@(BuildMode modeName) folder name = do
  let projectId = nameToProjectId name
  let file = folder </> projectFile projectId
  Just project <- decode <$> LB.readFile file

  let source = T.encodeUtf8 $ projectSource project
  let programId = sourceToProgramId source
  let deployId = sourceToDeployId source

  liftIO $ withProgramLock mode programId $ do
    ensureSourceDir mode programId
    B.writeFile (sourceRootDir mode </> sourceFile programId) source
    writeDeployLink mode deployId programId

  let baseURL = "/" <> if modeName == "codeworld" then "" else T.pack modeName

  return
    GalleryItem
      { galleryItemName = name,
        galleryItemURL =
          "run.html"
            <> "?mode="
            <> T.pack modeName
            <> "&dhash="
            <> unDeployId deployId,
        galleryItemCode = Just (baseURL <> "#" <> unProgramId programId)
      }

logHandler :: CodeWorldHandler
logHandler = public $ \ctx -> do
  Just message <- fmap T.decodeUtf8 <$> getParam "message"
  title <-
    fromMaybe "User-reported unhelpful error message"
      <$> fmap T.decodeUtf8
      <$> getParam "title"
  tag <- fromMaybe "error-message" <$> fmap T.decodeUtf8 <$> getParam "tag"

  liftIO $ do
    let body =
          object
            [ ("title", String title),
              ("body", String message),
              ("labels", toJSON [tag])
            ]
    authToken <- B.readFile "github-auth-token.txt"
    let authHeader = "token " <> authToken
    let userAgent = "https://code.world github integration by cdsmith"
    request <-
      addRequestHeader "Authorization" authHeader
        <$> addRequestHeader "User-agent" userAgent
        <$> setRequestBodyJSON body
        <$> parseRequestThrow "POST https://api.github.com/repos/google/codeworld/issues"
    httpNoBody request
  return ()

responseCodeFromCompileStatus :: CompileStatus -> Int
responseCodeFromCompileStatus CompileSuccess = 200
responseCodeFromCompileStatus CompileError = 400
responseCodeFromCompileStatus CompileAborted = 503

compileIfNeeded :: Context -> BuildMode -> ProgramId -> IO CompileStatus
compileIfNeeded ctx mode programId = do
  hasResult <- doesFileExist (buildRootDir mode </> resultFile programId)
  hasTarget <- doesFileExist (buildRootDir mode </> targetFile programId)
  if
      | hasResult && hasTarget -> return CompileSuccess
      | hasResult -> return CompileError
      | otherwise ->
        MSem.with (compileSem ctx) $ compileProgram ctx mode programId

compileProgram :: Context -> BuildMode -> ProgramId -> IO CompileStatus
compileProgram ctx mode programId = do
  ver <- baseVersion
  baseStatus <- buildBaseIfNeeded ctx ver

  case baseStatus of
    CompileSuccess -> do
      status <- compileIncrementally mode programId ver
      T.writeFile (buildRootDir mode </> baseVersionFile programId) ver

      -- It's possible that a new library was built during the compile.  If so, then the code
      -- we've just built is suspect, and it's better to just build it anew!
      checkVer <- baseVersion
      if ver == checkVer
        then return status
        else compileProgram ctx mode programId
    _ -> return CompileAborted

compileIncrementally :: BuildMode -> ProgramId -> Text -> IO CompileStatus
compileIncrementally mode programId ver =
  compileSource stage source (projectModuleFinder mode) result (getMode mode) False
  where
    source = sourceRootDir mode </> sourceFile programId
    target = buildRootDir mode </> targetFile programId
    result = buildRootDir mode </> resultFile programId
    baseURL = "runBaseJS?version=" ++ T.unpack ver
    stage = UseBase target (baseSymbolFile ver) baseURL

projectModuleFinder :: BuildMode -> String -> IO (Maybe FilePath)
projectModuleFinder mode modName
  | length modName /= 23 || '.' `elem` modName = return Nothing
  | "P" `isPrefixOf` modName = go (ProgramId (T.pack modName))
  | "D" `isPrefixOf` modName = do
    let deployId = DeployId (T.pack modName)
    resolveDeployId mode deployId >>= go
  | otherwise = return Nothing
  where
    go programId = do
      let path = sourceRootDir mode </> sourceFile programId
      exists <- doesFileExist path
      if exists then return (Just path) else return Nothing

noModuleFinder :: String -> IO (Maybe FilePath)
noModuleFinder _ = return Nothing

buildBaseIfNeeded :: Context -> Text -> IO CompileStatus
buildBaseIfNeeded ctx ver = do
  codeExists <- doesFileExist (baseCodeFile ver)
  symbolsExist <- doesFileExist (baseSymbolFile ver)
  if not codeExists || not symbolsExist
    then MSem.with (baseSem ctx) $ withSystemTempDirectory "genbase" $ \tmpdir -> do
      let linkMain = tmpdir </> "LinkMain.hs"
      let linkBase = tmpdir </> "LinkBase.hs"
      let err = tmpdir </> "output.txt"
      generateBaseBundle basePaths baseIgnore "codeworld" linkMain linkBase
      let stage = GenBase "LinkBase" linkBase (baseCodeFile ver) (baseSymbolFile ver)
      compileSource stage linkMain noModuleFinder err "codeworld" False
    else return CompileSuccess

basePaths :: [FilePath]
basePaths = ["codeworld-base/dist/doc/html/codeworld-base/codeworld-base.txt"]

baseIgnore :: [Text]
baseIgnore = ["fromCWText", "toCWText", "randomsFrom"]

errorCheck :: Context -> BuildMode -> B.ByteString -> IO (CompileStatus, B.ByteString)
errorCheck ctx mode source = withSystemTempDirectory "cw_errorCheck" $ \dir -> do
  let srcFile = dir </> "program.hs"
  let errFile = dir </> "output.txt"
  B.writeFile srcFile source
  status <-
    MSem.with (errorSem ctx) $ MSem.with (compileSem ctx) $
      compileSource ErrorCheck srcFile (projectModuleFinder mode) errFile (getMode mode) False
  hasOutput <- doesFileExist errFile
  output <- if hasOutput then B.readFile errFile else return B.empty
  return (status, output)

getMode :: BuildMode -> String
getMode (BuildMode m) = m


text:
package net.krinsoft.jobsuite.commands;

import net.krinsoft.jobsuite.Job;
import net.krinsoft.jobsuite.JobCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;

import java.util.List;

/**
 * @author krinsdeath
 */
public class JobDescriptionCommand extends JobCommand {

    public JobDescriptionCommand(JobCore instance) {
        super(instance);
        setName("JobSuite: Description");
        setArgRange(1, 20);
        addKey("jobsuite description");
        addKey("job description");
        addKey("js description");
        addKey("jobsuite desc");
        addKey("job desc");
        addKey("js desc");
        setPermission("jobsuite.description", "Sets the description for this job.", PermissionDefault.TRUE);
    }

    @Override
    public void runCommand(CommandSender sender, List<String> args) {
        Job job = manager.getQueuedJob(sender.getName());
        if (job != null) {
            StringBuilder desc = new StringBuilder();
            for (String word : args) {
                desc.append(word).append(" ");
            }
            job.setDescription(desc.toString().trim());
            message(sender, "Description set successfully.");
            message(sender, "Now, set a reward: " + ChatColor.AQUA + "/job reward [amount]");
        } else {
            error(sender, "You aren't currently making a job.");
        }
    }
}


text:
#include "panel_manager.h"
#include "internal.h"
#include "panel.h"

#include <wayland-server.h>
#include "swc-server-protocol.h"

static void
create_panel(struct wl_client *client, struct wl_resource *resource, uint32_t id, struct wl_resource *surface_resource)
{
	struct surface *surface = wl_resource_get_user_data(surface_resource);

	if (!panel_new(client, wl_resource_get_version(resource), id, surface))
		wl_client_post_no_memory(client);
}

static const struct swc_panel_manager_interface panel_manager_impl = {
	.create_panel = create_panel,
};

static void
bind_panel_manager(struct wl_client *client, void *data, uint32_t version, uint32_t id)
{
	struct wl_resource *resource;

	resource = wl_resource_create(client, &swc_panel_manager_interface, version, id);
	if (!resource) {
		wl_client_post_no_memory(client);
		return;
	}
	wl_resource_set_implementation(resource, &panel_manager_impl, NULL, NULL);
}

struct wl_global *
panel_manager_create(struct wl_display *display)
{
	return wl_global_create(display, &swc_panel_manager_interface, 1, NULL, &bind_panel_manager);
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\SageSubcategoriaSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Sage Subcategoria';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Adicionar Subcategoria', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

			[
			    'attribute'=>'id_categoria',
			    'value'=>'idCategoria.nome',
   			 'filter'=> '',
   			 'enableSorting'=>false,
			],

            'nome',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
@implementation SPDYHeaderBlockCompressor
{
    z_stream _zlibStream;
    int _zlibStreamStatus;
}

- (instancetype)init
{
    return [self initWithCompressionLevel:ZLIB_COMPRESSION_LEVEL];
}

- (instancetype)initWithCompressionLevel:(NSUInteger)compressionLevel
{
    self = [super init];
    if (self) {
        bzero(&_zlibStream, sizeof(_zlibStream));

        _zlibStream.zalloc   = Z_NULL;
        _zlibStream.zfree    = Z_NULL;
        _zlibStream.opaque   = Z_NULL;

        _zlibStream.avail_in = 0;
        _zlibStream.next_in  = Z_NULL;

        _zlibStreamStatus = deflateInit2(&_zlibStream, compressionLevel, Z_DEFLATED, ZLIB_WINDOW_SIZE, ZLIB_MEMORY_LEVEL, Z_DEFAULT_STRATEGY);
        NSAssert(_zlibStreamStatus == Z_OK, @"unable to initialize zlib stream");

        _zlibStreamStatus = deflateSetDictionary(&_zlibStream, kSPDYDict, sizeof(kSPDYDict));
        NSAssert(_zlibStreamStatus == Z_OK, @"unable to set zlib dictionary");
    }
    return self;
}

- (void)dealloc
{
    (void)deflateEnd(&_zlibStream);
}

// Always consumes ALL available input or sets an error, and returns the number of bytes written to the output buffer.
- (NSUInteger)deflate:(uint8_t *)inputBuffer availIn:(NSUInteger)inputLength outputBuffer:(uint8_t *)outputBuffer availOut:(NSUInteger)outputLength error:(NSError **)pError
{
    if (_zlibStreamStatus != Z_OK) {
        if (pError) *pError = SPDY_CODEC_ERROR(SPDYHeaderBlockEncodingError, @"invalid zlib stream state");
        return 0;
    }

    _zlibStream.next_in = inputBuffer;
    _zlibStream.avail_in = (uInt)inputLength;

    _zlibStream.next_out = outputBuffer;
    _zlibStream.avail_out = (uInt)outputLength;

    _zlibStreamStatus = deflate(&_zlibStream, Z_SYNC_FLUSH);

    if (_zlibStreamStatus != Z_OK && pError) {
        *pError = SPDY_CODEC_ERROR(SPDYHeaderBlockEncodingError, @"error compressing header block");
    }

    return _zlibStream.next_out - outputBuffer;
}

@end


text:
namespace history {

const double kLn2 = 0.6931471805599453;

VisitFilter::VisitFilter()
    : day_(DAY_UNDEFINED),
      max_results_(0),
      sorting_order_(ORDER_BY_RECENCY) {
}

VisitFilter::~VisitFilter() {
}

void VisitFilter::SetFilterTime(const base::Time& filter_time) {
  filter_time_ = filter_time;
  UpdateTimeVector();
}

void VisitFilter::SetFilterWidth(const base::TimeDelta& filter_width) {
  filter_width_ = filter_width;
  UpdateTimeVector();
}

void VisitFilter::SetDayOfTheWeekFilter(int day) {
  day_ = day;
  UpdateTimeVector();
}

void VisitFilter::SetDayTypeFilter(bool workday) {
  day_ = workday ? WORKDAY : HOLIDAY;
  UpdateTimeVector();
}

void VisitFilter::ClearFilters() {
  filter_time_ = base::Time();
  filter_width_ = base::TimeDelta::FromHours(0);
  day_ = DAY_UNDEFINED;
  UpdateTimeVector();
}

bool VisitFilter::UpdateTimeVector() {

  TimeVector days_of_the_week;
  if (day_ >= 0 && day_ <= 6) {
    GetTimesOnTheDayOfTheWeek(day_, filter_time_, max_results_,
                              &days_of_the_week);
  } else if (day_ == WORKDAY || day_ == HOLIDAY) {
    GetTimesOnTheSameDayType(
        (day_ == WORKDAY), filter_time_, max_results_, &days_of_the_week);
  }

  TimeVector times_of_the_day;
  if (filter_width_ != base::TimeDelta::FromSeconds(0)) {
    if (sorting_order_ == ORDER_BY_TIME_GAUSSIAN) {
      // Limit queries to 5 standard deviations.
      GetTimesInRange(filter_time_ - 5 * filter_width_,
                      filter_time_ + 5 * filter_width_,
                      max_results_, &times_of_the_day);
    } else {
      GetTimesInRange(filter_time_ - filter_width_,
                      filter_time_ + filter_width_,
                      max_results_, &times_of_the_day);
    }
  }

  if (times_of_the_day.empty()) {
    if (days_of_the_week.empty())
      times_.clear();
    else
      times_.swap(days_of_the_week);
  } else {
    if (days_of_the_week.empty())
      times_.swap(times_of_the_day);
    else
      IntersectTimeVectors(times_of_the_day, days_of_the_week, &times_);
  }

  return !times_.empty();
}

// static
void VisitFilter::GetTimesInRange(base::Time begin_time_of_the_day,
                                  base::Time end_time_of_the_day,
                                  size_t max_results,
                                  TimeVector* times) {
  DCHECK(times);
  times->clear();
  times->reserve(max_results);
  const size_t kMaxReturnedResults = 62;  // 2 months (<= 62 days).

  if (!max_results)
    max_results = kMaxReturnedResults;

  // If range is more than 24 hours, return a contiguous interval covering
  // |max_results| days.
  base::TimeDelta one_day = base::TimeDelta::FromDays(1);
  if (end_time_of_the_day - begin_time_of_the_day >= one_day) {
    times->push_back(
        std::make_pair(begin_time_of_the_day - one_day * (max_results - 1),
                       end_time_of_the_day));
    return;
  }

  for (int i = 0; i < static_cast<int>(max_results); ++i) {
    times->push_back(
        std::make_pair(begin_time_of_the_day - base::TimeDelta::FromDays(i),
                       end_time_of_the_day - base::TimeDelta::FromDays(i)));
  }
}

double VisitFilter::GetVisitScore(const VisitRow& visit) const {
  // Decay score by half each week.
  base::TimeDelta time_passed = filter_time_ - visit.visit_time;
  // Clamp to 0 in case time jumps backwards (e.g. due to DST).
  double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(
      time_passed.InMicroseconds()) / base::Time::kMicrosecondsPerWeek);
  double staleness = 1.0 / exp(decay_exponent);

  double score = 0;
  switch (sorting_order()) {
    case ORDER_BY_RECENCY:
      score = 1.0;  // Let the staleness factor take care of it.
      break;
    case ORDER_BY_VISIT_COUNT:
      score = 1.0;  // Every visit counts the same.
      staleness = 1.0;  // No decay on this one.
      break;
    case ORDER_BY_TIME_GAUSSIAN: {
      double offset =
          GetTimeOfDayDifference(filter_time_,
                                 visit.visit_time).InMicroseconds();
      double sd = filter_width_.InMicroseconds();

      // Calculate score using the normal distribution density function.
      score = exp(-(offset * offset) / (2 * sd * sd));
      break;
    }
    case ORDER_BY_TIME_LINEAR: {
      base::TimeDelta offset = GetTimeOfDayDifference(filter_time_,
                                                      visit.visit_time);
      if (offset > filter_width_) {
        score = 0;
      } else {
        score = 1 - offset.InMicroseconds() / static_cast<double>(
            filter_width_.InMicroseconds());
      }
      break;
    }
    case ORDER_BY_DURATION_SPENT:
    default:
      NOTREACHED() << "Not implemented!";
  }
  return staleness * score;
}

base::TimeDelta
VisitFilter::GetTimeOfDayDifference(base::Time t1, base::Time t2) {
  base::TimeDelta time_of_day1 = t1 - t1.LocalMidnight();
  base::TimeDelta time_of_day2 = t2 - t2.LocalMidnight();

  base::TimeDelta difference;
  if (time_of_day1 < time_of_day2)
    difference = time_of_day2 - time_of_day1;
  else
    difference = time_of_day1 - time_of_day2;

  // If the difference is more than 12 hours, we'll get closer by 'wrapping'
  // around the day barrier.
  if (difference > base::TimeDelta::FromHours(12))
    difference = base::TimeDelta::FromHours(24) - difference;

  return difference;
}

// static
void VisitFilter::GetTimesOnTheDayOfTheWeek(int day,
                                            base::Time week,
                                            size_t max_results,
                                            TimeVector* times) {
  DCHECK(times);

  base::Time::Exploded exploded_time;
  if (week.is_null())
    week = base::Time::Now();
  week.LocalExplode(&exploded_time);
  base::TimeDelta shift = base::TimeDelta::FromDays(
      exploded_time.day_of_week - day);

  base::Time day_base = week.LocalMidnight();
  day_base -= shift;

  times->clear();
  times->reserve(max_results);

  base::TimeDelta one_day = base::TimeDelta::FromDays(1);

  const size_t kMaxReturnedResults = 9;  // 2 months (<= 9 weeks).

  if (!max_results)
    max_results = kMaxReturnedResults;

  for (int i = 0; i < static_cast<int>(max_results); ++i) {
    times->push_back(
        std::make_pair(day_base - base::TimeDelta::FromDays(i * 7),
                       day_base + one_day - base::TimeDelta::FromDays(i * 7)));
  }
}

// static
void VisitFilter::GetTimesOnTheSameDayType(bool workday,
                                           base::Time week,
                                           size_t max_results,
                                           TimeVector* times) {
  DCHECK(times);
  if (week.is_null())
    week = base::Time::Now();
  // TODO(georgey): internationalize workdays/weekends/holidays.
  if (!workday) {
    TimeVector sunday;
    TimeVector saturday;
    base::Time::Exploded exploded_time;
    week.LocalExplode(&exploded_time);

    GetTimesOnTheDayOfTheWeek(exploded_time.day_of_week ? 7 : 0, week,
                              max_results, &sunday);
    GetTimesOnTheDayOfTheWeek(exploded_time.day_of_week ? 6 : -1, week,
                              max_results, &saturday);
    UniteTimeVectors(sunday, saturday, times);
    if (max_results && times->size() > max_results)
      times->resize(max_results);
  } else {
    TimeVector vectors[3];
    GetTimesOnTheDayOfTheWeek(1, week, max_results, &vectors[0]);
    for (int i = 2; i <= 5; ++i) {
      GetTimesOnTheDayOfTheWeek(i, week, max_results, &vectors[(i - 1) % 3]);
      UniteTimeVectors(vectors[(i - 2) % 3], vectors[(i - 1) % 3],
                       &vectors[i % 3]);
      if (max_results && vectors[i % 3].size() > max_results)
        vectors[i % 3].resize(max_results);
      vectors[i % 3].swap(vectors[(i - 1) % 3]);
    }
    // 1 == 5 - 1 % 3
    times->swap(vectors[1]);
  }
}

// static
bool VisitFilter::UniteTimeVectors(const TimeVector& vector1,
                                   const TimeVector& vector2,
                                   TimeVector* result) {
  // The vectors are sorted going back in time, but each pair has |first| as the
  // beginning of time period and |second| as the end, for example:
  // { 19:20, 20:00 } { 17:00, 18:10 } { 11:33, 11:35 }...
  // The pairs in one vector are guaranteed not to intersect.
  DCHECK(result);
  result->clear();
  result->reserve(vector1.size() + vector2.size());

  size_t vi[2];
  const TimeVector* vectors[2] = { &vector1, &vector2 };
  for (vi[0] = 0, vi[1] = 0;
       vi[0] < vectors[0]->size() && vi[1] < vectors[1]->size();) {
    std::pair<base::Time, base::Time> united_timeslot;
    // Check which element occurs later (for the following diagrams time is
    // increasing to the right, 'f' means first, 's' means second).
    // after the folowing 2 statements:
    // vectors[iterator_index][vi[iterator_index]]           f---s
    // vectors[1 - iterator_index][vi[1 - iterator_index]]  f---s
    // united_timeslot                                       f---s
    // or
    // vectors[iterator_index][vi[iterator_index]]           f---s
    // vectors[1 - iterator_index][vi[1 - iterator_index]]    f-s
    // united_timeslot                                       f---s
    size_t iterator_index =
        ((*vectors[0])[vi[0]].second >= (*vectors[1])[vi[1]].second) ? 0 : 1;
    united_timeslot = (*vectors[iterator_index])[vi[iterator_index]];
    ++vi[iterator_index];
    bool added_timeslot;
    // Merge all timeslots intersecting with |united_timeslot|.
    do {
      added_timeslot = false;
      for (size_t i = 0; i <= 1; ++i) {
        if (vi[i] < vectors[i]->size() &&
            (*vectors[i])[vi[i]].second >= united_timeslot.first) {
          // vectors[i][vi[i]]           f---s
          // united_timeslot               f---s
          // or
          // united_timeslot            f------s
          added_timeslot = true;
          if ((*vectors[i])[vi[i]].first < united_timeslot.first) {
            // vectors[i][vi[i]]           f---s
            // united_timeslot               f---s
            // results in:
            // united_timeslot             f-----s
            united_timeslot.first = (*vectors[i])[vi[i]].first;
          }
          ++vi[i];
        }
      }
    } while (added_timeslot);
    result->push_back(united_timeslot);
  }
  for (size_t i = 0; i <= 1; ++i) {
    for (; vi[i] < vectors[i]->size(); ++vi[i])
      result->push_back((*vectors[i])[vi[i]]);
  }
  return !result->empty();
}

// static
bool VisitFilter::IntersectTimeVectors(const TimeVector& vector1,
                                       const TimeVector& vector2,
                                       TimeVector* result) {
  DCHECK(result);
  result->clear();
  result->reserve(std::max(vector1.size(), vector2.size()));

  TimeVector::const_iterator vi[2];
  for (vi[0] = vector1.begin(), vi[1] = vector2.begin();
       vi[0] != vector1.end() && vi[1] != vector2.end();) {
    size_t it_index = (vi[0]->second >= vi[1]->second) ? 0 : 1;
    if (vi[it_index]->first >= vi[1 - it_index]->second) {
      // vector 1    ++++
      // vector 2 ++
      ++vi[it_index];
    } else if (vi[it_index]->first >= vi[1 - it_index]->first) {
      // vector 1    ++++
      // vector 2 +++++
      result->push_back(std::make_pair(vi[it_index]->first,
                                       vi[1 - it_index]->second));
      ++vi[it_index];
    } else {
      // vector 1 ++++
      // vector 2  ++
      result->push_back(std::make_pair(vi[1 - it_index]->first,
                                       vi[1 - it_index]->second));
      ++vi[1 - it_index];
    }
  }

  return !result->empty();
}

}  // namespace history


text:
package nl.nn.adapterframework.webcontrol.api;

import java.io.InputStream;
import java.util.LinkedHashMap;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;

import nl.nn.adapterframework.configuration.IbisManager.IbisAction;
import nl.nn.adapterframework.jndi.JndiDataSourceFactory;
import nl.nn.adapterframework.management.bus.BusAction;
import nl.nn.adapterframework.management.bus.BusTopic;
import nl.nn.adapterframework.management.bus.RequestMessageBuilder;
import nl.nn.adapterframework.util.Misc;

/**
 * Shows the configuration (with resolved variables).
 *
 * @since	7.0-B1
 * @author	Niels Meijer
 */

@Path("/")
public final class ShowConfiguration extends FrankApiBase {

	@GET
	@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations")
	@Produces(MediaType.APPLICATION_XML)
	public Response getXMLConfiguration(@QueryParam("loadedConfiguration") boolean loaded, @QueryParam("flow") String flow) throws ApiException {
		if(StringUtils.isNotEmpty(flow)) {
			RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.FLOW);
			return callSyncGateway(builder);
		} else {
			RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.GET);
			if(loaded) builder.addHeader("loaded", loaded);
			return callSyncGateway(builder);
		}
	}

	@PUT
	@RolesAllowed({"IbisAdmin", "IbisTester"})
	@Path("/configurations")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response fullReload(LinkedHashMap<String, Object> json) throws ApiException {
		Object value = json.get("action");
		if(value instanceof String && "reload".equals(value)) {
			RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.IBISACTION);
			builder.addHeader("action", IbisAction.FULLRELOAD.name());
			callAsyncGateway(builder);
			return Response.status(Response.Status.ACCEPTED).entity("{\"status\":\"ok\"}").build();
		}

		return Response.status(Response.Status.BAD_REQUEST).build();
	}

	@GET
	@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}")
	@Produces(MediaType.APPLICATION_XML)
	public Response getConfigurationByName(@PathParam("configuration") String configurationName, @QueryParam("loadedConfiguration") boolean loaded) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.GET);
		builder.addHeader("configuration", configurationName);
		if(loaded) builder.addHeader("loaded", loaded);
		return callSyncGateway(builder);
	}

	@GET
	@PermitAll
	@Path("/configurations/{configuration}/health")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getConfigurationHealth(@PathParam("configuration") String configurationName) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.HEALTH);
		builder.addHeader("configuration", configurationName);
		return callSyncGateway(builder);
	}

	@GET
	@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}/flow")
	public Response getConfigurationFlow(@PathParam("configuration") String configurationName) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.FLOW);
		builder.addHeader("configuration", configurationName);
		return callSyncGateway(builder);
	}

	@PUT
	@RolesAllowed({"IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response reloadConfiguration(@PathParam("configuration") String configurationName, LinkedHashMap<String, Object> json) throws ApiException {
		Object value = json.get("action");
		if(value instanceof String && "reload".equals(value)) {
			RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.IBISACTION);
			builder.addHeader("action", IbisAction.RELOAD.name());
			builder.addHeader("configuration", configurationName);
			callAsyncGateway(builder);
			return Response.status(Response.Status.ACCEPTED).entity("{\"status\":\"ok\"}").build();
		}

		return Response.status(Response.Status.BAD_REQUEST).build();
	}

	@GET
	@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}/versions")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getConfigurationDetailsByName(@PathParam("configuration") String configurationName, @QueryParam("datasourceName") String datasourceName) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.FIND);
		builder.addHeader("configuration", configurationName);
		builder.addHeader("datasourceName", datasourceName);
		return callSyncGateway(builder);
	}

	@PUT
	@RolesAllowed({"IbisTester", "IbisAdmin", "IbisDataAdmin"})
	@Path("/configurations/{configuration}/versions/{version}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response manageConfiguration(@PathParam("configuration") String configurationName, @PathParam("version") String encodedVersion, @QueryParam("datasourceName") String datasourceName, LinkedHashMap<String, Object> json) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.MANAGE);
		builder.addHeader("configuration", configurationName);
		builder.addHeader("version", Misc.urlDecode(encodedVersion));
		if(json.containsKey("activate")) {
			builder.addHeader("activate", json.get("activate"));
		} else if(json.containsKey("autoreload")) {
			builder.addHeader("autoreload", json.get("autoreload"));
		}
		builder.addHeader("datasourceName", datasourceName);
		return callSyncGateway(builder);
	}

	@POST
	@RolesAllowed({"IbisTester", "IbisAdmin", "IbisDataAdmin"})
	@Path("configurations")
	@Produces(MediaType.APPLICATION_JSON)
	public Response uploadConfiguration(MultipartBody inputDataMap) throws ApiException {
		if(inputDataMap == null) {
			throw new ApiException("Missing post parameters");
		}

		String datasource = resolveStringFromMap(inputDataMap, "datasource", JndiDataSourceFactory.GLOBAL_DEFAULT_DATASOURCE_NAME);
		boolean multipleConfigs = resolveTypeFromMap(inputDataMap, "multiple_configs", boolean.class, false);
		boolean activateConfig  = resolveTypeFromMap(inputDataMap, "activate_config", boolean.class, true);
		boolean automaticReload = resolveTypeFromMap(inputDataMap, "automatic_reload", boolean.class, false);
		InputStream file = resolveTypeFromMap(inputDataMap, "file", InputStream.class, null);

		String user = resolveTypeFromMap(inputDataMap, "user", String.class, "");
		if(StringUtils.isEmpty(user)) {
			user = getUserPrincipalName();
		}

		String fileName = inputDataMap.getAttachment("file").getContentDisposition().getParameter( "filename" );

		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.UPLOAD);
		builder.setPayload(file);
		builder.addHeader("filename", fileName);
		builder.addHeader("multiple_configs", multipleConfigs);
		builder.addHeader("activate_config", activateConfig);
		builder.addHeader("automatic_reload", automaticReload);
		builder.addHeader("user", user);
		builder.addHeader("datasourceName", datasource);
		return callSyncGateway(builder);
	}

	@GET
	@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}/versions/{version}/download")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadConfiguration(@PathParam("configuration") String configurationName, @PathParam("version") String version, @QueryParam("dataSourceName") String dataSourceName) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.DOWNLOAD);
		builder.addHeader("configuration", configurationName);
		builder.addHeader("version", version);
		builder.addHeader("datasourceName", dataSourceName);
		return callSyncGateway(builder);
	}

	@DELETE
	@RolesAllowed({"IbisDataAdmin", "IbisAdmin", "IbisTester"})
	@Path("/configurations/{configuration}/versions/{version}")
	public Response deleteConfiguration(@PathParam("configuration") String configurationName, @PathParam("version") String version, @QueryParam("datasourceName") String datasourceName) throws ApiException {
		RequestMessageBuilder builder = RequestMessageBuilder.create(this, BusTopic.CONFIGURATION, BusAction.DELETE);
		builder.addHeader("configuration", configurationName);
		builder.addHeader("version", version);
		builder.addHeader("datasourceName", datasourceName);
		return callAsyncGateway(builder);
	}
}


text:
class AddTaxonRangeIdToListedTaxa < ActiveRecord::Migration
  def self.up
    add_column :listed_taxa, :taxon_range_id, :integer
    add_column :listed_taxa, :source_id, :integer
    add_index :listed_taxa, :taxon_range_id
    add_index :listed_taxa, :source_id
  end

  def self.down
    remove_column :listed_taxa, :taxon_range_id
    remove_column :listed_taxa, :source_id
  end
end


text:
package flash.tools.debugger.threadsafe;

import flash.tools.debugger.Watch;

/**
 * Thread-safe wrapper for flash.tools.debugger.Watch
 * @author Mike Morearty
 */
public class ThreadSafeWatch extends ThreadSafeDebuggerObject implements Watch {

	private Watch fWatch;

	private ThreadSafeWatch(Object syncObj, Watch watch) {
		super(syncObj);
		fWatch = watch;
	}

	/**
	 * Wraps a Watch inside a ThreadSafeWatch.  If the passed-in Watch
	 * is null, then this function returns null.
	 */
	public static ThreadSafeWatch wrap(Object syncObj, Watch watch) {
		if (watch != null)
			return new ThreadSafeWatch(syncObj, watch);
		else
			return null;
	}

	/**
	 * Wraps an array of Watches inside an array of ThreadSafeWatches.
	 */
	public static ThreadSafeWatch[] wrapArray(Object syncObj, Watch[] watchs) {
		ThreadSafeWatch[] threadSafeWatches = new ThreadSafeWatch[watchs.length];
		for (int i=0; i<watchs.length; ++i) {
			threadSafeWatches[i] = wrap(syncObj, watchs[i]);
		}
		return threadSafeWatches;
	}

	/**
	 * Returns the raw Watch underlying a ThreadSafeWatch.
	 */
	public static Watch getRaw(Watch w) {
		if (w instanceof ThreadSafeWatch)
			return ((ThreadSafeWatch)w).fWatch;
		else
			return w;
	}

	public static Object getSyncObject(Watch w) {
		return ((ThreadSafeWatch)w).getSyncObject();
	}

	public int getKind() {
		synchronized (getSyncObject()) {
			return fWatch.getKind();
		}
	}

	public String getMemberName() {
		synchronized (getSyncObject()) {
			return fWatch.getMemberName();
		}
	}

	public long getValueId() {
		synchronized (getSyncObject()) {
			return fWatch.getValueId();
		}
	}

	@Override
	public int getIsolateId() {
		synchronized (getSyncObject()) {
			return fWatch.getIsolateId();
		}
	}
}


text:
from __future__ import print_function
from __future__ import unicode_literals

import os
from collections import OrderedDict

import six

from airflow import configuration
from airflow.configuration import conf, AirflowConfigParser, parameterized_config

if six.PY2:
    # Need `assertWarns` back-ported from unittest2
    import unittest2 as unittest
else:
    import unittest

class ConfTest(unittest.TestCase):

    def setup(self):
        configuration.load_test_config()

    def test_env_var_config(self):
        opt = conf.get('testsection', 'testkey')
        self.assertEqual(opt, 'testvalue')

    def test_conf_as_dict(self):
        cfg_dict = conf.as_dict()

        # test that configs are picked up
        self.assertEqual(cfg_dict['core']['unit_test_mode'], 'True')

        # test env vars
        self.assertEqual(cfg_dict['testsection']['testkey'], '< hidden >')

        # test display_source
        cfg_dict = conf.as_dict(display_source=True)
        self.assertEqual(
            cfg_dict['core']['load_examples'][1], 'airflow config')
        self.assertEqual(
            cfg_dict['testsection']['testkey'], ('< hidden >', 'env var'))

        # test display_sensitive
        cfg_dict = conf.as_dict(display_sensitive=True)
        self.assertEqual(cfg_dict['testsection']['testkey'], 'testvalue')

        # test display_source and display_sensitive
        cfg_dict = conf.as_dict(display_sensitive=True, display_source=True)
        self.assertEqual(
            cfg_dict['testsection']['testkey'], ('testvalue', 'env var'))

    def test_command_config(self):
        TEST_CONFIG = '''[test]
key1 = hello
key2_cmd = printf cmd_result
key3 = airflow
key4_cmd = printf key4_result
'''
        TEST_CONFIG_DEFAULT = '''[test]
key1 = awesome
key2 = airflow

[another]
key6 = value6
'''

        test_conf = AirflowConfigParser(
            default_config=parameterized_config(TEST_CONFIG_DEFAULT))
        test_conf.read_string(TEST_CONFIG)
        test_conf.as_command_stdout = test_conf.as_command_stdout | {
            ('test', 'key2'),
            ('test', 'key4'),
        }
        self.assertEqual('hello', test_conf.get('test', 'key1'))
        self.assertEqual('cmd_result', test_conf.get('test', 'key2'))
        self.assertEqual('airflow', test_conf.get('test', 'key3'))
        self.assertEqual('key4_result', test_conf.get('test', 'key4'))
        self.assertEqual('value6', test_conf.get('another', 'key6'))

        self.assertTrue(test_conf.has_option('test', 'key1'))
        self.assertTrue(test_conf.has_option('test', 'key2'))
        self.assertTrue(test_conf.has_option('test', 'key3'))
        self.assertTrue(test_conf.has_option('test', 'key4'))
        self.assertFalse(test_conf.has_option('test', 'key5'))
        self.assertTrue(test_conf.has_option('another', 'key6'))

    def test_remove_option(self):
        TEST_CONFIG = '''[test]
key1 = hello
key2 = airflow
'''
        TEST_CONFIG_DEFAULT = '''[test]
key1 = awesome
key2 = airflow
'''

        test_conf = AirflowConfigParser(
            default_config=parameterized_config(TEST_CONFIG_DEFAULT))
        test_conf.read_string(TEST_CONFIG)

        self.assertEqual('hello', test_conf.get('test', 'key1'))
        test_conf.remove_option('test', 'key1', remove_default=False)
        self.assertEqual('awesome', test_conf.get('test', 'key1'))

        test_conf.remove_option('test', 'key2')
        self.assertFalse(test_conf.has_option('test', 'key2'))

    def test_getsection(self):
        TEST_CONFIG = '''
[test]
key1 = hello
'''
        TEST_CONFIG_DEFAULT = '''
[test]
key1 = awesome
key2 = airflow

[another]
key3 = value3
'''
        test_conf = AirflowConfigParser(
            default_config=parameterized_config(TEST_CONFIG_DEFAULT))
        test_conf.read_string(TEST_CONFIG)

        self.assertEqual(
            OrderedDict([('key1', 'hello'), ('key2', 'airflow')]),
            test_conf.getsection('test')
        )
        self.assertEqual(
            OrderedDict([('key3', 'value3')]),
            test_conf.getsection('another')
        )

    def test_broker_transport_options(self):
        section_dict = conf.getsection("celery_broker_transport_options")
        self.assertTrue(isinstance(section_dict['visibility_timeout'], int))

        self.assertTrue(isinstance(section_dict['_test_only_bool'], bool))

        self.assertTrue(isinstance(section_dict['_test_only_float'], float))

        self.assertTrue(isinstance(section_dict['_test_only_string'], six.string_types))

    def test_deprecated_options(self):
        # Guarantee we have a deprecated setting, so we test the deprecation
        # lookup even if we remove this explicit fallback
        conf.deprecated_options['celery'] = {
            'worker_concurrency': 'celeryd_concurrency',
        }

        # Remove it so we are sure we use the right setting
        conf.remove_option('celery', 'worker_concurrency')

        with self.assertWarns(DeprecationWarning):
            os.environ['AIRFLOW__CELERY__CELERYD_CONCURRENCY'] = '99'
            self.assertEquals(conf.getint('celery', 'worker_concurrency'), 99)
            os.environ.pop('AIRFLOW__CELERY__CELERYD_CONCURRENCY')

        with self.assertWarns(DeprecationWarning):
            conf.set('celery', 'celeryd_concurrency', '99')
            self.assertEquals(conf.getint('celery', 'worker_concurrency'), 99)
            conf.remove_option('celery', 'celeryd_concurrency')

    def test_deprecated_options_cmd(self):
        # Guarantee we have a deprecated setting, so we test the deprecation
        # lookup even if we remove this explicit fallback
        conf.deprecated_options['celery'] = {'result_backend': 'celery_result_backend'}
        conf.as_command_stdout.add(('celery', 'celery_result_backend'))

        conf.remove_option('celery', 'result_backend')
        conf.set('celery', 'celery_result_backend_cmd', '/bin/echo 99')

        with self.assertWarns(DeprecationWarning):
            self.assertEquals(conf.getint('celery', 'result_backend'), 99)


text:
'use strict';

/**
 * Module dependencies
 */
var needsPolicy = require('../policies/needs.server.policy'),
  needs = require('../controllers/needs.server.controller');

module.exports = function(app) {
  // Needs Routes
  app.route('/api/needs').all(needsPolicy.isAllowed)
    .get(needs.list)
    .post(needs.create);

  app.route('/api/needs/:needId').all(needsPolicy.isAllowed)
    .get(needs.read)
    .put(needs.update)
    .delete(needs.delete);

  // Finish by binding the Need middleware
  app.param('needId', needs.needByID);
};


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn vcvttss2si_1() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(EDI)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 250], OperandSize::Dword)
}

#[test]
fn vcvttss2si_2() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(ESP)), operand2: Some(IndirectScaledIndexed(EDX, EAX, Two, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 36, 66], OperandSize::Dword)
}

#[test]
fn vcvttss2si_3() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(ESI)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 242], OperandSize::Qword)
}

#[test]
fn vcvttss2si_4() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(EDI)), operand2: Some(IndirectScaledDisplaced(RSI, Two, 768853748, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 60, 117, 244, 198, 211, 45], OperandSize::Qword)
}

#[test]
fn vcvttss2si_5() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(RCX)), operand2: Some(Direct(XMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 250, 44, 200], OperandSize::Qword)
}

#[test]
fn vcvttss2si_6() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(RBX)), operand2: Some(IndirectDisplaced(RDI, 1459352901, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 250, 44, 159, 69, 245, 251, 86], OperandSize::Qword)
}

#[test]
fn vcvttss2si_7() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(EBX)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: true, mask: None, broadcast: None }, &[98, 241, 126, 24, 44, 223], OperandSize::Dword)
}

#[test]
fn vcvttss2si_8() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(ESP)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 1876457298, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 36, 77, 82, 119, 216, 111], OperandSize::Dword)
}

#[test]
fn vcvttss2si_9() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(EDI)), operand2: Some(Direct(XMM22)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: true, mask: None, broadcast: None }, &[98, 177, 126, 24, 44, 254], OperandSize::Qword)
}

#[test]
fn vcvttss2si_10() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(EDI)), operand2: Some(IndirectScaledDisplaced(RAX, Two, 655223427, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 44, 60, 69, 131, 234, 13, 39], OperandSize::Qword)
}

#[test]
fn vcvttss2si_11() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(RDX)), operand2: Some(Direct(XMM18)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: true, mask: None, broadcast: None }, &[98, 177, 254, 24, 44, 210], OperandSize::Qword)
}

#[test]
fn vcvttss2si_12() {
    run_test(&Instruction { mnemonic: Mnemonic::VCVTTSS2SI, operand1: Some(Direct(RBX)), operand2: Some(IndirectDisplaced(RAX, 858370277, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 225, 250, 44, 152, 229, 176, 41, 51], OperandSize::Qword)
}


text:
package org.easyrec.plugin.itemitem.impl;

import org.easyrec.model.core.ItemAssocVO;
import org.easyrec.plugin.itemitem.ItemItemService;
import org.easyrec.plugin.itemitem.store.dao.impl.ActionDAOMemoryImpl;
import org.easyrec.plugin.itemitem.test.helpers.ItemAssocServiceStub;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.util.Date;
import java.util.List;

import static org.easyrec.plugin.itemitem.test.matchers.IsCloseToItemAssocMatcher.closeToItemAssoc;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link AdjustedCosineSimilarityCalculationStrategy}.
Company:  SAT, Research Studios
 * Austria

Copyright:  (c) 2007

last modified:
 $Author$
 $Date$

 * $Revision$

 *
 * @author Patrick Marschik
 */
public class AdjustedCosineSimilarityCalculationStrategyTest extends AbstractySimilarityCalculationStrategyTest {
    // ------------------------------ FIELDS ------------------------------

    private AdjustedCosineSimilarityCalculationStrategy strategy;

    // -------------------------- OTHER METHODS --------------------------

    @Before
    public void before() {
        actionDAO = new ActionDAOMemoryImpl(lemireRatings, 1);
        itemAssocService = new ItemAssocServiceStub();

        strategy = new AdjustedCosineSimilarityCalculationStrategy(actionDAO, itemAssocService);
    }

    @Test
    @Ignore
    public void calculateSimilarity_isCorrect() {
        Date now = new Date();

        strategy.calculateSimilarity(1, 1, 1, ASSOC_TYPE, SOURCE_TYPE, VIEW_TYPE, now, null);

        List<ItemAssocVO<Integer,Integer>> result = itemAssocService
                .getItemAssocs();

        double delta = 1.0e-6;

        assertThat(result.size(), is(16));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(1, 2, -0.91557180812291200000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(2, 1, -0.91557180812291200000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(1, 3, -0.42262153619390100000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(3, 1, -0.42262153619390100000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(1, 4, -0.98788278773686600000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(4, 1, -0.98788278773686600000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(1, 5, 1.0, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(5, 1, 1.0, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(2, 3, -1.0, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(3, 2, -1.0, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(2, 4, 0.90508621498992000000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(4, 2, 0.90508621498992000000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(3, 4, 0.40354863494078700000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(4, 3, 0.40354863494078700000, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(4, 5, -1.0, now), delta)));
        assertThat(result, hasItem(closeToItemAssoc(makeAssoc(5, 4, -1.0, now), delta)));
    }

    protected String getSourceInfo() { return ItemItemService.SOURCE_INFO_COSINE_ADJUSTED; }

    @Test
    public void getSourceInfo_isCorrect() {
        assertThat(strategy.getSourceInfo(), is(ItemItemService.SOURCE_INFO_COSINE_ADJUSTED));
    }
}


text:
/*
 *		INETPEER - A storage for permanent information about peers
 *
 *  Version:	$Id: inetpeer.h,v 1.2 2002/01/12 07:54:56 davem Exp $
 *
 *  Authors:	Andrey V. Savochkin <saw@msu.ru>
 */

#ifndef _NET_INETPEER_H
#define _NET_INETPEER_H

#include <linux/types.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/spinlock.h>
#include <asm/atomic.h>

struct inet_peer
{
	struct inet_peer	*avl_left, *avl_right;
	struct inet_peer	*unused_next, **unused_prevp;
	unsigned long		dtime;		/* the time of last use of not
						 * referenced entries */
	atomic_t		refcnt;
	__u32			v4daddr;	/* peer's address */
	__u16			avl_height;
	__u16			ip_id_count;	/* IP ID for the next packet */
	atomic_t		rid;		/* Frag reception counter */
	__u32			tcp_ts;
	unsigned long		tcp_ts_stamp;
};

void			inet_initpeers(void) __init;

/* can be called with or without local BH being disabled */
struct inet_peer	*inet_getpeer(__u32 daddr, int create);

extern spinlock_t inet_peer_unused_lock;
extern struct inet_peer **inet_peer_unused_tailp;
/* can be called from BH context or outside */
static inline void	inet_putpeer(struct inet_peer *p)
{
	spin_lock_bh(&inet_peer_unused_lock);
	if (atomic_dec_and_test(&p->refcnt)) {
		p->unused_prevp = inet_peer_unused_tailp;
		p->unused_next = NULL;
		*inet_peer_unused_tailp = p;
		inet_peer_unused_tailp = &p->unused_next;
		p->dtime = jiffies;
	}
	spin_unlock_bh(&inet_peer_unused_lock);
}

extern spinlock_t inet_peer_idlock;
/* can be called with or without local BH being disabled */
static inline __u16	inet_getid(struct inet_peer *p, int more)
{
	__u16 id;

	spin_lock_bh(&inet_peer_idlock);
	id = p->ip_id_count;
	p->ip_id_count += 1 + more;
	spin_unlock_bh(&inet_peer_idlock);
	return id;
}

#endif /* _NET_INETPEER_H */


text:
delegate是委托,用于抽象一系列参数相同、返回值相同的方法。

event是事件 事件本质上讲是相同委托的集合。事件使用发布-订阅(publisher-subscriber)模型。

# 2 Action

Action是泛型的委托,内部使用delegate实现。无返回值

```c#
public delegate void Action();
public delegate void Action<in T>(T arg);
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
.
.
.
public delegate void Action<in T1, in T2, ... ,in T16>(T1 arg1, T2 arg2, ... , T16 arg16);
```

# 3 EventHandler

```c#
public delegate void EventHandler(object sender, EventArgs e);
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs;
```

用例
```c#
private EventHandler<PlaySoundSuccessEventArgs> m_PlaySoundSuccessEventHandler;

public event EventHandler<PlaySoundSuccessEventArgs> PlaySoundSuccess
{
    add
    {
        m_PlaySoundSuccessEventHandler += value;
    }
    remove
    {
        m_PlaySoundSuccessEventHandler -= value;
    }
}
```


text:
blast_results :: blast_results (ALIGN* align, int keep_per_query, double score_thresh, int rep_len, double rep_perc)
:
ScanResults (align, keep_per_query, SST_NN, NULL, score_thresh, rep_len, rep_perc)
{
}

bool blast_results :: match_found  (NN_SEQ& xseq, int xpos, NN_SEQ& yseq, int ypos, int len, int matches)
{
    if (!(curx == xseq))
    {
        curx = xseq;
        seen_y.erase (seen_y.begin (), seen_y.end ());
    }
    else
    {
        req t (yseq);
        if (!seen_y.insert (t).second) return true;
    }

    ScanResults::match_found (&yseq, &xseq, matches);
    return true;
}


text:
require 'rails_helper'

RSpec.describe EmailChangeRequest do
  context 'validations' do
    describe '#new_email' do
      describe 'when email is invalid' do
        it 'should not be valid' do
          email_change_request = Fabricate.build(:email_change_request, new_email: 'testdiscourse.org')
          expect(email_change_request).to_not be_valid
        end
      end
    end
  end
end


text:
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/responsiveslides.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<link href="images/favicon.ico" rel="shortcut icon">

				Helen's Auto Sales

						(519) 781-1588

						C#206,1601 VICTORIA ST. N. KITCHENER ON CA, N2B 3E6

HOME

INVENTORY

CONTACT US

Leave us a message

						<form>

								Name * <input
									type="text" class="form-control" id="name"
									placeholder="Jane Doe">

								Email address * <input
									type="email" class="form-control" id="email"
									placeholder="jane.doe@example.com">

								Title <input
									type="text" class="form-control" id="title"
									placeholder="Title">

								Message
								<textarea class="form-control" rows="5"></textarea>

							<button type="submit" class="btn btn-default">Submit</button>
						</form>

				Helen's Auto Sales © 2014
				Privacy

				HOME
				INVENTORY
				CONTACT US


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZocBuild.Database
{
    /// <summary>
    /// Represents a database object on a specific database server, database, and schema.
    /// </summary>
    public class DatabaseObject
    {
        /// <summary>
        /// Instantiates a database object with the given identifiers.
        /// </summary>
        /// <param name="serverName">The name of the database server.</param>
        /// <param name="databaseName">The name of the database.</param>
        /// <param name="schemaName">The name of the schema.</param>
        /// <param name="objectName">The name of the object.</param>
        public DatabaseObject(string serverName, string databaseName, string schemaName, string objectName)
        {
            ServerName = serverName;
            DatabaseName = databaseName;
            SchemaName = schemaName;
            ObjectName = objectName;
        }

        /// <summary>
        /// Gets the name of the database server.
        /// </summary>
        public string ServerName { get; private set; }

        /// <summary>
        /// Gets the name of the database.
        /// </summary>
        public string DatabaseName { get; private set; }

        /// <summary>
        /// Gets the name of the schema.
        /// </summary>
        public string SchemaName { get; private set; }

        /// <summary>
        /// Gets the name of this database object.
        /// </summary>
        public string ObjectName { get; private set; }

        /// <summary>
        /// Returns a string representation of the object.
        /// </summary>
        /// <returns>A string that describes this object.</returns>
        public override string ToString()
        {
            string result = string.Empty;
            if(!string.IsNullOrWhiteSpace(ServerName))
            {
                result = ServerName;
            }
            if (!string.IsNullOrWhiteSpace(result))
            {
                result += ".";
            }
            if(!string.IsNullOrWhiteSpace(DatabaseName))
            {
                result += DatabaseName;
            }
            if (!string.IsNullOrWhiteSpace(result))
            {
                result += ".";
            }
            if (!string.IsNullOrWhiteSpace(SchemaName))
            {
                result += SchemaName;
            }
            if (!string.IsNullOrWhiteSpace(result))
            {
                result += ".";
            }
            result += ObjectName;
            return result;
        }
    }

    /// <summary>
    /// Represents a database object with a specific type on a specific database server, database, and schema.
    /// </summary>
    public class TypedDatabaseObject : DatabaseObject
    {
        /// <summary>
        /// Instantiates a database object with the given identifiers.
        /// </summary>
        /// <param name="serverName">The name of the database server.</param>
        /// <param name="databaseName">The name of the database.</param>
        /// <param name="schemaName">The name of the schema.</param>
        /// <param name="objectName">The name of the object.</param>
        /// <param name="objectType">The type of the object.</param>
        public TypedDatabaseObject(string serverName, string databaseName, string schemaName, string objectName, DatabaseObjectType objectType)
            : base(serverName, databaseName, schemaName, objectName)
        {
            ObjectType = objectType;
        }

        /// <summary>
        /// Gets the type of this database object.
        /// </summary>
        public DatabaseObjectType ObjectType { get; private set; }
    }

    /// <summary>
    /// Defines an enumeration of supported database objects.
    /// </summary>
    public enum DatabaseObjectType
    {
        /// <summary>
        /// Indicates that the object is a view.
        /// </summary>
        View = 0,

        /// <summary>
        /// Indicates that the object is a stored procedure.
        /// </summary>
        Procedure = 1,

        /// <summary>
        /// Indicates that the object is a user-defined function.
        /// </summary>
        Function = 2,

        /// <summary>
        /// Indicates that the object is a user-defined type.
        /// </summary>
        Type = 3
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Bareplan: Bareplan.Core.HtmlExporter Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Bareplan

Plan tasks

Main Page

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Namespaces Functions Properties

Bareplan

Core

HtmlExporter

Public Member Functions |
Public Attributes

Bareplan.Core.HtmlExporter Class Reference

Exports a class to HTML format.
 More...

Inheritance diagram for Bareplan.Core.HtmlExporter:

  <map id="Bareplan.Core.HtmlExporter_map" name="Bareplan.Core.HtmlExporter_map">
<area href="class_bareplan_1_1_core_1_1_document_exporter.html" title="Base class for all document exporters." alt="Bareplan.Core.DocumentExporter" shape="rect" coords="0,0,203,24"/>
</map>

List of all members.

Public Member Functions

 	HtmlExporter (Document doc, string path)

override void 	Export ()

 	Actually exports the document to an HTML string.

 Public Member Functions inherited from Bareplan.Core.DocumentExporter

 	DocumentExporter (Document doc, string path)

 	The base Bareplan.Core.DocumentExporter class for all exporters.

void 	Save ()

 	Saves the Contents. Invokes Export() if Contents is empty.

Public Attributes

const string 	DefaultExt = "html"

Additional Inherited Members

 Properties inherited from Bareplan.Core.DocumentExporter

string 	Contents [get, set]

 	The contents to be stored in the file. This is normally generated by Export().

Document 	Document [get, set]

 	Gets or sets the document.

string 	Path [get, set]

 	Gets or sets the path to the file to export.

Detailed Description

Exports a class to HTML format.

Member Function Documentation

          override void Bareplan.Core.HtmlExporter.Export
          (
          	)

virtual

Actually exports the document to an HTML string.

Implements Bareplan.Core.DocumentExporter.

The documentation for this class was generated from the following file:

C:/Users/baltasarq/Dropbox/prys/bareplan/Core/HtmlExporter.cs

<address class="footer">
Generated on Mon Oct 28 2013 17:50:24 for Bareplan by

 1.8.1
</address>