text:
<?php
/**
 *
 */

namespace Commercetools\Core\Request\Orders\Command;

use Commercetools\Core\Request\Carts\Command\CartSetLineItemCustomTypeAction;
use Commercetools\Core\Model\Type\TypeReference;
use Commercetools\Core\Model\CustomField\FieldContainer;

/**
 * @package Commercetools\Core\Request\Orders\Command
 *
 * @method string getAction()
 * @method OrderSetLineItemCustomTypeAction setAction(string $action = null)
 * @method TypeReference getType()
 * @method OrderSetLineItemCustomTypeAction setType(TypeReference $type = null)
 * @method string getLineItemId()
 * @method OrderSetLineItemCustomTypeAction setLineItemId(string $lineItemId = null)
 * @method FieldContainer getFields()
 * @method OrderSetLineItemCustomTypeAction setFields(FieldContainer $fields = null)
 */
class OrderSetLineItemCustomTypeAction extends CartSetLineItemCustomTypeAction
{
}


text:
class AvgTime;
//---------------------------------------------------------------------------
/// A high resolution timestamp
class Timestamp
{
   private:
   /// The data
   char data[64];

   friend class AvgTime;

   /// Get the raw storage space
   void* ptr() { return data; }
   /// Get the raw storage space
   const void* ptr() const { return data; }

   public:
   /// Constructor
   Timestamp();

   /// Hash
   unsigned long long getHash() const { return *static_cast<const unsigned long long*>(ptr()); }

   /// Difference in ms
   unsigned operator-(const Timestamp& other) const;
};
//---------------------------------------------------------------------------
/// Aggregate
class AvgTime {
   private:
   /// The data
   char data[64];
   /// Count
   unsigned count;

   /// Get the raw storage space
   void* ptr() { return data; }
   /// Get the raw storage space
   const void* ptr() const { return data; }

   public:
   /// Constructor
   AvgTime();

   /// Add an interval
   void add(const Timestamp& start,const Timestamp& end);
   /// The avg time in ms
   double avg() const;
};
//---------------------------------------------------------------------------
#endif

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- yet another config -->
<generator>
	<file name="bean">
		<include file="bean/setMemento.xsl" />
		<include file="bean/validate.xsl" />
		<include file="bean/getset.xsl" />
		<include file="bean/dump.xsl" />
	</file>
	<file name="dao" fileNameAppend="DAO">
		<include file="dao/create.xsl" />
		<include file="dao/read.xsl" />
		<include file="dao/update.xsl" />
		<include file="dao/delete.xsl" />
		<include file="dao/exists.xsl" />
		<include file="dao/save.xsl" />
		<include file="dao/queryRowToStruct.xsl" />
	</file>
	<file name="gateway">
		<include file="gateway/getByAttributes.xsl" />
	</file>
	<file name="service">
		<include file="service/getBean.xsl" />
		<include file="service/getBeansQuery.xsl" />
		<include file="service/saveBean.xsl" />
		<include file="service/deleteBean.xsl" />
	</file>
	<file name="to"/>
	<file name="coldspring" filetype="xml" />
	<file name="VO" filetype="as" />
</generator>


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @type {Object}
 * @const
 */
var TESTING_HELLO_DIR = Object.freeze({
  isDirectory: true,
  name: 'hello'
});

/**
 * @type {Object}
 * @const
 */
var TESTING_CANDIES_DIR = Object.freeze({
  isDirectory: true,
  name: 'candies'
});

/**
 * @type {Object}
 * @const
 */
var TESTING_TIRAMISU_FILE = Object.freeze({
  isDirectory: false,
  name: 'tiramisu.txt'
});

/**
 * Returns entries in the requested directory.
 *
 * @param {ReadDirectoryRequestedOptions} options Options.
 * @param {function(Array<Object>, boolean)} onSuccess Success callback with
 *     a list of entries. May be called multiple times.
 * @param {function(string)} onError Error callback with an error code.
 */
function onReadDirectoryRequested(options, onSuccess, onError) {
  if (options.fileSystemId !== test_util.FILE_SYSTEM_ID) {
    onError('SECURITY');  // enum ProviderError.
    return;
  }

  if (options.directoryPath !== '/' + TESTING_HELLO_DIR.name) {
    onError('NOT_FOUND');  // enum ProviderError.
    return;
  }

  onSuccess([TESTING_TIRAMISU_FILE], true /* hasMore */);
  onSuccess([TESTING_CANDIES_DIR], false /* hasMore */);
}

/**
 * Sets up the tests. Called once per all test cases. In case of a failure,
 * the callback is not called.
 *
 * @param {function()} callback Success callback.
 */
function setUp(callback) {
  chrome.fileSystemProvider.onGetMetadataRequested.addListener(
      test_util.onGetMetadataRequestedDefault);

  test_util.defaultMetadata['/' + TESTING_HELLO_DIR.name] =
      TESTING_HELLO_DIR;
  test_util.defaultMetadata['/' + TESTING_HELLO_DIR.name + '/' +
        TESTING_TIRAMISU_FILE.name] = TESTING_TIRAMISU_FILE;
  test_util.defaultMetadata['/' + TESTING_HELLO_DIR.name + '/' +
      TESTING_CANDIES_DIR.name] = TESTING_CANDIES_DIR;

  chrome.fileSystemProvider.onReadDirectoryRequested.addListener(
      onReadDirectoryRequested);

  test_util.mountFileSystem(callback);
}

/**
 * Runs all of the test cases, one by one.
 */
function runTests() {
  chrome.test.runTests([
    // Read contents of the /hello directory. This directory exists, so it
    // should succeed.
    function readEntriesSuccess() {
      test_util.fileSystem.root.getDirectory(
          'hello',
          {create: false},
          chrome.test.callbackPass(function(dirEntry) {
            var dirReader = dirEntry.createReader();
            var entries = [];
            var readEntriesNext = function() {
              dirReader.readEntries(
                  chrome.test.callbackPass(function(inEntries) {
                    Array.prototype.push.apply(entries, inEntries);
                    if (!inEntries.length) {
                      // No more entries, so verify.
                      chrome.test.assertEq(2, entries.length);
                      chrome.test.assertTrue(entries[0].isFile);
                      chrome.test.assertEq('tiramisu.txt', entries[0].name);
                      chrome.test.assertEq(
                          '/hello/tiramisu.txt', entries[0].fullPath);
                      chrome.test.assertTrue(entries[1].isDirectory);
                      chrome.test.assertEq('candies', entries[1].name);
                      chrome.test.assertEq(
                          '/hello/candies', entries[1].fullPath);
                    } else {
                      readEntriesNext();
                    }
                  }), function(error) {
                    chrome.test.fail();
                  });
            };
            readEntriesNext();
          }),
          function(error) {
            chrome.test.fail();
          });
    },
    // Read contents of a directory which does not exist, what should return an
    // error.
    function readEntriesError() {
      test_util.fileSystem.root.getDirectory(
          'cranberries',
          {create: false},
          function(dirEntry) {
            chrome.test.fail();
          },
          chrome.test.callbackPass(function(error) {
            chrome.test.assertEq('NotFoundError', error.name);
          }));
    }
  ]);
}

// Setup and run all of the test cases.
setUp(runTests);


text:
  function out = block_op(Ab, varargin)
%|function out = block_op(Ab, varargin)
%|
%| Various operations on "block" objects and block data.
%|
%| There are (at least) three types of block objects possible in this toolbox.
%| 1. Cell arrays of matrices (or of some other matrix-like object).
%| 2. A Fatrix object with block capabilities (mtimes_block).
%| 3. The Gblock class (which is being phased out).
%|
%| This routine provides a common interface to all of them.
%|
%| arguments for object operations:
%|	'is'		is it a block object?
%|	'n'		nblock: # of blocks
%|	'ensure'	make it at least a 1-block block object (if needed)
%|
%| arguments for data operations:
%|	'ensure_block_data', data	rearrange arrays into cells
%|
%| Copyright 2005-6-19, Jeff Fessler, University of Michigan

if nargin < 2, help(mfilename), error(mfilename), end

switch length(varargin)
case 1
	out = block_op_ob(Ab, varargin{1});
case 2
	out = block_op_data(Ab, varargin{1}, varargin{2});
otherwise
	error 'bad args'
end

%
% block_op_data()
%
function out = block_op_data(Ab, arg, data)

if streq(arg, 'ensure_block_data')
	if iscell(data)
		out = data; % ok, already cell

	elseif isa(Ab, 'Fatrix')
		if ~isempty(Ab.handle_blockify_data)
			out = blockify_data(Ab, data);
			return
		end

		% attempt to be smart for backward compat!
		try
			nblock = block_op(Ab, 'n');
			starts = subset_start(nblock);
			out = cell(1,nblock);

			if ndims(data) == 3 % [ns,nt,na]
				data = reshaper(data, '2d'); % [ns*nt,na]
			end

			na = size(data,2);
			if nblock > na, error 'tried 2d but failed', end

			for iset=1:nblock
				istart = starts(iset);
				ia = istart:nblock:na;
				out{istart} = col(data(:,ia));
			end

		catch
			error([mfilename  ': failed to blockify data'])
		end
	else
		error 'unknown blockify case'
	end
else
	error 'bug'
end

%
% block_op_ob()
%
function out = block_op_ob(Ab, arg)

switch arg
case 'is'
	switch class(Ab)
	case 'cell'
		out = true;
	case {'Fatrix', 'fatrix2'}
		out = ~isempty(Ab.nblock);
	case 'Gblock'
		out = true;
	otherwise
		out = false;
	end

case 'n'
	if ~block_ob(Ab, 'is'), error 'not a block object', end
	switch class(Ab)
	case 'cell'
		out = length(Ab);
	case {'Fatrix', 'fatrix2'}
		out = Ab.nblock;
	case 'Gblock'
		out = Ab.nblock;
	otherwise
		fail 'bug'
	end

case 'ensure'
	if block_ob(Ab, 'is')
		out = Ab;
		return
	end

	if iscell(Ab)
		error 'bug: cell already is a block object'
	elseif isnumeric(Ab)
		Ab = Gsparse(Ab);
		Ab = Gblock(Ab, 1, 0);
	elseif (isa(Ab, 'Fatrix') || isa(Ab, 'fatrix2')) && ~isempty(Ab.nblock)
		out = Ab;
	else
		out = Gblock(Ab, 1, 0);
	end

otherwise
	fail('unknown argument: %s', arg)
end


text:
angular.module('download-data', [])

.value('BRANCHES', [
    {
      branch: '1.2.*', version: '${CDN_VERSION_1_2}',
      title: '1.2.x (legacy)',
      cssClass: 'branch-1-2-x'
    },
    {
      branch: '1.3.*', version: '${CDN_VERSION_1_3}',
      title: '1.3.x (latest)',
      cssClass: 'branch-1-3-x'
    }
])

.value('BUILDS', [
    { name: 'Minified' },
    { name: 'Uncompressed' },
    { name: 'Zip' }
])

