text:
"""A test library for handling date and time values.

_DateTime_ is a Robot Framework standard library that supports creating and
converting date and time values (e.g. `Get Current Date`, `Convert Time`),
as well as doing simple calculations with them (e.g. `Subtract Time From Date`,
`Add Time To Time`). It supports dates and times in various formats, and can
also be used by other libraries programmatically.

This library is new in Robot Framework 2.8.5.

= Table of Contents =

- `Terminology`
- `Date formats`
- `Time formats`
- `Millisecond handling`
- `Programmatic usage`
- `Shortcuts`
- `Keywords`

= Terminology =

In the context of this library, _date_ and _time_ generally have following
meanings:

- _date_: An entity with both date and time components but without any
   timezone information. For example, '2014-06-11 10:07:42'.
- _time_: A time interval. For example, '1 hour 20 minutes' or '01:20:00'.

This terminology differs from what Python's standard
[https://docs.python.org/2/library/datetime.html|datetime] module uses.
Basically its
[https://docs.python.org/2/library/datetime.html#datetime-objects|datetime] and
[https://docs.python.org/2/library/datetime.html#timedelta-objects|timedelta]
objects match _date_ and _time_ as defined by this library.

= Date formats =

Dates can given to and received from keywords in `timestamp`, `custom
timestamp`, `Python datetime` and `epoch time` formats. These formats are
discussed thoroughly in subsequent sections.

Input format is determined automatically based on the given date except when
using custom timestamps, in which case it needs to be given using
`date_format` argument. Default result format is timestamp, but it can
be overridden using `result_format` argument.

== Timestamp ==

If a date is given as a string, it is always considered to be a timestamp.
If no custom formatting is given using `date_format` argument, the timestamp
is expected to be in [http://en.wikipedia.org/wiki/ISO_8601|ISO 8601] like
format 'YYYY-MM-DD hh:mm:ss.mil', where any non-digit character can be used
as a separator or separators can be omitted altogether. Additionallly,
only the date part is mandatory, all possibly missing time components are
considered to be zeros.

Dates can also be returned in the same 'YYYY-MM-DD hh:mm:ss.mil' format by using
_timestamp_ value with `result_format` argument. This is also the default
format that keywords returning dates use. Milliseconds can be excluded using
`exclude_millis` as explained in `Millisecond handling` section.

Examples:
| ${date1} =      | Convert Date | 2014-06-11 10:07:42.000 |
| ${date2} =      | Convert Date | 20140611 100742         | result_format=timestamp |
| Should Be Equal | ${date1}     | ${date2}                |
| ${date} =       | Convert Date | 20140612 12:57          | exclude_millis=yes |
| Should Be Equal | ${date}      | 2014-06-12 12:57:00     |

== Custom timestamp ==

It is possible to use custom timestamps in both input and output.
The custom format is same as accepted by Python's
[https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior|
datatime.strptime() function]. For example, the default timestamp discussed
in the previous section would match '%Y-%m-%d %H:%M:%S.%f'.

When using a custom timestamp in input, it must be specified using `date_format`
argument. The actual input value must be a string that matches the specified
format exactly. When using a custom timestamp in output, it must be given
using `result_format` argument.

Examples:
| ${date} =       | Convert Date | 28.05.2014 12:05        | date_format=%d.%m.%Y %H:%M |
| Should Be Equal | ${date}      | 2014-05-28 12:05:00.000 |
| ${date} =       | Convert Date | ${date}                 | result_format=%d.%m.%Y |
| Should Be Equal | ${date}      | 28.05.2014              |

== Python datetime ==

Python's standard
[https://docs.python.org/2/library/datetime.html#datetime.datetime|datetime]
objects can be used both in input and output. In input they are recognized
automatically, and in output it is possible to get them by giving _datetime_
value to `result_format` argument.

One nice benefit with datetime objects is that they have different time
components available as attributes that can be easily accessed using the
extended variable syntax.

Examples:
| ${datetime} = | Convert Date | 2014-06-11 10:07:42.123 | datetime |
| Should Be Equal As Integers | ${datetime.year}        | 2014   |
| Should Be Equal As Integers | ${datetime.month}       | 6      |
| Should Be Equal As Integers | ${datetime.day}         | 11     |
| Should Be Equal As Integers | ${datetime.hour}        | 10     |
| Should Be Equal As Integers | ${datetime.minute}      | 7      |
| Should Be Equal As Integers | ${datetime.second}      | 42     |
| Should Be Equal As Integers | ${datetime.microsecond} | 123000 |

== Epoch time ==

Epoch time is the time in seconds since the
[http://en.wikipedia.org/wiki/Unix_time|UNIX epoch] i.e. 00:00:00.000 (UTC)
1 January 1970. To give a date in epoch time, it must be given as a number
(integer or float), not as a string. To return a date in epoch time,
it is possible to use _epoch_ value with `result_format` argument.
Epoch time is returned as a floating point number.

Notice that epoch time itself is independent on timezones and thus same
around the world at a certain time. What local time a certain epoch time
matches obviously then depends on the timezone. For example, examples below
were tested in Finland but verifications would fail on other timezones.

Examples:
| ${date} =       | Convert Date | ${1000000000}           |
| Should Be Equal | ${date}      | 2001-09-09 04:46:40.000 |
| ${date} =       | Convert Date | 2014-06-12 13:27:59.279 | epoch |
| Should Be Equal | ${date}      | ${1402568879.279}       |

= Time formats =

Similarly as dates, times can be given to and received from keywords in
various different formats. Supported formats are `number`, `time string`
(verbose and compact), `timer string` and `Python timedelta`.

Input format for time is always determined automatically based on the input.
Result format is number by default, but it can be customised using
`result_format` argument.

== Number ==

Time given as a number is interpreted to be seconds. It can be given
either as an integer or a float, or it can be a string that can be converted
to a number.

To return a time as a number, `result_format` argument must be _number_,
which is also the default. Returned number is always a float.

Examples:
| ${time} =       | Convert Time | 3.14    |
| Should Be Equal | ${time}      | ${3.14} |
| ${time} =       | Convert Time | ${time} | result_format=number |
| Should Be Equal | ${time}      | ${3.14} |

== Time string ==

Time strings are strings in format like '1 minutes 42 seconds' or '1min 42s'.
The basic idea of this format is having first a number and then a text
specifying what time that number represents. Numbers can be either
integers or floating point numbers, the whole format is case and space
insensitive, and it is possible to add a minus prefix to specify negative
times. The available time specifiers are:

- days, day, d
- hours, hour, h
- minutes, minute, mins, min, m
- seconds, second, secs, sec, s
- milliseconds, millisecond, millis, ms

When returning a time string, it is possible to select between _verbose_
and _compact_ representations using `result_format` argument. The verbose
format uses long specifiers 'day', 'hour', 'minute', 'second' and
'millisecond', and adds 's' at the end when needed. The compact format uses
shorter specifiers 'd', 'h', 'min', 's' and 'ms', and even drops a space
between the number and the specifier.

Examples:
| ${time} =       | Convert Time | 1 minute 42 seconds |
| Should Be Equal | ${time}      | ${102}              |
| ${time} =       | Convert Time | 4200                | verbose |
| Should Be Equal | ${time}      | 1 hour 10 minutes   |
| ${time} =       | Convert Time | - 1.5 hours         | compact |
| Should Be Equal | ${time}      | - 1h 30min          |

== Timer string ==

Timer string is a string given in timer like format 'hh:mm:ss.mil'. In this
format both hour and millisecond parts are optional, leading and trailing
zeros can be left out when they are not meaningful, and negative times can
be represented by adding a minus prefix.

To return a time as timer string, `result_format` argument must be given
value _timer_. Timer strings are by default returned in full _hh:mm:ss.mil_
format, but milliseconds can be excluded using `exclude_millis` as explained
in `Millisecond handling` section.

Examples:
| ${time} =       | Convert Time | 01:42        |
| Should Be Equal | ${time}      | ${102}       |
| ${time} =       | Convert Time | 01:10:00.123 |
| Should Be Equal | ${time}      | ${4200.123}  |
| ${time} =       | Convert Time | 102          | timer |
| Should Be Equal | ${time}      | 00:01:42.000 |
| ${time} =       | Convert Time | -101.567     | timer | exclude_millis=yes |
| Should Be Equal | ${time}      | -00:01:42    |

== Python timedelta ==

Python's standard
[https://docs.python.org/2/library/datetime.html#datetime.timedelta|timedelta]
objects are also supported both in input and in output. In input they are
recognized automatically, and in output it is possible to receive them by
giving _timedelta_ value to `result_format` argument.

Examples:
| ${timedelta} =  | Convert Time                 | 01:10:02.123 | timedelta |
| Should Be Equal | ${timedelta.total_seconds()} | ${4202.123}  |

= Millisecond handling =

This library handles dates and times internally using the precision of the
given input. With `timestamp`, `time string`, and `timer string` result
formats seconds are, however, rounded to millisecond accuracy. Milliseconds
may also be included even if there would be none.

All keywords returning dates or times have an option to leave milliseconds
out by giving any value considered true (e.g. any non-empty string) to
`exclude_millis` argument. When this option is used, seconds in returned
dates and times are rounded to the nearest full second. With `timestamp`
and `timer string` result formats, milliseconds will also be removed from
the returned string altogether.

Examples:
| ${date} =       | Convert Date | 2014-06-11 10:07:42     |
| Should Be Equal | ${date}      | 2014-06-11 10:07:42.000 |
| ${date} =       | Convert Date | 2014-06-11 10:07:42.500 | exclude_millis=yes |
| Should Be Equal | ${date}      | 2014-06-11 10:07:43     |
| ${dt} =         | Convert Date | 2014-06-11 10:07:42.500 | datetime | exclude_millis=yes |
| Should Be Equal | ${dt.second} | ${43}        |
| Should Be Equal | ${dt.microsecond} | ${0}    |
| ${time} =       | Convert Time | 102          | timer |
| Should Be Equal | ${time}      | 00:01:42.000 |       |
| ${time} =       | Convert Time | 102.567      | timer | exclude_millis=true |
| Should Be Equal | ${time}      | 00:01:43     |       |

= Programmatic usage =

In addition to be used as normal library, this library is intended to
provide a stable API for other libraries to use if they want to support
same date and time formats as this library. All the provided keywords
are available as functions that can be easily imported:

| from robot.libraries.DateTime import convert_time
|
| def example_keyword(timeout):
|     seconds = convert_time(timeout)
|     # ...

Additionally helper classes _Date_ and _Time_ can be used directly:

| from robot.libraries.DateTime import Date, Time
|
| def example_keyword(date, interval):
|     date = Date(date).convert('datetime')
|     interval = Time(interval).convert('number')
|     # ...
"""

from datetime import datetime, timedelta
import time
import sys
import re

from robot.version import get_version
from robot.utils import elapsed_time_to_string, secs_to_timestr, timestr_to_secs

__version__ = get_version()
__all__ = ['convert_time', 'convert_date', 'subtract_date_from_date',
           'subtract_time_from_date', 'subtract_time_from_time',
           'add_time_to_time', 'add_time_to_date', 'get_current_date']

def get_current_date(time_zone='local', increment=0,
                     result_format='timestamp', exclude_millis=False):
    """Returns current local or UTC time with an optional increment.

    Arguments:
    - _time_zone:_      Get the current time on this time zone. Currently only
                        'local' (default) and 'UTC' are supported.
    - _increment:_      Optional time increment to add to the returned date in
                        one of the supported `time formats`. Can be negative.
    - _result_format:_  Format of the returned date (see `date formats`).
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.

    Examples:
    | ${date} =       | Get Current Date |
    | Should Be Equal | ${date}          | 2014-06-12 20:00:58.946 |
    | ${date} =       | Get Current Date | UTC                     |
    | Should Be Equal | ${date}          | 2014-06-12 17:00:58.946 |
    | ${date} =       | Get Current Date | increment=02:30:00      |
    | Should Be Equal | ${date}          | 2014-06-12 22:30:58.946 |
    | ${date} =       | Get Current Date | UTC                     | - 5 hours |
    | Should Be Equal | ${date}          | 2014-06-12 12:00:58.946 |
    | ${date} =       | Get Current Date | result_format=datetime  |
    | Should Be Equal | ${date.year}     | ${2014}                 |
    | Should Be Equal | ${date.month}    | ${6}                    |
    """
    if time_zone.upper() == 'LOCAL':
        dt = datetime.now()
    elif time_zone.upper() == 'UTC':
        dt = datetime.utcnow()
    else:
        raise ValueError("Unsupported timezone '%s'." % time_zone)
    date = Date(dt) + Time(increment)
    return date.convert(result_format, millis=not exclude_millis)

