text:
using std::set;
using std::vector;

namespace browser_sync {

using sessions::OrderedCommitSet;
using sessions::SyncSession;
using sessions::StatusController;

GetCommitIdsCommand::GetCommitIdsCommand(int commit_batch_size)
    : requested_commit_batch_size_(commit_batch_size) {}

GetCommitIdsCommand::~GetCommitIdsCommand() {}

SyncerError GetCommitIdsCommand::ExecuteImpl(SyncSession* session) {
  // Gather the full set of unsynced items and store it in the session. They
  // are not in the correct order for commit.
  std::set<int64> ready_unsynced_set;
  syncable::Directory::UnsyncedMetaHandles all_unsynced_handles;
  SyncerUtil::GetUnsyncedEntries(session->write_transaction(),
                                 &all_unsynced_handles);

  syncable::ModelTypeSet encrypted_types;
  bool passphrase_missing = false;
  Cryptographer* cryptographer =
      session->context()->directory_manager()->GetCryptographer(
          session->write_transaction());
  if (cryptographer) {
    encrypted_types = cryptographer->GetEncryptedTypes();
    passphrase_missing = cryptographer->has_pending_keys();
  };

  const syncable::ModelTypeSet throttled_types =
       session->context()->GetThrottledTypes();
  // We filter out all unready entries from the set of unsynced handles. This
  // new set of ready and unsynced items (which excludes throttled items as
  // well) is then what we use to determine what is a candidate for commit.
  FilterUnreadyEntries(session->write_transaction(),
                       throttled_types,
                       encrypted_types,
                       passphrase_missing,
                       all_unsynced_handles,
                       &ready_unsynced_set);

  BuildCommitIds(session->write_transaction(),
                 session->routing_info(),
                 ready_unsynced_set);

  StatusController* status = session->mutable_status_controller();
  syncable::Directory::UnsyncedMetaHandles ready_unsynced_vector(
      ready_unsynced_set.begin(), ready_unsynced_set.end());
  status->set_unsynced_handles(ready_unsynced_vector);
  const vector<syncable::Id>& verified_commit_ids =
      ordered_commit_set_->GetAllCommitIds();

  for (size_t i = 0; i < verified_commit_ids.size(); i++)
    DVLOG(1) << "Debug commit batch result:" << verified_commit_ids[i];

  status->set_commit_set(*ordered_commit_set_.get());
  return SYNCER_OK;
}

namespace {

bool IsEntryInConflict(const syncable::Entry& entry) {
  if (entry.Get(syncable::IS_UNSYNCED) &&
      entry.Get(syncable::SERVER_VERSION) > 0 &&
      (entry.Get(syncable::SERVER_VERSION) >
       entry.Get(syncable::BASE_VERSION))) {
    // The local and server versions don't match. The item must be in
    // conflict, so there's no point in attempting to commit.
    DCHECK(entry.Get(syncable::IS_UNAPPLIED_UPDATE));
    DVLOG(1) << "Excluding entry from commit due to version mismatch "
             << entry;
    return true;
  }
  return false;
}

// An entry is not considered ready for commit if any are true:
// 1. It's in conflict.
// 2. It requires encryption (either the type is encrypted but a passphrase
//    is missing from the cryptographer, or the entry itself wasn't properly
//    encrypted).
// 3. It's type is currently throttled.
// 4. It's a delete but has not been committed.
bool IsEntryReadyForCommit(syncable::ModelTypeSet throttled_types,
                           syncable::ModelTypeSet encrypted_types,
                           bool passphrase_missing,
                           const syncable::Entry& entry) {
  DCHECK(entry.Get(syncable::IS_UNSYNCED));
  if (IsEntryInConflict(entry))
    return false;

  const syncable::ModelType type = entry.GetModelType();
  // We special case the nigori node because even though it is considered an
  // "encrypted type", not all nigori node changes require valid encryption
  // (ex: sync_tabs).
  if ((type != syncable::NIGORI) &&
      encrypted_types.Has(type) &&
      (passphrase_missing ||
       syncable::EntryNeedsEncryption(encrypted_types, entry))) {
    // This entry requires encryption but is not properly encrypted (possibly
    // due to the cryptographer not being initialized or the user hasn't
    // provided the most recent passphrase).
    DVLOG(1) << "Excluding entry from commit due to lack of encryption "
             << entry;
    return false;
  }

  // Look at the throttled types.
  if (throttled_types.Has(type))
    return false;

  // Drop deleted uncommitted entries.
  if (entry.Get(syncable::IS_DEL) && !entry.Get(syncable::ID).ServerKnows()) {
    // TODO(zea): These will remain unsynced indefinitely. This is harmless,
    // but we should clean them up somewhere.
    DVLOG(1) << "Ignoring deleted and uncommitted item." << entry;
    return false;
  }

  // Extra validity checks.
  syncable::Id id = entry.Get(syncable::ID);
  if (id == entry.Get(syncable::PARENT_ID)) {
    CHECK(id.IsRoot()) << "Non-root item is self parenting." << entry;
    // If the root becomes unsynced it can cause us problems.
    NOTREACHED() << "Root item became unsynced " << entry;
    return false;
  }

  if (entry.IsRoot()) {
    NOTREACHED() << "Permanent item became unsynced " << entry;
    return false;
  }

  DVLOG(2) << "Entry is ready for commit: " << entry;
  return true;
}

}  // namespace

void GetCommitIdsCommand::FilterUnreadyEntries(
    syncable::BaseTransaction* trans,
    syncable::ModelTypeSet throttled_types,
    syncable::ModelTypeSet encrypted_types,
    bool passphrase_missing,
    const syncable::Directory::UnsyncedMetaHandles& unsynced_handles,
    std::set<int64>* ready_unsynced_set) {
  for (syncable::Directory::UnsyncedMetaHandles::const_iterator iter =
           unsynced_handles.begin(); iter != unsynced_handles.end(); ++iter) {
    syncable::Entry entry(trans, syncable::GET_BY_HANDLE, *iter);
    if (IsEntryReadyForCommit(throttled_types,
                              encrypted_types,
                              passphrase_missing,
                              entry)) {
      ready_unsynced_set->insert(*iter);
    }
  }
}

bool GetCommitIdsCommand::AddUncommittedParentsAndTheirPredecessors(
    syncable::BaseTransaction* trans,
    const ModelSafeRoutingInfo& routes,
    const std::set<int64>& ready_unsynced_set,
    const syncable::Entry& item,
    sessions::OrderedCommitSet* result) const {
  OrderedCommitSet item_dependencies(routes);
  syncable::Id parent_id = item.Get(syncable::PARENT_ID);

  // Climb the tree adding entries leaf -> root.
  while (!parent_id.ServerKnows()) {
    syncable::Entry parent(trans, syncable::GET_BY_ID, parent_id);
    CHECK(parent.good()) << "Bad user-only parent in item path.";
    int64 handle = parent.Get(syncable::META_HANDLE);
    if (ordered_commit_set_->HaveCommitItem(handle)) {
      // We've already added this parent (and therefore all of its parents).
      // We can return early.
      break;
    }
    if (!AddItemThenPredecessors(trans, ready_unsynced_set, parent,
                                 &item_dependencies)) {
      // There was a parent/predecessor in conflict. We return without adding
      // anything to |ordered_commit_set_|.
      DVLOG(1) << "Parent or parent's predecessor was in conflict, omitting "
               << item;
      return false;
    }
    parent_id = parent.Get(syncable::PARENT_ID);
  }

  // Reverse what we added to get the correct order.
  result->AppendReverse(item_dependencies);
  return true;
}

bool GetCommitIdsCommand::AddItem(const std::set<int64>& ready_unsynced_set,
                                  const syncable::Entry& item,
                                  OrderedCommitSet* result) const {
  DCHECK(item.Get(syncable::IS_UNSYNCED));
  // An item in conflict means that dependent items (successors and children)
  // cannot be added either.
  if (IsEntryInConflict(item))
    return false;
  int64 item_handle = item.Get(syncable::META_HANDLE);
  if (ready_unsynced_set.count(item_handle) == 0) {
    // It's not in conflict, but not ready for commit. Just return true without
    // adding it to the commit set.
    return true;
  }
  result->AddCommitItem(item_handle, item.Get(syncable::ID),
                        item.GetModelType());
  return true;
}

bool GetCommitIdsCommand::AddItemThenPredecessors(
    syncable::BaseTransaction* trans,
    const std::set<int64>& ready_unsynced_set,
    const syncable::Entry& item,
    OrderedCommitSet* result) const {
  int64 item_handle = item.Get(syncable::META_HANDLE);
  if (ordered_commit_set_->HaveCommitItem(item_handle)) {
    // We've already added this item to the commit set, and so must have
    // already added the predecessors as well.
    return true;
  }
  if (!AddItem(ready_unsynced_set, item, result))
    return false;  // Item is in conflict.
  if (item.Get(syncable::IS_DEL))
    return true;  // Deleted items have no predecessors.

  syncable::Id prev_id = item.Get(syncable::PREV_ID);
  while (!prev_id.IsRoot()) {
    syncable::Entry prev(trans, syncable::GET_BY_ID, prev_id);
    CHECK(prev.good()) << "Bad id when walking predecessors.";
    if (!prev.Get(syncable::IS_UNSYNCED))
      break;
    int64 handle = prev.Get(syncable::META_HANDLE);
    if (ordered_commit_set_->HaveCommitItem(handle)) {
      // We've already added this item to the commit set, and so must have
      // already added the predecessors as well.
      return true;
    }
    if (!AddItem(ready_unsynced_set, prev, result))
      return false;  // Item is in conflict.
    prev_id = prev.Get(syncable::PREV_ID);
  }
  return true;
}

bool GetCommitIdsCommand::AddPredecessorsThenItem(
    syncable::BaseTransaction* trans,
    const ModelSafeRoutingInfo& routes,
    const std::set<int64>& ready_unsynced_set,
    const syncable::Entry& item,
    OrderedCommitSet* result) const {
  OrderedCommitSet item_dependencies(routes);
  if (!AddItemThenPredecessors(trans, ready_unsynced_set, item,
                               &item_dependencies)) {
    // Either the item or its predecessors are in conflict, so don't add any
    // items to the commit set.
    DVLOG(1) << "Predecessor was in conflict, omitting " << item;
    return false;
  }

  // Reverse what we added to get the correct order.
  result->AppendReverse(item_dependencies);
  return true;
}

bool GetCommitIdsCommand::IsCommitBatchFull() const {
  return ordered_commit_set_->Size() >= requested_commit_batch_size_;
}

void GetCommitIdsCommand::AddCreatesAndMoves(
    syncable::WriteTransaction* write_transaction,
    const ModelSafeRoutingInfo& routes,
    const std::set<int64>& ready_unsynced_set) {
  // Add moves and creates, and prepend their uncommitted parents.
  for (std::set<int64>::const_iterator iter = ready_unsynced_set.begin();
       !IsCommitBatchFull() && iter != ready_unsynced_set.end(); ++iter) {
    int64 metahandle = *iter;
    if (ordered_commit_set_->HaveCommitItem(metahandle))
      continue;

    syncable::Entry entry(write_transaction,
                          syncable::GET_BY_HANDLE,
                          metahandle);
    if (!entry.Get(syncable::IS_DEL)) {
      // We only commit an item + its dependencies if it and all its
      // dependencies are not in conflict.
      OrderedCommitSet item_dependencies(routes);
      if (AddUncommittedParentsAndTheirPredecessors(
              write_transaction,
              routes,
              ready_unsynced_set,
              entry,
              &item_dependencies) &&
          AddPredecessorsThenItem(write_transaction,
                                  routes,
                                  ready_unsynced_set,
                                  entry,
                                  &item_dependencies)) {
        ordered_commit_set_->Append(item_dependencies);
      }
    }
  }

  // It's possible that we overcommitted while trying to expand dependent
  // items.  If so, truncate the set down to the allowed size.
  ordered_commit_set_->Truncate(requested_commit_batch_size_);
}

void GetCommitIdsCommand::AddDeletes(
    syncable::WriteTransaction* write_transaction,
    const std::set<int64>& ready_unsynced_set) {
  set<syncable::Id> legal_delete_parents;

  for (std::set<int64>::const_iterator iter = ready_unsynced_set.begin();
       !IsCommitBatchFull() && iter != ready_unsynced_set.end(); ++iter) {
    int64 metahandle = *iter;
    if (ordered_commit_set_->HaveCommitItem(metahandle))
      continue;

    syncable::Entry entry(write_transaction, syncable::GET_BY_HANDLE,
                          metahandle);

    if (entry.Get(syncable::IS_DEL)) {
      syncable::Entry parent(write_transaction, syncable::GET_BY_ID,
                             entry.Get(syncable::PARENT_ID));
      // If the parent is deleted and unsynced, then any children of that
      // parent don't need to be added to the delete queue.
      //
      // Note: the parent could be synced if there was an update deleting a
      // folder when we had a deleted all items in it.
      // We may get more updates, or we may want to delete the entry.
      if (parent.good() &&
          parent.Get(syncable::IS_DEL) &&
          parent.Get(syncable::IS_UNSYNCED)) {
        // However, if an entry is moved, these rules can apply differently.
        //
        // If the entry was moved, then the destination parent was deleted,
        // then we'll miss it in the roll up. We have to add it in manually.
        // TODO(chron): Unit test for move / delete cases:
        // Case 1: Locally moved, then parent deleted
        // Case 2: Server moved, then locally issue recursive delete.
        if (entry.Get(syncable::ID).ServerKnows() &&
            entry.Get(syncable::PARENT_ID) !=
                entry.Get(syncable::SERVER_PARENT_ID)) {
          DVLOG(1) << "Inserting moved and deleted entry, will be missed by "
                   << "delete roll." << entry.Get(syncable::ID);

          ordered_commit_set_->AddCommitItem(metahandle,
              entry.Get(syncable::ID),
              entry.GetModelType());
        }

        // Skip this entry since it's a child of a parent that will be
        // deleted. The server will unroll the delete and delete the
        // child as well.
        continue;
      }

      legal_delete_parents.insert(entry.Get(syncable::PARENT_ID));
    }
  }

  // We could store all the potential entries with a particular parent during
  // the above scan, but instead we rescan here. This is less efficient, but
  // we're dropping memory alloc/dealloc in favor of linear scans of recently
  // examined entries.
  //
  // Scan through the UnsyncedMetaHandles again. If we have a deleted
  // entry, then check if the parent is in legal_delete_parents.
  //
  // Parent being in legal_delete_parents means for the child:
  //   a recursive delete is not currently happening (no recent deletes in same
  //     folder)
  //   parent did expect at least one old deleted child
  //   parent was not deleted
  for (std::set<int64>::const_iterator iter = ready_unsynced_set.begin();
       !IsCommitBatchFull() && iter != ready_unsynced_set.end(); ++iter) {
    int64 metahandle = *iter;
    if (ordered_commit_set_->HaveCommitItem(metahandle))
      continue;
    syncable::MutableEntry entry(write_transaction, syncable::GET_BY_HANDLE,
                                 metahandle);
    if (entry.Get(syncable::IS_DEL)) {
      syncable::Id parent_id = entry.Get(syncable::PARENT_ID);
      if (legal_delete_parents.count(parent_id)) {
        ordered_commit_set_->AddCommitItem(metahandle, entry.Get(syncable::ID),
            entry.GetModelType());
      }
    }
  }
}

void GetCommitIdsCommand::BuildCommitIds(
    syncable::WriteTransaction* write_transaction,
    const ModelSafeRoutingInfo& routes,
    const std::set<int64>& ready_unsynced_set) {
  ordered_commit_set_.reset(new OrderedCommitSet(routes));
  // Commits follow these rules:
  // 1. Moves or creates are preceded by needed folder creates, from
  //    root to leaf.  For folders whose contents are ordered, moves
  //    and creates appear in order.
  // 2. Moves/Creates before deletes.
  // 3. Deletes, collapsed.
  // We commit deleted moves under deleted items as moves when collapsing
  // delete trees.

  // Add moves and creates, and prepend their uncommitted parents.
  AddCreatesAndMoves(write_transaction, routes, ready_unsynced_set);

  // Add all deletes.
  AddDeletes(write_transaction, ready_unsynced_set);
}

}  // namespace browser_sync


