text:
from __future__ import absolute_import
from __future__ import print_function

from functools import wraps

from django.core.cache import cache as djcache
from django.core.cache import caches
from django.conf import settings
from django.db.models import Q
from django.core.cache.backends.base import BaseCache

from typing import Any, Callable, Iterable, Optional, Union, TypeVar, Text

from zerver.lib.utils import statsd, statsd_key, make_safe_digest
import subprocess
import time
import base64
import random
import sys
import os
import os.path
import hashlib
import six

if False:
    from zerver.models import UserProfile, Realm, Message
    # These modules have to be imported for type annotations but
    # they cannot be imported at runtime due to cyclic dependency.

FuncT = TypeVar('FuncT', bound=Callable[..., Any])

class NotFoundInCache(Exception):
    pass

remote_cache_time_start = 0.0
remote_cache_total_time = 0.0
remote_cache_total_requests = 0

def get_remote_cache_time():
    # type: () -> float
    return remote_cache_total_time

def get_remote_cache_requests():
    # type: () -> int
    return remote_cache_total_requests

def remote_cache_stats_start():
    # type: () -> None
    global remote_cache_time_start
    remote_cache_time_start = time.time()

def remote_cache_stats_finish():
    # type: () -> None
    global remote_cache_total_time
    global remote_cache_total_requests
    global remote_cache_time_start
    remote_cache_total_requests += 1
    remote_cache_total_time += (time.time() - remote_cache_time_start)

def get_or_create_key_prefix():
    # type: () -> Text
    if settings.CASPER_TESTS:
        # This sets the prefix for the benefit of the Casper tests.
        #
        # Having a fixed key is OK since we don't support running
        # multiple copies of the casper tests at the same time anyway.
        return u'casper_tests:'
    elif settings.TEST_SUITE:
        # The Python tests overwrite KEY_PREFIX on each test, but use
        # this codepath as well, just to save running the more complex
        # code below for reading the normal key prefix.
        return u'django_tests_unused:'

    # directory `var` should exist in production
    subprocess.check_call(["mkdir", "-p", os.path.join(settings.DEPLOY_ROOT, "var")])

    filename = os.path.join(settings.DEPLOY_ROOT, "var", "remote_cache_prefix")
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o444)
        random_hash = hashlib.sha256(Text(random.getrandbits(256)).encode('utf-8')).digest()
        prefix = base64.b16encode(random_hash)[:32].decode('utf-8').lower() + ':'
        # This does close the underlying file
        with os.fdopen(fd, 'w') as f:
            f.write(prefix + "\n")
    except OSError:
        # The file already exists
        tries = 1
        while tries < 10:
            with open(filename, 'r') as f:
                prefix = f.readline()[:-1]
            if len(prefix) == 33:
                break
            tries += 1
            prefix = ''
            time.sleep(0.5)

    if not prefix:
        print("Could not read remote cache key prefix file")
        sys.exit(1)

    return prefix

KEY_PREFIX = get_or_create_key_prefix() # type: Text

def bounce_key_prefix_for_testing(test_name):
    # type: (Text) -> None
    global KEY_PREFIX
    KEY_PREFIX = test_name + u':' + Text(os.getpid()) + u':'

def get_cache_backend(cache_name):
    # type: (Optional[str]) -> BaseCache
    if cache_name is None:
        return djcache
    return caches[cache_name]

def get_cache_with_key(keyfunc, cache_name=None):
    # type: (Any, Optional[str]) -> Any
    """
    The main goal of this function getting value from the cache like in the "cache_with_key".
    A cache value can contain any data including the "None", so
    here used exception for case if value isn't found in the cache.
    """
    def decorator(func):
        # type: (Callable[..., Any]) -> (Callable[..., Any])
        @wraps(func)
        def func_with_caching(*args, **kwargs):
            # type: (*Any, **Any) -> Callable[..., Any]
            key = keyfunc(*args, **kwargs)
            val = cache_get(key, cache_name=cache_name)
            if val is not None:
                return val[0]
            raise NotFoundInCache()

        return func_with_caching

    return decorator

def cache_with_key(keyfunc, cache_name=None, timeout=None, with_statsd_key=None):
    # type: (Any, Optional[str], Optional[int], Optional[str]) -> Any
    # This function can't be typed perfectly because returning a generic function
    # isn't supported in mypy - https://github.com/python/mypy/issues/1551.
    """Decorator which applies Django caching to a function.

       Decorator argument is a function which computes a cache key
       from the original function's arguments.  You are responsible
       for avoiding collisions with other uses of this decorator or
       other uses of caching."""

    def decorator(func):
        # type: (Callable[..., Any]) -> (Callable[..., Any])
        @wraps(func)
        def func_with_caching(*args, **kwargs):
            # type: (*Any, **Any) -> Callable[..., Any]
            key = keyfunc(*args, **kwargs)

            val = cache_get(key, cache_name=cache_name)

            extra = ""
            if cache_name == 'database':
                extra = ".dbcache"

            if with_statsd_key is not None:
                metric_key = with_statsd_key
            else:
                metric_key = statsd_key(key)

            status = "hit" if val is not None else "miss"
            statsd.incr("cache%s.%s.%s" % (extra, metric_key, status))

            # Values are singleton tuples so that we can distinguish
            # a result of None from a missing key.
            if val is not None:
                return val[0]

            val = func(*args, **kwargs)

            cache_set(key, val, cache_name=cache_name, timeout=timeout)

            return val

        return func_with_caching

    return decorator

def cache_set(key, val, cache_name=None, timeout=None):
    # type: (Text, Any, Optional[str], Optional[int]) -> None
    remote_cache_stats_start()
    cache_backend = get_cache_backend(cache_name)
    cache_backend.set(KEY_PREFIX + key, (val,), timeout=timeout)
    remote_cache_stats_finish()

def cache_get(key, cache_name=None):
    # type: (Text, Optional[str]) -> Any
    remote_cache_stats_start()
    cache_backend = get_cache_backend(cache_name)
    ret = cache_backend.get(KEY_PREFIX + key)
    remote_cache_stats_finish()
    return ret

def cache_get_many(keys, cache_name=None):
    # type: (List[Text], Optional[str]) -> Dict[Text, Any]
    keys = [KEY_PREFIX + key for key in keys]
    remote_cache_stats_start()
    ret = get_cache_backend(cache_name).get_many(keys)
    remote_cache_stats_finish()
    return dict([(key[len(KEY_PREFIX):], value) for key, value in ret.items()])

def cache_set_many(items, cache_name=None, timeout=None):
    # type: (Dict[Text, Any], Optional[str], Optional[int]) -> None
    new_items = {}
    for key in items:
        new_items[KEY_PREFIX + key] = items[key]
    items = new_items
    remote_cache_stats_start()
    get_cache_backend(cache_name).set_many(items, timeout=timeout)
    remote_cache_stats_finish()

def cache_delete(key, cache_name=None):
    # type: (Text, Optional[str]) -> None
    remote_cache_stats_start()
    get_cache_backend(cache_name).delete(KEY_PREFIX + key)
    remote_cache_stats_finish()

def cache_delete_many(items, cache_name=None):
    # type: (Iterable[Text], Optional[str]) -> None
    remote_cache_stats_start()
    get_cache_backend(cache_name).delete_many(
        KEY_PREFIX + item for item in items)
    remote_cache_stats_finish()

