text:
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Kachuwa.Identity.Extensions;
using Kachuwa.Web;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Connections.Features;
using Microsoft.AspNetCore.SignalR;

namespace Kachuwa.RTC.Hubs
{

    //[Authorize(JwtBearerDefaults.AuthenticationScheme)]
    //[Authorize]
    public class BaseHub : Hub
    {
        public readonly IRTCConnectionManager ConnectionManager;

        public BaseHub(IRTCConnectionManager connectionManager)
        {
            ConnectionManager = connectionManager;
        }

        public   override Task OnConnectedAsync()
        {
            string connectionId = Context.ConnectionId;
            var rtcUser = new RTCUser();
            var context = ContextResolver.Context;
            string ua = context.Request.Headers["User-Agent"].ToString();
            rtcUser.UserDevice = ua;
            rtcUser.ConnectionIds.Add(connectionId);
            rtcUser.IdentityUserId = context.User.Identity.GetIdentityUserId();
            rtcUser.SessionId = context.Session.Id;

            rtcUser.HubNames.Add(this.GetType().Name);
            //rtcUser.IsFromMobile = false;
            rtcUser.IsFromWeb = true;
            rtcUser.UserRoles = string.Join(',', context.User.Identity.GetRoles());
            rtcUser.ConnectionId = connectionId;
            ConnectionManager.AddUser(rtcUser);

                try
                 {
                    var status =  ConnectionManager.GetOnlineUserStatus().Result;
                     Clients.All.SendAsync("OnUserChange", status);
                }
                catch (Exception e)
                {

                }

            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            ConnectionManager.RemoveUser(Context.ConnectionId);
            try
            {
                var status = ConnectionManager.GetOnlineUserStatus().Result;
                Clients.All.SendAsync("OnUserChange", status);
            }
            catch (Exception e)
            {

            }

            return base.OnDisconnectedAsync(exception);
        }
    }
}


text:
import argparse

parser = argparse.ArgumentParser(description='''
        the argparse module test
''')

parser.add_argument('-l', '--list', help='a list', nargs='*', default=[])
args = parser.parse_args()

print(args.list)

redpajama_set_name: RedPajamaGithub


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

namespace FLS.Server.Service.RulesEngine
{
    public abstract class BaseRule<T> : IRule<T>
    {
        protected Logger Logger { get; set; } = LogManager.GetLogger("FLS.Server.Service.RulesEngine.BaseRule");

        protected BaseRule()
        {
            Conditions = new List<ICondition>();
        }

        public IList<ICondition> Conditions { get; set; }

        public void ClearConditions()
        {
            Conditions.Clear();
            RuleApplied = false;
        }

        public virtual bool IsValid()
        {
            return Conditions.All(x => x.IsSatisfied());
        }

        public abstract void Initialize(T obj);

        public virtual T Apply(T obj)
        {
            RuleApplied = true;
            Logger.Debug($"Applied rule {this}");
            return obj;
        }

        public virtual T ElseApply(T obj)
        {
            Logger.Debug($"NOT applied rule {this}");
            return obj;
        }

        public bool RuleApplied { get; protected set; }

        public bool StopRuleEngineWhenRuleApplied { get; set; }

        public override string ToString()
        {
            return $"{this.GetType().Name}, Nr of Conditions={Conditions.Count}, RuleApplied={RuleApplied}, StopRuleEngineWhenRuleApplied={StopRuleEngineWhenRuleApplied}";
        }
    }
}


text:
package com.alibaba.dubbo.examples.generic.api;

import java.io.Serializable;

import com.alibaba.dubbo.examples.generic.api.IUserService.Params;
import com.alibaba.dubbo.examples.generic.api.IUserService.User;

/**
 * @author chao.liuc
 *
 */
public interface IUserService extends IService<Params, User> {

    public static class Params implements Serializable {
        private static final long serialVersionUID = 1L;

        public Params(String query) {
        }
    }

    public static class User implements Serializable {
        private static final long serialVersionUID = 1L;

        public User(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + "]";
        }
    }
}


text:
package com.microsoft.azure.management.customerinsights;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The error mangement.
 */
public class ConnectorMappingErrorManagement {
    /**
     * The type of error management to use for the mapping. Possible values
     * include: 'RejectAndContinue', 'StopImport', 'RejectUntilLimit'.
     */
    @JsonProperty(value = "errorManagementType", required = true)
    private ErrorManagementTypes errorManagementType;

    /**
     * The error limit allowed while importing data.
     */
    @JsonProperty(value = "errorLimit")
    private Integer errorLimit;

    /**
     * Get the errorManagementType value.
     *
     * @return the errorManagementType value
     */
    public ErrorManagementTypes errorManagementType() {
        return this.errorManagementType;
    }

    /**
     * Set the errorManagementType value.
     *
     * @param errorManagementType the errorManagementType value to set
     * @return the ConnectorMappingErrorManagement object itself.
     */
    public ConnectorMappingErrorManagement withErrorManagementType(ErrorManagementTypes errorManagementType) {
        this.errorManagementType = errorManagementType;
        return this;
    }

    /**
     * Get the errorLimit value.
     *
     * @return the errorLimit value
     */
    public Integer errorLimit() {
        return this.errorLimit;
    }

    /**
     * Set the errorLimit value.
     *
     * @param errorLimit the errorLimit value to set
     * @return the ConnectorMappingErrorManagement object itself.
     */
    public ConnectorMappingErrorManagement withErrorLimit(Integer errorLimit) {
        this.errorLimit = errorLimit;
        return this;
    }

}


text:
--+ holdcas on;
set system parameters 'dont_reuse_heap_file=yes';
create table tb (a int unique, b int);
create index i_tb_all on tb(a,b) with online;
create index i_tb_b on tb(b) with online;
insert into tb values (1,1);
insert into tb values (2,2);
insert into tb values (3,3);
insert into tb values (4,null);
insert into tb values (null, null);
insert into tb values (null, 1);
select /*+ recompile */ * from tb where a is null order by a;
select /*+ recompile */ * from tb where b is null or b is not null;
select /*+ recompile */ b from tb where b >0;

drop table tb;

set system parameters 'dont_reuse_heap_file=no';
commit;
--+ holdcas off;


text:
Track and replicate DML changes

####Documentation
http://jeffreypolk.github.io/sql-track-change


text:
"""See docstring for MozillaURLProvider class"""

import re
import urllib
import urllib2
import urlparse
from distutils.version import LooseVersion

from autopkglib import Processor, ProcessorError

__all__ = ["MozillaURLProvider"]

MOZ_BASE_URL = "https://download.mozilla.org/?product=%s-%s&os=osx&lang=%s"

# As of 16 Nov 2015 here are the supported products:
# firefox-latest
# firefox-esr-latest
# firefox-beta-latest
# thunderbird-latest
# thunderbird-beta-latest
#
# See also:
#    http://ftp.mozilla.org/pub/firefox/releases/latest/README.txt
#    http://ftp.mozilla.org/pub/firefox/releases/latest-esr/README.txt
#    http://ftp.mozilla.org/pub/firefox/releases/latest-beta/README.txt
#    http://ftp.mozilla.org/pub/thunderbird/releases/latest/README.txt
#    http://ftp.mozilla.org/pub/thunderbird/releases/latest-beta/README.txt

class MozillaURLProvider(Processor):
    """Provides URL to the latest Firefox release."""
    description = __doc__
    input_variables = {
        "product_name": {
            "required": True,
            "description":
                "Product to fetch URL for. One of 'firefox', 'thunderbird'.",
        },
        "release": {
            "required": False,
            "default": 'latest',
            "description": (
                "Which release to download. Examples: 'latest', "
                "'esr-latest', 'beta-latest'. Defaults to 'latest'"),
        },
        "locale": {
            "required": False,
            "default": 'en-US',
            "description":
                "Which localization to download, default is 'en-US'.",
        },
        "base_url": {
            "required": False,
            "description": "Default is '%s." % MOZ_BASE_URL,
        },
    }
    output_variables = {
        "url": {
            "description": "URL to the latest Mozilla product release.",
        },
    }

    def get_mozilla_dmg_url(self, base_url, product_name, release, locale):
        """Assemble download URL for Mozilla product"""
        #pylint: disable=no-self-use
        # Allow locale as both en-US and en_US.
        locale = locale.replace("_", "-")

        # fix releases into new format
        if release == 'latest-esr':
            release = 'esr-latest'
        if release == 'latest-beta':
            release = 'beta-latest'

        # Construct download URL.
        return base_url % (product_name, release, locale)

    def main(self):
        """Provide a Mozilla download URL"""
        # Determine product_name, release, locale, and base_url.
        product_name = self.env["product_name"]
        release = self.env.get("release", "latest")
        locale = self.env.get("locale", "en-US")
        base_url = self.env.get("base_url", MOZ_BASE_URL)

        self.env["url"] = self.get_mozilla_dmg_url(
            base_url, product_name, release, locale)
        self.output("Found URL %s" % self.env["url"])

if __name__ == "__main__":
    PROCESSOR = MozillaURLProvider()
    PROCESSOR.execute_shell()


text:
{{ header }}

.. _api.indexing:

=============
Index objects
=============

Index
-----
.. currentmodule:: pandas

**Many of these methods or variants thereof are available on the objects
that contain an index (Series/DataFrame) and those should most likely be
used before calling these methods directly.**

.. autosummary::
   :toctree: api/

   Index

Properties
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.values
   Index.is_monotonic
   Index.is_monotonic_increasing
   Index.is_monotonic_decreasing
   Index.is_unique
   Index.has_duplicates
   Index.hasnans
   Index.dtype
   Index.inferred_type
   Index.is_all_dates
   Index.shape
   Index.name
   Index.names
   Index.nbytes
   Index.ndim
   Index.size
   Index.empty
   Index.T
   Index.memory_usage