text:
require 'spec_helper'

describe OrganizationPresenter do
  let(:organization_owner) do
    create(
      :carto_user,
      period_end_date: Time.parse('2018-01-01'),
      factory_bot_context: { only_db_setup: true }
    )
  end
  let(:organization) { create(:organization, :with_owner, owner: organization_owner) }
  let(:user) { organization.owner }
  let(:presenter) { described_class.new(organization) }
  let(:date_range) { { Date.new(2017, 3, 20) => 1 } }

  describe '#data' do
    before do
      CartoDB::ServiceUsageMetrics.any_instance.stubs(:get_date_range).returns(date_range)
    end

    it 'returns the default representation' do
      expect(presenter.data[:id]).to eq(organization.id)
      expect(presenter.data[:owner][:username]).to eq(organization.owner.username)
    end

    it 'returns extra attributes for the extended representation' do
      presenter = described_class.new(organization, extended: true)

      expect(presenter.data[:table_count]).to eq(0)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.sonatype.flexmojos.plugin.air.packager;

import java.io.File;
import java.io.IOException;

import com.adobe.air.nai.DMGPackager;

public class FlexmojosDMGPackager
    extends DMGPackager
    implements IPackager
{

    private File naiDir;

    public FlexmojosDMGPackager( File naiDir, File runtimeDir )
    {
        super.setRuntimeDir( runtimeDir );
        this.naiDir = naiDir;
    }

    @Override
    protected File getNAISDKBinDir()
        throws IOException
    {
        return new File( naiDir, "bin" );
    }

    @Override
    protected File getNAISDKLibDir()
        throws IOException
    {
        return new File( naiDir, "lib" );
    }

}


text:
package packfile

import (
	"bytes"

	"gopkg.in/src-d/go-git.v4/plumbing"
)

// See https://github.com/jelmer/dulwich/blob/master/dulwich/pack.py and
// https://github.com/tarruda/node-git-core/blob/master/src/js/delta.js
// for more info

const (
	// Standard chunk size used to generate fingerprints
	s = 16

	// https://github.com/git/git/blob/f7466e94375b3be27f229c78873f0acf8301c0a5/diff-delta.c#L428
	// Max size of a copy operation (64KB)
	maxCopySize = 64 * 1024
)

// GetDelta returns an EncodedObject of type OFSDeltaObject. Base and Target object,
// will be loaded into memory to be able to create the delta object.
// To generate target again, you will need the obtained object and "base" one.
// Error will be returned if base or target object cannot be read.
func GetDelta(base, target plumbing.EncodedObject) (plumbing.EncodedObject, error) {
	return getDelta(new(deltaIndex), base, target)
}

func getDelta(index *deltaIndex, base, target plumbing.EncodedObject) (plumbing.EncodedObject, error) {
	br, err := base.Reader()
	if err != nil {
		return nil, err
	}
	defer br.Close()
	tr, err := target.Reader()
	if err != nil {
		return nil, err
	}
	defer tr.Close()

	bb := bufPool.Get().(*bytes.Buffer)
	bb.Reset()
	defer bufPool.Put(bb)

	_, err = bb.ReadFrom(br)
	if err != nil {
		return nil, err
	}

	tb := bufPool.Get().(*bytes.Buffer)
	tb.Reset()
	defer bufPool.Put(tb)

	_, err = tb.ReadFrom(tr)
	if err != nil {
		return nil, err
	}

	db := diffDelta(index, bb.Bytes(), tb.Bytes())
	delta := &plumbing.MemoryObject{}
	_, err = delta.Write(db)
	if err != nil {
		return nil, err
	}

	delta.SetSize(int64(len(db)))
	delta.SetType(plumbing.OFSDeltaObject)

	return delta, nil
}

// DiffDelta returns the delta that transforms src into tgt.
func DiffDelta(src, tgt []byte) []byte {
	return diffDelta(new(deltaIndex), src, tgt)
}

func diffDelta(index *deltaIndex, src []byte, tgt []byte) []byte {
	buf := bufPool.Get().(*bytes.Buffer)
	buf.Reset()
	buf.Write(deltaEncodeSize(len(src)))
	buf.Write(deltaEncodeSize(len(tgt)))

	if len(index.entries) == 0 {
		index.init(src)
	}

	ibuf := bufPool.Get().(*bytes.Buffer)
	ibuf.Reset()
	for i := 0; i < len(tgt); i++ {
		offset, l := index.findMatch(src, tgt, i)

		if l == 0 {
			// couldn't find a match, just write the current byte and continue
			ibuf.WriteByte(tgt[i])
		} else if l < 0 {
			// src is less than blksz, copy the rest of the target to avoid
			// calls to findMatch
			for ; i < len(tgt); i++ {
				ibuf.WriteByte(tgt[i])
			}
		} else if l < s {
			// remaining target is less than blksz, copy what's left of it
			// and avoid calls to findMatch
			for j := i; j < i+l; j++ {
				ibuf.WriteByte(tgt[j])
			}
			i += l - 1
		} else {
			encodeInsertOperation(ibuf, buf)

			rl := l
			aOffset := offset
			for {
				if rl < maxCopySize {
					buf.Write(encodeCopyOperation(aOffset, rl))
					break
				}

				buf.Write(encodeCopyOperation(aOffset, maxCopySize))
				rl -= maxCopySize
				aOffset += maxCopySize
			}

			i += l - 1
		}
	}

	encodeInsertOperation(ibuf, buf)
	bytes := buf.Bytes()

	bufPool.Put(buf)
	bufPool.Put(ibuf)

	return bytes
}

func encodeInsertOperation(ibuf, buf *bytes.Buffer) {
	if ibuf.Len() == 0 {
		return
	}

	b := ibuf.Bytes()
	s := ibuf.Len()
	o := 0
	for {
		if s <= 127 {
			break
		}
		buf.WriteByte(byte(127))
		buf.Write(b[o : o+127])
		s -= 127
		o += 127
	}
	buf.WriteByte(byte(s))
	buf.Write(b[o : o+s])

	ibuf.Reset()
}