def convert_date(date, result_format='timestamp', exclude_millis=False,
                 date_format=None):
    """Converts between supported `date formats`.

    Arguments:
    - _date:_           Date in one of the supported `date formats`.
    - _result_format:_  Format of the returned date.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.
    - _date_format:_    Specifies possible `custom timestamp` format.

    Examples:
    | ${date} =       | Convert Date | 20140528 12:05:03.111   |
    | Should Be Equal | ${date}      | 2014-05-28 12:05:03.111 |
    | ${date} =       | Convert Date | ${date}                 | epoch |
    | Should Be Equal | ${date}      | ${1401267903.111}       |
    | ${date} =       | Convert Date | 5.28.2014 12:05         | exclude_millis=yes | date_format=%m.%d.%Y %H:%M |
    | Should Be Equal | ${date}      | 2014-05-28 12:05:00     |
    """
    return Date(date, date_format).convert(result_format,
                                           millis=not exclude_millis)

def convert_time(time, result_format='number', exclude_millis=False):
    """Converts between supported `time formats`.

    Arguments:
    - _time:_           Time in one of the supported `time formats`.
    - _result_format:_  Format of the returned time.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.

    Examples:
    | ${time} =       | Convert Time  | 10 seconds        |
    | Should Be Equal | ${time}       | ${10}             |
    | ${time} =       | Convert Time  | 1:00:01           | verbose |
    | Should Be Equal | ${time}       | 1 hour 1 second   |
    | ${time} =       | Convert Time  | ${3661.5} | timer | exclude_milles=yes |
    | Should Be Equal | ${time}       | 01:01:02          |
    """
    return Time(time).convert(result_format, millis=not exclude_millis)

def subtract_date_from_date(date1, date2, result_format='number',
                            exclude_millis=False, date1_format=None,
                            date2_format=None):
    """Subtracts date from another date and returns time between.

    Arguments:
    - _date1:_          Date to subtract another date from in one of the
                        supported `date formats`.
    - _date2:_          Date that is subtracted in one of the supported
                        `date formats`.
    - _result_format:_  Format of the returned time (see `time formats`).
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.
    - _date1_format:_   Specifies possible `custom timestamp` format of _date1_.
    - _date2_format:_   Specifies possible `custom timestamp` format of _date2_.

     Examples:
    | ${time} =       | Subtract Date From Date | 2014-05-28 12:05:52     | 2014-05-28 12:05:10 |
    | Should Be Equal | ${time}                 | ${42}                   |
    | ${time} =       | Subtract Date From Date | 2014-05-28 12:05:52     | 2014-05-27 12:05:10 | verbose |
    | Should Be Equal | ${time}                 | 1 day 42 seconds        |
    """
    time = Date(date1, date1_format) - Date(date2, date2_format)
    return time.convert(result_format, millis=not exclude_millis)

def add_time_to_date(date, time, result_format='timestamp',
                     exclude_millis=False, date_format=None):
    """Adds time to date and returns the resulting date.

    Arguments:
    - _date:_           Date to add time to in one of the supported
                        `date formats`.
    - _time:_           Time that is added in one of the supported
                        `time formats`.
    - _result_format:_  Format of the returned date.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.
    - _date_format:_    Specifies possible `custom timestamp` format of _date_.

    Examples:
    | ${date} =       | Add Time To Date | 2014-05-28 12:05:03.111 | 7 days       |
    | Should Be Equal | ${date}          | 2014-06-04 12:05:03.111 |              |
    | ${date} =       | Add Time To Date | 2014-05-28 12:05:03.111 | 01:02:03:004 |
    | Should Be Equal | ${date}          | 2014-05-28 13:07:06.115 |
    """
    date = Date(date, date_format) + Time(time)
    return date.convert(result_format, millis=not exclude_millis)

def subtract_time_from_date(date, time, result_format='timestamp',
                       exclude_millis=False, date_format=None):
    """Subtracts time from date and returns the resulting date.

    Arguments:
    - _date:_           Date to subtract time from in one of the supported
                        `date formats`.
    - _time:_           Time that is subtracted in one of the supported
                        `time formats`.
    - _result_format:_  Format of the returned date.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.
    - _date_format:_    Specifies possible `custom timestamp` format of _date_.

    Examples:
    | ${date} =       | Subtract Time From Date | 2014-06-04 12:05:03.111 | 7 days |
    | Should Be Equal | ${date}                 | 2014-05-28 12:05:03.111 |
    | ${date} =       | Subtract Time From Date | 2014-05-28 13:07:06.115 | 01:02:03:004 |
    | Should Be Equal | ${date}                 | 2014-05-28 12:05:03.111 |
    """
    date = Date(date, date_format) - Time(time)
    return date.convert(result_format, millis=not exclude_millis)

def add_time_to_time(time1, time2, result_format='number',
                     exclude_millis=False):
    """Adds time to another time and returns the resulting time.

    Arguments:
    - _time1:_          First time in one of the supported `time formats`.
    - _time2:_          Second time in one of the supported `time formats`.
    - _result_format:_  Format of the returned time.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.

    Examples:
    | ${time} =       | Add Time To Time | 1 minute          | 42       |
    | Should Be Equal | ${time}          | ${102}            |
    | ${time} =       | Add Time To Time | 3 hours 5 minutes | 01:02:03 | timer | exclude_millis=yes |
    | Should Be Equal | ${time}          | 04:07:03          |
    """
    time = Time(time1) + Time(time2)
    return time.convert(result_format, millis=not exclude_millis)

def subtract_time_from_time(time1, time2, result_format='number',
                       exclude_millis=False):
    """Subtracts time from another time and returns the resulting time.

    Arguments:
    - _time1:_          Time to subtract another time from in one of
                        the supported `time formats`.
    - _time2:_          Time to subtract in one of the supported `time formats`.
    - _result_format:_  Format of the returned time.
    - _exclude_millis:_ When set to any true value, rounds and drops
                        milliseconds as explained in `millisecond handling`.

    Examples:
    | ${time} =       | Subtract Time From Time | 00:02:30 | 100      |
    | Should Be Equal | ${time}                 | ${50}    |
    | ${time} =       | Subtract Time From Time | ${time}  | 1 minute | compact |
    | Should Be Equal | ${time}                 | - 10s    |
    """
    time = Time(time1) - Time(time2)
    return time.convert(result_format, millis=not exclude_millis)

class Date(object):

    def __init__(self, date, input_format=None):
        self.seconds = self._convert_date_to_seconds(date, input_format)

    def _convert_date_to_seconds(self, date, input_format):
        if isinstance(date, basestring):
            return self._string_to_epoch(date, input_format)
        elif isinstance(date, datetime):
            return self._mktime_with_millis(date)
        elif isinstance(date, (int, long, float)):
            return float(date)
        raise ValueError("Unsupported input '%s'." % date)

    def _string_to_epoch(self, ts, input_format):
        if not input_format:
            ts = self._normalize_timestamp(ts)
            input_format = '%Y-%m-%d %H:%M:%S.%f'
        if self._need_to_handle_f_directive(input_format):
            return self._handle_un_supported_f_directive(ts, input_format)
        return self._mktime_with_millis(datetime.strptime(ts, input_format))

    def _need_to_handle_f_directive(self, format):
        if '%f' not in format:
            return False
        if sys.version_info < (2, 6):
            return True
        # https://ironpython.codeplex.com/workitem/34706
        # http://bugs.jython.org/issue2166
        return sys.platform == 'cli' or sys.platform.startswith('java')

    def _normalize_timestamp(self, date):
        ts = ''.join(d for d in date if d.isdigit())
        if len(ts) < 8:
            raise ValueError("Invalid timestamp '%s'." % date)
        ts = ts.ljust(20, '0')
        return '%s-%s-%s %s:%s:%s.%s' % (ts[:4], ts[4:6], ts[6:8], ts[8:10],
                                         ts[10:12], ts[12:14], ts[14:])

    def _handle_un_supported_f_directive(self, ts, input_format):
        input_format = self._remove_f_from_format(input_format)
        micro = re.search('\d+$', ts).group(0)
        ts = ts[:-len(micro)]
        epoch = time.mktime(time.strptime(ts, input_format))
        epoch += float(micro) / 10**len(micro)
        return epoch

    def _remove_f_from_format(self, format):
        if not format.endswith('%f'):
            raise ValueError('%f directive is supported only at the end of '
                             'the format string on this Python interpreter.')
        return format[:-2]

    def _mktime_with_millis(self, dt):
        return time.mktime(dt.timetuple()) + dt.microsecond / 10.0**6

    def convert(self, format, millis=True):
        seconds = self.seconds if millis else round(self.seconds)
        if '%' in format:
            return self._convert_to_custom_timestamp(seconds, format)
        try:
            result_converter = getattr(self, '_convert_to_%s' % format.lower())
        except AttributeError:
            raise ValueError("Unknown format '%s'." % format)
        return result_converter(seconds, millis)

    def _convert_to_custom_timestamp(self, seconds, format):
        format = str(format)  # Needed by Python 2.5
        dt = self._datetime_from_seconds(seconds)
        if not self._need_to_handle_f_directive(format):
            return dt.strftime(format)
        format = self._remove_f_from_format(format)
        micro = round(seconds % 1 * 10**6)
        return '%s%06d' % (dt.strftime(format), micro)

    def _convert_to_timestamp(self, seconds, millis=True):
        milliseconds = int(round(seconds % 1 * 1000))
        if milliseconds == 1000:
            seconds = round(seconds)
            milliseconds = 0
        dt = self._datetime_from_seconds(seconds)
        ts = dt.strftime('%Y-%m-%d %H:%M:%S')
        if millis:
            ts += '.%03d' % milliseconds
        return ts

    def _datetime_from_seconds(self, ts):
        # Jython and IronPython handle floats incorrectly. For example:
        # datetime.fromtimestamp(1399410716.123).microsecond == 122999
        dt = datetime.fromtimestamp(ts)
        return dt.replace(microsecond=int(round(ts % 1 * 10**6)))

    def _convert_to_epoch(self, seconds, millis=True):
        return seconds

    def _convert_to_datetime(self, seconds, millis=True):
        return self._datetime_from_seconds(seconds)

    def __add__(self, other):
        if isinstance(other, Time):
            return Date(self.seconds + other.seconds)
        raise TypeError('Can only add Time to Date, not %s.'
                        % type(other).__name__)

    def __sub__(self, other):
        if isinstance(other, Date):
            return Time(self.seconds - other.seconds)
        if isinstance(other, Time):
            return Date(self.seconds - other.seconds)
        raise TypeError('Can only subtract Date or Time from Date, not %s.'
                        % type(other).__name__)

class Time(object):

    def __init__(self, time):
        self.seconds = self._convert_time_to_seconds(time)

    def _convert_time_to_seconds(self, time):
        if isinstance(time, timedelta):
            # timedelta.total_seconds() is new in Python 2.7
            return (time.days * 24 * 60 * 60 + time.seconds +
                    time.microseconds / 1000000.0)
        return timestr_to_secs(time, round_to=None)

    def convert(self, format, millis=True):
        try:
            result_converter = getattr(self, '_convert_to_%s' % format.lower())
        except AttributeError:
            raise ValueError("Unknown format '%s'." % format)
        seconds = self.seconds if millis else round(self.seconds)
        return result_converter(seconds, millis)

    def _convert_to_number(self, seconds, millis=True):
        return seconds

    def _convert_to_verbose(self, seconds, millis=True):
        return secs_to_timestr(seconds)

    def _convert_to_compact(self, seconds, millis=True):
        return secs_to_timestr(seconds, compact=True)

    def _convert_to_timer(self, seconds, millis=True):
        return elapsed_time_to_string(seconds * 1000, include_millis=millis)

    def _convert_to_timedelta(self, seconds, millis=True):
        return timedelta(seconds=seconds)

    def __add__(self, other):
        if isinstance(other, Time):
            return Time(self.seconds + other.seconds)
        raise TypeError('Can only add Time to Time, not %s.'
                        % type(other).__name__)

    def __sub__(self, other):
        if isinstance(other, Time):
            return Time(self.seconds - other.seconds)
        raise TypeError('Can only subtract Time from Time, not %s.'
                        % type(other).__name__)


