text:
/* jslint node: true */
'use strict';

/**
* Creates an instance of StyleContextStack used for style inheritance and style overrides
*
* @constructor
* @this {StyleContextStack}
* @param {Object} named styles dictionary
* @param {Object} optional default style definition
*/
function StyleContextStack (styleDictionary, defaultStyle) {
	this.defaultStyle = defaultStyle || {};
	this.styleDictionary = styleDictionary;
	this.styleOverrides = [];
}

/**
* Creates cloned version of current stack
* @return {StyleContextStack} current stack snapshot
*/
StyleContextStack.prototype.clone = function() {
	var stack = new StyleContextStack(this.styleDictionary, this.defaultStyle);

	this.styleOverrides.forEach(function(item) {
		stack.styleOverrides.push(item);
	});

	return stack;
};

/**
* Pushes style-name or style-overrides-object onto the stack for future evaluation
*
* @param {String|Object} styleNameOrOverride style-name (referring to styleDictionary) or
*                                            a new dictionary defining overriding properties
*/
StyleContextStack.prototype.push = function(styleNameOrOverride) {
	this.styleOverrides.push(styleNameOrOverride);
};

/**
* Removes last style-name or style-overrides-object from the stack
*
* @param {Number} howMany - optional number of elements to be popped (if not specified,
*                           one element will be removed from the stack)
*/
StyleContextStack.prototype.pop = function(howMany) {
	howMany = howMany || 1;

	while(howMany-- > 0) {
		this.styleOverrides.pop();
	}
};

/**
* Creates a set of named styles or/and a style-overrides-object based on the item,
* pushes those elements onto the stack for future evaluation and returns the number
* of elements pushed, so they can be easily poped then.
*
* @param {Object} item - an object with optional style property and/or style overrides
* @return the number of items pushed onto the stack
*/
StyleContextStack.prototype.autopush = function(item) {
	if (typeof item === 'string' || item instanceof String) return 0;

	var styleNames = [];

	if (item.style) {
		if (item.style instanceof Array) {
			styleNames = item.style;
		} else {
			styleNames = [ item.style ];
		}
	}

	for(var i = 0, l = styleNames.length; i < l; i++) {
		this.push(styleNames[i]);
	}

	var styleOverrideObject = {};
	var pushSOO = false;

	[
		'font',
		'fontSize',
		'bold',
		'italics',
		'alignment',
		'color',
		'columnGap',
		'fillColor',
		'decoration',
		'decorationStyle',
		'decorationColor',
		'background',
		'lineHeight',
		'noWrap'
		//'tableCellPadding'
		// 'cellBorder',
		// 'headerCellBorder',
		// 'oddRowCellBorder',
		// 'evenRowCellBorder',
		// 'tableBorder'
	].forEach(function(key) {
		if (item[key] !== undefined && item[key] !== null) {
			styleOverrideObject[key] = item[key];
			pushSOO = true;
		}
	});

	if (pushSOO) {
		this.push(styleOverrideObject);
	}

	return styleNames.length + (pushSOO ? 1 : 0);
};

/**
* Automatically pushes elements onto the stack, using autopush based on item,
* executes callback and then pops elements back. Returns value returned by callback
*
* @param  {Object}   item - an object with optional style property and/or style overrides
* @param  {Function} function to be called between autopush and pop
* @return {Object} value returned by callback
*/
StyleContextStack.prototype.auto = function(item, callback) {
	var pushedItems = this.autopush(item);
	var result = callback();

	if (pushedItems > 0) {
		this.pop(pushedItems);
	}

	return result;
};

/**
* Evaluates stack and returns value of a named property
*
* @param {String} property - property name
* @return property value or null if not found
*/
StyleContextStack.prototype.getProperty = function(property) {
	if (this.styleOverrides) {
		for(var i = this.styleOverrides.length - 1; i >= 0; i--) {
			var item = this.styleOverrides[i];

			if (typeof item == 'string' || item instanceof String) {
				// named-style-override

				var style = this.styleDictionary[item];
				if (style && style[property] !== null && style[property] !== undefined) {
					return style[property];
				}
			} else {
				// style-overrides-object
				if (item[property] !== undefined && item[property] !== null) {
					return item[property];
				}
			}
		}
	}

	return this.defaultStyle && this.defaultStyle[property];
};

module.exports = StyleContextStack;


text:
<resources>
    <string name="app_name">手机卫士</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<?php slot('body_id') ?>body_links<?php end_slot() ?>
<?php slot('page_header') ?><?php echo __('Links') ?><?php end_slot() ?>

<?php include_component('text', 'show', array('id'=>4)); ?>


text:
using Dot42;
using Dot42.Internal;
using Java.Lang;
using Java.Text;
using Java.Util;

namespace System.Text
{
	partial class StringBuilder
	{
        /// <summary>
        /// Initialize a new instance with given initial and maximum capacity.
        /// </summary>
        /// <remarks>
        /// The maximum capacity is not used in this implementation.</remarks>
        /// <param name="capacity"></param>
        /// <param name="maxCapacity"></param>
        public StringBuilder(int capacity, int maxCapacity)
            : this(capacity)
        {
            if ((maxCapacity < 1) || (capacity < 1) || (capacity > maxCapacity))
                throw new ArgumentOutOfRangeException();
        }

        /// <summary>
        /// Initialize a new instance with given initial value and capacity.
        /// </summary>
        public StringBuilder(string value, int capacity)
            : this(capacity)
        {
            if (capacity < 0)
                throw new ArgumentOutOfRangeException();
            Append(value);
        }

        /// <summary>
        /// Initialize a new instance with given substring of the given value and capacity.
        /// </summary>
        public StringBuilder(string value, int startIndex, int length, int capacity)
            : this(capacity)
        {
            if (capacity < 0)
                throw new ArgumentOutOfRangeException();
            if (value != null)
            {
                if ((startIndex < 0) || (length < 0) || (startIndex + length > value.Length))
                    throw new ArgumentOutOfRangeException();
                JavaAppend(value, startIndex, startIndex + length);
            }
        }

        /// <summary>
        /// Append a given number of the given characters.
        /// </summary>
        public StringBuilder Append(char value, int repeatCount)
        {
            // TODO: check if the allocation is more expensive than a simple while loop
            char[] append = new char[repeatCount];
            Arrays.Fill(append, value);
            Append(append);
            return this;
        }

        /// <summary>
        /// Append a substring of the given string from into this builder.
        /// </summary>
        [Inline]
        public StringBuilder Append(string value, int startIndex, int count)
        {
            JavaAppend(value, startIndex, startIndex + count);
            return this;
        }

        /// <summary>
        /// Append a substring of the given string from into this builder.
        /// </summary>
        public StringBuilder AppendFormat(string format, params object[] args)
        {
            Append(string.Format(format, args));
            return this;
        }

        /// <summary>
        /// Appends the default line terminator to the end of the current StringBuilder object.
        /// </summary>
	    public StringBuilder AppendLine()
	    {
	        return Append(Environment.NewLine);
	    }