.value('DOWNLOAD_INFO', {
  branchesInfo:
    "
"+
    "
Legacy 1.2.x
"+
    "
This branch is in maintenance mode. It is stable and the API will not undergo any further changes. New releases will only contain bug-fixes.
"+
    "
Latest 1.3.x
"+
    "
This branch is being actively developed. The API's are subject to change without any prior notice. Use if you want to have access to the most recent features.
"+
    "
",

  buildsInfo:
    "
"+
    "
Minified
"+
    "
Minified and obfuscated version of the AngularJS base code. Use this in your deployed application (but only if you can't use Google's CDN)
"+
    "
Uncompressed
"+
    "
The main AngularJS source code, as is. Useful for debugging and development purpose, but should ideally not be used in your deployed application
"+
    "
Zipped
"+
    "
The zipped version of the Angular Build, which contains both the builds of AngularJS, as well as documentation and other extras
"+
    "
",

  cdnInfo:
    "While downloading and using the AngularJS source code is great for development, "+
    "we recommend that you source the script from Google's CDN (Content Delivery Network) in your deployed, customer facing app whenever possible. "+
    "You get the following advantages for doing so:"+
    "
"+
    "
Better Caching : If you host AngularJS yourself, your users will have to download the source code atleast once. But if the browser sees that you are referring to Google CDN's version of AngularJS, and your user has visited another app which uses AngularJS, then he can avail the benefits of caching, and thus reduce one download, speeding up his overall experience!
"+
    "
Decreased Latency : Google's CDN distributes your static content across the globe, in various diverse, physical locations. It increases the odds that the user gets a version of AngularJS served from a location near him, thus reducing overall latency.
"+
    "
Increased Parallelism : Using Google's CDN reduces one request to your domain. Depending on the browser, the number of parallel requests it can make to a domain is restricted (as low as 2 in IE 7). So it can make a gigantic difference in loading times for users of those browsers.
"+
    "
",

  bowerInfo:
    "Bower is a package manager for client-side JavaScript components.

"+
    "For more info please see: https://github.com/bower/bower"
});


text:
#ifndef TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_
#define TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_

#include <stdlib.h>

#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <sstream>
#include <string>

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/stat_summarizer_options.h"
#include "tensorflow/core/util/stats_calculator.h"

namespace tensorflow {

class GraphDef;
class StepStats;
class NodeExecStats;

// A StatSummarizer assists in performance analysis of Graph executions.
//
// It summarizes time spent executing (on GPU/CPU), memory used etc. across
// multiple executions of a single Graph from the StepStats collected during
// graph execution.
//
// See tensorflow/tools/benchmark/benchmark_model.cc for an example usage.
class StatSummarizer {
 public:
  explicit StatSummarizer(const StatSummarizerOptions& options);

  // Deprecated: Use StatSummarizer(const StatSummarizerOptions&) instead. The
  // GraphDef is not needed by the StatSummarizer.
  explicit StatSummarizer(const tensorflow::GraphDef& tensorflow_graph);

  ~StatSummarizer();

  // Adds another run's StepStats output to the aggregate counts.
  void ProcessStepStats(const StepStats& step_stats);

  // Returns a string detailing the accumulated runtime stats in a tab-separated
  // format which can be pasted into a spreadsheet for further analysis.
  std::string GetOutputString() const {
    return stats_calculator_->GetOutputString();
  }

  std::string ShortSummary() const {
    return stats_calculator_->GetShortSummary();
  }

  // Prints the string returned by GetOutputString().
  void PrintStepStats() const { stats_calculator_->PrintStepStats(); }

  // Prints the output tensor sizes and types for each node.
  void PrintOutputs() const;

  void ComputeStatsByType(
      std::map<std::string, int64_t>* node_type_map_count,
      std::map<std::string, int64_t>* node_type_map_time,
      std::map<std::string, int64_t>* node_type_map_memory,
      std::map<std::string, int64_t>* node_type_map_times_called,
      int64_t* accumulated_us) const {
    stats_calculator_->ComputeStatsByType(
        node_type_map_count, node_type_map_time, node_type_map_memory,
        node_type_map_times_called, accumulated_us);
  }

  std::string GetStatsByNodeType() const {
    return stats_calculator_->GetStatsByNodeType();
  }

  std::string GetStatsByMetric(const string& title,
                               StatsCalculator::SortingMetric sorting_metric,
                               int num_stats) const {
    return stats_calculator_->GetStatsByMetric(title, sorting_metric,
                                               num_stats);
  }

  int num_runs() const { return stats_calculator_->num_runs(); }

  // Returns stats of total microseconds spent by all nodes in each run.
  const Stat<int64_t>& run_total_us() const {
    return stats_calculator_->run_total_us();
  }

 private:
  void Validate(const std::vector<TensorDescription>* outputs,
                const NodeExecStats& ns) const;

  std::map<std::string, std::vector<TensorDescription> > outputs_;

  std::unique_ptr<StatsCalculator> stats_calculator_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_


text:
"""
A module to perform nonmonotonic reasoning.  The ideas and demonstrations in
this module are based on "Logical Foundations of Artificial Intelligence" by
Michael R. Genesereth and Nils J. Nilsson.
"""

from nltk.sem.logic import *
from api import Prover, ProverCommandDecorator
from prover9 import Prover9, Prover9Command
from nltk.compat import defaultdict

class ProverParseError(Exception): pass

def get_domain(goal, assumptions):
    if goal is None:
        all_expressions = assumptions
    else:
        all_expressions = assumptions + [-goal]

    domain = set()
    for a in all_expressions:
        domain |= (a.free(False) - a.free(True))
    return domain

class ClosedDomainProver(ProverCommandDecorator):
    """
    This is a prover decorator that adds domain closure assumptions before
    proving.
    """
    def assumptions(self):
        assumptions = [a for a in self._command.assumptions()]
        goal = self._command.goal()
        domain = get_domain(goal, assumptions)
        return list([self.replace_quants(ex, domain) for ex in assumptions])

    def goal(self):
        goal = self._command.goal()
        domain = get_domain(goal, self._command.assumptions())
        return self.replace_quants(goal, domain)

    def replace_quants(self, ex, domain):
        """
        Apply the closed domain assumption to the expression
         - Domain = union([e.free(False) for e in all_expressions])
         - translate "exists x.P" to "(z=d1 | z=d2 | ... ) & P.replace(x,z)" OR
                     "P.replace(x, d1) | P.replace(x, d2) | ..."
         - translate "all x.P" to "P.replace(x, d1) & P.replace(x, d2) & ..."
        @param ex: C{Expression}
        @param domain: C{set} of {Variable}s
        @return: C{Expression}
        """
        if isinstance(ex, AllExpression):
            conjuncts = [ex.term.replace(ex.variable, VariableExpression(d))
                         for d in domain]
            conjuncts = [self.replace_quants(c, domain) for c in conjuncts]
            return reduce(lambda x,y: x&y, conjuncts)
        elif isinstance(ex, BooleanExpression):
            return ex.__class__(self.replace_quants(ex.first, domain),
                                self.replace_quants(ex.second, domain) )
        elif isinstance(ex, NegatedExpression):
            return -self.replace_quants(ex.term, domain)
        elif isinstance(ex, ExistsExpression):
            disjuncts = [ex.term.replace(ex.variable, VariableExpression(d))
                         for d in domain]
            disjuncts = [self.replace_quants(d, domain) for d in disjuncts]
            return reduce(lambda x,y: x|y, disjuncts)
        else:
            return ex

class UniqueNamesProver(ProverCommandDecorator):
    """
    This is a prover decorator that adds unique names assumptions before
    proving.
    """
    def assumptions(self):
        """
         - Domain = union([e.free(False) for e in all_expressions])
         - if "d1 = d2" cannot be proven from the premises, then add "d1 != d2"
        """
        assumptions = self._command.assumptions()

        domain = list(get_domain(self._command.goal(), assumptions))

        #build a dictionary of obvious equalities
        eq_sets = SetHolder()
        for a in assumptions:
            if isinstance(a, EqualityExpression):
                av = a.first.variable
                bv = a.second.variable
                #put 'a' and 'b' in the same set
                eq_sets[av].add(bv)

        new_assumptions = []
        for i,a in enumerate(domain):
            for b in domain[i+1:]:
                #if a and b are not already in the same equality set
                if b not in eq_sets[a]:
                    newEqEx = EqualityExpression(VariableExpression(a),
                                                 VariableExpression(b))
                    if Prover9().prove(newEqEx, assumptions):
                        #we can prove that the names are the same entity.
                        #remember that they are equal so we don't re-check.
                        eq_sets[a].add(b)
                    else:
                        #we can't prove it, so assume unique names
                        new_assumptions.append(-newEqEx)

        return assumptions + new_assumptions

class SetHolder(list):
    """
    A list of sets of Variables.
    """
    def __getitem__(self, item):
        """
        @param item: C{Variable}
        @return: the C{set} containing 'item'
        """
        assert isinstance(item, Variable)
        for s in self:
            if item in s:
                return s
        #item is not found in any existing set.  so create a new set
        new = set([item])
        self.append(new)
        return new

class ClosedWorldProver(ProverCommandDecorator):
    """
    This is a prover decorator that completes predicates before proving.

    If the assumptions contain "P(A)", then "all x.(P(x) -> (x=A))" is the completion of "P".
    If the assumptions contain "all x.(ostrich(x) -> bird(x))", then "all x.(bird(x) -> ostrich(x))" is the completion of "bird".
    If the assumptions don't contain anything that are "P", then "all x.-P(x)" is the completion of "P".

    walk(Socrates)
    Socrates != Bill
    + all x.(walk(x) -> (x=Socrates))
    ----------------
    -walk(Bill)

    see(Socrates, John)
    see(John, Mary)
    Socrates != John
    John != Mary
    + all x.all y.(see(x,y) -> ((x=Socrates & y=John) | (x=John & y=Mary)))
    ----------------
    -see(Socrates, Mary)

    all x.(ostrich(x) -> bird(x))
    bird(Tweety)
    -ostrich(Sam)
    Sam != Tweety
    + all x.(bird(x) -> (ostrich(x) | x=Tweety))
    + all x.-ostrich(x)
    -------------------
    -bird(Sam)
    """
    def assumptions(self):
        assumptions = self._command.assumptions()

        predicates = self._make_predicate_dict(assumptions)

        new_assumptions = []
        for p, predHolder in predicates.iteritems():
            new_sig = self._make_unique_signature(predHolder)
            new_sig_exs = [VariableExpression(v) for v in new_sig]

            disjuncts = []

            #Turn the signatures into disjuncts
            for sig in predHolder.signatures:
                equality_exs = []
                for v1,v2 in zip(new_sig_exs, sig):
                    equality_exs.append(EqualityExpression(v1,v2))
                disjuncts.append(reduce(lambda x,y: x&y, equality_exs))

            #Turn the properties into disjuncts
            for prop in predHolder.properties:
                #replace variables from the signature with new sig variables
                bindings = {}
                for v1,v2 in zip(new_sig_exs, prop[0]):
                    bindings[v2] = v1
                disjuncts.append(prop[1].substitute_bindings(bindings))