Modifying and computations
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.all
   Index.any
   Index.argmin
   Index.argmax
   Index.copy
   Index.delete
   Index.drop
   Index.drop_duplicates
   Index.duplicated
   Index.equals
   Index.factorize
   Index.identical
   Index.insert
   Index.is_
   Index.is_boolean
   Index.is_categorical
   Index.is_floating
   Index.is_integer
   Index.is_interval
   Index.is_mixed
   Index.is_numeric
   Index.is_object
   Index.min
   Index.max
   Index.reindex
   Index.rename
   Index.repeat
   Index.where
   Index.take
   Index.putmask
   Index.unique
   Index.nunique
   Index.value_counts

Compatibility with MultiIndex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.set_names
   Index.droplevel

Missing values
~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.fillna
   Index.dropna
   Index.isna
   Index.notna

Conversion
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.astype
   Index.item
   Index.map
   Index.ravel
   Index.to_list
   Index.to_native_types
   Index.to_series
   Index.to_frame
   Index.view

Sorting
~~~~~~~
.. autosummary::
   :toctree: api/

   Index.argsort
   Index.searchsorted
   Index.sort_values

Time-specific operations
~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.shift

Combining / joining / set operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.append
   Index.join
   Index.intersection
   Index.union
   Index.difference
   Index.symmetric_difference

Selecting
~~~~~~~~~
.. autosummary::
   :toctree: api/

   Index.asof
   Index.asof_locs
   Index.get_indexer
   Index.get_indexer_for
   Index.get_indexer_non_unique
   Index.get_level_values
   Index.get_loc
   Index.get_slice_bound
   Index.get_value
   Index.isin
   Index.slice_indexer
   Index.slice_locs

.. _api.numericindex:

Numeric Index
-------------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   NumericIndex
   RangeIndex
   Int64Index
   UInt64Index
   Float64Index

.. We need this autosummary so that the methods are generated.
.. Separate block, since they aren't classes.

.. autosummary::
   :toctree: api/

   RangeIndex.start
   RangeIndex.stop
   RangeIndex.step
   RangeIndex.from_range

.. _api.categoricalindex:

CategoricalIndex
----------------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   CategoricalIndex

Categorical components
~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   CategoricalIndex.codes
   CategoricalIndex.categories
   CategoricalIndex.ordered
   CategoricalIndex.rename_categories
   CategoricalIndex.reorder_categories
   CategoricalIndex.add_categories
   CategoricalIndex.remove_categories
   CategoricalIndex.remove_unused_categories
   CategoricalIndex.set_categories
   CategoricalIndex.as_ordered
   CategoricalIndex.as_unordered

Modifying and computations
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   CategoricalIndex.map
   CategoricalIndex.equals

.. _api.intervalindex:

IntervalIndex
-------------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   IntervalIndex

IntervalIndex components
~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   IntervalIndex.from_arrays
   IntervalIndex.from_tuples
   IntervalIndex.from_breaks
   IntervalIndex.left
   IntervalIndex.right
   IntervalIndex.mid
   IntervalIndex.closed
   IntervalIndex.length
   IntervalIndex.values
   IntervalIndex.is_empty
   IntervalIndex.is_non_overlapping_monotonic
   IntervalIndex.is_overlapping
   IntervalIndex.get_loc
   IntervalIndex.get_indexer
   IntervalIndex.set_closed
   IntervalIndex.contains
   IntervalIndex.overlaps
   IntervalIndex.to_tuples

.. _api.multiindex:

MultiIndex
----------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   MultiIndex

.. autosummary::
   :toctree: api/

   IndexSlice

MultiIndex constructors
~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   MultiIndex.from_arrays
   MultiIndex.from_tuples
   MultiIndex.from_product
   MultiIndex.from_frame

MultiIndex properties
~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   MultiIndex.names
   MultiIndex.levels
   MultiIndex.codes
   MultiIndex.nlevels
   MultiIndex.levshape
   MultiIndex.dtypes

MultiIndex components
~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   MultiIndex.set_levels
   MultiIndex.set_codes
   MultiIndex.to_flat_index
   MultiIndex.to_frame
   MultiIndex.sortlevel
   MultiIndex.droplevel
   MultiIndex.swaplevel
   MultiIndex.reorder_levels
   MultiIndex.remove_unused_levels

MultiIndex selecting
~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   MultiIndex.get_loc
   MultiIndex.get_locs
   MultiIndex.get_loc_level
   MultiIndex.get_indexer
   MultiIndex.get_level_values

.. _api.datetimeindex:

DatetimeIndex
-------------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   DatetimeIndex

Time/date components
~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   DatetimeIndex.year
   DatetimeIndex.month
   DatetimeIndex.day
   DatetimeIndex.hour
   DatetimeIndex.minute
   DatetimeIndex.second
   DatetimeIndex.microsecond
   DatetimeIndex.nanosecond
   DatetimeIndex.date
   DatetimeIndex.time
   DatetimeIndex.timetz
   DatetimeIndex.dayofyear
   DatetimeIndex.day_of_year
   DatetimeIndex.weekofyear
   DatetimeIndex.week
   DatetimeIndex.dayofweek
   DatetimeIndex.day_of_week
   DatetimeIndex.weekday
   DatetimeIndex.quarter
   DatetimeIndex.tz
   DatetimeIndex.freq
   DatetimeIndex.freqstr
   DatetimeIndex.is_month_start
   DatetimeIndex.is_month_end
   DatetimeIndex.is_quarter_start
   DatetimeIndex.is_quarter_end
   DatetimeIndex.is_year_start
   DatetimeIndex.is_year_end
   DatetimeIndex.is_leap_year
   DatetimeIndex.inferred_freq

Selecting
~~~~~~~~~
.. autosummary::
   :toctree: api/

   DatetimeIndex.indexer_at_time
   DatetimeIndex.indexer_between_time

Time-specific operations
~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

   DatetimeIndex.normalize
   DatetimeIndex.strftime
   DatetimeIndex.snap
   DatetimeIndex.tz_convert
   DatetimeIndex.tz_localize
   DatetimeIndex.round
   DatetimeIndex.floor
   DatetimeIndex.ceil
   DatetimeIndex.month_name
   DatetimeIndex.day_name

Conversion
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   DatetimeIndex.to_period
   DatetimeIndex.to_perioddelta
   DatetimeIndex.to_pydatetime
   DatetimeIndex.to_series
   DatetimeIndex.to_frame

Methods
~~~~~~~
.. autosummary::
    :toctree: api/

    DatetimeIndex.mean

TimedeltaIndex
--------------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   TimedeltaIndex

Components
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   TimedeltaIndex.days
   TimedeltaIndex.seconds
   TimedeltaIndex.microseconds
   TimedeltaIndex.nanoseconds
   TimedeltaIndex.components
   TimedeltaIndex.inferred_freq

Conversion
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   TimedeltaIndex.to_pytimedelta
   TimedeltaIndex.to_series
   TimedeltaIndex.round
   TimedeltaIndex.floor
   TimedeltaIndex.ceil
   TimedeltaIndex.to_frame

Methods
~~~~~~~
.. autosummary::
    :toctree: api/

    TimedeltaIndex.mean

.. currentmodule:: pandas

PeriodIndex
-----------
.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   PeriodIndex

Properties
~~~~~~~~~~
.. autosummary::
    :toctree: api/

    PeriodIndex.day
    PeriodIndex.dayofweek
    PeriodIndex.day_of_week
    PeriodIndex.dayofyear
    PeriodIndex.day_of_year
    PeriodIndex.days_in_month
    PeriodIndex.daysinmonth
    PeriodIndex.end_time
    PeriodIndex.freq
    PeriodIndex.freqstr
    PeriodIndex.hour
    PeriodIndex.is_leap_year
    PeriodIndex.minute
    PeriodIndex.month
    PeriodIndex.quarter
    PeriodIndex.qyear
    PeriodIndex.second
    PeriodIndex.start_time
    PeriodIndex.week
    PeriodIndex.weekday
    PeriodIndex.weekofyear
    PeriodIndex.year

Methods
~~~~~~~
.. autosummary::
    :toctree: api/

    PeriodIndex.asfreq
    PeriodIndex.strftime
    PeriodIndex.to_timestamp


text:
function Particle(stage) {
  this.stage = stage;
  this.el = document.createElement('div');
  this.el.classList.add('particle');
  this.stage.appendChild(this.el);
}

Particle.prototype.emit = function() {
  var style = window.getComputedStyle(this.stage);
  var x = (Math.random() * style.width.substr(0, style.width.length -2)) | 0;
  this.el.style.left = x + 'px';
  this.el.classList.add('fall');
}

function Game(stage) {
  this.stage = stage;
  this.fps = new FPS(document.getElementById('fps'));

  setInterval(this.emitParticle.bind(this), 40);

  // fps
  this.lastUpdate = Date.now();
  (function go() {
    var now = Date.now();
    var delta = now - this.lastUpdate;
    this.lastUpdate = now;
    this.fps.update(delta);
    requestAnimationFrame(go.bind(this));
  }.bind(this))();
}

Game.prototype.emitParticle = function() {
  for (var i = 0; i < 10; i++) {
    var particle = new Particle(this.stage);
    if (!particle) {
      return;
    }
    particle.emit();
  }
}

window.addEventListener('DOMContentLoaded', function() {
  new Game(document.getElementById('stage'));
});


text:
/**
 * @class strange.extensions.injector.impl.InjectionBinder
 *
 * The Binder for creating Injection mappings.
 *
 * @see strange.extensions.injector.api.IInjectionBinder
 * @see strange.extensions.injector.api.IInjectionBinding
 */