        /// <summary>
        /// Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
	    public StringBuilder AppendLine(string value)
        {
            Append(value);
            return AppendLine();
        }

        /// <summary>
        /// Insert the one or more copies of the given string at the given index in this string builder.
        /// </summary>
        public StringBuilder Insert(int index, string value, int count)
        {
            var length = value.Length;
            while (count > 0)
            {
                JavaInsert(index, value, 0, length);
                count--;
            }
            return this;
        }

        /// <summary>
        /// Remove length characters from this string builder, starting at the given start index.
        /// </summary>
        [Inline]
        public StringBuilder Remove(int startIndex, int length)
        {
            JavaDelete(startIndex, startIndex + length);
            return this;
        }

        /// <summary>
        /// Replace all occurrences of the given old character with the given new character.
        /// </summary>
        public StringBuilder Replace(char oldChar, char newChar)
        {
            var length = Length;
            for (var i = 0; i < length; i++)
            {
                if (this[i] == oldChar)
                {
                    SetCharAt(i, newChar);
                }
            }
            return this;
        }

        /// <summary>
        /// Replace all occurrences of the given old character with the given new character.
        /// </summary>
        public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
        {
            if (startIndex < 0)
                throw new ArgumentOutOfRangeException("startIndex");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count");
            if (startIndex + count > Length)
                throw new ArgumentOutOfRangeException("overflow");
            for (var i = 0; i < count; i++)
            {
                if (this[startIndex + i] == oldChar)
                {
                    SetCharAt(startIndex + i, newChar);
                }
            }
            return this;
        }

        /// <summary>
        /// Replace all occurrences of the given old string with the given new string.
        /// </summary>
        public StringBuilder Replace(string oldValue, string newValue)
        {
            if (oldValue == null)
                throw new ArgumentNullException("oldValue");
            if (oldValue.Length == 0)
                throw new ArgumentException("oldValue is empty");
            var start = 0;
            int index;
            while ((index = IndexOf(oldValue, start)) >= 0)
            {
                Remove(index, oldValue.Length);
                start = index;
                if (!string.IsNullOrEmpty(newValue))
                {
                    Insert(index, newValue);
                    start += newValue.Length;
                }
            }
            return this;
        }

        /// <summary>
        /// Replace all occurrences of the given old string with the given new string.
        /// </summary>
        public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count)
        {
            if (oldValue == null)
                throw new ArgumentNullException("oldValue");
            if (oldValue.Length == 0)
                throw new ArgumentException("oldValue is empty");
            if (startIndex < 0)
                throw new ArgumentOutOfRangeException("startIndex");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count");
            if ((startIndex + count > Length) || (startIndex + count < 0))
                throw new ArgumentOutOfRangeException("overflow");
            var start = startIndex;
            int index;
            while ((index = IndexOf(oldValue, start)) >= 0)
            {
                if (index >= startIndex + count)
                    break;
                Remove(index, oldValue.Length);
                start = index;
                if (!string.IsNullOrEmpty(newValue))
                {
                    Insert(index, newValue);
                    start += newValue.Length;
                }
            }
            return this;
        }

        /// <summary>
        /// Gets the maximum capacity of this builder.
        /// </summary>
	    public int MaxCapacity
	    {
            get { return int.MaxValue; }
	    }

        /// <summary>
        /// Return a substring of this instance.
        /// </summary>
        public string ToString(int startIndex, int length)
        {
            if (startIndex < 0)
                throw new ArgumentOutOfRangeException("startIndex");
            if (length < 0)
                throw new ArgumentOutOfRangeException("length");
            if ((startIndex + length > Length) || (startIndex + length < 0))
                throw new ArgumentOutOfRangeException("overflow");
            return JavaSubstring(startIndex, startIndex + length);
        }

        /// <summary>
        /// Returns the number of chars in this string.
        /// </summary>
        public int Length
        {
            [Dot42.DexImport("length", "()I", AccessFlags = 257)]
            get { return default(int); }
            [Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
            set { }
        }

        /// <summary>
        ///  Returns the char at index.
        /// </summary>
        [global::System.Runtime.CompilerServices.IndexerName("Chars")]
        public char this[int index]
        {
            [Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)]
            get { return default(char); }
            [Dot42.DexImport("setCharAt", "(IC)V", AccessFlags = 1)]
            set { }
        }
    }
}


text:
var pkg = require('./package.json');
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglifyjs');
var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var htmlmin = require('gulp-htmlmin');
var templateCache = require('gulp-angular-templatecache');
var livereload = require('gulp-livereload');

// Check programming styles
gulp.task('jshint', function(){
  return gulp.src('app/**/*.js')
            .pipe(jshint())
            .pipe(jshint.reporter('jshint-stylish'))
  ;
});

/*
 * Outputs a compiled file name in format:
   * 'to create a js compiled file named *
    * '../public/js/v1/<%= pkg.name %>-<%= type %>-<%= pkg.version %>.min.js':
 */
function compiledFileName(type, suffix){
  return pkg.name + '-' + type + '-' + pkg.version + suffix;
}
function ecUglify(src, type){
  var result = compiledFileName(type, '.min.js');
  return gulp.src(src)
            //.pipe(uglify(result, {
            //    outSourceMap: true
            //  }))
            .pipe(concat(result, {newLine: ';'}))
            .pipe(gulp.dest('../public/v1/js'))
            .pipe(livereload())
  ;
}

gulp.task('js:app', function(){
  var src = [
    'app/**/*.module.js',
    'app/app.js',
    'app/app.route.js',
    'app/**/*.js',
    '!app/**/*.spec.js'
  ];
  return ecUglify(src, 'app');
});

gulp.task('js:vendor', function(){

  var src = [
    'bower_components/angular/angular.min.js',
    'bower_components/angular-animate/angular-animate.min.js',
    'bower_components/angular-cookies/angular-cookies.min.js',
    'bower_components/angular-cookie/angular-cookie.min.js',
    'bower_components/ng-token-auth/dist/ng-token-auth.min.js',
    'bower_components/angular-ui-router/release/angular-ui-router.min.js',
    //'bower_components/angular-bootstrap/ui-bootstrap.min.js',
    'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
    'bower_components/lodash/dist/lodash.min.js',
    'bower_components/restangular/dist/restangular.min.js',
    //'bower_components/angular-toastr/dist/angular-toastr.min.js',
    'bower_components/angular-toastr/dist/angular-toastr.tpls.min.js',
    'bower_components/angular-loading-bar/build/loading-bar.min.js',
    'bower_components/angular-scroll/angular-scroll.min.js'
  ];
  return ecUglify(src, 'vendor');
});

