text:
{- |
Module      : $Header$
Description : SELinux policy module parsing and aggregation
Copyright   : (c) Galois, Inc.

SELinux policy module parsing and aggregation
-}

module SCD.M4.ModuleFiles(allDescendantFiles, readPolicyModule,
  readAllPolicyModules, readPolicy) where

import SCD.M4.Syntax(PolicyModule(..), LayerModule, Policy(..),
  SupportDefs, ClassPermissionDefs, GlobalBooleans,
  ModuleConf, IfdefDecl(..))

import SCD.M4.Util ( implementationId )

import SCD.SELinux.Syntax(mkId)
import System.Directory(getDirectoryContents)

import SCD.M4.Parser(parseInterface, parseImplementation,
  parseFileContexts, parseSupportDefs, parseClassPermissionDefs,
  parseGlobalBooleans, parseModulesConf, parseIfdefDecls)

import SCD.SELinux.Parser(AccessVectors, parseClasses,
  parseAccessVectors, parseInitialSids)

import SCD.SELinux.Syntax(ClassId, Sid)

import System.FilePath(splitFileName, takeFileName, addExtension,
  dropExtension, takeExtension, extSeparator,
  dropTrailingPathSeparator, (</>), takeBaseName)

import Data.NonEmptyList(NonEmptyList)
import Data.List(sort)

import Text.Regex.Posix.Wrap((=~))
import Text.Regex.Posix.String()

allDescendantFiles :: FilePath -> IO [FilePath]
allDescendantFiles f = do
  c <- (sort . map ((f ++ "/") ++) . filter ((/=".") . take 1)) `fmap`
       getDirectoryContents f `catch` (const (return []))
  ch <- mapM allDescendantFiles c
  return (c ++ concat ch)

-- | Filename extension for interface files
interfaceExtension :: String
interfaceExtension = "if"

-- | Filename extension for implementation files
implementationExtension :: String
implementationExtension = "te"

-- | Filename extension for file-context configuration files
fileContextExtension :: String
fileContextExtension = "fc"

-- | Filename extension for support-definition files
supportExtension :: String
supportExtension = "spt"

-- | Given a filename, read the interface, implementation and
-- file-configuration files (by appending ".if", ".te", and ".fc" to
-- the filename stripped from its extension).

readPolicyModule :: FilePath -> IO PolicyModule
readPolicyModule p = do
  let p' = dropExtension p
  i <- parseFile parseInterface interfaceExtension p'
  t <- parseFile parseImplementation implementationExtension p'
  let l = fst (getLayerModule p)
      lm = (l,implementationId t)
  f <- parseFile parseFileContexts fileContextExtension p'
  return PolicyModule{ layerModule = lm
                     , interface = i
                     , implementation = t
                     , fileContexts = f
                     , baseName = takeBaseName p'
                     }

-- | Extract the layer and the name from the filename prefix of a policy module
getLayerModule :: String -> LayerModule
getLayerModule p = (mkId l,mkId m)
  where (d,m) = splitFileName p
        l = takeFileName (dropTrailingPathSeparator d)

parseFile :: (FilePath -> String -> Either String a) -> String -> FilePath -> IO a
parseFile parse s p = do
  let f = addExtension p s
  c <- readFile f
  either (fail . ((f++": parser error: ")++))
         return
         (parse f c)

-- | Given a directory name containing all policy modules (in subdirectories)
-- , return a list of policy
readAllPolicyModules :: FilePath -> IO [PolicyModule]
readAllPolicyModules d = do
  ps <- filter ((==extSeparator:interfaceExtension) . takeExtension)
       `fmap` allDescendantFiles d
  mapM readPolicyModule ps

classPermissionFiles :: [FilePath]
classPermissionFiles = [ "obj_perm_sets" ]

readClassPermissionDefsFiles :: FilePath -> IO ClassPermissionDefs
readClassPermissionDefsFiles d = concat `fmap` mapM (readClassPermissionDefs . (d</>)) classPermissionFiles

supportFiles :: [FilePath]
supportFiles = [ "file_patterns"
               , "ipc_patterns"
               , "misc_patterns"
               ]

booleanFiles :: [FilePath]
booleanFiles = [ "global_booleans"
               , "global_tunables"
               ]

readSupportDefsFiles :: FilePath -> IO SupportDefs
readSupportDefsFiles d = ((specialSupportDefs++) . concat) `fmap`
                    mapM (readSupportDefs . (d</>)) supportFiles

readGlobalBooleanFiles :: FilePath -> IO GlobalBooleans
readGlobalBooleanFiles d = concat `fmap`
                           mapM (readGlobalBooleans . (d</>)) booleanFiles

-- Special hack to get a definition from misc_macros that ought to be in misc_patterns
specialSupportDefs :: SupportDefs
specialSupportDefs = either (error "specialSupportDefs") id
                     (parseSupportDefs "" "define(`can_exec',`allow $1 $2:file { mmap_file_perms execute_no_trans };')")

readClassPermissionDefs :: FilePath -> IO ClassPermissionDefs
readClassPermissionDefs = parseFile parseClassPermissionDefs supportExtension

readSupportDefs :: FilePath -> IO SupportDefs
readSupportDefs = parseFile parseSupportDefs supportExtension

readGlobalBooleans :: FilePath -> IO GlobalBooleans
readGlobalBooleans = parseFile parseGlobalBooleans ""

readClasses :: FilePath -> IO ([ClassId], [ClassId])
readClasses f = do
  kcs <- parseFile (parseFilterClasses (not.userspace)) "" f
  ucs <- parseFile (parseFilterClasses userspace) "" f
  return (kcs,ucs)
  where parseFilterClasses fi f' = parseClasses f' . unlines . filter' fi . lines
        userspace = (=~"#[ \t]*userspace")
        filter' p ll = [if p l then l else "" | l <- ll]

readAccessVectors :: FilePath -> IO AccessVectors
readAccessVectors = parseFile parseAccessVectors ""

readInitialSids :: FilePath -> IO (NonEmptyList Sid)
readInitialSids = parseFile parseInitialSids ""

_readModulesConf :: FilePath -> IO [ModuleConf]
_readModulesConf = parseFile parseModulesConf ""

readIfdefDecls :: Maybe FilePath -> IO [IfdefDecl]
readIfdefDecls mifdeffile =
  case mifdeffile of
    Just f -> parseFile parseIfdefDecls "" f
    Nothing -> do let known s = IfdefDecl (mkId s) Nothing
                      set s b = IfdefDecl (mkId s) (Just b)
                  return [ known "enable_mls"
                         , known "enable_mcs"
                         , known "distro_rhel4"
                         , known "distro_redhat"
                         , known "distro_debian"
                         , known "distro_gentoo"
                         , known "distro_suse"
                         , known "distro_ubuntu"
                         , known "targeted_policy"
                         , known "direct_sysadm_daemon"
                         , known "hide_broken_symptoms"
                         , set "TODO" False
                         ]

-- | Read a policy consisting of a set of modules and support
-- definitions, given path to ifdef-declaration file (unless the
-- builtin should be used), and path to reference policy directory.
readPolicy :: Maybe FilePath -> FilePath -> IO Policy
readPolicy mifdeffile pdtop = do
  let pd = pdtop </> "policy"
  ifds <- readIfdefDecls mifdeffile
  ms        <- readAllPolicyModules            (pd </> "modules")
  -- Ignore modules.conf, since it is generated from the module source.
  -- Potentially, we might want to read modules.conf and compare its content
  -- with the module source.
  -- mc        <- readModulesConf              (pd </> "modules.conf")
  let mc = []
  sds       <- readSupportDefsFiles         (pd </> "support")
  bs        <- readGlobalBooleanFiles       pd
  cpds      <- readClassPermissionDefsFiles (pd </> "support")
  (kcs,ucs) <- readClasses                  (pd </> "flask/security_classes")
  sids      <- readInitialSids              (pd </> "flask/initial_sids")
  (co,avs)  <- readAccessVectors            (pd </> "flask/access_vectors")
  return Policy{ policyModules = ms
               , supportDefs = sds
               , classPermissionDefs = cpds
               , kernelClasses = kcs
               , userClasses = ucs
               , initialSids = sids
               , commonPerms = co
               , avPerms = avs
               , globalBooleans = bs
               , modulesConf = mc
               , ifdefDecls = ifds
               }


text:
namespace yocs_msgs
{

  class NavigateToActionResult : public ros::Msg
  {
    public:
      typedef std_msgs::Header _header_type;
      _header_type header;
      typedef actionlib_msgs::GoalStatus _status_type;
      _status_type status;
      typedef yocs_msgs::NavigateToResult _result_type;
      _result_type result;

    NavigateToActionResult():
      header(),
      status(),
      result()
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      offset += this->header.serialize(outbuffer + offset);
      offset += this->status.serialize(outbuffer + offset);
      offset += this->result.serialize(outbuffer + offset);
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      offset += this->header.deserialize(inbuffer + offset);
      offset += this->status.deserialize(inbuffer + offset);
      offset += this->result.deserialize(inbuffer + offset);
     return offset;
    }

    const char * getType(){ return "yocs_msgs/NavigateToActionResult"; };
    const char * getMD5(){ return "8b1c61040f1b5f7e7ce4bb6b2de470b0"; };

  };

}
#endif

redpajama_set_name: RedPajamaGithub


text:
package com.webapp.client.userinterface;

import com.google.gwt.user.client.ui.Composite;
import com.webapp.client.userinterface.resources.Resources;