# Required Arguments are as follows:
# * object_ids: The list of object ids to look up
# * cache_key_function: object_id => cache key
# * query_function: [object_ids] => [objects from database]
# Optional keyword arguments:
# * setter: Function to call before storing items to cache (e.g. compression)
# * extractor: Function to call on items returned from cache
#   (e.g. decompression).  Should be the inverse of the setter
#   function.
# * id_fetcher: Function mapping an object from database => object_id
#   (in case we're using a key more complex than obj.id)
# * cache_transformer: Function mapping an object from database =>
#   value for cache (in case the values that we're caching are some
#   function of the objects, not the objects themselves)
ObjKT = TypeVar('ObjKT', int, Text)
ItemT = Any # https://github.com/python/mypy/issues/1721
CompressedItemT = Any # https://github.com/python/mypy/issues/1721
def generic_bulk_cached_fetch(cache_key_function, # type: Callable[[ObjKT], Text]
                              query_function, # type: Callable[[List[ObjKT]], Iterable[Any]]
                              object_ids, # type: Iterable[ObjKT]
                              extractor=lambda obj: obj, # type: Callable[[CompressedItemT], ItemT]
                              setter=lambda obj: obj, # type: Callable[[ItemT], CompressedItemT]
                              id_fetcher=lambda obj: obj.id, # type: Callable[[Any], ObjKT]
                              cache_transformer=lambda obj: obj # type: Callable[[Any], ItemT]
                              ):
    # type: (...) -> Dict[ObjKT, Any]
    cache_keys = {} # type: Dict[ObjKT, Text]
    for object_id in object_ids:
        cache_keys[object_id] = cache_key_function(object_id)
    cached_objects = cache_get_many([cache_keys[object_id]
                                     for object_id in object_ids])
    for (key, val) in cached_objects.items():
        cached_objects[key] = extractor(cached_objects[key][0])
    needed_ids = [object_id for object_id in object_ids if
                  cache_keys[object_id] not in cached_objects]
    db_objects = query_function(needed_ids)

    items_for_remote_cache = {} # type: Dict[Text, Any]
    for obj in db_objects:
        key = cache_keys[id_fetcher(obj)]
        item = cache_transformer(obj)
        items_for_remote_cache[key] = (setter(item),)
        cached_objects[key] = item
    if len(items_for_remote_cache) > 0:
        cache_set_many(items_for_remote_cache)
    return dict((object_id, cached_objects[cache_keys[object_id]]) for object_id in object_ids
                if cache_keys[object_id] in cached_objects)

def cache(func):
    # type: (FuncT) -> FuncT
    """Decorator which applies Django caching to a function.

       Uses a key based on the function's name, filename, and
       the repr() of its arguments."""

    func_uniqifier = '%s-%s' % (func.__code__.co_filename, func.__name__) # type: ignore # https://github.com/python/mypy/issues/1923

    @wraps(func)
    def keyfunc(*args, **kwargs):
        # type: (*Any, **Any) -> str
        # Django complains about spaces because memcached rejects them
        key = func_uniqifier + repr((args, kwargs))
        return key.replace('-', '--').replace(' ', '-s')

    return cache_with_key(keyfunc)(func)

def display_recipient_cache_key(recipient_id):
    # type: (int) -> Text
    return u"display_recipient_dict:%d" % (recipient_id,)

def user_profile_by_email_cache_key(email):
    # type: (Text) -> Text
    # See the comment in zerver/lib/avatar_hash.py:gravatar_hash for why we
    # are proactively encoding email addresses even though they will
    # with high likelihood be ASCII-only for the foreseeable future.
    return u'user_profile_by_email:%s' % (make_safe_digest(email.strip()),)

def user_profile_by_id_cache_key(user_profile_id):
    # type: (int) -> Text
    return u"user_profile_by_id:%s" % (user_profile_id,)

# TODO: Refactor these cache helpers into another file that can import
# models.py so that python v3 style type annotations can also work.

def cache_save_user_profile(user_profile):
    # type: (UserProfile) -> None
    cache_set(user_profile_by_id_cache_key(user_profile.id), user_profile, timeout=3600*24*7)

active_user_dict_fields = ['id', 'full_name', 'short_name', 'email', 'is_realm_admin', 'is_bot'] # type: List[str]
def active_user_dicts_in_realm_cache_key(realm):
    # type: (Realm) -> Text
    return u"active_user_dicts_in_realm:%s" % (realm.id,)

active_bot_dict_fields = ['id', 'full_name', 'short_name',
                          'email', 'default_sending_stream__name',
                          'default_events_register_stream__name',
                          'default_all_public_streams', 'api_key',
                          'bot_owner__email', 'avatar_source'] # type: List[str]
def active_bot_dicts_in_realm_cache_key(realm):
    # type: (Realm) -> Text
    return u"active_bot_dicts_in_realm:%s" % (realm.id,)

def get_stream_cache_key(stream_name, realm):
    # type: (Text, Union[Realm, int]) -> Text
    from zerver.models import Realm
    if isinstance(realm, Realm):
        realm_id = realm.id
    else:
        realm_id = realm
    return u"stream_by_realm_and_name:%s:%s" % (
        realm_id, make_safe_digest(stream_name.strip().lower()))

def delete_user_profile_caches(user_profiles):
    # type: (Iterable[UserProfile]) -> None
    keys = []
    for user_profile in user_profiles:
        keys.append(user_profile_by_email_cache_key(user_profile.email))
        keys.append(user_profile_by_id_cache_key(user_profile.id))

    cache_delete_many(keys)

# Called by models.py to flush the user_profile cache whenever we save
# a user_profile object
def flush_user_profile(sender, **kwargs):
    # type: (Any, **Any) -> None
    user_profile = kwargs['instance']
    delete_user_profile_caches([user_profile])

    # Invalidate our active_users_in_realm info dict if any user has changed
    # the fields in the dict or become (in)active
    if kwargs.get('update_fields') is None or \
            len(set(active_user_dict_fields + ['is_active']) &
                set(kwargs['update_fields'])) > 0:
        cache_delete(active_user_dicts_in_realm_cache_key(user_profile.realm))

    # Invalidate our active_bots_in_realm info dict if any bot has
    # changed the fields in the dict or become (in)active
    if user_profile.is_bot and (kwargs['update_fields'] is None or
                                (set(active_bot_dict_fields + ['is_active']) &
                                 set(kwargs['update_fields']))):
        cache_delete(active_bot_dicts_in_realm_cache_key(user_profile.realm))

    # Invalidate realm-wide alert words cache if any user in the realm has changed
    # alert words
    if kwargs.get('update_fields') is None or "alert_words" in kwargs['update_fields']:
        cache_delete(realm_alert_words_cache_key(user_profile.realm))

# Called by models.py to flush various caches whenever we save
# a Realm object.  The main tricky thing here is that Realm info is
# generally cached indirectly through user_profile objects.
def flush_realm(sender, **kwargs):
    # type: (Any, **Any) -> None
    realm = kwargs['instance']
    users = realm.get_active_users()
    delete_user_profile_caches(users)

    if realm.deactivated:
        cache_delete(active_user_dicts_in_realm_cache_key(realm))
        cache_delete(active_bot_dicts_in_realm_cache_key(realm))
        cache_delete(realm_alert_words_cache_key(realm))

def realm_alert_words_cache_key(realm):
    # type: (Realm) -> Text
    return u"realm_alert_words:%s" % (realm.domain,)

# Called by models.py to flush the stream cache whenever we save a stream
# object.
def flush_stream(sender, **kwargs):
    # type: (Any, **Any) -> None
    from zerver.models import UserProfile
    stream = kwargs['instance']
    items_for_remote_cache = {}
    items_for_remote_cache[get_stream_cache_key(stream.name, stream.realm)] = (stream,)
    cache_set_many(items_for_remote_cache)

    if kwargs.get('update_fields') is None or 'name' in kwargs['update_fields'] and \
       UserProfile.objects.filter(
           Q(default_sending_stream=stream) |
           Q(default_events_register_stream=stream)
       ).exists():
        cache_delete(active_bot_dicts_in_realm_cache_key(stream.realm))

# TODO: Rename to_dict_cache_key_id and to_dict_cache_key
def to_dict_cache_key_id(message_id, apply_markdown):
    # type: (int, bool) -> Text
    return u'message_dict:%d:%d' % (message_id, apply_markdown)

def to_dict_cache_key(message, apply_markdown):
    # type: (Message, bool) -> Text
    return to_dict_cache_key_id(message.id, apply_markdown)

def flush_message(sender, **kwargs):
    # type: (Any, **Any) -> None
    message = kwargs['instance']
    cache_delete(to_dict_cache_key(message, False))
    cache_delete(to_dict_cache_key(message, True))


text:
package fate.webapp.blog.service;

import fate.webapp.blog.model.DuoShuo;

public interface DuoShuoService {

	public void save(DuoShuo duoShuo);

	public DuoShuo update(DuoShuo duoShuo);

	public void delete(DuoShuo duoShuo);

