text:
from __future__ import annotations

import functools
import logging
import threading
from typing import Callable, Dict, Optional, List, Tuple, Any

CALL_DEPTH_ATTR_SUFFIX = '.depth'
CALL_COUNTER_ATTR_SUFFIX = '.count'
CALL_LIMIT_ATTR_SUFFIX = '.calllimit'

class _MethodCallTracker:
    """
    Tracks calls to methods within classes. The purpose of this code is to determine whether a given method is
    called first from the outside or whether it is a nested call inside a class or object.
    """
    _local_storage = threading.local()
    _instance = None

    @staticmethod
    def get_instance() -> _MethodCallTracker:
        return _MethodCallTracker._instance

    def __init__(self):
        if _MethodCallTracker._instance is not None:
            raise Exception('Internal error: cannot create another instance of this class')
        _MethodCallTracker._instance = self

    @staticmethod
    def init_stack(stack_name: str) -> List[Dict]:
        stack = getattr(_MethodCallTracker._local_storage, stack_name, None)
        if stack is None:
            stack = []
            _MethodCallTracker._local_storage.__setattr__(stack_name, stack)
        return stack

    @staticmethod
    def push_to_stack(stack_name: str, attributes: Dict):
        stack = _MethodCallTracker.init_stack(stack_name)
        stack.append(attributes)

    @staticmethod
    def pop_from_stack(stack_name: str) -> Optional[Dict]:
        stack: List[Dict] = _MethodCallTracker.init_stack(stack_name)
        if stack:
            return stack.pop()
        return None

    @staticmethod
    def get_class_storage_attr_names(obj: object, suffix: str) -> Tuple[str, str]:
        class_name = obj.__class__.__name__
        object_id = str(id(obj))

        attr_name_for_class = class_name + suffix
        attr_name_for_object = class_name + '.' + object_id + suffix
        return attr_name_for_class, attr_name_for_object

    @staticmethod
    def get_method_storage_attr_names(obj: object, method: Callable, suffix: str) -> Tuple[str, str, str, str]:
        class_name = obj.__class__.__name__
        object_id = str(id(obj))

        attr_name_for_class, attr_name_for_object = _MethodCallTracker.get_class_storage_attr_names(obj, suffix)
        attr_name_for_class_method = class_name + '.' + method.__name__ + suffix
        attr_name_for_object_method = class_name + '.' + object_id + '.' + method.__name__ + suffix
        return attr_name_for_class, attr_name_for_object, attr_name_for_class_method, attr_name_for_object_method

    @staticmethod
    def set_attr(attr_name: str, attr_value: Any):
        _MethodCallTracker._local_storage.__setattr__(attr_name, attr_value)

    @staticmethod
    def get_attr(attr_name: str, default_value: Any) -> Any:
        return getattr(_MethodCallTracker._local_storage, attr_name, default_value)

    @staticmethod
    def incr(attr_name):
        _MethodCallTracker.set_attr(attr_name, _MethodCallTracker.get_attr(attr_name, 0) + 1)

    @staticmethod
    def decr(attr_name):
        v = _MethodCallTracker.get_attr(attr_name, 0)
        if v > 0:
            _MethodCallTracker.set_attr(attr_name, v - 1)
        else:
            logging.warning('_MethodCallTracker: cannot decrease value of ' + attr_name + ' to negative')

    @staticmethod
    def method_call_started(obj: object, method: Callable):
        self = _MethodCallTracker

        # increase the call depth values
        attr_name_for_class, attr_name_for_object, attr_name_for_class_method, attr_name_for_object_method = \
            self.get_method_storage_attr_names(obj, method, CALL_DEPTH_ATTR_SUFFIX)

        self.incr(attr_name_for_class)
        self.incr(attr_name_for_object)
        self.incr(attr_name_for_class_method)
        self.incr(attr_name_for_object_method)

        # increase the call counter values
        attr_name_for_class, attr_name_for_object, attr_name_for_class_method, attr_name_for_object_method = \
            self.get_method_storage_attr_names(obj, method, CALL_COUNTER_ATTR_SUFFIX)

        self.incr(attr_name_for_class)
        self.incr(attr_name_for_object)
        self.incr(attr_name_for_class_method)
        self.incr(attr_name_for_object_method)

    @staticmethod
    def method_call_finished(obj: object, method: Callable):
        self = _MethodCallTracker

        # decrease only the method call depth values
        attr_name_for_class, attr_name_for_object, attr_name_for_class_method, attr_name_for_object_method = \
            self.get_method_storage_attr_names(obj, method, CALL_DEPTH_ATTR_SUFFIX)

        self.decr(attr_name_for_class)
        self.decr(attr_name_for_object)
        self.decr(attr_name_for_class_method)
        self.decr(attr_name_for_object_method)

    @staticmethod
    def get_call_depth_by_class(obj: object):
        attr_name_for_class, _ = _MethodCallTracker.get_class_storage_attr_names(obj, CALL_DEPTH_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_class, 0)

    @staticmethod
    def get_call_depth_by_object(obj: object):
        _, attr_name_for_object = _MethodCallTracker.get_class_storage_attr_names(obj, CALL_DEPTH_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_object, 0)

    @staticmethod
    def get_call_depth_by_class_method(obj: object, method: Callable):
        _, _, attr_name_for_class_method, _ = _MethodCallTracker.get_method_storage_attr_names(obj, method,
                                                                                CALL_DEPTH_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_class_method, 0)

    @staticmethod
    def get_call_depth_by_object_method(obj: object, method: Callable):
        _, _, _, attr_name_for_object_method = _MethodCallTracker.get_method_storage_attr_names(obj, method,
                                                                                CALL_DEPTH_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_object_method, 0)

    @staticmethod
    def get_call_count_by_class(obj: object):
        attr_name_for_class, _ = _MethodCallTracker.get_class_storage_attr_names(obj, CALL_COUNTER_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_class, 0)

    @staticmethod
    def get_call_count_by_object(obj: object):
        _, attr_name_for_object = _MethodCallTracker.get_class_storage_attr_names(obj, CALL_COUNTER_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_object, 0)

    @staticmethod
    def get_call_count_by_class_method(obj: object, method: Callable):
        _, _, attr_name_for_class_method, _ = _MethodCallTracker.get_method_storage_attr_names(obj, method,
                                                                                CALL_COUNTER_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_class_method, 0)

    @staticmethod
    def get_call_count_by_object_method(obj: object, method: Callable):
        _, _, _, attr_name_for_object_method = _MethodCallTracker.get_method_storage_attr_names(obj, method,
                                                                                CALL_COUNTER_ATTR_SUFFIX)
        return _MethodCallTracker.get_attr(attr_name_for_object_method, 0)

    @staticmethod
    def set_object_method_call_limit(obj: object, method: Callable, call_limit: int):
        self = _MethodCallTracker
        cur_call_count = self.get_call_count_by_object_method(obj, method)
        _, _, _, attr_name_for_object_method = self.get_method_storage_attr_names(obj, method, CALL_LIMIT_ATTR_SUFFIX)
        if call_limit is not None:
            val = cur_call_count + call_limit
        else:
            val = call_limit  # basically, it means disabling the call limit for the given method
        self.set_attr(attr_name_for_object_method, val)

    @staticmethod
    def get_object_method_call_limit(obj: object, method: Callable):
        self = _MethodCallTracker
        _, _, _, attr_name_for_object_method = self.get_method_storage_attr_names(obj, method, CALL_LIMIT_ATTR_SUFFIX)
        return self.get_attr(attr_name_for_object_method, None)

    def __call__(self, obj: object, method: Callable):
        # save obj and method values for the "__enter__" method
        # this should be called just before __enter__
        _MethodCallTracker._local_storage._obj = obj
        _MethodCallTracker._local_storage._method = method
        return self

    def __enter__(self):
        obj = _MethodCallTracker._local_storage._obj
        method = _MethodCallTracker._local_storage._method

        # use stack to pass the object and method values to the __exit__ method
        self.push_to_stack('OBJ_METHOD_STACK', {'obj': obj, 'method': method})
        self.method_call_started(obj, method)
        return self

    def __exit__(self, exc_type, exc_value, tb):
        v = self.pop_from_stack('OBJ_METHOD_STACK',)
        if not v:
            logging.error('No matching call to the __enter__ method.')
        else:
            self.method_call_finished(v['obj'], v['method'])
        if exc_type is not None or exc_value is not None:
            return False
        else:
            return True