gulp.task('css:vendor', function(){
  var result = compiledFileName('vendor', '.min.css');
  var src = [
    'bower_components/bootstrap/dist/css/bootstrap.min.css',
    'bower_components/animate.css/animate.min.css',
    'bower_components/angular-toastr/dist/angular-toastr.min.css',
    'bower_components/angular-loading-bar/build/loading-bar.min.css'
  ];

  return gulp.src(src)
      .pipe(concat(result))
      .pipe(gulp.dest('../public/v1/css'))
  ;
});

gulp.task('css:vendor', function(){
  var result = compiledFileName('vendor', '.min.css');
  var src = [
    'bower_components/bootstrap/dist/css/bootstrap.min.css',
    'bower_components/animate.css/animate.min.css',
    'bower_components/angular-toastr/dist/angular-toastr.min.css',
    'bower_components/angular-loading-bar/build/loading-bar.min.css'
  ];

  return gulp.src(src)
      .pipe(concat(result))
      .pipe(gulp.dest('../public/v1/css'));
});

gulp.task('css:app', function(){
  var result = compiledFileName('app', '.css');
  return gulp.src('app/**/*.css')
          .pipe(concatCss(result))
          .pipe(gulp.dest('../public/v1/css'))
          .pipe(livereload())
  ;
});

gulp.task('html', function(){
  return gulp.src('app/**/*.html')
            .pipe(htmlmin({collapseWhitespace:true}))
            .pipe(templateCache({
                    filename: compiledFileName('templates', '.js'),
                    root: 'app/',
                    module: pkg.name
            }))
            .pipe(gulp.dest('../public/v1/js'))
            .pipe(livereload())
  ;
});

gulp.task('watch', function(){
  // start the livereload server
  livereload.listen();

  // watch for changes to templates
  gulp.watch(['../public/v1/*.html', 'app/**/*.html'], ['html']);

  // watch for changes to js
  gulp.watch(['app/**/*.js'], ['js:app']);

  // watch for changes to css
  gulp.watch(['app/**/*.css'], ['css:app']);

  livereload();
});

gulp.task('build', ['js:vendor', 'js:app', 'css:vendor', 'css:app', 'html', 'jshint']);
gulp.task('default', ['build', 'watch']);

// TODO check out gulp-bump


text:
package com.normation.ldap.sdk

import com.unboundid.ldap.sdk.{DN,Attribute}
import com.unboundid.ldap.sdk.schema.Schema
import com.normation.exceptions.TechnicalException
import scala.collection.JavaConversions.asSet
import com.normation.utils.HashcodeCaching

/**
 * LDAP syntax
 *
 */
sealed trait TypedAttribute {
  val name:String
}
case class BooleanAttribute(name:String,value:List[Boolean]) extends TypedAttribute with HashcodeCaching
case class LongAttribute(name:String,values:List[Long]) extends TypedAttribute with HashcodeCaching
case class DNAttribute(name:String,values: List[DN]) extends TypedAttribute with HashcodeCaching
case class StringAttribute(name:String,values:List[String]) extends TypedAttribute with HashcodeCaching
case class BinaryAttribute(name:String,values: List[Array[Byte]]) extends TypedAttribute with HashcodeCaching
case class GeneralizedTimeAttribute(name:String,values:List[GeneralizedTime]) extends TypedAttribute with HashcodeCaching

object TypedAttribute {

  private def toBoolean(s:String) : Boolean = s.toLowerCase match {
    case "true"  | "t" | "yes" | "y" | "on"  | "1" => true
    case "false" | "f" | "no"  | "n" | "off" | "0" => false
    case x => throw new TechnicalException("Can not interpret %s as a boolean value".format(x))
  }

  def apply(attribute:Attribute)(implicit schema:Schema) : TypedAttribute = {

    schema.getAttributeType(attribute.getName) match {
      case null =>
        StringAttribute(attribute.getName,attribute.getValues.toList)
      case attrDef => attrDef.getSyntaxOID(schema) match {
        case null => StringAttribute(attribute.getName,attribute.getValues.toList)
        case oid => schema.getAttributeSyntax(oid) match {
          case null =>
            StringAttribute(attribute.getName,attribute.getValues.toList)
          case syntaxDef => syntaxDef.getOID match {
            case "1.3.6.1.4.1.1466.115.121.1.7" => //boolean
              BooleanAttribute(attribute.getName,attribute.getValues.map(v => toBoolean(v)).toList)
            case "1.3.6.1.4.1.1466.115.121.1.41" => // Postal addr.
              StringAttribute(attribute.getName,attribute.getValues.toList)
            case "1.3.6.1.4.1.1466.115.121.1.12" |
                 "1.3.6.1.4.1.1466.115.121.1.34" => // name&optional UID
              DNAttribute(attribute.getName,attribute.getValues.map(v => new DN(v)).toList)
            case "1.3.6.1.4.1.1466.115.121.1.24" |
                 "1.3.6.1.4.1.1466.115.121.1.53" =>  // UTC time
              GeneralizedTimeAttribute(attribute.getName,attribute.getValues.map(v => GeneralizedTime(v)).toList)
            case "1.3.6.1.4.1.1466.115.121.1.27" => // Integer
              LongAttribute(attribute.getName,attribute.getValues.map(v => v.toLong).toList)
            case "1.3.6.1.4.1.1466.115.121.1.36" => // numeric
              StringAttribute(attribute.getName,attribute.getValues.toList)
            case "1.3.6.1.4.1.4203.1.1.2" | // auth password
                 "1.3.6.1.4.1.1466.115.121.1.5" | // binary
                 "1.3.6.1.4.1.1466.115.121.1.8" | // certificate
                 "1.3.6.1.4.1.1466.115.121.1.9" | // cert list
                 "1.3.6.1.4.1.1466.115.121.1.10" | // cert pair
                 "1.3.6.1.4.1.1466.115.121.1.28" | // JPEG
                 "1.3.6.1.4.1.1466.115.121.1.40" => // octet string
             BinaryAttribute(attribute.getName,attribute.getRawValues.map(v => v.getValue).toList)
            case "1.3.6.1.4.1.1466.115.121.1.50" => //telephone number
             StringAttribute(attribute.getName,attribute.getValues.toList)
            case _ => //other are mapped as string
             StringAttribute(attribute.getName,attribute.getValues.toList)
          }
        }
      }
    }
  }
}


text:
/*
 * App
 *
 * @module app
 */

'use strict';

var React = require('react');
var async = require('async');
var debug = require('debug')('BrewUI:app');

var Context = require('./lib/Context');
var Application = React.createFactory(require('./components/Application.jsx'));
var routes = require('./config/routes');

var readBrewAction = require('./actions/brew/readBrew');
var findBrewLogAction = require('./actions/logs/findBrew');
var findOneBrewLogAction = require('./actions/logs/findOneBrew');

// Register stores
Context.registerStore(require('./stores/ApplicationStore'));
Context.registerStore(require('./stores/BrewStore'));
Context.registerStore(require('./stores/BrewerStore'));
Context.registerStore(require('./stores/LogStore'));

/*
 * App
 *
 * @constructor App
 * @param {Object} initialState
 *
 */