text:
package io.github.biezhi.wechat.api.enums;

import lombok.Getter;

/**
 * API URL
 *
 * @author biezhi
 * @date 2018/1/21
 */
@Getter
public enum ApiURL {

    IMAGE("%s/webwxgetmsgimg?msgid=%s&skey=%s", ".jpg", "images"),
    HEAD_IMG("%s/webwxgetheadimg?username=%s&skey=%s", ".jpg", "headimg"),
    ICON("%s/webwxgeticon?username=%s&skey=%s", ".jpg", "icons"),
    VOICE("%s/webwxgetvoice?msgid=%s&skey=%s", ".mp3", "voice"),
    VIDEO("%s/webwxgetvideo?msgid=%s&skey=%s", ".mp4", "video");

    private String url;
    private String suffix;
    private String dir;

    ApiURL(String url) {
        this.url = url;
    }

    ApiURL(String url, String suffix, String dir) {
        this.url = url;
        this.suffix = suffix;
        this.dir = dir;
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
    public class RudeEditDiagnosticTests
    {
        [Fact]
        public void ToDiagnostic()
        {
            var tree = SyntaxFactory.ParseCompilationUnit("class C { }").SyntaxTree;
            var syntaxNode = tree.GetRoot();

            // most rude edits have a single argument, list those that have different count:

            var arg0 = new HashSet<RudeEditKind>()
            {
                RudeEditKind.ActiveStatementUpdate,
                RudeEditKind.PartiallyExecutedActiveStatementUpdate,
                RudeEditKind.UpdateExceptionHandlerOfActiveTry,
                RudeEditKind.UpdateTryOrCatchWithActiveFinally,
                RudeEditKind.UpdateCatchHandlerAroundActiveStatement,
                RudeEditKind.FieldKindUpdate,
                RudeEditKind.TypeKindUpdate,
                RudeEditKind.AccessorKindUpdate,
                RudeEditKind.DeclareLibraryUpdate,
                RudeEditKind.DeclareAliasUpdate,
                RudeEditKind.InsertDllImport,
                RudeEditKind.GenericMethodUpdate,
                RudeEditKind.GenericTypeUpdate,
                RudeEditKind.ExperimentalFeaturesEnabled,
                RudeEditKind.AwaitStatementUpdate,
                RudeEditKind.InsertFile,
                RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas,
                RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement,
                RudeEditKind.SwitchBetweenLambdaAndLocalFunction,
                RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier,
                RudeEditKind.NotSupportedByRuntime,
                RudeEditKind.MakeMethodAsyncNotSupportedByRuntime,
                RudeEditKind.MakeMethodIteratorNotSupportedByRuntime,
                RudeEditKind.ChangeImplicitMainReturnType
            };

            var arg2 = new HashSet<RudeEditKind>()
            {
                RudeEditKind.InsertIntoStruct,
                RudeEditKind.InsertIntoStruct,
                RudeEditKind.ChangingCapturedVariableType,
                RudeEditKind.AccessingCapturedVariableInLambda,
                RudeEditKind.NotAccessingCapturedVariableInLambda,
                RudeEditKind.RenamingCapturedVariable,
                RudeEditKind.ChangingStateMachineShape,
                RudeEditKind.InternalError,
                RudeEditKind.MemberBodyInternalError,
                RudeEditKind.ChangingNonCustomAttribute,
            };

            var arg3 = new HashSet<RudeEditKind>()
            {
                RudeEditKind.InsertLambdaWithMultiScopeCapture,
                RudeEditKind.DeleteLambdaWithMultiScopeCapture,
                RudeEditKind.ChangingNamespace,
            };

            var allKinds = Enum.GetValues(typeof(RudeEditKind)).Cast<RudeEditKind>();

            foreach (var kind in allKinds)
            {
                if (kind == RudeEditKind.None)
                {
                    continue;
                }

                if (arg0.Contains(kind))
                {
                    var re = new RudeEditDiagnostic(kind, TextSpan.FromBounds(1, 2));
                    var d = re.ToDiagnostic(tree);
                    Assert.False(d.GetMessage().Contains("{"), kind.ToString());
                }
                else if (arg2.Contains(kind))
                {
                    var re = new RudeEditDiagnostic(kind, TextSpan.FromBounds(1, 2), syntaxNode, new[] { "<1>", "<2>" });
                    var d = re.ToDiagnostic(tree);
                    Assert.True(d.GetMessage().Contains("<1>"), kind.ToString());
                    Assert.True(d.GetMessage().Contains("<2>"), kind.ToString());
                    Assert.False(d.GetMessage().Contains("{"), kind.ToString());
                }
                else if (arg3.Contains(kind))
                {
                    var re = new RudeEditDiagnostic(kind, TextSpan.FromBounds(1, 2), syntaxNode, new[] { "<1>", "<2>", "<3>" });
                    var d = re.ToDiagnostic(tree);
                    Assert.True(d.GetMessage().Contains("<1>"), kind.ToString());
                    Assert.True(d.GetMessage().Contains("<2>"), kind.ToString());
                    Assert.True(d.GetMessage().Contains("<3>"), kind.ToString());
                    Assert.False(d.GetMessage().Contains("{"), kind.ToString());
                }
                else
                {
                    var re = new RudeEditDiagnostic(kind, TextSpan.FromBounds(1, 2), syntaxNode, new[] { "<1>" });
                    var d = re.ToDiagnostic(tree);
                    Assert.True(d.GetMessage().Contains("<1>"), kind.ToString());
                    Assert.False(d.GetMessage().Contains("{"), kind.ToString());
                }
            }

            // check that all values are unique:
            AssertEx.Equal(allKinds, allKinds.Distinct());
        }
    }
}


text:
var io=require('socket.io');
var Hop=require('./event');

var redis = require("redis");
var  client = redis.createClient();
var  eventClient = redis.createClient();

Hop.Event.Bus.emit=function(message,onComplete){
  client.publish("Hop.EVENT",JSON.stringify(message),onComplete);
}

eventClient.on("ready",function(){
  eventClient.subscribe("Hop.EVENT",function(){
    eventClient.on("message",function(channel,message){
      if(channel=="Hop.EVENT"){
        message = JSON.parse(message.toString());
        Hop.Event.Bus.localEmit(message,function(){});
      }
    });
  });
});


text:
bx.bitset_tests module
======================

.. automodule:: bx.bitset_tests
    :members:
    :undoc-members:
    :show-inheritance:


text:
#ifndef _ASM_ERRNO_H
#define _ASM_ERRNO_H

#include <uapi/asm/errno.h>

/* The biggest error number defined here or in <linux/errno.h>. */
#define EMAXERRNO	1133

#endif /* _ASM_ERRNO_H */


text:
var topojson       = require('topojson');
var colorbrewer    = require('../lib/colors/colorbrewer');
var legendTemplate = require('../templates/legend.jade');
var stateface      = require('../lib/stateface');

var RACES          = ['white', 'asian', 'multiracial', 'native', 'hispanic', 'black', 'islander'];
var COLORSCHEME    = colorbrewer.Greys[6];

// Some semblance of a geography-based ordering of FIPS codes
var NATURAL_STATE_ORDERING = [2, 30, 38, 27, 55, 26, 39, 36, 50, 23, 53, 16, 46, 31, 19, 17, 42, 34, 25, 33, 41, 32, 56, 20, 29, 18, 54, 10, 44, 9, 6, 49, 8, 40, 5, 21, 51, 24, 11, 37, 15, 4, 35, 48, 22, 47, 28, 1, 13, 45, 12];

/**
 * @param {Object} options Hash should contain a selector that picks out an
 *     element that the map should be rendered into.
 */
var PrisonPops = function(options) {
  if (!options || !options.el) {
    throw new Error('Must pass a selector when initializing a PrisonPops.');
  }
  this.el = d3.select(options.el);

  if (!options.url) {
    throw new Error('Must pass a url when initializing a PrisonPops');
  }
  d3.json(options.url, _.bind(this.handleFetch, this));

  d3.select(window).on('resize', _.bind(this.handleResize, this));
  this.handleResize();

  this.colorscale = d3.scale.category20();
    // .domain(RACES)
    // .range(COLORSCHEME);

  this.active = d3.select(null);
};

/**
 * Updates the size and path to reflect the new size. If the data is loaded, re-
 * renders the data.
 */
PrisonPops.prototype.handleResize = function() {
  var boundingRect = this.el.node().getBoundingClientRect();
  this.width       = boundingRect.width;
  this.height      = boundingRect.height;
  this.radius      = Math.min(this.width / 20, this.height / 10);
  this.arc         = d3.svg.arc()
    .outerRadius(this.radius * 0.78)
    .innerRadius(0);

  this.tileWidth  = (this.width - 2*this.radius) / 10  ;
  this.tileHeight = this.height / 6;

  // If we've loaded the data, then re-render the data.
  if (this.data) {
    this.renderData();
  }
};

/**
 * Handles the response the data fetch.
 *
 * @param  {Object} err
 * @param  {Object} data
 */
PrisonPops.prototype.handleFetch = function(err, data) {
  // If something bad happened abort and hide the widget.
  if (err) {
    console.log(err);
    this.el.style.display = 'none';
    return;
  }

  this.data = data;
  this.renderData();
};

/**
 * Renders the data. TODO: seperate out the rendering of everything non-data
 * dependent.
 */
PrisonPops.prototype.renderData = function() {
  var self = this;

  // Kill the loading text, or whatever was previously in the element we were
  // passed.
  this.el.html("");

  // Add the containing svg.
  this.svg = this.el.append("svg")
    .attr("width", this.width)
    .attr("height", this.height)
    .attr("class", "prisonpops-us")
    .append("g");
      // .attr("transform", "translate(" + [this.width / 2, this.height / 2] + ")" );

  var data = this.formatData(this.data);

  this.pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.population; });

  // Store the computed layout to avoid recomputing on rotation.
  _.each(data, function(value) {
    value.pie = self.pie(value.data);
  });

  var multiples = this.svg.selectAll('.small-multiple')
    .data(data)
    .enter().append('g')
    .attr('width', this.tileWidth)
    .attr('height', this.tileHeight)
    .classed('small-multiple', true)
    .attr('transform', function(d, i) {
      return 'translate(' + self.getGroupTranslation(d, i) + ')';
    });

  var rotators = multiples
    .append('g')
    .classed('rotational-frame', true);

  rotators.selectAll('.arc')
    .data(function(d) { return d.pie; })
    .enter().append('g')
    .classed('arc', true)
    .append('path')
      .attr('d', this.arc)
      .attr('class', function(d) { return 'wedge ' + d.data.type; })
      .style("fill", function(d) { return self.colorscale(d.data.type); })
      .attr('stroke', '#fff')
      .on('mouseover', function(d, i) {
        d3.selectAll('.' + d.data.type)
          .transition()
          .duration(300)
          .attr('transform', 'scale(1.2)');
      })
      .on('mouseout', function(d, i) {
        d3.selectAll('.' + d.data.type)
          .transition()
          .duration(300)
          .attr('transform', '');
      })
      .on('click', function(d, i, j) {
        var selectedType = d.data.type;
        d3.selectAll('.rotational-frame')
          .transition()
          .duration(500)
          .attr('transform', function(d, i) {
            var selectedArc = _.find(d.pie, function(arc) {
              return arc.data.type == selectedType;
            });

            var currentRotation   = d.currentRotation || 0; // Radians
            var currentStartAngle = currentRotation + selectedArc.startAngle;
            d.currentRotation     = currentRotation - currentStartAngle;
            var rotationDegrees   = 360 * d.currentRotation / (Math.PI * 2);

            return 'rotate(' + rotationDegrees + ')';
          })
      });

  multiples.append('text')
      // .attr('transform', 'translate(' + [this.tileWidth / 2, this.tileHeight] + ')')
      .attr("dy", ".35em")
      .classed("state-icon", true)
      .text(function(d) { return stateface(d.name); });

  multiples.append('text')
    .classed('multiple-label', true)
    .text(function(d) { return d.name; })
    .attr('transform', 'translate(' + [0, this.tileHeight / 2] + ')');

  this.renderLegend();
};