            #make the assumption
            if disjuncts:
                #disjuncts exist, so make an implication
                antecedent = self._make_antecedent(p, new_sig)
                consequent = reduce(lambda x,y: x|y, disjuncts)
                accum = ImpExpression(antecedent, consequent)
            else:
                #nothing has property 'p'
                accum = NegatedExpression(self._make_antecedent(p, new_sig))

            #quantify the implication
            for new_sig_var in new_sig[::-1]:
                accum = AllExpression(new_sig_var, accum)
            new_assumptions.append(accum)

        return assumptions + new_assumptions

    def _make_unique_signature(self, predHolder):
        """
        This method figures out how many arguments the predicate takes and
        returns a tuple containing that number of unique variables.
        """
        return tuple([unique_variable()
                      for i in range(predHolder.signature_len)])

    def _make_antecedent(self, predicate, signature):
        """
        Return an application expression with 'predicate' as the predicate
        and 'signature' as the list of arguments.
        """
        antecedent = predicate
        for v in signature:
            antecedent = antecedent(VariableExpression(v))
        return antecedent

    def _make_predicate_dict(self, assumptions):
        """
        Create a dictionary of predicates from the assumptions.

        @param assumptions: a C{list} of C{Expression}s
        @return: C{dict} mapping C{AbstractVariableExpression} to C{PredHolder}
        """
        predicates = defaultdict(PredHolder)
        for a in assumptions:
            self._map_predicates(a, predicates)
        return predicates

    def _map_predicates(self, expression, predDict):
        if isinstance(expression, ApplicationExpression):
            (func, args) = expression.uncurry()
            if isinstance(func, AbstractVariableExpression):
                predDict[func].append_sig(tuple(args))
        elif isinstance(expression, AndExpression):
            self._map_predicates(expression.first, predDict)
            self._map_predicates(expression.second, predDict)
        elif isinstance(expression, AllExpression):
            #collect all the universally quantified variables
            sig = [expression.variable]
            term = expression.term
            while isinstance(term, AllExpression):
                sig.append(term.variable)
                term = term.term
            if isinstance(term, ImpExpression):
                if isinstance(term.first, ApplicationExpression) and \
                   isinstance(term.second, ApplicationExpression):
                    func1, args1 = term.first.uncurry()
                    func2, args2 = term.second.uncurry()
                    if isinstance(func1, AbstractVariableExpression) and \
                       isinstance(func2, AbstractVariableExpression) and \
                       sig == [v.variable for v in args1] and \
                       sig == [v.variable for v in args2]:
                        predDict[func2].append_prop((tuple(sig), term.first))
                        predDict[func1].validate_sig_len(sig)

class PredHolder(object):
    """
    This class will be used by a dictionary that will store information
    about predicates to be used by the C{ClosedWorldProver}.

    The 'signatures' property is a list of tuples defining signatures for
    which the predicate is true.  For instance, 'see(john, mary)' would be
    result in the signature '(john,mary)' for 'see'.

    The second element of the pair is a list of pairs such that the first
    element of the pair is a tuple of variables and the second element is an
    expression of those variables that makes the predicate true.  For instance,
    'all x.all y.(see(x,y) -> know(x,y))' would result in "((x,y),('see(x,y)'))"
    for 'know'.
    """
    def __init__(self):
        self.signatures = []
        self.properties = []
        self.signature_len = None

    def append_sig(self, new_sig):
        self.validate_sig_len(new_sig)
        self.signatures.append(new_sig)

    def append_prop(self, new_prop):
        self.validate_sig_len(new_prop[0])
        self.properties.append(new_prop)

    def validate_sig_len(self, new_sig):
        if self.signature_len is None:
            self.signature_len = len(new_sig)
        elif self.signature_len != len(new_sig):
            raise Exception("Signature lengths do not match")

    def __str__(self):
        return '(%s,%s,%s)' % (self.signatures, self.properties,
                               self.signature_len)