function App(options) {
  options = options || {};

  var initialState = options.initialState;
  var fetcher = options.fetcher;

  debug('Creating context');
  this.context = new Context({
    routes: routes,
    fetcher: fetcher
  });

  if (initialState) {
    debug('rehydrating context');
    this.context.rehydrate(initialState);
  }
}

/*
 * Initialise
 *
 * @method init
 * @return {Promise}
 */
App.prototype.init = function () {
  var _this = this;

  debug('Initialise application');

  return new Promise(function (resolve, reject) {
    var actionContext = _this.context.getActionContext();

    // Load store data
    async.parallel({

      // Load brew
      brew: function loadBrew(cb) {
        actionContext.executeAction(readBrewAction, {}, cb);
      },

      // Load log
      log: function loadLog (logCb) {
        var LogStore = actionContext.getStore('LogStore');

        // Do not get logs when it's already loaded
        if(LogStore.brewLogs.length) {
          return logCb();
        }

        async.waterfall([

          // Find brew logs
          function findLogs(cb) {
            actionContext.executeAction(findBrewLogAction, {}, cb);
          },

          // Find selected brew
          function findOneLog(brews, cb) {
            if(!brews.length) {
              return cb();
            }

            actionContext.executeAction(findOneBrewLogAction, { id: brews[0]._id }, cb);
          }

        ], logCb);
      }
    }, function (err) {
      if(err) {
        return reject(err);
      }

      resolve();
    });
  });
};

/*
 * Get component
 *
 * @method getComponent
 * @return {Object}
 */
App.prototype.getComponent = function () {
  debug('Creating Application component');

  // Ignore because JSX
  var appComponent = Application({                      // jshint ignore:line
    context: this.context.getComponentContext()
  });

  debug('Rendering Application component');

  return appComponent;
};

/*
 * Get context
 *
 * @method getContext
 * @return {Object}
 */
App.prototype.getActionContext = function () {
  return this.context.getActionContext();
};

module.exports = App;


text:
package com.limitx.base;

/**
 * Created by root on 2018/1/23.
 */

public interface BaseView<T> {

    void setPresenter(T presenter);

}


text:
package org.simpleframework.xml.util;

import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * This is used to store Match objects, which can then be
 * retrieved using a string by comparing that string to the pattern of
 * the Match objects. Patterns consist of characters
 * with either the '*' or '?' characters as wild characters. The '*'
 * character is completely wild meaning that is will match nothing or
 * a long sequence of characters. The '?' character matches a single
 * character.
 *

 * If the '?' character immediately follows the '*' character then the
 * match is made as any sequence of characters up to the first match
 * of the next character. For example "/*?/index.jsp" will match all
 * files preceeded by only a single path. So "/pub/index.jsp" will
 * match, however "/pub/bin/index.jsp" will not, as it has two paths.
 * So, in effect the '*?' sequence will match anything or nothing up
 * to the first occurence of the next character in the pattern.
 *

 * A design goal of the Resolver was to make it capable
 * of  high performance. In order to achieve a high performance the
 * Resolver can cache the resolutions it makes so that if
 * the same text is given to the Resolver.resolve method
 * a cached result can be retrived quickly which will decrease the
 * length of time and work required to perform the match.
 *

 * The semantics of the resolver are such that the last pattern added
 * with a wild string is the first one checked for a match. This means
 * that if a sequence of insertions like add(x) followed
 * by add(y) is made, then a resolve(z) will
 * result in a comparison to y first and then x, if z matches y then
 * it is given as the result and if z does not match y and matches x
 * then x is returned, remember if z matches both x and y then y will
 * be the result due to the fact that is was the last pattern added.
 *
 * @author Niall Gallagher
 */
public class Resolver<M extends Match> extends AbstractSet<M> {

   /**
    * Caches the text resolutions made to reduce the work required.
    */
   protected final Cache cache;

   /**
    * Stores the matches added to the resolver in resolution order.
    */
   protected final Stack stack;

   /**
    * The default constructor will create a Resolver
    * without a large cache size. This is intended for use when
    * the requests for resolve tend to use strings
    * that are reasonably similar. If the strings issued to this
    * instance are dramatically different then the cache tends
    * to be an overhead rather than a bonus.
    */
   public Resolver(){
      this.stack = new Stack();
      this.cache = new Cache();
   }

   /**
    * This will search the patterns in this Resolver to
    * see if there is a pattern in it that matches the string given.
    * This will search the patterns from the last entered pattern to
    * the first entered. So that the last entered patterns are the
    * most searched patterns and will resolve it first if it matches.
    *
    * @param text this is the string that is to be matched by this
    *
    * @return this will return the first match within the resolver
    */
   public M resolve(String text){
      List<M> list = cache.get(text);

      if(list == null) {
         list = resolveAll(text);
      }
      if(list.isEmpty()) {
         return null;
      }
      return list.get(0);
   }

   /**
    * This will search the patterns in this Resolver to
    * see if there is a pattern in it that matches the string given.
    * This will search the patterns from the last entered pattern to
    * the first entered. So that the last entered patterns are the
    * most searched patterns and will resolve it first if it matches.
    *
    * @param text this is the string that is to be matched by this
    *
    * @return this will return all of the matches within the resolver
    */
   public List<M> resolveAll(String text){
      List<M> list = cache.get(text);

      if(list != null) {
         return list;
      }
      char[] array = text.toCharArray();

      if(array == null) {
         return null;
      }
      return resolveAll(text, array);
   }

   /**
    * This will search the patterns in this Resolver to
    * see if there is a pattern in it that matches the string given.
    * This will search the patterns from the last entered pattern to
    * the first entered. So that the last entered patterns are the
    * most searched patterns and will resolve it first if it matches.
    *
    * @param text this is the string that is to be matched by this
    * @param array this is the character array of the text string
    *
    * @return this will return all of the matches within the resolver
    */
   private List<M> resolveAll(String text, char[] array){
      List<M> list = new ArrayList<M>();

      for(M match : stack) {
         String wild = match.getPattern();

         if(match(array, wild.toCharArray())){
            cache.put(text, list);
            list.add(match);
         }
      }
      return list;
   }

   /**
    * This inserts the Match implementation into the set
    * so that it can be used for resolutions. The last added match is
    * the first resolved. Because this changes the state of the
    * resolver this clears the cache as it may affect resolutions.
    *
    * @param match this is the match that is to be inserted to this
    *
    * @return returns true if the addition succeeded, always true
    */
   public boolean add(M match) {
      stack.push(match);
      return true;
   }

   /**
    * This returns an Iterator that iterates over the
    * matches in insertion order. So the first match added is the
    * first retrieved from the Iterator. This order is
    * used to ensure that resolver can be serialized properly.
    *
    * @return returns an iterator for the sequence of insertion
    */
   public Iterator<M> iterator() {
      return stack.sequence();
   }