PrisonPops.prototype.getGroupTranslation = function(data, index) {
  var index = NATURAL_STATE_ORDERING.indexOf(data.geoid);
  if (index == -1) {
    console.log(data, 'not found in ordering!');
  }

  var row    = Math.floor(index / 10);
  var column = Math.floor(index % 10);
  if (index === 50) {
    row = 4;
    column = 10;
  }
  var hpadding = this.radius;
  var vpadding = 60 + this.radius;

  return [hpadding + column * this.tileWidth, vpadding + row * this.tileHeight];
};

/**
 * Constructs the legend and appends it.
 */
PrisonPops.prototype.renderLegend = function() {
  var segments = _.map(RACES, function(type) {
    return {
      color: this.colorscale(type),
      label: type
    }
  }, this);

  this.el.append("div").html(legendTemplate({ segments: segments }));
};

PrisonPops.prototype.handleLegendClick = function(target, d) {

};

PrisonPops.prototype.formatData = function(data) {
  return _.map(data, function(state) {
    return {
      geoid: state.geoid,
      name: state.name,
      data: _.map(RACES, function(race) {
        return {
          type: race,
          population: state[race + '-all-prisons']
        };
      }),
    };
  });
};

module.exports = PrisonPops;


text:
# broccoli-babel-transpiler