using System;
using System.Collections.Generic;
using strange.framework.api;
using strange.extensions.injector.api;
using strange.extensions.reflector.impl;
using strange.framework.impl;

namespace strange.extensions.injector.impl
{
	public class InjectionBinder : Binder, IInjectionBinder
	{
		private IInjector _injector;

		public InjectionBinder ()
		{
			injector = new Injector ();
			injector.binder = this;
			injector.reflector = new ReflectionBinder ();
		}

		public object GetInstance(Type key)
		{
			return GetInstance(key, null);
		}

		public virtual object GetInstance(Type key, object name)
		{
			IInjectionBinding binding = GetBinding (key, name) as IInjectionBinding;
			if (binding == null)
			{
				throw new InjectionException ("InjectionBinder has no binding for:\n\tkey: " + key + "\nname: " + name, InjectionExceptionType.NULL_BINDING);
			}
			object instance = GetInjectorForBinding(binding).Instantiate (binding);
			return instance;
		}

		protected virtual IInjector GetInjectorForBinding(IInjectionBinding binding)
		{
			return injector;
		}

		public T GetInstance<T>()
		{
			object instance = GetInstance (typeof (T));
			T retv = (T) instance;
			return retv;
		}

		public T GetInstance<T>(object name)
		{
			object instance = GetInstance (typeof (T), name);
			T retv = (T) instance;
			return retv;
		}

		override public IBinding GetRawBinding()
		{
			return new InjectionBinding (resolver);
		}

		public IInjector injector
		{
			get
			{
				return _injector;
			}
			set
			{
				if (_injector != null)
				{
					_injector.binder = null;
				}
				_injector = value;
				_injector.binder = this;
			}
		}

		new public IInjectionBinding Bind<T>()
		{
			return base.Bind<T> () as IInjectionBinding;
		}

		public IInjectionBinding Bind(Type key)
		{
			return base.Bind(key) as IInjectionBinding;
		}

		new virtual public IInjectionBinding GetBinding<T>()
		{
			return base.GetBinding<T> () as IInjectionBinding;
		}

		//SDM2014-0120: "virtual" added as dictated by changes to CrossContextInjectionBinder in relation to the cross-context implicit binding fix
		new virtual public IInjectionBinding GetBinding<T>(object name)
		{
			return base.GetBinding<T> (name) as IInjectionBinding;
		}

		//SDM2014-0120: "virtual" added as dictated by changes to CrossContextInjectionBinder in relation to the cross-context implicit binding fix
		new virtual public IInjectionBinding GetBinding(object key)
		{
			return base.GetBinding (key) as IInjectionBinding;
		}

		new virtual public IInjectionBinding GetBinding(object key, object name)
		{
			return base.GetBinding(key, name) as IInjectionBinding;
		}

		public int ReflectAll()
		{
			List<Type> list = new List<Type> ();
			foreach (KeyValuePair<object, Dictionary<object, IBinding>> pair in bindings)
			{
				Dictionary<object, IBinding> dict = pair.Value;
				foreach(KeyValuePair<object, IBinding> bPair in dict)
				{
					IBinding binding = bPair.Value as IBinding;
					Type t = (binding.value is Type) ? (Type) binding.value : binding.value.GetType();
					if (list.IndexOf(t) == -1)
					{
						list.Add (t);
					}
				}
			}
			return Reflect (list);
		}

		public int Reflect(List<Type> list)
		{
			int count = 0;
			foreach(Type t in list)
			{
				//Reflector won't permit primitive types, so screen them
				if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(string))
				{
					continue;
				}
				count ++;
				injector.reflector.Get (t);
			}
			return count;
		}
	}
}


text:
@(forgotPasswordForm: Form[org.slashgames.tournament.auth.formdata.ForgotPasswordData])

@import org.slashgames.tournament.core.views.html.main
@import org.slashgames.tournament.core.views.html.forms._