   /**
    * This is used to remove the Match implementation
    * from the resolver. This clears the cache as the removal of
    * a match may affect the resoultions existing in the cache. The
    * equals method of the match must be implemented.
    *
    * @param match this is the match that is to be removed
    *
    * @return true of the removal of the match was successful
    */
   public boolean remove(M match) {
      cache.clear();
      return stack.remove(match);
   }

   /**
    * Returns the number of matches that have been inserted into
    * the Resolver. Although this is a set, it does
    * not mean that matches cannot used the same pattern string.
    *
    * @return this returns the number of matches within the set
    */
   public int size() {
      return stack.size();
   }

   /**
    * This is used to clear all matches from the set. This ensures
    * that the resolver contains no matches and that the resolution
    * cache is cleared. This is used to that the set can be reused
    * and have new pattern matches inserted into it for resolution.
    */
   public void clear() {
      cache.clear();
      stack.clear();
   }

   /**
    * This acts as a driver to the match method so that
    * the offsets can be used as zeros for the start of matching for
    * the match(char[],int,char[],int). method. This is
    * also used as the initializing driver for the recursive method.
    *
    * @param text this is the buffer that is to be resolved
    * @param wild this is the pattern that will be used
    */
   private boolean match(char[] text, char[] wild){
      return match(text, 0, wild, 0);
   }

   /**
    * This will be used to check to see if a certain buffer matches
    * the pattern if it does then it returns true. This
    * is a recursive method that will attempt to match the buffers
    * based on the wild characters '?' and '*'. If there is a match
    * then this returns true.
    *
    * @param text this is the buffer that is to be resolved
    * @param off this is the read offset for the text buffer
    * @param wild this is the pattern that will be used
    * @param pos this is the read offset for the wild buffer
    */
   private boolean match(char[] text, int off, char[] wild, int pos){
      while(pos < wild.length && off < text.length){ /* examine chars */
         if(wild[pos] == '*'){
            while(wild[pos] == '*'){ /* totally wild */
               if(++pos >= wild.length) /* if finished */
                  return true;
            }
            if(wild[pos] == '?') { /* *? is special */
               if(++pos >= wild.length)
                  return true;
            }
            for(; off < text.length; off++){ /* find next matching char */
               if(text[off] == wild[pos] || wild[pos] == '?'){ /* match */
                  if(wild[pos - 1] != '?'){
                     if(match(text, off, wild, pos))
                        return true;
                  } else {
                     break;
                  }
               }
            }
            if(text.length == off)
               return false;
         }
         if(text[off++] != wild[pos++]){
            if(wild[pos-1] != '?')
               return false; /* if not equal */
         }
      }
      if(wild.length == pos){ /* if wild is finished */
          return text.length == off; /* is text finished */
      }
      while(wild[pos] == '*'){ /* ends in all stars */
         if(++pos >= wild.length) /* if finished */
            return true;
      }
      return false;
   }

   /**
    * This is used to cache resolutions made so that the matches can
    * be acquired the next time without performing the resolution.
    * This is an LRU cache so regardless of the number of resolutions
    * made this will not result in a memory leak for the resolver.
    *
    * @author Niall Gallagher
    */
   private class Cache extends LimitedCache<List<M>> {

      /**
       * Constructor for the Cache object. This is a
       * constructor that creates the linked hash map such that
       * it will purge the entries that are oldest within the map.
       */
      public Cache() {
         super(1024);
      }
   }

   /**
    * This is used to store the Match implementations in
    * resolution order. Resolving the match objects is performed so
    * that the last inserted match object is the first used in the
    * resolution process. This gives priority to the last inserted.
    *
    * @author Niall Gallagher
    */
   private class Stack extends LinkedList<M> {

      /**
       * The push method is used to push the match to
       * the top of the stack. This also ensures that the cache is
       * cleared so the semantics of the resolver are not affected.
       *
       * @param match this is the match to be inserted to the stack
       */
      public void push(M match) {
         cache.clear();
         addFirst(match);
      }

      /**
       * The purge method is used to purge a match from
       * the provided position. This also ensures that the cache is
       * cleared so that the semantics of the resolver do not change.
       *
       * @param index the index of the match that is to be removed
       */
      public void purge(int index) {
         cache.clear();
         remove(index);
      }

      /**
       * This is returned from the Resolver.iterator so
       * that matches can be iterated in insertion order. When a
       * match is removed from this iterator then it clears the cache
       * and removed the match from the Stack object.
       *
       * @return returns an iterator to iterate in insertion order
       */
      public Iterator<M> sequence() {
         return new Sequence();
      }

      /**
       * The is used to order the Match objects in the
       * insertion order. Iterating in insertion order allows the
       * resolver object to be serialized and deserialized to and
       * from an XML document without disruption resolution order.
       *
       * @author Niall Gallagher
       */
      private class Sequence implements Iterator<M> {

         /**
          * The cursor used to acquire objects from the stack.
          */
         private int cursor;

         /**
          * Constructor for the Sequence object. This is
          * used to position the cursor at the end of the list so the
          * first inserted match is the first returned from this.
          */
         public Sequence() {
            this.cursor = size();
         }

         /**
          * This returns the Match object at the cursor
          * position. If the cursor has reached the start of the
          * list then this returns null instead of the first match.
          *
          * @return this returns the match from the cursor position
          */
         public M next() {
            if(hasNext()) {
                return get(--cursor);
            }
            return null;
         }

         /**
          * This is used to determine if the cursor has reached the
          * start of the list. When the cursor reaches the start of
          * the list then this method returns false.
          *
          * @return this returns true if there are more matches left
          */
         public boolean hasNext() {
            return cursor > 0;
         }

         /**
          * Removes the match from the cursor position. This also
          * ensures that the cache is cleared so that resolutions
          * made before the removal do not affect the semantics.
          */
         public void remove() {
            purge(cursor);
         }
      }
   }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>jQuery plugin: Tablesorter 2.0 - Custom Filter Widget Search Types</title>

	<link class="ui-theme" rel="stylesheet" href="css/jquery-ui.min.css">

	<link rel="stylesheet" href="css/jq.css">
	<link href="css/prettify.css" rel="stylesheet">

	<link rel="stylesheet" href="../css/theme.blue.css">

tablesorter

Custom Filter Widget Search Types

Flexible client-side table sorting

	Back to documentation

Notes

This demo was added in v2.17.5, but modification using these instructions works for v2.13.3+; when the filter widget was restructured to allow the adding of custom filter search types.

In this demo, two additional search types have been added as an example

Start a search from beginning of the content using the ^ designator.

Search for a specific ending in the content using the $ designator.

Please review the following sections for more details.

Built-in Filters