[![Build Status](https://travis-ci.org/babel/broccoli-babel-transpiler.svg?branch=master)](https://travis-ci.org/babel/broccoli-babel-transpiler)
[![Build status](https://ci.appveyor.com/api/projects/status/a0nbd84m1x4y5fp5?svg=true)](https://ci.appveyor.com/project/embercli/broccoli-babel-transpiler)

A [Broccoli](https://github.com/broccolijs/broccoli) plugin which transpiles ES6 to readable ES5 (and much more) by using [Babel](https://github.com/babel/babel).

## How to install?

```sh
$ npm install broccoli-babel-transpiler --save-dev
```

## How to use?

In your `Brocfile.js`:

```js
const esTranspiler = require('broccoli-babel-transpiler');
const scriptTree = esTranspiler(inputTree, babelOptions);
```

Note that, since Babel 6 (and v6 of this plugin), you need to be specific as to
what your transpilation target is. Running `esTranspiler` with empty options
will not transpile anything. You will need:

  * Explicit options, such as `presets`. See available [options](https://babeljs.io/docs/usage/options) at Babel's GitHub repo.
  * Babel plugins that implement the transforms you require.

For a quick running example, install this plugin:

```sh
$ npm install babel-preset-env
```

And then run the transform like this:

```js
let scriptTree = babel(inputTree, {
  presets: [
    ['env', {
      'targets': {
        'browsers': ['last 2 versions']
      }
    }]
  ]
});
```

### Examples

You'll find three example projects using this plugin in the repository
[broccoli-babel-examples](https://github.com/givanse/broccoli-babel-examples).
Each one of them builds on top of the previous example so you can progess from
bare minimum to ambitious development.

 * [es6-fruits](https://github.com/givanse/broccoli-babel-examples/tree/master/es6-fruits) - Execute a single ES6 script.
 * [es6-website](https://github.com/givanse/broccoli-babel-examples/tree/master/es6-website) - Build a simple website.
 * [es6-modules](https://github.com/givanse/broccoli-babel-examples/tree/master/es6-modules) - Handle modules and unit tests.

## About source map

Currently this plugin only supports inline source map. If you need
separate source map feature, you're welcome to submit a pull request.

## Advanced usage

`filterExtensions` is an option to limit (or expand) the set of file extensions
that will be transformed.

The default `filterExtension` is `js`

```js
const esTranspiler = require('broccoli-babel-transpiler');
let scriptTree = esTranspiler(inputTree, {
    filterExtensions:['js', 'es6'] // babelize both .js and .es6 files
});
```

`targetExtension` is an option to specify the extension of the output files

The default `targetExtension` is `js`

```js
const esTranspiler = require('broccoli-babel-transpiler');
let scriptTree = esTranspiler(inputTree, {
    targetExtension: 'module.js' // create output files with module.js extension
});
```

## Polyfill

In order to use some of the ES6 features you must include the Babel
[polyfill](http://babeljs.io/docs/usage/polyfill/#usage-in-browser).

You don't always need this, review which features need the polyfill here: [ES6
Features](https://babeljs.io/docs/learn-es6).

```js
const esTranspiler = require('broccoli-babel-transpiler');
let scriptTree = esTranspiler(inputTree, { browserPolyfill: true });
```

## Plugins

Use of custom plugins works similarly to `babel` itself. You would pass a
`plugins` array in `options`:

```js
const esTranspiler = require('broccoli-babel-transpiler');
const applyFeatureFlags = require('babel-plugin-feature-flags');

let featureFlagPlugin = applyFeatureFlags({
  import: { module: 'ember-metal/features' },
  features: {
    'ember-metal-blah': true
  }
});

let scriptTree = esTranspiler(inputTree, {
  plugins: [
    featureFlagPlugin
  ]
});
```

### Caching

broccoli-babel-transpiler uses a persistent cache to enable rebuilds to be
significantly faster (by avoiding transpilation for files that have not
changed). However, since a plugin can do many things to affect the transpiled
output it must also influence the cache key to ensure transpiled files are
rebuilt
if the plugin changes (or the plugins configuration).

In order to aid plugin developers in this process, broccoli-babel-transpiler
will invoke two methods on a plugin so that it can augment the cache key:

* `cacheKey` - This method is used to describe any runtime information that may
  want to invalidate the cached result of each file transpilation. This is
  generally only needed when the configuration provided to the plugin is used
  to modify the AST output by a plugin like `babel-plugin-filter-imports`
  (module
  exports to strip from a build), `babel-plugin-feature-flags` (configured
  features and current status to strip or embed in a final build), or
  `babel-plugin-htmlbars-inline-precompile` (uses `ember-template-compiler.js`
  to compile inlined templates).
* `baseDir` - This method is expected to return the plugins base dir. The
  provided `baseDir` is used to ensure the cache is invalidated if any of the
  plugin's files change (including its deps). Each plugin should implement
  `baseDir` as: `Plugin.prototype.baseDir = function() { return \_\_dirname;
  };`.

## Parallel Transpilation

broccoli-babel-transpiler can run multiple babel transpiles in parallel using a
pool of workers, to take advantage of multi-core systems. Because these workers
are separate processes, the plugins and callback functions that are normally
passed as options to babel must be specified in a serializable form.
To enable this parallelization there is an API to tell the worker how to
construct the plugin or callback in its process.

To ensure a build remains parallel safe, one can set the
`throwUnlessParallelizable` option to true (defaults to false). This will cause
an error to be thrown, if parallelization is not possible due to an
incompatible babel plugin.

```js
new Babel(input, { throwUnlessParallelizable: true | false });
```

Plugins are specified as an object with a `_parallelBabel` property:

```js
let plugin = {
  _parallelBabel: {
    requireFile: '/full/path/to/the/file',
    useMethod: 'methodName',
    buildUsing: 'buildFunction',
    params: { ok: 'this object will be passed to buildFunction()' }
  }
};
```

Callbacks can be specified like plugins, or as functions with a
`_parallelBabel` property:

```js
function callback() { /* do something */ };

callback._parallelBabel = {
  requireFile: '/full/path/to/the/file',
  useMethod: 'methodName',
  buildUsing: 'buildFunction',
  params: { ok: 'this object will be passed to buildFunction()' }
};
```

### requireFile (required)

This property specifies the file to require in the worker process to create the
plugin or callback. This must be given as an absolute path.

```js
const esTranspiler = require('broccoli-babel-transpiler');

let somePlugin = {
  _parallelBabel: {
    requireFile: '/full/path/to/the/file'
  }
});

let scriptTree = esTranspiler(inputTree, {
  plugins: [
    'transform-strict-mode', // plugins that are given as strings will automatically be parallelized
    somePlugin
  ]
});
```

### useMethod (optional)

This property specifies the method to use from the file that is required.

If you have a plugin defined like this:

```js
// some_plugin.js

module.exports = {
  pluginFunction(babel) {
    // do plugin things
  }
};
```

You can tell broccoli-babel-transpiler to use that function in the worker
processes like so:

```js
const esTranspiler = require('broccoli-babel-transpiler');

let somePlugin = {
  _parallelBabel: {
    requireFile: '/path/to/some_plugin',
    useMethod: 'pluginFunction'
  }
});

let scriptTree = esTranspiler(inputTree, {
  plugins: [ somePlugin ]
});
```

### buildUsing and params (optional)

These properties specify a function to run to build the plugin (or callback),
and any parameters to pass to that function.

If the plugin needs to be built dynamically, you can do that like so:

```js
// some_plugin.js

module.exports = {
  buildPlugin(params) {
    return doSomethingWith(params.text);
  }
};
```

This will tell the worker process to require the plugin and call the
`buildPlugin` function with the `params` object as an argument:

```js
const esTranspiler = require('broccoli-babel-transpiler');

let somePlugin = {
  _parallelBabel: {
    requireFile: '/path/to/some_plugin',
    buildUsing: 'buildPlugin',
    params: { text: 'some text' }
  }
});

let scriptTree = esTranspiler(inputTree, {
  plugins: [ somePlugin ]
});
```

Note: If both `useMethod` and `buildUsing` are specified, `useMethod` takes
precedence.

### Number of jobs

The number of parallel jobs defaults to the number of detected CPUs - 1.

This can be changed with the `JOBS` environment variable:

```sh
JOBS=4 ember build
```

To disable parallelization:

```sh
JOBS=1 ember build
```


text:
	#include "c_hl2mp_player.h"
#else
	#include "eventqueue.h"
	#include "player.h"
	#include "gamerules.h"
	#include "game.h"
	#include "items.h"
	#include "entitylist.h"
	#include "mapentities.h"
	#include "in_buttons.h"
	#include <ctype.h>
	#include "voice_gamemgr.h"
	#include "iscorer.h"
	#include "hl2mp_player.h"
	#include "weapon_hl2mpbasehlmpcombatweapon.h"
	#include "team.h"
	#include "voice_gamemgr.h"
	#include "hl2mp_gameinterface.h"
	#include "hl2mp_cvars.h"
	#include "haj_cvars.h"
	#include "haj_capturepointmanager.h"
	#include "haj_team.h"
#ifdef DEBUG
	#include "hl2mp_bot_temp.h"
#endif

extern void respawn(CBaseEntity *pEdict, bool fCopyCorpse);

ConVar sv_hl2mp_weapon_respawn_time( "sv_hl2mp_weapon_respawn_time", "20", FCVAR_GAMEDLL | FCVAR_NOTIFY );
ConVar sv_hl2mp_item_respawn_time( "sv_hl2mp_item_respawn_time", "30", FCVAR_GAMEDLL | FCVAR_NOTIFY );
ConVar mp_restartgame( "mp_restartgame", "0", 0, "If non-zero, game will restart in the specified number of seconds" );
ConVar sv_report_client_settings("sv_report_client_settings", "0", FCVAR_GAMEDLL | FCVAR_NOTIFY );

extern ConVar mp_chattime;

// *HAJ 020* - Jed
extern CBaseEntity	 *g_pLastAxisSpawn;
extern CBaseEntity	 *g_pLastCWealthSpawn;

#define WEAPON_MAX_DISTANCE_FROM_SPAWN 64

#endif

REGISTER_GAMERULES_CLASS( CHL2MPRules );

BEGIN_NETWORK_TABLE_NOBASE( CHL2MPRules, DT_HL2MPRules )

	#ifdef CLIENT_DLL
		RecvPropBool( RECVINFO( m_bTeamPlayEnabled ) ),
		RecvPropInt( RECVINFO( m_nCommonwealth ) ), // Jamjar
		RecvPropInt( RECVINFO( m_nAxis ) ),
		RecvPropInt( RECVINFO( m_nYear ) ),
	#else
		SendPropBool( SENDINFO( m_bTeamPlayEnabled ) ),
		SendPropInt( SENDINFO( m_nCommonwealth ) ), // Jamjar
		SendPropInt( SENDINFO( m_nAxis ) ),
		SendPropInt( SENDINFO( m_nYear ) ),
	#endif

END_NETWORK_TABLE()

LINK_ENTITY_TO_CLASS( hl2mp_gamerules, CHL2MPGameRulesProxy );
IMPLEMENT_NETWORKCLASS_ALIASED( HL2MPGameRulesProxy, DT_HL2MPGameRulesProxy )

static HL2MPViewVectors g_HL2MPViewVectors(
	Vector( 0, 0, 64 ),        //m_vView

	Vector(-16, -16, 0 ),	  //m_vHullMin
	Vector( 16,  16,  72 ),	  //m_vHullMax

	Vector(-16, -16, 0 ),	  //m_vDuckHullMin
	Vector( 16,  16,  36 ),	  //m_vDuckHullMax
	Vector( 0, 0, 28 ),		  //m_vDuckView

	Vector(-10, -10, -10 ),	  //m_vObsHullMin
	Vector( 10,  10,  10 ),	  //m_vObsHullMax

	Vector( 0, 0, 14 ),		  //m_vDeadViewHeight

	Vector(-16, -16, 0 ),	  //m_vCrouchTraceMin
	Vector( 16,  16,  60 )	  //m_vCrouchTraceMax
);

static const char *s_PreserveEnts[] =
{
	"ai_network",
	"ai_hint",
	"hl2mp_gamerules",
	"team_manager",
	"player_manager",
	"env_soundscape",
	"env_soundscape_proxy",
	"env_soundscape_triggerable",
	"env_sun",
	"env_wind",
	"env_fog_controller",
	"func_brush",
	"func_wall",
	"func_buyzone",
	"func_illusionary",
	"infodecal",
	"info_projecteddecal",
	"info_node",
	"info_target",
	"info_node_hint",
	"info_player_deathmatch",

	// *HAJ 020* - Jed
	// Spawn entities
	//"info_player_combine",
	//"info_player_rebel",
	"info_player_commonwealth",
	"info_player_axis",

	"info_map_parameters",
	"keyframe_rope",
	"move_rope",
	"info_ladder",
	"player",
	"point_viewcontrol",
	"scene_manager",
	"shadow_control",
	"sky_camera",
	"soundent",
	"trigger_soundscape",
	"viewmodel",
	"predicted_viewmodel",
	"worldspawn",
	"point_devshot_camera",
	"", // END Marker
};

#ifdef CLIENT_DLL
	void RecvProxy_HL2MPRules( const RecvProp *pProp, void **pOut, void *pData, int objectID )
	{
		CHL2MPRules *pRules = HL2MPRules();
		Assert( pRules );
		*pOut = pRules;
	}

	BEGIN_RECV_TABLE( CHL2MPGameRulesProxy, DT_HL2MPGameRulesProxy )
		RecvPropDataTable( "hl2mp_gamerules_data", 0, 0, &REFERENCE_RECV_TABLE( DT_HL2MPRules ), RecvProxy_HL2MPRules )
	END_RECV_TABLE()
#else
	void* SendProxy_HL2MPRules( const SendProp *pProp, const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID )
	{
		CHL2MPRules *pRules = HL2MPRules();
		Assert( pRules );
		return pRules;
	}

	BEGIN_SEND_TABLE( CHL2MPGameRulesProxy, DT_HL2MPGameRulesProxy )
		SendPropDataTable( "hl2mp_gamerules_data", 0, &REFERENCE_SEND_TABLE( DT_HL2MPRules ), SendProxy_HL2MPRules )
	END_SEND_TABLE()
#endif

#ifndef CLIENT_DLL

	class CVoiceGameMgrHelper : public IVoiceGameMgrHelper
	{
	public:
		virtual bool		CanPlayerHearPlayer( CBasePlayer *pListener, CBasePlayer *pTalker )
		{
			return ( pListener->GetTeamNumber() == pTalker->GetTeamNumber() );
		}
	};
	CVoiceGameMgrHelper g_VoiceGameMgrHelper;
	IVoiceGameMgrHelper *g_pVoiceGameMgrHelper = &g_VoiceGameMgrHelper;

#endif

// NOTE: the indices here must match TEAM_TERRORIST, TEAM_CT, TEAM_SPECTATOR, etc.
char *sTeamNames[] =
{
	"Unassigned",
	"Spectator",
	// *HAJ 020* - Jed
	// Do we need a way to have these localised?
	"Commonwealth Forces",
	"Axis Forces",
	"Auto Assign", // needed for autoassign being different to unassigned
};

CHL2MPRules::CHL2MPRules()
{
#ifndef CLIENT_DLL
	// Create the team managers
	for ( int i = 0; i < ARRAYSIZE( sTeamNames ); i++ )
	{
		CTeam *pTeam = static_cast<CTeam*>(CreateEntityByName( "team_manager" ));
		pTeam->Init( sTeamNames[i], i );

		g_Teams.AddToTail( pTeam );
	}
	// *HAJ 020* - Jed
	// Hardwire teamplay (we're not a deathmatch game)
	//m_bTeamPlayEnabled = teamplay.GetBool();
	m_bTeamPlayEnabled = true;

	m_flIntermissionEndTime = 0.0f;
	m_flGameStartTime = 0;

	m_hRespawnableItemsAndWeapons.RemoveAll();
	m_tmNextPeriodicThink = 0;
	m_flRestartGameTime = 0;
	m_bCompleteReset = false;
	m_bHeardAllPlayersReady = false;
	m_bAwaitingReadyRestart = false;

	// Jam jar entity value placeholders
	m_nCommonwealth = 1;
	m_nAxis = 1;
	m_nYear = 1940;

#endif
}

const CViewVectors* CHL2MPRules::GetViewVectors()const
{
	return &g_HL2MPViewVectors;
}

const HL2MPViewVectors* CHL2MPRules::GetHL2MPViewVectors()const
{
	return &g_HL2MPViewVectors;
}

CHL2MPRules::~CHL2MPRules( void )
{
#ifndef CLIENT_DLL
	// Note, don't delete each team since they are in the gEntList and will
	// automatically be deleted from there, instead.
	g_Teams.Purge();
#endif
}

void CHL2MPRules::CreateStandardEntities( void )
{

#ifndef CLIENT_DLL
	// Create the entity that will send our data to the client.

	BaseClass::CreateStandardEntities();

	// *HAJ 020* - Jed
	g_pLastAxisSpawn = NULL;
	g_pLastCWealthSpawn = NULL;

	// *HaJ 020* - SteveUK

#ifdef _DEBUG
	CBaseEntity *pEnt =
#endif
	CBaseEntity::Create( "hl2mp_gamerules", vec3_origin, vec3_angle );
	Assert( pEnt );
#endif
}

//=========================================================
// FlWeaponRespawnTime - what is the time in the future
// at which this weapon may spawn?
//=========================================================
float CHL2MPRules::FlWeaponRespawnTime( CBaseCombatWeapon *pWeapon )
{
#ifndef CLIENT_DLL
	if ( weaponstay.GetInt() > 0 )
	{
		// make sure it's only certain weapons
		if ( !(pWeapon->GetWeaponFlags() & ITEM_FLAG_LIMITINWORLD) )
		{
			return 0;		// weapon respawns almost instantly
		}
	}

	return sv_hl2mp_weapon_respawn_time.GetFloat();
#endif

	return 0;		// weapon respawns almost instantly
}

bool CHL2MPRules::IsIntermission( void )
{
#ifndef CLIENT_DLL
	return m_flIntermissionEndTime > gpGlobals->curtime;
#endif

	return false;
}

void CHL2MPRules::PlayerKilled( CBasePlayer *pVictim, const CTakeDamageInfo &info )
{
#ifndef CLIENT_DLL
	if ( IsIntermission() )
		return;
	BaseClass::PlayerKilled( pVictim, info );
#endif
}

void CHL2MPRules::Think( void )
{

#ifndef CLIENT_DLL

	CGameRules::Think();

	if ( g_fGameOver )   // someone else quit the game already
	{
		// check to see if we should change levels now
		if ( m_flIntermissionEndTime < gpGlobals->curtime )
		{
			ChangeLevel(); // intermission is over
		}

		return;
	}

//	float flTimeLimit = mp_timelimit.GetFloat() * 60;
	float flFragLimit = fraglimit.GetFloat();

	if ( GetMapRemainingTime() < 0 )
	{
		GoToIntermission();
		return;
	}

	// *HAJ 020* - Jed
	// HaJ pointer names
	if ( flFragLimit )
	{
		if( IsTeamplay() == true )
		{
			CTeam *pAxis = g_Teams[TEAM_AXIS];
			CTeam *pCWealth = g_Teams[TEAM_CWEALTH];

			if ( pAxis->GetScore() >= flFragLimit || pCWealth->GetScore() >= flFragLimit )
			{
				GoToIntermission();
				return;
			}
		}
		else
		{
			// check if any player is over the frag limit
			for ( int i = 1; i <= gpGlobals->maxClients; i++ )
			{
				CBasePlayer *pPlayer = UTIL_PlayerByIndex( i );

				if ( pPlayer && pPlayer->FragCount() >= flFragLimit )
				{
					GoToIntermission();
					return;
				}
			}
		}
	}

	if ( gpGlobals->curtime > m_tmNextPeriodicThink )
	{
		CheckAllPlayersReady();
		CheckRestartGame();
		m_tmNextPeriodicThink = gpGlobals->curtime + 1.0;
	}

	if ( m_flRestartGameTime > 0.0f && m_flRestartGameTime <= gpGlobals->curtime )
	{
		RestartGame();
	}

	// TEMP: check if control point end condition is met
	int nCapturePoints = _capturePointManager.GetCapturePointCount();
	for(int i = CHajTeam::GetFirstCombatTeamIndex(); i < TEAM_LAST; ++i)
	{
		CHajTeam* pTeam = (CHajTeam*)g_Teams[i];
		if(pTeam->GetCapturePointsCount() == nCapturePoints)
		{
			GoToIntermission();
			return;
		}
	}

	if( m_bAwaitingReadyRestart && m_bHeardAllPlayersReady )
	{
		UTIL_ClientPrintAll( HUD_PRINTCENTER, "All players ready. Game will restart in 5 seconds" );
		UTIL_ClientPrintAll( HUD_PRINTCONSOLE, "All players ready. Game will restart in 5 seconds" );

		m_flRestartGameTime = gpGlobals->curtime + 5;
		m_bAwaitingReadyRestart = false;
	}

	ManageObjectRelocation();

#endif
}

void CHL2MPRules::GoToIntermission( void )
{
#ifndef CLIENT_DLL
	if ( g_fGameOver )
		return;

	g_fGameOver = true;

	m_flIntermissionEndTime = gpGlobals->curtime + mp_chattime.GetInt();

	for ( int i = 0; i < MAX_PLAYERS; i++ )
	{
		CBasePlayer *pPlayer = UTIL_PlayerByIndex( i );

		if ( !pPlayer )
			continue;

		pPlayer->ShowViewPortPanel( PANEL_SCOREBOARD );
		pPlayer->AddFlag( FL_FROZEN );
	}
#endif

}

bool CHL2MPRules::CheckGameOver()
{
#ifndef CLIENT_DLL
	if ( g_fGameOver )   // someone else quit the game already
	{
		// check to see if we should change levels now
		if ( m_flIntermissionEndTime < gpGlobals->curtime )
		{
			ChangeLevel(); // intermission is over
		}

		return true;
	}
#endif

	return false;
}

// when we are within this close to running out of entities,  items
// marked with the ITEM_FLAG_LIMITINWORLD will delay their respawn
#define ENTITY_INTOLERANCE	100

//=========================================================
// FlWeaponRespawnTime - Returns 0 if the weapon can respawn
// now,  otherwise it returns the time at which it can try
// to spawn again.
//=========================================================
float CHL2MPRules::FlWeaponTryRespawn( CBaseCombatWeapon *pWeapon )
{
#ifndef CLIENT_DLL
	if ( pWeapon && (pWeapon->GetWeaponFlags() & ITEM_FLAG_LIMITINWORLD) )
	{
		if ( gEntList.NumberOfEntities() < (gpGlobals->maxEntities - ENTITY_INTOLERANCE) )
			return 0;

		// we're past the entity tolerance level,  so delay the respawn
		return FlWeaponRespawnTime( pWeapon );
	}
#endif
	return 0;
}

//=========================================================
// VecWeaponRespawnSpot - where should this weapon spawn?
// Some game variations may choose to randomize spawn locations
//=========================================================
Vector CHL2MPRules::VecWeaponRespawnSpot( CBaseCombatWeapon *pWeapon )
{
#ifndef CLIENT_DLL
	CWeaponHL2MPBase *pHL2Weapon = dynamic_cast< CWeaponHL2MPBase*>( pWeapon );

	if ( pHL2Weapon )
	{
		return pHL2Weapon->GetOriginalSpawnOrigin();
	}
#endif

	return pWeapon->GetAbsOrigin();
}

#ifndef CLIENT_DLL

CItem* IsManagedObjectAnItem( CBaseEntity *pObject )
{
	return dynamic_cast< CItem*>( pObject );
}

CWeaponHL2MPBase* IsManagedObjectAWeapon( CBaseEntity *pObject )
{
	return dynamic_cast< CWeaponHL2MPBase*>( pObject );
}

bool GetObjectsOriginalParameters( CBaseEntity *pObject, Vector &vOriginalOrigin, QAngle &vOriginalAngles )
{
	if ( CItem *pItem = IsManagedObjectAnItem( pObject ) )
	{
		if ( pItem->m_flNextResetCheckTime > gpGlobals->curtime )
			 return false;

		vOriginalOrigin = pItem->GetOriginalSpawnOrigin();
		vOriginalAngles = pItem->GetOriginalSpawnAngles();

		pItem->m_flNextResetCheckTime = gpGlobals->curtime + sv_hl2mp_item_respawn_time.GetFloat();
		return true;
	}
	else if ( CWeaponHL2MPBase *pWeapon = IsManagedObjectAWeapon( pObject ))
	{
		if ( pWeapon->m_flNextResetCheckTime > gpGlobals->curtime )
			 return false;

		vOriginalOrigin = pWeapon->GetOriginalSpawnOrigin();
		vOriginalAngles = pWeapon->GetOriginalSpawnAngles();

		pWeapon->m_flNextResetCheckTime = gpGlobals->curtime + sv_hl2mp_weapon_respawn_time.GetFloat();
		return true;
	}

	return false;
}

void CHL2MPRules::ManageObjectRelocation( void )
{
	int iTotal = m_hRespawnableItemsAndWeapons.Count();

	if ( iTotal > 0 )
	{
		for ( int i = 0; i < iTotal; i++ )
		{
			CBaseEntity *pObject = m_hRespawnableItemsAndWeapons[i].Get();

			if ( pObject )
			{
				Vector vSpawOrigin;
				QAngle vSpawnAngles;

				if ( GetObjectsOriginalParameters( pObject, vSpawOrigin, vSpawnAngles ) == true )
				{
					float flDistanceFromSpawn = (pObject->GetAbsOrigin() - vSpawOrigin ).Length();

					if ( flDistanceFromSpawn > WEAPON_MAX_DISTANCE_FROM_SPAWN )
					{
						bool shouldReset = false;
						IPhysicsObject *pPhysics = pObject->VPhysicsGetObject();

						if ( pPhysics )
						{
							shouldReset = pPhysics->IsAsleep();
						}
						else
						{
							shouldReset = (pObject->GetFlags() & FL_ONGROUND) ? true : false;
						}

						if ( shouldReset )
						{
							pObject->Teleport( &vSpawOrigin, &vSpawnAngles, NULL );
							pObject->EmitSound( "AlyxEmp.Charge" );

							IPhysicsObject *pPhys = pObject->VPhysicsGetObject();

							if ( pPhys )
							{
								pPhys->Wake();
							}
						}
					}
				}
			}
		}
	}
}

//=========================================================
//AddLevelDesignerPlacedWeapon
//=========================================================
void CHL2MPRules::AddLevelDesignerPlacedObject( CBaseEntity *pEntity )
{
	if ( m_hRespawnableItemsAndWeapons.Find( pEntity ) == -1 )
	{
		m_hRespawnableItemsAndWeapons.AddToTail( pEntity );
	}
}

//=========================================================
//RemoveLevelDesignerPlacedWeapon
//=========================================================
void CHL2MPRules::RemoveLevelDesignerPlacedObject( CBaseEntity *pEntity )
{
	if ( m_hRespawnableItemsAndWeapons.Find( pEntity ) != -1 )
	{
		m_hRespawnableItemsAndWeapons.FindAndRemove( pEntity );
	}
}

//=========================================================
// Where should this item respawn?
// Some game variations may choose to randomize spawn locations
//=========================================================
Vector CHL2MPRules::VecItemRespawnSpot( CItem *pItem )
{
	return pItem->GetOriginalSpawnOrigin();
}

//=========================================================
// What angles should this item use to respawn?
//=========================================================
QAngle CHL2MPRules::VecItemRespawnAngles( CItem *pItem )
{
	return pItem->GetOriginalSpawnAngles();
}

//=========================================================
// At what time in the future may this Item respawn?
//=========================================================
float CHL2MPRules::FlItemRespawnTime( CItem *pItem )
{
	return sv_hl2mp_item_respawn_time.GetFloat();
}

//=========================================================
// CanHaveWeapon - returns false if the player is not allowed
// to pick up this weapon
//=========================================================
bool CHL2MPRules::CanHavePlayerItem( CBasePlayer *pPlayer, CBaseCombatWeapon *pItem )
{
	if ( weaponstay.GetInt() > 0 )
	{
		if ( pPlayer->Weapon_OwnsThisType( pItem->GetClassname(), pItem->GetSubType() ) )
			 return false;
	}

	return BaseClass::CanHavePlayerItem( pPlayer, pItem );
}

#endif

//=========================================================
// WeaponShouldRespawn - any conditions inhibiting the
// respawning of this weapon?
//=========================================================
int CHL2MPRules::WeaponShouldRespawn( CBaseCombatWeapon *pWeapon )
{
#ifndef CLIENT_DLL
	if ( pWeapon->HasSpawnFlags( SF_NORESPAWN ) )
	{
		return GR_WEAPON_RESPAWN_NO;
	}
#endif

	return GR_WEAPON_RESPAWN_YES;
}

//-----------------------------------------------------------------------------
// Purpose: Player has just left the game
//-----------------------------------------------------------------------------
void CHL2MPRules::ClientDisconnected( edict_t *pClient )
{
#ifndef CLIENT_DLL
	// Msg( "CLIENT DISCONNECTED, REMOVING FROM TEAM.\n" );

	CBasePlayer *pPlayer = (CBasePlayer *)CBaseEntity::Instance( pClient );
	if ( pPlayer )
	{
		// Remove the player from his team
		if ( pPlayer->GetTeam() )
		{
			pPlayer->GetTeam()->RemovePlayer( pPlayer );
		}
	}

	BaseClass::ClientDisconnected( pClient );

#endif
}

//=========================================================
// Deathnotice.
//=========================================================
void CHL2MPRules::DeathNotice( CBasePlayer *pVictim, const CTakeDamageInfo &info )
{
#ifndef CLIENT_DLL
	// Work out what killed the player, and send a message to all clients about it
	const char *killer_weapon_name = "world";		// by default, the player is killed by the world
	int killer_ID = 0;

	// Find the killer & the scorer
	CBaseEntity *pInflictor = info.GetInflictor();
	CBaseEntity *pKiller = info.GetAttacker();
	CBasePlayer *pScorer = GetDeathScorer( pKiller, pInflictor );

	// Custom kill type?
	if ( info.GetCustomKill() )
	{
		killer_weapon_name = GetCustomKillString( info );
		if ( pScorer )
		{
			killer_ID = pScorer->GetUserID();
		}
	}
	else
	{
		// Is the killer a client?
		if ( pScorer )
		{
			killer_ID = pScorer->GetUserID();

			if ( pInflictor )
			{
				if ( pInflictor == pScorer )
				{
					// If the inflictor is the killer,  then it must be their current weapon doing the damage
					if ( pScorer->GetActiveWeapon() )
					{
						killer_weapon_name = pScorer->GetActiveWeapon()->GetClassname();
					}
				}
				else
				{
					killer_weapon_name = pInflictor->GetClassname();  // it's just that easy
				}
			}
		}
		else
		{
			killer_weapon_name = pInflictor->GetClassname();
		}

		// strip the NPC_* or weapon_* from the inflictor's classname
		if ( strncmp( killer_weapon_name, "weapon_", 7 ) == 0 )
		{
			killer_weapon_name += 7;
		}
		else if ( strncmp( killer_weapon_name, "npc_", 4 ) == 0 )
		{
			killer_weapon_name += 4;
		}
		else if ( strncmp( killer_weapon_name, "func_", 5 ) == 0 )
		{
			killer_weapon_name += 5;
		}
		else if ( strstr( killer_weapon_name, "physics" ) )
		{
			killer_weapon_name = "physics";
		}

		if ( strcmp( killer_weapon_name, "prop_combine_ball" ) == 0 )
		{
			killer_weapon_name = "combine_ball";
		}
		else if ( strcmp( killer_weapon_name, "grenade_ar2" ) == 0 )
		{
			killer_weapon_name = "smg1_grenade";
		}
		else if ( strcmp( killer_weapon_name, "satchel" ) == 0 || strcmp( killer_weapon_name, "tripmine" ) == 0)
		{
			killer_weapon_name = "slam";
		}

	}

	IGameEvent *event = gameeventmanager->CreateEvent( "player_death" );
	if( event )
	{
		event->SetInt("userid", pVictim->GetUserID() );
		event->SetInt("attacker", killer_ID );
		event->SetString("weapon", killer_weapon_name );
		event->SetInt( "priority", 7 );
		gameeventmanager->FireEvent( event );
	}
#endif

}

void CHL2MPRules::ClientSettingsChanged( CBasePlayer *pPlayer )
{
#ifndef CLIENT_DLL

	CHL2MP_Player *pHL2Player = ToHL2MPPlayer( pPlayer );

	if ( pHL2Player == NULL )
		return;

	// *HAJ 020* - SteveUK
	//	I've removed the cl_playermodel shit because it doesn't actually crash the game at all.
	//  And it stops the glitch where you die and go to team "Unassigned" if you change a setting.

	if ( sv_report_client_settings.GetInt() == 1 )
	{
		UTIL_LogPrintf( "\"%s\" cl_cmdrate = \"%s\"\n", pHL2Player->GetPlayerName(), engine->GetClientConVarValue( pHL2Player->entindex(), "cl_cmdrate" ));
	}

	BaseClass::ClientSettingsChanged( pPlayer );
#endif

}

int CHL2MPRules::PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget )
{
#ifndef CLIENT_DLL
	// half life multiplay has a simple concept of Player Relationships.
	// you are either on another player's team, or you are not.
	if ( !pPlayer || !pTarget || !pTarget->IsPlayer() || IsTeamplay() == false )
		return GR_NOTTEAMMATE;

	if ( (*GetTeamID(pPlayer) != '\0') && (*GetTeamID(pTarget) != '\0') && !stricmp( GetTeamID(pPlayer), GetTeamID(pTarget) ) )
	{
		return GR_TEAMMATE;
	}
#endif

	return GR_NOTTEAMMATE;
}

const char *CHL2MPRules::GetGameDescription( void )
{
	if ( IsTeamplay() )
		return "Team Deathmatch";

	return "Deathmatch";
}

float CHL2MPRules::GetMapRemainingTime()
{
	// if timelimit is disabled, return 0
	if ( mp_timelimit.GetInt() <= 0 )
		return 0;

	// timelimit is in minutes

	float timeleft = (m_flGameStartTime + mp_timelimit.GetInt() * 60.0f ) - gpGlobals->curtime;

	return timeleft;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2MPRules::Precache( void )
{
	CBaseEntity::PrecacheScriptSound( "AlyxEmp.Charge" );
}

bool CHL2MPRules::ShouldCollide( int collisionGroup0, int collisionGroup1 )
{
	if ( collisionGroup0 > collisionGroup1 )
	{
		// swap so that lowest is always first
		swap(collisionGroup0,collisionGroup1);
	}

	if ( (collisionGroup0 == COLLISION_GROUP_PLAYER || collisionGroup0 == COLLISION_GROUP_PLAYER_MOVEMENT) &&
		collisionGroup1 == COLLISION_GROUP_WEAPON )
	{
		return false;
	}

	return BaseClass::ShouldCollide( collisionGroup0, collisionGroup1 );

}

bool CHL2MPRules::ClientCommand(const char *pcmd, CBaseEntity *pEdict )
{

#ifndef CLIENT_DLL
	if( BaseClass::ClientCommand(pcmd, pEdict) )
		return true;

	CHL2MP_Player *pPlayer = (CHL2MP_Player *) pEdict;

	if ( pPlayer->ClientCommand( pcmd ) )
		return true;
#endif

	return false;
}

// shared ammo definition
// JAY: Trying to make a more physical bullet response
#define BULLET_MASS_GRAINS_TO_LB(grains)	(0.002285*(grains)/16.0f)
#define BULLET_MASS_GRAINS_TO_KG(grains)	lbs2kg(BULLET_MASS_GRAINS_TO_LB(grains))

// exaggerate all of the forces, but use real numbers to keep them consistent
#define BULLET_IMPULSE_EXAGGERATION			3.5
// convert a velocity in ft/sec and a mass in grains to an impulse in kg in/s
#define BULLET_IMPULSE(grains, ftpersec)	((ftpersec)*12*BULLET_MASS_GRAINS_TO_KG(grains)*BULLET_IMPULSE_EXAGGERATION)

CAmmoDef *GetAmmoDef()
{
	static CAmmoDef def;
	static bool bInitted = false;

	if ( !bInitted )
	{
		bInitted = true;

		def.AddAmmoType("AR2",				DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			60,			BULLET_IMPULSE(200, 1225),	0 );
		def.AddAmmoType("AR2AltFire",		DMG_DISSOLVE,				TRACER_NONE,			0,			0,			3,			0,							0 );
		def.AddAmmoType("Pistol",			DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			150,		BULLET_IMPULSE(200, 1225),	0 );
		def.AddAmmoType("SMG1",				DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			225,		BULLET_IMPULSE(200, 1225),	0 );
		def.AddAmmoType("357",				DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			12,			BULLET_IMPULSE(800, 5000),	0 );
		def.AddAmmoType("XBowBolt",			DMG_BULLET,					TRACER_LINE,			0,			0,			10,			BULLET_IMPULSE(800, 8000),	0 );
		def.AddAmmoType("Buckshot",			DMG_BULLET | DMG_BUCKSHOT,	TRACER_LINE,			0,			0,			30,			BULLET_IMPULSE(400, 1200),	0 );
		def.AddAmmoType("RPG_Round",		DMG_BURN,					TRACER_NONE,			0,			0,			3,			0,							0 );
		def.AddAmmoType("SMG1_Grenade",		DMG_BURN,					TRACER_NONE,			0,			0,			3,			0,							0 );
		def.AddAmmoType("Grenade",			DMG_BURN,					TRACER_NONE,			0,			0,			5,			0,							0 );
		def.AddAmmoType("slam",				DMG_BURN,					TRACER_NONE,			0,			0,			5,			0,							0 );

		// *HAJ 020* - Jed
		// HaJ ammo types
		def.AddAmmoType("303",				DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			500,		0,							0 );
		def.AddAmmoType("303_tracer",		DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			500,		0,							0 );
		def.AddAmmoType("9mm",				DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			500,		0,							0 );
		def.AddAmmoType("792mm",			DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			500,		0,							0 );
		def.AddAmmoType("792mm_tracer",		DMG_BULLET,					TRACER_LINE_AND_WHIZ,	0,			0,			500,		0,							0 );
		def.AddAmmoType("mills_grenade",	DMG_BURN,					TRACER_NONE,			0,			0,			5,			0,							0 );
		def.AddAmmoType("stick_grenade",	DMG_BURN,					TRACER_NONE,			0,			0,			5,			0,							0 );
		def.AddAmmoType("smoke_grenade",	DMG_BURN,					TRACER_NONE,			0,			0,			5,			0,							0 );
	}

	return &def;
}

#ifdef CLIENT_DLL

	ConVar cl_autowepswitch(
		"cl_autowepswitch",
		"1",
		FCVAR_ARCHIVE | FCVAR_USERINFO,
		"Automatically switch to picked up weapons (if more powerful)" );

#else

	bool CHL2MPRules::FShouldSwitchWeapon( CBasePlayer *pPlayer, CBaseCombatWeapon *pWeapon )
	{
		if ( pPlayer->GetActiveWeapon() && pPlayer->IsNetClient() )
		{
			// Player has an active item, so let's check cl_autowepswitch.
			const char *cl_autowepswitch = engine->GetClientConVarValue( engine->IndexOfEdict( pPlayer->edict() ), "cl_autowepswitch" );
			if ( cl_autowepswitch && atoi( cl_autowepswitch ) <= 0 )
			{
				return false;
			}
		}

		return BaseClass::FShouldSwitchWeapon( pPlayer, pWeapon );
	}

#endif

#ifndef CLIENT_DLL

bool FindInList( const char **pStrings, const char *pToFind )
{
	int i = 0;
	while ( pStrings[i][0] != 0 )
	{
		if ( Q_stricmp( pStrings[i], pToFind ) == 0 )
			return true;
		i++;
	}

	return false;
}

void CHL2MPRules::RestartGame()
{
	// bounds check
	if ( mp_timelimit.GetInt() < 0 )
	{
		mp_timelimit.SetValue( 0 );
	}
	m_flGameStartTime = gpGlobals->curtime;
	if ( !IsFinite( m_flGameStartTime.Get() ) )
	{
		Warning( "Trying to set a NaN game start time\n" );
		m_flGameStartTime.GetForModify() = 0.0f;
	}

	CleanUpMap();

	// now respawn all players
	for (int i = 1; i <= gpGlobals->maxClients; i++ )
	{
		CHL2MP_Player *pPlayer = (CHL2MP_Player*) UTIL_PlayerByIndex( i );

		if ( !pPlayer )
			continue;

		if ( pPlayer->GetActiveWeapon() )
		{
			pPlayer->GetActiveWeapon()->Holster();
		}
		pPlayer->RemoveAllItems( true );
		respawn( pPlayer, false );
		pPlayer->Reset();
	}

	// Respawn entities (glass, doors, etc..)

	// *HAJ 020* - Jed
	// HaJ pointer names
	CTeam *pCWealth = GetGlobalTeam( TEAM_CWEALTH );
	CTeam *pAxis = GetGlobalTeam( TEAM_AXIS );

	if ( pCWealth )
	{
		pCWealth->SetScore( 0 );
	}

	if ( pAxis )
	{
		pAxis->SetScore( 0 );
	}

	m_flIntermissionEndTime = 0;
	m_flRestartGameTime = 0.0;
	m_bCompleteReset = false;

	IGameEvent * event = gameeventmanager->CreateEvent( "round_start" );
	if ( event )
	{
		event->SetInt("fraglimit", 0 );
		event->SetInt( "priority", 6 ); // HLTV event priority, not transmitted

		event->SetString("objective","DEATHMATCH");

		gameeventmanager->FireEvent( event );
	}
}

void CHL2MPRules::CleanUpMap()
{
	// Recreate all the map entities from the map data (preserving their indices),
	// then remove everything else except the players.

	// Get rid of all entities except players.
	CBaseEntity *pCur = gEntList.FirstEnt();
	while ( pCur )
	{
		CBaseHL2MPCombatWeapon *pWeapon = dynamic_cast< CBaseHL2MPCombatWeapon* >( pCur );
		// Weapons with owners don't want to be removed..
		if ( pWeapon )
		{
			if ( !pWeapon->GetPlayerOwner() )
			{
				UTIL_Remove( pCur );
			}
		}
		// remove entities that has to be restored on roundrestart (breakables etc)
		else if ( !FindInList( s_PreserveEnts, pCur->GetClassname() ) )
		{
			UTIL_Remove( pCur );
		}

		pCur = gEntList.NextEnt( pCur );
	}

	// Really remove the entities so we can have access to their slots below.
	gEntList.CleanupDeleteList();

	// Cancel all queued events, in case a func_bomb_target fired some delayed outputs that
	// could kill respawning CTs
	g_EventQueue.Clear();

	// Now reload the map entities.
	class CHL2MPMapEntityFilter : public IMapEntityFilter
	{
	public:
		virtual bool ShouldCreateEntity( const char *pClassname )
		{
			// Don't recreate the preserved entities.
			if ( !FindInList( s_PreserveEnts, pClassname ) )
			{
				return true;
			}
			else
			{
				// Increment our iterator since it's not going to call CreateNextEntity for this ent.
				if ( m_iIterator != g_MapEntityRefs.InvalidIndex() )
					m_iIterator = g_MapEntityRefs.Next( m_iIterator );

				return false;
			}
		}

		virtual CBaseEntity* CreateNextEntity( const char *pClassname )
		{
			if ( m_iIterator == g_MapEntityRefs.InvalidIndex() )
			{
				// This shouldn't be possible. When we loaded the map, it should have used
				// CCSMapLoadEntityFilter, which should have built the g_MapEntityRefs list
				// with the same list of entities we're referring to here.
				Assert( false );
				return NULL;
			}
			else
			{
				CMapEntityRef &ref = g_MapEntityRefs[m_iIterator];
				m_iIterator = g_MapEntityRefs.Next( m_iIterator );	// Seek to the next entity.

				if ( ref.m_iEdict == -1 || engine->PEntityOfEntIndex( ref.m_iEdict ) )
				{
					// Doh! The entity was delete and its slot was reused.
					// Just use any old edict slot. This case sucks because we lose the baseline.
					return CreateEntityByName( pClassname );
				}
				else
				{
					// Cool, the slot where this entity was is free again (most likely, the entity was
					// freed above). Now create an entity with this specific index.
					return CreateEntityByName( pClassname, ref.m_iEdict );
				}
			}
		}

	public:
		int m_iIterator; // Iterator into g_MapEntityRefs.
	};
	CHL2MPMapEntityFilter filter;
	filter.m_iIterator = g_MapEntityRefs.Head();

	// DO NOT CALL SPAWN ON info_node ENTITIES!

	MapEntity_ParseAllEntities( engine->GetMapEntitiesString(), &filter, true );
}

void CHL2MPRules::CheckChatForReadySignal( CHL2MP_Player *pPlayer, const char *chatmsg )
{
	if( m_bAwaitingReadyRestart && FStrEq( chatmsg, mp_ready_signal.GetString() ) )
	{
		if( !pPlayer->IsReady() )
		{
			pPlayer->SetReady( true );
		}
	}
}

void CHL2MPRules::CheckRestartGame( void )
{
	// Restart the game if specified by the server
	int iRestartDelay = mp_restartgame.GetInt();

	if ( iRestartDelay > 0 )
	{
		if ( iRestartDelay > 60 )
			iRestartDelay = 60;

		// let the players know
		char strRestartDelay[64];
		Q_snprintf( strRestartDelay, sizeof( strRestartDelay ), "%d", iRestartDelay );
		UTIL_ClientPrintAll( HUD_PRINTCENTER, "Game will restart in %s1 %s2", strRestartDelay, iRestartDelay == 1 ? "SECOND" : "SECONDS" );
		UTIL_ClientPrintAll( HUD_PRINTCONSOLE, "Game will restart in %s1 %s2", strRestartDelay, iRestartDelay == 1 ? "SECOND" : "SECONDS" );

		m_flRestartGameTime = gpGlobals->curtime + iRestartDelay;
		m_bCompleteReset = true;
		mp_restartgame.SetValue( 0 );
	}

	if( mp_readyrestart.GetBool() )
	{
		m_bAwaitingReadyRestart = true;
		m_bHeardAllPlayersReady = false;

		const char *pszReadyString = mp_ready_signal.GetString();

		// Don't let them put anything malicious in there
		if( pszReadyString == NULL || Q_strlen(pszReadyString) > 16 )
		{
			pszReadyString = "ready";
		}

		IGameEvent *event = gameeventmanager->CreateEvent( "hl2mp_ready_restart" );
		if ( event )
			gameeventmanager->FireEvent( event );

		mp_readyrestart.SetValue( 0 );

		// cancel any restart round in progress
		m_flRestartGameTime = -1;
	}
}

void CHL2MPRules::CheckAllPlayersReady( void )
{
	for (int i = 1; i <= gpGlobals->maxClients; i++ )
	{
		CHL2MP_Player *pPlayer = (CHL2MP_Player*) UTIL_PlayerByIndex( i );

		if ( !pPlayer )
			continue;
		if ( !pPlayer->IsReady() )
			return;
	}
	m_bHeardAllPlayersReady = true;
}

#endif


text:
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import PrintDialog from '../../../../components/wallet/paper-wallet-certificate/PrintDialog';
import type { InjectedDialogContainerProps } from '../../../../types/injectedPropsType';

type Props = InjectedDialogContainerProps;

@inject('actions')
@observer
class PrintDialogContainer extends Component<Props> {
  static defaultProps = {
    actions: null,
    stores: null,
    children: null,
    onClose: () => {},
  };
  onContinue = () => {
    this.props.actions.wallets.updateCertificateStep.trigger();
  };

  render() {
    return (
      <PrintDialog onContinue={this.onContinue} onClose={this.props.onClose} />
    );
  }
}

export default PrintDialogContainer;


text:
package iso20022

type EUCapitalGain1Code string


text:
from django.conf import settings as django_settings

class LDAPSettings(object):
    """
    Class that provides access to the LDAP settings specified in Django's
    settings, with defaults set if they are missing.

    Settings are prefixed in Django's settings, but are used here without prefix.
    So `AUTH_LDAP_URI` becomes `settings.URI`.
    """

    prefix = 'AUTH_LDAP_'
    defaults = {
        'ADMIN_GROUP': None,
        'BASE_DN': 'dc=example,dc=com',
        'BIND_TEMPLATE': 'uid={username},{base_dn}',
        'GROUP_MAP': None,
        'LOGIN_GROUP': '*',
        'UID_ATTRIB': 'uid',
        'USERNAME_PREFIX': None,
        'USERNAME_SUFFIX': None,
        'URI': 'ldap://localhost',
        'TLS': False,
        'TLS_CA_CERTS': None,
        'TLS_VALIDATE': True,
        'TLS_PRIVATE_KEY': None,
        'TLS_LOCAL_CERT': None,
    }

    def __init__(self):
        for name, default in self.defaults.items():
            v = getattr(django_settings, self.prefix + name, default)
            setattr(self, name, v)

    @property
    def settings_dict(self):
        return {k: getattr(self, k) for k in self.defaults.keys()}

settings = LDAPSettings()


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>RoadShow</title>
    <link href="https://fonts.googleapis.com/css?family=Crushed|Cuprum|PT+Sans" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link href="style/style.css" rel="stylesheet">

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

                </button>
               RoadShow

Home

My Trips

Log Out

Going somewhere? Create a Trip to track your journey and find shows at your Destinations

Create Trip

        ×

            Name your Trip

            <input type="text" name="newtripname" class="modalinput" id="newtripname">

            Describe your Trip

            <input type="text" name="newtripdescrip" class="modalinput" id="newtripdescrip">

            <input type="submit" id="newtripsubmit">

        ×

            New Destination Name

            <input type="text" name="newdestname" class="modalinput" id="newdestname">

            Address/Location

            <input type="text" name="newdestloc" class="modalinput" id="newdestloc">

            Arrival DD/MM/YYYY

            <input type="text" name="newdestarrd" class="modalinput destday" id="newdestarrd">
            <input type="text" name="newdestarrm" class="modalinput destmonth" id="newdestarrm">
            <input type="text" name="newdestarry" class="modalinput destyear" id="newdestarry">

            Departure DD/MM/YYYY

            <input type="text" name="newdestdeptd" class="modalinput destday" id="newdestdeptd">
            <input type="text" name="newdestdeptm" class="modalinput destmonth" id="newdestdeptm">
            <input type="text" name="newdestdepty" class="modalinput destyear" id="newdestdepty">

            Comments about this Destination

            <input type="text" name="newdestcomm" class="modalinput" id="newdestcomm">

            <input type="submit" id="newdestsubmit">

        ×

Back to top

© 2017 NateSalNick Company, Inc. · Privacy · Terms


text:
function sleepCallback( eventType )

	local appDLM = hs.application.find("xScope")
	if(appDLM ~= nil) then
		appDLM:kill()
	end

end
sleepWatcher = hs.caffeinate.watcher.new(sleepCallback):start()

function wakeCallback( eventType )
end
wakeWatcher = hs.caffeinate.watcher.new(wakeCallback):start()


text:
@implementation XIU_NetAPIClient
static AFHTTPSessionManager *_manager;
static XIU_NetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;

+ (XIU_NetAPIClient *)sharedJsonClient {

    dispatch_once(&onceToken, ^{
        _sharedClient = [[XIU_NetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:[NSObject baseURLStr]]];
    });
    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    _manager = [AFHTTPSessionManager manager];
    AFHTTPRequestSerializer *requestSerializer =  [AFJSONRequestSerializer serializer];
    //    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *headerFieldValueDictionary = @{@"Authorization": @"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",@"Accept": @"application/json"};
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    _manager.requestSerializer = requestSerializer;
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];

    return self;

    //不同设置类型 ----解开可用
//    self.responseSerializer = [AFJSONResponseSerializer serializer];
//    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
//
//    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [self.requestSerializer setValue:url.absoluteString forHTTPHeaderField:@"Referer"];
//
//    self.securityPolicy.allowInvalidCertificates = YES;
//
//    return self;
}

- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NetworkMethod)method
                       andBlock:(void (^)(id data, NSError *error))block{
    [self requestJsonDataWithPath:aPath withParams:params withMethodType:method autoShowError:YES andBlock:block];
}

- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NetworkMethod)method
                  autoShowError:(BOOL)autoShowError
                       andBlock:(void (^)(id data, NSError *error))block{
    if (!aPath || aPath.length <= 0) {
        return;
    }
    aPath = [aPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    switch (method) {
        case Get: {
            //所有 Post 请求,增加缓存机制
            NSMutableString *localPath = [aPath mutableCopy];
            if (params) {
                [localPath appendString:params.description];
            }
            [self GET:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                  id error = [self handleResponse:responseObject autoShowError:autoShowError];
                if (error) {
                    responseObject = [NSObject loadResponseWithPath:localPath];
                    block(responseObject, error);
                }else {
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        //判断数据是否符合预期,给出提示
                        if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                            if (responseObject[@"data"][@"too_many_files"]) {
                                if (autoShowError) {
//                                    [NSObject showHudTipStr:@"文件太多,不能正常显示"];
                                }
                            }
                        }
                        [NSObject saveResponseData:responseObject toPath:localPath];
                    }
                    block(responseObject, nil);

                }

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            }];
        }
            break;
        case Post: {
            //所有 post 请求,增加缓存机制

            NSMutableString *localPath = [aPath mutableCopy];
            if (params) {
                [localPath appendString:params.description];

            }

            [_manager POST:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                NSString * jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

                NSData * data1 = [[NSData alloc]initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

                NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];

                //                               NSLog(@"\n===========response===========\n%@:\n%@", aPath, jsonData);

                if ([jsonData isKindOfClass:[NSDictionary class]]) {
                    //判断数据是否符合预期,给出提示
                    if ([jsonData[@"data"] isKindOfClass:[NSDictionary class]]) {
                        if (jsonData[@"data"][@"too_many_files"]) {
                            if (autoShowError) {
                                //                                    [NSObject showHudTipStr:@"文件太多,不能正常显示"];
                            }
                        }
                    }

                }
                block(jsonData, nil);

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"error = %@", error);

            }];

        }
            break;

        default:
            break;
    }

}

//文件下载
+ (void)requestJSPatchDownLoadFileWithPath:(NSString *)aPath
                         withParams:(NSDictionary*)params
                     withMethodType:(NetworkMethod)method
                           andBlock:(void (^)(id data, NSError *error))block {
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:aPath]];

    //下载Task操作
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小

        // 给Progress添加监听 KVO
        NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        // 回到主队列刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            // 设置进度条的百分比

//            self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        });

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径

        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //设置下载完成操作
        // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用

//        NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
//        UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];

    }];
}
@end