public class ResourceWidget extends Composite {
	static {
		Resources.INSTANCE.introduction().ensureInjected();
		Resources.INSTANCE.mainpage().ensureInjected();
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ClosestColor
{
    public class RgbClosestColor : IClosestColor
    {
        public IReadOnlyList<IColor> GetClosestColorInGroup(IReadOnlyList<IColor> colorGroups, IColor color)
        {
            if (colorGroups == null)
            {
                throw new ArgumentNullException(nameof(colorGroups));
            }
            if (color == null)
            {
                throw new ArgumentNullException(nameof(color));
            }

            var hexColor = HexColor.Create(color);
            var hexColorGroups = colorGroups.Select(HexColor.Create).ToList();

            var colorDiffs = hexColorGroups.Select(n => ColorHelper.ColorDiff(HexColor.Create(n).Value, hexColor.Value))
                                           .Min(n => n);

            return colorGroups.Where(
                (x, i) => hexColorGroups.FindAllIndexes(n =>
                ColorHelper.ColorDiff(n.Value, hexColor.Value) ==colorDiffs).Contains(i))
                .ToList();

        }

    }
}


text:
#ifndef HORN_SUBSUME_MODEL_CONVERTER_H_
#define HORN_SUBSUME_MODEL_CONVERTER_H_

#include "model_converter.h"
#include "th_rewriter.h"

class horn_subsume_model_converter : public model_converter {
    ast_manager&    m;
    func_decl_ref_vector m_funcs;
    expr_ref_vector      m_bodies;
    th_rewriter          m_rewrite;
    app_ref_vector       m_delay_head;
    expr_ref_vector      m_delay_body;

    void add_default_false_interpretation(expr* e, model_ref& md);

    struct add_default_proc {
        ast_manager& m;
        model_ref& m_md;
        add_default_proc(ast_manager& m, model_ref& md): m(m), m_md(md) {}
        void operator()(app* n);
        void operator()(expr* n) {}
    };

public:

 horn_subsume_model_converter(ast_manager& m):
    m(m), m_funcs(m), m_bodies(m), m_rewrite(m),
        m_delay_head(m), m_delay_body(m) {}

    bool mk_horn(expr* clause, func_decl_ref& pred, expr_ref& body);

    bool mk_horn(app* head, expr* body, func_decl_ref& pred, expr_ref& body_res);

    void insert(app* head, expr* body);

    void insert(app* head, unsigned sz, expr* const* body);

    void insert(func_decl* p, expr* body) { m_funcs.push_back(p); m_bodies.push_back(body); }

    virtual void operator()(model_ref& _m);

    virtual model_converter * translate(ast_translation & translator);

    ast_manager& get_manager() { return m; }

};

#endif


text:
using System;
using System.IO;
using TESUnity.UI;
using UnityEngine;

namespace TESUnity
{
    public class TESUnity : MonoBehaviour
    {
        public static TESUnity instance;

        public enum MWMaterialType
        {
            Default, Standard, BumpedDiffuse, Unlit
        }

        #region Inspector-set Members

#if UNITY_EDITOR
        [Header("Editor Only")]
        [SerializeField]
        private bool _bypassINIConfig = false;
#endif

        [Header("Global")]
        public string dataPath;
        public bool useKinematicRigidbodies = true;
        public bool playMusic = false;
        public bool enableLog = false;

        [Header("Rendering")]
        public MWMaterialType materialType = MWMaterialType.BumpedDiffuse;
        public RenderingPath renderPath = RenderingPath.Forward;

        [Header("Lighting")]
        public float ambientIntensity = 1.5f;
        public bool renderSunShadows = false;
        public bool renderLightShadows = false;
        public bool renderExteriorCellLights = false;
        public bool animateLights = false;

        [Header("Effects")]
        public bool antiAliasing = false;
        public bool ambientOcclusion = false;
        public bool bloom = false;
        public bool waterBackSideTransparent = false;

        [Header("VR")]
        public bool followHeadDirection = false;
        public bool directModePreview = true;

        [Header("UI")]
        public UIManager UIManager;
        public Sprite UIBackgroundImg;
        public Sprite UICheckmarkImg;
        public Sprite UIDropdownArrowImg;
        public Sprite UIInputFieldBackgroundImg;
        public Sprite UIKnobImg;
        public Sprite UIMaskImg;
        public Sprite UISpriteImg;

        [Header("Prefabs")]
        public GameObject playerPrefab;
        public GameObject waterPrefab;

        [Header("Debug")]
        public bool creaturesEnabled = false;
        public bool npcsEnabled = false;

        #endregion

        private MorrowindDataReader MWDataReader;
        private MorrowindEngine MWEngine;
        private MusicPlayer musicPlayer;

        public MorrowindEngine Engine
        {
            get { return MWEngine; }
        }

        public TextureManager TextureManager
        {
            get { return MWEngine.textureManager; }
        }

        private void Awake()
        {
            Debug.unityLogger.logEnabled = enableLog;

            instance = this;

            var path = dataPath;

#if UNITY_EDITOR
            if(!_bypassINIConfig)
            {
                path = GameSettings.CheckSettings(this);
            }
#else
            var path = GameSettings.CheckSettings(this);
#endif

            if(!GameSettings.IsValidPath(path))
            {
                GameSettings.SetDataPath(string.Empty);
                UnityEngine.SceneManagement.SceneManager.LoadScene("AskPathScene");
            }
            else
            {
                dataPath = path;
            }
        }

        private void Start()
        {
            MWDataReader = new MorrowindDataReader(dataPath);
            MWEngine = new MorrowindEngine(MWDataReader, UIManager);

            if(playMusic)
            {
                // Start the music.
                musicPlayer = new MusicPlayer();

                foreach(var songFilePath in Directory.GetFiles(dataPath + "/Music/Explore"))
                {
                    if(!songFilePath.Contains("Morrowind Title"))
                    {
                        musicPlayer.AddSong(songFilePath);
                    }
                }

                musicPlayer.Play();
            }

            // Spawn the player.
            //MWEngine.SpawnPlayerInside(playerPrefab, new Vector2i(4537908, 1061158912), new Vector3(0.8f, -0.45f, -1.4f));

            MWEngine.SpawnPlayerOutside(playerPrefab, new Vector2i(-2, -9), new Vector3(-137.94f, 2.30f, -1037.6f));
        }

        private void OnDestroy()
        {
            if(MWDataReader != null)
            {
                MWDataReader.Close();
                MWDataReader = null;
            }
        }

        private void Update()
        {
            MWEngine.Update();

            if(playMusic)
            {
                musicPlayer.Update();
            }
        }

        private void TestAllCells(string resultsFilePath)
        {
            using(StreamWriter writer = new StreamWriter(resultsFilePath))
            {
                foreach(var record in MWDataReader.MorrowindESMFile.GetRecordsOfType<ESM.CELLRecord>())
                {
                    var CELL = (ESM.CELLRecord)record;

                    try
                    {
                        var cellInfo = MWEngine.cellManager.StartInstantiatingCell(CELL);
                        MWEngine.temporalLoadBalancer.WaitForTask(cellInfo.objectsCreationCoroutine);

                        DestroyImmediate(cellInfo.gameObject);

                        writer.Write("Pass: ");
                    }
                    catch(Exception exception)
                    {
                        writer.Write("Fail: ");
                    }
                    catch
                    {
                        writer.Write("Fail: ");
                    }

                    if(!CELL.isInterior)
                    {
                        writer.WriteLine(CELL.gridCoords.ToString());
                    }
                    else
                    {
                        writer.WriteLine(CELL.NAME.value);
                    }

                    writer.Flush();
                }
            }
        }
    }
}


text:
package com.facebook.watchman;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.google.common.util.concurrent.ListenableFuture;
import org.immutables.value.Value;

public interface WatchmanClient {

  ListenableFuture<Map<String, Object>> clock(Path path);
  ListenableFuture<Map<String, Object>> clock(Path path, Number syncTimeout);

  ListenableFuture<Map<String, Object>> watch(Path path);

  ListenableFuture<Map<String,Object>> watchDel(Path path);

  ListenableFuture<Boolean> unsubscribe(SubscriptionDescriptor descriptor);

  ListenableFuture<SubscriptionDescriptor> subscribe(
      Path path,
      Map<String, Object> query,
      Callback listener);

  ListenableFuture<Map<String, Object>> version();

  ListenableFuture<Map<String, Object>> version(
      List<String> optionalCapabilities,
      List<String> requiredCapabilities);

  ListenableFuture<Map<String, Object>> run(List<Object> command);

  ListenableFuture<Boolean> unsubscribeAll();

  void close() throws IOException;

  void start();

  @Value.Immutable
  @Value.Style(visibility = Value.Style.ImplementationVisibility.PRIVATE)
  abstract class SubscriptionDescriptor {
    public abstract String root();
    public abstract String name();

    @Override
    public int hashCode() {
      return Objects.hash(root(), name());
    }
  }
}


text:
package com.oxygenxml.jats;

import javax.swing.text.BadLocationException;

import ro.sync.annotations.api.API;
import ro.sync.annotations.api.APIType;
import ro.sync.annotations.api.SourceType;
import ro.sync.ecss.extensions.api.ArgumentDescriptor;
import ro.sync.ecss.extensions.api.ArgumentsMap;
import ro.sync.ecss.extensions.api.AuthorAccess;
import ro.sync.ecss.extensions.api.AuthorOperation;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.AuthorSchemaManager;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ro.sync.ecss.extensions.api.schemaaware.SchemaAwareHandlerResult;
import ro.sync.ecss.extensions.commons.ImageFileChooser;

/**
 * Operation used to insert an image in JATS documents.
 */
@API(type=APIType.INTERNAL, src=SourceType.PUBLIC)
public class InsertGraphicOperation implements AuthorOperation {

  /**
   * The reference value argument sent by the WebAuthor.
   */
  private static final String ARGUMENT_REFERENCE_VALUE = "imageUrl";

  /**
   * @see ro.sync.ecss.extensions.api.AuthorOperation#doOperation(ro.sync.ecss.extensions.api.AuthorAccess, ro.sync.ecss.extensions.api.ArgumentsMap)
   */
  public void doOperation(AuthorAccess authorAccess, ArgumentsMap args)
  throws IllegalArgumentException, AuthorOperationException {
    // the Web Author passes the ref as an argument.
    String ref = (String)args.getArgumentValue(ARGUMENT_REFERENCE_VALUE);
    if (ref == null) {
      ref = ImageFileChooser.chooseImageFile(authorAccess);
    }
    if(ref != null) {
      insertImageRef(authorAccess, ref);
    }
  }

  /**
   * Insert an image reference.
   *
   * @param authorAccess Author access
   * @param ref The image reference
   * @return The insertion result
   * @throws AuthorOperationException
   */
  public static SchemaAwareHandlerResult insertImageRef(AuthorAccess authorAccess, String ref) throws AuthorOperationException {
    SchemaAwareHandlerResult result = null;
    int caretOffset = authorAccess.getEditorAccess().getCaretOffset();
    boolean insertImageRef = true;
      try {
        AuthorNode nodeAtOffset = authorAccess.getDocumentController().getNodeAtOffset(caretOffset);
        if(nodeAtOffset.getType() == AuthorNode.NODE_TYPE_ELEMENT){
          AuthorElement elementAtOffset = (AuthorElement) nodeAtOffset;
          if("graphic".equals(elementAtOffset.getLocalName())
        		  || "inline-graphic".equals(elementAtOffset.getLocalName())){
            //Replace the fileref
            authorAccess.getDocumentController().setAttribute("xlink:href", new AttrValue(ref), elementAtOffset);
            //We have changed the reference to the image.
            insertImageRef = false;
          }
        }
      } catch (BadLocationException e) {
    	  e.printStackTrace();
      }
      if(insertImageRef) {
    	  //First try to insert an inline-graphic
    	  String inlineGraphFrag = createFragmentToInsert(ref, "inline-graphic");
    	  AuthorDocumentFragment frag = authorAccess.getDocumentController().createNewDocumentFragmentInContext(inlineGraphFrag,  caretOffset);
    	  if(frag != null && authorAccess.getDocumentController().getAuthorSchemaManager().canInsertDocumentFragment(frag, caretOffset, AuthorSchemaManager.VALIDATION_MODE_LAX)){
    		 //Insert inline-graphic
        	  result = authorAccess.getDocumentController().insertFragmentSchemaAware(
        			  caretOffset, frag);
    	  } else {
    		  String graphicFrag = createFragmentToInsert(ref, "graphic");
    		  // Insert the graphic
    		  result = authorAccess.getDocumentController().insertXMLFragmentSchemaAware(
    				  graphicFrag,
    				  caretOffset);
    	  }
      }
    return result;
  }

  /**
   * Create a fragment to insert.
   *
   * @param ref The href value.
   * @param elemName The element name.
   */
  private static String createFragmentToInsert(String ref, String elemName) {
	  StringBuffer fragment = new StringBuffer();
	  fragment.append("<" + elemName + " ");
	  fragment.append("xmlns:xlink=\"http://www.w3.org/1999/xlink\" ");
	  fragment.append("xlink:href=\"");
	  fragment.append(ref);
	  fragment.append("\">");
	  fragment.append("</" + elemName + ">");
	  return fragment.toString();
  }

  /**
   * No arguments. The operation will display a dialog for choosing the image fileref.
   *
   * @see ro.sync.ecss.extensions.api.AuthorOperation#getArguments()
   */
  public ArgumentDescriptor[] getArguments() {
    return null;
  }

  /**
   * @see ro.sync.ecss.extensions.api.Extension#getDescription()
   */
  public String getDescription() {
    return "Insert a JATS image";
  }
}


text:
<?php

namespace Sloth\Platform\Web\Factory;

use DMS\Standard\DI\ClassResolvingTarget;
use Interop\Container\ContainerInterface;
use Sloth\Platform\Slack\SlackClientInterface;

class GenericSlackAwareFactory extends ClassResolvingTarget
{
    public function __invoke(ContainerInterface $container)
    {
        $class = $this->getTargetName();
        return new $class($container->get(SlackClientInterface::class));
    }
}


text:
import {Server, createServer,} from 'http'
import * as cluster from 'cluster'
const sticky = require('sticky-session')
import {ExpressApp} from "./express-app"

export class HttpServer {

  constructor(private server: Server, private port = 3000)
  {

    this.config()
  }

public static bootstrap(server: Server, port = 3000) {
    return new HttpServer(server,port)
}
private config() {
     if (!sticky.listen(this.server, this.port)) {
         this.server.once('listening',() => {
    console.log(`server started on ${this.port} port`);

  });
  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });

  cluster.on('online', (worker) => {
  console.log(`The worker responded after it was forked ${worker.process.pid}`);
  });
     }
     else {

     }
}

}