    def __repr__(self):
        return str(self)

def closed_domain_demo():
    lp = LogicParser()

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1,p2])
    print prover.prove()
    cdp = ClosedDomainProver(prover)
    print 'assumptions:'
    for a in cdp.assumptions(): print '   ', a
    print 'goal:', cdp.goal()
    print cdp.prove()

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    p3 = lp.parse(r'-walk(Bill)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1,p2,p3])
    print prover.prove()
    cdp = ClosedDomainProver(prover)
    print 'assumptions:'
    for a in cdp.assumptions(): print '   ', a
    print 'goal:', cdp.goal()
    print cdp.prove()

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    p3 = lp.parse(r'-walk(Bill)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1,p2,p3])
    print prover.prove()
    cdp = ClosedDomainProver(prover)
    print 'assumptions:'
    for a in cdp.assumptions(): print '   ', a
    print 'goal:', cdp.goal()
    print cdp.prove()

    p1 = lp.parse(r'walk(Socrates)')
    p2 = lp.parse(r'walk(Bill)')
    c = lp.parse(r'all x.walk(x)')
    prover = Prover9Command(c, [p1,p2])
    print prover.prove()
    cdp = ClosedDomainProver(prover)
    print 'assumptions:'
    for a in cdp.assumptions(): print '   ', a
    print 'goal:', cdp.goal()
    print cdp.prove()

    p1 = lp.parse(r'girl(mary)')
    p2 = lp.parse(r'dog(rover)')
    p3 = lp.parse(r'all x.(girl(x) -> -dog(x))')
    p4 = lp.parse(r'all x.(dog(x) -> -girl(x))')
    p5 = lp.parse(r'chase(mary, rover)')
    c = lp.parse(r'exists y.(dog(y) & all x.(girl(x) -> chase(x,y)))')
    prover = Prover9Command(c, [p1,p2,p3,p4,p5])
    print prover.prove()
    cdp = ClosedDomainProver(prover)
    print 'assumptions:'
    for a in cdp.assumptions(): print '   ', a
    print 'goal:', cdp.goal()
    print cdp.prove()

def unique_names_demo():
    lp = LogicParser()

    p1 = lp.parse(r'man(Socrates)')
    p2 = lp.parse(r'man(Bill)')
    c = lp.parse(r'exists x.exists y.(x != y)')
    prover = Prover9Command(c, [p1,p2])
    print prover.prove()
    unp = UniqueNamesProver(prover)
    print 'assumptions:'
    for a in unp.assumptions(): print '   ', a
    print 'goal:', unp.goal()
    print unp.prove()

    p1 = lp.parse(r'all x.(walk(x) -> (x = Socrates))')
    p2 = lp.parse(r'Bill = William')
    p3 = lp.parse(r'Bill = Billy')
    c = lp.parse(r'-walk(William)')
    prover = Prover9Command(c, [p1,p2,p3])
    print prover.prove()
    unp = UniqueNamesProver(prover)
    print 'assumptions:'
    for a in unp.assumptions(): print '   ', a
    print 'goal:', unp.goal()
    print unp.prove()

def closed_world_demo():
    lp = LogicParser()

    p1 = lp.parse(r'walk(Socrates)')
    p2 = lp.parse(r'(Socrates != Bill)')
    c = lp.parse(r'-walk(Bill)')
    prover = Prover9Command(c, [p1,p2])
    print prover.prove()
    cwp = ClosedWorldProver(prover)
    print 'assumptions:'
    for a in cwp.assumptions(): print '   ', a
    print 'goal:', cwp.goal()
    print cwp.prove()

    p1 = lp.parse(r'see(Socrates, John)')
    p2 = lp.parse(r'see(John, Mary)')
    p3 = lp.parse(r'(Socrates != John)')
    p4 = lp.parse(r'(John != Mary)')
    c = lp.parse(r'-see(Socrates, Mary)')
    prover = Prover9Command(c, [p1,p2,p3,p4])
    print prover.prove()
    cwp = ClosedWorldProver(prover)
    print 'assumptions:'
    for a in cwp.assumptions(): print '   ', a
    print 'goal:', cwp.goal()
    print cwp.prove()

    p1 = lp.parse(r'all x.(ostrich(x) -> bird(x))')
    p2 = lp.parse(r'bird(Tweety)')
    p3 = lp.parse(r'-ostrich(Sam)')
    p4 = lp.parse(r'Sam != Tweety')
    c = lp.parse(r'-bird(Sam)')
    prover = Prover9Command(c, [p1,p2,p3,p4])
    print prover.prove()
    cwp = ClosedWorldProver(prover)
    print 'assumptions:'
    for a in cwp.assumptions(): print '   ', a
    print 'goal:', cwp.goal()
    print cwp.prove()

def combination_prover_demo():
    lp = LogicParser()

    p1 = lp.parse(r'see(Socrates, John)')
    p2 = lp.parse(r'see(John, Mary)')
    c = lp.parse(r'-see(Socrates, Mary)')
    prover = Prover9Command(c, [p1,p2])
    print prover.prove()
    command = ClosedDomainProver(
                  UniqueNamesProver(
                      ClosedWorldProver(prover)))
    for a in command.assumptions(): print a
    print command.prove()

def default_reasoning_demo():
    lp = LogicParser()

    premises = []

    #define taxonomy
    premises.append(lp.parse(r'all x.(elephant(x)        -> animal(x))'))
    premises.append(lp.parse(r'all x.(bird(x)            -> animal(x))'))
    premises.append(lp.parse(r'all x.(dove(x)            -> bird(x))'))
    premises.append(lp.parse(r'all x.(ostrich(x)         -> bird(x))'))
    premises.append(lp.parse(r'all x.(flying_ostrich(x)  -> ostrich(x))'))

    #default properties
    premises.append(lp.parse(r'all x.((animal(x)  & -Ab1(x)) -> -fly(x))')) #normal animals don't fly
    premises.append(lp.parse(r'all x.((bird(x)    & -Ab2(x)) -> fly(x))')) #normal birds fly
    premises.append(lp.parse(r'all x.((ostrich(x) & -Ab3(x)) -> -fly(x))')) #normal ostriches don't fly

    #specify abnormal entities
    premises.append(lp.parse(r'all x.(bird(x)           -> Ab1(x))')) #flight
    premises.append(lp.parse(r'all x.(ostrich(x)        -> Ab2(x))')) #non-flying bird
    premises.append(lp.parse(r'all x.(flying_ostrich(x) -> Ab3(x))')) #flying ostrich

    #define entities
    premises.append(lp.parse(r'elephant(E)'))
    premises.append(lp.parse(r'dove(D)'))
    premises.append(lp.parse(r'ostrich(O)'))

    #print the assumptions
    prover = Prover9Command(None, premises)
    command = UniqueNamesProver(ClosedWorldProver(prover))
    for a in command.assumptions(): print a

    print_proof('-fly(E)', premises)
    print_proof('fly(D)', premises)
    print_proof('-fly(O)', premises)

def print_proof(goal, premises):
    lp = LogicParser()
    prover = Prover9Command(lp.parse(goal), premises)
    command = UniqueNamesProver(ClosedWorldProver(prover))
    print goal, prover.prove(), command.prove()

def demo():
    closed_domain_demo()
    unique_names_demo()
    closed_world_demo()
    combination_prover_demo()
    default_reasoning_demo()

if __name__ == '__main__':
    demo()


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  CMetrics
 *  ========
 *  Copyright 2021-2022 The CMetrics Authors
 *
 *  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.
 */

#include <cmetrics/cmetrics.h>
#include <cmetrics/cmt_metric.h>
#include <cmetrics/cmt_math.h>
#include <cmetrics/cmt_atomic.h>

static inline int metric_hist_exchange(struct cmt_metric *metric,
                                       uint64_t timestamp,
                                       int bucket_id,
                                       uint64_t new, uint64_t old)
{
    int result;

    result = cmt_atomic_compare_exchange(&metric->hist_buckets[bucket_id],
                                         old, new);
    if (result == 0) {
        return 0;
    }

    cmt_atomic_store(&metric->timestamp, timestamp);
    return 1;
}

static inline int metric_hist_count_exchange(struct cmt_metric *metric,
                                             uint64_t timestamp,
                                             uint64_t new, uint64_t old)
{
    int result;

    result = cmt_atomic_compare_exchange(&metric->hist_count, old, new);
    if (result == 0) {
        return 0;
    }

    cmt_atomic_store(&metric->timestamp, timestamp);
    return 1;
}

static inline int metric_sum_exchange(struct cmt_metric *metric,
                                      uint64_t timestamp,
                                      double new_value, double old_value)
{
    uint64_t tmp_new;
    uint64_t tmp_old;
    int      result;

    tmp_new = cmt_math_d64_to_uint64(new_value);
    tmp_old = cmt_math_d64_to_uint64(old_value);

    result = cmt_atomic_compare_exchange(&metric->hist_sum, tmp_old, tmp_new);

    if (result == 0) {
        return 0;
    }

    cmt_atomic_store(&metric->timestamp, timestamp);
    return 1;
}

void cmt_metric_hist_inc(struct cmt_metric *metric, uint64_t timestamp,
                         int bucket_id)
{
    int result;
    uint64_t old;
    uint64_t new;

    do {
        old = cmt_atomic_load(&metric->hist_buckets[bucket_id]);
        new = old + 1;
        result = metric_hist_exchange(metric, timestamp, bucket_id, new, old);
    }
    while (result == 0);
}

void cmt_metric_hist_count_inc(struct cmt_metric *metric, uint64_t timestamp)
{
    int result;
    uint64_t old;
    uint64_t new;

    do {
        old = cmt_atomic_load(&metric->hist_count);
        new = old + 1;

        result = metric_hist_count_exchange(metric, timestamp, new, old);
    }
    while (result == 0);
}

void cmt_metric_hist_count_set(struct cmt_metric *metric, uint64_t timestamp,
                               uint64_t count)
{
    int result;
    uint64_t old;
    uint64_t new;

    do {
        old = cmt_atomic_load(&metric->hist_count);
        new = count;

        result = metric_hist_count_exchange(metric, timestamp, new, old);
    }
    while (result == 0);
}

void cmt_metric_hist_sum_add(struct cmt_metric *metric, uint64_t timestamp,
                             double val)
{
    double   old;
    double   new;
    int      result;

    do {
        old = cmt_metric_hist_get_sum_value(metric);
        new = old + val;
        result = metric_sum_exchange(metric, timestamp, new, old);
    }
    while (0 == result);
}

void cmt_metric_hist_sum_set(struct cmt_metric *metric, uint64_t timestamp,
                             double val)
{
    double   old;
    double   new;
    int      result;

    do {
        old = cmt_metric_hist_get_sum_value(metric);
        new = val;
        result = metric_sum_exchange(metric, timestamp, new, old);
    }
    while (0 == result);
}

void cmt_metric_hist_set(struct cmt_metric *metric, uint64_t timestamp,
                         int bucket_id, double val)
{
    int result;
    uint64_t old;
    uint64_t new;

    do {
        old = cmt_atomic_load(&metric->hist_buckets[bucket_id]);
        new = val;

        result = metric_hist_exchange(metric, timestamp, bucket_id, new, old);
    }
    while (result == 0);
}

uint64_t cmt_metric_hist_get_value(struct cmt_metric *metric, int bucket_id)
{
    uint64_t val;

    val = cmt_atomic_load(&metric->hist_buckets[bucket_id]);
    return val;
}

uint64_t cmt_metric_hist_get_count_value(struct cmt_metric *metric)
{
    uint64_t val;

    val = cmt_atomic_load(&metric->hist_count);
    return val;
}

double cmt_metric_hist_get_sum_value(struct cmt_metric *metric)
{
    uint64_t val;

    val = cmt_atomic_load(&metric->hist_sum);
    return cmt_math_uint64_to_d64(val);
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.codebase.user.web;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author salaboy
 */
@ApplicationScoped
public class ApplicationScopedProducers {

    @PersistenceContext(name = "primary")
    private EntityManager em;

    @Produces
    public EntityManager produceEntityManager() {
        return em;
    }
}


text:
package org.wildfly.swarm.microprofile.jwtauth.deployment.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.spi.CDI;

import io.undertow.security.api.AuthenticationMechanism;
import io.undertow.security.api.AuthenticationMechanismFactory;
import io.undertow.server.handlers.form.FormParserFactory;
import org.wildfly.swarm.microprofile.jwtauth.deployment.principal.JWTAuthContextInfo;
import org.jboss.logging.Logger;

/**
 * An AuthenticationMechanismFactory for the MicroProfile JWT RBAC
 */
@ApplicationScoped
public class JWTAuthMechanismFactory implements AuthenticationMechanismFactory {
    private static Logger log = Logger.getLogger(JWTAuthMechanismFactory.class);

    @PostConstruct
    public void init() {
        log.debugf("init");
    }

    /**
     * This builds the JWTAuthMechanism with a JWTAuthContextInfo containing the issuer and signer public key needed
     * to validate the token. This information is currently taken from the query parameters passed in via the
     * web.xml/login-config/auth-method value, or via CDI injection.
     *
     * @param mechanismName     - the login-config/auth-method, which will be MP-JWT for JWTAuthMechanism
     * @param formParserFactory - unused form type of authentication factory
     * @param properties        - the query parameters from the web.xml/login-config/auth-method value. We look for an issuedBy
     *                          and signerPubKey property to use for token validation.
     * @return the JWTAuthMechanism
     * @see JWTAuthContextInfo
     *
     */
    @Override
    public AuthenticationMechanism create(String mechanismName, FormParserFactory formParserFactory, Map<String, String> properties) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        JWTAuthContextInfo contextInfo;
        Optional<JWTAuthContextInfo> optContextInfo = Optional.empty();
        try {
            Instance<JWTAuthContextInfo> contextInfoInstance = CDI.current().select(JWTAuthContextInfo.class);
            contextInfo = contextInfoInstance.get();
            optContextInfo = Optional.of(contextInfo);
        } catch (Exception e) {
            log.debugf(e,"Unable to select JWTAuthContextInfo provider");
        }

        if (!optContextInfo.isPresent()) {
            // Try building the JWTAuthContextInfo from the properties and/or the deployment resources
            contextInfo = new JWTAuthContextInfo();
            String issuedBy = properties.get("issuedBy");
            if (issuedBy == null) {
                // Try the /META-INF/MP-JWT-ISSUER content
                URL issURL = loader.getResource("/META-INF/MP-JWT-ISSUER");
                if (issURL == null) {
                    throw new IllegalStateException("No issuedBy parameter was found");
                }
                issuedBy = readURLContent(issURL);
                if (issuedBy == null) {
                    throw new IllegalStateException("No issuedBy parameter was found");
                }
                issuedBy = issuedBy.trim();
            }
            String publicKeyPemEnc = properties.get("signerPubKey");
            if (publicKeyPemEnc == null) {
                // Try the /META-INF/MP-JWT-SIGNER content
                URL pkURL = loader.getResource("/META-INF/MP-JWT-SIGNER");
                if (pkURL == null) {
                    throw new IllegalStateException("No signerPubKey parameter was found");
                }
                publicKeyPemEnc = readURLContent(pkURL);
            }

            // Workaround the double decode issue; https://issues.jboss.org/browse/WFLY-9135
            String publicKeyPem = publicKeyPemEnc.replace(' ', '+');
            contextInfo.setIssuedBy(issuedBy);
            try {
                RSAPublicKey pk = (RSAPublicKey) KeyUtils.decodePublicKey(publicKeyPem);
                contextInfo.setSignerKey(pk);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        } else {
            contextInfo = optContextInfo.get();
        }

        return new JWTAuthMechanism(contextInfo);
    }

    private String readURLContent(URL url) {
        StringBuilder content = new StringBuilder();
        try {
            InputStream is = url.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = reader.readLine();
            while (line != null) {
                content.append(line);
                content.append('\n');
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            log.warnf("Failed to read content from: %s, error=%s", url, e.getMessage());
        }
        return content.toString();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.circularlist"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ActivitySimpleCircularList"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       <!--  <activity
            android:name=".ActivityListSelection"
            android:label="@string/title_activity_activity_list_selection" >
        </activity> -->
    </application>

</manifest>


text:
<?php

namespace tests\codeception\common\fixtures;

use yii\test\ActiveFixture;

/**
 * Class TermFixture
 *
 * @author Agiel K. Saputra <13nightevil@gmail.com>
 * @since 0.1.2
 */
class TermFixture extends ActiveFixture
{
    /**
     * @var string
     */
    public $modelClass = 'common\models\Term';
    /**
     * @var string
     */
    public $dataFile = '@tests/codeception/common/fixtures/data/init_term.php';
}


text:
<?php

declare(strict_types=1);

namespace Ecommit\CrudBundle\Tests\Crud;

use Doctrine\ORM\QueryBuilder;
use Ecommit\CrudBundle\Crud\CrudConfig;
use Ecommit\CrudBundle\Form\Searcher\SearcherInterface;
use PHPUnit\Framework\TestCase;

class CrudConfigTest extends TestCase
{
    public function testConstructorWithoutArgument(): void
    {
        $config = new CrudConfig();
        $this->assertSame([], $config->getOptions());
    }

    public function testConstructorWithArgument(): void
    {
        $config = new CrudConfig('session');
        $this->assertSame(['session_name' => 'session'], $config->getOptions());
    }

    public function testSetSessionName(): void
    {
        $config = (new CrudConfig())->setSessionName('session');
        $this->assertSame(['session_name' => 'session'], $config->getOptions());
    }

    public function testAddColumn(): void
    {
        $config = (new CrudConfig())
            ->addColumn('val1') // 1 argument
            ->addColumn('id2', 'alias2', 'label2') // 3 arguments
            ->addColumn('id3', 'alias3', 'label3', ['optionA' => 'valueA']); // 4 arguments
        $expected = [
            'columns' => [
                'val1',
                ['id' => 'id2', 'alias' => 'alias2', 'label' => 'label2'],
                ['id' => 'id3', 'alias' => 'alias3', 'label' => 'label3', 'optionA' => 'valueA'],
            ],
        ];
        $this->assertSame($expected, $config->getOptions());
    }

    public function testAddColumnWithoutArgument(): void
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Bad addColumn call');
        (new CrudConfig())->addColumn();
    }

    public function testAddColumnWithTooManyArguments(): void
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Bad addColumn call');
        (new CrudConfig())->addColumn(1, 2, 3, 4, 5);
    }

    public function testAddVirtualColumn(): void
    {
        $config = (new CrudConfig())
            ->addVirtualColumn('val1') // 1 argument
            ->addVirtualColumn('id2', 'alias2'); // 2 arguments
        $expected = [
            'virtual_columns' => [
                'val1',
                ['id' => 'id2', 'alias' => 'alias2'],
            ],
        ];
        $this->assertSame($expected, $config->getOptions());
    }

    public function testAddVirtualColumnWithoutArgument(): void
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Bad addVirtualColumn call');
        (new CrudConfig())->addVirtualColumn();
    }

    public function testAddVirtualColumnWithTooManyArguments(): void
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Bad addVirtualColumn call');
        (new CrudConfig())->addVirtualColumn(1, 2, 3);
    }

    public function testSetMaxPerPage(): void
    {
        $config = (new CrudConfig())->setMaxPerPage([10, 100], 100);
        $this->assertSame(['max_per_page_choices' => [10, 100], 'default_max_per_page' => 100], $config->getOptions());
    }

    public function testSetDefaultSort(): void
    {
        $config = (new CrudConfig())->setDefaultSort('sort', 'direction');
        $this->assertSame(['default_sort' => 'sort', 'default_sort_direction' => 'direction'], $config->getOptions());
    }

    public function testSetDefaultPersonalizedSort(): void
    {
        $config = (new CrudConfig())->setDefaultPersonalizedSort(['crit1', 'crit2']);
        $this->assertSame(['default_sort' => 'defaultPersonalizedSort', 'default_personalized_sort' => ['crit1', 'crit2']], $config->getOptions());
    }

    public function testSetQueryBuilder(): void
    {
        $queryBuilder = $this->createMock(QueryBuilder::class);
        $config = (new CrudConfig())->setQueryBuilder($queryBuilder);
        $this->assertSame(['query_builder' => $queryBuilder], $config->getOptions());
    }

    public function testSetRoute(): void
    {
        $config = (new CrudConfig())->setRoute('route', ['params']);
        $this->assertSame(['route_name' => 'route', 'route_parameters' => ['params']], $config->getOptions());
    }

    public function testCreateSearchForm(): void
    {
        $searchFormData = $this->createMock(SearcherInterface::class);
        $config = (new CrudConfig())->createSearchForm($searchFormData, 'type', ['option1']);
        $this->assertSame(['search_form_data' => $searchFormData, 'search_form_type' => 'type', 'search_form_options' => ['option1']], $config->getOptions());
    }

    public function testSetDisplayResultsOnlyIfSearch(): void
    {
        $config = (new CrudConfig())->setDisplayResultsOnlyIfSearch(true);
        $this->assertSame(['display_results_only_if_search' => true], $config->getOptions());
    }

    public function testSetBuildPaginator(): void
    {
        $config = (new CrudConfig())->setBuildPaginator(false);
        $this->assertSame(['build_paginator' => false], $config->getOptions());
    }

    public function testSetPersistentSettings(): void
    {
        $config = (new CrudConfig())->setPersistentSettings(true);
        $this->assertSame(['persistent_settings' => true], $config->getOptions());
    }

    public function testSetDivIdSearch(): void
    {
        $config = (new CrudConfig())->setDivIdSearch('id');
        $this->assertSame(['div_id_search' => 'id'], $config->getOptions());
    }

    public function testSetDivIdList(): void
    {
        $config = (new CrudConfig())->setDivIdList('id');
        $this->assertSame(['div_id_list' => 'id'], $config->getOptions());
    }

    public function testSetTwigFunctionsConfiguration(): void
    {
        $config = (new CrudConfig())->setTwigFunctionsConfiguration(['val1']);
        $this->assertSame(['twig_functions_configuration' => ['val1']], $config->getOptions());
    }

    /**
     * @dataProvider getTestResetOptionsProvider
     */
    public function testResetOptions(mixed $value, array $expected): void
    {
        $config = (new CrudConfig())
            ->setSessionName('session')
            ->setDefaultSort('sort', 'direction')
            ->resetOptions($value);
        $this->assertSame($expected, $config->getOptions());
    }

    public function getTestResetOptionsProvider(): array
    {
        return [
            [null, []],
            ['default_sort', ['session_name' => 'session', 'default_sort_direction' => 'direction']],
            [[], ['session_name' => 'session', 'default_sort' => 'sort', 'default_sort_direction' => 'direction']],
            [['default_sort', 'default_sort_direction'], ['session_name' => 'session']],
        ];
    }

    /**
     * @dataProvider getTestOffsetExistsProvider
     */
    public function testOffsetExists(string $offset, bool $expected): void
    {
        $config = (new CrudConfig())
            ->setSessionName('session');

        $this->assertSame($expected, $config->offsetExists($offset));
    }

    public function getTestOffsetExistsProvider(): array
    {
        return [
            ['session_name', true],
            ['bad_offset', false],
        ];
    }

    public function testOffsetGet(): void
    {
        $config = (new CrudConfig())
            ->setSessionName('session');

        $this->assertSame('session', $config->offsetGet('session_name'));
    }

    public function testOffsetSet(): void
    {
        $config = new CrudConfig();
        $config->offsetSet('session_name', 'session');

        $this->assertSame(['session_name' => 'session'], $config->getOptions());
    }

    public function testOffsetUnset(): void
    {
        $config = (new CrudConfig())
            ->setSessionName('session');
        $config->offsetUnset('session_name');

        $this->assertSame([], $config->getOptions());
    }
}


text:
An Angularjs directive that maintains an offset between 2 Datetimes

# Usage

You can use bower to install this directive:

    bower intall angular-datetime-keep-offset

Add it as a dependency to your application:

    var myApp = angular.module('myApp', 'modelKeepOffset')

Use it on combination with a datepicker or timepicker to maintain an offset

    <input type="text" ng-model="begin" ui-timepicker model-keep-offset="end">
    <input type="text" ng-model="end" ui-timepicker>


text:
using Abp.AspNetCore.Configuration;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.AspNetCore.Mvc.Results.Wrapping;
using Abp.Dependency;
using Abp.Reflection;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Abp.AspNetCore.Mvc.Results
{
    public class AbpResultFilter : IResultFilter, ITransientDependency
    {
        private readonly IAbpAspNetCoreConfiguration _configuration;
        private readonly IAbpActionResultWrapperFactory _actionResultWrapperFactory;

        public AbpResultFilter(IAbpAspNetCoreConfiguration configuration,
            IAbpActionResultWrapperFactory actionResultWrapper)
        {
            _configuration = configuration;
            _actionResultWrapperFactory = actionResultWrapper;
        }

        public virtual void OnResultExecuting(ResultExecutingContext context)
        {
            var methodInfo = context.ActionDescriptor.GetMethodInfo();

            //var clientCacheAttribute = ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
            //    methodInfo,
            //    _configuration.DefaultClientCacheAttribute
            //);

            //clientCacheAttribute?.Apply(context);

            var wrapResultAttribute =
                ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
                    methodInfo,
                    _configuration.DefaultWrapResultAttribute
                );

            if (!wrapResultAttribute.WrapOnSuccess)
            {
                return;
            }

            _actionResultWrapperFactory.CreateFor(context).Wrap(context);
        }

        public virtual void OnResultExecuted(ResultExecutedContext context)
        {
            //no action
        }
    }
}


text:
/*
 *               ~ CLNDR v1.1.0 ~
 * ==============================================
 *       https://github.com/kylestetz/CLNDR
 * ==============================================
 *  created by kyle stetz (github.com/kylestetz)
 *        &available under the MIT license
 * http://opensource.org/licenses/mit-license.php
 * ==============================================
 *
 * This is the fully-commented development version of CLNDR.
 * For the production version, check out clndr.min.js
 * at https://github.com/kylestetz/CLNDR
 *
 * This work is based on the
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

;(function ( $, window, document, undefined ) {

  // This is the default calendar template. This can be overridden.
  var clndrTemplate = "
" +
    "

previous

<%= month %> <%= year %>

next

" +
    "
" +
  "
" +

    "
" +
    "<% for(var i = 0; i < numberOfRows; i++){ %>" +
      "
" +
      "<% for(var j = 0; j < 7; j++){ %>" +
      "<% var d = j + i * 7; %>" +
      "<td class='<%= days[d].classes %>'>
<%= days[d].day %>" +
      "
	" +
      "<% } %>" +
      "
" +
    "<% } %>" +
    "
" +
  "
";

  var pluginName = 'clndr';

  var defaults = {
    template: clndrTemplate,
    weekOffset: 0,
    startWithMonth: null,
    clickEvents: {
      click: null,
      nextMonth: null,
      previousMonth: null,
      nextYear: null,
      previousYear: null,
      today: null,
      onMonthChange: null,
      onYearChange: null
    },
    targets: {
      nextButton: 'clndr-next-button',
      previousButton: 'clndr-previous-button',
      nextYearButton: 'clndr-next-year-button',
      previousYearButton: 'clndr-previous-year-button',
      todayButton: 'clndr-today-button',
      day: 'day',
      empty: 'empty'
    },
    events: [],
    extras: null,
    dateParameter: 'date',
    multiDayEvents: null,
    doneRendering: null,
    render: null,
    daysOfTheWeek: null,
    showAdjacentMonths: true,
    adjacentDaysChangeMonth: false,
    ready: null,
    constraints: null
  };

  // The actual plugin constructor
  function Clndr( element, options ) {
    this.element = element;

    // merge the default options with user-provided options
    this.options = $.extend(true, {}, defaults, options);

    // if there are events, we should run them through our addMomentObjectToEvents function
    // which will add a date object that we can use to make life easier. This is only necessary
    // when events are provided on instantiation, since our setEvents function uses addMomentObjectToEvents.
    if(this.options.events.length) {
      if(this.options.multiDayEvents) {
        this.options.events = this.addMultiDayMomentObjectsToEvents(this.options.events);
      } else {
        this.options.events = this.addMomentObjectToEvents(this.options.events);
      }
    }

    // this object will store a reference to the current month.
    // it's a moment object, which allows us to poke at it a little if we need to.
    // this will serve as the basis for switching between months & is the go-to
    // internally if we want to know which month we're currently at.
    if(this.options.startWithMonth) {
      this.month = moment(this.options.startWithMonth).startOf('month');
    } else {
      this.month = moment().startOf('month');
    }

    // if we've got constraints set, make sure the month is within them.
    if(this.options.constraints) {
      // first check if the start date exists & is later than now.
      if(this.options.constraints.startDate) {
        var startMoment = moment(this.options.constraints.startDate);
        if(this.month.isBefore(startMoment, 'month')) {
          this.month.set('month', startMoment.month());
          this.month.set('year', startMoment.year());
        }
      }
      // make sure the month (whether modified or not) is before the endDate
      if(this.options.constraints.endDate) {
        var endMoment = moment(this.options.constraints.endDate);
        if(this.month.isAfter(endMoment, 'month')) {
          this.month.set('month', endMoment.month()).set('year', endMoment.year());
        }
      }
    }

    this._defaults = defaults;
    this._name = pluginName;

    // Some first-time initialization -> day of the week offset,
    // template compiling, making and storing some elements we'll need later,
    // & event handling for the controller.
    this.init();
  }

  Clndr.prototype.init = function () {
    // create the days of the week using moment's current language setting
    this.daysOfTheWeek = this.options.daysOfTheWeek || [];
    if(!this.options.daysOfTheWeek) {
      this.daysOfTheWeek = [];
      for(var i = 0; i < 7; i++) {
        this.daysOfTheWeek.push( moment().weekday(i).format('dd').charAt(0) );
      }
    }
    // shuffle the week if there's an offset
    if(this.options.weekOffset) {
      this.daysOfTheWeek = this.shiftWeekdayLabels(this.options.weekOffset);
    }

    // quick & dirty test to make sure rendering is possible.
    if( !$.isFunction(this.options.render) ) {
      this.options.render = null;
      if (typeof _ === 'undefined') {
        throw new Error("Underscore was not found. Please include underscore.js OR provide a custom render function.");
      }
      else {
        // we're just going ahead and using underscore here if no render method has been supplied.
        this.compiledClndrTemplate = _.template(this.options.template);
      }
    }

    // create the parent element that will hold the plugin & save it for later
    $(this.element).html("

");
    this.calendarContainer = $('.clndr', this.element);

    // attach event handlers for clicks on buttons/cells
    this.bindEvents();

    // do a normal render of the calendar template
    this.render();

    // if a ready callback has been provided, call it.
    if(this.options.ready) {
      this.options.ready.apply(this, []);
    }
  };

  Clndr.prototype.shiftWeekdayLabels = function(offset) {
    var days = this.daysOfTheWeek;
    for(var i = 0; i < offset; i++) {
      days.push( days.shift() );
    }
    return days;
  };

  // This is where the magic happens. Given a moment object representing the current month,
  // an array of calendarDay objects is constructed that contains appropriate events and
  // classes depending on the circumstance.
  Clndr.prototype.createDaysObject = function(currentMonth) {
    // this array will hold numbers for the entire grid (even the blank spaces)
    daysArray = [];
    var date = currentMonth.startOf('month');

    // filter the events list (if it exists) to events that are happening last month, this month and next month (within the current grid view)
    this.eventsLastMonth = [];
    this.eventsThisMonth = [];
    this.eventsNextMonth = [];

    if(this.options.events.length) {

      // MULTI-DAY EVENT PARSING
      // if we're using multi-day events, the start or end must be in the current month
      if(this.options.multiDayEvents) {
        this.eventsThisMonth = $(this.options.events).filter( function() {
          return this._clndrStartDateObject.format("YYYY-MM") == currentMonth.format("YYYY-MM")
          || this._clndrEndDateObject.format("YYYY-MM") == currentMonth.format("YYYY-MM");
        }).toArray();

        if(this.options.showAdjacentMonths) {
          var lastMonth = currentMonth.clone().subtract('months', 1);
          var nextMonth = currentMonth.clone().add('months', 1);
          this.eventsLastMonth = $(this.options.events).filter( function() {
            return this._clndrStartDateObject.format("YYYY-MM") == lastMonth.format("YYYY-MM")
          || this._clndrEndDateObject.format("YYYY-MM") == lastMonth.format("YYYY-MM");
          }).toArray();

          this.eventsNextMonth = $(this.options.events).filter( function() {
            return this._clndrStartDateObject.format("YYYY-MM") == nextMonth.format("YYYY-MM")
          || this._clndrEndDateObject.format("YYYY-MM") == nextMonth.format("YYYY-MM");
          }).toArray();
        }
      }

      // SINGLE-DAY EVENT PARSING
      // if we're using single-day events, use _clndrDateObject
      else {
        this.eventsThisMonth = $(this.options.events).filter( function() {
          return this._clndrDateObject.format("YYYY-MM") == currentMonth.format("YYYY-MM");
        }).toArray();

        // filter the adjacent months as well, if the option is true
        if(this.options.showAdjacentMonths) {
          var lastMonth = currentMonth.clone().subtract('months', 1);
          var nextMonth = currentMonth.clone().add('months', 1);
          this.eventsLastMonth = $(this.options.events).filter( function() {
            return this._clndrDateObject.format("YYYY-MM") == lastMonth.format("YYYY-MM");
          }).toArray();

          this.eventsNextMonth = $(this.options.events).filter( function() {
            return this._clndrDateObject.format("YYYY-MM") == nextMonth.format("YYYY-MM");
          }).toArray();
        }
      }
    }

    // if diff is greater than 0, we'll have to fill in last days of the previous month
    // to account for the empty boxes in the grid.
    // we also need to take into account the weekOffset parameter
    var diff = date.weekday() - this.options.weekOffset;
    if(diff < 0) diff += 7;

    if(this.options.showAdjacentMonths) {
      for(var i = 0; i < diff; i++) {
        var day = moment([currentMonth.year(), currentMonth.month(), i - diff + 1]);
        daysArray.push( this.createDayObject(day, this.eventsLastMonth) );
      }
    } else {
      for(var i = 0; i < diff; i++) {
        daysArray.push( this.calendarDay({ classes: this.options.targets.empty + " last-month" }) );
      }
    }

    // now we push all of the days in a month
    var numOfDays = date.daysInMonth();
    for(var i = 1; i <= numOfDays; i++) {
      var day = moment([currentMonth.year(), currentMonth.month(), i]);
      daysArray.push(this.createDayObject(day, this.eventsThisMonth) )
    }

    // ...and if there are any trailing blank boxes, fill those in
    // with the next month first days
    if(this.options.showAdjacentMonths) {
      i = 1;
      while(daysArray.length % 7 !== 0) {
        var day = moment([currentMonth.year(), currentMonth.month(), numOfDays + i]);
        daysArray.push( this.createDayObject(day, this.eventsNextMonth) );
        i++;
      }
    } else {
      i = 1;
      while(daysArray.length % 7 !== 0) {
        daysArray.push( this.calendarDay({ classes: this.options.targets.empty + " next-month" }) );
        i++;
      }
    }

    return daysArray;
  };

  Clndr.prototype.createDayObject = function(day, monthEvents) {
    var eventsToday = [];
    var now = moment();
    var self = this;

    var j = 0, l = monthEvents.length;
    for(j; j < l; j++) {
      // keep in mind that the events here already passed the month/year test.
      // now all we have to compare is the moment.date(), which returns the day of the month.
      if(self.options.multiDayEvents) {
        var start = monthEvents[j]._clndrStartDateObject;
        var end = monthEvents[j]._clndrEndDateObject;
        // if today is the same day as start or is after the start, and
        // if today is the same day as the end or before the end ...
        // woohoo semantics!
        if( ( day.isSame(start, 'day') || day.isAfter(start, 'day') ) &&
          ( day.isSame(end, 'day') || day.isBefore(end, 'day') ) ) {
          eventsToday.push( monthEvents[j] );
        }
      } else {
        if( monthEvents[j]._clndrDateObject.date() == day.date() ) {
          eventsToday.push( monthEvents[j] );
        }
      }
    }

    var extraClasses = "";

    if(now.format("YYYY-MM-DD") == day.format("YYYY-MM-DD")) {
       extraClasses += " today";
    }
    if(day.isBefore(now, 'day')) {
      extraClasses += " past";
    }
    if(eventsToday.length) {
       extraClasses += " event";
    }
    if(this.month.month() > day.month()) {
       extraClasses += " adjacent-month";

       this.month.year() === day.year()
           ? extraClasses += " last-month"
           : extraClasses += " next-month";

    } else if(this.month.month() < day.month()) {
       extraClasses += " adjacent-month";

       this.month.year() === day.year()
           ? extraClasses += " next-month"
           : extraClasses += " last-month";
    }

    // if there are constraints, we need to add the inactive class to the days outside of them
    if(this.options.constraints) {
      if(this.options.constraints.startDate && day.isBefore(moment( this.options.constraints.startDate ))) {
        extraClasses += " inactive";
      }
      if(this.options.constraints.endDate && day.isAfter(moment( this.options.constraints.endDate ))) {
        extraClasses += " inactive";
      }
    }

    // validate moment date
    if (!day.isValid() && day.hasOwnProperty('_d') && day._d != undefined) {
        day = moment(day._d);
    }

    // we're moving away from using IDs in favor of classes, since when
    // using multiple calendars on a page we are technically violating the
    // uniqueness of IDs.
    extraClasses += " calendar-day-" + day.format("YYYY-MM-DD");

    return this.calendarDay({
      day: day.date(),
      classes: this.options.targets.day + extraClasses,
      events: eventsToday,
      date: day
    });
  };

  Clndr.prototype.render = function() {
    // get rid of the previous set of calendar parts.
    // TODO: figure out if this is the right way to ensure proper garbage collection?
    this.calendarContainer.children().remove();
    // get an array of days and blank spaces
    var days = this.createDaysObject(this.month);
    // this is to prevent a scope/naming issue between this.month and data.month
    var currentMonth = this.month;

    var data = {
      daysOfTheWeek: this.daysOfTheWeek,
      numberOfRows: Math.ceil(days.length / 7),
      days: days,
      month: this.month.format('MMMM'),
      year: this.month.year(),
      eventsThisMonth: this.eventsThisMonth,
      eventsLastMonth: this.eventsLastMonth,
      eventsNextMonth: this.eventsNextMonth,
      extras: this.options.extras
    };

    // render the calendar with the data above & bind events to its elements
    if(!this.options.render) {
      this.calendarContainer.html(this.compiledClndrTemplate(data));
    } else {
      this.calendarContainer.html(this.options.render.apply(this, [data]));
    }

    // if there are constraints, we need to add the 'inactive' class to the controls
    if(this.options.constraints) {
      // in the interest of clarity we're just going to remove all inactive classes and re-apply them each render.
      for(target in this.options.targets) {
        if(target != this.options.targets.day) {
          this.element.find('.' + this.options.targets[target]).toggleClass('inactive', false);
        }
      }

      var start = null;
      var end = null;

      if(this.options.constraints.startDate) {
        start = moment(this.options.constraints.startDate);
      }
      if(this.options.constraints.endDate) {
        end = moment(this.options.constraints.endDate);
      }
      // deal with the month controls first.
      // are we at the start month?
      if(start && this.month.isSame( start, 'month' )) {
        this.element.find('.' + this.options.targets.previousButton).toggleClass('inactive', true);
      }
      // are we at the end month?
      if(end && this.month.isSame( end, 'month' )) {
        this.element.find('.' + this.options.targets.nextButton).toggleClass('inactive', true);
      }
      // what's last year looking like?
      if(start && moment(start).subtract('years', 1).isBefore(moment(this.month).subtract('years', 1)) ) {
        this.element.find('.' + this.options.targets.previousYearButton).toggleClass('inactive', true);
      }
      // how about next year?
      if(end && moment(end).add('years', 1).isAfter(moment(this.month).add('years', 1)) ) {
        this.element.find('.' + this.options.targets.nextYearButton).toggleClass('inactive', true);
      }
      // today? we could put this in init(), but we want to support the user changing the constraints on a living instance.
      if(( start && start.isAfter( moment(), 'month' ) ) || ( end && end.isBefore( moment(), 'month' ) )) {
        this.element.find('.' + this.options.targets.today).toggleClass('inactive', true);
      }
    }

    if(this.options.doneRendering) {
      this.options.doneRendering.apply(this, []);
    }
  };

  Clndr.prototype.bindEvents = function() {
    var $container = $(this.element);
    var self = this;

    // target the day elements and give them click events
    $container.on('click', '.'+this.options.targets.day, function(event) {
      if(self.options.clickEvents.click) {
        var target = self.buildTargetObject(event.currentTarget, true);
        self.options.clickEvents.click.apply(self, [target]);
      }
      // if adjacentDaysChangeMonth is on, we need to change the month here.
      if(self.options.adjacentDaysChangeMonth) {
        if($(event.currentTarget).is(".last-month")) {
          self.backActionWithContext(self);
        } else if($(event.currentTarget).is(".next-month")) {
          self.forwardActionWithContext(self);
        }
      }
    });
    // target the empty calendar boxes as well
    $container.on('click', '.'+this.options.targets.empty, function(event) {
      if(self.options.clickEvents.click) {
        var target = self.buildTargetObject(event.currentTarget, false);
        self.options.clickEvents.click.apply(self, [target]);
      }
      if(self.options.adjacentDaysChangeMonth) {
        if($(event.currentTarget).is(".last-month")) {
          self.backActionWithContext(self);
        } else if($(event.currentTarget).is(".next-month")) {
          self.forwardActionWithContext(self);
        }
      }
    });

    // bind the previous, next and today buttons
    $container
      .on('click', '.'+this.options.targets.previousButton, { context: this }, this.backAction)
      .on('click', '.'+this.options.targets.nextButton, { context: this }, this.forwardAction)
      .on('click', '.'+this.options.targets.todayButton, { context: this }, this.todayAction)
      .on('click', '.'+this.options.targets.nextYearButton, { context: this }, this.nextYearAction)
      .on('click', '.'+this.options.targets.previousYearButton, { context: this }, this.previousYearAction);
  }

  // If the user provided a click callback we'd like to give them something nice to work with.
  // buildTargetObject takes the DOM element that was clicked and returns an object with
  // the DOM element, events, and the date (if the latter two exist). Currently it is based on the id,
  // however it'd be nice to use a data- attribute in the future.
  Clndr.prototype.buildTargetObject = function(currentTarget, targetWasDay) {
    // This is our default target object, assuming we hit an empty day with no events.
    var target = {
      element: currentTarget,
      events: [],
      date: null
    };
    // did we click on a day or just an empty box?
    if(targetWasDay) {
      var dateString;

      // Our identifier is in the list of classNames. Find it!
      var classNameIndex = currentTarget.className.indexOf('calendar-day-');
      if(classNameIndex !== 0) {
        // our unique identifier is always 23 characters long.
        // If this feels a little wonky, that's probably because it is.
        // Open to suggestions on how to improve this guy.
        dateString = currentTarget.className.substring(classNameIndex + 13, classNameIndex + 23);
        target.date = moment(dateString);
      } else {
        target.date = null;
      }

      // do we have events?
      if(this.options.events) {
        // are any of the events happening today?
        if(this.options.multiDayEvents) {
          target.events = $.makeArray( $(this.options.events).filter( function() {
            // filter the dates down to the ones that match.
            return ( ( target.date.isSame(this._clndrStartDateObject, 'day') || target.date.isAfter(this._clndrStartDateObject, 'day') ) &&
              ( target.date.isSame(this._clndrEndDateObject, 'day') || target.date.isBefore(this._clndrEndDateObject, 'day') ) );
          }) );
        } else {
          target.events = $.makeArray( $(this.options.events).filter( function() {
            // filter the dates down to the ones that match.
            return this._clndrDateObject.format('YYYY-MM-DD') == dateString;
          }) );
        }
      }
    }

    return target;
  }

  // the click handlers in bindEvents need a context, so these are wrappers
  // to the actual functions. Todo: better way to handle this?
  Clndr.prototype.forwardAction = function(event) {
    var self = event.data.context;
    self.forwardActionWithContext(self);
  };

  Clndr.prototype.backAction = function(event) {
    var self = event.data.context;
    self.backActionWithContext(self);
  };

  // These are called directly, except for in the bindEvent click handlers,
  // where forwardAction and backAction proxy to these guys.
  Clndr.prototype.backActionWithContext = function(self) {
    // before we do anything, check if there is an inactive class on the month control.
    // if it does, we want to return and take no action.
    if(self.element.find('.' + self.options.targets.previousButton).hasClass('inactive')) {
      return;
    }

    // is subtracting one month going to switch the year?
    var yearChanged = !self.month.isSame( moment(self.month).subtract('months', 1), 'year');
    self.month.subtract('months', 1);

    self.render();

    if(self.options.clickEvents.previousMonth) {
      self.options.clickEvents.previousMonth.apply( self, [moment(self.month)] );
    }
    if(self.options.clickEvents.onMonthChange) {
      self.options.clickEvents.onMonthChange.apply( self, [moment(self.month)] );
    }
    if(yearChanged) {
      if(self.options.clickEvents.onYearChange) {
        self.options.clickEvents.onYearChange.apply( self, [moment(self.month)] );
      }
    }
  };

  Clndr.prototype.forwardActionWithContext = function(self) {
    // before we do anything, check if there is an inactive class on the month control.
    // if it does, we want to return and take no action.
    if(self.element.find('.' + self.options.targets.nextButton).hasClass('inactive')) {
      return;
    }

    // is adding one month going to switch the year?
    var yearChanged = !self.month.isSame( moment(self.month).add('months', 1), 'year');
    self.month.add('months', 1);

    self.render();

    if(self.options.clickEvents.nextMonth) {
      self.options.clickEvents.nextMonth.apply(self, [moment(self.month)]);
    }
    if(self.options.clickEvents.onMonthChange) {
      self.options.clickEvents.onMonthChange.apply(self, [moment(self.month)]);
    }
    if(yearChanged) {
      if(self.options.clickEvents.onYearChange) {
        self.options.clickEvents.onYearChange.apply( self, [moment(self.month)] );
      }
    }
  };

  Clndr.prototype.todayAction = function(event) {
    var self = event.data.context;

    // did we switch months when the today button was hit?
    var monthChanged = !self.month.isSame(moment(), 'month');
    var yearChanged = !self.month.isSame(moment(), 'year');

    self.month = moment().startOf('month');

    // fire the today event handler regardless of whether the month changed.
    if(self.options.clickEvents.today) {
      self.options.clickEvents.today.apply( self, [moment(self.month)] );
    }

    if(monthChanged) {
      // no need to re-render if we didn't change months.
      self.render();

      self.month = moment();
      // fire the onMonthChange callback
      if(self.options.clickEvents.onMonthChange) {
        self.options.clickEvents.onMonthChange.apply( self, [moment(self.month)] );
      }
      // maybe fire the onYearChange callback?
      if(yearChanged) {
        if(self.options.clickEvents.onYearChange) {
          self.options.clickEvents.onYearChange.apply( self, [moment(self.month)] );
        }
      }
    }
  };

  Clndr.prototype.nextYearAction = function(event) {
    var self = event.data.context;
    // before we do anything, check if there is an inactive class on the month control.
    // if it does, we want to return and take no action.
    if(self.element.find('.' + self.options.targets.nextYearButton).hasClass('inactive')) {
      return;
    }

    self.month.add('years', 1);
    self.render();

    if(self.options.clickEvents.nextYear) {
      self.options.clickEvents.nextYear.apply( self, [moment(self.month)] );
    }
    if(self.options.clickEvents.onMonthChange) {
      self.options.clickEvents.onMonthChange.apply( self, [moment(self.month)] );
    }
    if(self.options.clickEvents.onYearChange) {
      self.options.clickEvents.onYearChange.apply( self, [moment(self.month)] );
    }
  };

  Clndr.prototype.previousYearAction = function(event) {
    var self = event.data.context;
    // before we do anything, check if there is an inactive class on the month control.
    // if it does, we want to return and take no action.
    if(self.element.find('.' + self.options.targets.previousYear).hasClass('inactive')) {
      return;
    }

    self.month.subtract('years', 1);
    self.render();

    if(self.options.clickEvents.previousYear) {
      self.options.clickEvents.previousYear.apply( self, [moment(self.month)] );
    }
    if(self.options.clickEvents.onMonthChange) {
      self.options.clickEvents.onMonthChange.apply( self, [moment(self.month)] );
    }
    if(self.options.clickEvents.onYearChange) {
      self.options.clickEvents.onYearChange.apply( self, [moment(self.month)] );
    }
  };

  Clndr.prototype.forward = function(options) {
    this.month.add('months', 1);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onMonthChange) {
        this.options.clickEvents.onMonthChange.apply( this, [moment(this.month)] );
      }

      // We entered a new year
      if (this.month.month() === 0 && this.options.clickEvents.onYearChange) {
        this.options.clickEvents.onYearChange.apply( this, [moment(this.month)] );
      }
    }

    return this;
  }

  Clndr.prototype.back = function(options) {
    this.month.subtract('months', 1);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onMonthChange) {
        this.options.clickEvents.onMonthChange.apply( this, [moment(this.month)] );
      }

      // We went all the way back to previous year
      if (this.month.month() === 11 && this.options.clickEvents.onYearChange) {
        this.options.clickEvents.onYearChange.apply( this, [moment(this.month)] );
      }
    }

    return this;
  }

  // alternate names for convenience
  Clndr.prototype.next = function(options) {
    this.forward(options);
    return this;
  }

  Clndr.prototype.previous = function(options) {
    this.back(options);
    return this;
  }

  Clndr.prototype.setMonth = function(newMonth, options) {
    // accepts 0 - 11 or a full/partial month name e.g. "Jan", "February", "Mar"
    this.month.month(newMonth);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onMonthChange) {
        this.options.clickEvents.onMonthChange.apply( this, [moment(this.month)] );
      }
    }
    return this;
  }

  Clndr.prototype.nextYear = function(options) {
    this.month.add('year', 1);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onYearChange) {
        this.options.clickEvents.onYearChange.apply( this, [moment(this.month)] );
      }
    }
    return this;
  }

  Clndr.prototype.previousYear = function(options) {
    this.month.subtract('year', 1);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onYearChange) {
        this.options.clickEvents.onYearChange.apply( this, [moment(this.month)] );
      }
    }
    return this;
  }

  Clndr.prototype.setYear = function(newYear, options) {
    this.month.year(newYear);
    this.render();
    if(options && options.withCallbacks) {
      if(this.options.clickEvents.onYearChange) {
        this.options.clickEvents.onYearChange.apply( this, [moment(this.month)] );
      }
    }
    return this;
  }

  Clndr.prototype.setEvents = function(events) {
    // go through each event and add a moment object
    if(this.options.multiDayEvents) {
      this.options.events = this.addMultiDayMomentObjectsToEvents(events);
    } else {
      this.options.events = this.addMomentObjectToEvents(events);
    }

    this.render();
    return this;
  };

  Clndr.prototype.addEvents = function(events) {
    // go through each event and add a moment object
    if(this.options.multiDayEvents) {
      this.options.events = $.merge(this.options.events, this.addMultiDayMomentObjectsToEvents(events));
    } else {
      this.options.events = $.merge(this.options.events, this.addMomentObjectToEvents(events));
    }

    this.render();
    return this;
  };

  Clndr.prototype.addMomentObjectToEvents = function(events) {
    var self = this;
    var i = 0, l = events.length;
    for(i; i < l; i++) {
      // stuff a _clndrDateObject in each event, which really, REALLY should not be
      // overriding any existing object... Man that would be weird.
      events[i]._clndrDateObject = moment( events[i][self.options.dateParameter] );
    }
    return events;
  }

  Clndr.prototype.addMultiDayMomentObjectsToEvents = function(events) {
    var self = this;
    var i = 0, l = events.length;
    for(i; i < l; i++) {
      events[i]._clndrStartDateObject = moment( events[i][self.options.multiDayEvents.startDate] );
      events[i]._clndrEndDateObject = moment( events[i][self.options.multiDayEvents.endDate] );
    }
    return events;
  }

  Clndr.prototype.calendarDay = function(options) {
    var defaults = { day: "", classes: this.options.targets.empty, events: [], date: null };
    return $.extend({}, defaults, options);
  }

  $.fn.clndr = function(options) {
    if( !$.data( this, 'plugin_clndr') ) {
      var clndr_instance = new Clndr(this, options);
      $.data(this, 'plugin_clndr', clndr_instance);
      return clndr_instance;
    }
  }

})( jQuery, window, document );


text:
var gmxVectorTileLoader = {
    _loadedTiles: {},
    _getKey: function(ti) {
        return [ti.layerID, ti.x, ti.y, ti.z, typeof ti.d === 'undefined' ? -1 : ti.d, typeof ti.s === 'undefined' ? -1 : ti.s, ti.v].join(':');
    },
    load: function(tileSenderPrefix, tileInfo) {
        var key = gmxVectorTileLoader._getKey(tileInfo);

        if (!this._loadedTiles[key]) {
            var def = new L.gmx.Deferred();
            this._loadedTiles[key] = def;

            var requestParams = {
                ModeKey: 'tile',
                r: 'j',
                LayerName: tileInfo.layerID,
                z: tileInfo.z,
                x: tileInfo.x,
                y: tileInfo.y,
                v: tileInfo.v
            };

            if (tileInfo.srs) {
                requestParams.srs = tileInfo.srs;
            }
            if (tileInfo.d !== -1) {
                requestParams.Level = tileInfo.d;
                requestParams.Span = tileInfo.s;
            }

            gmxAPIutils.requestJSONP(tileSenderPrefix, requestParams, {callbackParamName: null}).then(null, function() {
                def.reject();
            });
        }

        return this._loadedTiles[key];
    }
};

window.gmxAPI = window.gmxAPI || {};
window.gmxAPI._vectorTileReceiver = window.gmxAPI._vectorTileReceiver || function(data) {
    var key = gmxVectorTileLoader._getKey({
        layerID: data.LayerName,
        x: data.x,
        y: data.y,
        z: data.z,
        d: data.level,
        s: data.span,
        v: data.v
    });

    gmxVectorTileLoader._loadedTiles[key] && gmxVectorTileLoader._loadedTiles[key].resolve(data.values, data.bbox, data.srs, data.isGeneralized);
};


text:
package bitch.design.action.adapter;

/**
 * 方形桩 Target
 * @author chenhaipeng
 * @version 1.0
 * @date 2015/11/01 22:11
 */
public class SquarePeg {
    public void insert(String str){
        System.out.println("SquarePeg insert():"+str);
    }
}


text:
define(["dojo/_base/declare",
		"jimu/BaseWidgetPanel",
		"jimu/BaseWidgetFrame",
		"./PanelWrapper"
	], function(
		declare,
		BaseWidgetPanel,
		BaseWidgetFrame,
		PanelWrapper
		//By declaring BaseWidgetPanel with PanelWrapper, the frame will be contained in the
		//wrappers element with the data-dojo-attach-point="containerNode" attribute
	) { return declare([BaseWidgetPanel, PanelWrapper], {

		baseClass: "jimu-panel-floating",

		//INITIALIZATION///////////////////////////////////////////////////////////////////////////
		startup: function() {
			this.inherited(arguments);

			//Close the panel on close button click
			this.domNode.querySelector(".close").addEventListener("click", this.closePanel.bind(this));
		},

		//REMOVE LISTENERS ON DESTRUCTION//////////////////////////////////////////////////////////
		destroy: function() {
			this.domNode.querySelector(".close").removeEventListener("click", this.closePanel.bind(this));
		},

		//CLOSE THE PANEL ON BUTTON CLICK//////////////////////////////////////////////////////////
		closePanel: function() {
			this.panelManager.closePanel(this);
		},

		//SET LABEL WHEN A NEW WIDGET IS LOADED////////////////////////////////////////////////////
		reloadWidget: function(widgetConfig) {
			this.inherited(arguments);
			this.setTitleLabel(widgetConfig.label);
		},

		//UPDATE LABEL WHEN CONFIG CHANGED/////////////////////////////////////////////////////////
		updateConfig: function(config) {
			this.inherited(arguments);
			this.setTitleLabel(config.label);
		},

		//CREATE A NEW FRAME///////////////////////////////////////////////////////////////////////
		//This element will contain the widget and is called by BaseWidgetPanel
		createFrame: function(widgetConfig) {
			return new BaseWidgetFrame();
		}
	}); //End of declare
});


text:
using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace _04.MorseCodeUpgraded
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] message = Console.ReadLine().Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries).ToArray();

            long sum = 0L;
            string result = string.Empty;
            foreach (string code in message)
            {
                var zeroes = code.Where(a => a == char.Parse("0")).Count();
                int zeroesSum = zeroes * 3;
                var ones = code.Where(a => a == char.Parse("1")).Count();
                int onesSum = ones * 5;
                sum = zeroesSum + onesSum;
                int consecutiveDigitsSum = GetConsecutiveDigitsSum(code);
                if (consecutiveDigitsSum>= 1)
                {
                    sum += consecutiveDigitsSum;
                }
                result += (char)sum;
            }
            Console.WriteLine(result);
        }

        static int GetConsecutiveDigitsSum(string code)
        {
            string pattern = @"1{2,}|0{2,}";

            Regex regex = new Regex(pattern);

            MatchCollection matches = regex.Matches(code);
            int count = 0;
            foreach (Match match in matches)
            {
                count += match.Value.Length;
            }
            return count;
        }
    }
}


