text:
using namespace BamTools;

#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace BamTools {

// define constants
const unsigned int RANDOM_MAX_ALIGNMENT_COUNT = 10000;

// utility methods for RandomTool
int getRandomInt(const int& lowerBound, const int& upperBound)
{
    const int range = (upperBound - lowerBound) + 1;
    return (lowerBound + (int)(range * (double)rand() / ((double)RAND_MAX + 1)));
}

}  // namespace BamTools

// ---------------------------------------------
// RandomSettings implementation

struct RandomTool::RandomSettings
{

    // flags
    bool HasAlignmentCount;
    bool HasInput;
    bool HasInputFilelist;
    bool HasOutput;
    bool HasRandomNumberSeed;
    bool HasRegion;
    bool IsForceCompression;

    // parameters
    unsigned int AlignmentCount;
    std::vector<std::string> InputFiles;
    std::string InputFilelist;
    std::string OutputFilename;
    unsigned int RandomNumberSeed;
    std::string Region;

    // constructor
    RandomSettings()
        : HasAlignmentCount(false)
        , HasInput(false)
        , HasInputFilelist(false)
        , HasOutput(false)
        , HasRandomNumberSeed(false)
        , HasRegion(false)
        , IsForceCompression(false)
        , AlignmentCount(RANDOM_MAX_ALIGNMENT_COUNT)
        , OutputFilename(Options::StandardOut())
        , RandomNumberSeed(0)
    {}
};

// ---------------------------------------------
// RandomToolPrivate implementation

struct RandomTool::RandomToolPrivate
{

    // ctor & dtor
public:
    RandomToolPrivate(RandomTool::RandomSettings* settings)
        : m_settings(settings)
    {}

    ~RandomToolPrivate() {}

    // interface
public:
    bool Run();

    // data members
private:
    RandomTool::RandomSettings* m_settings;
};

bool RandomTool::RandomToolPrivate::Run()
{

    // set to default stdin if no input files provided
    if (!m_settings->HasInput && !m_settings->HasInputFilelist)
        m_settings->InputFiles.push_back(Options::StandardIn());

    // add files in the filelist to the input file list
    if (m_settings->HasInputFilelist) {

        std::ifstream filelist(m_settings->InputFilelist.c_str(), std::ios::in);
        if (!filelist.is_open()) {
            std::cerr << "bamtools random ERROR: could not open input BAM file list... Aborting."
                      << std::endl;
            return false;
        }

        std::string line;
        while (std::getline(filelist, line))
            m_settings->InputFiles.push_back(line);
    }

    // open our reader
    BamMultiReader reader;
    if (!reader.Open(m_settings->InputFiles)) {
        std::cerr << "bamtools random ERROR: could not open input BAM file(s)... Aborting."
                  << std::endl;
        return false;
    }

    // look up index files for all BAM files
    reader.LocateIndexes();

    // make sure index data is available
    if (!reader.HasIndexes()) {
        std::cerr << "bamtools random ERROR: could not load index data for all input BAM "
                     "file(s)... Aborting."
                  << std::endl;
        reader.Close();
        return false;
    }

    // get BamReader metadata
    const std::string headerText = reader.GetHeaderText();
    const RefVector references = reader.GetReferenceData();
    if (references.empty()) {
        std::cerr << "bamtools random ERROR: no reference data available... Aborting." << std::endl;
        reader.Close();
        return false;
    }

    // determine compression mode for BamWriter
    bool writeUncompressed =
        (m_settings->OutputFilename == Options::StandardOut() && !m_settings->IsForceCompression);
    BamWriter::CompressionMode compressionMode = BamWriter::Compressed;
    if (writeUncompressed) compressionMode = BamWriter::Uncompressed;

    // open BamWriter
    BamWriter writer;
    writer.SetCompressionMode(compressionMode);
    if (!writer.Open(m_settings->OutputFilename, headerText, references)) {
        std::cerr << "bamtools random ERROR: could not open " << m_settings->OutputFilename
                  << " for writing... Aborting." << std::endl;
        reader.Close();
        return false;
    }

    // if user specified a REGION constraint, attempt to parse REGION string
    BamRegion region;
    if (m_settings->HasRegion &&
        !Utilities::ParseRegionString(m_settings->Region, reader, region)) {
        std::cerr << "bamtools random ERROR: could not parse REGION: " << m_settings->Region
                  << std::endl;
        std::cerr << "Check that REGION is in valid format (see documentation) and that the "
                     "coordinates are valid"
                  << std::endl;
        reader.Close();
        writer.Close();
        return false;
    }

    // seed our random number generator
    if (m_settings->HasRandomNumberSeed)
        srand(m_settings->RandomNumberSeed);
    else
        srand(time(NULL));

    // grab random alignments
    BamAlignment al;
    unsigned int i = 0;
    while (i < m_settings->AlignmentCount) {

        int randomRefId = 0;
        int randomPosition = 0;

        // use REGION constraints to select random refId & position
        if (m_settings->HasRegion) {

            // select a random refId
            randomRefId = getRandomInt(region.LeftRefID, region.RightRefID);

            // select a random position based on randomRefId
            const int lowerBoundPosition =
                ((randomRefId == region.LeftRefID) ? region.LeftPosition : 0);
            const int upperBoundPosition =
                ((randomRefId == region.RightRefID) ? region.RightPosition
                                                    : (references.at(randomRefId).RefLength - 1));
            randomPosition = getRandomInt(lowerBoundPosition, upperBoundPosition);
        }

        // otherwise select from all possible random refId & position
        else {

            // select random refId
            randomRefId = getRandomInt(0, (int)references.size() - 1);

            // select random position based on randomRefId
            const int lowerBoundPosition = 0;
            const int upperBoundPosition = references.at(randomRefId).RefLength - 1;
            randomPosition = getRandomInt(lowerBoundPosition, upperBoundPosition);
        }

        // if jump & read successful, save first alignment that overlaps random refId & position
        if (reader.Jump(randomRefId, randomPosition)) {
            while (reader.GetNextAlignmentCore(al)) {
                if (al.RefID == randomRefId && al.Position >= randomPosition) {
                    writer.SaveAlignment(al);
                    ++i;
                    break;
                }
            }
        }
    }

    // cleanup & exit
    reader.Close();
    writer.Close();
    return true;
}

// ---------------------------------------------
// RandomTool implementation

RandomTool::RandomTool()
    : AbstractTool()
    , m_settings(new RandomSettings)
    , m_impl(0)
{
    // set program details
    Options::SetProgramInfo("bamtools random", "grab a random subset of alignments",
                            "[-in <filename> -in <filename> ... | -list <filelist>] [-out "
                            "<filename>] [-forceCompression] [-n] [-region <REGION>]");

    // set up options
    OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
    Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInput,
                            m_settings->InputFiles, IO_Opts, Options::StandardIn());
    Options::AddValueOption("-list", "filename", "the input BAM file list, one line per file", "",
                            m_settings->HasInputFilelist, m_settings->InputFilelist, IO_Opts);
    Options::AddValueOption("-out", "BAM filename", "the output BAM file", "",
                            m_settings->HasOutput, m_settings->OutputFilename, IO_Opts,
                            Options::StandardOut());
    Options::AddValueOption("-region", "REGION",
                            "only pull random alignments from within this genomic region. Index "
                            "file is recommended for better performance, and is used automatically "
                            "if it exists. See \'bamtools help index\' for more details on "
                            "creating one",
                            "", m_settings->HasRegion, m_settings->Region, IO_Opts);
    Options::AddOption("-forceCompression",
                       "if results are sent to stdout (like when piping to another tool), default "
                       "behavior is to leave output uncompressed. Use this flag to override and "
                       "force compression",
                       m_settings->IsForceCompression, IO_Opts);

    OptionGroup* SettingsOpts = Options::CreateOptionGroup("Settings");
    Options::AddValueOption(
        "-n", "count", "number of alignments to grab. Note - no duplicate checking is performed",
        "", m_settings->HasAlignmentCount, m_settings->AlignmentCount, SettingsOpts,
        RANDOM_MAX_ALIGNMENT_COUNT);
    Options::AddValueOption("-seed", "unsigned integer",
                            "random number generator seed (for repeatable results). Current time "
                            "is used if no seed value is provided.",
                            "", m_settings->HasRandomNumberSeed, m_settings->RandomNumberSeed,
                            SettingsOpts);
}

RandomTool::~RandomTool()
{

    delete m_settings;
    m_settings = 0;

    delete m_impl;
    m_impl = 0;
}

int RandomTool::Help()
{
    Options::DisplayHelp();
    return 0;
}

int RandomTool::Run(int argc, char* argv[])
{

    // parse command line arguments
    Options::Parse(argc, argv, 1);

    // initialize RandomTool with settings
    m_impl = new RandomToolPrivate(m_settings);

    // run RandomTool, return success/fail
    if (m_impl->Run())
        return 0;
    else
        return 1;
}