text:
package com.laytonsmith.core.compiler.keywords;

import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.core.MSVersion;
import com.laytonsmith.core.ParseTree;
import com.laytonsmith.core.compiler.Keyword;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import java.util.List;

/**
 *
 */
@Keyword.keyword("static")
public class StaticKeyword extends Keyword {

	@Override
	public int process(List<ParseTree> list, int keywordPosition) throws ConfigCompileException {
		throw new ConfigCompileException("Keyword not supported yet.", list.get(keywordPosition).getTarget());
	}

	@Override
	public String docs() {
		return "Indicates that the item is statically defined (i.e. not associated with a particular instance of a"
				+ " class, but rather the class itself).";
	}

	@Override
	public Version since() {
		return MSVersion.V0_0_0;
	}

}


text:
  Document Generation

    <button
      class="generate btn btn-primary"
      ng-click="exportConfig.export(exportConfig.selectedType)"
      >
      Printable {{ exportConfig.exportTypes[exportConfig.selectedType].name }}
    </button>

  Generation URL

    <input
      class="clipboard-text form-control url"
      type="text"
      readonly="readonly"
      value="{{ exportConfig.exportTypes[exportConfig.selectedType].link }}"
      >
    <button class="clipboard-button btn btn-default">

    </button>

  Please save your work before generating a report.


text:
<?php

$md5 = (isset($_GET['md5']) && $_GET['md5'] != "") ? $_GET['md5'] : NULL;
$name = (isset($_GET['name']) && $_GET['name'] != "") ? $_GET['name'] : NULL;

include("config.php");
include("function.php");

//Récupération du nom du fichier dans la BDD

$bdd = bddConnect();

if (($name != NULL) && (file_exists($FILES_FOLDER . $md5)))
{

	$size = filesize($FILES_FOLDER . $md5);

	header("Content-Type: application/force-download; name=\"" . $name . ".html\"");
	header("Content-Transfer-Encoding: UTF-8");
	header("Content-Length: $size");
	header("Content-Disposition: attachment; filename=\"" . $name . ".html\"");
	header("Expires: 0");
	header("Cache-Control: no-cache, must-revalidate");
	header("Pragma: no-cache");

	$bdd->exec("UPDATE reg_rglsit SET downloads=downloads+1 WHERE id=".$id."");
}
else
{
	$bdd->exec("UPDATE reg_rglsit SET views=views+1 WHERE id=".$id."");
}

$out = array();
exec('./markdown /Volumes/Partage/rglsit/files/' . $md5 .' 2>&1', $out);

foreach($out as $line)
{
	echo utf8_decode(stripslashes($line))."\n";
}
exit();

?>


text:
![one2one](imgs/one2one.png "one2one")

In the above diagram, I take songs on itunes as an example to demostrate the one-to-one relationship. Information of Songs on itunes can be stored inside one spreadsheet if it is big enough. As people might not interested at knowing the lyrics, popularity and its genre before listening to the song. Those information seems to be useless to some people. So it would be a good idea to break the bulky songs table down into more than one sheet. And since people might be interested if the song is written by a talented artist or the high rating by public on the social media. Therefore, some important information will stay on the songs table while other less important details will be moved to the new table called Song Details.

## Release 4 # Many to many Schema:

![many2many](imgs/many2many.png "many2many")

## Release 6 # Reflection:

### What is a one-to-one database?

One-to-one relationships occur when there is exactly one record in the first table that
corresponds to exactly one record in the related table.

### When would you use a one-to-one database? (Think generally, not in terms of the example you created).

I would use a one-to-one database for the events that one collection of data is indeed the
details information for another set of data.

### What is a many-to-many database?

Many-tomany database refers to the relationship between two entities, says, A and B in which
A may contain a parent record for which there are many children in B and vice versa.

### When would you use a many-to-many database? (Think generally, not in terms of the example you created).

I would use many-to-many database when there are several set of data and when I need to relate
each row in one table to many rows in another table, and vice versa.

### What is confusing about database schemas? What makes sense?

It was hard to explain these relationship between tables without using examples. I found these
hardto apply at the moment.


text:
require 'test_helper'

module BarkestCore
  class UserMailerTest < ActionMailer::TestCase

    def sender_address
      BarkestCore.email_config[:default_sender]
    end

    test 'account_activation' do
      user = users(:standard)
      user.activation_token = User.new_token
      mail = BarkestCore::UserMailer.account_activation(user: user)
      assert_equal 'Account activation', mail.subject
      assert_equal [user.email], mail.to
      assert_equal [sender_address], mail.from
      assert_match user.name, mail.body.encoded
      assert_match user.activation_token, mail.body.encoded
      assert_match CGI::escape(user.email), mail.body.encoded
    end

    test 'password_reset' do
      user = users(:standard)
      user.reset_token = User.new_token
      mail = BarkestCore::UserMailer.password_reset(user: user)
      assert_equal 'Password reset request', mail.subject
      assert_equal [user.email], mail.to
      assert_equal [sender_address], mail.from
      assert_match user.reset_token, mail.body.encoded
      assert_match CGI::escape(user.email), mail.body.encoded
    end

    test 'invalid_password_reset' do
      email = 'sombody@example.com'
      mail = BarkestCore::UserMailer.invalid_password_reset(email: email)
      assert_equal 'Password reset request', mail.subject
      assert_equal [email], mail.to
      assert_equal [sender_address], mail.from
      assert_match email, mail.body.encoded
    end

  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peziza ditricha Fr.

### Remarks
null


text:
package org.zywx.wbpalmstar.plugin.uexbaidumap;

import com.baidu.mapapi.model.LatLng;

public class EBaiduMapDotOptions extends EBaiduMapOverlayOptions {
	private String fillColor;
	private String radius;
	private LatLng latLng;

	public String getFillColor() {
		return fillColor;
	}
	public void setFillColor(String fillColor) {
		this.fillColor = fillColor;
	}
	public String getRadius() {
		return radius;
	}
	public void setRadius(String radius) {
		this.radius = radius;
	}
	public LatLng getLatLng() {
		return latLng;
	}
	public void setLatLng(Double latitude, Double longitude) {
		this.latLng = new LatLng(latitude, longitude);
	}

}


text:
namespace Headless
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Text.RegularExpressions;

    /// <summary>
    ///     The <see cref="IPage" />
    ///     interface defines the structure of a page returned from a <see cref="Browser" />.
    /// </summary>
    public interface IPage
    {
        /// <summary>
        /// Initializes the page using the specified browser and response.
        /// </summary>
        /// <param name="browser">
        /// The browser.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <param name="result">
        /// The HTTP result.
        /// </param>
        void Initialize(IBrowser browser, HttpResponseMessage response, HttpResult result);

        /// <summary>
        /// Determines whether the the page is on the specified location.
        /// </summary>
        /// <param name="location">
        /// The current location.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified location is valid for the page; otherwise, <c>false</c>.
        /// </returns>
        bool IsOn(Uri location);

        /// <summary>
        ///     Gets the owning browser.
        /// </summary>
        /// <value>
        ///     The owning browser.
        /// </value>
        IBrowser Browser
        {
            get;
        }

        /// <summary>
        ///     Gets the current location of the page.
        /// </summary>
        /// <value>
        ///     The current location of the page.
        /// </value>
        Uri Location
        {
            get;
        }

        /// <summary>
        ///     Gets the location expressions for validating the location of the page.
        /// </summary>
        /// <value>
        ///     The location expressions for validating the location of the page.
        /// </value>
        IEnumerable<Regex> LocationExpressions
        {
            get;
        }

        /// <summary>
        ///     Gets the HTTP result for the page.
        /// </summary>
        /// <value>
        ///     The HTTP result for the page.
        /// </value>
        HttpResult Result
        {
            get;
        }

        /// <summary>
        ///     Gets the final status code for the page.
        /// </summary>
        /// <value>
        ///     The final status code for the page.
        /// </value>
        HttpStatusCode StatusCode
        {
            get;
        }

        /// <summary>
        ///     Gets the status description.
        /// </summary>
        /// <value>
        ///     The status description.
        /// </value>
        string StatusDescription
        {
            get;
        }

        /// <summary>
        ///     Gets the location the browser should navigate to in order to load this page.
        /// </summary>
        /// <value>
        ///     The location the browser should navigate to in order to load this page.
        /// </value>
        /// <remarks>
        ///     The <see cref="IBrowser" /> may also use this location for validation that the final response matches this
        ///     location. The actual implementation of this logic is determined by the
        ///     <see cref="IBrowser.LocationValidator" />.
        /// </remarks>
        Uri TargetLocation
        {
            get;
        }
    }
}


text:
require "spec_helper"

describe HungryForm::Elements::Group do
  let(:resolver_options) { {} }
  let(:resolver) { HungryForm::Resolver.new(resolver_options) }
  let(:group_options) { {} }
  let(:group) { HungryForm::Elements::Group.new(:parent_name, nil, resolver, group_options) {} }
  let(:options) { {} }

  subject { HungryForm::Elements::Group.new(:element_name, group, resolver, options) {} }

  it_behaves_like 'an element'
  it_behaves_like 'a group'
end


text:
public class Solution {
    int min = Integer.MAX_VALUE;

    public int getMinimumDifference(TreeNode root) {
        helper(root, null);
        return min;
    }

    private TreeNode helper(TreeNode root, TreeNode pre) {
        if (root == null) return pre;

        pre = helper(root.left, pre);

        if (pre != null) {
            min = Math.min(min, Math.abs(pre.val - root.val));
        }

        return helper(root.right, root);
    }
}

// second solution
public class Solution {
    int min = Integer.MAX_VALUE;
    TreeNode pre = null;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return min;
        getMinimumDifference(root.left);
        if (pre != null)
            min = Math.min(min, Math.abs(pre.val - root.val));
        pre = root;
        return getMinimumDifference(root.right);
    }
}


text:
import { combineReducers } from 'redux';
import todo from './todo/todo-reducer';