@main("Passwort vergessen") {
	<p>
		Falls Du Dein Passwort vergessen hast, kannst Du Dir eine Mail zusenden lassen, die einen Link zum Zurücksetzen Deines Passworts enthält.
	</p>

	@helper.form(org.slashgames.tournament.auth.controllers.routes.LoginController.resetPassword){
		@formError(forgotPasswordForm)

		@formInput(forgotPasswordForm, "email", "email", "E-mail")

	 	@formButton("Mail abschicken")
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_jjs"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.fredrick_tam.dinecu.JJs">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>


text:
<?php

namespace Larium\Pay\Transaction;

use Larium\Pay\TransactionException;

trait Commit
{
    /**
     * @var bool
     */
    private $committed = false;

    abstract public function canCommit();

    /**
     * {@inheritdoc}
     */
    public function commit()
    {
        if (!$this->canCommit()) {
            throw TransactionException::unableToCommit();
        }
        $this->committed = true;
    }

    /**
     * {@inheritdoc}
     */
    public function isCommitted()
    {
        return $this->committed;
    }

    /**
     * {@inheritdoc}
     */
    public function allowChanges()
    {
        if ($this->isCommitted()) {
            throw TransactionException::alreadyCommited();
        }

        return true;
    }
}


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

#include "ui/message_center/views/message_popup_collection.h"

#include <list>

#include "base/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/rect.h"
#include "ui/message_center/fake_message_center.h"
#include "ui/message_center/views/toast_contents_view.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget.h"

namespace message_center {
namespace test {

class MessagePopupCollectionTest : public views::ViewsTestBase {
 public:
  virtual void SetUp() OVERRIDE {
    views::ViewsTestBase::SetUp();
    MessageCenter::Initialize();
    collection_.reset(
        new MessagePopupCollection(GetContext(), MessageCenter::Get(), NULL));
    // This size fits test machines resolution and also can keep a few toasts
    // w/o ill effects of hitting the screen overflow. This allows us to assume
    // and verify normal layout of the toast stack.
    collection_->SetWorkAreaForTest(gfx::Rect(0, 0, 600, 400));
    id_ = 0;
  }

  virtual void TearDown() OVERRIDE {
    collection_->CloseAllWidgets();
    collection_.reset();
    MessageCenter::Shutdown();
    views::ViewsTestBase::TearDown();
  }

 protected:
  MessagePopupCollection* collection() { return collection_.get(); }

  size_t GetToastCounts() {
    return collection_->toasts_.size();
  }

  bool IsToastShown(const std::string& id) {
    views::Widget* widget = collection_->GetWidgetForTest(id);
    return widget && widget->IsVisible();
  }

  views::Widget* GetWidget(const std::string& id) {
    return collection_->GetWidgetForTest(id);
  }

  ToastContentsView* GetToast(const std::string& id) {
    for (MessagePopupCollection::Toasts::iterator iter =
             collection_->toasts_.begin();
         iter != collection_->toasts_.end(); ++iter) {
      if ((*iter)->id() == id)
        return *iter;
    }
    return NULL;
  }

  std::string AddNotification() {
    std::string id = base::IntToString(id_++);
    scoped_ptr<Notification> notification(
        new Notification(NOTIFICATION_TYPE_BASE_FORMAT,
                         id,
                         UTF8ToUTF16("test title"),
                         UTF8ToUTF16("test message"),
                         gfx::Image(),
                         string16() /* display_source */,
                         "" /* extension_id */,
                         message_center::RichNotificationData(),
                         NULL /* delegate */));
    MessageCenter::Get()->AddNotification(notification.Pass());
    return id;
  }

  // Assumes there is non-zero pending work.
  void WaitForTransitionsDone() {
    collection_->RunLoopForTest();
  }

  void CloseAllToastsAndWait() {
    // Assumes there is at least one toast to close.
    EXPECT_TRUE(GetToastCounts() > 0);
    MessageCenter::Get()->RemoveAllNotifications(false);
    WaitForTransitionsDone();
  }

  gfx::Rect GetToastRectAt(size_t index) {
    return collection_->GetToastRectAt(index);
  }

 private:
  scoped_ptr<MessagePopupCollection> collection_;
  int id_;
};

TEST_F(MessagePopupCollectionTest, DismissOnClick) {
  std::string id1 = AddNotification();
  std::string id2 = AddNotification();
  WaitForTransitionsDone();
  EXPECT_EQ(2u, GetToastCounts());
  EXPECT_TRUE(IsToastShown(id1));
  EXPECT_TRUE(IsToastShown(id2));

  MessageCenter::Get()->ClickOnNotification(id2);
  WaitForTransitionsDone();
  EXPECT_EQ(1u, GetToastCounts());
  EXPECT_TRUE(IsToastShown(id1));
  EXPECT_FALSE(IsToastShown(id2));

  MessageCenter::Get()->ClickOnNotificationButton(id1, 0);
  WaitForTransitionsDone();
  EXPECT_EQ(0u, GetToastCounts());
  EXPECT_FALSE(IsToastShown(id1));
  EXPECT_FALSE(IsToastShown(id2));
}

TEST_F(MessagePopupCollectionTest, ShutdownDuringShowing) {
  std::string id1 = AddNotification();
  std::string id2 = AddNotification();
  WaitForTransitionsDone();
  EXPECT_EQ(2u, GetToastCounts());
  EXPECT_TRUE(IsToastShown(id1));
  EXPECT_TRUE(IsToastShown(id2));

  // Finish without cleanup of notifications, which may cause use-after-free.
  // See crbug.com/236448
  GetWidget(id1)->CloseNow();
  collection()->OnMouseExited(GetToast(id2));
}

TEST_F(MessagePopupCollectionTest, DefaultPositioning) {
  std::string id0 = AddNotification();
  std::string id1 = AddNotification();
  std::string id2 = AddNotification();
  std::string id3 = AddNotification();
  WaitForTransitionsDone();

  gfx::Rect r0 = GetToastRectAt(0);
  gfx::Rect r1 = GetToastRectAt(1);
  gfx::Rect r2 = GetToastRectAt(2);
  gfx::Rect r3 = GetToastRectAt(3);

  // 3 toasts are shown, equal size, vertical stack.
  EXPECT_TRUE(IsToastShown(id0));
  EXPECT_TRUE(IsToastShown(id1));
  EXPECT_TRUE(IsToastShown(id2));

  EXPECT_EQ(r0.width(), r1.width());
  EXPECT_EQ(r1.width(), r2.width());

  EXPECT_EQ(r0.height(), r1.height());
  EXPECT_EQ(r1.height(), r2.height());

  EXPECT_GT(r0.y(), r1.y());
  EXPECT_GT(r1.y(), r2.y());

  EXPECT_EQ(r0.x(), r1.x());
  EXPECT_EQ(r1.x(), r2.x());

  // The 4th toast is not shown yet.
  EXPECT_FALSE(IsToastShown(id3));
  EXPECT_EQ(0, r3.width());
  EXPECT_EQ(0, r3.height());

  CloseAllToastsAndWait();
  EXPECT_EQ(0u, GetToastCounts());
}

// TODO(dimich): Test repositioning - both normal one and when user is closing
// the toasts.

}  // namespace test
}  // namespace message_center


text:
"use strict";

var Dispatcher = require('../appDispatcher');
var CourseApi = require('../api/CourseApi');
var ActionTypes = require('../constants/actionTypes');

var CourseActions = {
    createCourse: function(course) {
        var newCourse = CourseApi.saveCourse(course);

        // This will dispatch an author created event/action to all the stores
        Dispatcher.dispatch({
            actionType: ActionTypes.CREATE_COURSE,
            course: newCourse
        });
    },

    updateCourse: function(course) {
        var updatedCourse = CourseApi.saveCourse(course);

        Dispatcher.dispatch({
            actionType: ActionTypes.UPDATE_COURSE,
            course: updatedCourse
        });
    },

    deleteCourse: function(courseId) {
        CourseApi.deleteCourse(courseId);

        Dispatcher.dispatch({
            actionType: ActionTypes.DELETE_COURSE,
            id: courseId
        });
    }
};

module.exports = CourseActions;


text:
    <cc-panel [title]="'Package-Changes'" icon="fa-book" [collapsable]="true"
              subTitle="last update: {{host.lastSeen | date:'dd.MM.yyyy HH:mm:ss'}}">

          All Packages are in sync with the template.

            State
            Package Name
            Host version
            Template version

          <ng-template ngFor let-pkg [ngForOf]="packages">

                  {{pkg.state}}

              {{pkg.name}}

                {{pkg.hostVersion}}
                None

                {{pkg.templateVersion}}
                None

          </ng-template>

    </cc-panel>


text:
set -eu -o pipefail

ls -la "$(dirname "$0")"

source "$(dirname "$0")/../test_util.sh"

readonly centipede_dir="$(centipede::get_centipede_test_srcdir)"
centipede::maybe_set_var_to_executable_path centipede "${centipede_dir}/centipede"
readonly centipede

readonly target_name="$(basename "$0")"
readonly seed_and_puzzle_name="${target_name#run_}"
readonly seed="${seed_and_puzzle_name:0:1}"
readonly puzzle_name="${seed_and_puzzle_name:2}"
readonly puzzle_source_name="${puzzle_name}.cc"
readonly puzzle_path="${centipede_dir}/puzzles/${puzzle_name}"
readonly puzzle_source_path="${centipede_dir}/puzzles/${puzzle_source_name}"

readonly workdir="${TEST_TMPDIR}/workdir"
readonly log="${TEST_TMPDIR}/log"
readonly script="${TEST_TMPDIR}/script"

# Read the configuration from the puzzle source.
grep 'RUN:' "${puzzle_source_path}" | sed 's/^.*RUN://' > "${script}"
echo "======== SCRIPT"
cat "${script}"
echo "======== END SCRIPT"

##################################### USER_FUNCTIONS

# Runs Centipede with additional parameters in $@, saves the result in log, cats
# the log. Expects Centipede to exit with failure.
function Run() {
  echo "======== Run $*"
  rm -rf "${workdir}"
  mkdir "${workdir}"
  "${centipede}" \
    --workdir "${workdir}" \
    --binary "${puzzle_path}" \
    --seed="${seed}" \
    --num_runs=2000000 \
    --timeout=10 \
    --exit_on_crash \
    "$@" \
    > "${log}" 2>&1 && exit 1  # Centipede must exit with failure.
  cat "${log}"
}

# Checks that $1 is the solution for the puzzle.
function SolutionIs() {
  echo "====== ${FUNCNAME[0]}: $1"
  centipede::assert_regex_in_file "Input bytes.*: $1" "${log}"
}

# Expects that Centipede found a timeout.
function ExpectTimeout() {
  echo "======= ${FUNCNAME[0]}"
  centipede::assert_regex_in_file "Timeout of .* seconds exceeded; exiting" "${log}"
  centipede::assert_regex_in_file "Failure.*: timeout-exceeded" "${log}"
}

# Expects that Centipede found a OOM.
function ExpectOOM() {
  echo "======= ${FUNCNAME[0]}"
  centipede::assert_regex_in_file "Failure.*: out-of-memory" "${log}"
}

# Expects that $1 is found in the log.
function ExpectInLog() {
  echo "======= ${FUNCNAME[0]}: $1"
  centipede::assert_regex_in_file "$1" "${log}"
}

##################################### end USER_FUNCTIONS

# shellcheck disable=SC1090
source "${script}"

echo PASS


text:
#pragma once

#include "SFML/Graphics.hpp"
#include "Colors.h"
#include "ResourceCache.h"
#include "ResourceDirectory.h"

#include <vector>
#include <iostream>

class context;

/*
 *  Rules of Thumb for this class:
 *
 *      - Only allow getters to be 'const noexcept'
 *      - Setters must never be 'const' and 'noexcept' is not valid because
 *        the functions may or may not throw.
 *      - Constructors and destructors cannot be noexcept or const.
 *      - 'void create(...)' can throw for some derived classes.
 */

namespace gui {

	class widget {
		protected:
			int x;
			int y;
			int width;
			int height;
			int user_data;

		public:
			widget();
			widget(int wx, int wy, int w, int h);
			virtual ~widget();

			virtual int get_x() const;
			virtual int get_y() const;

			virtual void set_x(int);
			virtual void set_y(int);
			virtual void set_position(int, int);

			virtual int get_width() const;
			virtual int get_height() const;

			virtual void set_width(int);
			virtual void set_height(int);
			virtual void set_size(int, int);

			virtual void update(context& context);
			virtual bool handle_event(context& context);
			virtual void draw(context& context);

			virtual bool contains_xy(int pX, int pY) const;

			int get_user_data() const;
			void set_user_data(int data);

			// Debug-only function
			void print_metrics(const std::string& name);
	};
}


text:
<!DOCTYPE html>

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

    <title>Bootstrap Demo</title>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Project name

Home

About

Contact

Bootstrap Demo

		Bootstrap demo for example.

		<button id="info" class="btn btn-primary">info</button>
		<button id="success" class="btn btn-success">success</button>
		<button id="warning" class="btn btn-warning">warning</button>
		<button id="error" class="btn btn-danger">error</button>
		<button id="clear" class="btn btn-default">clear</button>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Simple Snake</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <link rel="stylesheet" href="assets/css/main.css">

Responsive Snake

(R) - Reset | (Space) - Pause | (B) - Bot | (0) - On/Off | (-/+) Adjust Speed

* Check out the source code *

        <canvas id="snake-canvas" autofocus="autofocus" data-full-screen="true"></canvas>

                Score :
                0

                Hi Score :
                0

                Bot Hi Score :
                0


text: package testdata // import "github.com/gyuho/goraph/testdata"


text:
![Build Status badge](https://ersh.visualstudio.com/_apis/public/build/definitions/c9754d86-e84f-486e-a3b3-f7f42d31c01d/1/badge)

A tool to backup files.

Backups consist of file copies (backed up files) in `file_storage` directory and snapshot files in `snapshots`
directory. Snapshot file is a text file where every line describes one file: checksum, modification time, size, relative
path.

Example snapshot file `snapshots/MyBackup/2019-11-17_12-00-05`:

```
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 2019-11-17T11:56:53.2720115Z 5 hello.txt
a9a66978f378456c818fb8a3e7c6ad3d2c83e62724ccbdea7b36253fb8df5edd 2019-11-17T11:59:23.9767909Z 11 lorem/ipsum.txt
```

Files in file_storage are identified by their SHA-256 checksums. File storage contains no duplicates.

```
file_storage
+- a9
|  +- a9a66978f378456c818fb8a3e7c6ad3d2c83e62724ccbdea7b36253fb8df5edd
+- 2c
   +- 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
```

Backup command creates a snapshot file and then for every file in source folder it creates a copy in `file_storage` and
adds a line in snapshot file.

Restore command reads snapshot file, for every line it finds (by its checksum value) corresponding file in storage, and
creates a copy in the destination folder.

## Features
 - Supports hash functions: SHA-512, SHA-384, SHA-256, SHA-1, MD5.
 - Works with long paths.

## Usage

    ctlg <command> [<options>]

### backup

    ctlg backup -f -n <backup name> -s <mask> <directory>

Backup files from specified directory.

Available options:

    -n <backup name>
    --name <backup name>

Backup name. Required.

    -s <mask>
    --search <mask>

Include files by name matching `<mask>`.

    -f
    --fast

Fast mode. Does not recalculate hashes if file was not modified since last backup.

### restore

    ctlg restore -n <backup name> -d <date> <directory>

Restore files from backup to specified directory.

Available options:

    -n <backup name>
    --name <backup name>

Backup name. Required.

    -d <date>
    --date <date>

Date when backup was taken in `yyyy-MM-dd_HH-mm-ss` format. It is possible to skip date parts from the right e.g.
`yyyy-MM-dd_HH-mm`, `yyyy-MM-dd` are laso valid.

### pull-backup

    ctlg pull-backup -n <backup name> -d <date> <directory>

Imports backup from `<directory>`.

Available options:

    -n <backup name>
    --name <backup name>

Backup name. Required.

    -d <date>
    --date <date>

Date when backup was taken in `yyyy-MM-dd_HH-mm-ss` format. It is possible to skip date parts from the right e.g.
`yyyy-MM-dd_HH-mm`, `yyyy-MM-dd` are laso valid.

## Implementation details

 - .NET console application (.NET Framework 4.6.2).
 - Pri.LongPath is used to support long paths.
 - Autofac is used to inject dependencies.
 - NUnit and Moq for testing.
 - NLog is used for logging.


text:
  <div *ngIf="!tasks || (tasks && tasks.length < 1)">Sie haben momentan keine offenen Tasks!

        {{ task.stateName }}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * The BDB storage engine
 *
 * @package PhpMyAdmin-Engines
 */
namespace PMA\libraries\engines;

use PMA\libraries\StorageEngine;

/**
 * The BDB storage engine
 *
 * @package PhpMyAdmin-Engines
 */
class Bdb extends StorageEngine
{
    /**
     * Returns array with variable names related to this storage engine
     *
     * @return array   variable names
     */
    public function getVariables()
    {
        return array(
            'version_bdb'         => array(
                'title' => __('Version information'),
            ),
            'bdb_cache_size'      => array(
                'type' => PMA_ENGINE_DETAILS_TYPE_SIZE,
            ),
            'bdb_home'            => array(),
            'bdb_log_buffer_size' => array(
                'type' => PMA_ENGINE_DETAILS_TYPE_SIZE,
            ),
            'bdb_logdir'          => array(),
            'bdb_max_lock'        => array(
                'type' => PMA_ENGINE_DETAILS_TYPE_NUMERIC,
            ),
            'bdb_shared_data'     => array(),
            'bdb_tmpdir'          => array(),
            'bdb_data_direct'     => array(),
            'bdb_lock_detect'     => array(),
            'bdb_log_direct'      => array(),
            'bdb_no_recover'      => array(),
            'bdb_no_sync'         => array(),
            'skip_sync_bdb_logs'  => array(),
            'sync_bdb_logs'       => array(),
        );
    }

    /**
     * Returns the pattern to be used in the query for SQL variables
     * related to this storage engine
     *
     * @return string LIKE pattern
     */
    public function getVariablesLikePattern()
    {
        return '%bdb%';
    }

    /**
     * returns string with filename for the MySQL helppage
     * about this storage engine
     *
     * @return string  mysql helppage filename
     */
    public function getMysqlHelpPage()
    {
        return 'bdb';
    }
}


text:
<!DOCTYPE html>

	<title>three.js webgl - materials - clearcoat normal</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<link type="text/css" rel="stylesheet" href="main.css">

		three.js - webgl - materials - clearcoat normal map


text:
default['bcpc']['monitoring']['provider'] = false
# VIP for monitoring services and agents
default['bcpc']['monitoring']['vip'] = "10.17.1.16"
# List of monitoring clients external to cluster that we are monitoring
default['bcpc']['monitoring']['external_clients'] = []
# Monitoring database settings
default['bcpc']['monitoring']['mysql']['innodb_buffer_pool_size'] = '128M'
default['bcpc']['monitoring']['mysql']['innodb_buffer_pool_instances'] = 1
# Pagerduty integration
default['bcpc']['monitoring']['pagerduty']['enabled'] = false
# Pagerduty service key
default['bcpc']['monitoring']['pagerduty']['key'] = nil

###########################################
#
# Graphite settings
#
###########################################
#
# Graphite version
default['bcpc']['graphite']['version'] = '0.9.15'
# Graphite Server FQDN
default['bcpc']['graphite']['fqdn'] = "graphite.#{node['bcpc']['cluster_domain']}"
#
# Default retention rates
# http://graphite.readthedocs.org/en/latest/config-carbon.html#storage-schemas-conf
default['bcpc']['graphite']['retention'] = '60s:1d'
#
# Maximum number of whisper files to create per minute. This is set low to avoid
# I/O storm when new nodes are enrolled into cluster.
# Set to 'inf' (infinite) to remove limit.
default['bcpc']['graphite']['max_creates_per_min'] = '60'
# Limit the number of updates to prevent over-utilizing the disk
default['bcpc']['graphite']['max_updates_per_sec'] = '500'
# Graphite whitelist/blacklist toggle
default['bcpc']['graphite']['use_whitelist'] = {
  'enabled' => 'False',
  'whitelist' => [],
  'blacklist' => []
}

###########################################
#
# Diamond settings
#
###########################################
#
# CPU Collector parameters
default['bcpc']['diamond']['collectors']['CPU']['normalize'] = 'True'
default['bcpc']['diamond']['collectors']['CPU']['percore'] = 'False'
# LoadAverage Collector parameters
default['bcpc']['diamond']['collectors']['LoadAverage']['metrics_blacklist'] = '^[01][15]_normalized$'
# List of queue names separated by whitespace to report on. If nil, report all.
default['bcpc']['diamond']['collectors']['rabbitmq']['queues'] = nil
# Regular expression or list of queues to not report on.
# If not nil, this overrides "queues".
default['bcpc']['diamond']['collectors']['rabbitmq']['queues_ignored'] = '.*'
# List of vhosts to report on. If nil, report none.
default['bcpc']['diamond']['collectors']['rabbitmq']['vhosts'] = nil
# Ceph Collector parameters
default['bcpc']['diamond']['collectors']['CephCollector']['metrics_whitelist'] = "ceph.mon.#{node['hostname']}.cluster.*"
# Openstack Collector parameters
default['bcpc']['diamond']['collectors']['cloud'] = {
  "interval" => "900",
  "path" => "openstack",
  "hostname" => "#{node['bcpc']['region_name']}",
  "db_host" => "#{node['bcpc']['management']['vip']}",
}

###########################################
#
# Zabbix settings
#
###########################################
#
default['bcpc']['zabbix']['discovery']['delay'] = 600
default['bcpc']['zabbix']['discovery']['ip_ranges'] = [node['bcpc']['management']['cidr']]
default['bcpc']['zabbix']['fqdn'] = "zabbix.#{node['bcpc']['cluster_domain']}"
default['bcpc']['zabbix']['storage_retention'] = 7
default['bcpc']['zabbix']['php_settings'] = {
    'max_execution_time' => 300,
    'memory_limit' => '256M',
    'post_max_size' => '16M',
    'upload_max_filesize' => '2M',
    'max_input_time' => 300,
    'date.timezone' => 'America/New_York'
}
# Zabbix severities to notify about.
# https://www.zabbix.com/documentation/2.4/manual/api/reference/usermedia/object
default['bcpc']['zabbix']['severity'] = 63
# Timeout for Zabbix agentd
default['bcpc']['zabbix']['agentd_timeout'] = 10
# Timeout for Zabbix server. It is slightly higher than agentd to better detect
# cause of timeout.
default['bcpc']['zabbix']['server_timeout'] = node['bcpc']['zabbix']['agentd_timeout'] + 1

###########################################
#
# Kibana settings
#
###########################################
#
# Kibana Server FQDN
default['bcpc']['kibana']['fqdn'] = "kibana.#{node['bcpc']['cluster_domain']}"

###########################################
#
# Elasticsearch settings
#
###########################################
#
# Heap memory size
default['bcpc']['elasticsearch']['heap_size'] = '256m'
# Additional Java options
default['bcpc']['elasticsearch']['java_opts'] = '-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -verbose:gc -Xloggc:/var/log/elasticsearch/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=10m'


text:
/*
 * 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.
 */
package io.prestosql.spi.connector;

import io.airlift.slice.Slice;
import io.prestosql.spi.Page;
import io.prestosql.spi.block.Block;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;

import static java.util.concurrent.CompletableFuture.completedFuture;

public class EmptyPageSource
        implements UpdatablePageSource
{
    @Override
    public void deleteRows(Block rowIds)
    {
        throw new UnsupportedOperationException("deleteRows called on EmptyPageSource");
    }

    @Override
    public CompletableFuture<Collection<Slice>> finish()
    {
        return completedFuture(Collections.emptyList());
    }

    @Override
    public long getCompletedBytes()
    {
        return 0;
    }

    @Override
    public long getReadTimeNanos()
    {
        return 0;
    }

    @Override
    public boolean isFinished()
    {
        return true;
    }

    @Override
    public Page getNextPage()
    {
        return null;
    }

    @Override
    public long getSystemMemoryUsage()
    {
        return 0;
    }

    @Override
    public void close() {}
}


text:
package com.baidubce.services.dugo.map;

import com.baidubce.model.AbstractBceResponse;

import java.util.List;

/**
 * Response for driving behavior
 */
public class DrivingBehaviorResponse extends AbstractBceResponse {
    private Double distance;
    private Integer duration;
    private Double averageSpeed;
    private Double maxSpeed;
    private Integer speedingNum;
    private Integer harshAccelerationNum;
    private Integer harshBreakingNum;
    private Integer harshSteeringNum;
    private Point startPoint;
    private Point endPoint;
    private List<Speeding> speeding;
    private List<HarshAcceleration> harshAcceleration;
    private List<HarshBreaking> harshBreaking;
    private List<HarshSteering> harshSteering;

    public Double getDistance() {
        return distance;
    }

    public void setDistance(Double distance) {
        this.distance = distance;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public Double getAverageSpeed() {
        return averageSpeed;
    }

    public void setAverageSpeed(Double averageSpeed) {
        this.averageSpeed = averageSpeed;
    }

    public Double getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(Double maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public Integer getSpeedingNum() {
        return speedingNum;
    }

    public void setSpeedingNum(Integer speedingNum) {
        this.speedingNum = speedingNum;
    }

    public Integer getHarshAccelerationNum() {
        return harshAccelerationNum;
    }

    public void setHarshAccelerationNum(Integer harshAccelerationNum) {
        this.harshAccelerationNum = harshAccelerationNum;
    }

    public Integer getHarshBreakingNum() {
        return harshBreakingNum;
    }

    public void setHarshBreakingNum(Integer harshBreakingNum) {
        this.harshBreakingNum = harshBreakingNum;
    }

    public Integer getHarshSteeringNum() {
        return harshSteeringNum;
    }

    public void setHarshSteeringNum(Integer harshSteeringNum) {
        this.harshSteeringNum = harshSteeringNum;
    }

    public Point getStartPoint() {
        return startPoint;
    }

    public void setStartPoint(Point startPoint) {
        this.startPoint = startPoint;
    }

    public Point getEndPoint() {
        return endPoint;
    }

    public void setEndPoint(Point endPoint) {
        this.endPoint = endPoint;
    }

    public List<Speeding> getSpeeding() {
        return speeding;
    }

    public void setSpeeding(
            List<Speeding> speeding) {
        this.speeding = speeding;
    }

    public List<HarshAcceleration> getHarshAcceleration() {
        return harshAcceleration;
    }

    public void setHarshAcceleration(
            List<HarshAcceleration> harshAcceleration) {
        this.harshAcceleration = harshAcceleration;
    }

    public List<HarshBreaking> getHarshBreaking() {
        return harshBreaking;
    }

    public void setHarshBreaking(
            List<HarshBreaking> harshBreaking) {
        this.harshBreaking = harshBreaking;
    }

    public List<HarshSteering> getHarshSteering() {
        return harshSteering;
    }

    public void setHarshSteering(
            List<HarshSteering> harshSteering) {
        this.harshSteering = harshSteering;
    }

    public static class HarshAcceleration {
        private Double latitude;
        private Double longitude;
        private String coordType;
        private Long locTime;
        private Double acceleration;
        private Double initialSpeed;
        private Double endSpeed;

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public String getCoordType() {
            return coordType;
        }

        public void setCoordType(String coordType) {
            this.coordType = coordType;
        }

        public Long getLocTime() {
            return locTime;
        }

        public void setLocTime(Long locTime) {
            this.locTime = locTime;
        }

        public Double getAcceleration() {
            return acceleration;
        }

        public void setAcceleration(Double acceleration) {
            this.acceleration = acceleration;
        }

        public Double getInitialSpeed() {
            return initialSpeed;
        }

        public void setInitialSpeed(Double initialSpeed) {
            this.initialSpeed = initialSpeed;
        }

        public Double getEndSpeed() {
            return endSpeed;
        }

        public void setEndSpeed(Double endSpeed) {
            this.endSpeed = endSpeed;
        }
    }

    public static class Point {
        private Double latitude;
        private Double longitude;
        private String coordType;
        private Long locTime;
        private String address;

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public String getCoordType() {
            return coordType;
        }

        public void setCoordType(String coordType) {
            this.coordType = coordType;
        }

        public Long getLocTime() {
            return locTime;
        }

        public void setLocTime(Long locTime) {
            this.locTime = locTime;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }
    }

    public static class Speeding {
        private Double speedingDistance;
        private List<SpeedingPoint> speedingPoints;

        public Double getSpeedingDistance() {
            return speedingDistance;
        }

        public void setSpeedingDistance(Double speedingDistance) {
            this.speedingDistance = speedingDistance;
        }

        public List<SpeedingPoint> getSpeedingPoints() {
            return speedingPoints;
        }

        public void setSpeedingPoints(
                List<SpeedingPoint> speedingPoints) {
            this.speedingPoints = speedingPoints;
        }
    }

    public static class SpeedingPoint {
        private Double latitude;
        private Double longitude;
        private String coordType;
        private Long locTime;
        private Double actualSpeed;
        private Double limitSpeed;

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public String getCoordType() {
            return coordType;
        }

        public void setCoordType(String coordType) {
            this.coordType = coordType;
        }

        public Long getLocTime() {
            return locTime;
        }

        public void setLocTime(Long locTime) {
            this.locTime = locTime;
        }

        public Double getActualSpeed() {
            return actualSpeed;
        }

        public void setActualSpeed(Double actualSpeed) {
            this.actualSpeed = actualSpeed;
        }

        public Double getLimitSpeed() {
            return limitSpeed;
        }

        public void setLimitSpeed(Double limitSpeed) {
            this.limitSpeed = limitSpeed;
        }
    }

    public static class HarshBreaking {
        private Double latitude;
        private Double longitude;
        private String coordType;
        private Long locTime;
        private Double acceleration;
        private Double initialSpeed;
        private Double endSpeed;

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public String getCoordType() {
            return coordType;
        }

        public void setCoordType(String coordType) {
            this.coordType = coordType;
        }

        public Long getLocTime() {
            return locTime;
        }

        public void setLocTime(Long locTime) {
            this.locTime = locTime;
        }

        public Double getAcceleration() {
            return acceleration;
        }

        public void setAcceleration(Double acceleration) {
            this.acceleration = acceleration;
        }

        public Double getInitialSpeed() {
            return initialSpeed;
        }

        public void setInitialSpeed(Double initialSpeed) {
            this.initialSpeed = initialSpeed;
        }

        public Double getEndSpeed() {
            return endSpeed;
        }

        public void setEndSpeed(Double endSpeed) {
            this.endSpeed = endSpeed;
        }
    }

    public static class HarshSteering {
        private Double latitude;
        private Double longitude;
        private String coordType;
        private Long locTime;
        private Double centripetalAcceleration;
        private String turnType;
        private Double speed;

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public String getCoordType() {
            return coordType;
        }

        public void setCoordType(String coordType) {
            this.coordType = coordType;
        }

        public Long getLocTime() {
            return locTime;
        }

        public void setLocTime(Long locTime) {
            this.locTime = locTime;
        }

        public Double getCentripetalAcceleration() {
            return centripetalAcceleration;
        }

        public void setCentripetalAcceleration(Double centripetalAcceleration) {
            this.centripetalAcceleration = centripetalAcceleration;
        }

        public String getTurnType() {
            return turnType;
        }

        public void setTurnType(String turnType) {
            this.turnType = turnType;
        }

        public Double getSpeed() {
            return speed;
        }

        public void setSpeed(Double speed) {
            this.speed = speed;
        }
    }
}


text:
use strict;
use warnings;

use Frontier::Client;

my $HOST = 'oholutya.naoxy.com';
my $user = 'apiro';
my $pass = 'apiro';

my $client = new Frontier::Client(url => "http://$HOST/rpc/api");
my $session = $client->call('auth.login' , $user , $pass);

my $systemGroupName = $ARGV[0];

my $systems = $client->call('systemgroup.listSystems' , $session , $systemGroupName);
print("Systems in group $systemGroupName:\n");
#printf("%-20s %-24s %-10s\n" , 'HOSTNAME' , 'LAST CHECK-IN' , 'SYSTEM ID');
foreach my $system (@$systems) {
	#my $dt = $system->{'last_checkin'};
	#my ($date,$trashT,$time) = split(' ' ,sprintf("%d-%02d-%02d %s %s", unpack('A4A2A2AA8', $dt->value())));
	#printf("%-20s %-24s %-10s\n" , $system->{'name'} , "$date $time" , $system->{'id'});
	print("$system->{'profile_name'}\n");
}
$client->call('auth.logout' , $session);


text:
package de.doofmars.ghb.util;

import java.text.DecimalFormat;

public class CustomValueFormatter implements com.github.mikephil.charting.utils.ValueFormatter {

    private DecimalFormat mFormat;
    public static final long KB_FACTOR = 1024;
    public static final long MB_FACTOR = 1048576;
    public static final long GB_FACTOR = 1073741824;

    public CustomValueFormatter() {
        mFormat = new DecimalFormat("#0.00");
    }

    @Override
    public String getFormattedValue(float value) {
        if (value > GB_FACTOR) {
            return mFormat.format(value / GB_FACTOR) + " GB";
        } else if (value > MB_FACTOR) {
            return mFormat.format(value / MB_FACTOR) + " MB";
        } else {
            return mFormat.format(value / KB_FACTOR) + " KB";
        }
    }

}


text:
package org.judal.jdbc.metadata;

import java.sql.SQLException;

import org.judal.jdbc.RDBMS;
import org.judal.metadata.ColumnDef;
import org.judal.metadata.TypeDef;

import com.knowgate.debug.DebugFile;

/**
 *
Helper functions for loading, storing and deleting rows from a SQL table.

 * @author Sergio Montoro Ten
 * @version 1.0
 */
public class SQLBuilder {

	private SQLStatements sqlStatements;
	private TypeDef tdef;

	// ----------------------------------------------------------

	/**
	 * @param dbms int Integer code from RDMBS enum
	 * @param tdef TypeDef
	 * @param timestampColumn String Name of creation timestamp column. If provided, the value of this column will not be updated after it has been initially set.
	 * @throws SQLException new SQLHelper
	 */
	public SQLBuilder(int dbms, TypeDef tdef, String timestampColumn) throws SQLException {
		this.tdef = tdef;
		sqlStatements = new SQLStatements();
		sqlStatements.setTimestampColumn(timestampColumn);
		precomputeSqlStatements(dbms);
	}

	// ----------------------------------------------------------

	/**
	 * @param dbms RDBMS
	 * @param tdef TypeDef
	 * @param timestampColumn String Name of creation timestamp column. If provided, the value of this column will not be updated after it has been initially set.
	 * @throws SQLException
	 */
	public SQLBuilder(RDBMS dbms, TypeDef tdef, String timestampColumn) throws SQLException {
		this.tdef = tdef;
		sqlStatements = new SQLStatements();
		sqlStatements.setTimestampColumn(timestampColumn);
		precomputeSqlStatements(dbms.intValue());
	}

	// ----------------------------------------------------------

	public SQLStatements getSqlStatements() {
		return sqlStatements;
	}

	// ----------------------------------------------------------

	private void precomputeSqlStatements(int dbms) throws SQLException {

		String insertAllCols = "";
		String getAllCols = "";
		String setAllCols = "";
		String setPkCols = "";
		String setNoPkCols = "";

		if (DebugFile.trace)
		{
			DebugFile.writeln("Begin SQLBuilder.precomputeSqlStatements(" + RDBMS.valueOf(dbms)+ ")" );
			DebugFile.incIdent();
			DebugFile.writeln("catalog is " + tdef.getCatalog());
			DebugFile.writeln("schema is " + tdef.getSchema());
			DebugFile.writeln("table or view is " + tdef.getName());
		}

		for (ColumnDef column : tdef.getColumns()) {
			String columnName = column.getName();
			if (DebugFile.trace)
				DebugFile.writeln("reading column "+columnName+" of type "+((SQLColumn) column).getSqlTypeName());

			if (column.isPrimaryKey())
				setPkCols += column.getName() + "=? AND ";

			if (dbms==RDBMS.POSTGRESQL.intValue()) {
				if (((SQLColumn) column).getSqlTypeName().equalsIgnoreCase("geography")) {
					insertAllCols  += columnName+",";
					getAllCols  += "ST_X("+columnName+"::geometry)||' '||ST_Y("+columnName+"::geometry) AS "+columnName+",";
					setAllCols  += "ST_SetSRID(ST_MakePoint(?,?),4326),";
					setNoPkCols += columnName + "=ST_SetSRID(ST_MakePoint(?,?),4326),";
				} else if (((SQLColumn) column).getSqlTypeName().equalsIgnoreCase("serial")) {
					getAllCols += columnName + ",";
				} else {
					insertAllCols += columnName + ",";
					getAllCols += columnName + ",";
					setAllCols += "?,";
					if (!column.isPrimaryKey() && !columnName.equalsIgnoreCase(sqlStatements.getTimestampColumn()))
						setNoPkCols += columnName + "=?,";
				}
			} else {
				if (column.getAutoIncrement()) {
					getAllCols += columnName + ",";
				} else {
					insertAllCols += columnName + ",";
					getAllCols += columnName + ",";
					setAllCols += "?,";
					if (!column.isPrimaryKey() && !columnName.equalsIgnoreCase(sqlStatements.getTimestampColumn()))
						setNoPkCols += columnName + "=?,";
				}
			}
		} // wend

		if (setPkCols.length()>0)
			setPkCols = setPkCols.substring(0, setPkCols.length()-5);

		if (DebugFile.trace) DebugFile.writeln("get all cols " + getAllCols );

		if (getAllCols.length()>0)
			getAllCols = getAllCols.substring(0, getAllCols.length()-1);
		else
			getAllCols = "*";

		if (insertAllCols.length()>0)
			insertAllCols = insertAllCols.substring(0, insertAllCols.length()-1);

		if (DebugFile.trace) DebugFile.writeln("set all cols " + setAllCols );

		if (setAllCols.length()>0)
			setAllCols = setAllCols.substring(0, setAllCols.length()-1);

		if (DebugFile.trace) DebugFile.writeln("set no pk cols " + setNoPkCols );

		if (setNoPkCols.length()>0)
			setNoPkCols = setNoPkCols.substring(0, setNoPkCols.length()-1);

		if (DebugFile.trace) DebugFile.writeln("set pk cols " + setPkCols );

		if (setPkCols.length()>0) {
			sqlStatements.setSelect("SELECT " + getAllCols + " FROM " + tdef.getName() + " WHERE " + setPkCols);
			sqlStatements.setInsert("INSERT INTO " + tdef.getName() + "(" + insertAllCols + ") VALUES (" + setAllCols + ")");
			if (setNoPkCols.length()>0)
				sqlStatements.setUpdate("UPDATE " + tdef.getName() + " SET " + setNoPkCols + " WHERE " + setPkCols);
			else
				sqlStatements.setUpdate(null);
			sqlStatements.setDelete("DELETE FROM " + tdef.getName() + " WHERE " + setPkCols);
			sqlStatements.setExists("SELECT NULL FROM " + tdef.getName() + " WHERE " + setPkCols);
			if (DebugFile.trace) {
				DebugFile.writeln("Generated SQL statements for "+tdef.getName());
				DebugFile.writeln("Generated "+sqlStatements.getSelect());
				DebugFile.writeln("Generated "+sqlStatements.getInsert());
				DebugFile.writeln("Generated "+sqlStatements.getUpdate());
				DebugFile.writeln("Generated "+sqlStatements.getDelete());
			}
		}
		else {
			sqlStatements.setSelect(null);
			sqlStatements.setInsert("INSERT INTO " + tdef.getName() + "(" + insertAllCols + ") VALUES (" + setAllCols + ")");
			sqlStatements.setUpdate(null);
			sqlStatements.setDelete(null);
			sqlStatements.setExists(null);
			if (DebugFile.trace) {
				DebugFile.writeln("WARNING No Primary Key found for table " + tdef.getName());
				DebugFile.writeln("Generated SQL statement for "+tdef.getName());
				DebugFile.writeln("Generated "+sqlStatements.getInsert());
			}
		}

		if (DebugFile.trace)
		{
			DebugFile.decIdent();
			DebugFile.writeln("End SQLBuilder.precomputeSqlStatements()");
		}

	} // precomputeSqlStatements

}


text:
import { TestBed, inject } from '@angular/core/testing';

import { FacebookService } from './facebook.service';

describe('FriendsService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [FacebookService]
    });
  });

  it('should be created', inject([FacebookService], (service: FacebookService) => {
    expect(service).toBeTruthy();
  }));
});