func deltaEncodeSize(size int) []byte {
	var ret []byte
	c := size & 0x7f
	size >>= 7
	for {
		if size == 0 {
			break
		}

		ret = append(ret, byte(c|0x80))
		c = size & 0x7f
		size >>= 7
	}
	ret = append(ret, byte(c))

	return ret
}

func encodeCopyOperation(offset, length int) []byte {
	code := 0x80
	var opcodes []byte

	var i uint
	for i = 0; i < 4; i++ {
		f := 0xff << (i * 8)
		if offset&f != 0 {
			opcodes = append(opcodes, byte(offset&f>>(i*8)))
			code |= 0x01 << i
		}
	}

	for i = 0; i < 3; i++ {
		f := 0xff << (i * 8)
		if length&f != 0 {
			opcodes = append(opcodes, byte(length&f>>(i*8)))
			code |= 0x10 << i
		}
	}

	return append([]byte{byte(code)}, opcodes...)
}


text:
from setuptools import setup, find_packages
import versioneer

setup(
    name='deepmachine',
    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),
    description='Deep Learning Framework',
    packages=find_packages(),
    author='Yuxiang ZHOU',
    author_email='mr.yuxiang.zhou@googlemail.com',
    url='https://github.com/yuxiang-zhou/deepmachine',
    install_requires=[
        'cython',
        'numpy',
        'h5py',
        'jupyter',
        'scikit-image',
        'scikit-learn',
        'tensorflow-gpu',
        'Keras>=2.2.2',
    ]
)


text:
package gwen.core.eval

import gwen.core._
import gwen.core.behavior.FeatureMode
import gwen.core.node.GwenNode
import gwen.core.node.gherkin.Dialect
import gwen.core.node.gherkin.GherkinKeyword
import gwen.core.node.gherkin.SpecPrinter
import gwen.core.node.gherkin.StepKeyword
import gwen.core.node.gherkin.Step
import gwen.core.state.ScopedDataStack
import gwen.core.state.StateLevel

import scala.jdk.CollectionConverters._
import scala.util.Failure
import scala.util.Success
import scala.util.chaining._

import jline.console.completer.AggregateCompleter
import jline.console.ConsoleReader
import jline.console.completer.StringsCompleter
import jline.console.history.FileHistory
import org.fusesource.jansi.Ansi._

import java.io.File
import java.io.PrintWriter

/**
  * Read-Eval-Print-Loop console.
  *
  * @author Branko Juric
  */
class GwenREPL[T <: EvalContext](val engine: EvalEngine[T], ctx: T) {

  private val outDir = GwenSettings.`gwen.outDir`
  private val history = new FileHistory(new File(outDir, ".history").getAbsoluteFile)

  private var paste: Option[List[String]] = None
  private var pastingDocString: Boolean = false
  private var debug: Boolean = false

  private val colors = ConsoleColors.isEnabled
  private val printer = new SpecPrinter(deep = false, colors)
  private def prompt = s"${if (colors) ansi.bold else ""}gwen${if (debug) s"@Breakpoint" else ""}> ${if (colors) ansi.reset else ""}"

  private lazy val reader = {
    new ConsoleReader() tap { reader =>
      reader.setHistory(history)
      reader.setBellEnabled(false)
      reader.setExpandEvents(false)
      reader.setPrompt(prompt)
      reader.addCompleter(new StringsCompleter((StepKeyword.names ++ List("help", "env", "history", "exit")).asJava))
      reader.addCompleter(new AggregateCompleter(new StringsCompleter(StepKeyword.names.flatMap(x => ctx.dsl.distinct.map(y => s"$x $y")).asJava)))
    }
  }

  // repl always runs in imperative mode
  Settings.setLocal("gwen.feature.mode", FeatureMode.imperative.toString)

  /** Reads an input string or command from the command line. */
  private def read(): String = {
    if (paste.isEmpty) System.out.println()
    reader.readLine() tap { _ => if (paste.isEmpty) System.out.println() }
  }

  /**
    * Evaluates a given input string or command.
    *
    * @param input an input step or command
    * @return optional result of the command as a string
    */
  private def eval(input: String): Option[String] = {
    Option(input).getOrElse(paste.map(_ => ":paste").getOrElse("exit")).trim match {
      case "" if paste.isEmpty =>
        Some("[noop]")
      case "help" if paste.isEmpty =>
        Some(helpText())
      case r"""env(.+?)?$$$options""" if paste.isEmpty => Option(options) match {
        case None => Some(ctx.visibleScopes.asString)
        case _ => options.trim match {
          case r"""(-f|-a)$switch "(.+?)"$$$filter""" => switch match {
            case "-f" => Some(ScopedDataStack(ctx.topScope.filterAtts(GwenREPL.attrFilter(filter))).asString)
            case "-a" => Some(ctx.filterAtts(GwenREPL.attrFilter(filter)).asString)
          }
          case r"""(-f|-a)$$$switch""" => switch match {
            case "-f" => Some(ctx.topScope.asString())
            case "-a" => Some(ctx.asString)
          }
          case r""""(.+?)"$$$filter""" =>
            Some(ctx.visibleScopes.filterAtts(GwenREPL.attrFilter(filter)).asString)
          case _ =>
            Some("""Try again using: env [-a|-f] ["filter"]""")
        }
      }
      case "history" if paste.isEmpty =>
        Some(history.toString)
      case r"""!(\d+)$$$historyValue""" if paste.isEmpty =>
        val num = historyValue.toInt
        if (num < (history.size() - 1)) {
          history.get(num).toString match {
            case x if input.trim.equals(x) =>
              Some(s"Unable to refer to self history - !$historyValue")
            case s => System.out.println(s"--> $s\n"); eval(s)
          }
        } else {
          Some(s"No such history: !$historyValue")
        }
      case "paste" | ":paste" =>
        if (paste.isEmpty) {
          paste = Some(List())
          reader.setPrompt("")
          System.out.println("REPL Console (paste mode)\n\nEnter or paste steps and press ctrl-D to evaluate..\n")
          Some("")
        } else {
          paste foreach { steps =>
            System.out.println(s"\nExiting paste mode, ${if (steps.nonEmpty) "interpreting now.." else "nothing pasted"}")
            steps.reverse map { step =>
              System.out.println(s"\n$prompt${Formatting.padTailLines(step, "      ")}\n")
              evaluateInput(step) tap { output => System.out.println(output) }
            }
          }
          reader.setPrompt(prompt)
          paste = None
          pastingDocString = false
          Some("\nREPL Console\n\nEnter steps to evaluate or type exit to quit..")
        }
      case "q" | "exit" | "bye" | "quit" if paste.isEmpty =>
        reader.getHistory.asInstanceOf[FileHistory].flush()
        None
      case "c" | "continue" | "resume" if debug =>
        reader.getHistory.asInstanceOf[FileHistory].flush()
        Some("continue")
      case _ =>
        if (paste.isEmpty) {
          Some(evaluateInput(input))
        } else {
          if (!pastingDocString) pastingDocString = input.trim.startsWith("\"\"\"")
          else pastingDocString = input.trim != "\"\"\""
          paste = paste map { entries =>
            if (GherkinKeyword.literals.exists(reserved => input.trim.startsWith(reserved)) && !pastingDocString) {
              input :: entries
            } else {
              entries match {
                case Nil => if (input.trim.nonEmpty) List(input) else Nil
                case head :: tail => s"$head${System.lineSeparator}$input" :: tail
              }
            }
          }
          Some(input)
        }
    }
  }

  private def evaluateInput(input: String): String = {
    input.trim match {
      case r"^Feature:(.*)$$$name" =>
        ctx.topScope.set("gwen.feature.name", name.trim)
        s"[gwen.feature.name = ${name.trim}]"
      case r"^Rule:(.*)$$$name" =>
        ctx.topScope.set("gwen.rule.name", name.trim)
        s"[gwen.rule.name = ${name.trim}]"
      case r"^(Scenario|Example):(.*)$$$name" =>
        if (StateLevel.scenario.equals(ctx.stateLevel)) {
          ctx.reset(StateLevel.scenario)
        }
        ctx.topScope.set("gwen.scenario.name", name.trim)
        s"[gwen.scenario.name = ${name.trim}]"
      case r"^Scenario(?: (Outline|Template))?:(.*)$$$name" =>
        ctx.topScope.set("gwen.scenario.name", name.trim)
        s"[gwen.scenario.name = ${name.trim}]"
      case r"""^#\s*language:\s*(\S+)$$$language""" =>
        Dialect.setLanguage(language)
        s"# language: $language"
      case _ =>
        engine.interpretStep(input, ctx) match {
          case Success(step) => printer.printStatus(step, withMessage = true)
          case Failure(error) => s"${if (colors) ansi.fg(Color.RED) else ""}$error\n\n[non-step]${if (colors) ansi.reset else ""}"
        }
    }
  }

  /** Runs the read-eval-print-loop. */
  def run(): Unit = {
    debug = false
    System.out.println("\nREPL Console")
    System.out.println("\nEnter steps to evaluate or type help for more options..")
    while(eval(read()).map(output => output tap { _ => if (paste.isEmpty) System.out.println(output) } ).nonEmpty) { }
  }

  /** Runs the read-eval-print-loop in debug mode. */
  def debug(parent: GwenNode, step: Step): Boolean = {
    var continue: Boolean = false
    debug = true
    System.out.println(s"\nPaused at${step.sourceRef.map(sref => s" $sref").getOrElse("")}")
    System.out.println(printer.prettyPrint(parent, step))
    System.out.println("\nEnter c to continue or q to quit (or type help for more options)..")
    while(
      eval(read()) map { output =>
        continue = output == "continue"
        output tap { _ => if (paste.isEmpty && !continue) System.out.println(output) }
        output
      } filter { output => output != "continue" } nonEmpty
    ) { }
    continue
  }

  private def helpText() = {
    val help = """
      | Gwen REPL commands:
      |
      | help
      |   Displays this help text
      |
      | env [switch] ["filter"]
      |   Lists attributes in the current environment
      |     Only lists visible attributes if no options are specified
      |     switch :
      |       -a : to list all attributes in all scopes
      |       -f : to list all attributes in the feature (global) scope
      |     filter : literal string or regex filter expression
      |
      | :paste|paste
      |   Enters paste mode (for evaluating multiline steps)
      |
      | history
      |   Lists all previously entered commands
      |
      | !<#>
      |   Executes a previously entered command (history bang operator)
      |     # : the history command number
      |
      | Given|When|Then|And|But <step>
      |   Evaluates a step
      |     step : the step expression
      |
      | q|exit|quit|bye
      |   Closes the REPL session and exits
      |
      | ctrl-D
      |   If in past mode: exits paste mode and interprets provided steps
      |   Otherwise: Closes REPL session and exits
      |
      | <tab>
      |   Press tab key at any time for tab completion
      | """.stripMargin
    if (!debug) help else help ++ s"""
      | c|continue|resume
      |   Continue executing from current step (debug mode only)
      | """.stripMargin
  }
}

object GwenREPL {
  /** Filters attributes containing or matching given expression (both names and values are checked). */
  def attrFilter(filter: String): PartialFunction[(String, String), Boolean] = {
    case (n, v) => n.contains(filter) || n.matches(filter) || (v != null && (v.contains(filter) || v.matches(filter)))
  }
}