// Combine all reducers into one root reduce
export default combineReducers({
  todo,
});


text:
--TEST--
Test get_class() function : usage variations  - ensure class name case is preserved.
--FILE--
<?php
/* Prototype  : proto string get_class([object object])
 * Description: Retrieves the class name
 * Source code: Zend/zend_builtin_functions.c
 * Alias to functions:
 */

class caseSensitivityTest {}
var_dump(get_class(new casesensitivitytest));

echo "Done";
?>
--EXPECTF--
string(19) "caseSensitivityTest"
Done


text:
package com.linkedin.pinot.core.segment.index;

import com.linkedin.pinot.common.data.FieldSpec;
import com.linkedin.pinot.common.segment.ReadMode;
import com.linkedin.pinot.core.indexsegment.generator.SegmentGeneratorConfig;
import com.linkedin.pinot.core.segment.creator.SegmentIndexCreationDriver;
import com.linkedin.pinot.core.segment.creator.impl.SegmentCreationDriverFactory;
import com.linkedin.pinot.core.segment.index.loader.Loaders;
import com.linkedin.pinot.segments.v1.creator.SegmentTestUtils;
import com.linkedin.pinot.util.TestUtils;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ColumnMetadataTest {
  private static Logger LOGGER = LoggerFactory.getLogger(ColumnMetadataTest.class);

  private static final String AVRO_DATA = "data/test_data-mv.avro";
  private static final File INDEX_DIR = new File(ColumnMetadataTest.class.toString());

  @BeforeClass
  public void setUP() throws Exception {

    if (INDEX_DIR.exists()) {
      FileUtils.deleteQuietly(INDEX_DIR);
    }

    final String filePath =
        TestUtils
            .getFileFromResourceUrl(ColumnMetadataTest.class.getClassLoader().getResource(AVRO_DATA));

    // intentionally changed this to TimeUnit.Hours to make it non-default for testing
    final SegmentGeneratorConfig config =
        SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(new File(filePath), INDEX_DIR, "daysSinceEpoch",
            TimeUnit.HOURS, "testTable");
    config.setSegmentNamePostfix("1");
    config.setTimeColumnName("daysSinceEpoch");
    final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
    driver.init(config);
    driver.build();
  }

  @AfterClass
  public void tearDown() {
    FileUtils.deleteQuietly(INDEX_DIR);
  }

  @Test
  public void testAllFieldsInitialized()
      throws Exception {
    final IndexSegmentImpl segment =
        (IndexSegmentImpl) Loaders.IndexSegment.load(INDEX_DIR.listFiles()[0], ReadMode.mmap);
    SegmentMetadataImpl metadata = (SegmentMetadataImpl) segment.getSegmentMetadata();
    ColumnMetadata col7Meta =  metadata.getColumnMetadataFor("column7");
    Assert.assertEquals("column7", col7Meta.getColumnName());
    Assert.assertEquals(359, col7Meta.getCardinality());
    Assert.assertEquals(false, col7Meta.isSingleValue());
    Assert.assertEquals(FieldSpec.DataType.INT, col7Meta.getDataType());
    Assert.assertEquals(9, col7Meta.getBitsPerElement());
    Assert.assertEquals(FieldSpec.FieldType.DIMENSION, col7Meta.getFieldType());
    Assert.assertEquals(24, col7Meta.getMaxNumberOfMultiValues());
    Assert.assertEquals(0, col7Meta.getTotalAggreateDocs());
    Assert.assertEquals(100000, col7Meta.getTotalRawDocs());
    Assert.assertEquals(100000, col7Meta.getTotalDocs());
    Assert.assertEquals(0, col7Meta.getStringColumnMaxLength());
    Assert.assertEquals(true, col7Meta.hasDictionary());
    Assert.assertEquals(true, col7Meta.isHasInvertedIndex());
    Assert.assertEquals(false, col7Meta.hasNulls());
    Assert.assertEquals(false, col7Meta.isSorted());
    // since this is MV field
    Assert.assertTrue(col7Meta.getTotalDocs() < col7Meta.getTotalNumberOfEntries());

    // single valued string field
    ColumnMetadata col3 = metadata.getColumnMetadataFor("column3");
    Assert.assertEquals(FieldSpec.DataType.STRING, col3.getDataType());
    Assert.assertEquals(true, col3.isSingleValue());
    Assert.assertEquals(4, col3.getStringColumnMaxLength());
    // this will be default
    Assert.assertEquals(0, col3.getMaxNumberOfMultiValues());

    ColumnMetadata timeColumn = metadata.getColumnMetadataFor("daysSinceEpoch");
    Assert.assertEquals(TimeUnit.HOURS, timeColumn.getTimeunit());
  }
}


text:
MagicFrame
===========

iFrame redirect with child title support and query string and hash pass-through.

If url is set to 'abc.com' and incoming address is 'http://originaldomain.com/hello.html?q=test&testmode=true#test', the iFrame will take visitors to 'http://abc.com?q=test&testmode=true#test' and sets the title to that of abc.com.


text:
package global.namespace.truelicense.ui.wizard;

import global.namespace.truelicense.api.i18n.Message;
import global.namespace.truelicense.spi.i18n.Formattable;

/**
 * Enumerates the standard messages of any wizard dialog.
 */
public enum WizardMessage implements Formattable {

    wizard_back, wizard_next, wizard_cancel, wizard_finish;

    @Override public Message format(Object... args) {
        return Messages.message(name(), args);
    }
}


text:
module RuboCop
  module Cop
    module Layout
      # This cop checks that the indentation method is consistent.
      # Either tabs only or spaces only are used for indentation.
      #
      # @example EnforcedStyle: spaces (default)
      #   # bad
      #   # This example uses a tab to indent bar.
      #   def foo
      #     bar
      #   end
      #
      #   # good
      #   # This example uses spaces to indent bar.
      #   def foo
      #     bar
      #   end
      #
      # @example EnforcedStyle: tabs
      #   # bad
      #   # This example uses spaces to indent bar.
      #   def foo
      #     bar
      #   end
      #
      #   # good
      #   # This example uses a tab to indent bar.
      #   def foo
      #     bar
      #   end
      class IndentationStyle < Base
        include Alignment
        include ConfigurableEnforcedStyle
        include RangeHelp
        extend AutoCorrector

        MSG = '%<type>s detected in indentation.'

        def on_new_investigation
          str_ranges = string_literal_ranges(processed_source.ast)

          processed_source.lines.each.with_index(1) do |line, lineno|
            next unless (range = find_offense(line, lineno))
            next if in_string_literal?(str_ranges, range)

            add_offense(range) { |corrector| autocorrect(corrector, range) }
          end
        end

        private

        def autocorrect(corrector, range)
          if range.source.include?("\t")
            autocorrect_lambda_for_tabs(corrector, range)
          else
            autocorrect_lambda_for_spaces(corrector, range)
          end
        end

        def find_offense(line, lineno)
          match = if style == :spaces
                    line.match(/\A\s*\t+/)
                  else
                    line.match(/\A\s* +/)
                  end
          return unless match

          source_range(processed_source.buffer, lineno, match.begin(0)...match.end(0))
        end

        def autocorrect_lambda_for_tabs(corrector, range)
          spaces = ' ' * configured_indentation_width
          corrector.replace(range, range.source.gsub(/\t/, spaces))
        end

        def autocorrect_lambda_for_spaces(corrector, range)
          corrector.replace(range, range.source.gsub(/\A\s+/) do |match|
            "\t" * (match.size / configured_indentation_width)
          end)
        end

        def in_string_literal?(ranges, tabs_range)
          ranges.any? { |range| range.contains?(tabs_range) }
        end

        def string_literal_ranges(ast)
          # which lines start inside a string literal?
          return [] if ast.nil?

          ast.each_node(:str, :dstr).each_with_object(Set.new) do |str, ranges|
            loc = str.location

            if str.heredoc?
              ranges << loc.heredoc_body
            elsif loc.respond_to?(:begin) && loc.begin
              ranges << loc.expression
            end
          end
        end

        def message(_node)
          format(MSG, type: style == :spaces ? 'Tab' : 'Space')
        end
      end
    end
  end
end


text:
package org.scalaide.core.internal.text

import org.eclipse.jface.text.IDocument
import org.eclipse.jface.text.IRegion
import org.eclipse.jface.text.Region
import org.scalaide.core.text.Document
import org.scalaide.core.text.InternalDocument

class TextDocument(private val doc: IDocument) extends Document with InternalDocument {

  override def apply(i: Int): Char =
    doc.getChar(i)

  override def length: Int =
    doc.getLength()

  override def text: String =
    doc.get()

  override def textRange(start: Int, end: Int): String =
    doc.get(start, end-start)

  override def textRangeOpt(start: Int, end: Int): Option[String] =
    if (isValidRange(start, end))
      Some(doc.get(start, end-start))
    else
      None

  override def lines: Seq[IRegion] =
    0 until lineCount map lineInformation

  override def lineCount: Int =
    doc.getNumberOfLines()

  override def lineInformation(lineNumber: Int): IRegion =
    doc.getLineInformation(lineNumber)

  override def lineInformationOfOffset(offset: Int): IRegion =
    doc.getLineInformationOfOffset(offset)

  override def replace(start: Int, end: Int, text: String): Unit =
    doc.replace(start, end-start, text)

  override def head: Char =
    doc.getChar(0)

  override def headOpt: Option[Char] =
    if (!isEmpty)
      Some(doc.getChar(0))
    else
      None

  override def tail: String =
    doc.get(1, length-1)

  override def tailOpt: Option[String] =
    if (!isEmpty)
      Some(doc.get(1, length-1))
    else
      None

  override def init: String =
    doc.get(0, length-1)

  override def initOpt: Option[String] =
    if (!isEmpty)
      Some(doc.get(0, length-1))
    else
      None

  override def last: Char =
    doc.getChar(length-1)

  override def lastOpt: Option[Char] =
    if (!isEmpty)
      Some(doc.getChar(length-1))
    else
      None

  override def toString(): String =
    text

  private def isEmpty: Boolean =
    length == 0

  private def isValidRange(start: Int, end: Int): Boolean =
    start >= 0 && start <= end && end <= length
}


text:
<?php

declare(strict_types=1);

namespace Apine\Core\Views;

use Apine\Core\Http\Response;
use Apine\Core\Http\Stream;
use Apine\Utility\Files;
use Psr\Http\Message\ResponseInterface;

/**
 * Class FileView
 *
 * @package Apine\Core\Views
 */
class FileView extends View
{
    /**
     * @var resource
     */
    private $resource;

    /**
     * @var string
     */
    private $path;

    /**
     * FileView constructor.
     *
     * @param string $file
     */
    public function __construct(string $file)
    {
        $this->setFile($file);
    }

    public function respond(): ResponseInterface
    {
        $response = new Response($this->statusCode);

        foreach ($this->headers as $header) {
            $response = $response->withHeader($header['name'], $header['value']);
        }

        $response = $response->withBody(new Stream($this->resource));

        return $response;
    }

    public function setFile(string $file)
    {
        if (!file_exists($file)) {
            throw new \InvalidArgumentException(sprintf('File %s not found',$file));
        }

        $this->resource = fopen($file, 'r');
        $this->path = $file;

        $this->addHeader('Content-Type', self::fileType($this->path));
        $this->addHeader('Content-Length', filesize($this->path));
    }