MethodCallTracker = _MethodCallTracker()

def method_call_tracker(func):
    """Decorator function to track the execution of a given method and work in tandem with MethodCallLimit to
    implement method call limiting."""
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        # if we reached limit set for 'func' calls, suppress call and return None
        call_limit = MethodCallTracker.get_object_method_call_limit(self, func)
        if call_limit is not None:
            cur_call_cont = MethodCallTracker.get_call_count_by_object_method(self, func)
            if cur_call_cont >= call_limit:
                return None

        with MethodCallTracker(self, func):
            ret = func(self, *args, **kwargs)
        return ret
    return wrapper

class MethodCallLimit:
    """
    The purpose of this class is to allow limiting the number of executions of a given method between
    __enter__ and __exit__ (using with clause). Methods being limited this way must use the 'method_call_tracker'
    decorator.
    Example:
        class Test:
            def some_function():
                with CallMethodIfNotCalledInside(self, self.controlled_method, 1):
                    self.method_name()  # will be executed
                    self.method_name()  # execution will be suppressed

            @method_call_tracker
            def controlled_method():
                pass
    """
    def __init__(self, obj: object, method: Callable, call_count_limit: int):
        self.object = obj
        self.method = method
        self.call_count_limit = call_count_limit
        self.old_call_limit = None

    def __enter__(self):
        self.old_call_limit = MethodCallTracker.get_object_method_call_limit(self.object, self.method)
        MethodCallTracker.set_object_method_call_limit(self.object, self.method, self.call_count_limit)
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        # restore the old limit
        MethodCallTracker.set_object_method_call_limit(self.object, self.method, self.old_call_limit)
        if exc_type is not None or exc_value is not None:
            return False
        else:
            return True


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">
    <link href="css/rangeslider.css" rel="stylesheet">

    <title>Color Combinations</title>

Color Combinations <button id="reveal" type="button" class="btn btn-default btn-circle"></button>

          Toggle hue, saturation and lightness using the sliders below for each color and watch the HTML color codes dynamically change!

          Hue<input id ="hue" type="range" min="0" max="360" step="1" value="80" class="rangeslider">
Saturation<input id ="saturation" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
Lightness<input id ="lightness" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
          Hue<input id ="hue2" type="range" min="0" max="360" step="1" value="80" class="rangeslider">
Saturation<input id ="saturation2" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
Lightness<input id ="lightness2" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
          Hue<input id ="hue3" type="range" min="0" max="360" step="1" value="80" class="rangeslider">
Saturation<input id ="saturation3" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
Lightness<input id ="lightness3" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
          Hue<input id ="hue4" type="range" min="0" max="360" step="1" value="80" class="rangeslider">
Saturation<input id ="saturation4" type="range" min="0" max="100" step="1" value="50" class="rangeslider">
Lightness<input id ="lightness4" type="range" min="0" max="100" step="1" value="50" class="rangeslider">

redpajama_set_name: RedPajamaGithub


text:
CREATE DATABASE music
WITH
OWNER = postgres
ENCODING = 'UTF8'
CONNECTION LIMIT = -1;

COMMENT ON DATABASE music
IS 'Bluetooth music library';


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <mmsolutions.im.ShadowTextView
        android:id="@+id/text"
        android:gravity="center"
        android:padding="5dp"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>
</RelativeLayout>


text: Using remotes as wand, two users will battle each other, a separate arduino acts as a score keeper