text:
@extends('liddleforum::layout')

@section('liddleforum_content_inner')

    @include('liddleforum::admin.partials.tabs')

Moderators

Manage your moderators here. Either create global moderators or limit moderators' powers to specific categories and their subcategories.

    @include('liddleforum::flashed.form_errors')

Moderators

                @if(count($moderators))

                            User ID
                            Name
                            Category
                            Actions

                        @foreach($moderators as $moderator)

                                {{ $moderator->user->getKey() }}
                                {{ $moderator->user->{config('liddleforum.user.name_column')} }}

                                    @if($moderator->category)
                                        {{ $moderator->category->name }}
                                    @else
                                        Global
                                    @endif

                                    <form method="POST" action="{{ route('liddleforum.admin.moderators.delete', ['id' => $moderator->id]) }}">
                                        {!! csrf_field() !!}
                                        {!! method_field('DELETE') !!}
                                        <button class="btn btn-danger btn-sm">Remove</button>
                                    </form>

                        @endforeach

                @else

                        There are currently no moderators, add them below.

                @endif

                    <form method="POST" action="{{ route('liddleforum.admin.moderators.create') }}">
                        {!! csrf_field() !!}

                            User ID
                            <input type="text" class="form-control" id="user_id" name="user_id" placeholder="User ID" value="{{ old('user_id', Request::get('user_id')) }}" />

                            Category
                            <select id="category_id" name="category_id" class="form-control">
                                <option value="">- Global -</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" @if(old('category_id', Request::get('category_id')) === $category->id) selected @endif>{{ $category->getDropdownName() }}</option>
                                @endforeach
                            </select>

                        <button class="btn btn-sm btn-success">Add Mod</button>
                    </form>

@endsection


text:
psychoanalysis
==============

NHS Hack Day project.

A quick hack project over the weekend for assigning various job roles different types
of activities to be tracked.  These can then have reports ran on them, compared to different time periods and used to improve workflow/identify issues with practitioners.

Commands
------

python manage.py runserver 0.0.0.0:8000 --settings=psychoanalysis.settings.development

TODO:
----

* Fix posting for activity entries.
* Remove ugo javascript
* Fix inserts so they only need to occur when an item is created (instead of that honking great database for loop)
* Style/Fix HTML.
* Create a better user display for inputting activity entries.
* At the very least split categories/activities into their own select boxes and filter the activities dependant on the category selected.
* Move charting into its own app.
* Improve Backbone so we aren't creating json strings, forms and triggering button clicks.
* Try to move the majority of the setup/creation out of the Django admin for a smoother, simplified experience.
* Make sure MC Nickle doesn't drink again.
* Look at database schema again.
* Add tests!


text:
package models

import "github.com/hongrich/revel"

type User struct {
	Username        string
	FirstName       string
	LastName        string
	Age             int
	Password        string
	PasswordConfirm string
	Email           string
	EmailConfirm    string
	TermsOfUse      bool
}

func (user *User) Validate(v *revel.Validation) {
	v.Required(user.Username)
	v.MinSize(user.Username, 6)
	v.Required(user.FirstName)
	v.Required(user.LastName)
	v.Required(user.Age)
	v.Range(user.Age, 16, 120)
	v.Required(user.Password)
	v.MinSize(user.Password, 6)
	v.Required(user.PasswordConfirm)
	v.Required(user.PasswordConfirm == user.Password).
		Message("The passwords do not match.")
	v.Required(user.Email)
	v.Email(user.Email)
	v.Required(user.EmailConfirm)
	v.Required(user.EmailConfirm == user.Email).
		Message("The email addresses do not match")
	v.Required(user.TermsOfUse)
}


text:
Check if a string is CSS color stop