text:
require 'spec_helper'

describe Billy::ProxyHandler do
  subject { Billy::ProxyHandler.new }
  let(:request) do
    {
      method:   'post',
      url:      'http://usern:pw@example.test:8080/index?some=param',
      headers:  { 'Accept-Encoding'  => 'gzip',
                  'Cache-Control'    => 'no-cache' },
      body:     'Some body'
    }
  end

  describe '#handles_request?' do
    context 'with non-whitelisted requests enabled' do
      before do
        expect(Billy.config).to receive(:non_whitelisted_requests_disabled).and_return(false)
      end

      it 'handles all requests' do
        expect(subject.handles_request?(request[:method],
                                        request[:url],
                                        request[:headers],
                                        request[:body])).to be true
      end
    end
    context 'with non-whitelisted requests disabled' do
      before do
        expect(Billy.config).to receive(:non_whitelisted_requests_disabled).and_return(true)
      end

      it 'does not handle requests that are not white or black listed' do
        expect(subject.handles_request?(request[:method],
                                        request[:url],
                                        request[:headers],
                                        request[:body])).to be false
      end

      context 'a whitelisted host' do
        context 'with a blacklisted path' do
          before do
            expect(Billy.config).to receive(:path_blacklist) { ['/index'] }
          end

          it 'does not handle requests for blacklisted paths' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test:8080/index?some=param',
                                            request[:headers],
                                            request[:body])).to be false
          end
        end

        context 'as a regex' do
          before do
            expect(Billy.config).to receive(:whitelist) { [%r{example\.test\/a}] }
          end

          it 'handles requests for the host without a port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test/a',
                                            request[:headers],
                                            request[:body])).to be true
          end

          it 'handles requests for the host with a port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test:8080/a',
                                            request[:headers],
                                            request[:body])).to be true
          end
        end

        context 'without a port' do
          before do
            expect(Billy.config).to receive(:whitelist) { ['example.test'] }
          end

          it 'handles requests for the host without a port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test',
                                            request[:headers],
                                            request[:body])).to be true
          end

          it 'handles requests for the host with a port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test:8080',
                                            request[:headers],
                                            request[:body])).to be true
          end
        end

        context 'with a port' do
          before do
            expect(Billy.config).to receive(:whitelist) { ['example.test:8080'] }
          end

          it 'does not handle requests whitelisted for a specific port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test',
                                            request[:headers],
                                            request[:body])).to be false
          end

          it 'handles requests for the host with a port' do
            expect(subject.handles_request?(request[:method],
                                            'http://example.test:8080',
                                            request[:headers],
                                            request[:body])).to be true
          end
        end
      end
    end
  end

  describe '#handle_request' do
    it 'returns nil if it does not handle the request' do
      expect(subject).to receive(:handles_request?).and_return(false)
      expect(subject.handle_request(request[:method],
                                    request[:url],
                                    request[:headers],
                                    request[:body])).to be nil
    end

    context 'with a handled request' do
      let(:response_header) do
        header = Struct.new(:status, :raw).new
        header.status = 200
        header.raw = {}
        header
      end

      let(:em_response)     { double('response') }
      let(:em_request)      do
        double('EM::HttpRequest', error: nil, response: em_response, response_header: response_header)
      end

      before do
        allow(subject).to receive(:handles_request?).and_return(true)
        allow(em_response).to receive(:force_encoding).and_return('The response body')
        allow(EventMachine::HttpRequest).to receive(:new).and_return(em_request)
        expect(em_request).to receive(:post).and_return(em_request)
      end

      it 'returns any error in the response' do
        allow(em_request).to receive(:error).and_return('ERROR!')
        expect(subject.handle_request(request[:method],
                                      request[:url],
                                      request[:headers],
                                      request[:body])).to eql(error: "Request to #{request[:url]} failed with error: ERROR!")
      end

      it 'returns a hashed response if the request succeeds' do
        expect(subject.handle_request(request[:method],
                                      request[:url],
                                      request[:headers],
                                      request[:body])).to eql(status: 200, headers: { 'Connection' => 'close' }, content: 'The response body')
      end

      it 'returns nil if both the error and response are for some reason nil' do
        allow(em_request).to receive(:response).and_return(nil)
        expect(subject.handle_request(request[:method],
                                      request[:url],
                                      request[:headers],
                                      request[:body])).to be nil
      end

      it 'caches the response if cacheable' do
        expect(subject).to receive(:allowed_response_code?).and_return(true)
        expect(Billy::Cache.instance).to receive(:store)
        subject.handle_request(request[:method],
                               request[:url],
                               request[:headers],
                               request[:body])
      end

      it 'does NOT cache the response if the host is whitelisted but not cache_whitelisted' do
        uri = Addressable::URI.parse(request[:url])

        expect(subject).to receive(:allowed_response_code?).and_return(true)
        expect(Billy.config).to receive(:whitelist).and_return([uri.host])
        expect(Billy.config).to receive(:cache_whitelist).and_return([])

        expect(Billy::Cache.instance).not_to receive(:store)
        subject.handle_request(request[:method],
                               request[:url],
                               request[:headers],
                               request[:body])
      end

      it 'caches the response if the host is whitelisted AND cache_whitelisted' do
        uri = Addressable::URI.parse(request[:url])

        expect(subject).to receive(:allowed_response_code?).and_return(true)
        expect(Billy.config).to receive(:whitelist).and_return([uri.host])
        expect(Billy.config).to receive(:cache_whitelist).and_return([uri.host])

        expect(Billy::Cache.instance).to receive(:store)
        subject.handle_request(request[:method],
                               request[:url],
                               request[:headers],
                               request[:body])
      end

      it 'uses the timeouts defined in configuration' do
        allow(Billy.config).to receive(:proxied_request_inactivity_timeout).and_return(42)
        allow(Billy.config).to receive(:proxied_request_connect_timeout).and_return(24)

        expect(EventMachine::HttpRequest).to receive(:new).with(request[:url],
                                                                {
                                                                  inactivity_timeout: 42,
                                                                  connect_timeout: 24
                                                                }
        )

        subject.handle_request(request[:method],
                               request[:url],
                               request[:headers],
                               request[:body])
      end

      it 'uses the internal proxy settings defined in configuration' do
        allow(Billy.config).to receive(:proxied_request_host).and_return('10.10.10.10')
        allow(Billy.config).to receive(:proxied_request_port).and_return('2080')

        expect(EventMachine::HttpRequest).to receive(:new).with(request[:url],
                                                                {
                                                                  inactivity_timeout: 10,
                                                                  connect_timeout: 5,
                                                                  proxy: { host: '10.10.10.10', port: '2080' }
                                                                }
        )

        subject.handle_request(request[:method],
                               request[:url],
                               request[:headers],
                               request[:body])
      end
    end
  end

  describe '#build_request_options' do
    it 'creates authorization header when URL has basic auth' do
      request_options = subject.send(:build_request_options, request[:url],
                                                             request[:headers],
                                                             request[:body])
      expect(request_options[:head]).to have_key 'authorization'
    end

    it 'does not include authorization header without basic auth' do
      request_options = subject.send(:build_request_options, request[:url].gsub('usern:pw@',''),
                                                             request[:headers],
                                                             request[:body])
      expect(request_options[:head]).not_to have_key 'authorization'
    end
  end