text:
namespace ResXManager.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Threading;
    using System.Threading.Tasks;

    public interface ITranslationSession : IDisposable
    {
        bool IsActive { get; }

        bool IsCanceled { get; }

        bool IsComplete { get; }

        CancellationToken CancellationToken { get; }

        void Cancel();

        ICollection<ITranslationItem> Items { get; }

        IList<string> Messages { get; }

        CultureInfo NeutralResourcesLanguage { get; }

        int Progress { get; set; }

        CultureInfo SourceLanguage { get; }

        TaskFactory MainThread { get; }

        void AddMessage(string text);
    }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150520_074517_c_table_joblogs extends Migration
{
    public function up()
    {
          $this->createTable('joblogs', [
             'recid'=>Schema::TYPE_PK,
             'jobid'=>  Schema::TYPE_INTEGER.'(10) NOT NULL',
             'logdate1'=>  Schema::TYPE_DATETIME,
            'logdate2'=>  Schema::TYPE_DATETIME,
            'logdate3'=>  Schema::TYPE_DATETIME,
            'logdate4'=>  Schema::TYPE_DATETIME,
             'logrem1'=>Schema::TYPE_STRING.'(255)NULL',
           'logrem2'=>Schema::TYPE_STRING.'(255)NULL',
           'logrem3'=>Schema::TYPE_STRING.'(255)NULL',
           'logrem4'=>Schema::TYPE_STRING.'(255)NULL',
             'devicename'=>Schema::TYPE_STRING.'(255)NULL',
           'ip'=>Schema::TYPE_STRING.'(255)NULL',
        ]);
        $this->createIndex('idx_jobid', 'joblogs', 'jobid');
    }

    public function down()
    {
        echo "m150520_074517_c_table_joblogs cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
//Write methods to calculate minimum, maximum, average, sum and product of given set of integer numbers.
//Use variable number of arguments.

using System;

class IntegerCalculations
{
    static void Main()
    {
        Console.Write("Please enter number of arguments: ");
        int n = int.Parse(Console.ReadLine());
        int[] integers = new int[n];
        Console.Write("Please enter {0} numbers separeted by space: ",n);
        string[] input = Console.ReadLine().Split(' ');
        for (int i = 0; i < n; i++)
        {
            integers[i] = int.Parse(input[i]);
        }

        Console.WriteLine("Minimum: {0}",Minimum(integers));
        Console.WriteLine("Maximum: {0}", Maximum(integers));
        Console.WriteLine("Average:{0}",Average(integers));
        Console.WriteLine("Sum: {0}",Sum(integers));
        Console.WriteLine("Product: {0}",Product(integers));
    }

    static int Minimum(int[] numbers)
    {
        int min = int.MaxValue;
        for (int i = 0; i < numbers.Length; i++)
        {
           if(numbers[i]<min)
           {
               min = numbers[i];
           }
        }
        return min;
    }

    static int Maximum(int[] numbers)
    {
        int max = int.MinValue;
            for (int i = 0; i < numbers.Length; i++)
			{
			 if(numbers[i]>max)
             {
                 max = numbers[i];
             }
			}
            return max;
    }

    static double Average(int[] numbers)
    {
        int sum = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            sum += numbers[i];
        }
        double avg =(double)sum / (double)numbers.Length;
        return avg ;
    }

    static int Sum(int[] numbers)
    {
        int sum = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            sum += numbers[i];
        }
        return sum;
    }

    static int Product(int[] numbers)
    {
        int prod = 1;
        for (int i = 0; i < numbers.Length; i++)
        {
            prod *= numbers[i];
        }
        return prod;
    }
}


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using SF.Sys.ServiceFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SF.Sys.Services
{
	public static class InitializableDIServiceCollectionExtension
	{
		class InitHelper : IServiceInitializable
		{
			public Func<IServiceProvider, IReadOnlyDictionary<string, string>,Task> Callback { get; set; }
			public string Group { get; set; }
			public string Title { get; set; }
			public int Priority { get; set; }
			public Task Init(IServiceProvider ServiceProvider,IReadOnlyDictionary<string,string> Args)
			{
				return Callback(ServiceProvider, Args);
			}
		}
		public static IServiceCollection AddInitializer(
			this IServiceCollection sc,
			string Group,
			string Title,
			Func<IServiceProvider, Task> Callback,
			int Priority = 0
			)
			=> sc.AddInitializer(
				Group,
				Title,
				(sp, arg) => Callback(sp),
				Priority
				);
		public static IServiceCollection AddInitializer(
			this IServiceCollection sc,
			string Group,
			string Title,
			Func<IServiceProvider, IReadOnlyDictionary<string, string>, Task> Callback,
			int Priority=0
			)
			{
				sc.AddSingleton<IServiceInitializable>(sp =>
					new InitHelper
					{
						Group=Group,
						Title=Title,
						Callback = Callback,
						Priority=Priority
					});
				return sc;
			}

		public static IServiceCollection AddInitializer(
			this IServiceCollection sc,
			string Group,
			string Title,
			Action<IServiceProvider,IReadOnlyDictionary<string,string>> Callback,
			int Priority = 0)
		{
			sc.AddInitializer(
				Group,
				Title,
				(sp,args) =>
				{
					Callback(sp,args);
					return Task.CompletedTask;
				},
				Priority
				);
			return sc;
		}
		public static IServiceCollection AddInitializer(
			this IServiceCollection sc,
			string Group,
			string Title,
			Action<IServiceProvider> Callback,
			int Priority = 0)
			=> sc.AddInitializer(Group, Title, (sp, args) => Callback(sp), Priority);
	}
}


text:
package sampleclean.clean

import org.apache.spark.{SparkConf, SparkContext}
import sampleclean.api.SampleCleanContext

/**
 * Provides a method to run tests against a {@link SparkContext} variable that is correctly stopped
 * after each test.
 */