[![NPM version](https://img.shields.io/npm/v/is-color-stop.svg?style=flat)](https://npmjs.org/package/is-color-stop)
[![Build Status](https://img.shields.io/travis/pigcan/is-color-stop.svg?style=flat)](https://travis-ci.org/pigcan/is-color-stop)
[![Coverage Status](https://img.shields.io/coveralls/pigcan/is-color-stop.svg?style=flat)](https://coveralls.io/r/pigcan/is-color-stop)
[![NPM downloads](http://img.shields.io/npm/dm/is-color-stop.svg?style=flat)](https://npmjs.org/package/is-color-stop)
[![Dependency Status](https://david-dm.org/pigcan/is-color-stop.svg)](https://david-dm.org/pigcan/is-color-stop)

## Install

```shell
$ npm install is-color-stop
```

## Usage

```js
const isColorStop = require('is-color-stop');

isColorStop('yellow') // true
isColorStop('yellow', '12px') // true
isColorStop('yellow', 'calc(100%)') // true
isColorStop('yellow', 'px') // false

isColorStop.isColor('red') // true
isColorStop.isColor('rgb(255)') // false

isColorStop.isRGB('rgb(255, 0, 0)') // true
isColorStop.isRGB('rgb(255)') // false

isColorStop.isRGBA('rgba(255, 0, 0, .8)') // true
isColorStop.isRGBA('rgba(255, 0, 0)') // false

isColorStop.isHSL('hsl(123, 45%, 67%)') // true
isColorStop.isHSL('hsl(123, 45%)') // false

isColorStop.isHSLA('hsla(123, 45%, 67%, 0.4)') // true
isColorStop.isHSLA('hsla(123, 45%, 67%)') // false

isColorStop.isHex('#fff') // true
isColorStop.isHex('#ff') // false

isColorStop.isCSSColorName('tomato') // true
isColorStop.isCSSColorName('hoge') // false

isColorStop.isCSSLengthUnit('px') // true
isColorStop.isCSSLengthUnit('x') // false

isColorStop.isTransparent('transparent') // true
```

## License

The MIT License (MIT)

Copyright (c) 2017 Pigcan


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

namespace HawkSharp.Exceptions
{
    class InsufficientMotorHawksException : MotorHawkException
    {
        public InsufficientMotorHawksException(string message) : base(message) { }
    }
}


text:
package org.gedcomx.atom;

import org.gedcomx.conclusion.Conclusion;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * @author Ryan Heaton
 */
@XmlRootElement ( namespace = "urn:custom" )
@XmlType ( namespace = "urn:custom" )
public class CustomEntity extends Conclusion {
}


text:
/*jshint laxcomma:true, expr:true, evil:true */
(function(define, require, $, window, undefined){

  define([ 'text!datajam/templates/modal.html',
           'datajam/init',
           'datajam/models/content_update'
         ], function(modalTemplate){

    var App = window.Datajam;

    App.views.Modal = Backbone.View.extend({

      events: {
        'toggle': 'toggle',
        'hide': 'hide',
        'click .modal-update': 'save',
        'click .close': 'hide',
        'keydown': 'handleKeyDown'
      },
      templates: {},

      initialize: function(){
        _.bindAll(this, 'handleKeyDown'
                      , 'hide'
                      , 'render'
                      , 'save'
                      , 'toggle'
                      );

        App.templates['modal'] || (App.templates['modal'] = Handlebars.compile(modalTemplate));

        this.$el.data('modalView', this);
        this.model.bind('change', this.render, this);

        return this;
      },

      handleKeyDown: function(evt){
        if(evt.keyCode == 13 &&
          (evt.metaKey || evt.ctrlKey)){

          evt.preventDefault();
          evt.stopPropagation();
          this.save();
        }
      },

      hide: function(evt){
        try{
          evt.preventDefault();
          evt.stopPropagation();
        }catch(e){}
        this.$el.modal('hide');

        return this;
      },

      render: function(){
        var tmpl = typeof(this.template) === 'function' && this.template || App.templates['modal'];
        this.$el.html(tmpl(this.model.toJSON()));

        return this;
      },

      save: function(evt){
        try{
          evt.preventDefault();
          evt.stopPropagation();
        }catch(e){}

        new App.models.ContentUpdate({
          contentArea: this.model,
          html: this.$el.find('textarea').val()
        }).save()
          .then(_.bind(function(){
            this.hide();
          }, this))
          .fail(_.bind(function(){

          }, this));

        return this;
      },

      toggle: function(evt){
        try{
          evt.preventDefault();
          evt.stopPropagation();
        }catch(e){}

        var visible = this.$el.is(':visible');
        this.$el.modal('toggle');
        if(! visible) this.$el.find('input, select, textarea').eq(0).focus();

        return this;
      }

    });
  });

})(define, require, jQuery, window);


text:
HOST_NUMBER=$1
OTHER_HOSTS=$2

# Bridge address
BRIDGE_ADDRESS=10.10.$HOST_NUMBER.1/24
UNION_IP=192.168.250.$HOST_NUMBER
UNION_ADDRESS=$UNION_IP/24

# Add the docker0 bridge
brctl addbr docker0
# Set up the IP for the docker0 bridge
ip address add $BRIDGE_ADDRESS dev docker0
# Activate the bridge
ip link set docker0 up

# Add the br0 Open vSwitch bridge
ovs-vsctl add-br br0
# Create the tunnel to the other host and attach it to the
# br0 bridge
COUNTER=0
for REMOTE_IP in $OTHER_HOSTS; do
  let COUNTER=COUNTER+1
  ovs-vsctl add-port br0 gre$COUNTER -- set interface gre$COUNTER type=gre options:remote_ip=$REMOTE_IP
done
ovs-vsctl add-port br0 tep0 -- set interface tep0 type=internal
ip address add $UNION_ADDRESS dev tep0
ip link set tep0 up

# Add the br0 bridge to docker0 bridge
brctl addif docker0 br0


text:
<?php

/**
 * @see Zend_Validate_CreditCard
 */
require_once 'Zend/Validate/CreditCard.php';

/**
 * @category   Zend
 * @package    Zend_Validate
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Validate
 */
class Zend_Validate_CreditCardTest extends PHPUnit_Framework_TestCase
{
    /**
     * Ensures that the validator follows expected behavior
     *
     * @return void
     */
    public function testBasic()
    {
        $validator      = new Zend_Validate_CreditCard();
        $valuesExpected = array(
            array('4111111111111111', true),
            array('5404000000000001', true),
            array('374200000000004',  true),
            array('4444555566667777', false),
            array('ABCDEF',           false)
            );
        foreach ($valuesExpected as $test) {
            $input = $test[0];
            $result = $test[1];
            $this->assertEquals($result, $validator->isValid($input), 'Test failed at ' . $input);
        }
    }

    /**
     * Ensures that getMessages() returns expected default value
     *
     * @return void
     */
    public function testGetMessages()
    {
        $validator = new Zend_Validate_CreditCard();
        $this->assertEquals(array(), $validator->getMessages());
    }

    /**
     * Ensures that get and setType works as expected
     *
     * @return void
     */
    public function testGetSetType()
    {
        $validator = new Zend_Validate_CreditCard();
        $this->assertEquals(11, count($validator->getType()));

        $validator->setType(Zend_Validate_CreditCard::MAESTRO);
        $this->assertEquals(array(Zend_Validate_CreditCard::MAESTRO), $validator->getType());

        $validator->setType(
            array(
                Zend_Validate_CreditCard::AMERICAN_EXPRESS,
                Zend_Validate_CreditCard::MAESTRO
            )
        );
        $this->assertEquals(
            array(
                Zend_Validate_CreditCard::AMERICAN_EXPRESS,
                Zend_Validate_CreditCard::MAESTRO
            ),
            $validator->getType()
        );

        $validator->addType(
            Zend_Validate_CreditCard::MASTERCARD
        );
        $this->assertEquals(
            array(
                Zend_Validate_CreditCard::AMERICAN_EXPRESS,
                Zend_Validate_CreditCard::MAESTRO,
                Zend_Validate_CreditCard::MASTERCARD
            ),
            $validator->getType()
        );
    }

    /**
     * Test specific provider
     *
     * @return void
     */
    public function testProvider()
    {
        $validator      = new Zend_Validate_CreditCard(Zend_Validate_CreditCard::VISA);
        $valuesExpected = array(
            array('4111111111111111', true),
            array('5404000000000001', false),
            array('374200000000004',  false),
            array('4444555566667777', false),
            array('ABCDEF',           false)
            );
        foreach ($valuesExpected as $test) {
            $input = $test[0];
            $result = $test[1];
            $this->assertEquals($result, $validator->isValid($input));
        }
    }

    /**
     * Test non string input
     *
     * @return void
     */
    public function testIsValidWithNonString()
    {
        $validator = new Zend_Validate_CreditCard(Zend_Validate_CreditCard::VISA);
        $this->assertFalse($validator->isValid(array('something')));
    }

    /**
     * Test service class with invalid validation
     *
     * @return void
     */
    public function testServiceClass()
    {
        $validator = new Zend_Validate_CreditCard();
        $this->assertEquals(null, $validator->getService());
        $validator->setService(array('Zend_Validate_CreditCardTest', 'staticCallback'));
        $valuesExpected = array(
            '4111111111111111' => false,
            '5404000000000001' => false,
            '374200000000004'  => false,
            '4444555566667777' => false,
            'ABCDEF'           => false
            );
        foreach ($valuesExpected as $input => $result) {
            $this->assertEquals($result, $validator->isValid($input));
        }
    }

    /**
     * Test non string input
     *
     * @return void
     */
    public function testConstructionWithOptions()
    {
        $validator = new Zend_Validate_CreditCard(
            array(
                'type' => Zend_Validate_CreditCard::VISA,
                'service' => array('Zend_Validate_CreditCardTest', 'staticCallback')
            )
        );

        $valuesExpected = array(
            '4111111111111111' => false,
            '5404000000000001' => false,
            '374200000000004'  => false,
            '4444555566667777' => false,
            'ABCDEF'           => false
            );
        foreach ($valuesExpected as $input => $result) {
            $this->assertEquals($result, $validator->isValid($input));
        }
    }

    /**
     * Test a invalid service class
     *
     * @return void
     */
    public function testInvalidServiceClass()
    {
        $validator = new Zend_Validate_CreditCard();
        $this->assertEquals(null, $validator->getService());
        try {
            $validator->setService(array('Zend_Validate_CreditCardTest', 'nocallback'));
            $this->fail('Exception expected');
        } catch(Zend_Exception $e) {
            $this->assertContains('Invalid callback given', $e->getMessage());
        }
    }

    /**
     * Test a config object
     *
     * @return void
     */
    public function testConfigObject()
    {
        require_once 'Zend/Config.php';
        $options = array('type' => 'Visa');
        $config = new Zend_Config($options, false);

        $validator = new Zend_Validate_CreditCard($config);
        $this->assertEquals(array('Visa'), $validator->getType());
    }

    /**
     * Test optional parameters with config object
     *
     * @return void
     */
    public function testOptionalConstructorParameterByConfigObject()
    {
        require_once 'Zend/Config.php';
        $config = new Zend_Config(array('type' => 'Visa', 'service' => array('Zend_Validate_CreditCardTest', 'staticCallback')));

        $validator = new Zend_Validate_CreditCard($config);
        $this->assertEquals(array('Visa'), $validator->getType());
        $this->assertEquals(array('Zend_Validate_CreditCardTest', 'staticCallback'), $validator->getService());
    }

    /**
     * Test optional constructor parameters
     *
     * @return void
     */
    public function testOptionalConstructorParameter()
    {
        $validator = new Zend_Validate_CreditCard('Visa', array('Zend_Validate_CreditCardTest', 'staticCallback'));
        $this->assertEquals(array('Visa'), $validator->getType());
        $this->assertEquals(array('Zend_Validate_CreditCardTest', 'staticCallback'), $validator->getService());
    }

    /**
     * @group ZF-9477
     */
    public function testMultiInstitute() {
        $validator      = new Zend_Validate_CreditCard(array('type' => Zend_Validate_CreditCard::MASTERCARD));
        $this->assertFalse($validator->isValid('4111111111111111'));
        $message = $validator->getMessages();
        $this->assertContains('not from an allowed institute', current($message));
    }

    public static function staticCallback($value)
    {
        return false;
    }
}


text:
//
//  eLongHTTPRequest.h
//  eLongNetworking
//
//  Created by Dawn on 14-11-29.
//  Copyright (c) 2014年 Kirn. All rights reserved.
//
//  完成网络请求的发起和请求数据的回调处理

#import <Foundation/Foundation.h>
#import "eLongHTTPRequestDelegate.h"
#import "eLongHTTPRequestOperation.h"

@interface eLongHTTPRequest : NSObject<eLongHTTPRequestOperationDelegate>
/**
 *  网络请求回调
 */
@property (nonatomic,weak) id<eLongHTTPRequestDelegate> delegate;
/**
 *  实例网络请求初始化方法
 *
 *  @param request NSURLRequest
 *
 *  @return eLongHTTPRequest实例
 */
- (eLongHTTPRequest *)initWithRequest:(NSURLRequest *)request;

/**
 *  实例网络请求初始化方法,block
 *
 *  @param request NSURLRequest
 *  @param success success block (eLongHTTPRequestOperation 实例,JSON对象)
 *  @param failure failure block (eLongHTTPRequestOperation 实例,error对象)
 *
 *  @return eLongHTTPRequest实例
 */
- (eLongHTTPRequest *)initWithRequest:(NSURLRequest *)request
                              success:(void (^)(eLongHTTPRequestOperation *operation, id responseObject))success
                              failure:(void (^)(eLongHTTPRequestOperation *operation, NSError *error))failure;
/**
 *  eLongHTTPRequest的单例网络请求
 *
 *  @param request         NSURLRequest
 *  @param contentEncoding 网络请求下行数据压缩格式
 *  @param delegate        delegate
 *
 *  @return eLongHTTPRequestOperation实例
 */
+ (eLongHTTPRequestOperation *)startRequest:(NSURLRequest *)request
                                    delegate:(id<eLongHTTPRequestDelegate>)delegate;
/**
 *  eLongHTTPRequest的单例网络请求
 *
 *  @param request         NSURLRequest
 *  @param contentEncoding 网络请求下行数据压缩格式
 *  @param success         success block (eLongHTTPRequestOperation 实例,JSON对象)
 *  @param failure         failure block (eLongHTTPRequestOperation 实例,error对象)
 *
 *  @return eLongHTTPRequestOperation实例
 */
+ (eLongHTTPRequestOperation *)startRequest:(NSURLRequest *)request
                                     success:(void (^)(eLongHTTPRequestOperation *operation, id responseObject))success
                                     failure:(void (^)(eLongHTTPRequestOperation *operation, NSError *error))failure;
/**
 *  开始网络请求
 */
- (void)start;
/**
 *  取消当前网络请求
 */
- (void)cancel;
@end


text:
package api

import (
	"github.com/cilium/cilium/pkg/policy/api/kafka"
)

// L4Proto is a layer 4 protocol name
type L4Proto string

const (
	// Keep pkg/u8proto up-to-date with any additions here

	ProtoTCP    L4Proto = "TCP"
	ProtoUDP    L4Proto = "UDP"
	ProtoICMP   L4Proto = "ICMP"
	ProtoICMPv6 L4Proto = "ICMPV6"
	ProtoAny    L4Proto = "ANY"

	PortProtocolAny = "0/ANY"
)

// PortProtocol specifies an L4 port with an optional transport protocol
type PortProtocol struct {
	// Port is an L4 port number. For now the string will be strictly
	// parsed as a single uint16. In the future, this field may support
	// ranges in the form "1024-2048
	// Port can also be a port name, which must contain at least one [a-z],
	// and may also contain [0-9] and '-' anywhere except adjacent to another
	// '-' or in the beginning or the end.
	//
	// +kubebuilder:validation:Pattern=`^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[0-9]{1,4})|([a-zA-Z0-9]-?)*[a-zA-Z](-?[a-zA-Z0-9])*$`
	Port string `json:"port"`

	// Protocol is the L4 protocol. If omitted or empty, any protocol
	// matches. Accepted values: "TCP", "UDP", ""/"ANY"
	//
	// Matching on ICMP is not supported.
	//
	// Named port specified for a container may narrow this down, but may not
	// contradict this.
	//
	// +kubebuilder:validation:Enum=TCP;UDP;ANY
	// +kubebuilder:validation:Optional
	Protocol L4Proto `json:"protocol,omitempty"`
}

// Covers returns true if the ports and protocol specified in the received
// PortProtocol are equal to or a superset of the ports and protocol in 'other'.
// Named ports only cover other named ports with exactly the same name.
func (p PortProtocol) Covers(other PortProtocol) bool {
	if p.Port != other.Port {
		return false
	}
	if p.Protocol != other.Protocol {
		return p.Protocol == "" || p.Protocol == ProtoAny
	}
	return true
}

// Secret is a reference to a secret, backed by k8s or local file system.
type Secret struct {
	// Namespace is the namespace in which the secret exists. Context of use
	// determines the default value if left out (e.g., "default").
	//
	// +kubebuilder:validation:Optional
	Namespace string `json:"namespace,omitempty"`

	// Name is the name of the secret.
	//
	// +kubebuilder:validation:Required
	Name string `json:"name"`
}

// TLSContext provides TLS configuration via reference to either k8s secrets
// or via filepath. If both are set, directory is given priority over
// k8sSecrets.
type TLSContext struct {
	// Secret is the secret that contains the certificates and private key for
	// the TLS context.
	// By default, Cilium will search in this secret for the following items:
	//  - 'ca.crt'  - Which represents the trusted CA to verify remote source.
	//  - 'tls.crt' - Which represents the public key certificate.
	//  - 'tls.key' - Which represents the private key matching the public key
	//                certificate.
	//
	// +kubebuilder:validation:Required
	Secret *Secret `json:"secret"`

	// TrustedCA is the file name or k8s secret item name for the trusted CA.
	// If omitted, 'ca.crt' is assumed, if it exists. If given, the item must
	// exist.
	//
	// +kubebuilder:validation:Optional
	TrustedCA string `json:"trustedCA,omitempty"`

	// Certificate is the file name or k8s secret item name for the certificate
	// chain. If omitted, 'tls.crt' is assumed, if it exists. If given, the
	// item must exist.
	//
	// +kubebuilder:validation:Optional
	Certificate string `json:"certificate,omitempty"`

	// PrivateKey is the file name or k8s secret item name for the private key
	// matching the certificate chain. If omitted, 'tls.key' is assumed, if it
	// exists. If given, the item must exist.
	//
	// +kubebuilder:validation:Optional
	PrivateKey string `json:"privateKey,omitempty"`
}

// PortRule is a list of ports/protocol combinations with optional Layer 7
// rules which must be met.
type PortRule struct {
	// Ports is a list of L4 port/protocol
	//
	// +kubebuilder:validation:Optional
	Ports []PortProtocol `json:"ports,omitempty"`

	// TerminatingTLS is the TLS context for the connection terminated by
	// the L7 proxy.  For egress policy this specifies the server-side TLS
	// parameters to be applied on the connections originated from the local
	// endpoint and terminated by the L7 proxy. For ingress policy this specifies
	// the server-side TLS parameters to be applied on the connections
	// originated from a remote source and terminated by the L7 proxy.
	//
	// +kubebuilder:validation:Optional
	TerminatingTLS *TLSContext `json:"terminatingTLS,omitempty"`

	// OriginatingTLS is the TLS context for the connections originated by
	// the L7 proxy.  For egress policy this specifies the client-side TLS
	// parameters for the upstream connection originating from the L7 proxy
	// to the remote destination. For ingress policy this specifies the
	// client-side TLS parameters for the connection from the L7 proxy to
	// the local endpoint.
	//
	// +kubebuilder:validation:Optional
	OriginatingTLS *TLSContext `json:"originatingTLS,omitempty"`

	// Rules is a list of additional port level rules which must be met in
	// order for the PortRule to allow the traffic. If omitted or empty,
	// no layer 7 rules are enforced.
	//
	// +kubebuilder:validation:Optional
	Rules *L7Rules `json:"rules,omitempty"`
}

// GetPortProtocols returns the Ports field of the PortRule.
func (pd PortRule) GetPortProtocols() []PortProtocol {
	return pd.Ports
}

// GetPortRule returns the PortRule.
func (pd *PortRule) GetPortRule() *PortRule {
	return pd
}

// PortDenyRule is a list of ports/protocol that should be used for deny
// policies. This structure lacks the L7Rules since it's not supported in deny
// policies.
type PortDenyRule struct {
	// Ports is a list of L4 port/protocol
	//
	// +kubebuilder:validation:Optional
	Ports []PortProtocol `json:"ports,omitempty"`
}

// GetPortProtocols returns the Ports field of the PortDenyRule.
func (pd PortDenyRule) GetPortProtocols() []PortProtocol {
	return pd.Ports
}

// GetPortRule returns nil has it is not a PortRule.
func (pd *PortDenyRule) GetPortRule() *PortRule {
	return nil
}

// L7Rules is a union of port level rule types. Mixing of different port
// level rule types is disallowed, so exactly one of the following must be set.
// If none are specified, then no additional port level rules are applied.
type L7Rules struct {
	// HTTP specific rules.
	//
	// +kubebuilder:validation:Optional
	HTTP []PortRuleHTTP `json:"http,omitempty"`

	// Kafka-specific rules.
	//
	// +kubebuilder:validation:Optional
	Kafka []kafka.PortRule `json:"kafka,omitempty"`

	// DNS-specific rules.
	//
	// +kubebuilder:validation:Optional
	DNS []PortRuleDNS `json:"dns,omitempty"`

	// Name of the L7 protocol for which the Key-value pair rules apply.
	//
	// +kubebuilder:validation:Optional
	L7Proto string `json:"l7proto,omitempty"`

	// Key-value pair rules.
	//
	// +kubebuilder:validation:Optional
	L7 []PortRuleL7 `json:"l7,omitempty"`
}

// Len returns the total number of rules inside `L7Rules`.
// Returns 0 if nil.
func (rules *L7Rules) Len() int {
	if rules == nil {
		return 0
	}
	return len(rules.HTTP) + len(rules.Kafka) + len(rules.DNS) + len(rules.L7)
}

// IsEmpty returns whether the `L7Rules` is nil or contains nil rules.
func (rules *L7Rules) IsEmpty() bool {
	return rules == nil || (rules.HTTP == nil && rules.Kafka == nil && rules.DNS == nil && rules.L7 == nil)
}

// PortRules is a slice of PortRule.
type PortRules []PortRule

// Iterate iterates over all elements of PortRules.
func (pr PortRules) Iterate(f func(pr Ports) error) error {
	for i := range pr {
		err := f(&pr[i])
		if err != nil {
			return err
		}
	}
	return nil
}

// Len returns the length of the elements of PortRules.
func (pr PortRules) Len() int {
	return len(pr)
}

// PortDenyRules is a slice of PortDenyRule.
type PortDenyRules []PortDenyRule

// Iterate iterates over all elements of PortDenyRules.
func (pr PortDenyRules) Iterate(f func(pr Ports) error) error {
	for i := range pr {
		err := f(&pr[i])
		if err != nil {
			return err
		}
	}
	return nil
}

// Len returns the length of the elements of PortDenyRules.
func (pr PortDenyRules) Len() int {
	return len(pr)
}

// Ports is an interface that should be used by all implementations of the
// PortProtocols.
type Ports interface {
	// GetPortProtocols returns the slice PortProtocol
	GetPortProtocols() []PortProtocol
	// GetPortRule returns a PortRule, if the implementation does not support
	// it, then returns nil.
	GetPortRule() *PortRule
}

// PortsIterator is an interface that should be implemented by structures that
// can iterate over a list of Ports interfaces.
type PortsIterator interface {
	Iterate(f func(pr Ports) error) error
	Len() int
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mysql.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.mysql.fluent.models.ServerAdministratorResourceInner;
import com.azure.resourcemanager.mysql.models.AdministratorType;
import java.util.UUID;

/** Samples for ServerAdministrators CreateOrUpdate. */
public final class ServerAdministratorsCreateOrUpdateSamples {
    /*
     * x-ms-original-file: specification/mysql/resource-manager/Microsoft.DBforMySQL/stable/2017-12-01/examples/ServerAdminCreateUpdate.json
     */
    /**
     * Sample code: ServerAdministratorCreate.
     *
     * @param manager Entry point to MySqlManager.
     */
    public static void serverAdministratorCreate(com.azure.resourcemanager.mysql.MySqlManager manager) {
        manager
            .serverAdministrators()
            .createOrUpdate(
                "testrg",
                "mysqltestsvc4",
                new ServerAdministratorResourceInner()
                    .withAdministratorType(AdministratorType.ACTIVE_DIRECTORY)
                    .withLogin("bob@contoso.com")
                    .withSid(UUID.fromString("c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c"))
                    .withTenantId(UUID.fromString("c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c")),
                Context.NONE);
    }
}


text:
package org.apereo.cas.adaptors.yubikey;

import com.yubico.client.v2.YubicoClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.adaptors.yubikey.registry.WhitelistYubiKeyAccountRegistry;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.web.support.WebUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.webflow.core.collection.LocalAttributeMap;
import org.springframework.webflow.execution.RequestContext;
import org.springframework.webflow.execution.RequestContextHolder;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;
import java.util.HashMap;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Test cases for {@link YubiKeyAuthenticationHandler}.
 *
 * @author Misagh Moayyed
 * @since 4.1
 */
@Slf4j
public class YubiKeyAuthenticationHandlerTests {

    private static final Integer CLIENT_ID = 18421;
    private static final String SECRET_KEY = "iBIehjui12aK8x82oe5qzGeb0As=";
    private static final String OTP = "cccccccvlidcnlednilgctgcvcjtivrjidfbdgrefcvi";

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void before() {
        final RequestContext ctx = mock(RequestContext.class);
        when(ctx.getConversationScope()).thenReturn(new LocalAttributeMap<>());
        WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), ctx);
        RequestContextHolder.setRequestContext(ctx);
    }

    @Test
    public void checkDefaultAccountRegistry() {
        final YubiKeyAuthenticationHandler handler = new YubiKeyAuthenticationHandler(YubicoClient.getClient(CLIENT_ID, SECRET_KEY));
        assertNotNull(handler.getRegistry());
    }

    @Test
    public void checkReplayedAuthn() throws Exception {
        final YubiKeyAuthenticationHandler handler = new YubiKeyAuthenticationHandler(YubicoClient.getClient(CLIENT_ID, SECRET_KEY));

        this.thrown.expect(FailedLoginException.class);

        handler.authenticate(new YubiKeyCredential(OTP));
    }

    @Test
    public void checkBadConfigAuthn() throws Exception {
        final YubiKeyAuthenticationHandler handler = new YubiKeyAuthenticationHandler(YubicoClient.getClient(123456, "123456"));

        this.thrown.expect(AccountNotFoundException.class);
        handler.authenticate(new YubiKeyCredential("casuser"));
    }

    @Test
    public void checkAccountNotFound() throws Exception {
        final YubiKeyAuthenticationHandler handler = new YubiKeyAuthenticationHandler(StringUtils.EMPTY,
                null, new DefaultPrincipalFactory(),
                YubicoClient.getClient(CLIENT_ID, SECRET_KEY),
                new WhitelistYubiKeyAccountRegistry(new HashMap<>(),
                        new DefaultYubiKeyAccountValidator(YubicoClient.getClient(CLIENT_ID, SECRET_KEY))));
        this.thrown.expect(AccountNotFoundException.class);
        handler.authenticate(new YubiKeyCredential(OTP));
    }
}


text:
require 'rails_helper'

RSpec.describe TodosController, :type => :controller do
  render_views

  describe 'GET index' do
    before do
      (1..10).each { |i| FactoryGirl.create :todo }
      get :index, {format: 'json'}
    end
    it { should respond_with(200) }
    it 'responds todos json' do
      json = JSON[response.body]
      expect(json).not_to be_nil
      expect(json).to be_kind_of(Array)
    end
  end

  describe 'GET show' do
    before do
      object = FactoryGirl.create :todo
      get :show, {format: 'json', id: object.id}
    end
    it { should respond_with(200) }
    it 'responds todo json' do
      json = JSON[response.body]
      expect(json).not_to be_nil
      expect(json['id']).to be request.filtered_parameters['id'].to_i
      expect { Todo.find(json['id']) } .not_to raise_exception
    end
  end

  describe 'PATCH update' do
    before do
      object = FactoryGirl.create :todo
      patch :update, {format: 'json', id: object.id, what:'patched what!?'}
    end
    it { should respond_with(200) }
    it 'responds todo json which updated' do
      json = JSON[response.body]
      expect(json).not_to be_nil
      expect(json['id']).to be request.filtered_parameters['id'].to_i
      expect { Todo.find(json['id']) } .not_to raise_exception
      expect(json['what']).to eq 'patched what!?'
    end
  end

  describe 'POST create' do
    before do
      t = Todo.new what:'try to create', urgency:3, priority:3
      json = JSON[t.to_json]
      json['format'] = 'json'
      post :create, json
    end
    it { should respond_with(200) }
    it 'responds todo json which created' do
      json = JSON[response.body]
      expect(json).not_to be_nil
      expect { Todo.find(json['id']) } .not_to raise_exception
      expect(json['what']).to eq 'try to create'
    end
  end

  describe 'DELETE destroy' do
    before do
      object = FactoryGirl.create :todo
      delete :destroy, {format: 'json', id: object.id}
    end
    it { should respond_with(200) }
    it 'responds todo json which removed' do
      json = JSON[response.body]
      expect(json).not_to be_nil
      expect(json['id']).to be request.filtered_parameters['id'].to_i
      expect { Todo.find(json['id']) } .to raise_exception
    end
  end

end


text:
import math
import json

# dev
import uasio.os_io.io_wrapper as iow
import convertors_simple_data_types.xintyy_type_convertors as tc
kSensorCfgMap_ = 'sensors_cfg_names.json'
kSensorCfgMap = 'sensors_cfg_names.json'

# Читаем конфигурация сенсора
def get_sensors_cfg():
    """ Deprecated! """
    sets = { 'name': kSensorCfgMap_, 'howOpen': 'r', 'coding': 'cp1251'}
    readedList = iow.file2list(sets)
    sensor_sets = json.loads(' '.join(readedList))
    print json.dumps(sensor_sets, sort_keys=True, indent=2)
    return sensor_sets

def get_sensor_cfg(name):
    """ Deprecated! """
    # читае общую конфигурацию

    uni_sensor_sets = get_sensors_cfg()

    # читаем конфигурацию для тока
    sets['name'] = uni_sensor_sets[name]
    sensorSettings = iow.file2list(sets)

    # here we are converting python object to json string
    sensor_sets = json.loads(' '.join(sensorSettings))
    print json.dumps(sensor_sets, sort_keys=True, indent=2)
    return sensor_sets

def _json_in_file_to_obj(fname):
    """ Преобразует json-структуру, содержащуюся в файле в python-объект.

    Args: Имя исходного файла.

    Returns:

    TODO(zaqwes): Обработка ошибок опущена.
    """

    sets = {'name': fname, 'howOpen': 'r', 'coding': 'cp1251'}

    readed_list = iow.file2list(sets)
    py_object = json.loads(' '.join(readed_list))
    return py_object

def get_sensor_cfg_new(name, global_cfg_file):
    """ Читает общую конфигурацию сенсора.
    Имя конфигурации задано в глобальной конфигурации.
    """
    uni_sensor_sets = _json_in_file_to_obj(global_cfg_file)

    sets = {'name': uni_sensor_sets[name],
            'howOpen': 'r',
            'coding': 'cp1251'}
    sensor_settings = iow.file2list(sets)

    sensor_sets = json.loads(' '.join(sensor_settings))
    #print json.dumps(sensor_sets, sort_keys=True, indent=2)
    return sensor_sets

class SensorChannal(object):
    """ Базовый класс, описывающий канал сенсора.

    Переводит значение некой физической величины в некий код код.
    Сперва величина переводится в вольты (пропускается через кривую преобразования).
    Затем домножается на коэффциент передачи канала сенсора.
    И в итоге оцифровывается и возможно кодируется.

    Может использоваться как в канале измерения, так и в каналах сравнения.

    Только для преобразования в код.

    TODO(zaqwes): Преобразование кода в величину.

    Attributes:
    """
    _sensor_settings_map = None

    def init_channal(self, sensor_settings_map):
        """ Загружает настройки канала.
        Warinig: Необходимо вызвать до начала использования объекта.
        """
        self._sensor_settings_map = sensor_settings_map

    def phy_value_to_voltage(self, value):
        """ Переводит измеряемую величину в вольты.
        Чисто виртуальная функция.
        """
        return 0

    def transmit_voltage(self, value_in_volts):
        """ Доводит напряжение до АЦП.
        По сути домножает на коэффициент передачи напряжения по цепи сенсора.
        Чисто виртуальная функция.
        """
        return 0

    def voltage_to_digital(self, value_in_volts):
        """ Оцифровывает напряжение, прищедшее на АЦП, и возможно кодирует его.
        Чисто виртуальная функция.
        """
        return 0

class HallCurrenSensor(SensorChannal):
    """ """
    pass

class SensorChannalHall():
    _addac = None
    _splitter_params = None
    _sensor_curve_cb = None
    _sensor_curve_sets = None
    def __init__(self, sensor_sets, addacName, hxName, curve_cb):
        # Параметры делителя напряжения
        self._splitter_params = sensor_sets[hxName]

        # Параметры ADDAC
        self._addac = sensor_sets[addacName]

        # кривая сенсора
        self._sensor_curve_cb = curve_cb
        self._sensor_curve_sets = sensor_sets['sensor_curve_params']

    def get_splitter(self):
        R1 = self._splitter_params['R1']
        R2 = self._splitter_params['R2']
        splitter = R2/(R1+R2)
        return splitter

    def get_ad_coeff(self):
        dVmax = self._addac['dVmax']    # mV сдвиг ЦАП
        VmaxIdeal = self._addac['VmaxIdeal']

        capacity = self._addac['capacity']
        Vmax = VmaxIdeal-dVmax     # mV - это максимальное значение ЦАП - площадка при выс. сигн.
        resolution = math.pow(2, capacity)

        to_digital = resolution/Vmax
        return to_digital

    def get_capacity(self):
        return self._addac['capacity']

    def get_da_coeff(self):
        return 1/self.get_ad_coeff()

    def sensor_curve(self, value):
        return self._sensor_curve_cb(value, self._sensor_curve_sets)

def value_to_voltage_hall(value, curve_params):
    """ Параметры входной кривой. Датчик Холла """
    Kiu = curve_params['Kiu']  # mV/A
    dU = curve_params['dU']  # mV
    U = value * Kiu + dU
    return U

def calc_coeff_transform(value, channal):
    """ Ток в код и обратно I, A код не переведен в цифру - предст. с плав. точкой
        Sample usige:
         Uo = R16*Uerr/(R16+R10) = 10*500/(10+5.11) = 330.907 mV
         2^10 - 5000 mV
         x - Uo ; x = 67.76 ue = 68 ue = 0x44 ue

    Args:

    Returns:

    Raises:

    """
    # Получаем описание канала и кривой сенсора
    multer = channal.get_splitter()
    to_digital = channal.get_ad_coeff()

    # Обработка
    U = channal.sensor_curve(value)

    # Умножаем на коэфф. перед. аналоговой цепи и "оцифровываем"
    Uadc = U * multer * to_digital
    Udig = int(Uadc)
    return tc.byte4strhex(Udig), str(channal.get_capacity())


text:
"""
Load OCD elections models with data extracted and scraped from CAL-ACCESS.
"""
import os
from django.apps import apps
from django.conf import settings
from django.utils.timezone import now
from django.core.management import call_command
from . import LoadOCDElectionsBase

class Command(LoadOCDElectionsBase):
    """
    Load OCD elections models with data extracted and scraped from CAL-ACCESS.
    """
    help = 'Load OCD elections models with data extracted and scraped from CAL-ACCESS'

    def handle(self, *args, **options):
        """
        Make it happen.
        """
        super(Command, self).handle(*args, **options)

        # Get the tracking model instance for this version
        self.processed_version = self.get_or_create_processed_version()[0]

        # create subdirectory in processed_data_dir, if missing
        filings_data_path = os.path.join(self.processed_data_dir, 'relational')
        os.path.isdir(filings_data_path) or os.makedirs(filings_data_path)

        # Start off loading all the data
        self.load()

        # archive if django project setting enabled
        if getattr(settings, 'CALACCESS_STORE_ARCHIVE', False):
            # then archive
            if self.verbosity > 2:
                self.log(' Archiving OCD processed data files.')
            self.archive()

        # Wrap it up
        self.success('Done!')

    def load(self):
        """
        Load all of the processed models.
        """
        # Set options for commands
        options = dict(verbosity=self.verbosity, no_color=self.no_color)

        #
        # Load parties
        #

        call_command('loadocdparties', **options)
        self.duration()

        #
        # Load elections
        #

        call_command('loadocdballotmeasureelections', **options)
        self.duration()

        call_command('loadocdcandidateelections', **options)
        self.duration()

        #
        # Load contests and candidates
        #

        call_command('loadocdcandidatecontests', **options)
        self.duration()

        call_command('loadocdballotmeasurecontests', **options)
        self.duration()

        call_command('loadocdretentioncontests', **options)
        self.duration()

        call_command('loadocdcandidaciesfrom501s', **options)
        self.duration()

        call_command('loadocdincumbentofficeholders', **options)
        self.duration()

        #
        # Merge duplicates
        #

        call_command('mergeocdpersonsbyfilerid', **options)
        self.duration()

        call_command('mergeocdpersonsbycontestandname', **options)
        self.duration()

    def archive(self):
        """
        Save a csv file for each loaded OCD model.
        """
        models_to_archive = apps.get_app_config("calaccess_processed_elections").get_ocd_models_list()

        for m in models_to_archive:
            obj, created = self.processed_version.files.get_or_create(file_name=m._meta.object_name)
            obj.process_start_datetime = now()
            obj.save()

            call_command('archivecalaccesselectionsfile', m._meta.object_name)
            obj.refresh_from_db()
            obj.process_finish_datetime = now()
            obj.save()


text:
'use strict';

/* Controllers */
angular.module('ssApp.controllers')
  .controller('liveController', function($scope, $http, $routeParams, $location, $route, $interval) {

    $scope.liveVolume = [];
    $interval(function(){
      $http.get('live').
        success(function(data, status, headers, config) {
          $scope.liveVolume = data;
          if (data.length > 0 ){
            $scope.first = data[0];
            if (data.length > 1){
              $scope.last = data[data.length -1];
            }
          }

        }).
        error(function(data, status, headers, config) {

        });
    },1500);
 });


text:
$(document).ready(function() {
    SLNBar.isAuthenticated = false;
    SLNBar.urlConnectButton = '\x2Fsession\x2Fnew?target=' + document.URL;

        SLNBar.searchActive = true;
    SLNBar.searchUrl = '\x2Fsearch';
    SLNBar.searchUrlMethod = 'GET';
    SLNBar.searchUrlAutocomplete = '\x2Fsearch_autosuggest';
    SLNBar.searchUrlAutocompleteMethod = 'GET';

        SLNBar.searchAutocompleteSelect = function (event, ui) {
        if (ui.item.path) {
            $("#sln_autocomplete").val(ui.item.label);
            window.location.href = ui.item.path;

            return false;
        }
    }
    SLNBar.searchAutocompleteRenderItem = function (data) {
        var ul = data.ul;
        var item = data.item;
        var group = data.group;
        var first = data.first;

        var label = item.label;

        var regex = new RegExp($('#sln_autocomplete').val(), 'gi');
        label = label.replace(regex, '$&');

        return $("

")
            .addClass('ui-menusln')
            .addClass(first)
            .data("item.autocomplete", item)
            .append("" + label + "")
            .appendTo(ul)
        ;
    };

    $('#sln').html(SLNBar.render());
    SLNBar.bindEvents();
});


text:
class AddAncestryToComments < ActiveRecord::Migration[5.0]
  def change
    add_column :comments, :ancestry, :string
    add_index :comments, :ancestry

  end
end


text:
<!DOCTYPE html>
<html>
  {% include head.html %}
  <body>
    {% include header.html %}
    <article class="group">
      {{ content }}
    </article>
    {% include print-footer.html %}
    {% include footer.html %}

  </body>
</html>


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Glow Unit Test</title>

Glow Unit Test

See this blog entry for more information.

		Here are some links in a normal paragraph: Google,
		Google Groups.
		This link has class="blog":
		diveintomark

Everything inside the red border is inside a div with id="foo".

This is a normal link: Yahoo

This link has class="blog": Simon Willison's Weblog

Try them out:

	<form id="form" action="formaction">
		<input type="text" name="action" value="Test" id="text1"/> label
		<input type="text" name="text2" value="Test" id="text2" disabled="disabled"/>
		<input type="radio" name="radio1" id="radio1" value="on"/>

		<input type="radio" name="radio2" id="radio2" checked="checked"/>
		<input type="checkbox" name="check" id="check1" checked="checked"/>
		<input type="checkbox" id="check2" value="on"/>

		<input type="hidden" name="hidden" id="hidden1"/>
		<input type="text" style="display:none;" name="foo[bar]" id="hidden2"/>

		<input type="text" id="name" name="name" value="name" maxlength="15" />

		<button id="button" name="button">Button</button>

		<textarea id="area1">foobar</textarea>

		<select name="select1" id="select1">
			<option id="option1a" value="">Nothing</option>
			<option id="option1b" value="1">1</option>
			<option id="option1c" value="2">2</option>
			<option id="option1d" value="3">3</option>
		</select>
		<select name="select2" id="select2">
			<option id="option2a" value="">Nothing</option>
			<option id="option2b" value="1">1</option>
			<option id="option2c" value="2">2</option>
			<option id="option2d" selected="selected" value="3">3</option>
		</select>
		<select name="select3" id="select3" multiple="multiple">
			<option id="option3a" value="">Nothing</option>
			<option id="option3b" selected="selected" value="1">1</option>
			<option id="option3c" selected="selected" value="2">2</option>
			<option id="option3d" value="3">3</option>
		</select>

		<object id="object1" codebase="stupid">
			<param name="p1" value="x1" />
			<param name="p2" value="x2" />
		</object>

		<foo_bar id="foobar">test element</foo_bar>
	</form>
	Float test.

	<form id="lengthtest">
		<input type="text" id="length" name="test"/>
		<input type="text" id="idTest" name="id"/>
	</form>

	<form id="testForm" action="#" method="get">
		<textarea name="T3" rows="2" cols="15">?
Z</textarea>
		<input type="hidden" name="H1" value="x" />
		<input type="hidden" name="H2" />
		<input name="PWD" type="password" value="" />
		<input name="T1" type="text" />
		<input name="T2" type="text" value="YES" readonly="readonly" id="T2" />
		<input type="checkbox" name="C1" value="1" />
		<input type="checkbox" name="C2" />
		<input type="radio" name="R1" value="1" />
		<input type="radio" name="R1" value="2" />
		<input type="text" name="My Name" value="me" />
		<input type="reset" name="reset" value="NO" />
		<select name="S1">
			<option value="abc">ABC</option>
			<option value="abc">ABC</option>
			<option value="abc">ABC</option>
		</select>
		<select name="S2" multiple="multiple" size="3">
			<option value="abc">ABC</option>

			<option value="abc">ABC</option>
			<option value="abc">ABC</option>
		</select>
		<select name="S3">
			<option selected="selected">YES</option>
		</select>
		<select name="S4">
			<option value="" selected="selected">NO</option>
		</select>
		<input type="submit"  name="sub1" value="NO" />
		<input type="submit"  name="sub2" value="NO" />

		<button name="sub4" type="submit" value="NO">NO</button>
		<input name="D1" type="text" value="NO" disabled="disabled" />
		<input type="checkbox" checked="checked" disabled="disabled" name="D2" value="NO" />
		<input type="radio" name="D3" value="NO" checked="checked" disabled="disabled" />
		<select name="D4" disabled="disabled">
			<option selected="selected" value="NO">NO</option>
		</select>
	</form>

fadeIn
fadeIn

fadeOut
fadeOut

slideUp
slideUp

slideDown
slideDown

User agent string goes here

Options

	<form action="?" id="optionForm">

			Test Module:
			<select id="module" name="module">
				<option value="">All</option>
			</select>

			Loading Method:
			<select id="loadMethod" name="loadMethod">
				<option value="scriptTags">Script tags, no gloader</option>
				<option value="gloaderAsync">Gloader - Async</option>
				<option value="gloaderSyncCallback">Gloader - Sync with callback</option>
				<option value="gloaderSyncNoCallback">Gloader - Sync without callback</option>
			</select>

<input type="submit" value="Apply" />

	</form>


text:
<!DOCTYPE html>

    <meta charset='utf-8' />
    <meta http-equiv="X-UA-Compatible" content="chrome=1" />
    <meta name="description" content="Bootstrap-accessibility-plugin : Accessibility Plugin for Bootstrap 3 and Bootstrap 3 as SubModule" />

    <link rel="stylesheet" type="text/css" media="screen" href="stylesheets/stylesheet.css">

    <title>Bootstrap accessibility plugin</title>

          View on GitHub

Bootstrap accessibility plugin

Accessibility Plugin for Bootstrap 3 and Bootstrap 3 as SubModule

              Download this project as a .zip file
              Download this project as a tar.gz file

Bootstrap Accessibility Plugin is an extension for the Bootstrap 3 web development framework that makes many of the components of this library accessible for keyboard and screen reader users. This plugin is available on Github  under the BSD license. We hope that this extension will make it very simple for website developers who use Bootstrap 3 components to provide great user experience for as many users as possible.

If you develop websites or web applications using Bootstrap components and want it to be accessible with a minimal development effort, this accessibility plugin may be the perfect solution. By adding the JavaScript plugin in your Bootstrapped HTML pages, you extend the stock components with an additional mark-up and events without modifying the original Bootstrap code. In doing so, you make those widgets keyboard-navigable and introduce the compatibility with screen reader software used by people who are visually impaired.

Bookmarklet

Experimental: if you want an even easier way to apply the Bootstrap Accessibility Plugin to your Bootstrap-driven website, you may want to try out our Bootstrap Accessibility Bookmarklet below.

<a href="javascript:(function(){var lin=document.createElement('link');lin.setAttribute('rel','stylesheet');lin.setAttribute('type','text/css');lin.setAttribute('href', 'http://paypal.github.io/bootstrap-accessibility-plugin/plugins/css/bootstrap-accessibility.css');document.getElementsByTagName('head')[0].appendChild(lin);var scr=document.createElement('SCRIPT');scr.type='text/javascript';scr.src='http://paypal.github.io/bootstrap-accessibility-plugin/plugins/js/bootstrap-accessibility.min.js';document.getElementsByTagName('head')[0].appendChild(scr);})();">
Bootstrap Accessibility

		This bookmarklet allows you to apply Bootstrap Accessibility Plugin features to any page that runs Bootstrap widgets. To install, follow these steps:

copy or drag the bookmarklet link above to your browser bookmarks

	Go to a webpage with Bootstrap widgets

Click bookmarklet in your "bookmarks" bar to load the plugin

Features

This plugin provides enhancements to the Bootstrap 3 components in two areas: keyboard navigation and  screen reader compatibility. There are also minor changes to improve color contrast in alert messages.

Keyboard Navigation

For some widgets, like tab panel, carousel, drop-down menu, etc, the onKeyDown event is employed in various places in order to make the desktop-style keyboard navigation possible. This enables someone who does not or cannot use the mouse navigate those components using tab and arrow keys. To further enhance the seamless navigation for keyboard users the plugin manages keyboard focus wherever appropriate.

Compatibility With Screen Readers

Once the plugin is loaded into your page, it will search for any available Bootstrap components and, if found, append the necessary ARIA roles and states to provide the enhanced semantics to those widgets. This is primarily useful for screen readers. Without ARIA mark-up it is difficult for this technology to express the meaning of dynamic elements, such as modeless alerts, tab panels, popup menus, carousels, etc, to users who cannot see the screen.

Color Contrast

We found that the foreground-to-background color contrast ratio for a Bootstrap alert message is too low. To make it easier for users to read, the color contrast has been increased.

Please see the README file for the list of components and more implementation details.

Try it out

If you want to use the Bootstrap Accessibility Plugin in your project, simply include the JavaScript file right after Bootstrap's JavaScript file. The exact instructions of how to do this can be found in the README.

Also, play around with the live demo of the Bootstrap Accessibility Plugin. For better effect, you may want to get hold of one of the popular screen readers if you would like to immerse yourself into the screen reader user experience. Seeing and hearing how "accessified" widgets work in this demo will help you verify whether the plugin is installed correctly on your website.

We look forward to improvements and suggestions from the community. To learn more about how Bootstrap Accessibility Plugin works, check out our detailed documentation.

To stay in touch with us, follow @PayPalInclusive and submit issues on GitHub.

Bootstrap-accessibility-plugin maintained by paypal

Published with GitHub Pages


text:
require 'spec_helper'
describe "The CVE-2015-3448 vulnerability" do
	before(:all) do
		@check = Dawn::Kb::CVE_2015_3448.new
		# @check.debug = true
	end
  it "is reported when vulnerable rest-client gem is used (1.7.2)" do
    @check.dependencies = [{:name=>"rest-client", :version=>'1.7.2'}]
    @check.vuln?.should   == true
  end
  it "is not reported when safe rest-client gem is used (1.7.3)" do
    @check.dependencies = [{:name=>"rest-client", :version=>'1.7.3'}]
    @check.vuln?.should   == false
  end

end


text:
NS_ASSUME_NONNULL_BEGIN

@class ASCollectionElement, ASElementMap;

ASDISPLAYNODE_EXTERN_C_BEGIN

struct ASDirectionalScreenfulBuffer {
  CGFloat positiveDirection; // Positive relative to iOS Core Animation layer coordinate space.
  CGFloat negativeDirection;
};
typedef struct ASDirectionalScreenfulBuffer ASDirectionalScreenfulBuffer;

ASDISPLAYNODE_EXTERN_C_END

@protocol ASLayoutController <NSObject>

- (void)setTuningParameters:(ASRangeTuningParameters)tuningParameters forRangeMode:(ASLayoutRangeMode)rangeMode rangeType:(ASLayoutRangeType)rangeType;

- (ASRangeTuningParameters)tuningParametersForRangeMode:(ASLayoutRangeMode)rangeMode rangeType:(ASLayoutRangeType)rangeType;

- (NSSet<ASCollectionElement *> *)elementsForScrolling:(ASScrollDirection)scrollDirection rangeMode:(ASLayoutRangeMode)rangeMode rangeType:(ASLayoutRangeType)rangeType map:(ASElementMap *)map;

- (void)allElementsForScrolling:(ASScrollDirection)scrollDirection rangeMode:(ASLayoutRangeMode)rangeMode displaySet:(NSSet<ASCollectionElement *> * _Nullable * _Nullable)displaySet preloadSet:(NSSet<ASCollectionElement *> * _Nullable * _Nullable)preloadSet map:(ASElementMap *)map;

@optional

@end

NS_ASSUME_NONNULL_END