text:
package com.github.maven_nar.cpptasks;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.github.maven_nar.cpptasks.compiler.ProcessorConfiguration;

/**
 * Tests for TargetHistoryTable
 *
 * @author CurtA
 */
public class TestTargetHistoryTable extends TestXMLConsumer {
  public static class MockProcessorConfiguration implements ProcessorConfiguration {
    public MockProcessorConfiguration() {
    }

    @Override
    public int bid(final String fileName) {
      return 100;
    }

    @Override
    public String getIdentifier() {
      return "Mock Configuration";
    }

    @Override
    public String[] getOutputFileNames(final String baseName, final VersionInfo versionInfo) {
      return new String[] {
        baseName
      };
    }

    @Override
    public ProcessorParam[] getParams() {
      return new ProcessorParam[0];
    }

    @Override
    public boolean getRebuild() {
      return false;
    }
  }

  /**
   * Constructor
   *
   * @param name
   *          test case name
   * @see junit.framework.TestCase#TestCase(String)
   */
  public TestTargetHistoryTable(final String name) {
    super(name);
  }

  /**
   * Tests loading a stock history file
   *
   * @throws IOException
   */
  public void testLoadOpenshore() throws IOException {
    try {
      copyResourceToTmpDir("openshore/history.xml", "history.xml");
      final CCTask task = new CCTask();
      final String tmpDir = System.getProperty("java.io.tmpdir");
      final TargetHistoryTable history = new TargetHistoryTable(task, new File(tmpDir));
    } finally {
      deleteTmpFile("history.xml");
    }
  }