text:
{-
   Copyright 2016, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish

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

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

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

module Camfort.Transformation.EquivalenceElim
  ( refactorEquivalences
  ) where

import Data.List
import Data.Void (Void)
import qualified Data.Map as M
import Data.Generics.Uniplate.Operations
import Control.Monad.State.Lazy

import qualified Language.Fortran.AST as F
import qualified Language.Fortran.Analysis.Types as FAT (analyseTypes, TypeEnv)
import qualified Language.Fortran.Util.Position as FU
import qualified Language.Fortran.Analysis.Renaming as FAR
import qualified Language.Fortran.Analysis as FA

import Camfort.Analysis
import Camfort.Helpers.Syntax
import Camfort.Analysis.Annotations
import Camfort.Transformation.DeadCode

type EquivalenceRefactoring = PureAnalysis Void Void

type A1 = FA.Analysis Annotation
type RmEqState = ([[F.Expression A1]], Int)

refactorEquivalences :: F.ProgramFile A -> EquivalenceRefactoring (F.ProgramFile A)
refactorEquivalences pf = do
  let
    -- initialise analysis
    pf'             = FAR.analyseRenames . FA.initAnalysis $ pf
    -- calculate types
    (pf'', typeEnv) = FAT.analyseTypes pf'
    -- Remove equivalences and add appropriate copy statements
  pf''' <- refactoring typeEnv pf''
  -- Lastly deadcode eliminate any redundant copy statements
  -- generated by the refactoring (but don't dead code elim
  -- existing code)
  deadCode True (fmap FA.prevAnnotation pf''')
  where
    refactoring
      :: FAT.TypeEnv -> F.ProgramFile A1
      -> EquivalenceRefactoring (F.ProgramFile A1)
    refactoring tenv pf = do
      (pf', _) <- runStateT equiv ([], 0)
      return pf'
      where
         equiv = do pf' <- transformBiM perBlockRmEquiv pf
                    descendBiM (addCopysPerBlockGroup tenv) pf'

addCopysPerBlockGroup
  :: FAT.TypeEnv -> [F.Block A1]
  -> StateT RmEqState EquivalenceRefactoring [F.Block A1]
addCopysPerBlockGroup tenv blocks = do
    blockss <- mapM (addCopysPerBlock tenv) blocks
    return $ concat blockss

addCopysPerBlock
  :: FAT.TypeEnv -> F.Block A1
  -> StateT RmEqState EquivalenceRefactoring [F.Block A1]
addCopysPerBlock tenv x@(F.BlStatement _ _ _
                 (F.StExpressionAssign a sp@(FU.SrcSpan s1 _) dstE _))
  | not (pRefactored $ FA.prevAnnotation a) = do
    -- Find all variables/cells that are equivalent to the target
    -- of this assignment
    eqs <- equivalentsToExpr dstE
    -- If there is only one, then it must refer to itself, so do nothing
    if length eqs <= 1
      then return [x]
    -- If there are more than one, copy statements must be generated
      else do
        (equivs, n) <- get

        -- Remove the destination from the equivalents
        let eqs' = deleteBy (\x y -> af x == af y) dstE eqs

        -- Make copy statements
        let pos = afterAligned sp
        let copies = map (mkCopy tenv pos dstE) eqs'

        let (FU.Position ao c l) = s1
            reportSpan i =
              let pos = FU.Position (ao + i) c (l + i)
              in (FU.SrcSpan pos pos)

        forM_ [n..(n + length copies - 1)] $ \i -> do
          origin <- atSpanned (reportSpan i)
          logInfo origin $ "added copy due to refactored equivalence"

        -- Update refactoring state
        put (equivs, n + length eqs')
        -- Sequence original assignment with new assignments
        return $ x : copies

addCopysPerBlock tenv x = do
   x' <- descendBiM (addCopysPerBlockGroup tenv) x
   return [x']

-- see if two expressions have the same type
equalTypes tenv e e' = do
    v1 <- extractVariable e
    v2 <- extractVariable e'
    t1 <- M.lookup v1 tenv
    t2 <- M.lookup v2 tenv
    if t1 == t2 then Just t1 else Nothing

-- Create copy statements. Parameters:
--    * A type environment to find out if a type cast is needed
--    * A SrcPos where the copy statements are going to inserted at
--    * The source expression
--    * The number of copies to increment the line by
--           paired with the destination expression
mkCopy :: FAT.TypeEnv
       -> FU.Position
       -> F.Expression A1 -> F.Expression A1 -> F.Block A1
mkCopy tenv pos srcE dstE = FA.initAnalysis $
   F.BlStatement a sp Nothing $
     case equalTypes tenv srcE dstE of
       -- Types not equal, so create a transfer
       Nothing -> F.StExpressionAssign a sp dstE' call
                    where
                     call = F.ExpFunctionCall a sp transf argst
                     transf = F.ExpValue a sp (F.ValVariable "transfer")
                     argst  = Just (F.AList a sp args)
                     args   = map (F.Argument a sp Nothing) [srcE', dstE']
       -- Types are equal, simple a assignment
       Just _ -> F.StExpressionAssign a sp dstE' srcE'
  where
     -- Set position to be at col = 0
     sp   = FU.SrcSpan (toCol0 pos) (toCol0 pos)
     -- But store the aligned position in refactored so
     -- that the reprint algorithm can add the appropriate indentation
     a = unitAnnotation { refactored = Just pos, newNode = True }
     dstE' = FA.stripAnalysis dstE
     srcE' = FA.stripAnalysis srcE

perBlockRmEquiv :: F.Block A1 -> StateT RmEqState EquivalenceRefactoring (F.Block A1)
perBlockRmEquiv = transformBiM perStatementRmEquiv

perStatementRmEquiv
  :: F.Statement A1
  -> StateT RmEqState EquivalenceRefactoring (F.Statement A1)
perStatementRmEquiv x@(F.StEquivalence a sp@(FU.SrcSpan spL _) equivs) = do
    (ess, n) <- get

    let spL' = FU.SrcSpan spL spL
    logInfo' spL' $ "removed equivalence"

    put (((map F.aStrip) . F.aStrip $ equivs) ++ ess, n - 1)
    let a' = onPrev (\ap -> ap {refactored = Just spL, deleteNode = True}) a
    return (F.StEquivalence a' (deleteLine sp) equivs)
perStatementRmEquiv f = return f

-- 'equivalents e' returns a list of variables/memory cells
-- that have been equivalenced with "e".
equivalentsToExpr
  :: F.Expression A1
  -> StateT RmEqState EquivalenceRefactoring [F.Expression A1]
equivalentsToExpr x = do
    (equivs, _) <- get
    return (inGroup x equivs)
  where
    inGroup _ [] = []
    inGroup x (xs:xss) =
        if AnnotationFree x `elem` map AnnotationFree xs
        then xs
        else inGroup x xss

redpajama_set_name: RedPajamaGithub


text:
package com.avsystem.scex
package compiler

import java.{lang => jl, util => ju}

/**
 * Created: 12-12-2013
 * Author: ghik
 */
object Markers {

  trait Synthetic extends Any

  trait ExpressionUtil extends Any with Synthetic

  trait JavaGetterAdapter extends Any with Synthetic

  trait ProfileObject extends Any with Synthetic

}


text:
package org.apache.spark.sql.execution.python

import scala.collection.JavaConverters._

import org.apache.spark.TaskContext
import org.apache.spark.api.python.ChainedPythonFunctions
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.util.ArrowUtils

/**
 * Grouped a iterator into batches.
 * This is similar to iter.grouped but returns Iterator[T] instead of Seq[T].
 * This is necessary because sometimes we cannot hold reference of input rows
 * because the some input rows are mutable and can be reused.
 */
private[spark] class BatchIterator[T](iter: Iterator[T], batchSize: Int)
  extends Iterator[Iterator[T]] {

  override def hasNext: Boolean = iter.hasNext

  override def next(): Iterator[T] = {
    new Iterator[T] {
      var count = 0

      override def hasNext: Boolean = iter.hasNext && count < batchSize

      override def next(): T = {
        if (!hasNext) {
          Iterator.empty.next()
        } else {
          count += 1
          iter.next()
        }
      }
    }
  }
}

/**
 * A physical plan that evaluates a [[PythonUDF]].
 */
case class ArrowEvalPythonExec(udfs: Seq[PythonUDF], resultAttrs: Seq[Attribute], child: SparkPlan,
    evalType: Int)
  extends EvalPythonExec {

  private val batchSize = conf.arrowMaxRecordsPerBatch
  private val sessionLocalTimeZone = conf.sessionLocalTimeZone
  private val pythonRunnerConf = ArrowUtils.getPythonRunnerConfMap(conf)

  protected override def evaluate(
      funcs: Seq[ChainedPythonFunctions],
      argOffsets: Array[Array[Int]],
      iter: Iterator[InternalRow],
      schema: StructType,
      context: TaskContext): Iterator[InternalRow] = {

    val outputTypes = output.drop(child.output.length).map(_.dataType)

    // DO NOT use iter.grouped(). See BatchIterator.
    val batchIter = if (batchSize > 0) new BatchIterator(iter, batchSize) else Iterator(iter)

    val columnarBatchIter = new ArrowPythonRunner(
      funcs,
      evalType,
      argOffsets,
      schema,
      sessionLocalTimeZone,
      pythonRunnerConf).compute(batchIter, context.partitionId(), context)

    columnarBatchIter.flatMap { batch =>
      val actualDataTypes = (0 until batch.numCols()).map(i => batch.column(i).dataType())
      assert(outputTypes == actualDataTypes, "Invalid schema from pandas_udf: " +
        s"expected ${outputTypes.mkString(", ")}, got ${actualDataTypes.mkString(", ")}")
      batch.rowIterator.asScala
    }
  }
}


text:
module("atom.url");

test("url (init using custom locations)", function runTest()
{
	var url1 = atom.url("http://localhost:63342/atom/test/tests/utils.html?module=atom.url");
	var url2 = atom.url("http://www.nbcnews.com:99/id/21134540/vp/#53399221");
	var url3 = atom.url("https://igor.france:p4$$w0rd@www.facebook.com/posts/534650296624196?comment_id=3279283&notif_t=like");

	equal(url1.components.protocol, "http", "Url test 1");
	equal(url1.components.host, "localhost", "Url test 2");
	equal(url1.components.port, "63342", "Url test 3");
	equal(url1.components.directory, "/atom/test/tests/", "Url test 4");
	equal(url1.components.query, "module=atom.url", "Url test 5");
	equal(url1.components.file, "utils.html", "Url test 6");
	equal(url1.getQueryParam("module"), "atom.url", "Url test 7");

	equal(url2.components.authority, "www.nbcnews.com:99", "Url test 8");
	equal(url2.components.hash, "53399221", "Url test 9");

	equal(url3.components.protocol, "https", "Url test 10");
	equal(url3.components.user, "igor.france", "Url test 11");
	equal(url3.components.password, "p4$$w0rd", "Url test 12");
	equal(url3.components.host, "www.facebook.com", "Url test 13");
	equal(url3.getQueryParam("comment_id"), "3279283", "Url test 14");
	equal(url3.getQueryParam("notif_t"), "like", "Url test 15");
});

test("url (init using window.location)", function runTest()
{
	equal(atom.url.getQueryParam("not-there-at-all"), null,
		"Fetching a non existing query parameter from the current url should return a null");
	equal(atom.url.getHashParam("not-there-at-all"), null,
		"Fetching a non existing hash parameter from the current url should return a null");
});

test("url.serializeParams", function runTest()
{
	var params1 = { v: 1, z: 4, p: [1,2,3] };

	equal(atom.url.serializeParams(params1),
		"v=1&z=4&p=1,2,3",
		"Serializing parameters with default options should generate a valid string");

	equal(atom.url.serializeParams(params1, { separator: "|", equals: "+" }),
		"v+1|z+4|p+1,2,3",
		"Serializing parameters with default options should generate a valid string");

	equal(atom.url.serializeParams(params1, { separator: "|", equals: "", encode: true }),
		"v1|z4|p1%2C2%2C3",
		"Serializing parameters with default options should generate a valid string");

});

test("url.getQuery", function runTest()
{
	var url1 = atom.url("index.html?a=5&b=7&c=8");

	equal(url1.getQuery(), "a=5&b=7&c=8");
	equal(url1.getQuery("?"), "?a=5&b=7&c=8");
});

test("url.getHash", function runTest()
{
	var url1 = atom.url("index.html#a=5&b=7&c=8");

	equal(url1.getHash(), "a=5&b=7&c=8");
	equal(url1.getHash("#"), "#a=5&b=7&c=8");
});


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GPSoft.Games.GPMagic.GPMagicBase.Model;
using GPSoft.Games.GPMagic.GPMagicBase.Model.Database;

namespace GPSoft.Games.GPMagic.GPMagicBase.UI
{
    public partial class CheckValuesDialog : Form
    {
        /// <summary>
        /// 当前处理的数据实例
        /// </summary>
        private AbstractTableInstance tableInstance;
        private Type modelType;
        private CheckValuesDialog()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 打开列表选择对话框
        /// </summary>
        /// <param name="title">对话框标题</param>
        /// <param name="defaultValue">初始值</param>
        /// <param name="split">多数值的分隔符</param>
        /// <param name="modelType">数据对应的类型</param>
        /// <returns></returns>
        public static string Show(string title, string defaultValue, string split, Type modelType)
        {
            string result = string.Empty;
            CheckValuesDialog cvd = new CheckValuesDialog();
            cvd.Text = title;
            cvd.tbxSearch.Focus();
            cvd.modelType = modelType;
            cvd.tableInstance = Activator.CreateInstance(modelType) as AbstractTableInstance;
            cvd.SetValueListData();
            string[] defaultArray = defaultValue.Split(split.ToCharArray());
            foreach (string valueText in defaultArray)
            {
                int valueIndex = cvd.GetValueItemIndex(valueText);
                if (valueIndex >= 0)
                {
                    cvd.lvwValues.Items[valueIndex].Checked = true;
                }
            }
            if (cvd.ShowDialog() == DialogResult.OK)
            {
                List<string> list = new List<string>();
                foreach (ListViewItem item in cvd.lvwResults.Items)
                {
                    list.Add(item.Text);
                }
                result = string.Join(split, list.ToArray());
            }
            else
            {
                result = defaultValue;
            }
            return result;
        }

        private void SetValueListData()
        {
            lvwValues.Items.Clear();
            string displayColumnName = tableInstance.DisplayColumnName;
            foreach (DataRow aRow in this.tableInstance.Records.Rows)
            {
                lvwValues.Items.Add(string.Empty).SubItems.Add(aRow[displayColumnName].ToString());
            }
        }

        private int GetValueItemIndex(string value)
        {
            int result = -1;
            DataRow[] rows = tableInstance.Records.Select(
                string.Format("{0}='{1}'", tableInstance.DisplayColumnName, value));
            result = rows.Length > 0 ? tableInstance.Records.Rows.IndexOf(rows[0]) : -1;
            return result;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            string newValue = InputTextDialog.Show(string.Format("新建 - {0}", this.Text), string.Empty);
            if (!string.IsNullOrEmpty(newValue))
            {
                int existIndex = GetValueItemIndex(newValue);
                if (existIndex >= 0)
                {
                    MessageBox.Show("新建数据已经存在,本次新建操作失败。",
                        "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    object newObj = tableInstance.NewDataInstance();
                    tableInstance.DataInstanceType.GetProperty(tableInstance.DisplayColumnName).SetValue(newObj, newValue, null);
                    tableInstance.Add(newObj);
                    tableInstance.Reload();
                    lvwValues.Items.Add(string.Empty).SubItems.Add(newValue);
                    existIndex = tableInstance.Records.Rows.Count - 1;
                }
                if (existIndex >= 0) lvwValues.Items[existIndex].Selected = true;
            }
        }

        private void mnuItemDelete_Click(object sender, EventArgs e)
        {

        }

        private void DeleteSelectedResultItems()
        {
            foreach (ListViewItem resultItem in lvwResults.SelectedItems)
            {
                int valueIndex = GetValueItemIndex(resultItem.Text);
                if (valueIndex >= 0)
                {
                    lvwValues.Items[valueIndex].Checked = false;
                }
            }
        }

        private void lvwValues_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            string itemText = string.Empty;
            if (e.Item.Checked)
            {
                itemText = e.Item.SubItems[1].Text;
                lvwResults.Items.Add(itemText, itemText, -1);
            }
            else
            {
                if (lvwResults.Items.Count > 0)
                {
                    if (e.Item.SubItems.Count > 1) itemText = e.Item.SubItems[1].Text;
                    foreach (ListViewItem item in lvwResults.Items.Find(itemText, true))
                    {
                        item.Remove();
                    }
                }
            }
        }

        private void lvwValues_DragDrop(object sender, DragEventArgs e)
        {
            DeleteSelectedResultItems();
        }

        private void lvwResults_ItemDrag(object sender, ItemDragEventArgs e)
        {
            lvwResults.DoDragDrop(lvwResults.SelectedItems, DragDropEffects.Copy);
        }

        private void lvwValues_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void lvwResults_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    {
                        DeleteSelectedResultItems();
                        break;
                    }
            }
        }
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../src/css/bootstrap.css" rel="stylesheet">

Post id: <input type="text" id="pid" required>

<input type="button" id="getp" value="Get post">


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2011-2012, Jakob Korherr

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

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

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.apacheextras.myfaces</groupId>
    <artifactId>relative-resource-handler-aggregate-project</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>Relative ResourceHandler Aggregator Project</name>

    <modules>
        <module>resource-handler</module>
        <module>examples</module>
    </modules>

</project>


text:
"""
Unit testing
"""
import unittest
import os.path
import arcpy
import forestryTools

class TestUsingLocalData(unittest.TestCase):

    # useful variables
    dirThis = os.path.dirname(__file__)
    fcTracts = r'D:\dev\forestry-tools\resources\data.gdb\Demographic_Layers__BDS__Tracts'
    lyrTracts = arcpy.MakeFeatureLayer_management(fcTracts, 'lyrTracts', "ID = '53033029204'")
    gdbSrtch = os.path.join(dirThis, 'resources', 'data.gdb')

    # overwrite previous outputs if they exist
    arcpy.env.overwriteOutput = True

    def test_random150by150_defaultUnits(self):

        forestryTools.postPointsByDimensionRandom(
            inputFeatures=self.lyrTracts,
            xGridSpacing=150,
            yGridSpacing=150,
            outputFeatureClass=os.path.join(self.gdbSrtch, 'random150by150default')
        )

    def test_random6by6_chains(self):

        forestryTools.postPointsByDimensionRandom(
            inputFeatures=self.lyrTracts,
            xGridSpacing=6,
            yGridSpacing=6,
            outputFeatureClass=os.path.join(self.gdbSrtch, 'random6by6chains'),
            inputUnitMeasure='Chains'
        )

    def test_regular150by150_defaultUnits(self):

        forestryTools.postPointsByDimension(
            inputFeatures=self.lyrTracts,
            xGridSpacing=150,
            yGridSpacing=150,
            outputFeatureClass=os.path.join(self.gdbSrtch, 'regular150by150default')
        )

    def test_regular6by6_chains(self):

        forestryTools.postPointsByDimension(
            inputFeatures=self.lyrTracts,
            xGridSpacing=6,
            yGridSpacing=6,
            outputFeatureClass=os.path.join(self.gdbSrtch, 'regular6by6chains'),
            inputUnitMeasure='Chains'
        )


text:
package com.cloud.utils.storage;

import com.cloud.utils.NumbersUtil;

import java.io.IOException;
import java.io.InputStream;

public final class QCOW2Utils {
    private static final int VIRTUALSIZE_HEADER_LOCATION = 24;
    private static final int VIRTUALSIZE_HEADER_LENGTH = 8;

    /**
     * Private constructor ->  This utility class cannot be instantiated.
     */
    private QCOW2Utils() {
    }

    /**
     * @return the header location of the virtual size field.
     */
    public static int getVirtualSizeHeaderLocation() {
        return VIRTUALSIZE_HEADER_LOCATION;
    }

    /**
     * @param inputStream The QCOW2 object in stream format.
     * @return The virtual size of the QCOW2 object.
     */
    public static long getVirtualSize(final InputStream inputStream) throws IOException {
        final byte[] bytes = new byte[VIRTUALSIZE_HEADER_LENGTH];

        if (inputStream.skip(VIRTUALSIZE_HEADER_LOCATION) != VIRTUALSIZE_HEADER_LOCATION) {
            throw new IOException("Unable to skip to the virtual size header");
        }

        if (inputStream.read(bytes) != VIRTUALSIZE_HEADER_LENGTH) {
            throw new IOException("Unable to properly read the size");
        }

        return NumbersUtil.bytesToLong(bytes);
    }
}


text:
package org.broadinstitute.dsde.rawls.model

import java.time.OffsetDateTime

import spray.json.RootJsonFormat

case class MethodRepoMethod(
                   methodNamespace: String,
                   methodName: String,
                   methodVersion: Int
                   )

case class MethodConfiguration(
                   namespace: String,
                   name: String,
                   rootEntityType: Option[String] = None,
                   prerequisites: Map[String, AttributeString],
                   inputs: Map[String, AttributeString],
                   outputs: Map[String, AttributeString],
                   methodRepoMethod: MethodRepoMethod,
                   methodConfigVersion: Int = 1,
                   deleted: Boolean = false,
                   deletedDate: Option[OffsetDateTime] = None
                   ) {
}

sealed trait Attribute
sealed trait AttributeListElementable extends Attribute //terrible name for "this type can legally go in an attribute list"
sealed trait AttributeValue extends AttributeListElementable
case class AttributeString(value: String) extends AttributeValue

class WorkspaceJsonSupport extends JsonSupport {
  import spray.json.DefaultJsonProtocol._

  implicit val MethodStoreMethodFormat: RootJsonFormat[MethodRepoMethod] = jsonFormat3(MethodRepoMethod)

  implicit val MethodConfigurationFormat: RootJsonFormat[MethodConfiguration] = jsonFormat10(MethodConfiguration)
}

object WorkspaceJsonSupport extends WorkspaceJsonSupport


text:
package org.apache.kylin.rest.util;

import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.engine.mr.CubingJob;
import org.apache.kylin.job.JobInstance;
import org.apache.kylin.job.execution.AbstractExecutable;
import org.apache.kylin.job.execution.CheckpointExecutable;
import org.apache.kylin.job.execution.ExecutableManager;
import org.apache.kylin.metadata.project.ProjectInstance;
import org.apache.kylin.metadata.project.ProjectManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

@Component("aclEvaluate")
public class AclEvaluate {
    @Autowired
    private AclUtil aclUtil;

    private ProjectInstance getProjectInstance(String projectName) {
        return ProjectManager.getInstance(KylinConfig.getInstanceFromEnv()).getProject(projectName);
    }

    private ProjectInstance getProjectInstanceByCubeName(String cube) {
        CubeInstance cubeInstance = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()).getCube(cube);
        return cubeInstance.getProjectInstance();
    }

    private ProjectInstance getProjectByJob(JobInstance job) {
        AbstractExecutable executable = ExecutableManager.getInstance(KylinConfig.getInstanceFromEnv())
                .getJob(job.getUuid());
        String projectName = null;
        if (executable instanceof CubingJob) {
            projectName = ((CubingJob) executable).getProjectName();
        } else if (executable instanceof CheckpointExecutable) {
            projectName = ((CheckpointExecutable) executable).getProjectName();
        } else {
            return null;
        }
        return getProjectInstance(projectName);
    }

    public void checkProjectAdminPermission(ProjectInstance projectInstance) {
        aclUtil.hasProjectAdminPermission(projectInstance);
    }

    //for raw project
    public void checkProjectReadPermission(ProjectInstance projectInstance) {
        aclUtil.hasProjectReadPermission(projectInstance);
    }

    public void checkProjectWritePermission(ProjectInstance projectInstance) {
        aclUtil.hasProjectWritePermission(projectInstance);
    }

    public void checkProjectOperationPermission(ProjectInstance projectInstance) {
        aclUtil.hasProjectOperationPermission(projectInstance);
    }

    public void checkProjectAdminPermission(String projectName) {
        ProjectInstance projectInstance = getProjectInstance(projectName);
        checkProjectAdminPermission(projectInstance);
    }

    //for raw project
    public void checkProjectReadPermission(String projectName) {
        ProjectInstance projectInstance = getProjectInstance(projectName);
        checkProjectReadPermission(projectInstance);
    }

    public void checkProjectWritePermission(String projectName) {
        ProjectInstance projectInstance = getProjectInstance(projectName);
        checkProjectWritePermission(projectInstance);
    }

    public void checkProjectOperationPermission(String projectName) {
        ProjectInstance projectInstance = getProjectInstance(projectName);
        checkProjectOperationPermission(projectInstance);
    }

    //for cube acl entity
    public void checkProjectReadPermission(CubeInstance cube) {
        aclUtil.hasProjectReadPermission(cube.getProjectInstance());
    }

    public void checkProjectWritePermission(CubeInstance cube) {
        aclUtil.hasProjectWritePermission(cube.getProjectInstance());
    }

    public void checkProjectOperationPermission(CubeInstance cube) {
        aclUtil.hasProjectOperationPermission(cube.getProjectInstance());
    }

    //for job acl entity
    public void checkProjectReadPermission(JobInstance job) {
        aclUtil.hasProjectReadPermission(getProjectByJob(job));
    }

    public void checkProjectWritePermission(JobInstance job) {
        aclUtil.hasProjectWritePermission(getProjectByJob(job));
    }

    public void checkProjectOperationPermission(JobInstance job) {
        aclUtil.hasProjectOperationPermission(getProjectByJob(job));
    }

    // ACL util's method, so that you can use AclEvaluate
    public String getCurrentUserName() {
        return aclUtil.getCurrentUserName();
    }

    public boolean hasCubeReadPermission(CubeInstance cube) {
        return hasProjectReadPermission(cube.getProjectInstance());
    }

    public boolean hasProjectReadPermission(ProjectInstance project) {
        boolean _hasProjectReadPermission = false;
        try {
            _hasProjectReadPermission = aclUtil.hasProjectReadPermission(project);
        } catch (AccessDeniedException e) {
            //ignore to continue
        }
        return _hasProjectReadPermission;
    }

    public boolean hasProjectOperationPermission(ProjectInstance project) {
        boolean _hasProjectOperationPermission = false;
        try {
            _hasProjectOperationPermission = aclUtil.hasProjectOperationPermission(project);
        } catch (AccessDeniedException e) {
            //ignore to continue
        }
        return _hasProjectOperationPermission;
    }

    public boolean hasProjectWritePermission(ProjectInstance project) {
        boolean _hasProjectWritePermission = false;
        try {
            _hasProjectWritePermission = aclUtil.hasProjectWritePermission(project);
        } catch (AccessDeniedException e) {
            //ignore to continue
        }
        return _hasProjectWritePermission;
    }

    public boolean hasProjectAdminPermission(ProjectInstance project) {
        boolean _hasProjectAdminPermission = false;
        try {
            _hasProjectAdminPermission = aclUtil.hasProjectAdminPermission(project);
        } catch (AccessDeniedException e) {
            //ignore to continue
        }
        return _hasProjectAdminPermission;
    }

    public void checkIsGlobalAdmin() {
        aclUtil.checkIsGlobalAdmin();
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Project',
            fields=[
                ('id', models.AutoField(primary_key=True,
                                        verbose_name='ID', serialize=False, auto_created=True)),
                ('project_title', models.CharField(max_length=30)),
            ],
        ),
        migrations.CreateModel(
            name='QuestionAndAnswer',
            fields=[
                ('id', models.AutoField(primary_key=True,
                                        verbose_name='ID', serialize=False, auto_created=True)),
                ('question_text', models.CharField(max_length=120)),
                ('answer_text', models.CharField(max_length=120)),
            ],
        ),
    ]


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

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

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

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

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

    <parent>
        <groupId>org.apache.camel</groupId>
        <artifactId>components</artifactId>
        <version>3.6.0-SNAPSHOT</version>
    </parent>

    <artifactId>camel-geocoder</artifactId>
    <packaging>jar</packaging>
    <name>Camel :: Geocoder</name>
    <description>Camel GeoCoder support</description>

    <properties>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-support</artifactId>
        </dependency>
        <!-- Java client library for Google Maps API Web Services -->
        <dependency>
            <groupId>com.google.maps</groupId>
            <artifactId>google-maps-services</artifactId>
            <version>${google-maps-services-version}</version>
        </dependency>

        <!-- Client library for JSON responses -->
        <!-- Used with Nominatim -->
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>${json-path-version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!-- testing -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-junit5</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <childDelegation>false</childDelegation>
                    <useFile>true</useFile>
                    <forkedProcessTimeoutInSeconds>300</forkedProcessTimeoutInSeconds>
                    <excludes>
                        <!-- exclude all tests as they require online internet -->
                        <exclude>**/*Test.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>geo-test</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <childDelegation>false</childDelegation>
                            <useFile>true</useFile>
                            <forkedProcessTimeoutInSeconds>300</forkedProcessTimeoutInSeconds>
                            <includes>
                                <include>**/*Test.java</include>
                            </includes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


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

//
// A btree_map<> implements the STL unique sorted associative container
// interface and the pair associative container interface (a.k.a map<>) using a
// btree. A btree_multimap<> implements the STL multiple sorted associative
// container interface and the pair associative container interface (a.k.a
// multimap<>) using a btree. See btree.h for details of the btree
// implementation and caveats.
//

#ifndef S2_UTIL_GTL_BTREE_MAP_H_
#define S2_UTIL_GTL_BTREE_MAP_H_

#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>

#include "s2/util/gtl/btree.h"            // IWYU pragma: export
#include "s2/util/gtl/btree_container.h"  // IWYU pragma: export

namespace gtl {

template <typename Key, typename Value, typename Compare = std::less<Key>,
          typename Alloc = std::allocator<std::pair<const Key, Value>>,
          int TargetNodeSize = 256>
class btree_map
    : public internal_btree::btree_map_container<
          internal_btree::btree<internal_btree::map_params<
              Key, Value, Compare, Alloc, TargetNodeSize, /*Multi=*/false>>> {
  using Base = typename btree_map::btree_map_container;

 public:
  btree_map() {}
  using Base::Base;
};

template <typename K, typename V, typename C, typename A, int T>
void swap(btree_map<K, V, C, A, T> &x, btree_map<K, V, C, A, T> &y) {
  return x.swap(y);
}

template <typename Key, typename Value, typename Compare = std::less<Key>,
          typename Alloc = std::allocator<std::pair<const Key, Value>>,
          int TargetNodeSize = 256>
class btree_multimap
    : public internal_btree::btree_multimap_container<
          internal_btree::btree<internal_btree::map_params<
              Key, Value, Compare, Alloc, TargetNodeSize, /*Multi=*/true>>> {
  using Base = typename btree_multimap::btree_multimap_container;

 public:
  btree_multimap() {}
  using Base::Base;
};

template <typename K, typename V, typename C, typename A, int T>
void swap(btree_multimap<K, V, C, A, T> &x, btree_multimap<K, V, C, A, T> &y) {
  return x.swap(y);
}

}  // namespace gtl

#endif  // S2_UTIL_GTL_BTREE_MAP_H_


text:
@interface ZLPeoplePickerViewController () <
    ABPeoplePickerNavigationControllerDelegate, ABPersonViewControllerDelegate,
    ABNewPersonViewControllerDelegate, ABUnknownPersonViewControllerDelegate,
    UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating>
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) ZLResultsTableViewController *resultsTableViewController;

// for state restoration
@property BOOL searchControllerWasActive;
@property BOOL searchControllerSearchFieldWasFirstResponder;

@end

@implementation ZLPeoplePickerViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    _numberOfSelectedPeople = ZLNumSelectionNone;
    self.fieldMask = ZLContactFieldDefault;
    self.allowAddPeople = YES;
}

+ (void)initializeAddressBook {
    [[ZLAddressBook sharedInstance] loadContacts:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.resultsTableViewController = [[ZLResultsTableViewController alloc] init];
    self.searchController = [[UISearchController alloc]
        initWithSearchResultsController:self.resultsTableViewController];
    self.searchController.searchResultsUpdater = self;
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;

    // we want to be the delegate for our filtered table so
    // didSelectRowAtIndexPath is called for both tables
    self.resultsTableViewController.tableView.delegate = self;
    self.searchController.delegate = self;
    //    self.searchController.dimsBackgroundDuringPresentation = NO; //
    //    default is YES
    self.searchController.searchBar.delegate =
        self; // so we can monitor text changes + others

    // Search is now just presenting a view controller. As such, normal view
    // controller
    // presentation semantics apply. Namely that presentation will walk up the
    // view controller
    // hierarchy until it finds the root view controller or one that defines a
    // presentation context.
    //
    self.definesPresentationContext =
        YES; // know where you want UISearchController to be displayed

    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:self.refreshControl];
    [self.refreshControl addTarget:self
                            action:@selector(refreshControlAction:)
                  forControlEvents:UIControlEventValueChanged];
    [self refreshControlAction:self.refreshControl];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    self.navigationItem.title = self.title.length > 0 ? self.title : NSLocalizedString(@"Contacts", nil);

    if (self.allowAddPeople) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                  target:self
                                                  action:@selector(showNewPersonViewController)];
    }

    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(addressBookDidChangeNotification:)
               name:ZLAddressBookDidChangeNotification
             object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // restore the searchController's active state
    if (self.searchControllerWasActive) {
        self.searchController.active = self.searchControllerWasActive;
        _searchControllerWasActive = NO;

        if (self.searchControllerSearchFieldWasFirstResponder) {
            [self.searchController.searchBar becomeFirstResponder];
            _searchControllerSearchFieldWasFirstResponder = NO;
        }
    }
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    if (![parent isEqual:self.parentViewController]) {
        [self invokeReturnDelegate];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]
        removeObserver:self
                  name:ZLAddressBookDidChangeNotification
                object:nil];
}