    private static function fileType(string $path) : string
    {
        $mime = '';

        if (class_exists('finfo')) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $path);
        } elseif (!strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $filename = escapeshellcmd($path);
            $mime = shell_exec("file -b --mime-type '" . $filename . "'");
        } elseif (self::isExecAvailable()) {
            $filename = escapeshellcmd($path);
            $mime = exec("file -b --mime-type '" . $filename . "'");
        }

        return $mime;
    }

    /**
     * Verify if exec is disabled
     *
     * @author Daniel Convissor
     * @see http://stackoverflow.com/questions/3938120/check-if-exec-is-disabled
     */
    private static function isExecAvailable()
    {
        static $available;

        if (!isset($available)) {
            $available = true;
            if (ini_get('safe_mode')) {
                $available = false;
            } else {
                $d = ini_get('disable_functions');
                $s = ini_get('suhosin.executor.func.blacklist');
                if ("$d$s") {
                    $array = preg_split('/,\s*/', "$d,$s");
                    if (in_array('exec', $array)) {
                        $available = false;
                    }
                }
            }
        }

        return $available;
    }
}


text:
@protocol ZZRouterSequentialIndependenceProtocol <NSObject>

-(void)sequentialIndependenceMethod;

@end


text:
'use strict';

import React from 'react';
import Router from 'react-router';
import {Route, DefaultRoute, RouteHandler} from 'react-router';
import App from './App';

import TripStore from './TripStore';

// window.tripSummaries is provided by an auto-generated JS script
// included in index.html
window.tripSummaries.forEach((trip, tripNum) => {
  if (trip) trip.tripNum = tripNum;
});

var tripStore = new TripStore(window.tripSummaries);

var AppWrapper = React.createClass({
  childContextTypes: {
    tripStore: React.PropTypes.object.isRequired,
  },
  getChildContext() {
    return {
      tripStore: tripStore,
    };
  },
  render() {
    return <RouteHandler {...this.props} />;
  }
});

var Routes = (
  <Route name="/" handler={AppWrapper}>
    <DefaultRoute handler={App} />
  </Route>
);

Router.run(Routes, function (Handler) {
  React.render(<Handler/>, document.getElementById('root'));
});


text:
package cn.liutils.core.debug;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import cn.liutils.api.client.key.IKeyHandler;

/**
 * @author WeAthFolD
 *
 */
public class KeyShowInfo implements IKeyHandler {

    /**
     *
     */
    public KeyShowInfo() {
        // TODO Auto-generated constructor stub
    }

    /* (non-Javadoc)
     * @see cn.liutils.api.client.register.IKeyHandler#onKeyDown(int, boolean)
     */
    @Override
    public void onKeyDown(int keyCode, boolean tickEnd) {
        if(tickEnd) return;
        EntityPlayer player = Minecraft.getMinecraft().thePlayer;
        if(player == null) return;
        FieldModifierHandler.sendInfo(player);
    }

    @Override
    public void onKeyUp(int keyCode, boolean tickEnd) {
    }

    @Override
    public void onKeyTick(int keyCode, boolean tickEnd) {
    }

}


text:
package com.nanyang.app.main.home.sport.myanmarOdds;

import android.view.View;
import android.widget.TextView;

import com.nanyang.app.MenuItemInfo;
import com.nanyang.app.R;
import com.nanyang.app.main.home.sport.model.LeagueBean;
import com.nanyang.app.main.home.sport.model.TableSportInfo;
import com.nanyang.app.main.home.sportInterface.BallItemCallBack;
import com.nanyang.app.main.home.sportInterface.IAdapterHelper;
import com.nanyang.app.main.home.sportInterface.IBetHelper;
import com.nanyang.app.main.home.sport.main.SportAdapterHelper;
import com.nanyang.app.main.home.sport.main.SportContract;
import com.nanyang.app.main.home.sport.main.SportState;
import com.unkonw.testapp.training.ScrollLayout;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/10.
 */

public abstract class MyanmarState extends SportState<MyanmarInfo, SportContract.View<MyanmarInfo>> {

    protected Map<String, Map<String, Boolean>> localCollectionMap = new HashMap<>();
    private boolean isCollection;

    public MyanmarState(SportContract.View baseView) {
        super(baseView);
    }

    public boolean isCollection() {
        return isCollection;
    }

    public boolean collection() {
        isCollection = !isCollection;
        initAllData(allData);
        return isCollection;
    }

    @Override
    public IAdapterHelper<MyanmarInfo> onSetAdapterHelper() {
        return new MyanmarAdapterHelper(getBaseView().getContextActivity());
    }

    @Override
    protected SportAdapterHelper.ItemCallBack onSetItemCallBack() {
        return new BallItemCallBack<MyanmarInfo>(baseRecyclerAdapter) {
            @Override
            public ScrollLayout onSetHeaderFollower() {
                return getBaseView().onSetScrollHeader();
            }

            @Override
            public boolean isItemCollection(MyanmarInfo item) {
                return false;
            }

            @Override
            public void clickOdds(TextView v, MyanmarInfo item, String type, boolean isHf, String odds) {
                IBetHelper<MyanmarInfo> helper = onSetBetHelper();
                helper.setCompositeSubscription(mCompositeSubscription);
                helper.clickOdds(item, type, odds, v, isHf, "");
            }

            @Override
            public void clickView(View v, MyanmarInfo item,int position) {
                switch (v.getId()) {
                    case R.id.module_right_mark_tv:
                        getBaseView().clickItemAdd(v, item, "common");
                        break;
                }

            }

        };
    }

    @Override
    protected IBetHelper<MyanmarInfo> onSetBetHelper() {
        return new MyanmarBetHelper(getBaseView());
    }

    @Override
    protected List<TableSportInfo<MyanmarInfo>> updateJsonData(JSONArray dataListArray) throws JSONException {
        ArrayList<TableSportInfo<MyanmarInfo>> tableModules = new ArrayList<>();
        if (dataListArray.length() > 0) {
            for (int i = 0; i < dataListArray.length(); i++) {
                LeagueBean leagueBean;
                List<MyanmarInfo> matchList = new ArrayList<>();
                JSONArray jsonArray3 = dataListArray.getJSONArray(i);
                if (jsonArray3.length() > 1) {
                    JSONArray LeagueArray = jsonArray3.getJSONArray(0);
                    if (LeagueArray.length() > 1) {
                        leagueBean = new LeagueBean(LeagueArray.get(0).toString(), LeagueArray.getString(1));
                    } else {
                        continue;
                    }
                    JSONArray LeagueMatchArray = jsonArray3.getJSONArray(1);
                    if (LeagueMatchArray.length() > 0) {
                        for (int j = 0; j < LeagueMatchArray.length(); j++) {
                            JSONArray matchArray = LeagueMatchArray.getJSONArray(j);
                            matchList.add(parseMatch(matchArray));
                        }
                    } else {
                        continue;
                    }
                    tableModules.add(new TableSportInfo<>(leagueBean, matchList));
                }
            }
        }
        return tableModules;
    }

    private MyanmarInfo parseMatch(JSONArray matchArray) throws JSONException {
        MyanmarInfo info = new MyanmarInfo();

        info.setSocOddsId(matchArray.opt(0) == null ? "" : matchArray.optString(0));         //全场ID
        info.setSocOddsId_FH(matchArray.opt(1) == null ? "" : matchArray.optString(1));      //半场ID
        info.setLive(matchArray.opt(2) == null ? "" : matchArray.optString(2));              //是否显示live
        info.setHomeId(matchArray.opt(3) == null ? "" : matchArray.optString(3));            //主队id
        info.setAwayId(matchArray.opt(4) == null ? "" : matchArray.optString(4));            //客队id
        info.setIsInFavourite(matchArray.opt(5) == null ? "" : matchArray.optString(5));     //是否加入我的最爱
        info.setScoreNew(matchArray.opt(6) == null ? "" : matchArray.optString(6));          //IsScoreNew;		//有没有更新比数, 作闪闪图片用
        info.setIsLastCall(matchArray.opt(7) == null ? "" : matchArray.optString(7));        //是否最后一次请求数据
        info.setMatchDate(matchArray.opt(8) == null ? "" : matchArray.optString(8));         //比赛时间
        info.setStatus(matchArray.opt(9) == null ? "" : matchArray.optString(9));            //状态(开始或者还没开始)
        info.setCurMinute(matchArray.opt(10) == null ? "" : matchArray.optString(10));         //比赛进行了多少时间
        info.setIsInetBet(matchArray.opt(11) == null ? "" : matchArray.optString(11));         //允许或不允许成员下注
        info.setHasHdp(matchArray.opt(12) == null ? "" : matchArray.optString(12));            //是否有hdp
        info.setHdpOdds(matchArray.opt(13) == null ? "" : matchArray.optString(13));           //分出HomeHdpOdds,AwayHdpOdds
        info.setIsHomeGive(matchArray.opt(14) == null ? "" : matchArray.optString(14));        //是否主队让球
        info.setHomeRank(matchArray.opt(15) == null ? "" : matchArray.optString(15));          //主队排名
        info.setHome(matchArray.opt(16) == null ? "" : matchArray.optString(16));              //主队名
        info.setRCHome(matchArray.opt(17) == null ? "" : matchArray.optString(17));            //主队红牌数
        info.setRTSMatchId(matchArray.opt(18) == null ? "" : matchArray.optString(18));        //RTS livecast 图标所用
        info.setAwayRank(matchArray.opt(19) == null ? "" : matchArray.optString(19));          //客队排名
        info.setAway(matchArray.opt(20) == null ? "" : matchArray.optString(20));              //客队名
        info.setRCAway(matchArray.opt(21) == null ? "" : matchArray.optString(21));            //客队红牌数
        info.setHdp(matchArray.opt(22) == null ? "" : matchArray.optString(22));               //hdp让球数
        info.setHomeHdpOdds(matchArray.opt(23) == null ? "" : matchArray.optString(23));       //主队hdp赔率
        info.setAwayHdpOdds(matchArray.opt(24) == null ? "" : matchArray.optString(24));       //客队hdp赔率
        info.setHasOU(matchArray.opt(25) == null ? "" : matchArray.optString(25));             //是否有ou
        info.setOU(matchArray.opt(26) == null ? "" : matchArray.optString(26));                //大小球
        info.setRunHomeScore(matchArray.opt(27) == null ? "" : matchArray.optString(27));      //滚球主队的分数
        info.setRunAwayScore(matchArray.opt(28) == null ? "" : matchArray.optString(28));      //滚球客队的分数
        info.setOverOdds(matchArray.opt(29) == null ? "" : matchArray.optString(29));          //over赔率
        info.setUnderOdds(matchArray.opt(30) == null ? "" : matchArray.optString(30));         //under赔率
        info.setOUOdds(matchArray.opt(31) == null ? "" : matchArray.optString(31));            //从中分出OverOdds,UnderOdds
        info.setHasHdp_FH(matchArray.opt(32) == null ? "" : matchArray.optString(32));         //半场是否有hdp
        info.setHdp_FH(matchArray.opt(33) == null ? "" : matchArray.optString(33));            //半场hdp让球
        info.setIsHomeGive_FH(matchArray.opt(34) == null ? "" : matchArray.optString(34));     //半场是否主队让球
        info.setHomeHdpOdds_FH(matchArray.opt(35) == null ? "" : matchArray.optString(35));    //半场主队hdp赔率
        info.setAwayHdpOdds_FH(matchArray.opt(36) == null ? "" : matchArray.optString(36));    //半场客队hdp赔率
        info.setHdpOdds_FH(matchArray.opt(37) == null ? "" : matchArray.optString(37));        //分出HomeHdpOdds,AwayHdpOdds
        info.setIsInetBet_FH(matchArray.opt(38) == null ? "" : matchArray.optString(38));      //半场允许或不允许成员下注
        info.setHasOU_FH(matchArray.opt(39) == null ? "" : matchArray.optString(39));          //半场是否有ou
        info.setOU_FH(matchArray.opt(40) == null ? "" : matchArray.optString(40));             //半场大小球
        info.setRunHomeScore_FH(matchArray.opt(41) == null ? "" : matchArray.optString(41));   //半场滚球主队的分数
        info.setRunAwayScore_FH(matchArray.opt(42) == null ? "" : matchArray.optString(42));   //半场滚球客队的分数
        info.setOverOdds_FH(matchArray.opt(43) == null ? "" : matchArray.optString(43));       //半场over赔率
        info.setUnderOdds_FH(matchArray.opt(44) == null ? "" : matchArray.optString(44));      //半场under赔率
        info.setOUOdds_FH(matchArray.opt(45) == null ? "" : matchArray.optString(45));         //分出OverOdds_FH,UnderOdds_FH
        info.setStatsId(matchArray.opt(46) == null ? "" : matchArray.optString(46));           //- statistic id
        info.setWorkingDate(matchArray.opt(47) == null ? "" : matchArray.optString(47));       //比赛开始的时间
        info.setPreSocOddsId(matchArray.opt(48) == null ? "" : matchArray.optString(48));
        info.setIsHideMM(matchArray.opt(49) == null ? "" : matchArray.optString(49));
        info.setMMHdpPct(matchArray.opt(50) == null ? "" : matchArray.optString(50));
        info.setMMOUPct(matchArray.opt(51) == null ? "" : matchArray.optString(51));
        info.setMMHdp(matchArray.opt(52) == null ? "" : matchArray.optString(52));
        info.setMMIsHomeGive(matchArray.opt(53) == null ? "" : matchArray.optString(53));
        info.setMMHdpOdds(matchArray.opt(54) == null ? "" : matchArray.optString(54));
        info.setMMOU(matchArray.opt(55) == null ? "" : matchArray.optString(55));
        info.setMMOUOdds(matchArray.opt(56) == null ? "" : matchArray.optString(56));
        info.setHasX12(matchArray.opt(57) == null ? "" : matchArray.optString(57));
        return info;

    }