	public DuoShuo find(int id);

	/**
	 * 统计评论总数
	 * @return
	 */
	public long count();

	public void update(String ids, String action, long logId);

	public long findLastLogId();

	public void delete(String ids);
}

redpajama_set_name: RedPajamaGithub


text:
(function ($) {
    $.fn.multipleInput = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.multipleInput');
            return false;
        }
    };

    var events = {
        /**
         * afterAddRow event is triggered after widget's initialization.
         * The signature of the event handler should be:
         *     function (event)
         * where event is an Event object.
         *
         */
        afterInit: 'afterInit',
        /**
         * afterAddRow event is triggered after successful adding new row.
         * The signature of the event handler should be:
         *     function (event)
         * where event is an Event object.
         *
         */
        afterAddRow: 'afterAddRow',
        /**
         * beforeDeleteRow event is triggered before row will be removed.
         * The signature of the event handler should be:
         *     function (event, row)
         * where event is an Event object and row is html container of row for removal
         *
         * If the handler returns a boolean false, it will stop removal the row.
         */
        beforeDeleteRow: 'beforeDeleteRow',

        /**
         * afterAddRow event is triggered after successful removal the row.
         * The signature of the event handler should be:
         *     function (event)
         * where event is an Event object.
         *
         */
        afterDeleteRow: 'afterDeleteRow'
    };

    var defaultOptions = {
        id: null,
        // the template of row
        template: null,
        // string that collect js templates of widgets which uses in the columns
        jsTemplates: [],
        // how many row has to renders
        limit: 1,
        // minimum number of rows
        min: 1
    };

    var defaultAttributeOptions = {
        enableAjaxValidation: false,
        validateOnBlur: false,
        validateOnChange: false,
        validateOnType: false
    };

    var methods = {
        init: function (options) {
            var settings = $.extend(true, {}, defaultOptions, options || {}),
                $wrapper = $('#' + settings.id),
                form = $wrapper.closest('form'),
                id = this.selector.replace('#', '');

            $wrapper.data('multipleInput', {
                settings: settings,
                currentIndex: 0,
                attributeDefaults: {}
            });

            $wrapper.on('click.multipleInput', '.js-input-remove', function (e) {
                e.preventDefault();
                removeInput($(this));
            });

            $wrapper.on('click.multipleInput', '.js-input-plus', function (e) {
                e.preventDefault();
                addInput($(this));
            });

            var intervalID = setInterval(function () {
                if (typeof form.data('yiiActiveForm') === 'object') {
                    var attribute = form.yiiActiveForm('find', id);
                    var attributeDefaults = [];
                    if (typeof attribute === 'object') {
                        $.each(attribute, function (key, value) {
                            if (['id', 'input', 'container'].indexOf(key) == -1) {
                                attributeDefaults[key] = value;
                            }
                        });
                        form.yiiActiveForm('remove', id);
                    }

                    var attributeOptions = $.extend({}, defaultAttributeOptions, settings.attributeOptions);
                    $.each(attributeOptions, function (key, value) {
                        if (typeof attributeDefaults[key] === 'undefined') {
                            attributeDefaults[key] = value;
                        }
                    });

                    $wrapper.data('multipleInput').attributeDefaults = attributeDefaults;

                    $wrapper.find('.multiple-input-list').find('input, select, textarea').each(function () {
                        addAttribute($(this));
                    });
                    $wrapper.data('multipleInput').currentIndex = $wrapper.find('.multiple-input-list__item').length;
                    clearInterval(intervalID);

                    var event = $.Event(events.afterInit);
                    $wrapper.trigger(event);
                }
            }, 100);
        },
        add: function (values) {
            addInput($(this), values);
        },
        remove: function (index) {
            var row = null;
            if (index) {
                row = $(this).find('.js-input-remove:eq(' + index + ')');
            } else {
                row = $(this).find('.js-input-remove').last();
            }
            removeInput(row);
        },
        clear: function () {
            $('.js-input-remove').each(function () {
                removeInput($(this));
            });
        }
    };

    var addInput = function (btn, values) {
        var $wrapper = $(btn).closest('.multiple-input').first(),
            data = $wrapper.data('multipleInput'),
            settings = data.settings,
            template = settings.template,
            inputList = $wrapper.find('.multiple-input-list').first(),
            count = $wrapper.find('.multiple-input-list__item').length;

        if (settings.limit != null && count >= settings.limit) {
            return;
        }

        template = template.replaceAll('{multiple_index}', data.currentIndex);

        $(template).hide().appendTo(inputList).fadeIn(300);

        if (values instanceof Object) {
            var tmp = [];
            for (var key in values) {
                if (values.hasOwnProperty(key)) {
                    tmp.push(values[key]);
                }
            }
            values = tmp;
        }

        var index = 0;
        $(template).find('input, select, textarea').each(function () {
            var that = $(this),
                tag = that.get(0).tagName,
                id = getInputId(that),
                obj = $('#' + id);

            if (values) {
                var val = values[index];

                if (tag == 'INPUT' || tag == 'TEXTAREA') {
                    obj.val(val);
                } else if (tag == 'SELECT') {
                    if (val && val.indexOf('option')) {
                        obj.append(val);
                    } else {
                        var option = obj.find('option[value="' + val + '"]');
                        if (option.length) {
                            obj.val(val);
                        }
                    }
                }
            }

            addAttribute(that);

            index++;
        });

        var jsTemplate;
        for (var i in settings.jsTemplates) {
            jsTemplate = settings.jsTemplates[i]
                .replaceAll('{multiple_index}', data.currentIndex)
                .replaceAll('%7Bmultiple_index%7D', data.currentIndex);
            window.eval(jsTemplate);
        }
        $wrapper.data('multipleInput').currentIndex++;

        var event = $.Event(events.afterAddRow);
        $wrapper.trigger(event);
    };

    var removeInput = function ($btn) {
        var $wrapper = $btn.closest('.multiple-input').first(),
            $toDelete = $btn.closest('.multiple-input-list__item'),
            count = $('.multiple-input-list__item').length,
            data = $wrapper.data('multipleInput'),
            settings = data.settings;

        if (count > settings.min) {
            var event = $.Event(events.beforeDeleteRow);
            $wrapper.trigger(event, [$toDelete]);
            if (event.result === false) {
                return;
            }

            $toDelete.find('input, select, textarea').each(function () {
                removeAttribute($(this));
            });

            $toDelete.fadeOut(300, function () {
                $(this).remove();

                event = $.Event(events.afterDeleteRow);
                $wrapper.trigger(event);
            });
        }
    };

    var addAttribute = function (input) {
        var id = getInputId(input);

        // skip if we could not get an ID of input
        if (id === null) {
            return;
        }

        var ele = $('#' + id),
            wrapper = ele.closest('.multiple-input').first(),
            form = ele.closest('form');

        // do not add attribute which are not the part of widget
        if (wrapper.length == 0) {
            return;
        }

        // check that input has been already added to the activeForm
        if (typeof form.yiiActiveForm('find', id) !== 'undefined') {
            return;
        }

        var data = wrapper.data('multipleInput');
        form.yiiActiveForm('add', $.extend({}, data.attributeDefaults, {
            'id': id,
            'input': '#' + id,
            'container': '.field-' + id
        }));
    };

    var removeAttribute = function () {
        var id = getInputId($(this));

        if (id === null) {
            return;
        }

        var form = $('#' + id).closest('form');

        if (form.length !== 0) {
            form.yiiActiveForm('remove', id);
        }
    };

    var getInputId = function ($input) {
        var id = $input.attr('id');

        if (typeof id === 'undefined') {
            id = $input.data('id');
        }

        if (typeof id === 'undefined') {
            return null;
        }

        return id;
    };

    String.prototype.replaceAll = function (search, replace) {
        return this.split(search).join(replace);
    };
})(window.jQuery);


text:
import { Component } from '@angular/core';

@Component({
  selector: 'ngx-govuk-prose',
  template: `

<ng-content></ng-content>

  `
})
export class ProseComponent {

  constructor() {}

}


text:
import {EventEmitter} from "../../../"