end


text:
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/spot_light.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh_builder.h>
#include <babylon/samples/babylon_register_sample.h>

namespace BABYLON {
namespace Samples {

/**
 * @brief Scene demonstrating the use of the spot light. This light defines a cone of light pointing
 * in a direction.
 * @see https://www.babylonjs-playground.com/#20OAV9#3
 * @see https://doc.babylonjs.com/babylon101/lights#the-spot-light
 */
struct SpotLightScene : public IRenderableScene {

  SpotLightScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
  {
  }

  ~SpotLightScene() override = default;

  const char* getName() override
  {
    return "Spot Light Scene";
  }
  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    auto camera
      = ArcRotateCamera::New("Camera", -Math::PI_2, Math::PI_4, 5.f, Vector3::Zero(), scene);
    camera->attachControl(canvas, true);

    // Light direction is directly down from a position one unit up, slow decay
    auto light      = SpotLight::New("spotLight", Vector3(-1.f, 1.f, -1.f), Vector3(0.f, -1.f, 0.f),
                                Math::PI_2, 10.f, scene);
    light->diffuse  = Color3(1.f, 0.f, 0.f);
    light->specular = Color3(0.f, 1.f, 0.f);

    // Light direction is directly down from a position one unit up, fast decay
    auto light1      = SpotLight::New("spotLight1", Vector3(1.f, 1.f, 1.f), Vector3(0.f, -1.f, 0.f),
                                 Math::PI_2, 50.f, scene);
    light1->diffuse  = Color3(0.f, 1.f, 0.f);
    light1->specular = Color3(0.f, 1.f, 0.f);