#pragma mark - Action
+ (instancetype)presentPeoplePickerViewControllerForParentViewController:
                    (nullable __kindof id<ZLPeoplePickerViewControllerDelegate>)parentViewController {
    UINavigationController *navController =
        [[UINavigationController alloc] init];
    ZLPeoplePickerViewController *peoplePicker =
        [[ZLPeoplePickerViewController alloc] init];
    [navController pushViewController:peoplePicker animated:NO];
    peoplePicker.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
        initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                             target:peoplePicker
                             action:@selector(doneButtonAction:)];
    peoplePicker.delegate = parentViewController;
    [parentViewController presentViewController:navController
                                       animated:YES
                                     completion:nil];
    return peoplePicker;
}

- (void)doneButtonAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    [self invokeReturnDelegate];
}

- (void)refreshControlAction:(UIRefreshControl *)aRefreshControl {
    [aRefreshControl beginRefreshing];
    [self reloadData:^(BOOL succeeded, NSError *error) {
        [aRefreshControl endRefreshing];
    }];
}

- (void)addressBookDidChangeNotification:(NSNotification *)note {
    [self performSelector:@selector(reloadData) withObject:nil];
}

- (void)reloadData {
    [self reloadData:nil];
}

- (void)reloadData:(void (^)(BOOL succeeded, NSError *error))completionBlock {
    __weak __typeof(self) weakSelf = self;
    if ([ZLAddressBook sharedInstance].contacts.count > 0) {
        [weakSelf
            setPartitionedContactsWithContacts:[ZLAddressBook sharedInstance]
                                                   .contacts];
        [weakSelf.tableView reloadData];
    }
    [[ZLAddressBook sharedInstance]
        loadContacts:^(BOOL succeeded, NSError *error) {
            if (!error) {
                [weakSelf setPartitionedContactsWithContacts:
                              [ZLAddressBook sharedInstance].contacts];
                [weakSelf.tableView reloadData];
                if (completionBlock) {
                    completionBlock(YES, nil);
                }
            } else {
                if (completionBlock) {
                    completionBlock(NO, nil);
                }
            }
        }];
}