    @Override
    protected List<TableSportInfo<MyanmarInfo>> filterChildData(List<TableSportInfo<MyanmarInfo>> allData) {
        return allData;
    }

    @Override
    protected int getIndexSocOddsId() {
        return 0;
    }

    @Override
    protected int getIndexPreSocOddsId() {
        return 48;
    }

    @Override
    protected List<MenuItemInfo> getTypes() {
        List<MenuItemInfo> types = new ArrayList<>();
        types.add(new MenuItemInfo(1, getBaseView().getContextActivity().getString(R.string.Today), "Today"));
        types.add(new MenuItemInfo(1, getBaseView().getContextActivity().getString(R.string.Early), "Early"));
        types.add(new MenuItemInfo(1, getBaseView().getContextActivity().getString(R.string.Running), "Running"));
        return types;
    }

    @Override
    public boolean mix() {
        return false;
    }

//    @Override
//    protected List<List<String>> initHeaderList() {
//        List<List<String>> lists = super.initHeaderList();
//        lists.add(new ArrayList<>(Arrays.asList(getBaseView().getContextActivity().getString(R.string.AFB_FT_HDP), getBaseView().getContextActivity().getString(R.string.AFB_FT_OU))));
//        return lists;
//    }

    @Override
    protected List<TableSportInfo<MyanmarInfo>> updateJsonArray(String updateString) throws JSONException {

        JSONArray jsonArray = new JSONArray(updateString);
        if (jsonArray.length() > 4) {
            parseLidValue(jsonArray);
            JSONArray dataListArray = jsonArray.getJSONArray(4);
            this.dataJsonArray = dataListArray;
            return updateJsonData(dataListArray);
        }
        return new ArrayList<>();
    }
}


text:
@interface WBSession : NSObject

-(void)setCurrentSession:(id)session;

@property(readonly, nonatomic, getter=isValid) BOOL valid;//是否有效
@property(readonly) BOOL hasUser;//是否已登陆
@property(readonly) NSString *userWBID;//微博id
@property(readonly) NSString *accessToken;//微博认证口令

@end


text:
<TITLE>Review for Hoffa (1992)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Hoffa (1992)

reviewed by
Frank Maloney

                                   HOFFA
                       A film review by Frank Maloney
                        Copyright 1992 Frank Maloney

     HOFFA is a film directed by Danny DeVito, from a script by David
Mamet.  It stars Jack Nicholson, DeVito, Armand Assante.  Rated R for
violence.

     HOFFA is quite simply an amazing achievement.  It marks the
emergence of Danny DeVito as a director of the first rank.  It also
marks the reemergence of Jack Nicholson as a major actor, instead of
merely a major ham.  However, HOFFA is a tricky film to take in insofar
as DeVito and David Mamet, the writer, take no moral positions vis-a-vis
Jimmy Hoffa.  They provide us with a few texts to guide us, especially
when Hoffa tells a reporter, "You have to weigh what is lost and what is
gained."  Hoffa was the brilliant leader of the Teamsters Union who also
enmeshed his union with organized crime.  I should say that I am not
neutral myself on this subject, even if I am of two minds.  My father
was an associate of Hoffa and Dave Beck, his predecessor as president of
the Teamsters.  I actually met Hoffa when I was a child.  My father was
subpoenaed to appear before the McClellan Senate Labor Rackets Committee
and earned the undying enmity of Bobby Kennedy.  I am not neutral, be
warned.

     The story is a series of flashbacks, memories as Hoffa and his
longtime (and composite) sidekick (DeVito) wait for a rendezvous with
his secret Mafia partner.  We see how they met in the days when a driver
would be fired and blackballed for being pro-union; we witness an
exciting, bloody, brilliantly directed, horrible battle between
Teamsters and management goons.  We see the secret deal with the mob
that established the union's ascendency.  We see Hoffa's long and very
personal feud with Bobby Kennedy.  All of these scenes and the others
are filtered through the sidekick's eyes and loyalties.  The structure
ensures that DeVito gets at least as much screen time as Nicholson.  But
it also makes it possible to make a film that need not pretend
neutrality or to make judgments.  What we do see through DeVito's eyes
is a complex, tragically flawed, remote and enigmatic leader of
brilliance and a radical devotion to his cause.

     As Hoffa, Jack Nicholson is brilliant, perfect, inspiring.  He
becomes Hoffa.  Nicholson recedes until he is lost entirely.  It is the
performance of a lifetime.  He fully captures the drive and devils that
propelled Hoffa.  It is a performance of nuance and self-effacement.
And it is exciting to watch.

     DeVito does his usual job of being DeVito in his role as the
sidekick, venal, amoral, shy only the dirty laugh of most of his parts.
It's acceptable and it in no way competes with Nicholson.

     However, as director, DeVito is a brilliant chance-taker and
problem-solver, producing a far less conventional biopic than
"non-Hollywood" Spike Lee's MALCOM X.  We have no childhood prologue, no
family life.  All we have is what the sidekick knows and sees of his
idol.  DeVito employs successfully split screens, creative transitional
devices, and other unconventional story-telling techniques.

     This, I should warn the squeamish, is a rough film: violence,
blood.  The f-word is just about the first one you hear.  There is
worse, too.

     I recommend HOFFA to the rest of you in the strongest of terms.
This is a masterpiece.

--
Frank Richard Aloysius Jude Maloney
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package uk.gov.dvla.vehicles.sandbox

import sbt.Compile
import sbt.Def
import sbt.File
import sbt.Keys.baseDirectory
import sbt.Keys.classDirectory
import sbt.Keys.fullClasspath
import sbt.Keys.run
import sbt.Keys.target
import sbt.{Runtime, Test}
import sbt.ThisProject
import Runner.ConfigDetails
import Runner.ConfigOutput
import Runner.runJavaMain
import Runner.runProject
import Runner.runProjectForked
import Runner.configLocation
import Runner.setServicePort
import Runner.setServicePortAndLegacyServicesPort
import Runner.substituteProp
import SandboxSettings.acceptanceTests
import SandboxSettings.applicationContext
import SandboxSettings.auditProject
import SandboxSettings.bruteForceEnabled
import SandboxSettings.emailServiceProject
import SandboxSettings.legacyStubsProject
import SandboxSettings.loadTests
import SandboxSettings.osAddressLookupProject
import SandboxSettings.paymentSolveProject
import SandboxSettings.portOffset
import SandboxSettings.runAllMicroservices
import SandboxSettings.vehicleAndKeeperLookupProject
import SandboxSettings.vehiclesAcquireFulfilProject
import SandboxSettings.vehiclesDisposeFulfilProject
import SandboxSettings.vrmAssignEligibilityProject
import SandboxSettings.vrmAssignFulfilProject
import SandboxSettings.vrmRetentionEligibilityProject
import SandboxSettings.vrmRetentionRetainProject

object Tasks {
  private val httpsPort = Def.setting(portOffset.value + 443)
  private val osAddressLookupPort = Def.setting(portOffset.value + 801)
  private val vehicleDisposePort = Def.setting(portOffset.value + 803)
  private val vehiclesAcquireFulfilPort = Def.setting(portOffset.value + 804)
  private val legacyServicesStubsPort = Def.setting(portOffset.value + 806)
  private val vehicleAndKeeperLookupPort = Def.setting(portOffset.value + 807)
  private val paymentSolvePort = Def.setting(portOffset.value + 808)
  private val vrmRetentionEligibilityPort = Def.setting(portOffset.value + 809)
  private val vrmRetentionRetainPort = Def.setting(portOffset.value + 810)
  private val vrmAssignEligibilityPort = Def.setting(portOffset.value + 811)
  private val vrmAssignFulfilPort = Def.setting(portOffset.value + 812)
  private val auditPort = Def.setting(portOffset.value + 813)
  private val emailServicePort = Def.setting(portOffset.value + 814)