				The built-in filter search types include:

Priority	Type	Designator	Function

1	regex	/./mig	$.tablesorter.filter.types.regex

2	operators	< <= >= >	$.tablesorter.filter.types.operators

3	not	! or !=	$.tablesorter.filter.types.notMatch

4	exact	" or =	$.tablesorter.filter.types.exact

5	and	 &&  or  and 	$.tablesorter.filter.types.and

6	range	 -  or  to 	$.tablesorter.filter.types.range

7	wild	* or ?	$.tablesorter.filter.types.wild

7	or	| or  or 	$.tablesorter.filter.types.wild (built-into wild)

8	fuzzy	~	$.tablesorter.filter.types.fuzzy

How to add Custom filter types

The first step is to decide what you want your filter to do.

Should it look for a symbol at the beginning, middle or end of the filter?

Does the designator need spaces around it (e.g. " and " or " or ") to prevent problems? You wouldn't be able to find the country of "Andorra" if the "and" or "or" designators didn't require spaces.

Make sure to name your filter so that it doesn't interfere with already existing ones, unless your filter is meant to replace an existing one. See the "Built-in Filters" section for a full list of filter function names.

Within your filter, first test for your designator symbol.

If it exists within the filter, then do your comparison and return a boolean of true or false.

Four arguments are passed to the filter function:

filter - The exact text from the filter input (e.g. ^h).

iFilter - The text from the filter in all lower case for case insensitive searches.

exact - The exact (or parsed) text from the current table cell; the parsed text is passed when the column has a "filter-parsed" class name set.

iExact - The exact (or parsed) text in all lower case for case insensitive searches.

If your designator doesn't exist, you *must* return null to allow comparisons with other filter types.

Here is a basic example with extensive comments:

// search for a match from the beginning of a string
// "^l" matches "lion" but not "koala"
$.tablesorter.filter.types.start = function( filter, iFilter, exact, iExact ) {
	// test for filter type designator. In this example, "^" must be at the beginning of the filter
	// for this test, the use of the case insensitive "iFilter" variable
	// doesn't matter since we are only looking at the symbol
	if ( /^\^/.test( iFilter ) ) {
		// test the table content (exact or parsed) against the filter
		// * Don't forget to remove the designator first ( the substring(1) part ), so "^h".substring(1) becomes "h"
		// * In this case, we do care about using "iFilter" since we're comparing it with "iExact"
		// * We use "indexOf" so that we know the match starts from the beginning of the string.
		// * Your function should return a boolean indicating a match, or not.
		return iExact.indexOf( iFilter.substring(1) ) === 0;
	}
	// ALWAYS return null if your custom filter type doesn't match
	return null;
};

How to remove filter types

If one of the built-in search types is interfering or bothersome to your users, then you can remove it using the following command (using fuzzy search as an example):

$(function(){

	// Remove fuzzy search
	delete $.tablesorter.filter.types.fuzzy;

	$('table').tablesorter({
		theme: 'blue',
		widgets: ['filter']
	});

});

The full list of built-in filter type functions can be found in the "Built-in Filters" section.

Localization

			You can change the language of the searches used within the filter widget. This only applies to the "and", "or" and "to" (range) searches. For example, to change the localization to French, do the following:

// add French support
$.extend($.tablesorter.language, {
	to  : 'à',
	or  : 'ou',
	and : 'et'
});
This results in searches that can be performed as follows:

"and" search: Pierre et Franc or Pierre && Franc.

"or" search: Marie ou Claudette or Marie|Claudette

"to" search: 10 à 20 or 10 - 20

			Note the symbolic searches never changed ( && , | and  - )

			Important Even though the language settings don't include spaces, the user is still required to enter spaces in the filter to perform these searches, e.g. 1 à 10 (shows rows with numbers between 1 and 10).

			If you want to support multiple languages, separate the language variables with a vertical bar (|, Shift + \):

// add French & Spanish support
$.extend($.tablesorter.language, {
	to  : 'à|a',
	or  : 'ou|o',
	and : 'et|y'
});

Demo

<button type="button" data-filter-column="1">^h</button> (beginning of word)

<button type="button" data-filter-column="1">s$</button> (end of word)

<button type="button" class="reset">Reset</button>

First Name	Last Name	City	Age	Total	Discount	Date

Aaron	Johnson Sr	Atlanta	35	$5.95	22%	Jun 26, 2004 7:22 AM

Aaron	Johnson	Yuma	12	$2.99	5%	Aug 21, 2009 12:21 PM

Clark	Henry Jr	Tampa	51	$42.29	18%	Oct 13, 2000 1:15 PM

Denni	Henry	New York	28	$9.99	20%	Jul 6, 2006 8:14 AM

John	Hood	Boston	33	$19.99	25%	Dec 10, 2002 5:14 AM

Clark	Kent Sr	Los Angeles	18	$15.89	44%	Jan 12, 2003 11:14 AM

Peter	Kent Esq	Seattle	45	$153.19	44%	Jan 18, 2021 9:12 AM

Peter	Johns	Milwaukee	13	$5.29	4%	Jan 8, 2012 5:11 PM

Aaron	Evan	Chicago	24	$14.19	14%	Jan 14, 2004 11:23 AM

Bruce	Evans	Upland	22	$13.19	11%	Jan 18, 2007 9:12 AM

Clark	McMasters	Pheonix	18	$55.20	15%	Feb 12, 2010 7:23 PM

Dennis	Masters	Indianapolis	65	$123.00	32%	Jan 20, 2001 1:12 PM

John	Hood	Fort Worth	25	$22.09	17%	Jun 11, 2011 10:55 AM

Javascript

HTML

	Next up: jQuery custom filter widget formatter (jQuery UI widgets) ››


text:
var network = require('./lib/index');

network.ifconfig(function (err, interfaces) {
	if(err) return console.log(err);
	console.log('\nIFCONFIG INTERFACES:\n', interfaces);
});

network.route(function (err, routes) {
	if(err) return console.log(err);
	console.log('\nROUTE ROUTES:\n', routes);
});

network.getNetworkInfo(function (err, interfaces) {
	if(err) return console.log(err);
	console.log('\nNETWORK INFO INTERFACES (WITH DEFAULT GATEWAY):\n', interfaces);
});


text:
#include "VisibleGameObject.h"
#include <random>

class GameBall : public VisibleGameObject {
public:
    GameBall();
    ~GameBall();

	void update(const float elapsedTime);
	const bool ballIsActive();

private:
	float velocity;
	float angle;
	float elapsedTimeSinceStart;

	float linearVelocityX(const float angle);
	float linearVelocityY(const float angle);

	const float randomAngle();

	const bool adjustForPaddleCollision(const std::string paddleName, const sf::Rect<float>& originalPosition, const sf::Rect<float>& newPosition);
	void resetBallPosition();