#pragma mark - UISearchBarDelegate

- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar {
    [aSearchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)aSearchBar {
    [aSearchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar {
    [aSearchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    APContact *contact = [self contactForRowAtIndexPath:indexPath];

    if (![tableView isEqual:self.tableView]) {
        contact = [(ZLResultsTableViewController *)
                       self.searchController.searchResultsController
            contactForRowAtIndexPath:indexPath];
    }

    if (![self shouldEnableCellforContact:contact]) {
        return;
    }

    if (self.delegate &&
        [self.delegate
            respondsToSelector:@selector(peoplePickerViewController:
                                                    didSelectPerson:)]) {
        [self.delegate peoplePickerViewController:self
                                  didSelectPerson:contact.recordID];
    }

    if ([self.selectedPeople containsObject:contact.recordID]) {
        [self.selectedPeople removeObject:contact.recordID];
    } else {
        if (self.selectedPeople.count < self.numberOfSelectedPeople) {
            [self.selectedPeople addObject:contact.recordID];
        }
    }

    //    NSLog(@"heree");

    [tableView reloadData];
    [self.tableView reloadData];
}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:
            (UISearchController *)searchController {
    // update the filtered array based on the search text
    NSString *searchText = searchController.searchBar.text;
    NSMutableArray *searchResults = [[self.partitionedContacts
        valueForKeyPath:@"@unionOfArrays.self"] mutableCopy];

    // strip out all the leading and trailing spaces
    NSString *strippedStr =
        [searchText stringByTrimmingCharactersInSet:
                        [NSCharacterSet whitespaceCharacterSet]];

    // break up the search terms (separated by spaces)
    NSArray *searchItems = nil;
    if (strippedStr.length > 0) {
        searchItems = [strippedStr componentsSeparatedByString:@" "];
    }
    // build all the "AND" expressions for each value in the searchString
    NSMutableArray *andMatchPredicates = [NSMutableArray array];

    for (NSString *searchString in searchItems) {
        NSMutableArray *searchItemsPredicate = [NSMutableArray array];

        // TODO: match phone number matching

        // name field matching
        NSPredicate *finalPredicate = [NSPredicate
            predicateWithFormat:@"compositeName CONTAINS[c] %@", searchString];
        [searchItemsPredicate addObject:finalPredicate];

        NSPredicate *predicate =
            [NSPredicate predicateWithFormat:@"ANY SELF.emails.address CONTAINS[c] %@",
                                             searchString];
        [searchItemsPredicate addObject:predicate];

        predicate = [NSPredicate
            predicateWithFormat:@"ANY SELF.addresses.street CONTAINS[c] %@",
                                searchString];
        [searchItemsPredicate addObject:predicate];
        predicate = [NSPredicate
            predicateWithFormat:@"ANY SELF.addresses.city CONTAINS[c] %@",
                                searchString];
        [searchItemsPredicate addObject:predicate];
        predicate = [NSPredicate
            predicateWithFormat:@"ANY SELF.addresses.zip CONTAINS[c] %@",
                                searchString];
        [searchItemsPredicate addObject:predicate];
        predicate = [NSPredicate
            predicateWithFormat:@"ANY SELF.addresses.country CONTAINS[c] %@",
                                searchString];
        [searchItemsPredicate addObject:predicate];
        predicate = [NSPredicate
            predicateWithFormat:
                @"ANY SELF.addresses.countryCode CONTAINS[c] %@", searchString];
        [searchItemsPredicate addObject:predicate];

        //        NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc]
        //        init];
        //        [numFormatter setNumberStyle:NSNumberFormatterNoStyle];
        //        NSNumber *targetNumber = [numFormatter
        //        numberFromString:searchString];
        //        if (targetNumber != nil) {   // searchString may not convert
        //        to a number
        //            predicate = [NSPredicate predicateWithFormat:@"ANY
        //            SELF.sanitizePhones CONTAINS[c] %@", searchString];
        //            [searchItemsPredicate addObject:predicate];
        //        }

        // at this OR predicate to our master AND predicate
        NSCompoundPredicate *orMatchPredicates =
            (NSCompoundPredicate *)[NSCompoundPredicate
                orPredicateWithSubpredicates:searchItemsPredicate];
        [andMatchPredicates addObject:orMatchPredicates];
    }

    NSCompoundPredicate *finalCompoundPredicate = nil;

    // match up the fields of the Product object
    finalCompoundPredicate = (NSCompoundPredicate *)
        [NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];

    searchResults = [[searchResults
        filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];

    // hand over the filtered results to our search results table
    ZLResultsTableViewController *tableController =
        (ZLResultsTableViewController *)
            self.searchController.searchResultsController;
    tableController.fieldMask = self.fieldMask;
    tableController.selectedPeople = self.selectedPeople;
    [tableController setPartitionedContactsWithContacts:searchResults];
    [tableController.tableView reloadData];
}

#pragma mark - ABAdressBookUI

#pragma mark Create a new person
- (void)showNewPersonViewController {
    ABNewPersonViewController *picker =
        [[ABNewPersonViewController alloc] init];
    picker.newPersonViewDelegate = self;

    UINavigationController *navigation =
        [[UINavigationController alloc] initWithRootViewController:picker];
    [self presentViewController:navigation animated:YES completion:nil];
}
#pragma mark ABNewPersonViewControllerDelegate methods
// Dismisses the new-person view controller.
- (void)newPersonViewController:
            (ABNewPersonViewController *)newPersonViewController
       didCompleteWithNewPerson:(ABRecordRef)person {
    [self dismissViewControllerAnimated:YES completion:NULL];
    if (self.delegate &&
        [self.delegate
         respondsToSelector:@selector(newPersonViewControllerDidCompleteWithNewPerson:)]) {
            [self.delegate newPersonViewControllerDidCompleteWithNewPerson:person];
         }
}
#pragma mark ABUnknownPersonViewControllerDelegate
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController
                 didResolveToPerson:(ABRecordRef)person {

}
#pragma mark ABPersonViewControllerDelegate
- (BOOL)personViewController:(ABPersonViewController *)personViewController
    shouldPerformDefaultActionForPerson:(ABRecordRef)person
                               property:(ABPropertyID)property
                             identifier:
                                 (ABMultiValueIdentifier)identifierForValue {
    return NO;
}

#pragma mark - ()
- (void)invokeReturnDelegate {
    if (self.delegate &&
        [self.delegate
            respondsToSelector:@selector(peoplePickerViewController:
                                        didReturnWithSelectedPeople:)]) {
        [self.delegate peoplePickerViewController:self
                      didReturnWithSelectedPeople:[self.selectedPeople copy]];
    }
}

@end


text:
@extends('layouts.app')

@section('content')

Dashboard

				Application dashboard.

@stop


text:
const registry = [];

/**
 * Add new component to registry
 * @private
 * @param {*} component
 */
export function addComponentToRegistry(component) {
  registry.push(component);
}

/**
 * Inject property to all components
 * @private
 * @param {*} callback
 */
export function injectPropertyToAllComponents(callback) {
  registry.forEach(callback);
}


text:
from urwid import Filler, Pile, WidgetWrap

from ubuntui.utils import Color, Padding
from ubuntui.widgets.buttons import done_btn
from ubuntui.widgets.hr import HR

class StepsView(WidgetWrap):

    def __init__(self, app, steps, cb=None):
        """ init

        Arguments:
        cb: process step callback
        """
        self.app = app
        self.cb = cb
        self.steps = steps
        self.step_pile = Pile(
            [Padding.center_90(HR()),
             Padding.line_break("")] +
            [Padding.center_90(s) for s in self.steps] +
            [Padding.line_break(""),
             Padding.center_20(self.buttons())]
        )
        super().__init__(Filler(self.step_pile, valign="top"))

    def get_step_widget(self, index):
        return self.step_pile[index + 2]

    @property
    def current_summary_button_index(self):
        """ Returns the pile index where the summary button is located
        """
        return len(self.step_pile.contents) - 1

    def buttons(self):
        buttons = [
            Color.button_primary(
                done_btn(on_press=self.done, label="View Summary"),
                focus_map='button_primary focus')
        ]
        return Pile(buttons)

    def done(self, *args):
        self.cb(None, None, done=True)


text:
package net.java.sip.communicator.impl.gui.main.chat;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.service.contactlist.*;

/**
 * The <tt>MetaContactChatContact</tt> represents a <tt>ChatContact</tt> in a
 * user-to-user chat.
 *
 * @author Yana Stamcheva
 * @author Lubomir Marinov
 */
public class MetaContactChatContact
    extends ChatContact<MetaContact>
{

    /**
     * Creates an instance of <tt>ChatContact</tt> by passing to it the
     * corresponding <tt>MetaContact</tt> and <tt>Contact</tt>.
     *
     * @param metaContact the <tt>MetaContact</tt> encapsulating the given
     * <tt>Contact</tt>
     */
    public MetaContactChatContact(MetaContact metaContact)
    {
        super(metaContact);
    }

    /*
     * Implements ChatContact#getAvatarBytes(). Delegates to metaContact.
     */
    @Override
    public byte[] getAvatarBytes()
    {
        return descriptor.getAvatar();
    }

    /**
     * Returns the contact name.
     *
     * @return the contact name
     */
    @Override
    public String getName()
    {
        String name = descriptor.getDisplayName();

        if (name == null || name.length() < 1)
            name
                = GuiActivator.getResources()
                        .getI18NString("service.gui.UNKNOWN");

        return name;
    }

    /*
     * Implements ChatContact#getUID(). Delegates to MetaContact#getMetaUID()
     * because it's known to be unique.
     */
    @Override
    public String getUID()
    {
        return descriptor.getMetaUID();
    }
}


text:
package org.tmt.addons.rti;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.tmt.addons.rti.throughput.Throughput;
import org.tmt.addons.rti.throughput.ThroughputDataWriter;
import org.tmt.addons.rti.throughput.ThroughputTypeSupport;

import com.persistent.bcsuite.base.PublisherBase;
import com.rti.dds.domain.DomainParticipant;
import com.rti.dds.domain.DomainParticipantFactory;
import com.rti.dds.domain.DomainParticipantQos;
import com.rti.dds.infrastructure.Duration_t;
import com.rti.dds.infrastructure.InstanceHandle_t;
import com.rti.dds.infrastructure.RETCODE_ERROR;
import com.rti.dds.infrastructure.ReliabilityQosPolicyKind;
import com.rti.dds.infrastructure.StatusKind;
import com.rti.dds.publication.DataWriterQos;
import com.rti.dds.publication.PublicationMatchedStatus;
import com.rti.dds.publication.Publisher;
import com.rti.dds.publication.PublisherQos;
import com.rti.dds.topic.Topic;
import com.rti.dds.topic.TopicQos;

public class RTISimplePub extends PublisherBase {

	public static Logger logger = Logger.getLogger(RTISimplePub.class);
	private static DomainParticipantFactory factory;
	private static DomainParticipant participant;
	private Publisher publisher;
	private Topic topic;
//	private StringDataWriter dataWriter;
	private ThroughputDataWriter dataWriter;
	private String topicName;
	private static int effort =0;

	boolean isReliable = false;
	private final Duration_t threeSecond = new Duration_t(3, 0);
	private static int counter = 0;

	 InstanceHandle_t data_instanceHandle = null;

	@Override
	public void init(Map<String, String> attributes) {
		super.init(attributes);
		String strEffort = attributes.get("effort");
		if(strEffort != null){
			effort = Integer.parseInt(strEffort);
		}
		String strReliable = attributes.get("isReliable");
		if (strReliable != null && !strReliable.isEmpty()) {
			isReliable = Boolean.parseBoolean(strReliable);
			System.out.println("Setting Reliability " + isReliable);
		}
		if (factory == null) {
			initFactory();

		}
		if (participant == null) {
			initDomainParticipant();
		}
		initPublisher();
		topicName = attributes.get("topic");
		System.out.println("Topic received "+topicName);
		// Create a topic from the message
		// if(topic ==null)
		createTopic(topicName);
		// Create the datawriter
		createDataWriter();
		System.out.println("Ready to write data.");
		System.out.print("Press CTRL+C to terminate\n\n");
		incrementCounter();
	}

	private synchronized void initFactory() {
		factory = DomainParticipantFactory.get_instance();
	}

	private synchronized void initDomainParticipant() {
		DomainParticipantQos participant_qos = new DomainParticipantQos();
		factory.get_default_participant_qos(participant_qos);
		participant = factory.create_participant(0, // Domain ID = 0
				participant_qos, null, // listener
				StatusKind.STATUS_MASK_NONE);
		  ThroughputTypeSupport.register_type(participant,
                  ThroughputTypeSupport.get_type_name());
		  if (participant == null) {
			  System.out.println("Unable to create domain participant");
			  return;
		  }
	}

	private void initPublisher() {
		PublisherQos publisher_qos = new PublisherQos();
		participant.get_default_publisher_qos(publisher_qos);
		publisher = participant.create_publisher(publisher_qos, null,
				StatusKind.STATUS_MASK_NONE);
	}

	/**
	 * Create a topic from the message generated
	 */
	private void createTopic(String topicName) {
		System.out.println("Creating Topic " + topicName);
		 TopicQos data_topic_qos = new TopicQos();
		participant.get_default_topic_qos(data_topic_qos );
		Topic tempTopic = null;
		try {
			tempTopic = participant.create_topic(topicName,
                    ThroughputTypeSupport.get_type_name(), data_topic_qos,
                    null, StatusKind.STATUS_MASK_NONE);
		} catch (RETCODE_ERROR error) {
			System.out.println("Cannot Create topic. Topic already exists ");
		}
		if (tempTopic == null) {
			logger.debug("Topic already exists. Getting handle to topic");
			topic = participant.find_topic(topicName, threeSecond);
			logger.debug("Discovered Topic " + topic.get_name());
			System.out.println("Discovered Topic " + topic.get_name());
		} else {
			topic = tempTopic;
		}
	}

	private void createDataWriter() {
		logger.debug("Creating the Data Writer");
		// Create the data writer using the default publisher
		DataWriterQos datawriter_qos = new DataWriterQos();
		publisher.get_default_datawriter_qos(datawriter_qos);
		if (isReliable) {
			datawriter_qos.reliability.kind = ReliabilityQosPolicyKind.RELIABLE_RELIABILITY_QOS;
		}
		dataWriter = (ThroughputDataWriter) publisher.create_datawriter(topic,
				datawriter_qos, null, StatusKind.STATUS_MASK_NONE);

		// dataWriter.enable();
		if (dataWriter == null) {
			logger.error("Unable to create data writer\n");
		}
	}

	@Override
	public void cleanup() {
		System.out.println("Exiting...");

		decrementCounter();
		if (counter == 0) {
			System.out
					.println("All threads have finished execution. Shutting down...");
			if (participant != null) {
				participant.delete_contained_entities();
				DomainParticipantFactory.get_instance().delete_participant(
						participant);
			}
		}
	}

	private static synchronized void incrementCounter() {
		counter++;
	}

	private static synchronized void decrementCounter() {
		counter--;
	}

	@Override
	public void sendMessageForThroughput(byte[] message) {
		int len = message.length;
		int exceptionCnt = 0;
		long messageCounter = 0;
		Throughput throughput = new Throughput(message.length);
		throughput.data.addAllByte(message);
		  data_instanceHandle = dataWriter.register_instance(throughput);
		setStartTime(new Date());
		while (canContinue()) {
			try {
//				for (int l = 0; l < 20000 && canContinue; l++) {
					try {
						dataWriter.write(throughput ,
								InstanceHandle_t.HANDLE_NIL);
						messageCounter++;
						addToStatisticsPool(len);
					} catch (RETCODE_ERROR e) {
						if(exceptionCnt <=5){
							e.printStackTrace();
						}
						exceptionCnt++;

					}
//				}
				if (getThinkTimeInMillis() > 0) {
					try {
						Thread.sleep(getThinkTimeInMillis());
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} catch (Exception ex) {
				logger.error("Aborting Publisher -- Recieved exception during sending message. Exception is = "
						+ ex);
			}
		}

		setEndTime(new Date());
		System.out.println("Sleeping for 8 seconds");
		System.out.println("Exceptions " + exceptionCnt);
		try {
			Thread.sleep(8000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} finally {
			markTaskComplete();
		}
	}

	@Override
   public void sendMessageForLatency(byte[] message) {
	   String s = new String(message);
      int len = message.length;
      int exceptionCnt = 0;
      long messageCounter = 0;
      Throughput throughput = new Throughput(message.length);

        data_instanceHandle = dataWriter.register_instance(throughput);
      setStartTime(new Date());
      while (canContinue()) {
         try {
               try {
                  throughput.data.clear();
                  long nanoTime = System.nanoTime();
                  throughput.data.addAllByte((String.valueOf(nanoTime) + ":" +s).getBytes());
                  dataWriter.write(throughput ,
                        InstanceHandle_t.HANDLE_NIL);
                  messageCounter++;
                  addToStatisticsPool(len);
               } catch (RETCODE_ERROR e) {
                  if(exceptionCnt <=5){
                     e.printStackTrace();
                  }
                  exceptionCnt++;
               }
            if (getThinkTimeInMillis() > 0) {
               try {
                  Thread.sleep(getThinkTimeInMillis());
               } catch (InterruptedException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
               }
            }
         } catch (Exception ex) {
            logger.error("Aborting Publisher -- Recieved exception during sending message. Exception is = "
                  + ex);
         }
      }

      setEndTime(new Date());
      System.out.println("Sleeping for 8 seconds");
      System.out.println("Exceptions " + exceptionCnt);
      try {
         Thread.sleep(8000);
      } catch (InterruptedException e1) {
         e1.printStackTrace();
      } finally {
         markTaskComplete();
      }
   }

	@Override
	public boolean isReadyToRun() {
		boolean isReadyToRun = false;
			PublicationMatchedStatus pubMatch = new PublicationMatchedStatus();
			dataWriter.get_publication_matched_status(pubMatch);
			if (pubMatch.current_count > 0) {
				logger.info("Publisher -Subscriber Matched ");
				isReadyToRun = true;
			} else {
				logger.info("Not Matched ");

			}

		return isReadyToRun;
	}

}


text:
using FluentValidation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace BrowseDotNet.Web.Models.Validators
{
    public class RootDirectoryViewModelValidator : AbstractValidator<RootDirectoryViewModel>
    {
        public RootDirectoryViewModelValidator()
        {
            RuleFor(s => s.RootDirectoryPath)
                .Must(IsValidPath)
                .WithMessage("Enter a valid root directory path.");
        }

        private bool IsValidPath(string filePath)
        {
            bool _isValidSolutionPath = new bool();

            try
            {

                if (Directory.Exists(filePath))
                    _isValidSolutionPath = true;
            }
            catch
            {
                _isValidSolutionPath = false;
            }

            return _isValidSolutionPath;
        }
    }
}


text:
(function() {

	var parent = "div[descriptorId=jenkins.plugins.parameter_separator.ParameterSeparatorDefinition]";

	Behaviour.specify(`${parent} textarea`, "autosize", 0, function (e) {
		e.rows = e.textContent.split("\n").length;
	});

	Behaviour.specify(`${parent} a[previewendpoint=/markupFormatter/previewDescription]`, "preview", 200, function (e) {
		var originalOnclick = e.onclick;
		e.onclick = function () {
			var url = "/descriptorByName/jenkins.plugins.parameter_separator.ParameterSeparatorDefinition/preview";
			var params = ["separatorStyle", "sectionHeaderStyle"].map(function(name) {
				var style = encodeURIComponent(document.getElementsByName(`_.${name}`)[0].getValue());
				return `${name}=${style}`;
			});
			e.setAttribute('previewendpoint', `${url}?${params.join("&")}`);
			originalOnclick();
		};
	});

})();


text:
<?php
return [

	/*
	|--------------------------------------------------------------------------
	| Login form Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are used in the login form.
	|
	*/
	'title_sign_in' => "Sign in",
	'email' => "Email Address",
	'password' => "Password",
	'remember' => "Remember me",
	'sign_in' => "Sign in",
	'forgot_your_password' => "Forgot your password?",
];


text:
id: installation
title: BookKeeper installation
---

You can install BookKeeper either by [downloading](#download) a [GZipped](http://www.gzip.org/) tarball package, using the [Docker image](https://hub.docker.com/r/apache/bookkeeper/tags) or [cloning](#clone) the BookKeeper repository.

## Requirements

* [Unix environment](https://www.opengroup.org/membership/forums/platform/unix)
* [Java Development Kit 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) or later

## Download

You can download Apache BookKeeper releases from the [Download page](/releases).

## Clone

To build BookKeeper from source, clone the repository from the [GitHub mirror]({{ site.github_repo }}):

```shell
$ git clone {{ site.github_repo }}
```

## Build using Maven

Once you have the BookKeeper on your local machine, either by [downloading](#download) or [cloning](#clone) it, you can then build BookKeeper from source using Maven:

```shell
$ mvn package
```

Since 4.8.0, bookkeeper introduces `table service`. If you would like to build and tryout table service, you can build it with `stream` profile.

```shell
$ mvn package -Dstream
```

> You can skip tests by adding the `-DskipTests` flag when running `mvn package`.

### Useful Maven commands

Some other useful Maven commands beyond `mvn package`:

| Command                                      | Action                                                                                |
|:---------------------------------------------|:----------------------------------------------------------------------------------------------------------------------|
| `mvn clean`                                  | Removes build artifacts                                                                                |
| `mvn compile`                                | Compiles JAR files from Java sources                                                                                |
| `mvn compile spotbugs:spotbugs`              | Compile using the Maven [SpotBugs](https://github.com/spotbugs/spotbugs-maven-plugin) plugin                          |
| `mvn install`                                | Install the BookKeeper JAR locally in your local Maven cache (usually in the `~/.m2` directory)                       |
| `mvn deploy`                                 | Deploy the BookKeeper JAR to the Maven repo (if you have the proper credentials)                                      |
| `mvn verify`                                 | Performs a wide variety of verification and validation tasks                                                          |
| `mvn apache-rat:check`                       | Run Maven using the [Apache Rat](http://creadur.apache.org/rat/apache-rat-plugin/) plugin                             |
| `mvn compile javadoc:aggregate`              | Build Javadocs locally                                                                                |
| `mvn -am -pl bookkeeper-dist/server package` | Build a server distribution using the Maven [Assembly](http://maven.apache.org/plugins/maven-assembly-plugin/) plugin |

> You can enable `table service` by adding the `-Dstream` flag when running above commands.

## Package directory

The BookKeeper project contains several subfolders that you should be aware of:

| Subfolder                                                                                | Contains                                                  |
|:----------------------------------------------------------------------------------------------|:----------------------------------------------------------|
| [`bookkeeper-server`]({{ site.github_repo }}/tree/master/bookkeeper-server)                   | The BookKeeper server and client                          |
| [`bookkeeper-benchmark`]({{ site.github_repo }}/tree/master/bookkeeper-benchmark)             | A benchmarking suite for measuring BookKeeper performance |
| [`bookkeeper-stats`]({{ site.github_repo }}/tree/master/bookkeeper-stats)                     | A BookKeeper stats library                                |
| [`bookkeeper-stats-providers`]({{ site.github_repo }}/tree/master/bookkeeper-stats-providers) | BookKeeper stats providers                                |


text:
from django.db.models import Q

from wizresource.models import Zone, VM, FirewallRule, PublicIP, Firewall
from wizresource.services import userToTenant

from wizresource.tasks import createFirewallRule, deleteFirewallRule

from utils.common import fakeID

from pprint import pprint

def lists_firewallrule(user, firewallid, pageIndex=0, pageSize=20):
    tenant = userToTenant(user)

    firewall = Firewall.objects.filter(fakeid=firewallid)
    if not firewall:
        return {'status': False, 'message': '错误的id'}
    firewall = firewall.get()

    filters = Q(tenantid=tenant) & ~Q(status='Deleted') &Q(firewallid=firewall)

    if pageSize:
        (lists, total, page, pages) = FirewallRule.objects.pages(pageIndex, pageSize, filters)

        result = {
            'pageIndex': pageIndex,
            'pageSize': pageSize,
            'total': total,
            'pages': pages,
            'lists': FirewallRule.jsonable(lists)
        }
    else:
        lists = FirewallRule.objects.filter(filters)
        result = {
            'lists': FirewallRule.jsonable(lists)
        }
    return result

def edit_firewallrule(fakeid, firewallrulename):
    firewallrule = FirewallRule.objects.filter(fakeid=fakeid)
    if not firewallrule:
        return {'status': False, 'message': '错误的id'}
    firewallrule = firewallrule.get()
    if not firewallrule:
        return {'status': False, 'message': 'firewallrule不能为空'}

    firewallrule.firewallrulename = firewallrulename
    firewallrule.save()
    return {'status': True}

def create_firewallrule(user, firewallid, firewallrulename, sourcecidr,
    protocol, beginport, endport, icmptype, icmpcode ):

    tenant = userToTenant(user)
    fakeid = fakeID('firewallrule')

    firewall = Firewall.objects.filter(Q(tenantid=tenant, fakeid=firewallid))
    if not firewall:
        return {'status': False, 'message': 'id error'}
    firewall = firewall.get()

    if protocol == 0 or protocol == 1:
        firewallrule = FirewallRule(tenantid=tenant,
                    fakeid=fakeid,
                    firewallid=firewall,
                    firewallrulename=firewallrulename if firewallrulename else fakeid,
                    sourceCIDR=sourcecidr,
                    protocol=protocol,
                    beginport=int(beginport),
                    endport=int(endport),
                    )

    else:
        firewallrule = FirewallRule(tenantid=tenant,
                    fakeid=fakeid,
                    firewallid=firewall,
                    firewallrulename=firewallrulename if firewallrulename else fakeid,
                    sourceCIDR=sourcecidr,
                    protocol=protocol,
                    icmptype=int(icmptype),
                    icmpcode=int(icmpcode),
                    )
    firewallrule.save()

    jobid = createFirewallRule.delay(firewallrule)

    return {'jobid': jobid.id, 'status': True}

def delete_firewallrule(fakeid):

    firewallrule = FirewallRule.objects.filter(fakeid=fakeid)
    if not firewallrule:
        return {'status': False, 'message': 'id error'}
    firewallrule = firewallrule.get()

    if firewallrule.enable == 1:
        return {'status': False, 'message': 'publicip is updateing, can not be operated'}

    jobid = deleteFirewallRule.delay(firewallrule)
    return {'jobid': jobid.id, 'status': True}

def lists_firewall(user, pageIndex=0, pageSize=20):
    tenant = userToTenant(user)

    filters = Q(tenantid=tenant) & ~Q(status='Deleted')

    if pageSize:
        (lists, total, page, pages) = Firewall.objects.pages(pageIndex, pageSize, filters)

        result = {
            'pageIndex': pageIndex,
            'pageSize': pageSize,
            'total': total,
            'pages': pages,
            'lists': Firewall.jsonable(lists)
        }
    else:
        lists = Firewall.objects.filter(filters)
        result = {
            'lists': Firewall.jsonable(lists)
        }
    return result

def detail_firewall(user, fakeid):

    tenant = userToTenant(user)
    firewall = Firewall.objects.filter(Q(tenantid=tenant, fakeid=fakeid))
    if not firewall:
        return {'status': False, 'message': 'id error'}
    firewall = firewall.get()
    result = {
        'status': True,
        'detail': {
            'fakeid': firewall.fakeid,
            'firewallname':firewall.firewallname,
            'firewalltype':firewall.firewalltype,
            'firewalltypeShow':firewall.get_firewalltype_display(),
            'loadbalancerid':firewall.loadbalancerid.fakeid if firewall.loadbalancerid else '',
            'publicipid':firewall.publicipid.fakeid if firewall.publicipid else '',
            'status': firewall.status,
            'enableShow': firewall.get_enable_display(),
            'enable': firewall.enable,
            'createtime': firewall.createtime.strftime("%Y-%m-%d %H:%M:%S")
        }
    }

    return result

def edit_firewall(fakeid, firewallname):
    firewall = Firewall.objects.filter(fakeid=fakeid)
    if not firewall:
        return {'status': False, 'message': '错误的id'}
    firewall = firewall.get()
    if not firewall:
        return {'status': False, 'message': 'firewallrule不能为空'}

    firewall.firewallname = firewallname
    firewall.save()
    return {'status': True}


text:
'use strict';

var mongoose = require('mongoose'),
    uuid = require('node-uuid'),
    validator = require('validator'),
    guestName = require('../utilities/guest-name.js');

var SessionModel = mongoose.model('Session');

/**
 * A traditional Node.js "errorback" function.
 * @callback nodeCallback
 */

/**
 * Updates a specified session, then executes a specified callback.
 * @param {Object} query            - A Mongoose query statement object.
 * @param {Object} update           - A Mongoose update statement object.
 * @param {Object} options          - A Mongoose options object.
 * @param {nodeCallback} callback   - A callback function to execute.
 * @readonly
 */
var updateSession = function(query, update, options, callback) {
    SessionModel.findOneAndUpdate(query, update, options).populate('user').lean().exec(function(error, session) {
        if (error) {
            if (callback && typeof callback === 'function') {
                return callback(error);
            }
        }

        if (callback && typeof callback === 'function') {
            return callback(null, session);
        }
    });
};

/**
 * Finds or creates a session if it does not exist, updates the expiration (last accessed)
 * date, and executes a given callback with the updated session information.
 * @param {string} session_id       - The session id to update.
 * @param {nodeCallback} callback   - A callback function to execute.
 * @readonly
 */
exports.start = function(session_id, callback) {
    if (!validator.isUUID(session_id, 4)) {
        session_id = uuid.v4();
    }

    var query = {
        id: String(session_id)
    };

    var update = {
        expires: new Date()
    };

    var options = {
        new: true,
        upsert: true
    };

    return updateSession(query, update, options, callback);
};

/**
 * Creates a new session from a given session, binding user information to the new
 * session as appropriate. Executes a given callback with the updaed session information.
 * @param {string} session_id       - The local socket session object.
 * @param {Object} user             - A document representing a user to bind to this session.
 *                                    Set null to log the session out.
 * @param {nodeCallback} callback   - A callback function to execute.
 * @readonly
 */
exports.regenerate = function(session_id, user, callback) {
    var query = {
        id: String(session_id)
    };

    var update = {
        id: uuid.v4(),
        expires: new Date()
    };

    var options = {
        new: true
    };

    if (user) {
        update.user = user._id;
        update.upsert = true;
    }
    else {
        update.user = undefined;
    }

    return updateSession(query, update, options, callback);
};

/**
 * Generates a guest name from the provided session id.
 * @param {string} session_id - A session id.
 * @returns {string} - A guest name generated from the socket session object.
 * @readonly
 */
exports.guestName = function(session_id) {
    return guestName.generate(session_id);
};


text:
const React = require('react');

module.exports = class extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    var userIsOnFirstStep = this.props.activeStep === 0,
        userIsOnLastStep = this.props.activeStep + 1 === this.props.steps.length;

    return (
      <div className="navButtons">

        {!userIsOnFirstStep & !userIsOnLastStep ?
          <input type="button" value="Tilbage" className="btn btn-default prevButton" onClick={this.props.prevFunc} disabled={this.props.stepping} />
          : null
        }

        {!userIsOnLastStep ?
          <input type="button" value="Næste" className="btn btn-default nextButton pull-right" onClick={this.props.nextFunc} disabled={this.props.stepping} />
          :null
        }
      </div>
    );
  }
}


text:
.class public interface abstract Landroid/net/wifi/WifiEnterpriseConfig$SupplicantLoader;
.super Ljava/lang/Object;
.source "WifiEnterpriseConfig.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/WifiEnterpriseConfig;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "SupplicantLoader"
.end annotation

# virtual methods
.method public abstract loadValue(Ljava/lang/String;)Ljava/lang/String;
.end method