    GroundOptions options;
    options.width  = 4;
    options.height = 4;
    MeshBuilder::CreateGround("ground", options, scene);
  }

}; // end of struct SpotLightScene

BABYLON_REGISTER_SAMPLE("Ligths", SpotLightScene)

} // end of namespace Samples
} // end of namespace BABYLON


text:
import DS from 'ember-data';

export default DS.Model.extend({
  player: DS.belongsTo('player'),
  war: DS.belongsTo('war'),
  friendly: DS.attr('boolean'),
  attacks: DS.hasMany('attack-log', { inverse: 'attacker' }),
  defenses: DS.hasMany('attack-log', { inverse: 'target' }),
  position: DS.attr('number')
});


text:
Class(Kanji, {
  id: 'LoginForm',
  lazy: false,

  actions: {
    '[name=username]': 'keydown:checkUsername',
    '[name=password]': 'keydown:checkPassword',
    '[type=submit]':   'login'
  },

  init: function(form, config) {
    console.log('init');
    ends.push(+new Date());
  },

  checkUsername: function(event, input) {
    // do something when keydown event happens on username field
    console.log('onCheckUsername');
  },

  checkPassword: function(event, input) {
    // do something when keydown event happens on password field
    console.log('onCheckPassword');
  },

  login: function(event, input) {
    // do something when click event happens on button submit
    console.log('onLogin');

    // prevent form from submitting
    return false;
  }
});