  val legacyStubsClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(legacyStubsProject.value)}
  lazy val runLegacyStubs = Def.task {
    runProject(
      legacyStubsClassPath.value,
      None,
      runJavaMain("service.LegacyServicesRunner", Array(legacyServicesStubsPort.value.toString))
    )
  }

  val osAddressLookupClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(osAddressLookupProject.value)}
  val osAddressLookupClassDir = Def.settingDyn {classDirectory.in(Runtime).in(osAddressLookupProject.value)}
  lazy val runOsAddressLookup = Def.task {
    runProject(
      osAddressLookupClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "os-address-lookup/os-address-lookup.conf",
        Some(ConfigOutput(
          new File(osAddressLookupClassDir.value, "os-address-lookup.conf"),
          setServicePortAndLegacyServicesPort(
            osAddressLookupPort.value,
            "ordnancesurvey.preproduction.baseurl",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vehicleAndKeeperLookupClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vehicleAndKeeperLookupProject.value)}
  val vehicleAndKeeperLookupClassDir = Def.settingDyn {classDirectory.in(Runtime).in(vehicleAndKeeperLookupProject.value)}
  lazy val runVehicleAndKeeperLookup = Def.task {
    runProject(
      vehicleAndKeeperLookupClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vehicle-and-keeper-lookup/vehicle-and-keeper-lookup.conf",
        Some(ConfigOutput(
          new File(vehicleAndKeeperLookupClassDir.value, "vehicle-and-keeper-lookup.conf"),
          setServicePortAndLegacyServicesPort(
            vehicleAndKeeperLookupPort.value,
            "getVehicleAndKeeperDetails.baseurl",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vehiclesDisposeFulfilClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vehiclesDisposeFulfilProject.value)}
  val vehiclesDisposeFulfilDir = Def.settingDyn {classDirectory.in(Runtime).in(vehiclesDisposeFulfilProject.value)}
  lazy val runVehiclesDisposeFulfil = Def.task {
    runProject(
      vehiclesDisposeFulfilClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vehicles-dispose-fulfil/vehicles-dispose-fulfil.conf",
        Some(ConfigOutput(
          new File(vehiclesDisposeFulfilDir.value, "vehicles-dispose-fulfil.conf"),
          setServicePortAndLegacyServicesPort(
            vehicleDisposePort.value,
            "vss.baseurl",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vehiclesAcquireFulfilClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vehiclesAcquireFulfilProject.value)}
  val vehiclesAcquireFulfilDir = Def.settingDyn {classDirectory.in(Runtime).in(vehiclesAcquireFulfilProject.value)}
  lazy val runVehiclesAcquireFulfil = Def.task {
    runProject(
      vehiclesAcquireFulfilClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vehicles-acquire-fulfil/vehicles-acquire-fulfil.conf",
        Some(ConfigOutput(
          new File(vehiclesAcquireFulfilDir.value, "vehicles-acquire-fulfil.conf"),
          setServicePortAndLegacyServicesPort(
            vehiclesAcquireFulfilPort.value,
            "vss.baseurl",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val paymentSolveClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(paymentSolveProject.value)}
  val paymentSolveClassDir = Def.settingDyn {classDirectory.in(Runtime).in(paymentSolveProject.value)}
  lazy val runPaymentSolve = Def.task {
    runProject(
      paymentSolveClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "payment-solve/payment-solve.conf",
        Some(ConfigOutput(
          new File(paymentSolveClassDir.value, "payment-solve.conf"),
          setServicePort(paymentSolvePort.value)
        ))
      ))
    )
  }

  val vrmRetentionEligibilityClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vrmRetentionEligibilityProject.value)}
  val vrmRetentionEligibilityClassDir = Def.settingDyn {classDirectory.in(Runtime).in(vrmRetentionEligibilityProject.value)}
  lazy val runVrmRetentionEligibility = Def.task {
    runProject(
      vrmRetentionEligibilityClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vrm-retention-eligibility/vrm-retention-eligibility.conf",
        Some(ConfigOutput(
          new File(vrmRetentionEligibilityClassDir.value, "vrm-retention-eligibility.conf"),
          setServicePortAndLegacyServicesPort(
            vrmRetentionEligibilityPort.value,
            "validateRetain.url",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vrmRetentionRetainClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vrmRetentionRetainProject.value)}
  val vrmRetentionRetainClassDir = Def.settingDyn {classDirectory.in(Runtime).in(vrmRetentionRetainProject.value)}
  lazy val runVrmRetentionRetain = Def.task {
    runProject(
      vrmRetentionRetainClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vrm-retention-retain/vrm-retention-retain.conf",
        Some(ConfigOutput(
          new File(vrmRetentionRetainClassDir.value, "vrm-retention-retain.conf"),
          setServicePortAndLegacyServicesPort(
            vrmRetentionRetainPort.value,
            "retain.url",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vrmAssignEligibilityClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vrmAssignEligibilityProject.value)}
  val vrmAssignEligibilityClassDir = Def.settingDyn {classDirectory.in(Runtime).in(vrmAssignEligibilityProject.value)}
  lazy val runVrmAssignEligibility = Def.task {
    runProject(
      vrmAssignEligibilityClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vrm-assign-eligibility/vrm-assign-eligibility.conf",
        Some(ConfigOutput(
          new File(vrmAssignEligibilityClassDir.value, "vrm-assign-eligibility.conf"),
          setServicePortAndLegacyServicesPort(
            vrmAssignEligibilityPort.value,
            "validateAssign.url",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val vrmAssignFulfilClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(vrmAssignFulfilProject.value)}
  val vrmAssignFulfilClassDir = Def.settingDyn {classDirectory.in(Runtime).in(vrmAssignFulfilProject.value)}
  lazy val runVrmAssignFulfil = Def.task {
    runProject(
      vrmAssignFulfilClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "vrm-assign-fulfil/vrm-assign-fulfil.conf",
        Some(ConfigOutput(
          new File(vrmAssignFulfilClassDir.value, "vrm-assign-fulfil.conf"),
          setServicePortAndLegacyServicesPort(
            vrmAssignFulfilPort.value,
            "assignFulfil.url",
            legacyServicesStubsPort.value
          )
        ))
      ))
    )
  }

  val auditClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(auditProject.value)}
  val auditClassDir = Def.settingDyn {classDirectory.in(Runtime).in(auditProject.value)}
  lazy val runAudit = Def.task {
    runProject(
      auditClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "audit/audit.conf",
        Some(ConfigOutput(
          new File(auditClassDir.value, "audit.conf"),
          setServicePort(auditPort.value)
        ))
      ))
    )
  }

  val emailServiceClassPath = Def.taskDyn {fullClasspath.in(Runtime).in(emailServiceProject.value)}
  val emailServiceClassDir = Def.settingDyn {classDirectory.in(Runtime).in(emailServiceProject.value)}
  lazy val runEmailService = Def.task {
    runProject(
      emailServiceClassPath.value,
      Some(ConfigDetails(
        configLocation((target in ThisProject).value),
        "email-service/email-service.conf",
        Some(ConfigOutput(
          new File(emailServiceClassDir.value, "email-service.conf"),
          setServicePort(emailServicePort.value)
        ))
      ))
    )
  }

  lazy val runAppAndMicroservices = Def.task {
    runAllMicroservices.value
    run.in(Compile).toTask("").value
  }

  lazy val runAsync = Def.task {
    val httpsEnvVars = asyncHttpsEnvVars.value

    // Gatling and cucumber run tests against the test.url
    sys.props ++= httpsEnvVars.filter { case (k, _) => k == "test.url" }

    val options = sbt.ForkOptions(
      workingDirectory = Some((baseDirectory in ThisProject).value),
      outputStrategy = sbt.Keys.outputStrategy.value,
      javaHome = sbt.Keys.javaHome.value,
      runJVMOptions = sbt.Keys.javaOptions.value ++ (httpsEnvVars ++ microservicesPortsEnvVars.value).map {
        case (k, v) => s"-D$k=$v"
      }.toList,
      connectInput = false
    )

    runProjectForked(
      options,
      fullClasspath.in(Test).value.map(_.data),
      "play.core.server.NettyServer"
    )
  }

  lazy val runAppAndMicroservicesAsync = Def.task[Unit] {
    runAllMicroservices.value
    runAsync.value
  }

  lazy val allAcceptanceTests = Def.task {
    acceptanceTests.value
    loadTests.value
  }

  private lazy val asyncHttpsEnvVars = Def.setting {
    val appContext = applicationContext.value match {
      case context: String if context.isEmpty => ""
      case context: String => s"/$context"
    }

    Map(
      "openingTimeMinOfDay" -> "0",
      "closingTimeMinOfDay" -> "1439",
      "https.port" -> httpsPort.value.toString,
      "http.port" -> "disabled",
      "jsse.enableSNIExtension" -> "false", // Disable the SNI for testing
      "baseUrl" -> s"https://localhost:${httpsPort.value}$appContext",
      "test.url" -> s"https://localhost:${httpsPort.value}$appContext/",
      "test.remote" -> "true"
    ) ++ (
      if (bruteForceEnabled.value) Map(
        "bruteForcePrevention.enabled" -> "true",
        "bruteForcePrevention.baseUrl" -> s"http://localhost:${legacyServicesStubsPort.value}/demo/services"
      ) else Map("bruteForcePrevention.enabled" -> "false")
    )
  }

  private lazy val microservicesPortsEnvVars = Def.setting {
    Map(
      "acquireVehicle.baseUrl" -> s"http://localhost:${vehiclesAcquireFulfilPort.value}",
      "auditMicroServiceUrlBase" -> s"http://localhost:${auditPort.value}",
      "disposeVehicle.baseUrl" -> s"http://localhost:${vehicleDisposePort.value}",
      "emailServiceMicroServiceUrlBase" -> s"http://localhost:${emailServicePort.value}",
      "ordnancesurvey.baseUrl" -> s"http://localhost:${osAddressLookupPort.value}",
      "paymentSolveMicroServiceUrlBase" -> s"http://localhost:${paymentSolvePort.value}",
      "vehicleAndKeeperLookupMicroServiceUrlBase" -> s"http://localhost:${vehicleAndKeeperLookupPort.value}",
      "vrmAssignEligibilityMicroServiceUrlBase" -> s"http://localhost:${vrmAssignEligibilityPort.value}",
      "vrmAssignFulfilMicroServiceUrlBase" -> s"http://localhost:${vrmAssignFulfilPort.value}",
      "vrmRetentionEligibilityMicroServiceUrlBase" -> s"http://localhost:${vrmRetentionEligibilityPort.value}",
      "vrmRetentionRetainMicroServiceUrlBase" -> s"http://localhost:${vrmRetentionRetainPort.value}"
    ) ++ (
      if (bruteForceEnabled.value) Map(
        "bruteForcePrevention.enabled" -> "true",
        "bruteForcePrevention.baseUrl" -> s"http://localhost:${legacyServicesStubsPort.value}/demo/services"
      ) else Map("bruteForcePrevention.enabled" -> "false")
    )
  }

  /**
   * Overrides the properties that the exemplars use to connect to their external dependencies (micro services
   * and only brute force in the legacy stub). Achieved using JVM system properties which supersede anything
   * explicitly defined in the configuration files
   */
  val setMicroservicesPortsEnvVars = Def.task {
    sys.props ++= microservicesPortsEnvVars.value

    val sandboxProperties = List("acquireVehicle.baseUrl", "auditMicroServiceUrlBase",
      "bruteForcePrevention.baseUrl", "bruteForcePrevention.enabled", "disposeVehicle.baseUrl",
      "emailServiceMicroServiceUrlBase", "ordnancesurvey.baseUrl", "paymentSolveMicroServiceUrlBase",
      "vehicleAndKeeperLookupMicroServiceUrlBase", "vrmAssignEligibilityMicroServiceUrlBase",
      "vrmAssignFulfilMicroServiceUrlBase", "vrmRetentionEligibilityMicroServiceUrlBase",
      "vrmRetentionRetainMicroServiceUrlBase"
    )
    println(s"Overriding the web apps's config with the following JVM system properties:")
    sys.props.foreach { case(key, value) =>
      if (sandboxProperties.contains(key)) println(s"${scala.Console.YELLOW}$key: $value${scala.Console.RESET}")}
    println("-- end JVM system properties --")
  }
}


text:
<?php

App::uses('AppModel', 'Model');

/**
 * Class CategoriesPost
 */
class CategoriesPost extends AppModel
{
    /**
     * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
     *
     * This field is also used in `find('list')` when called with no extra parameters in the fields list
     *
     * @var string
     */
    public $displayField = 'category_id';
}


text:
<document>
<result>success</result>
<resultcode>000000</resultcode>
<note></note>
<event_id>120266</event_id>
</document>


text:
module 'mock'

---DEAD LOCK DEBUG HELPER
local DEADLOCK_THRESHOLD = 100
local DEADLOCK_TRACK     = 10
local DEADLOCK_TRACK_ENABLED = true

local function tovalue( v )
	v = v:trim()
	if value == 'true' then
		return true, true
	elseif value == 'false' then
		return true, false
	elseif value == 'nil' then
		return true, nil
	else
		local n = tonumber( v )
		if n then return true, n end
		local s = v:match( [[^'(.*)'$]])
		if s then return true, s end
		local s = v:match( [[^"(.*)"$]])
		if s then return true, s end
	end
	return false
end

--------------------------------------------------------------------
local function buildFSMScheme( scheme )
	-- assert(targetClass,'Target Class required')
	assert( scheme, 'FSM Data required' )

	--for deadlock detection
	local trackedStates = {}

	--
	local stateFuncs    = {}

	---
	local function parseExprJump( msg )
		local content = msg:match('%s*if%s*%((.*)%)%s*')
		if not content then return nil end
		content = content:trim()

		local valueFunc, err = loadEvalScriptWithEnv( content )
		if not valueFunc then
			_warn( 'failed compiling condition expr:', err )
			return false
		else
			return valueFunc
		end
	end

	--build state funcs
	for name, stateBody in pairs( scheme ) do
		local id         = stateBody.id     --current state id
		local jump       = stateBody.jump   --transition trigger by msg
		local outStates  = stateBody.next   --transition trigger by state return value

		local localName  = stateBody.localName
		local stepName   = id .. '__step'
		local exitName   = id .. '__exit'
		local enterName  = id .. '__enter'

		local exprJump = false
		if jump then
			for msg, target in pairs( jump ) do
				local exprFunc = parseExprJump( msg )
				if exprFunc then
					if not exprJump then exprJump = {} end
					exprJump[ msg ] = exprFunc
				end
			end
			if exprJump then
				for msg, exprFunc in pairs( exprJump ) do
					--replace msg
					local target = jump[ msg ]
					jump[ msg ] = nil
					jump[ exprFunc ] = target
				end
			end
		end
		--generated function
		local function stateStep( controller, dt, switchCount )
			----PRE STEP TRANSISTION
			local nextState
			local transMsg, transMsgArg

			local forceJumping = controller.forceJumping
			if forceJumping then
				controller.forceJumping = false
				nextState, transMsg, transMsgArg = unpack( forceJumping )
			else
				---STEP
				local step = controller[ stepName ]
				local out  = true
				--step return name of next state
				if step then
					out = step( controller, dt )
					dt = 0 --delta time is consumed
				elseif step == nil then
					controller[ stepName ] = false
				end

				----POST STEP TRANSISTION
				if out and outStates then --approach next state
					nextState = outStates[ out ]
					if not nextState then
						_error( '! error in state:'..name )
						if type( out ) ~= 'string' then
							return error( 'output state name expected' )
						end
						error( 'output state not found:'..tostring( out ) )
					end
				else
					--find triggering msg (post phase)
					while true do
						transMsg, transMsgArg = controller:pollMsg()
						if not transMsg then return end
						nextState = jump and jump[ transMsg ]
						if nextState then break end
					end
				end

			end

			if DEADLOCK_TRACK_ENABLED then
				--DEADLOCK DETECTOR
				switchCount = switchCount + 1
				if switchCount == DEADLOCK_THRESHOLD then
					trackedStates = {}
				elseif switchCount > DEADLOCK_THRESHOLD then
					table.insert( trackedStates, name )
					if switchCount > DEADLOCK_THRESHOLD + DEADLOCK_TRACK then
						--state traceback
						_log( "state switch deadlock:", switchCount )
						for i, s in ipairs( trackedStates ) do
							_log( i, s )
						end
						if getG( 'debugstop' ) then
							debugStop()
						end
						-- game:debugStop()
						error('TERMINATED') --terminate
					end
				end
			end

			local nextStateBody
			local nextStateName

			if controller:acceptStateChange( nextState ) == false then
				return
			end
			--TRANSITION
			local tt = type( nextState )
			if tt == 'string' then --direct transition
				nextStateName = nextState
				local exit = controller[ exitName ]
				if exit then --exit previous state
					exit( controller, nextStateName, transMsg, transMsgArg )
				elseif exit == nil then
					controller[ exitName ] = false
				end

			else --group transitions
				local l = #nextState
				nextStateName = nextState[l]
				local exit = controller[ exitName ]
				if exit then --exit previous state
					exit( controller, nextStateName, transMsg, transMsgArg )
				elseif exit == nil then
					controller[ exitName ] = false
				end
				--extra state group exit/enter
				for i = 1, l-1 do
					local funcName = nextState[ i ]
					local func = controller[ funcName ]
					if func then
						func( controller, name, nextStateName, transMsg, transMsgArg )
					end
				end
			end

			controller:setState( nextStateName )
			nextStateBody = scheme[ nextStateName ]
			if not nextStateBody then
				error( 'state body not found:' .. nextStateName, 2 )
			end
			local enterName = nextStateBody.enterName
			--activate and enter new state handler
			local nextFunc = nextStateBody.func
			controller.currentStateFunc = nextFunc
			controller.currentExprJump  = nextStateBody.exprJump
			local enter = controller[ enterName ]
			if enter then --entering new state
				enter( controller, name, transMsg, transMsgArg )
			elseif enter == nil then
				controller[ enterName ] = false
			end
			controller:updateExprJump()
			return nextFunc( controller, dt, switchCount )

		end

		stateBody.func      = stateStep
		stateBody.stepName  = stepName
		stateBody.enterName = enterName
		stateBody.exitName  = exitName
		stateBody.exprJump  = exprJump

	end

	local startFunc      = scheme['start'].func
	local startEnterName = scheme['start'].enterName
	local startExprJump  = scheme['start'].exprJump
	scheme[0] = function( controller, dt )
		controller.currentStateFunc = startFunc
		controller.currentExprJump  = startExprJump
		local f = controller[ startEnterName ]
		if f then
			f( controller ) --fsm.start:enter
		end
		controller:updateExprJump()
		return startFunc( controller, dt, 0 )
	end
end

--------------------------------------------------------------------
function FSMSchemeLoader( node )
	local path = node:getObjectFile('def')
	local scheme = dofile( path )
	buildFSMScheme( scheme )
	return scheme
end

registerAssetLoader ( 'fsm_scheme', FSMSchemeLoader )


text:
'use strict';

//////////////////////////////
// Requires
//////////////////////////////
var karma = require('karma').server;

//////////////////////////////
// Internal Vars
//////////////////////////////
var karmaOptions = {
  configFile: __dirname + '/../karma.conf.js',
  singleRun: false
}

//////////////////////////////
// Export
//////////////////////////////
module.exports = function (gulp, options) {
  // Run once
  gulp.task('karma', function (done) {
    options = options || karmaOptions;
    options.singleRun = true;

    karma.start(options, done);
  });

  // Run continuously
  gulp.task('karma--dev', function (done) {
    options = options || karmaOptions;
    options.singleRun = false;

    karma.start(options, done);
  });

  // Get code coverage
  gulp.task('karma--coverage', function (done) {
    options = options || karmaOptions;
    options.singleRun = true;
    options.preprocessors = {};
    options.preprocessors['build/**/*.js'] = ['coverage'];
    options.reporters = ['coverage', 'coveralls'];
    options.coverageReporter = {
      type: 'lcov',
      dir: 'coverage/'
    }

    karma.start(options, done);
  });
}


text:
package com.bupt.core.system.model;

public class RolePrivilegeKey {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_security_role_privilege.privilege_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    private Integer privilegeId;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_security_role_privilege.role_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    private Integer roleId;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_security_role_privilege.privilege_id
     *
     * @return the value of t_security_role_privilege.privilege_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    public Integer getPrivilegeId() {
        return privilegeId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_security_role_privilege.privilege_id
     *
     * @param privilegeId the value for t_security_role_privilege.privilege_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    public void setPrivilegeId(Integer privilegeId) {
        this.privilegeId = privilegeId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_security_role_privilege.role_id
     *
     * @return the value of t_security_role_privilege.role_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    public Integer getRoleId() {
        return roleId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_security_role_privilege.role_id
     *
     * @param roleId the value for t_security_role_privilege.role_id
     *
     * @mbggenerated Wed Sep 25 18:54:09 CST 2013
     */
    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }
}


text:
<link href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<link href="<?php echo base_url(); ?>css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="<?php echo base_url(); ?>dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />

<link href="<?php echo base_url(); ?>plugins/iCheck/square/blue.css" rel="stylesheet" type="text/css" />

<link id="base-style-responsive" href="<?php echo base_url(); ?>css/mine.css" rel="stylesheet">

                            <?php
                            if (is_array($roleID) && count($roleID)) {
                                foreach ($roleID as $role) {
                                    ?>

                                    <form id="edit-form" name="edit-form" enctype="multipart/form-data"  action='<?= base_url(); ?>index.php/Role/update'  method="post">

                                                        Update user role

                                                    <fieldset>

                                                                <input type="text" class="span12" id="edit_role" name="edit_role" value="<?= $role->name ?>"  />
                                                                <input type="hidden" class="span12" id="roleID" name="roleID" value="<?= $role->id ?>" />

                                                            Please select the user privileges

                                                         Actions
                                                        <input type="text" class="span12" id="edit_actions" name="edit_actions" value="<?= $role->actions ?>"  />

                                                        <button type="submit" class="width-10  btn btn-small btn-success">
                                                            Update

                                                        </button>

                                                    </fieldset>

                                    </form>

                                <?php }
                            } else {
                                ?>

                                <form id="role-form" name="role-form" enctype="multipart/form-data"  action='<?= base_url(); ?>index.php/Role/save'  method="post">

                                                <fieldset>
    <?php echo $this->session->flashdata('msg'); ?>

                                                        Please select the user privileges

                                                    <input type="text" class="span3" id="role" name="role" required="" placeholder="Role" />
                                                    <img src="<?= base_url(); ?>images/ajax-loader.gif" alt="Ajax Indicator" />

                                                     Level(1-4)
                                                    <input type="text" class="span12" id="actions" name="actions"   />

                                                    <button type="submit" class="width-10  btn btn-small btn-success">
                                                        Submit

                                                    </button>

                                                </fieldset>

                                </form>

<?php } ?>

                                                <input type="checkbox" />

                                        Role name
                                        level

                                    <?php
                                    if (is_array($roles) && count($roles)) {
                                        foreach ($roles as $loop) {
                                            ?>

                                                <input type="checkbox" />

                                                <?= $loop->name ?>
                                                <?= $loop->actions ?>

                                                    <a href="<?php echo base_url() . "index.php/Role/edit/" . $loop->id; ?>" class="tooltip-info" data-rel="tooltip" title="View">
                                                        Edit

                                                    <a href="<?php echo base_url() . "index.php/Role/delete/" . $loop->id; ?>" class="tooltip-error" data-rel="tooltip" title="Delete">
                                                        Delete

                                            <?php
                                        }
                                    }
                                    ?>