text:
var _ = require('lodash');
var ViewAbstract = require('../Abstract');

module.exports = ViewTextarea;

function ViewTextarea() {
    ViewAbstract.call(this);
    this.template = require('./textarea.html');
}

ViewTextarea.prototype = _.create(ViewAbstract.prototype, {
    constructor: ViewTextarea
});


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"

namespace content {

class ProcessInternalsWebUiBrowserTest : public ContentBrowserTest {};

// This test verifies that loading of the process-internals WebUI works
// correctly and the process rendering it has no WebUI bindings.
IN_PROC_BROWSER_TEST_F(ProcessInternalsWebUiBrowserTest, NoProcessBindings) {
  GURL url("chrome://process-internals/#web-contents");
  EXPECT_TRUE(NavigateToURL(shell(), url));

  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetMainFrame()->GetProcess()->GetID()));

  // Execute script to ensure the page has loaded correctly and was successful
  // at retrieving data from the browser process.
  // Note: This requires using an isolated world in which to execute the
  // script because WebUI has a default CSP policy denying "eval()", which is
  // what EvalJs uses under the hood.
  EXPECT_NE(-1,
            EvalJs(shell()->web_contents()->GetMainFrame(),
                   "document.body.innerHTML.search('Process Model Internals');",
                   EXECUTE_SCRIPT_DEFAULT_OPTIONS, 1 /* world_id */));
}

}  // namespace content