text:
namespace Resta.UriTemplates
{
    using System;
    using System.Text;

    /// <summary>
    /// Description of URI template variable.
    /// </summary>
    public sealed class VarSpec
    {
        private readonly string name;
        private readonly bool exploded;
        private readonly int maxLength;

        public VarSpec(string name)
            : this(name, false, 0, false)
        {
        }

        public VarSpec(string name, bool exploded)
            : this(name, exploded, 0, false)
        {
        }

        public VarSpec(string name, int maxLength)
            : this(name, false, maxLength, false)
        {
            if (maxLength < 0)
            {
                throw new ArgumentOutOfRangeException("maxLength", "maxLength must be greater then 0");
            }
        }

        internal VarSpec(string name, bool exploded, int maxLength, bool safe)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (name.Length == 0)
            {
                throw new ArgumentException("Variable name cannot be empty.", "name");
            }

            if (!safe && !IsWellFormedName(name))
            {
                throw new ArgumentException(string.Format("Invalid variable name \"{0}\"", name), "name");
            }

            this.name = name;
            this.exploded = exploded;
            this.maxLength = maxLength;
        }

        public string Name
        {
            get { return name; }
        }

        public bool Exploded
        {
            get { return exploded; }
        }

        public int MaxLength
        {
            get { return maxLength; }
        }

        public static implicit operator VarSpec(string name)
        {
            return new VarSpec(name);
        }

        public static string Escape(string name)
        {
            return PctEncoding.Escape(name, CharSpec.VarChar);
        }

        public static string Unescape(string name)
        {
            return PctEncoding.Unescape(name, CharSpec.VarChar);
        }

        private static bool IsWellFormedName(string name)
        {
            for (var i = 0; i < name.Length; i++)
            {
                if (!CharSpec.IsVarChar(name[i]))
                {
                    return false;
                }
            }

            return true;
        }
    }
}


text:
var path = require('path')
var webpack = require('webpack')
var BrowserSyncPlugin = require('browser-sync-webpack-plugin')

module.exports = {
  entry: './app/client.jsx',
  output: { path: __dirname + '/assets', filename: 'bundle.js' },
  devtool: "eval-source-map",
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /.jsx?$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    }]
  },
  devServer: {
    historyApiFallback: true
  },
  plugins: [
    new BrowserSyncPlugin({
      host: 'localhost',
      port: 3000,
      proxy: 'http://localhost:8080/'
    }
 )]
}