	std::default_random_engine rng;
	std::uniform_real_distribution<float> dist;
};

#endif // GAMEBALL_H_INCLUDED


text:
import textwrap

import pytest

import capa.rules
import capa.engine
import capa.features.common
from capa.features.file import FunctionName
from capa.features.insn import Number, Offset, Property
from capa.features.common import (
    OS,
    OS_LINUX,
    ARCH_I386,
    FORMAT_PE,
    ARCH_AMD64,
    FORMAT_ELF,
    OS_WINDOWS,
    Arch,
    Format,
    String,
    Substring,
    FeatureAccess,
)

def test_rule_ctor():
    r = capa.rules.Rule("test rule", capa.rules.FUNCTION_SCOPE, Number(1), {})
    assert r.evaluate({Number(0): {1}}) == False
    assert r.evaluate({Number(1): {1}}) == True

def test_rule_yaml():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                authors:
                    - user@domain.com
                scope: function
                examples:
                    - foo1234
                    - bar5678
            features:
                - and:
                    - number: 1
                    - number: 2
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(0): {1}}) == False
    assert r.evaluate({Number(0): {1}, Number(1): {1}}) == False
    assert r.evaluate({Number(0): {1}, Number(1): {1}, Number(2): {1}}) == True
    assert r.evaluate({Number(0): {1}, Number(1): {1}, Number(2): {1}, Number(3): {1}}) == True

def test_rule_yaml_complex():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - and:
                        - number: 1
                        - number: 2
                    - or:
                        - number: 3
                        - 2 or more:
                            - number: 4
                            - number: 5
                            - number: 6
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(5): {1}, Number(6): {1}, Number(7): {1}, Number(8): {1}}) == True
    assert r.evaluate({Number(6): {1}, Number(7): {1}, Number(8): {1}}) == False

def test_rule_descriptions():
    rule = textwrap.dedent(
        """
        rule:
          meta:
            name: test rule
          features:
            - and:
              - description: and description
              - number: 1 = number description
              - string: mystring
                description: string description
              - string: '/myregex/'
                description: regex description
              - mnemonic: inc = mnemonic description
              # TODO - count(number(2 = number description)): 2
              - or:
                - description: or description
                - and:
                  - offset: 0x50 = offset description
                  - offset: 0x34 = offset description
                  - description: and description
                - and:
                  - description: and description
        """
    )
    r = capa.rules.Rule.from_yaml(rule)

    def rec(statement):
        if isinstance(statement, capa.engine.Statement):
            assert statement.description == statement.name.lower() + " description"
            for child in statement.get_children():
                rec(child)
        else:
            if isinstance(statement.value, str):
                assert "description" not in statement.value
            assert statement.description == statement.name + " description"

    rec(r.statement)

def test_invalid_rule_statement_descriptions():
    # statements can only have one description
    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                  meta:
                    name: test rule
                  features:
                    - or:
                      - number: 1 = This is the number 1
                      - description: description
                      - description: another description (invalid)
                """
            )
        )

def test_rule_yaml_not():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - and:
                    - number: 1
                    - not:
                        - number: 2
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(1): {1}}) == True
    assert r.evaluate({Number(1): {1}, Number(2): {1}}) == False

def test_rule_yaml_count():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - count(number(100)): 1
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(100): {}}) == False
    assert r.evaluate({Number(100): {1}}) == True
    assert r.evaluate({Number(100): {1, 2}}) == False

def test_rule_yaml_count_range():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - count(number(100)): (1, 2)
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(100): {}}) == False
    assert r.evaluate({Number(100): {1}}) == True
    assert r.evaluate({Number(100): {1, 2}}) == True
    assert r.evaluate({Number(100): {1, 2, 3}}) == False

def test_rule_yaml_count_string():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - count(string(foo)): 2
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({String("foo"): {}}) == False
    assert r.evaluate({String("foo"): {1}}) == False
    assert r.evaluate({String("foo"): {1, 2}}) == True
    assert r.evaluate({String("foo"): {1, 2, 3}}) == False

def test_invalid_rule_feature():
    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - foo: true
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                        scope: file
                    features:
                        - characteristic: nzxor
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                        scope: function
                    features:
                        - characteristic: embedded pe
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                        scope: basic block
                    features:
                        - characteristic: embedded pe
                """
            )
        )

def test_lib_rules():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: a lib rule
                            lib: true
                        features:
                            - api: CreateFileA
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: a standard rule
                            lib: false
                        features:
                            - api: CreateFileW
                    """
                )
            ),
        ]
    )
    # lib rules are added to the rule set
    assert len(rules.function_rules) == 2

def test_subscope_rules():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: test rule
                            scope: file
                        features:
                            - and:
                                - characteristic: embedded pe
                                - function:
                                    - and:
                                        - characteristic: nzxor
                                        - characteristic: loop
                    """
                )
            )
        ]
    )
    # the file rule scope will have one rules:
    #  - `test rule`
    assert len(rules.file_rules) == 1

    # the function rule scope have one rule:
    #  - the rule on which `test rule` depends
    assert len(rules.function_rules) == 1

def test_duplicate_rules():
    with pytest.raises(capa.rules.InvalidRule):
        rules = capa.rules.RuleSet(
            [
                capa.rules.Rule.from_yaml(
                    textwrap.dedent(
                        """
                        rule:
                            meta:
                                name: rule-name
                            features:
                                - api: CreateFileA
                        """
                    )
                ),
                capa.rules.Rule.from_yaml(
                    textwrap.dedent(
                        """
                        rule:
                            meta:
                                name: rule-name
                            features:
                                - api: CreateFileW
                        """
                    )
                ),
            ]
        )

def test_missing_dependency():
    with pytest.raises(capa.rules.InvalidRule):
        rules = capa.rules.RuleSet(
            [
                capa.rules.Rule.from_yaml(
                    textwrap.dedent(
                        """
                        rule:
                            meta:
                                name: dependent rule
                            features:
                                - match: missing rule
                        """
                    )
                ),
            ]
        )

def test_invalid_rules():
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - characteristic: number(1)
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - characteristic: count(number(100))
                """
            )
        )

    # att&ck and mbc must be lists
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                        att&ck: Tactic::Technique::Subtechnique [Identifier]
                    features:
                        - number: 1
                """
            )
        )
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                        mbc: Objective::Behavior::Method [Identifier]
                    features:
                        - number: 1
                """
            )
        )

def test_number_symbol():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - and:
                    - number: 1
                    - number: 0xFFFFFFFF
                    - number: 2 = symbol name
                    - number: 3  =  symbol name
                    - number: 4  =  symbol name = another name
                    - number: 0x100 = symbol name
                    - number: 0x11 = (FLAG_A | FLAG_B)
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Number(1) in children) == True
    assert (Number(0xFFFFFFFF) in children) == True
    assert (Number(2, description="symbol name") in children) == True
    assert (Number(3, description="symbol name") in children) == True
    assert (Number(4, description="symbol name = another name") in children) == True
    assert (Number(0x100, description="symbol name") in children) == True

def test_count_number_symbol():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - count(number(2 = symbol name)): 1
                    - count(number(0x100 = symbol name)): 2 or more
                    - count(number(0x11 = (FLAG_A | FLAG_B))): 2 or more
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Number(2): {}}) == False
    assert r.evaluate({Number(2): {1}}) == True
    assert r.evaluate({Number(2): {1, 2}}) == False
    assert r.evaluate({Number(0x100, description="symbol name"): {1}}) == False
    assert r.evaluate({Number(0x100, description="symbol name"): {1, 2, 3}}) == True

def test_invalid_number():
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - number: "this is a string"
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - number: 2=
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - number: symbol name = 2
                """
            )
        )