trait LocalSCContext extends Serializable{
  /** Runs `f` on a new SparkContext and ensures that it is stopped afterwards. */
  def withSampleCleanContext[T](f: SampleCleanContext => T): T = {
    val conf = new SparkConf()
      .set("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext("local[*]", "test", conf)
    val scc = new SampleCleanContext(sc)
    try {
      f(scc)
    } finally {
      sc.stop()
    }
  }

  def withSingleAttribute[T](sample:Int,f: SampleCleanContext => T): T = {
    val conf = new SparkConf()
      .set("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext("local[*]", "test", conf)
    val scc = new SampleCleanContext(sc)
    val context = List("id", "col0")
    val contextString = context.mkString(" String,") + " String"

    val hiveContext = scc.getHiveContext()
    scc.closeHiveSession()
    scc.hql("DROP TABLE IF EXISTS test")
    scc.hql("CREATE TABLE IF NOT EXISTS test(%s) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n'".format(contextString))
    scc.hql("LOAD DATA LOCAL INPATH './src/test/resources/csvJaccard100dupsAttr' OVERWRITE INTO TABLE test")
    scc.initializeConsistent("test", "test_sample", "id", sample)

    try {
      f(scc)
    } finally {
      sc.stop()
    }
  }

  def withFullRecords[T](sample:Double, f: SampleCleanContext => T): T = {
    val conf = new SparkConf()
      .set("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext("local[*]", "test", conf)
    val scc = new SampleCleanContext(sc)
    val context = List("id") ++ (0 until 20).toList.map("col" + _.toString)

    val contextString = context.mkString(" String,") + " String"
    val hiveContext = scc.getHiveContext()
    scc.closeHiveSession()
    scc.hql("DROP TABLE IF EXISTS test")
    scc.hql("CREATE TABLE IF NOT EXISTS test(%s) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n'".format(contextString))
    scc.hql("LOAD DATA LOCAL INPATH './src/test/resources/csvJaccard100dups' OVERWRITE INTO TABLE test")
    scc.initializeConsistent("test", "test_sample", "id", sample)

    try {
      f(scc)
    } finally {
      sc.stop()
    }
  }

  def withFullRecordsLarge[T](sample:Double, f: SampleCleanContext => T): T = {
    val conf = new SparkConf()
      .set("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext("local[*]", "test", conf)
    val scc = new SampleCleanContext(sc)
    val context = List("id") ++ (0 until 20).toList.map("col" + _.toString)

    val contextString = context.mkString(" String,") + " String"
    val hiveContext = scc.getHiveContext()
    scc.closeHiveSession()
    scc.hql("DROP TABLE IF EXISTS test")
    scc.hql("CREATE TABLE IF NOT EXISTS test(%s) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n'".format(contextString))
    scc.hql("LOAD DATA LOCAL INPATH './src/test/resources/csvJaccard100000dups' OVERWRITE INTO TABLE test")
    scc.initializeConsistent("test", "test_sample", "id", sample)

    try {
      f(scc)
    } finally {
      sc.stop()
    }
  }
}


text:
package org.gearvrf;

import android.content.Intent;
import android.content.res.Configuration;
import android.view.MotionEvent;

/**
 * This class contains null implementations for the event interfaces
 * (subclasses of {@link IEvent}, such as {@link IScriptEvents} and {@link IActivityEvents}).
 * They can be extended to override individual methods, which produces less code than
 * implementing the complete interfaces, when the latter is unnecessary.
 *
 * For example, code to implement complete IScriptEvents includes 4 methods or more.
 * If only one method needs to be overridden, {@code GVREventListener.ScriptEvents} can be
 * derived to produce shorter and clearer code:
 *
 * <pre>
 *     IScriptEvents myScriptEventsHandler = new GVREventListener.ScriptEvents {
 *         public onInit(GVRContext gvrContext) throws Throwable {
 *         }
 *     };
 * </pre>
 */
public class GVREventListeners {
    /**
     * Null implementation of {@link IScriptEvents}.
     */
    public static class ScriptEvents implements IScriptEvents {
        @Override
        public void onEarlyInit(GVRContext gvrContext) {
        }

        @Override
        public void onInit(GVRContext gvrContext) throws Throwable {
        }

        @Override
        public void onAfterInit() {
        }

        @Override
        public void onStep() {
        }
    }

    /**
     * Null implementation of {@link IActivityEvents}.
     */
    public static class ActivityEvents implements IActivityEvents {
        @Override
        public void onPause() {
        }

        @Override
        public void onResume() {
        }

        @Override
        public void onDestroy() {
        }

        @Override
        public void onSetScript(GVRScript script) {
        }

        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
        }

        @Override
        public void onConfigurationChanged(Configuration config) {
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode,
                Intent data) {
        }

        @Override
        public void onTouchEvent(MotionEvent event) {
        }

        @Override
        public void dispatchTouchEvent(MotionEvent event) {
        }
    }

    /**
     * Null implementation of {@link ISceneObjectEvents}.
     */
    public static class SceneObjectEvents implements ISceneObjectEvents {
        @Override
        public void onAfterInit() {
        }

        @Override
        public void onStep() {
        }

        @Override
        public void onInit(GVRContext gvrContext, GVRSceneObject sceneObject) {
        }

        @Override
        public void onLoaded() {
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>cortex.built_ins.transforms package — Cortex2.0  documentation</title>

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Develop" href="develop.html" />
    <link rel="prev" title="cortex.built_ins.networks package" href="cortex.built_ins.networks.html" />

             Cortex2.0

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

User Documentation

Installation

Getting Started

cortex

cortex package

Subpackages

cortex.built_ins package

Submodules

cortex.main module

cortex.plugins module

Module contents

Develop

Custom demos

A walkthrough a custom classifier:

Defining losses and results

Visualization

Putting it together

          Cortex2.0

Docs »

cortex »

cortex package »

cortex.built_ins package »

cortex.built_ins.transforms package

             View page source

cortex.built_ins.transforms package¶

Submodules¶

cortex.built_ins.transforms.sobel module¶

Module for Sobel transformation

class cortex.built_ins.transforms.sobel.Sobel[source]¶

Bases: object

Module contents¶

        Next

         Previous

        © Copyright 2018, MILA.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package org.assertj.core.api.assumptions;

abstract class AssumptionRunner<T> {

  protected final T actual;

  AssumptionRunner() {
    this.actual = null;
  }

  AssumptionRunner(T actual) {
    this.actual = actual;
  }

  protected abstract void runFailingAssumption();

  protected abstract void runPassingAssumption();
}


text: Web services for talking to a LDAP directory


text:
package org.wso2.carbon.identity.oidc.dcr;

import org.wso2.carbon.identity.oauth.dcr.DCRClientException;

public class OIDCDCRClientException extends DCRClientException {
    public OIDCDCRClientException(String message) {
        super(message);
    }

    public OIDCDCRClientException(String errorCode, String message) {
        super(errorCode, message);
    }

    public OIDCDCRClientException(String message, Throwable cause) {
        super(message, cause);
    }

    public OIDCDCRClientException(String errorCode, String message, Throwable cause) {
        super(errorCode, message, cause);
    }
}


text:
PeeperJs is a JavaScript module for observing the properties changes

# How to use

```js

var peeper = require('./peeper.js');

var person = {

    Id: 1,
    Name: 'Brad',
    Age: 12
};

var observation = peeper.observe(person, function(o) {
    console.log(o);
});

person.Name = 'Krzysztof';

// Console output:
// { object: {person}, property: 'Name', oldValue: 'Brad', newValue: 'Krzysztof' }

// Dispose an observer
observation.dispose();

person.Age = 33;

// No console output
```


text:
namespace TestApp.Messages
{
    public class TestMessage2
    {
        public int ID { get; set; }
        public int Modified { get; set; }
    }
}


text:
package org.jboss.rhiot.beacon.scannerjni;

import org.jboss.logging.Logger;
import org.jboss.rhiot.beacon.bluez.HCIDump;
import org.jboss.rhiot.beacon.common.Beacon;
import org.jboss.rhiot.beacon.common.IBeaconMapper;
import org.jboss.rhiot.beacon.common.MsgType;
import org.jboss.rhiot.beacon.common.ParseCommand;
import org.jboss.rhiot.beacon.beaconmaps.file.PropertiesMapper;
import org.jboss.rhiot.beacon.bluez.BeaconInfo;
import org.jboss.rhiot.beacon.common.EventsBucket;
import org.jboss.rhiot.beacon.common.EventsWindow;
import org.jboss.rhiot.beacon.common.MsgPublisher;
import org.jboss.rhiot.beacon.common.MsgPublisherFactory;
import org.jboss.rhiot.beacon.common.StatusInformation;
import org.jboss.rhiot.beacon.lcd.AbstractLcdView;
import org.jboss.rhiot.beacon.lcd.LcdDisplayType;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * A parser for the {@link BeaconInfo} events generated by the native bluez hcidump integration.
 * @see HCIDump
 */
public class HCIDumpParser {
    private static Logger log = Logger.getLogger(HCIDumpParser.class);
    private static String STOP_MARKER_FILE = "/var/run/scannerd.STOP";

    /** Command line argument information */
    private ParseCommand parseCommand;
    /** The interface for the messaging layer publisher */
    private MsgPublisher publisher;
    /** The thread for the publishing beacon_info events via the MsgPublisher */
    private Thread consumerThread;
    /** The beacon_info event consumer class running in background */
    private BeaconEventConsumer eventConsumer = new BeaconEventConsumer();
    /** Shared queue for producer/consumer message exchange */
    private ConcurrentLinkedDeque<EventsBucket> eventExchanger = new ConcurrentLinkedDeque<>();
    /** An information class published by the HealthStatus task */
    private StatusInformation statusInformation = new StatusInformation();
    /** The ScannerView implementation used to output information about the scanner */
    private ScannerView scannerView;
    /** A background status monitor task class */
    private HealthStatus statusMonitor = new HealthStatus();
    /** The time window of collected beacon_info events */
    private EventsWindow timeWindow = new EventsWindow();
    private IBeaconMapper beaconMapper;
    private volatile boolean stopped;
    private int lastRSSI[] = new int[10];
    private int heartbeatCount = 0;
    private long eventCount = 0;
    private long maxEventCount = 0;
    private long lastMarkerCheckTime = 0;

    /**
     * Remove the stop marker file if it exists
     */
    public static void removeStopMarker() {
        File test = new File(STOP_MARKER_FILE);
        boolean exists = test.exists();
        if(exists) {
            if(!test.delete()) {
                log.warnf("Failed to remove stop marker: %s", STOP_MARKER_FILE);
            }
        }
    }

    /**
     * Test if the stop marker file exists
     * @return true if the stop marker file exists
     */
    public static boolean stopMarkerExists() {
        File test = new File(STOP_MARKER_FILE);
        boolean stop = test.exists();
        if(stop) {
            log.info("Found STOP marker file, will exit...");
        }
        return stop;
    }

    public HCIDumpParser(ParseCommand cmdArgs) {
        this.parseCommand = cmdArgs;
    }

    public IBeaconMapper getBeaconMapper() {
        return beaconMapper;
    }

    public void setBeaconMapper(IBeaconMapper beaconMapper) {
        this.beaconMapper = beaconMapper;
    }

    public void run() {
        try {
            start();
        } catch (Exception e) {
            log.error("Failed to start scanner", e);
        }
    }

    public void start() throws Exception {
        stopped = false;
        eventConsumer.setParseCommand(parseCommand);
        String clientID = parseCommand.clientID;
        if (clientID.isEmpty())
            clientID = parseCommand.scannerID;
        timeWindow.reset(parseCommand.analyzeWindow);
        // Setup the status information
        statusInformation.setScannerID(parseCommand.getScannerID());
        statusInformation.setStatusInterval(parseCommand.statusInterval);
        statusInformation.setStatusQueue(parseCommand.getStatusDestinationName());
        statusInformation.setBcastAddress(parseCommand.getBcastAddress());
        statusInformation.setBcastPort(parseCommand.getBcastPort());

        if (parseCommand.isAnalyzeMode()) {
            log.infof("Running in analyze mode, window=%d seconds, begin=%d\n", parseCommand.getAnalyzeWindow(),
                timeWindow.getBegin());
        }
        else if (!parseCommand.isSkipPublish()) {
            String username = parseCommand.getUsername();
            String password = parseCommand.getPassword();
            publisher = MsgPublisherFactory.newMsgPublisher(parseCommand.getPubType(), parseCommand.getBrokerURL(), username, password, clientID);
            publisher.setUseTopics(!parseCommand.isUseQueues());
            log.infof("setUseTopics: %s\n", publisher.isUseTopics() ? "true" : "false");
            publisher.setDestinationName(parseCommand.getDestinationName());
            if (parseCommand.batchCount > 0) {
                publisher.setUseTransactions(true);
                log.infof("Enabled transactions\n");
            }
            publisher.start(parseCommand.isAsyncMode());
            log.info("Publisher started");

            // Create a thread for the consumer unless running in battery test mode
            if(!parseCommand.isBatteryTestMode()) {
                eventConsumer.init(eventExchanger, publisher, statusInformation);
                consumerThread = new Thread(eventConsumer::publishEvents, "BeaconEventConsumer");
                consumerThread.setDaemon(true);
                consumerThread.start();
                log.infof("Started event consumer thread\n");
            }
        }
        else {
            log.infof("Skipping publish of parsed beacons\n");
        }

        // If the status interval is > 0, start the health status monitor
        if(parseCommand.getStatusInterval() > 0) {
            statusMonitor.start(publisher, statusInformation);
        }

        // Load the beacon mapping
        if(parseCommand.beaconMapping != null) {
            loadBeaconMapping(parseCommand.beaconMapping);
        }

        // Try to load the scanner view
        if(parseCommand.lcdType != LcdDisplayType.INVALID_LCD_TYPE) {
            log.infof("Trying to load LCD type: %s", parseCommand.lcdType);
            try {
                scannerView = AbstractLcdView.getLcdDisplayInstance(parseCommand.lcdType);
                log.info("Loaded LCD instance");
                scannerView.init();
                if(beaconMapper != null)
                    scannerView.setBeaconMapper(beaconMapper);
            } catch (Throwable error) {
                log.warn("Failed to load LCD instance", error);
            }
        }
    }

    public void stop() throws Exception {
        stopped = true;
        if(consumerThread != null)
            consumerThread.interrupt();
        if(publisher != null)
            publisher.stop();
        statusMonitor.stop();
    }

    /**
     * Callback from native stack
     * @param rawInfo - the raw direct ByteBuffer store shared with native stack
     */
    public boolean beaconEvent(ByteBuffer rawInfo) {
        // First get a read only ByteBuffer view for efficient testing of the event info
        BeaconInfo info = new BeaconInfo(rawInfo);
        info.setScannerID(parseCommand.scannerID);
        eventCount ++;
        if(log.isTraceEnabled()) {
            log.tracef("beaconEvent(), uuid=%s, major=%d, minor=%d, rssi=%d\n",
                info.uuid, info.major, info.minor, info.rssi);
        }

        // Check for a termination marker every 1000 events or 5 seconds
        boolean stop = false;
        long elapsed = info.time - lastMarkerCheckTime;
        if((eventCount % 1000) == 0 || elapsed > 5000) {
            lastMarkerCheckTime = info.time;
            stop = stopMarkerExists();
            log.infof("beaconEvent(time=%d), status eventCount=%d, stop=%b\n", info.time, eventCount, stop);
        }
        // Check max event count limit
        if(maxEventCount > 0 && eventCount >= maxEventCount)
            stop = true;

        // Check for heartbeat
        boolean isHeartbeat = parseCommand.heartbeatUUID.compareTo(info.uuid) == 0;
        if(parseCommand.isBatteryTestMode()) {
            // Send the raw unaveraged heartbeat info, or ignore non-heartbeat events
            if(isHeartbeat)
                sendRawHeartbeat(info);
        } else {
            // Merge the event into the current time window
            EventsBucket bucket = timeWindow.addEvent(info, isHeartbeat);
            statusInformation.addEvent(info, isHeartbeat);
            // Now handle the bucket if a new one has been created
            if (bucket != null) {
                if (!parseCommand.isSkipPublish()) {
                    eventExchanger.offerLast(bucket);
                } else {
                    if (parseCommand.isAnalyzeMode()) {
                        printBeaconCounts(bucket);
                    } else {
                        if (!isHeartbeat || (isHeartbeat && !parseCommand.isSkipHeartbeat()))
                            printBeaconCounts(info, bucket);
                    }
                }
                // Display either the closest beacon or status
                if (scannerView != null) {
                    if (scannerView.isDisplayBeaconsMode())
                        displayClosestBeacon(bucket);
                    else
                        displayStatus();
                }
            }
        }
        // If stop is true, notify any callers in waitForStop
        if(stop) {
            synchronized (this) {
                stopped = true;
                this.notifyAll();
            }
        }
        return stop;
    }

    /**
     *
     */
    public synchronized void waitForStop() {
        try {
            while(stopped == false)
                this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void printBeaconCounts(BeaconInfo beacon, EventsBucket bucket) {
        log.infof("Window: parsed(%s):\n", beacon.toString());
        printBeaconCounts(bucket);
    }
    void printBeaconCounts(EventsBucket bucket) {
        StringBuilder tmp = new StringBuilder();
        bucket.toString(tmp);
        log.infof("%s\n", tmp.toString());
    }

    void sendRawHeartbeat(BeaconInfo info) {
        Beacon beacon = new Beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major, info.minor,
            info.power, info.rssi, info.time);
        beacon.setMessageType(MsgType.SCANNER_HEARTBEAT.ordinal());
        publisher.publishStatus(beacon);
        lastRSSI[heartbeatCount%10] = info.rssi;
        heartbeatCount ++;
        if(heartbeatCount % 100 == 0) {
            log.infof("Last[10].RSSI:");
            for(int n = 0; n < 10; n ++)
                log.infof("%d,", lastRSSI[n]);
            log.infof("\n");
        }
    }

    /**
     * Display the closest beacon seen in the given even bucket
     * @param bucket collection of beacon events seen in last time window
     */
    void displayClosestBeacon(EventsBucket bucket) {
        int maxRSSI = -100;
        BeaconInfo closest = null;
        BeaconInfo heartbeat = null;
        for(Map.Entry<Integer,BeaconInfo> iter : bucket.getBucket().entrySet()) {
            if(iter.getValue().getRssi() > maxRSSI) {
                BeaconInfo info = iter.getValue();
                if(parseCommand.heartbeatUUID.compareTo(info.getUuid()) == 0)
                    heartbeat = info;
                else {
                    maxRSSI = info.rssi;
                    closest = info;
                }
            }
        }
        if(closest != null) {
            log.infof("closestBeacon: %s", closest);
            scannerView.displayBeacon(closest);
        } else if(heartbeat != null) {
            // The only beacon seen was the heartbeat beacon, so display it
            scannerView.displayHeartbeat(heartbeat);
        }
    }

    /**
     * Display the current scanner status on the scannerview
     */
    void displayStatus() {
        scannerView.displayStatus(statusInformation);
    }

    private void loadBeaconMapping(String beaconMapping) {
        if (beaconMapping.startsWith("file:")) {
            File propFile = new File(beaconMapping.substring(5));
            try {
                this.beaconMapper = new PropertiesMapper(propFile);
            } catch (IOException e) {
                log.warn("Failed to load beacon mapping file: " + beaconMapping, e);
            }
        } else {
            this.beaconMapper = new PropertiesMapper(beaconMapping);
        }
    }
}


text:
package java.security.cert;

public interface CertSelector
  extends java.lang.Cloneable
{
  // Methods

  public java.lang.Object clone();
  public boolean match(Certificate arg1);
}


text:
package org.jetbrains.plugins.hocon.codestyle

import com.intellij.application.options.{CodeStyleAbstractConfigurable, TabbedLanguageCodeStylePanel}
import com.intellij.psi.codeStyle.{CodeStyleSettings, CodeStyleSettingsProvider, DisplayPriority}
import org.jetbrains.plugins.hocon.lang.HoconLanguage

class HoconCodeStyleSettingsProvider extends CodeStyleSettingsProvider {

  override def getConfigurableDisplayName = "HOCON"

  override def getPriority = DisplayPriority.COMMON_SETTINGS

  def createSettingsPage(settings: CodeStyleSettings, originalSettings: CodeStyleSettings): CodeStyleAbstractConfigurable =
    new CodeStyleAbstractConfigurable(settings, originalSettings, "HOCON") {
      override protected def createPanel(settings: CodeStyleSettings): TabbedLanguageCodeStylePanel =
        new TabbedLanguageCodeStylePanel(HoconLanguage, getCurrentSettings, settings) {}
    }

  override def createCustomSettings(settings: CodeStyleSettings) =
    new HoconCustomCodeStyleSettings(settings)
}


text:
@implementation Grupo

@dynamic fechaCreacion;
@dynamic id;
@dynamic nombre;
@dynamic tipo;
@dynamic usuarios;

@end


text:
<?php

declare(strict_types=1);

namespace Shopware\PluginInfo\Backend;

/**
 * Automatically detect the required backend
 */
class AutoDetect implements BackendInterface
{
    /**
     * @param array|string $plugin
     *
     * @throws \RuntimeException
     */
    public function getPluginInfo($plugin): array
    {
        switch (true) {
            case \is_array($plugin):
                $backend = new ArrayTestCase();
                break;
            case is_dir($plugin):
                $backend = new Directory();
                break;
            case is_file($plugin):
                $backend = new Zip();
                break;
            default:
                throw new \RuntimeException('Could not automatically detect type of given plugin');
        }

        return $backend->getPluginInfo($plugin);
    }
}


text:
<!DOCTYPE html>

  <wicket:panel>

        <wicket:message key="tags" />

          <button wicket:id="create" class="btn btn-primary">

            <wicket:message key="create"/>
          </button>

        <select wicket:id="tag" class="form-control"></select>

  </wicket:panel>


text:
package todoapp.dom.seed.roles;

import org.isisaddons.module.security.dom.permission.ApplicationPermissionMode;
import org.isisaddons.module.security.dom.permission.ApplicationPermissionRule;
import org.isisaddons.module.security.seed.scripts.AbstractRoleAndPermissionsFixtureScript;

public class TogglzModuleAdminRole extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "isis-module-togglz-admin";

    public TogglzModuleAdminRole() {
        super(ROLE_NAME, "Admin access to feature toggle");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.isisaddons.module.togglz.glue");
    }

}


text:
package core

import (
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/event"
	"github.com/ethereum/go-ethereum/params"
)

func ExampleGenerateChain() {
	params.MinGasLimit = big.NewInt(125000)      // Minimum the gas limit may ever be.
	params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.

	var (
		key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
		key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
		key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
		addr1   = crypto.PubkeyToAddress(key1.PublicKey)
		addr2   = crypto.PubkeyToAddress(key2.PublicKey)
		addr3   = crypto.PubkeyToAddress(key3.PublicKey)
		db, _   = ethdb.NewMemDatabase()
		signer  = types.HomesteadSigner{}
	)

	chainConfig := &params.ChainConfig{
		HomesteadBlock: new(big.Int),
	}
	// Ensure that key1 has some funds in the genesis block.
	genesis := WriteGenesisBlockForTesting(db, GenesisAccount{addr1, big.NewInt(1000000)})

	// This call generates a chain of 5 blocks. The function runs for
	// each block and adds different features to gen based on the
	// block index.
	chain, _ := GenerateChain(chainConfig, genesis, db, 5, func(i int, gen *BlockGen) {
		switch i {
		case 0:
			// In block 1, addr1 sends addr2 some ether.
			tx, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(signer, key1)
			gen.AddTx(tx)
		case 1:
			// In block 2, addr1 sends some more ether to addr2.
			// addr2 passes it on to addr3.
			tx1, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key1)
			tx2, _ := types.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key2)
			gen.AddTx(tx1)
			gen.AddTx(tx2)
		case 2:
			// Block 3 is empty but was mined by addr3.
			gen.SetCoinbase(addr3)
			gen.SetExtra([]byte("yeehaw"))
		case 3:
			// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
			b2 := gen.PrevBlock(1).Header()
			b2.Extra = []byte("foo")
			gen.AddUncle(b2)
			b3 := gen.PrevBlock(2).Header()
			b3.Extra = []byte("foo")
			gen.AddUncle(b3)
		}
	})

	// Import the chain. This runs all block validation rules.
	evmux := &event.TypeMux{}
	blockchain, _ := NewBlockChain(db, chainConfig, FakePow{}, evmux)
	if i, err := blockchain.InsertChain(chain); err != nil {
		fmt.Printf("insert error (block %d): %v\n", chain[i].NumberU64(), err)
		return
	}

	state, _ := blockchain.State()
	fmt.Printf("last block: #%d\n", blockchain.CurrentBlock().Number())
	fmt.Println("balance of addr1:", state.GetBalance(addr1))
	fmt.Println("balance of addr2:", state.GetBalance(addr2))
	fmt.Println("balance of addr3:", state.GetBalance(addr3))
	// Output:
	// last block: #5
	// balance of addr1: 989000
	// balance of addr2: 10000
	// balance of addr3: 19687500000000001000
}


text:
<!-- IBM_PROLOG_BEGIN_TAG                                                   -->
<!-- This is an automatically generated prolog.                             -->
<!--                                                                        -->
<!-- $Source: src/import/chips/p9/procedures/xml/error_info/p9_sbe_nest_startclocks_errors.xml $ -->
<!--                                                                        -->
<!-- OpenPOWER HostBoot Project                                             -->
<!--                                                                        -->
<!-- Contributors Listed Below - COPYRIGHT 2015,2016                        -->
<!-- [+] International Business Machines Corp.                              -->
<!--                                                                        -->
<!--                                                                        -->
<!-- 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.                         -->
<!--                                                                        -->
<!-- IBM_PROLOG_END_TAG                                                     -->
<!-- This is an automatically generated file. -->
<!-- File: p9_sbe_nest_startclocks_errors.xml. -->
<!-- Halt codes for p9_sbe_nest_startclocks -->

<hwpErrors>

</hwpErrors>


text:
# Faceting

SolrNet supports [faceted searching](http://wiki.apache.org/solr/SolrFacetingOverview).

There are basically three kinds of facet queries:

 1. querying by field
 1. date facets
 1. arbitrary facet queries

Facet queries are issued through the `FacetQueries` property of `QueryOptions`. Then the `QueryOptions` instance is passed to the server instance.

### Querying by field
Querying by field is handled by the `SolrFacetFieldQuery` class. Results are available through the `FacetFields` property.

Example: print all categories sorted by popularity.

```c#
ISolrOperations<Document> solr = ...
var r = solr.Query(SolrQuery.All, new QueryOptions {
    Rows = 0,
    Facet = new FacetParameters {
        Queries = new[] {new SolrFacetFieldQuery("category")}
    }
});
foreach (var facet in r.FacetFields["category"]) {
  Console.WriteLine("{0}: {1}", facet.Key, facet.Value);
}
```

### Date facets
Date facet queries create facets from date ranges. Sample code:

```C#
ISolrOperations<Product> solr = ...
var results = solr.Query(SolrQuery.All, new QueryOptions {
    Facet = new FacetParameters {
        Queries = new[] {
            new SolrFacetDateQuery("timestamp", new DateTime(2001, 1, 1).AddDays(-1) /* range start */, new DateTime(2001, 1, 1).AddMonths(1) /* range end */, "+1DAY" /* gap */) {
                HardEnd = true,
                Other = new[] {FacetDateOther.After, FacetDateOther.Before}
            },
        }
    }
});
DateFacetingResult dateFacetResult = results.FacetDates["timestamp"];
foreach (KeyValuePair<DateTime, int> dr in dateFacetResult.DateResults) {
    Console.WriteLine(dr.Key);
    Console.WriteLine(dr.Value);
}
```

### Arbitrary facet queries
Arbitrary facet queries are handled by the `SolrFacetQuery` class. Results are available through the `FacetQueries` property.

Example: segregate items by price (less than $500 - more than $500)

```C#
ISolrOperations<Document> solr = ...
var lessThan500 = new SolrQueryByRange<decimal>("price", 0m, 500m);
var moreThan500 = new SolrQueryByRange<string>("price", "500", "*");
var r = solr.Query(SolrQuery.All, new QueryOptions {
    Rows = 0,
    Facet = new FacetParameters {
        Queries = new[] {new SolrFacetQuery(lessThan500), new SolrFacetQuery(moreThan500)}
    }
});
foreach (var facet in r.FacetQueries) {
  Console.WriteLine("{0}: {1}", facet.Key, facet.Value);
}
```

### Pivot faceting
http://wiki.apache.org/solr/HierarchicalFaceting#Pivot_Facets

http://wiki.apache.org/solr/SimpleFacetParameters#Pivot_.28ie_Decision_Tree.29_Faceting

(to be documented)


text:
using System.Collections.Generic;
using osu.Game.Scoring;
using osu.Game.Screens.Multi.Ranking.Types;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Ranking.Types;

namespace osu.Game.Screens.Multi.Ranking
{
    public class MatchResults : Results
    {
        public MatchResults(ScoreInfo score)
            : base(score)
        {
        }

        protected override IEnumerable<IResultPageInfo> CreateResultPages() => new IResultPageInfo[]
        {
            new ScoreOverviewPageInfo(Score, Beatmap.Value),
            new LocalLeaderboardPageInfo(Score, Beatmap.Value),
            new RoomLeaderboardPageInfo(Score, Beatmap.Value),
        };
    }
}


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Pages;

/**
 * PagesSearch represents the model behind the search form about `common\models\Pages`.
 */
class PagesSearch extends Pages
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status'], 'integer'],
            [['title_ru', 'slug', 'content_ru', 'created_at', 'updated_at'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Pages::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'title_ru', $this->title_ru])
            ->andFilterWhere(['like', 'slug', $this->slug])
            ->andFilterWhere(['like', 'content_ru', $this->content_ru]);

        return $dataProvider;
    }
}


text:
var mongoose = require('mongoose');
var url = 'mongodb://localhost/ctf01';

var db = mongoose.createConnection(url, function(err, res) {
  if (err) console.log('Error connected: ' + url + ' - ' + err);
  else     console.log('Success connected: ' + url);
});

exports.User = db.model('User', new mongoose.Schema({
    id        : String,
    password  : String,
    score     : Number,
    solved_challenges: Array,
}, { collection: 'user' }));

/*
exports.Problem = db.model('Problem', new mongoose.Schema({
    id        : Number,
    title     : String,
    point     : Number,
    category  : Number,
    content   : String,
    flag      : String
}, { collection: 'problem' }));
*/


text:
<?php

namespace PharIo\Manifest;

class ManifestDocumentMapperTest extends \PHPUnit\Framework\TestCase {
    /**
     * @dataProvider dataProvider
     *
     * @param $expected
     *
     * @uses         \PharIo\Manifest\Application
     * @uses         \PharIo\Manifest\ApplicationName
     * @uses         \PharIo\Manifest\Library
     * @uses         \PharIo\Manifest\Extension
     * @uses         \PharIo\Manifest\ExtensionElement
     */
    public function testCanSerializeToString($expected) {
        $manifestDocument = ManifestDocument::fromFile($expected);
        $mapper           = new ManifestDocumentMapper();

        $this->assertInstanceOf(
            Manifest::class,
            $mapper->map($manifestDocument)
        );
    }

    public function dataProvider() {
        return [
            'application' => [__DIR__ . '/_fixture/phpunit-5.6.5.xml'],
            'library'     => [__DIR__ . '/_fixture/library.xml'],
            'extension'   => [__DIR__ . '/_fixture/extension.xml']
        ];
    }

    public function testThrowsExceptionOnUnsupportedType() {
        $manifestDocument = ManifestDocument::fromFile(__DIR__ . '/_fixture/custom.xml');
        $mapper           = new ManifestDocumentMapper();

        $this->expectException(ManifestDocumentMapperException::class);
        $mapper->map($manifestDocument);
    }

    public function testInvalidVersionInformationThrowsException() {
        $manifestDocument = ManifestDocument::fromFile(__DIR__ . '/_fixture/invalidversion.xml');
        $mapper           = new ManifestDocumentMapper();

        $this->expectException(ManifestDocumentMapperException::class);
        $mapper->map($manifestDocument);
    }

    public function testInvalidVersionConstraintThrowsException() {
        $manifestDocument = ManifestDocument::fromFile(__DIR__ . '/_fixture/invalidversionconstraint.xml');
        $mapper           = new ManifestDocumentMapper();

        $this->expectException(ManifestDocumentMapperException::class);
        $mapper->map($manifestDocument);
    }

    /**
     * @uses \PharIo\Manifest\ExtensionElement
     */
    public function testInvalidCompatibleConstraintThrowsException() {
        $manifestDocument = ManifestDocument::fromFile(__DIR__ . '/_fixture/extension-invalidcompatible.xml');
        $mapper           = new ManifestDocumentMapper();

        $this->expectException(ManifestDocumentMapperException::class);
        $mapper->map($manifestDocument);
    }

}


text:
// Fantasy Adventure Environment
// Copyright Staggart Creations
// staggart.xyz

using UnityEngine;
using System.Collections;

namespace FAE
{
#if UNITY_EDITOR
    using UnityEditor;
    [ExecuteInEditMode]
#endif

    /// <summary>
    /// Sets world-space obstacle position and bending strength on the FAE foliage shader
    /// </summary>
    public class FoliageBender : MonoBehaviour
    {

        [Range(0f, 100f)]
        public float strength = 20f;
        [Range(0f, 5f)]
        public float radius = 1.5f;

        void Update()
        {
            Shader.SetGlobalVector("_ObstaclePosition", this.transform.position);
            Shader.SetGlobalFloat("_BendingStrength", strength);
            Shader.SetGlobalFloat("_BendingRadius", radius);
        }
    }
}


text:
/* global module*/

module.exports = function(config) {
	"use strict";

	config.set({

		basePath: 'webapp',

		frameworks: ['qunit', 'openui5'],

		openui5: {
			path: 'http://localhost:8080/resources/sap-ui-core.js',
			useMockServer : true

		},

		client: {
			openui5: {
				config: {
					theme: 'sap_belize',
					language: 'EN',
					animation: false,
					compatVersion: 'edge',
					async: true,
					resourceroots: {'sap.ui.demo.basicTemplate': './base'}
				},
				tests: [
					'sap/ui/demo/basicTemplate/test/unit/AllTests',
					'sap/ui/demo/basicTemplate/test/integration/AllJourneys'
				],
				mockserver: {
					metadataURL: '/base/localService/metadata.xml'
				}
			},
			clearContext: false,
			qunit: {
				showUI: true
			}
		},

		files: [
			{ pattern: '**', included: false, served: true, watched: true}
		],

		reporters: ['progress'],

		logLevel: config.LOG_INFO,

		browserConsoleLogOptions: {
			level: 'warn'
		},

		autoWatch: true,

		browsers: ['Chrome'],

		singleRun: false
	});
};