text:
package wmlove.learnandroid.AsyncLoad;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import wmlove.learnandroid.R;

/**
 * Created by Administrator on 2015/6/12.
 */
public class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener{
    private List<NewsBean> mNewsBeanList;
    private LayoutInflater mLayoutInflater;
    public static List<String> urls;
    private ImageLoader mImageLoader;
    private int mStart,mEnd;
    private boolean isFirst;

    public NewsAdapter(List<NewsBean> mNewsBeanList,Context context,ListView listView) {
        this.mNewsBeanList = mNewsBeanList;
        this.mLayoutInflater = LayoutInflater.from(context);
        this.urls = AsyncUtils.getUrls(mNewsBeanList);
        this.mImageLoader = new ImageLoader(listView);
        isFirst = true;
        listView.setOnScrollListener(this);
    }

    @Override
    public int getCount() {
        return mNewsBeanList.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertview, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if(convertview==null){
            convertview = mLayoutInflater.inflate(R.layout.item_news,null);
            viewHolder = new ViewHolder();
            viewHolder.tvTitle = (TextView) convertview.findViewById(R.id.tvTitle);
            viewHolder.tvContent = (TextView) convertview.findViewById(R.id.tvContent);
            viewHolder.ivIcon = (ImageView) convertview.findViewById(R.id.ivIcon);
            convertview.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertview.getTag();
        }
        viewHolder.tvTitle.setText(mNewsBeanList.get(position).name);
        viewHolder.tvContent.setText(mNewsBeanList.get(position).description);
        viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher);
        viewHolder.ivIcon.setTag(urls.get(position));
        mImageLoader.showImageByAsyncTask(viewHolder.ivIcon, urls.get(position));
        return convertview;
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            mImageLoader.loadImage(mStart,mEnd);
        }else{
            mImageLoader.cacheAllTasks();
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int start, int count, int totalcount) {
        mStart = start;
        mEnd = start + count;
        if(isFirst && count>0){
            mImageLoader.loadImage(mStart,mEnd);
            isFirst = false;
        }
    }

    class ViewHolder{
        public TextView tvTitle,tvContent;
        public ImageView ivIcon;
    }
}