def test_offset_symbol():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - and:
                    - offset: 1
                    - offset: 2 = symbol name
                    - offset: 3  =  symbol name
                    - offset: 4  =  symbol name = another name
                    - offset: 0x100 = symbol name
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Offset(1) in children) == True
    assert (Offset(2, description="symbol name") in children) == True
    assert (Offset(3, description="symbol name") in children) == True
    assert (Offset(4, description="symbol name = another name") in children) == True
    assert (Offset(0x100, description="symbol name") in children) == True

def test_count_offset_symbol():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - count(offset(2 = symbol name)): 1
                    - count(offset(0x100 = symbol name)): 2 or more
                    - count(offset(0x11 = (FLAG_A | FLAG_B))): 2 or more
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    assert r.evaluate({Offset(2): {}}) == False
    assert r.evaluate({Offset(2): {1}}) == True
    assert r.evaluate({Offset(2): {1, 2}}) == False
    assert r.evaluate({Offset(0x100, description="symbol name"): {1}}) == False
    assert r.evaluate({Offset(0x100, description="symbol name"): {1, 2, 3}}) == True

def test_invalid_offset():
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - offset: "this is a string"
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - offset: 2=
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - offset: symbol name = 2
                """
            )
        )

def test_invalid_string_values_int():
    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - string: 123
                """
            )
        )

    with pytest.raises(capa.rules.InvalidRule):
        r = capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: test rule
                    features:
                        - string: 0x123
                """
            )
        )

def test_explicit_string_values_int():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - string: "123"
                    - string: "0x123"
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (String("123") in children) == True
    assert (String("0x123") in children) == True

def test_string_values_special_characters():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - string: "hello\\r\\nworld"
                    - string: "bye\\nbye"
                      description: "test description"
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (String("hello\r\nworld") in children) == True
    assert (String("bye\nbye") in children) == True

def test_substring_feature():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - substring: abc
                    - substring: "def"
                    - substring: "gh\\ni"
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Substring("abc") in children) == True
    assert (Substring("def") in children) == True
    assert (Substring("gh\ni") in children) == True

def test_substring_description():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
            features:
                - or:
                    - substring: abc
                      description: the start of the alphabet
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Substring("abc") in children) == True

def test_filter_rules():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: rule 1
                            authors:
                              - joe
                        features:
                            - api: CreateFile
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: rule 2
                        features:
                            - string: joe
                    """
                )
            ),
        ]
    )
    rules = rules.filter_rules_by_meta("joe")
    assert len(rules) == 1
    assert "rule 1" in rules.rules

def test_filter_rules_dependencies():
    rules = capa.rules.RuleSet(
        [
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: rule 1
                        features:
                            - match: rule 2
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: rule 2
                        features:
                            - match: rule 3
                    """
                )
            ),
            capa.rules.Rule.from_yaml(
                textwrap.dedent(
                    """
                    rule:
                        meta:
                            name: rule 3
                        features:
                            - api: CreateFile
                    """
                )
            ),
        ]
    )
    rules = rules.filter_rules_by_meta("rule 1")
    assert len(rules.rules) == 3
    assert "rule 1" in rules.rules
    assert "rule 2" in rules.rules
    assert "rule 3" in rules.rules

def test_filter_rules_missing_dependency():
    with pytest.raises(capa.rules.InvalidRule):
        capa.rules.RuleSet(
            [
                capa.rules.Rule.from_yaml(
                    textwrap.dedent(
                        """
                        rule:
                            meta:
                                name: rule 1
                                authors:
                                  - joe
                            features:
                                - match: rule 2
                        """
                    )
                ),
            ]
        )

def test_rules_namespace_dependencies():
    rules = [
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: rule 1
                        namespace: ns1/nsA
                    features:
                        - api: CreateFile
                """
            )
        ),
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: rule 2
                        namespace: ns1/nsB
                    features:
                        - api: CreateFile
                """
            )
        ),
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: rule 3
                    features:
                        - match: ns1/nsA
                """
            )
        ),
        capa.rules.Rule.from_yaml(
            textwrap.dedent(
                """
                rule:
                    meta:
                        name: rule 4
                    features:
                        - match: ns1
                """
            )
        ),
    ]

    r3 = set(map(lambda r: r.name, capa.rules.get_rules_and_dependencies(rules, "rule 3")))
    assert "rule 1" in r3
    assert "rule 2" not in r3
    assert "rule 4" not in r3

    r4 = set(map(lambda r: r.name, capa.rules.get_rules_and_dependencies(rules, "rule 4")))
    assert "rule 1" in r4
    assert "rule 2" in r4
    assert "rule 3" not in r4

def test_function_name_features():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
                - and:
                    - function-name: strcpy
                    - function-name: strcmp = copy from here to there
                    - function-name: strdup
                      description: duplicate a string
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (FunctionName("strcpy") in children) == True
    assert (FunctionName("strcmp", description="copy from here to there") in children) == True
    assert (FunctionName("strdup", description="duplicate a string") in children) == True

def test_os_features():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
                - and:
                    - os: windows
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (OS(OS_WINDOWS) in children) == True
    assert (OS(OS_LINUX) not in children) == True

def test_format_features():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
                - and:
                    - format: pe
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Format(FORMAT_PE) in children) == True
    assert (Format(FORMAT_ELF) not in children) == True

def test_arch_features():
    rule = textwrap.dedent(
        """
        rule:
            meta:
                name: test rule
                scope: file
            features:
                - and:
                    - arch: amd64
        """
    )
    r = capa.rules.Rule.from_yaml(rule)
    children = list(r.statement.get_children())
    assert (Arch(ARCH_AMD64) in children) == True
    assert (Arch(ARCH_I386) not in children) == True

def test_property_access():
    r = capa.rules.Rule.from_yaml(
        textwrap.dedent(
            """
            rule:
                meta:
                    name: test rule
                features:
                    - property/read: System.IO.FileInfo::Length
            """
        )
    )
    assert r.evaluate({Property("System.IO.FileInfo::Length", access=FeatureAccess.READ): {1}}) == True

    assert r.evaluate({Property("System.IO.FileInfo::Length"): {1}}) == False
    assert r.evaluate({Property("System.IO.FileInfo::Length", access=FeatureAccess.WRITE): {1}}) == False

def test_property_access_symbol():
    r = capa.rules.Rule.from_yaml(
        textwrap.dedent(
            """
            rule:
                meta:
                    name: test rule
                features:
                    - property/read: System.IO.FileInfo::Length = some property
            """
        )
    )
    assert (
        r.evaluate(
            {Property("System.IO.FileInfo::Length", access=FeatureAccess.READ, description="some property"): {1}}
        )
        == True
    )