  /**
   * Tests loading a stock history file
   *
   * @throws IOException
   */
  public void testLoadXerces() throws IOException {
    try {
      copyResourceToTmpDir("xerces-c/history.xml", "history.xml");
      final CCTask task = new CCTask();
      final String tmpDir = System.getProperty("java.io.tmpdir");
      final TargetHistoryTable history = new TargetHistoryTable(task, new File(tmpDir));
    } finally {
      deleteTmpFile("history.xml");
    }
  }

  /**
   * Tests for bug fixed by patch [ 650397 ] Fix: Needless rebuilds on Unix
   *
   * @throws IOException
   */
  public void testUpdateTimeResolution() throws IOException {
    File compiledFile = null;

    try {
      //
      // delete any history file that might exist
      // in the test output directory
      final String tempDir = System.getProperty("java.io.tmpdir");
      File historyFile = new File(tempDir, "history.xml");
      historyFile.deleteOnExit();
      if (historyFile.exists()) {
        historyFile.delete();
      }
      final TargetHistoryTable table = new TargetHistoryTable(null, new File(tempDir));
      //
      // create a dummy compiled unit
      //
      compiledFile = new File(tempDir, "dummy.o");
      final FileOutputStream compiledStream = new FileOutputStream(compiledFile);
      compiledStream.close();
      //
      // lastModified times can be slightly less than
      // task start time due to file system resolution.
      // Mimic this by slightly incrementing the last modification time.
      //
      final long startTime = compiledFile.lastModified() + 1;
      //
      // update the table
      //
      table.update(new MockProcessorConfiguration(), new String[] {
        "dummy.o"
      }, null);
      //
      // commit. If "compiled" file was judged to be
      // valid we should have a history file.
      //
      table.commit();
      historyFile = table.getHistoryFile();
      assertTrue("History file was not created", historyFile.exists());
      assertTrue("History file was empty", historyFile.length() > 10);
    } finally {
      if (compiledFile != null && compiledFile.exists()) {
        compiledFile.delete();
      }

    }
  }
}


text:
import os
import logging

from flask.ext.script import Manager, Shell

from app import create_app, db
from app.models import Entry

app = create_app(os.getenv('EXFLASKR_CONFIG') or 'default')
manager = Manager(app)

def make_shell_context():
    return dict(app=app, db=db, Entry=Entry)
manager.add_command('shell', Shell(make_context=make_shell_context))

@manager.command
def test():
    """
    Run testing procedure.
    """

    from subprocess import call
    call(['nosetests', '-v',
          '--with-coverage', '--cover-package=app', '--cover-branches',
          '--cover-erase', '--cover-html', '--cover-html-dir=cover'])

@manager.command
def initapp():
    """
    Initialize App.
    """

    db.create_all()
    logging.info('Application initialization completed successfully.')

if __name__ == '__main__':
    manager.run()