describe("EventEmitter", ()=> {

  beforeEach(()=> {
    this.emitter = new EventEmitter()
  })

  it("constructor()", ()=> {
    expect(this.emitter.listeners).toEqual([])
  })

  it("add, trigger, remove", ()=> {
    let argsStr = ""
    let fn = (...args)=> {
      argsStr = args.join("")
    }
    let removeFn = this.emitter.addListener(fn)
    expect(this.emitter.listeners)
      .toEqual([fn])
    this.emitter.trigger("a", "b", "c")
    expect(argsStr).toEqual("abc")

    removeFn()
    expect(this.emitter.listeners).toEqual([])

  })

})


text:
<?php
/**
 * AIGA Nebraska includes
 *
 * The $NEIGHBORHOOD_mandatory_includes array determines the code library included in your theme.
 * Add or remove files to the array as needed. Supports child theme overrides.
 *
 * Please note that missing files will produce a fatal error.
 */

$NEIGHBORHOOD_mandatory_includes = [
	'wp/init_plugins.php',            // Initial theme setup and constants
	'wp/init.php',                    // Initial theme setup and constants
	'wp/conf_routes.php',             // Reroute pages or archives
	'wp/conf_activation.php',         // Theme activation
	'wp/conf_scripts.php',            // Scripts and stylesheets
	'wp/etc_utils.php',               // Utility functions
	'wp/conf_post_formats.php',       // configures post format changes
	'wp/conf_post_types.php',         // Initiates custom post types
	'wp/conf_post_taxonomies.php',    // Initiates taxonomies
	'wp/conf_post_acf.php',           // Initiates default ACF fields
	'wp/init_wrapper.php',            // Theme wrapper class
	'wp/init_search.php',             // Search queries
	'wp/conf_images.php',             // Functions for images and custom sizes
	'wp/init_sidebar.php',            // Sidebar class
	'wp/init_walkers_nav.php',        // Custom walkers
	'wp/conf_admin.php',              // Admin config
	'wp/etc_extras.php',              // Custom functions
	'wp/init_sendo.php',              // SENDO
	'wp/init_pjax.php',               // PJAX settings and fixes
	'wp/conf_editor.php',             // Configuration settings for the Editor/TinyMCE
	'wp/conf_gallery.php',            // Markup changes for the media gallery functionality
];

$NEIGHBORHOOD_features_prepend = [
	'wp/api_mobiledetect.php',        // gets user agent string from request
	'wp/api_carbon.php',              // Carbon API - Helps with date/times.
	// 'wp/api_codepen.php',             // Codepen API
	// 'wp/api_dribbble.php',            // Dribbble API
	// 'wp/api_facebook.php',            // Facebook API
	// 'wp/api_vimeo.php',               // Vimeo API
	// 'wp/api_instagram.php',           // Instagram API
	// 'wp/api_medium.php',              // Medium API
	// 'wp/api_rss.php',                 // RSS API Provider
	// 'wp/api_twitter.php',             // Twitter API
	// 'wp/api_helpers.php',             // Helper functions that make the above API's usable.
];

$NEIGHBORHOOD_features_append = [
	'wp/api_carbon.php',              // Carbon - Makes dealing with date/time easier
	'wp/init_htmlcompression.php',    // HTML compression on every request
	'wp/conf_shortcodes.php',         // Contains shortcodes, like [smart_image]
	'wp/conf_prettify_acf.php',       // Contains the code to make flexible content fields look prettier.
];

$NEIGHBORHOOD_includes = array_merge($NEIGHBORHOOD_features_prepend, $NEIGHBORHOOD_mandatory_includes, $NEIGHBORHOOD_features_append);

foreach ($NEIGHBORHOOD_includes as $file) {
	if (!$filepath = locate_template($file)) {
		trigger_error(sprintf(__('Error locating %s for inclusion', 'NEIGHBORHOOD'), $file), E_USER_ERROR);
	}

	require_once $filepath;
}

unset($file, $filepath);

if (class_exists('SENDO')) {
	$sendo = new SENDO();
}


text:
Release Process
====================

* update translations (ping wumpus, Diapolo or tcatm on IRC)
* see https://github.com/bitcoin/bitcoin/blob/master/doc/translation_process.md#syncing-with-transifex

* * *

###update (commit) version in sources

	bitcoin-qt.pro
	contrib/verifysfbinaries/verify.sh
	doc/README*
	share/setup.nsi
	src/clientversion.h (change CLIENT_VERSION_IS_RELEASE to true)

###tag version in git

	git tag -s v(new version, e.g. 0.8.0)

###write release notes. git shortlog helps a lot, for example:

	git shortlog --no-merges v(current version, e.g. 0.7.2)..v(new version, e.g. 0.8.0)

* * *

##perform gitian builds

 From a directory containing the bitcoin source, gitian-builder and gitian.sigs

	export SIGNER=(your gitian key, ie bluematt, sipa, etc)
	export VERSION=(new version, e.g. 0.8.0)
	pushd ./bitcoin
	git checkout v${VERSION}
	popd
	pushd ./gitian-builder

 Fetch and build inputs: (first time, or when dependency versions change)

	mkdir -p inputs; cd inputs/
	wget 'http://miniupnp.free.fr/files/download.php?file=miniupnpc-1.9.tar.gz' -O miniupnpc-1.9.tar.gz
	wget 'https://www.openssl.org/source/openssl-1.0.1g.tar.gz'
	wget 'http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz'
	wget 'http://zlib.net/zlib-1.2.8.tar.gz'
	wget 'ftp://ftp.simplesystems.org/pub/png/src/history/libpng16/libpng-1.6.8.tar.gz'
	wget 'https://fukuchi.org/works/qrencode/qrencode-3.4.3.tar.bz2'
	wget 'https://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.bz2'
	wget 'https://svn.boost.org/trac/boost/raw-attachment/ticket/7262/boost-mingw.patch' -O \
	     boost-mingw-gas-cross-compile-2013-03-03.patch
	wget 'https://download.qt-project.org/official_releases/qt/5.2/5.2.0/single/qt-everywhere-opensource-src-5.2.0.tar.gz'
	wget 'https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.bz2'
	cd ..
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/boost-linux.yml
	mv build/out/boost-*.zip inputs/
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/deps-linux.yml
	mv build/out/bitcoin-deps-*.zip inputs/
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/boost-win.yml
	mv build/out/boost-*.zip inputs/
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/deps-win.yml
	mv build/out/bitcoin-deps-*.zip inputs/
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/qt-win.yml
	mv build/out/qt-*.zip inputs/
	./bin/gbuild ../bitcoin/contrib/gitian-descriptors/protobuf-win.yml
	mv build/out/protobuf-*.zip inputs/

 The expected SHA256 hashes of the intermediate inputs are:

    35c3dfd8b9362f59e81b51881b295232e3bc9e286f1add193b59d486d9ac4a5c  bitcoin-deps-linux32-gitian-r5.zip
    571789867d172500fa96d63d0ba8c5b1e1a3d6f44f720eddf2f93665affc88b3  bitcoin-deps-linux64-gitian-r5.zip
    f29b7d9577417333fb56e023c2977f5726a7c297f320b175a4108cf7cd4c2d29  boost-linux32-1.55.0-gitian-r1.zip
    88232451c4104f7eb16e469ac6474fd1231bd485687253f7b2bdf46c0781d535  boost-linux64-1.55.0-gitian-r1.zip
    60dc2d3b61e9c7d5dbe2f90d5955772ad748a47918ff2d8b74e8db9b1b91c909  boost-win32-1.55.0-gitian-r6.zip
    f65fcaf346bc7b73bc8db3a8614f4f6bee2f61fcbe495e9881133a7c2612a167  boost-win64-1.55.0-gitian-r6.zip
    97e62002d338885336bb24e7cbb9471491294bd8857af7a83d18c0961f864ec0  bitcoin-deps-win32-gitian-r11.zip
    ee3ea2d5aac1a67ea6bfbea2c04068a7c0940616ce48ee4f37c264bb9d4438ef  bitcoin-deps-win64-gitian-r11.zip
    963e3e5e85879010a91143c90a711a5d1d5aba992e38672cdf7b54e42c56b2f1  qt-win32-5.2.0-gitian-r3.zip
    751c579830d173ef3e6f194e83d18b92ebef6df03289db13ab77a52b6bc86ef0  qt-win64-5.2.0-gitian-r3.zip
    e2e403e1a08869c7eed4d4293bce13d51ec6a63592918b90ae215a0eceb44cb4  protobuf-win32-2.5.0-gitian-r4.zip
    a0999037e8b0ef9ade13efd88fee261ba401f5ca910068b7e0cd3262ba667db0  protobuf-win64-2.5.0-gitian-r4.zip

 Build bitcoind and bitcoin-qt on Linux32, Linux64, and Win32:

	./bin/gbuild --commit bitcoin=v${VERSION} ../bitcoin/contrib/gitian-descriptors/gitian-linux.yml
	./bin/gsign --signer $SIGNER --release ${VERSION} --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-linux.yml
	pushd build/out
	zip -r bitcoin-${VERSION}-linux-gitian.zip *
	mv bitcoin-${VERSION}-linux-gitian.zip ../../../
	popd
	./bin/gbuild --commit bitcoin=v${VERSION} ../bitcoin/contrib/gitian-descriptors/gitian-win.yml
	./bin/gsign --signer $SIGNER --release ${VERSION}-win --destination ../gitian.sigs/ ../bitcoin/contrib/gitian-descriptors/gitian-win.yml
	pushd build/out
	zip -r bitcoin-${VERSION}-win-gitian.zip *
	mv bitcoin-${VERSION}-win-gitian.zip ../../../
	popd
	popd

  Build output expected:

  1. linux 32-bit and 64-bit binaries + source (bitcoin-${VERSION}-linux-gitian.zip)
  2. windows 32-bit and 64-bit binaries + installer + source (bitcoin-${VERSION}-win-gitian.zip)
  3. Gitian signatures (in gitian.sigs/${VERSION}[-win]/(your gitian key)/

repackage gitian builds for release as stand-alone zip/tar/installer exe

**Linux .tar.gz:**

	unzip bitcoin-${VERSION}-linux-gitian.zip -d bitcoin-${VERSION}-linux
	tar czvf bitcoin-${VERSION}-linux.tar.gz bitcoin-${VERSION}-linux
	rm -rf bitcoin-${VERSION}-linux

**Windows .zip and setup.exe:**

	unzip bitcoin-${VERSION}-win-gitian.zip -d bitcoin-${VERSION}-win
	mv bitcoin-${VERSION}-win/bitcoin-*-setup.exe .
	zip -r bitcoin-${VERSION}-win.zip bitcoin-${VERSION}-win
	rm -rf bitcoin-${VERSION}-win

**Perform Mac build:**

  OSX binaries are created by Gavin Andresen on a 64-bit, OSX 10.6 machine.

	./autogen.sh
        SDK=$(xcode-select --print-path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.6.sdk
        CXXFLAGS="-mmacosx-version-min=10.6 -isysroot $SDK" ./configure --enable-upnp-default
	make
	export QTDIR=/opt/local/share/qt4  # needed to find translations/qt_*.qm files
	T=$(contrib/qt_translations.py $QTDIR/translations src/qt/locale)
        export CODESIGNARGS='--keychain ...path_to_keychain --sign "Developer ID Application: BITCOIN FOUNDATION, INC., THE"'
	python2.7 contrib/macdeploy/macdeployqtplus Bitcoin-Qt.app -sign -add-qt-tr $T -dmg -fancy contrib/macdeploy/fancy.plist

 Build output expected: Bitcoin-Qt.dmg

###Next steps:

* Code-sign Windows -setup.exe (in a Windows virtual machine using signtool)
 Note: only Gavin has the code-signing keys currently.

* upload builds to SourceForge

* create SHA256SUMS for builds, and PGP-sign it

* update bitcoin.org version
  make sure all OS download links go to the right versions

* update download sizes on bitcoin.org/_templates/download.html

* update forum version

* update wiki download links

* update wiki changelog: [https://en.bitcoin.it/wiki/Changelog](https://en.bitcoin.it/wiki/Changelog)

Commit your signature to gitian.sigs:

	pushd gitian.sigs
	git add ${VERSION}/${SIGNER}
	git add ${VERSION}-win/${SIGNER}
	git commit -a
	git push  # Assuming you can push to the gitian.sigs tree
	popd

-------------------------------------------------------------------------

### After 3 or more people have gitian-built, repackage gitian-signed zips:

From a directory containing bitcoin source, gitian.sigs and gitian zips

	export VERSION=(new version, e.g. 0.8.0)
	mkdir bitcoin-${VERSION}-linux-gitian
	pushd bitcoin-${VERSION}-linux-gitian
	unzip ../bitcoin-${VERSION}-linux-gitian.zip
	mkdir gitian
	cp ../bitcoin/contrib/gitian-downloader/*.pgp ./gitian/
	for signer in $(ls ../gitian.sigs/${VERSION}/); do
	 cp ../gitian.sigs/${VERSION}/${signer}/bitcoin-build.assert ./gitian/${signer}-build.assert
	 cp ../gitian.sigs/${VERSION}/${signer}/bitcoin-build.assert.sig ./gitian/${signer}-build.assert.sig
	done
	zip -r bitcoin-${VERSION}-linux-gitian.zip *
	cp bitcoin-${VERSION}-linux-gitian.zip ../
	popd
	mkdir bitcoin-${VERSION}-win-gitian
	pushd bitcoin-${VERSION}-win-gitian
	unzip ../bitcoin-${VERSION}-win-gitian.zip
	mkdir gitian
	cp ../bitcoin/contrib/gitian-downloader/*.pgp ./gitian/
	for signer in $(ls ../gitian.sigs/${VERSION}-win/); do
	 cp ../gitian.sigs/${VERSION}-win/${signer}/bitcoin-build.assert ./gitian/${signer}-build.assert
	 cp ../gitian.sigs/${VERSION}-win/${signer}/bitcoin-build.assert.sig ./gitian/${signer}-build.assert.sig
	done
	zip -r bitcoin-${VERSION}-win-gitian.zip *
	cp bitcoin-${VERSION}-win-gitian.zip ../
	popd

- Upload gitian zips to SourceForge

- Announce the release:

  - Add the release to bitcoin.org: https://github.com/bitcoin/bitcoin.org/tree/master/_releases

  - Release sticky on bitcointalk: https://bitcointalk.org/index.php?board=1.0

  - Bitcoin-development mailing list

  - Optionally reddit /r/Bitcoin, ...

- Celebrate


text: This is cool stuff


text:
/*
 * patMapMatchingEnvironment.cc
 *
 *  Created on: Oct 19, 2011
 *      Author: jchen
 */

#include "patNetworkEnvironment.h"
#include "patGeoBoundingBox.h"
#include "patWay.h"
#include "patPostGreSQLConnector.h"
#include "patDisplay.h"
#include "patNetworkCar.h"
#include "patNetworkBus.h"
#include "patNetworkTrain.h"
#include "patNetworkWalk.h"
#include "patNetworkMetro.h"
#include "patNetworkBike.h"
#include "patNBParameters.h"
#include "libconfig.h++"
using namespace libconfig;

patNetworkEnvironment::patNetworkEnvironment(patGeoBoundingBox& bb) {
//Initiate rules for loading types of network elements.
//	DEBUG_MESSAGE(patNBParameters::the()->enableTrainNetwork
//			<<patNBParameters::the()->enableBikeNetwork
//			<<patNBParameters::the()->enableWalkNetwork
//			<<patNBParameters::the()->enableBusNetwork
//			<<patNBParameters::the()->enableCarNetwork
//			<<patNBParameters::the()->enableMetroNetwork
//			);

//
	if (patNBParameters::the()->databaseHost != "") {
		m_network_elements.readNetworkFromPostGreSQL(bb);
	} else {
		m_network_elements.readNetworkFromOSMFile(

		patNBParameters::the()->OsmNetworkFileName, bb);
	}

	DEBUG_MESSAGE("Network topology has been read.");
	DEBUG_MESSAGE("Start to read transport network structures.");
	if (patNBParameters::the()->enableTrainNetwork == 1) {
		m_networks["train"] = new patNetworkTrain();
		m_networks["train"]->getFromNetwork(&m_network_elements, bb);
	}
	if (patNBParameters::the()->enableBikeNetwork == 1) {
		m_networks["bike"] = new patNetworkBike();
		m_networks["bike"]->getFromNetwork(&m_network_elements, bb);
	}
	if (patNBParameters::the()->enableWalkNetwork == 1) {
		m_networks["walk"] = new patNetworkWalk();
		m_networks["walk"]->getFromNetwork(&m_network_elements, bb);
	}
	if (patNBParameters::the()->enableBusNetwork == 1) {
		m_networks["bus"] = new patNetworkBus();
		m_networks["bus"]->getFromNetwork(&m_network_elements, bb);
	}

	if (patNBParameters::the()->enableCarNetwork == 1) {
		m_networks["car"] = new patNetworkCar();
		m_networks["car"]->getFromNetwork(&m_network_elements, bb);
	}

	if (patNBParameters::the()->enableMetroNetwork == 1) {
		m_networks["metro"] = new patNetworkMetro();
		m_networks["metro"]->getFromNetwork(&m_network_elements, bb);
	}
	if (m_networks.find("walk") != m_networks.end()) {
		DEBUG_MESSAGE("Deal with walk connection for networks");

		for (map<string, patNetworkBase*>::iterator network_iter =
				m_networks.begin(); network_iter != m_networks.end();
				++network_iter) {
			/*
			 if(isPublicTransport(network_iter->second->getTransportMode())){
			 network_iter->second->walkFromToStops(&m_network_elements,m_networks["walk"]);
			 }
			 */
			if (network_iter->second->getTransportMode() == METRO) {
//				if (patNBParameters::the()->walkOnTrack) {
//					network_iter->second->walkOnTrack(&m_network_elements,
//							m_networks["walk"]);
//				}
				network_iter->second->walkFromToStops(&m_network_elements,
						m_networks["walk"]);
			}
		}
	}

	m_network_elements.computeLength(); //It has to be here. after reading all network, before finalize them.

	for (map<string, patNetworkBase*>::iterator network_iter =
			m_networks.begin(); network_iter != m_networks.end();
			++network_iter) {
		network_iter->second->finalizeNetwork();
		DEBUG_MESSAGE(
				network_iter->first << " network node size" << network_iter->second->getNodeSize());

	}

//		DEBUG_MESSAGE("network with nodes: "<<getNetwork(CAR)->getNodeSize());

//		DEBUG_MESSAGE("finished");
//		exportNetwork();

//}

//	DEBUG_MESSAGE("network with nodes: "<<getNetwork(CAR)->getNodeSize());
}

void patNetworkEnvironment::exportNetwork() {
	for (map<string, patNetworkBase*>::iterator network_iter =
			m_networks.begin(); network_iter != m_networks.end();
			++network_iter) {
//		network_iter->second->exportKML(network_iter->first);
		network_iter->second->exportShpFiles(network_iter->first);
	}
}
patNetworkEnvironment::~patNetworkEnvironment() {
	for (map<string, patNetworkBase*>::iterator network_iter =
			m_networks.begin(); network_iter != m_networks.end();
			++network_iter) {
		delete network_iter->second;
		network_iter->second = NULL;
	}
}

const patNetworkBase* patNetworkEnvironment::getNetwork(string network_type) {
	map<string, patNetworkBase*>::const_iterator find_network = m_networks.find(
			network_type);
	if (find_network == m_networks.end()) {
		return NULL;
	} else {
		return find_network->second;
	}
}

const map<string, patNetworkBase*>* patNetworkEnvironment::getAllNetworks() const {
	return &m_networks;
}
const patNetworkElements& patNetworkEnvironment::getNetworkElements() const {
	return m_network_elements;
}

const patNetworkBase* patNetworkEnvironment::getNetwork(
		TransportMode mode) const {
	string network_string = getTransportMode(mode);
	const map<string, patNetworkBase*>::const_iterator find_network =
			m_networks.find(network_string);

	if (find_network == m_networks.end()) {
//		DEBUG_MESSAGE("NETWORK"<<mode<<"NOT FOUND");

		throw RuntimeException("Network not found");
		return NULL;
	} else {
//		DEBUG_MESSAGE("NETWORK"<<mode<<" FOUND");
		return find_network->second;
	}
}

double patNetworkEnvironment::getMinimumTravelTime(const patRoadBase* road,
		TransportMode mode) const {
	return 3.6 * (road->getLength()) / (getNetwork(mode)->getMaxSpeed());
}

bool patNetworkEnvironment::isPTStop(const patNode* stop) const {

	for (map<string, patNetworkBase*>::const_iterator network_iter =
			m_networks.begin(); network_iter != m_networks.end();
			++network_iter) {
		if (network_iter->second->isPT()) {
			if (network_iter->second->isStop(stop)) {
				return true;
			}
		}
	}
	return false;
}
void patNetworkEnvironment::computeGeneralizedCost(
		const map<ARC_ATTRIBUTES_TYPES, double>& link_coef) {
	m_network_elements.computeGeneralizedCost(link_coef);
}


text:
import { DemoFile } from "../demo";
import { IServerClass, UnknownEntityProps } from "../entities";
/**
 * Represents an in-game entity.
 */
export declare class Networkable<Props = UnknownEntityProps> {
    /**
     * Get the serverclass associated with this entity.
     * @returns Object representing the entity's class
     */
    get serverClass(): IServerClass;
    /**
     * @returns Number uniquely identifying this entity. Should be unique throughout the entire demo.
     */
    get handle(): number;
    /**
     * Entity index.
     */
    index: number;
    /**
     * Server class ID.
     */
    classId: number;
    /**
     * Serial number.
     */
    serialNum: number;
    props: Props;
    /**
     * Entity is scheduled for removal this tick.
     */
    deleting: boolean;
    protected _demo: DemoFile;
    constructor(demo: DemoFile, index: number, classId: number, serialNum: number, props: Props | undefined);
    /**
     * Retrieves the value of a networked property
     * @param {string} tableName - Table name (e.g., DT_BaseEntity)
     * @param {string} varName - Network variable name (e.g., m_vecOrigin)
     * @returns {*} Property value, `undefined` if non-existent
     * @public
     */
    getProp<Table extends keyof Props, VarName extends keyof Props[Table]>(tableName: Table, varName: VarName): Props[Table][VarName];
    /**
     * Interpret an array-like data table (e.g., m_iAmmo) as an array
     * @param tableName Name of the data table
     */
    getIndexedProps<TableName extends keyof Props, TableKeys extends keyof Props[TableName], ArrayType extends "000" extends TableKeys ? ReadonlyArray<Props[TableName][TableKeys]> : undefined>(tableName: TableName): ArrayType;
    /**
     * Update the value of a prop
     * @param tableName Name of the data table
     * @param varName Name of the prop to update
     * @param newValue New prop value
     */
    updateProp<Table extends keyof Props, VarName extends keyof Props[Table], PropType extends Props[Table][VarName]>(tableName: Table, varName: VarName, newValue: PropType): void;
    /**
     * True if this entity is out of the PVS.
     * Always false on GOTV demos as all entities are always in the PVS.
     */
    get isDormant(): boolean;
    toJSON(): string;
}


text:
using Bridge.Test.NUnit;
using Bridge.ClientTestHelper;
using System;

namespace Bridge.ClientTest.SimpleTypes
{
    [Category(Constants.MODULE_DATETIME)]
    [TestFixture(TestNameFormat = "TimeSpan - {0}")]
    public class TimeSpanTests
    {
        [Test]
        public void TypePropertiesAreCorrect_SPI_1717()
        {
            Assert.AreEqual("System.TimeSpan", typeof(TimeSpan).FullName);
            Assert.False(typeof(TimeSpan).IsClass);
            Assert.True(typeof(IComparable<TimeSpan>).IsAssignableFrom(typeof(TimeSpan)));
            Assert.True(typeof(IEquatable<TimeSpan>).IsAssignableFrom(typeof(TimeSpan)));
            object d = new TimeSpan();
            Assert.True(d is TimeSpan);
            Assert.True(d is IComparable<TimeSpan>);
            Assert.True(d is IEquatable<TimeSpan>);

            var interfaces = typeof(TimeSpan).GetInterfaces();
            Assert.AreEqual(3, interfaces.Length);
            Assert.True(interfaces.Contains(typeof(IComparable<TimeSpan>)));
            Assert.True(interfaces.Contains(typeof(IEquatable<TimeSpan>)));
        }

        [Test]
        public void DefaultConstructorWorks()
        {
            var time = new TimeSpan();
            Assert.AreEqual(0L, time.Ticks);
        }

        [Test]
        public void DefaultValueWorks()
        {
            var ts = default(TimeSpan);
            Assert.AreEqual(0L, ts.Ticks);
        }

        [Test]
        public void ZeroWorks()
        {
            var ts = TimeSpan.Zero;
            Assert.AreEqual(0L, ts.Ticks);
        }

        [Test]
        public void CreatingInstanceReturnsTimeSpanWithZeroValue()
        {
            var ts = Activator.CreateInstance<TimeSpan>();
            Assert.AreEqual(0L, ts.Ticks);
        }

        [Test]
        public void ParameterConstructorsWorks()
        {
            var time = new TimeSpan(34567L);
            Assert.True((object)time is TimeSpan, "ticks type");
            Assert.AreEqual(34567L, time.Ticks, "ticks value");

            time = new TimeSpan(10, 20, 5);
            Assert.True((object)time is TimeSpan, "h, m, s type");
            Assert.AreEqual(372050000000L, time.Ticks, "h, m, s value");

            time = new TimeSpan(15, 10, 20, 5);
            Assert.True((object)time is TimeSpan, "d, h, m, s type");
            Assert.AreEqual(13332050000000L, time.Ticks, "d, h, m, s value");

            time = new TimeSpan(15, 10, 20, 5, 14);
            Assert.True((object)time is TimeSpan, "full type");
            Assert.AreEqual(13332050140000L, time.Ticks, "full value");
        }

        [Test]
        public void FactoryMethodsWork()
        {
            var time = TimeSpan.FromDays(3);
            Assert.True((object)time is TimeSpan, "FromDays type");
            Assert.AreEqual(2592000000000L, time.Ticks, "FromDays value");

            time = TimeSpan.FromHours(3);
            Assert.True((object)time is TimeSpan, "FromHours type");
            Assert.AreEqual(108000000000L, time.Ticks, "FromHours value");

            time = TimeSpan.FromMinutes(3);
            Assert.True((object)time is TimeSpan, "FromMinutes type");
            Assert.AreEqual(1800000000L, time.Ticks, "FromMinutes value");

            time = TimeSpan.FromSeconds(3);
            Assert.True((object)time is TimeSpan, "FromSeconds type");
            Assert.AreEqual(30000000L, time.Ticks, "FromSeconds value");

            time = TimeSpan.FromMilliseconds(3);
            Assert.True((object)time is TimeSpan, "FromMilliseconds type");
            Assert.AreEqual(30000L, time.Ticks, "FromMilliseconds value");

            time = TimeSpan.FromTicks(3);
            Assert.True((object)time is TimeSpan, "FromTicks type");
            Assert.AreEqual(3L, time.Ticks, "FromTicks value");
        }

        [Test]
        public void PropertiesWork()
        {
            var time = new TimeSpan(15, 10, 20, 5, 14);
            Assert.AreEqual(15, time.Days);
            Assert.AreEqual(10, time.Hours);
            Assert.AreEqual(20, time.Minutes);
            Assert.AreEqual(5, time.Seconds);
            Assert.AreEqual(14, time.Milliseconds);
            NumberHelper.AssertDoubleWithEpsilon8(15.430613587962963d, time.TotalDays);
            NumberHelper.AssertDoubleWithEpsilon8(370.33472611111108d, time.TotalHours);
            NumberHelper.AssertDoubleWithEpsilon8(22220.083566666668d, time.TotalMinutes);
            NumberHelper.AssertDoubleWithEpsilon8(1333205.014d, time.TotalSeconds);
            NumberHelper.AssertDoubleWithEpsilon8(1333205014.0d, time.TotalMilliseconds);
            Assert.AreEqual(15 * TimeSpan.TicksPerDay + 10 * TimeSpan.TicksPerHour + 20 * TimeSpan.TicksPerMinute + 5 * TimeSpan.TicksPerSecond + 14 * TimeSpan.TicksPerMillisecond, time.Ticks);
        }

        [Test]
        public void CompareToWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(15, 10, 20, 5, 14);
            var time3 = new TimeSpan(14, 10, 20, 5, 14);
            var time4 = new TimeSpan(15, 11, 20, 5, 14);
            Assert.AreEqual(time1.CompareTo(time1), 0);
            Assert.AreEqual(time1.CompareTo(time2), 0);
            Assert.AreEqual(time1.CompareTo(time3), 1);
            Assert.AreEqual(time1.CompareTo(time4), -1);
        }

        [Test]
        public void CompareWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(15, 10, 20, 5, 14);
            var time3 = new TimeSpan(14, 10, 20, 5, 14);
            var time4 = new TimeSpan(15, 11, 20, 5, 14);
            Assert.AreEqual(TimeSpan.Compare(time1, time1), 0);
            Assert.AreEqual(TimeSpan.Compare(time1, time2), 0);
            Assert.AreEqual(TimeSpan.Compare(time1, time3), 1);
            Assert.AreEqual(TimeSpan.Compare(time1, time4), -1);
        }

        [Test]
        public void StaticEqualsWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(14, 10, 20, 5, 14);
            var time3 = new TimeSpan(15, 10, 20, 5, 14);

            Assert.False(TimeSpan.Equals(time1, time2));
            Assert.True(TimeSpan.Equals(time1, time3));
        }

        [Test]
        public void EqualsWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(14, 10, 20, 5, 14);
            var time3 = new TimeSpan(15, 10, 20, 5, 14);

            Assert.False(time1.Equals(time2));
            Assert.True(time1.Equals(time3));
        }

        [Test]
        public void IEquatableEqualsWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(14, 10, 20, 5, 14);
            var time3 = new TimeSpan(15, 10, 20, 5, 14);

            Assert.False(((IEquatable<TimeSpan>)time1).Equals(time2));
            Assert.True(((IEquatable<TimeSpan>)time1).Equals(time3));
        }

        [Test]
        public void ToStringWorks()
        {
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(14, 10, 20, 5, 2);
            var time3 = new TimeSpan(15, 11, 20, 6, 14);
            var time4 = new TimeSpan(1, 2, 3);
            Assert.AreEqual("15.10:20:05.0140000", time1.ToString());
            Assert.AreEqual("14.10:20:05.0020000", time2.ToString());
            Assert.AreEqual("15.11:20:06.0140000", time3.ToString());
            Assert.AreEqual("01:02:03", time4.ToString());
        }

        [Test]
        public void AddWorks()
        {
            var time1 = new TimeSpan(2, 3, 4, 5, 6);
            var time2 = new TimeSpan(3, 4, 5, 6, 7);
            TimeSpan actual = time1.Add(time2);
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual(((((((5 * 24) + 7) * 60) + 9) * 60) + 11) * 1000 + 13, actual.TotalMilliseconds, "TotalMilliseconds should be correct");
        }

        [Test]
        public void SubtractWorks()
        {
            var time1 = new TimeSpan(4, 3, 7, 2, 6);
            var time2 = new TimeSpan(3, 4, 5, 6, 7);
            TimeSpan actual = time1.Subtract(time2);
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual(((((((1 * 24) - 1) * 60) + 2) * 60) - 4) * 1000 - 1, actual.TotalMilliseconds, "TotalMilliseconds should be correct");
        }

        [Test]
        public void DurationWorks()
        {
            var time1 = new TimeSpan(-3, -2, -1, -5, -4);
            var time2 = new TimeSpan(2, 1, 5, 4, 3);
            TimeSpan actual1 = time1.Duration();
            TimeSpan actual2 = time2.Duration();
            Assert.True((object)time1 is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual((((((3 * 24) + 2) * 60 + 1) * 60) + 5) * 1000 + 4, actual1.TotalMilliseconds, "Negative should be negated");
            Assert.AreEqual((((((2 * 24) + 1) * 60 + 5) * 60) + 4) * 1000 + 3, actual2.TotalMilliseconds, "Positive should be preserved");
        }

        [Test]
        public void NegateWorks()
        {
            var time = new TimeSpan(-3, 2, -1, 5, -4);
            TimeSpan actual = time.Negate();
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual((((((3 * 24) - 2) * 60 + 1) * 60) - 5) * 1000 + 4, actual.TotalMilliseconds, "Ticks should be correct");
        }

        [Test]
        public void ComparisonOperatorsWork()
        {
#pragma warning disable 1718
            var time1 = new TimeSpan(15, 10, 20, 5, 14);
            var time2 = new TimeSpan(15, 10, 20, 5, 14);
            var time3 = new TimeSpan(14, 10, 20, 5, 14);
            var time4 = new TimeSpan(15, 11, 20, 5, 14);

            Assert.False(time1 > time2, "> 1");
            Assert.True(time1 > time3, "> 2");
            Assert.False(time1 > time4, "> 3");

            Assert.True(time1 >= time2, ">= 1");
            Assert.True(time1 >= time3, ">= 2");
            Assert.False(time1 >= time4, ">= 3");

            Assert.False(time1 < time2, "< 1");
            Assert.False(time1 < time3, "< 2");
            Assert.True(time1 < time4, "< 3");

            Assert.True(time1 <= time2, "<= 1");
            Assert.False(time1 <= time3, "<= 2");
            Assert.True(time1 <= time4, "<= 3");

            Assert.True(time1 == time1, "== 1");
            Assert.True(time1 == time2, "== 2");
            Assert.False(time1 == time3, "== 3");
            Assert.False(time1 == time4, "== 4");

            Assert.False(time1 != time1, "!= 1");
            Assert.False(time1 != time2, "!= 2");
            Assert.True(time1 != time3, "!= 3");
            Assert.True(time1 != time4, "!= 4");
#pragma warning restore 1718
        }

        [Test]
        public void AdditionOperatorWorks()
        {
            var time1 = new TimeSpan(2, 3, 4, 5, 6);
            var time2 = new TimeSpan(3, 4, 5, 6, 7);
            TimeSpan actual = time1 + time2;
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual(((((((5 * 24) + 7) * 60) + 9) * 60) + 11) * 1000 + 13, actual.TotalMilliseconds, "TotalMilliseconds should be correct");
        }

        [Test]
        public void SubtractionOperatorWorks()
        {
            var time1 = new TimeSpan(4, 3, 7, 2, 6);
            var time2 = new TimeSpan(3, 4, 5, 6, 7);
            TimeSpan actual = time1 - time2;
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual(((((((1 * 24) - 1) * 60) + 2) * 60) - 4) * 1000 - 1, actual.TotalMilliseconds, "TotalMilliseconds should be correct");
        }

        [Test]
        public void UnaryPlusWorks()
        {
            var time = new TimeSpan(-3, 2, -1, 5, -4);
            TimeSpan actual = +time;
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual((((((-3 * 24) + 2) * 60 - 1) * 60) + 5) * 1000 - 4, actual.TotalMilliseconds, "Ticks should be correct");
        }

        [Test]
        public void UnaryMinusWorks()
        {
            var time = new TimeSpan(-3, 2, -1, 5, -4);
            TimeSpan actual = -time;
            Assert.True((object)actual is TimeSpan, "Should be TimeSpan");
            Assert.AreEqual((((((3 * 24) - 2) * 60 + 1) * 60) - 5) * 1000 + 4, actual.TotalMilliseconds, "Ticks should be correct");
        }

        [Test]
        public void ParseWorks()
        {
            var str = "01:02:03";
            var ts = TimeSpan.Parse(str);

            Assert.AreEqual(0, ts.Days, "Could parse amount of days from HH:MM:SS time span.");
            Assert.AreEqual(1, ts.Hours, "Could parse amount of hours from HH:MM:SS time span.");
            Assert.AreEqual(2, ts.Minutes, "Could parse amount of minutes from HH:MM:SS time span.");
            Assert.AreEqual(3, ts.Seconds, "Could parse amount of seconds from HH:MM:SS time span.");
            Assert.AreEqual(0, ts.Milliseconds, "Could parse amount of milliseconds from HH:MM:SS time span.");

            str = "-01:02:03";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(0, ts.Days, "Could parse amount of days from -HH:MM:SS time span.");
            Assert.AreEqual(-1, ts.Hours, "Could parse amount of hours from -HH:MM:SS time span.");
            Assert.AreEqual(-2, ts.Minutes, "Could parse amount of minutes from -HH:MM:SS time span.");
            Assert.AreEqual(-3, ts.Seconds, "Could parse amount of seconds from -HH:MM:SS time span.");
            Assert.AreEqual(0, ts.Milliseconds, "Could parse amount of milliseconds from -HH:MM:SS time span.");
            Assert.True(ts.Ticks < 0, "Amount of ticks in less than zero on -HH:MM:SS time span.");

            str = "01:02:03.999";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(0, ts.Days, "Could parse amount of days from HH:MM:SS.sss time span.");
            Assert.AreEqual(1, ts.Hours, "Could parse amount of hours from HH:MM:SS.sss time span.");
            Assert.AreEqual(2, ts.Minutes, "Could parse amount of minutes from HH:MM:SS.sss time span.");
            Assert.AreEqual(3, ts.Seconds, "Could parse amount of seconds from HH:MM:SS.sss time span.");
            Assert.AreEqual(999, ts.Milliseconds, "Could parse amount of milliseconds from HH:MM:SS.sss time span.");

            str = "04:01:02:03";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(4, ts.Days, "Could parse amount of days from DD:HH:MM:SS time span.");
            Assert.AreEqual(1, ts.Hours, "Could parse amount of hours from DD:HH:MM:SS time span.");
            Assert.AreEqual(2, ts.Minutes, "Could parse amount of minutes from DD:HH:MM:SS time span.");
            Assert.AreEqual(3, ts.Seconds, "Could parse amount of seconds from DD:HH:MM:SS time span.");
            Assert.AreEqual(0, ts.Milliseconds, "Could parse amount of milisseconds from DD:HH:MM:SS time span.");

            str = "04.01:02:03";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(4, ts.Days, "Could parse amount of days from DD.HH:MM:SS time span.");
            Assert.AreEqual(1, ts.Hours, "Could parse amount of hours from DD.HH:MM:SS time span.");
            Assert.AreEqual(2, ts.Minutes, "Could parse amount of minutes from DD.HH:MM:SS time span.");
            Assert.AreEqual(3, ts.Seconds, "Could parse amount of seconds from DD.HH:MM:SS time span.");
            Assert.AreEqual(0, ts.Milliseconds, "Could parse amount of milisseconds from DD.HH:MM:SS time span.");

            str = "-04.01:02:03";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(-4, ts.Days, "Could parse amount of days from -DD.HH:MM:SS time span.");
            Assert.AreEqual(-1, ts.Hours, "Could parse amount of hours from -DD.HH:MM:SS time span.");
            Assert.AreEqual(-2, ts.Minutes, "Could parse amount of minutes from -DD.HH:MM:SS time span.");
            Assert.AreEqual(-3, ts.Seconds, "Could parse amount of seconds from -DD.HH:MM:SS time span.");
            Assert.AreEqual(0, ts.Milliseconds, "Could parse amount of milisseconds from -DD.HH:MM:SS time span.");
            Assert.True(ts.Ticks < 0, "Amount of ticks in less than zero on -DD.HH:MM:SS time span.");

            str = "04.01:02:03.999";
            ts = TimeSpan.Parse(str);

            Assert.AreEqual(4, ts.Days, "Could parse amount of days from DD.HH:MM:SS.sss time span.");
            Assert.AreEqual(1, ts.Hours, "Could parse amount of hours from DD.HH:MM:SS.sss time span.");
            Assert.AreEqual(2, ts.Minutes, "Could parse amount of minutes from DD.HH:MM:SS.sss time span.");
            Assert.AreEqual(3, ts.Seconds, "Could parse amount of seconds from DD.HH:MM:SS.sss time span.");
            Assert.AreEqual(999, ts.Milliseconds, "Could parse amount of milliseconds from DD.HH:MM:SS.sss time span.");
        }
    }
}