import asyncio
import functools
import random
import time
from testing import Client
from testing import default_test_setup
from testing import gen_data
from testing import gen_points
from testing import gen_series
from testing import InsertError
from testing import PoolError
from testing import QueryError
from testing import run_test
from testing import Series
from testing import Server
from testing import ServerError
from testing import SiriDB
from testing import TestBase
from testing import UserAuthError
from testing import parse_args


DATA = {
    'log': [
        [1471254710, 'log line one'],
        [1471254712, 'log line two'],
        [1471254714, 'log line three'],
        [1471254715, 'log line four'],
        [1471254716, 'log line five'],
        [1471254718, 'another line (six)'],
        [1471254720, 'and yet one more, this is log line seven']
    ],
    'utf16': [
        [1471254710, ''],
        [1471254712, ''],
        [1471254714, '  '],
        [1471254715, ' '],
        [1471254716, ' '],
        [1471254718, 'ԉ']
    ],
    'long_log': [
        [1471254710, '''
time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. Thus it is a sequence of discrete-time data. Examples of time series are heights of ocean tides, counts of sunspots, and the daily closing value of the Dow Jones Industrial Average.
Time series are very frequently plotted via line charts. Time series are used in statistics, signal processing, pattern recognition, econometrics, mathematical finance, weather forecasting, earthquake prediction, electroencephalography, control engineering, astronomy, communications engineering, and largely in any domain of applied science and engineering which involves temporal measurements.
Time series analysis comprises methods for analyzing time series data in order to extract meaningful statistics and other characteristics of the data. Time series forecasting is the use of a model to predict future values based on previously observed values. While regression analysis is often employed in such a way as to test theories that the current values of one or more independent time series affect the current value of another time series, this type of analysis of time series is not called "time series analysis", which focuses on comparing values of a single time series or multiple dependent time series at different points in time.[1] Interrupted time series analysis is the analysis of interventions on a single time series.
Time series data have a natural temporal ordering. This makes time series analysis distinct from cross-sectional studies, in which there is no natural ordering of the observations (e.g. explaining people's wages by reference to their respective education levels, where the individuals' data could be entered in any order). Time series analysis is also distinct from spatial data analysis where the observations typically relate to geographical locations (e.g. accounting for house prices by the location as well as the intrinsic characteristics of the houses). A stochastic model for a time series will generally reflect the fact that observations close together in time will be more closely related than observations further apart. In addition, time series models will often make use of the natural one-way ordering of time so that values for a given period will be expressed as deriving in some way from past values, rather than from future values (see time reversibility.)
Time series analysis can be applied to real-valued, continuous data, discrete numeric data, or discrete symbolic data (i.e. sequences of characters, such as letters and words in the English language[2]).']
'''],  # nopep8
        [1471254712, '''
Methods for time series analysis may be divided into two classes: frequency-domain methods and time-domain methods. The former include spectral analysis and wavelet analysis; the latter include auto-correlation and cross-correlation analysis. In the time domain, correlation and analysis can be made in a filter-like manner using scaled correlation, thereby mitigating the need to operate in the frequency domain.
Additionally, time series analysis techniques may be divided into parametric and non-parametric methods. The parametric approaches assume that the underlying stationary stochastic process has a certain structure which can be described using a small number of parameters (for example, using an autoregressive or moving average model). In these approaches, the task is to estimate the parameters of the model that describes the stochastic process. By contrast, non-parametric approaches explicitly estimate the covariance or the spectrum of the process without assuming that the process has any particular structure.
Methods of time series analysis may also be divided into linear and non-linear, and univariate and multivariate.
'''],  # nopep8
        [1471254714, '''
Curve fitting
Main article: Curve fitting
Curve fitting[5][6] is the process of constructing a curve, or mathematical function, that has the best fit to a series of data points,[7] possibly subject to constraints.[8][9] Curve fitting can involve either interpolation,[10][11] where an exact fit to the data is required, or smoothing,[12][13] in which a "smooth" function is constructed that approximately fits the data. A related topic is regression analysis,[14][15] which focuses more on questions of statistical inference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization,[16][17] to infer values of a function where no data are available,[18] and to summarize the relationships among two or more variables.[19] Extrapolation refers to the use of a fitted curve beyond the range of the observed data,[20] and is subject to a degree of uncertainty[21] since it may reflect the method used to construct the curve as much as it reflects the observed data.
The construction of economic time series involves the estimation of some components for some dates by interpolation between values ("benchmarks") for earlier and later dates. Interpolation is estimation of an unknown quantity between two known quantities (historical data), or drawing conclusions about missing information from the available information ("reading between the lines").[22] Interpolation is useful where the data surrounding the missing data is available and its trend, seasonality, and longer-term cycles are known. This is often done by using a related series known for all relevant dates.[23] Alternatively polynomial interpolation or spline interpolation is used where piecewise polynomial functions are fit into time intervals such that they fit smoothly together. A different problem which is closely related to interpolation is the approximation of a complicated function by a simple function (also called regression).The main difference between regression and interpolation is that polynomial regression gives a single polynomial that models the entire data set. Spline interpolation, however, yield a piecewise continuous function composed of many polynomials to model the data set.
Extrapolation is the process of estimating, beyond the original observation range, the value of a variable on the basis of its relationship with another variable. It is similar to interpolation, which produces estimates between known observations, but extrapolation is subject to greater uncertainty and a higher risk of producing meaningless results.

'''],  # nopep8
        [1471254715, '''
Function approximation
Main article: Function approximation
In general, a function approximation problem asks us to select a function among a well-defined class that closely matches ("approximates") a target function in a task-specific way. One can distinguish two major classes of function approximation problems: First, for known target functions approximation theory is the branch of numerical analysis that investigates how certain known functions (for example, special functions) can be approximated by a specific class of functions (for example, polynomials or rational functions) that often have desirable properties (inexpensive computation, continuity, integral and limit values, etc.).
Second, the target function, call it g, may be unknown; instead of an explicit formula, only a set of points (a time series) of the form (x, g(x)) is provided. Depending on the structure of the domain and codomain of g, several techniques for approximating g may be applicable. For example, if g is an operation on the real numbers, techniques of interpolation, extrapolation, regression analysis, and curve fitting can be used. If the codomain (range or target set) of g is a finite set, one is dealing with a classification problem instead. A related problem of online time series approximation[24] is to summarize the data in one-pass and construct an approximate representation that can support a variety of time series queries with bounds on worst-case error.
To some extent the different problems (regression, classification, fitness approximation) have received a unified treatment in statistical learning theory, where they are viewed as supervised learning problems.
'''],  # nopep8
        [1471254716, '''
Prediction and forecasting
In statistics, prediction is a part of statistical inference. One particular approach to such inference is known as predictive inference, but the prediction can be undertaken within any of the several approaches to statistical inference. Indeed, one description of statistics is that it provides a means of transferring knowledge about a sample of a population to the whole population, and to other related populations, which is not necessarily the same as prediction over time. When information is transferred across time, often to specific points in time, the process is known as forecasting.
Fully formed statistical models for stochastic simulation purposes, so as to generate alternative versions of the time series, representing what might happen over non-specific time-periods in the future
Simple or fully formed statistical models to describe the likely outcome of the time series in the immediate future, given knowledge of the most recent outcomes (forecasting).
Forecasting on time series is usually done using automated statistical software packages and programming languages, such as R, S, SAS, SPSS, Minitab, pandas (Python) and many others.
Forecasting on large scale data is done using Spark which has spark-ts as a third party package.
Classification
Main article: Statistical classification
Assigning time series pattern to a specific category, for example identify a word based on series of hand movements in sign language.
Signal estimation
See also: Signal processing and Estimation theory
This approach is based on harmonic analysis and filtering of signals in the frequency domain using the Fourier transform, and spectral density estimation, the development of which was significantly accelerated during World War II by mathematician Norbert Wiener, electrical engineers Rudolf E. Kálmán, Dennis Gabor and others for filtering signals from noise and predicting signal values at a certain point in time. See Kalman filter, Estimation theory, and Digital signal processing
'''],  # nopep8
        [1471254718, '''
Segmentation
Main article: Time-series segmentation
Splitting a time-series into a sequence of segments. It is often the case that a time-series can be represented as a sequence of individual segments, each with its own characteristic properties. For example, the audio signal from a conference call can be partitioned into pieces corresponding to the times during which each person was speaking. In time-series segmentation, the goal is to identify the segment boundary points in the time-series, and to characterize the dynamical properties associated with each segment. One can approach this problem using change-point detection, or by modeling the time-series as a more sophisticated system, such as a Markov jump linear system.
Models
Models for time series data can have many forms and represent different stochastic processes. When modeling variations in the level of a process, three broad classes of practical importance are the autoregressive (AR) models, the integrated (I) models, and the moving average (MA) models. These three classes depend linearly on previous data points.[25] Combinations of these ideas produce autoregressive moving average (ARMA) and autoregressive integrated moving average (ARIMA) models. The autoregressive fractionally integrated moving average (ARFIMA) model generalizes the former three. Extensions of these classes to deal with vector-valued data are available under the heading of multivariate time-series models and sometimes the preceding acronyms are extended by including an initial "V" for "vector", as in VAR for vector autoregression. An additional set of extensions of these models is available for use where the observed time-series is driven by some "forcing" time-series (which may not have a causal effect on the observed series): the distinction from the multivariate case is that the forcing series may be deterministic or under the experimenter's control. For these models, the acronyms are extended with a final "X" for "exogenous".
Non-linear dependence of the level of a series on previous data points is of interest, partly because of the possibility of producing a chaotic time series. However, more importantly, empirical investigations can indicate the advantage of using predictions derived from non-linear models, over those from linear models, as for example in nonlinear autoregressive exogenous models. Further references on nonlinear time series analysis: (Kantz and Schreiber),[26] and (Abarbanel)[27]
Among other types of non-linear time series models, there are models to represent the changes of variance over time (heteroskedasticity). These models represent autoregressive conditional heteroskedasticity (ARCH) and the collection comprises a wide variety of representation (GARCH, TARCH, EGARCH, FIGARCH, CGARCH, etc.). Here changes in variability are related to, or predicted by, recent past values of the observed series. This is in contrast to other possible representations of locally varying variability, where the variability might be modelled as being driven by a separate time-varying process, as in a doubly stochastic model.
In recent work on model-free analyses, wavelet transform based methods (for example locally stationary wavelets and wavelet decomposed neural networks) have gained favor. Multiscale (often referred to as multiresolution) techniques decompose a given time series, attempting to illustrate time dependence at multiple scales. See also Markov switching multifractal (MSMF) techniques for modeling volatility evolution.
A Hidden Markov model (HMM) is a statistical Markov model in which the system being modeled is assumed to be a Markov process with unobserved (hidden) states. An HMM can be considered as the simplest dynamic Bayesian network. HMM models are widely used in speech recognition, for translating a time series of spoken words into text.
'''],  # nopep8
        [1471254720, '''
Time
The flow of sand in an hourglass can be used to measure the passage of time. It also concretely represents the present as being between the past and the future.
Time is the indefinite continued progress of existence and events that occur in apparently irreversible succession from the past through the present to the future.[1][2][3] Time is a component quantity of various measurements used to sequence events, to compare the duration of events or the intervals between them, and to quantify rates of change of quantities in material reality or in the conscious experience.[4][5][6][7] Time is often referred to as a fourth dimension, along with three spatial dimensions.[8]
Time has long been an important subject of study in religion, philosophy, and science, but defining it in a manner applicable to all fields without circularity has consistently eluded scholars.[2][6][7][9][10][11] Nevertheless, diverse fields such as business, industry, sports, the sciences, and the performing arts all incorporate some notion of time into their respective measuring systems.[12][13][14]
Two contrasting viewpoints on time divide prominent philosophers. One view is that time is part of the fundamental structure of the universe – a dimension independent of events, in which events occur in sequence. Isaac Newton subscribed to this realist view, and hence it is sometimes referred to as Newtonian time.[15][16] The opposing view is that time does not refer to any kind of "container" that events and objects "move through", nor to any entity that "flows", but that it is instead part of a fundamental intellectual structure (together with space and number) within which humans sequence and compare events. This second view, in the tradition of Gottfried Leibniz[17] and Immanuel Kant,[18][19] holds that time is neither an event nor a thing, and thus is not itself measurable nor can it be travelled.
Time in physics is unambiguously operationally defined as "what a clock reads".[6][17][20] See Units of Time. Time is one of the seven fundamental physical quantities in both the International System of Units and International System of Quantities. Time is used to define other quantities – such as velocity – so defining time in terms of such quantities would result in circularity of definition.[21] An operational definition of time, wherein one says that observing a certain number of repetitions of one or another standard cyclical event (such as the passage of a free-swinging pendulum) constitutes one standard unit such as the second, is highly useful in the conduct of both advanced experiments and everyday affairs of life. The operational definition leaves aside the question whether there is something called time, apart from the counting activity just mentioned, that flows and that can be measured. Investigations of a single continuum called spacetime bring questions about space into questions about time, questions that have their roots in the works of early students of natural philosophy.
Temporal measurement has occupied scientists and technologists, and was a prime motivation in navigation and astronomy. Periodic events and periodic motion have long served as standards for units of time. Examples include the apparent motion of the sun across the sky, the phases of the moon, the swing of a pendulum, and the beat of a heart. Currently, the international unit of time, the second, is defined by measuring the electronic transition frequency of caesium atoms (see below). Time is also of significant social importance, having economic value ("time is money") as well as personal value, due to an awareness of the limited time in each day and in human life spans.]
Temporal measurement and history
Generally speaking, methods of temporal measurement, or chronometry, take two distinct forms: the calendar, a mathematical tool for organising intervals of time,[22] and the clock, a physical mechanism that counts the passage of time. In day-to-day life, the clock is consulted for periods less than a day whereas the calendar is consulted for periods longer than a day. Increasingly, personal electronic devices display both calendars and clocks simultaneously. The number (as on a clock dial or calendar) that marks the occurrence of a specified event as to hour or date is obtained by counting from a fiducial epoch – a central reference point.
History of the calendar
Main article: Calendar
Artifacts from the Paleolithic suggest that the moon was used to reckon time as early as 6,000 years ago.[23] Lunar calendars were among the first to appear, either 12 or 13 lunar months (either 354 or 384 days). Without intercalation to add days or months to some years, seasons quickly drift in a calendar based solely on twelve lunar months. Lunisolar calendars have a thirteenth month added to some years to make up for the difference between a full year (now known to be about 365.24 days) and a year of just twelve lunar months. The numbers twelve and thirteen came to feature prominently in many cultures, at least partly due to this relationship of months to years. Other early forms of calendars originated in Mesoamerica, particularly in ancient Mayan civilization. These calendars were religiously and astronomically based, with 18 months in a year and 20 days in a month, plus five epagomenal days at the end of the year.[24]
The reforms of Julius Caesar in 45 BC put the Roman world on a solar calendar. This Julian calendar was faulty in that its intercalation still allowed the astronomical solstices and equinoxes to advance against it by about 11 minutes per year. Pope Gregory XIII introduced a correction in 1582; the Gregorian calendar was only slowly adopted by different nations over a period of centuries, but it is now the most commonly used calendar around the world, by far.
During the French Revolution, a new clock and calendar were invented in attempt to de-Christianize time and create a more rational system in order to replace the Gregorian calendar. The French Republican Calendar's days consisted of ten hours of a hundred minutes of a hundred seconds, which marked a deviation from the 12-based duodecimal system used in many other devices by many cultures. The system was later abolished in 1806.[25]
History of time measurement devices
Horizontal sundial in Taganrog
An old kitchen clock
Main article: History of timekeeping devices
See also: Clock
A large variety of devices have been invented to measure time. The study of these devices is called horology.
An Egyptian device that dates to c.1500 BC, similar in shape to a bent T-square, measured the passage of time from the shadow cast by its crossbar on a nonlinear rule. The T was oriented eastward in the mornings. At noon, the device was turned around so that it could cast its shadow in the evening direction.[26]
A sundial uses a gnomon to cast a shadow on a set of markings calibrated to the hour. The position of the shadow marks the hour in local time. The idea to separate the day into smaller parts is credited to Egyptians because of their sundials, which operated on a duodecimal system. The importance of the number 12 is due the number of lunar cycles in a year and the number of stars used to count the passage of night.[27]
The most precise timekeeping device of the ancient world was the water clock, or clepsydra, one of which was found in the tomb of Egyptian pharaoh Amenhotep I (1525–1504 BC). They could be used to measure the hours even at night, but required manual upkeep to replenish the flow of water. The Ancient Greeks and the people from Chaldea (southeastern Mesopotamia) regularly maintained timekeeping records as an essential part of their astronomical observations. Arab inventors and engineers in particular made improvements on the use of water clocks up to the Middle Ages.[28] In the 11th century, Chinese inventors and engineers invented the first mechanical clocks driven by an escapement mechanism.
The hourglass uses the flow of sand to measure the flow of time. They were used in navigation. Ferdinand Magellan used 18 glasses on each ship for his circumnavigation of the globe (1522).[29] Incense sticks and candles were, and are, commonly used to measure time in temples and churches across the globe. Waterclocks, and later, mechanical clocks, were used to mark the events of the abbeys and monasteries of the Middle Ages. Richard of Wallingford (1292–1336), abbot of St. Alban's abbey, famously built a mechanical clock as an astronomical orrery about 1330.[30][31] Great advances in accurate time-keeping were made by Galileo Galilei and especially Christiaan Huygens with the invention of pendulum driven clocks along with the invention of the minute hand by Jost Burgi.[32]
The English word clock probably comes from the Middle Dutch word klocke which, in turn, derives from the medieval Latin word clocca, which ultimately derives from Celtic and is cognate with French, Latin, and German words that mean bell. The passage of the hours at sea were marked by bells, and denoted the time (see ship's bell). The hours were marked by bells in abbeys as well as at sea.
Clocks can range from watches, to more exotic varieties such as the Clock of the Long Now. They can be driven by a variety of means, including gravity, springs, and various forms of electrical power, and regulated by a variety of means such as a pendulum.
The English word clock probably comes from the Middle Dutch word klocke which, in turn, derives from the medieval Latin word clocca, which ultimately derives from Celtic and is cognate with French, Latin, and German words that mean bell. The passage of the hours at sea were marked by bells, and denoted the time (see ship's bell). The hours were marked by bells in abbeys as well as at sea.
Chip-scale atomic clocks, such as this one unveiled in 2004, are expected to greatly improve GPS location.[33]
Clocks can range from watches, to more exotic varieties such as the Clock of the Long Now. They can be driven by a variety of means, including gravity, springs, and various forms of electrical power, and regulated by a variety of means such as a pendulum.
Alarm clocks first appeared in ancient Greece around 250 BC with a water clock that would set off a whistle. This idea was later mechanized by Levi Hutchins and Seth E. Thomas
A chronometer is a portable timekeeper that meets certain precision standards. Initially, the term was used to refer to the marine chronometer, a timepiece used to determine longitude by means of celestial navigation, a precision firstly achieved by John Harrison. More recently, the term has also been applied to the chronometer watch, a watch that meets precision standards set by the Swiss agency COSC.
The most accurate timekeeping devices are atomic clocks, which are accurate to seconds in many millions of years,[34] and are used to calibrate other clocks and timekeeping instruments. Atomic clocks use the frequency of electronic transitions in certain atoms to measure the second. One of the most common atoms used is caesium, most modern atomic clocks probe caesium with microwaves to determine the frequency of these electron vibrations.[35] Since 1967, the International System of Measurements bases its unit of time, the second, on the properties of caesium atoms. SI defines the second as 9,192,631,770 cycles of the radiation that corresponds to the transition between two electron spin energy levels of the ground state of the 133Cs atom.
Today, the Global Positioning System in coordination with the Network Time Protocol can be used to synchronize timekeeping systems across the globe.
Definitions and standards
The Mean Solar Time system defines the second as 1/86,400 of the mean solar day, which is the year-average of the solar day. The solar day is the time interval between two successive solar noons, i.e., the time interval between two successive passages of the Sun across the local meridian. The local meridian is an imaginary line that runs from celestial north pole to celestial south pole passing directly over the head of the observer. At the local meridian the Sun reaches its highest point on its daily arc across the sky.
In 1874 the British Association for the Advancement of Science introduced the CGS (centimetre/gramme/second system) combining fundamental units of length, mass and time. The second is "elastic", because tidal friction is slowing the earth's rotation rate. For use in calculating ephemerides of celestial motion, therefore, in 1952 astronomers introduced the "ephemeris second", currently defined as the fraction 1/31,556,925.9747 of the tropical year for 1900 January 0 at 12 hours ephemeris time.
The CGS system has been superseded by the Système international. The SI base unit for time is the SI second. The International System of Quantities, which incorporates the SI, also defines larger units of time equal to fixed integer multiples of one second (1 s), such as the minute, hour and day. These are not part of the SI, but may be used alongside the SI. Other units of time such as the month and the year are not equal to fixed multiples of 1 s, and instead exhibit significant variations in duration.
The official SI definition of the second is as follows: The second is the duration of 9,192,631,770 periods of the radiation corresponding to the transition between the two hyperfine levels of the ground state of the caesium 133 atom.
At its 1997 meeting, the CIPM affirmed that this definition refers to a caesium atom in its ground state at a temperature of 0 K.
The current definition of the second, coupled with the current definition of the metre, is based on the special theory of relativity, which affirms our spacetime to be a Minkowski space. The definition of the second in mean solar time, however, is unchanged.
World time
While in theory, the concept of a single worldwide universal time-scale may have been conceived of many centuries ago, in practicality the technical ability to create and maintain such a time-scale did not become possible until the mid-19th century. The timescale adopted was Greenwich Mean Time, created in 1847. A few countries have replaced it with Coordinated Universal Time, UTC.
History of the development of UTC
With the advent of the industrial revolution, a greater understanding and agreement on the nature of time itself became increasingly necessary and helpful. In 1847 in Britain, Greenwich Mean Time (GMT) was first created for use by the British railways, the British navy, and the British shipping industry. Using telescopes, GMT was calibrated to the mean solar time at the Royal Observatory, Greenwich in the UK.
As international commerce continued to increase throughout Europe, in order to achieve a more efficiently functioning modern society, an agreed upon, and highly accurate international standard of time measurement became necessary. In order to find or determine such a time-standard, three steps had to be followed:
An internationally agreed upon time-standard had to be defined.
This new time-standard then had to be consistently and accurately measured.
The new time-standard then had to be freely shared and distributed around the world.
The development of what is now known as UTC time came about historically as an effort which first began as a collaboration between 41 nations, officially agreed to and signed at the International Meridian Conference, in Washington D.C. in 1884. At this conference, the local mean solar time at the Royal Observatory, Greenwich in England was chosen to define the "universal day", counted from 0 hours at Greenwich mean midnight. This agreed with the civil Greenwich Mean Time used on the island of Great Britain since 1847. In contrast astronomical GMT began at mean noon, i.e. astronomical day X began at noon of civil day X. The purpose of this was to keep one night's observations under one date. The civil system was adopted as of 0 hours (civil) 1 January 1925. Nautical GMT began 24 hours before astronomical GMT, at least until 1805 in the Royal Navy, but persisted much later elsewhere because it was mentioned at the 1884 conference. In 1884, the Greenwich meridian was used for two-thirds of all charts and maps as their Prime Meridian.[42]
Among the 41 nations represented at the conference, the advanced time-technologies that had already come into use in Britain were fundamental components of the agreed upon method of arriving at a universal and agreed upon international time. In 1928 Greenwich Mean Time was rebranded for scientific purposes by the International Astronomical Union as Universal Time (UT). This was to avoid confusion with the previous system where the day had begun at noon. As the general public had always begun the day at midnight the timescale continued to be presented to them as Greenwich Mean Time. By 1956, universal time had been split into various versions – UT2, which smoothed for polar motion and seasonal effects, was presented to the public as Greenwich Mean Time. Later, UT1 (which smooths only for polar motion) became the default form of UT used by astronomers and hence the form used in navigation, sunrise and sunset and moonrise and moonset tables where the name Greenwich Mean Time continues to be employed. Greenwich Mean Time is also the preferred method of describing the timescale used by legislators. Even to the present day, UT is still based on an international telescopic system. Observations at the Greenwich Observatory itself ceased in 1954, though the location is still used as the basis for the coordinate system. Because the rotational period of Earth is not perfectly constant, the duration of a second would vary if calibrated to a telescope-based standard like GMT, where the second is defined as 1/86 400 of the mean solar day.
For the better part of the first century following the "International Meridian Conference," until 1960, the methods and definitions of time-keeping that had been laid out at the conference proved to be adequate to meet time tracking needs of science. Still, with the advent of the "electronic revolution" in the latter half of the 20th century, the technologies that had been available at the time of the Convention of the Metre proved to be in need of further refinement in order to meet the needs of the ever-increasing precision that the "electronic revolution" had begun to require.
The ephemeris second
An invariable second (the "ephemeris second") had been defined, use of which removed the errors in ephemerides resulting from the use of the variable mean solar second as the time argument. In 1960 this ephemeris second was made the basis of the "coordinated universal time" which was being derived from atomic clocks. It is a specified fraction of the mean tropical year as at 1900 and, being based on historical telescope observations, corresponds roughly to the mean solar second of the early nineteenth century.[43]
The SI second
In 1967 a further step was taken with the introduction of the SI second, essentially the ephemeris second as measured by atomic clocks and formally defined in atomic terms.[44] The SI second (Standard Internationale second) is based directly on the measurement of the atomic-clock observation of the frequency oscillation of caesium atoms. It is the basis of all atomic timescales, e.g. coordinated universal time, GPS time, International Atomic Time, etc. Atomic clocks do not measure nuclear decay rates, which is a common misconception, but rather measure a certain natural vibrational frequency of caesium-133.[45] Coordinated universal time is subject to one constraint which does not affect the other atomic timescales. As it has been adopted as the civil timescale by some countries (most countries have opted to retain mean solar time) it is not permitted to deviate from GMT by more than 0.9 second. This is achieved by the occasional insertion of a leap second.
Current application of UTC
Most countries use mean solar time. Australia, Canada (Quebec only), Colombia, France, Germany, New Zealand, Papua New Guinea (Bougainville only), Paraguay, Portugal, Switzerland, the United States and Venezuela use UTC. However, UTC is widely used by the scientific community in countries where mean solar time is official. UTC time is based on the SI second, which was first defined in 1967, and is based on the use of atomic clocks. Some other less used but closely related time-standards include International Atomic Time (TAI), Terrestrial Time, and Barycentric Dynamical Time.
Between 1967 and 1971, UTC was periodically adjusted by fractional amounts of a second in order to adjust and refine for variations in mean solar time, with which it is aligned. After 1 January 1972, UTC time has been defined as being offset from atomic time by a whole number of seconds, changing only when a leap second is added to keep radio-controlled clocks synchronized with the rotation of the Earth.
The Global Positioning System also broadcasts a very precise time signal worldwide, along with instructions for converting GPS time to UTC. GPS-time is based on, and regularly synchronized with or from, UTC-time.
Earth is split up into a number of time zones. Most time zones are exactly one hour apart, and by convention compute their local time as an offset from GMT. For example, time zones at sea are based on GMT. In many locations (but not at sea) these offsets vary twice yearly due to daylight saving time transitions.
Philosophy
Main articles: Philosophy of space and time and Temporal finitism
Time's mortal aspect is personified in this bronze statue by Charles van der Stappen.
Two distinct viewpoints on time divide many prominent philosophers. One view is that time is part of the fundamental structure of the universe, a dimension in which events occur in sequence. Sir Isaac Newton subscribed to this realist view, and hence it is sometimes referred to as Newtonian time.[16] An opposing view is that time does not refer to any kind of actually existing dimension that events and objects "move through", nor to any entity that "flows", but that it is instead an intellectual concept (together with space and number) that enables humans to sequence and compare events.[56] This second view, in the tradition of Gottfried Leibniz[17] and Immanuel Kant,[18][19] holds that space and time "do not exist in and of themselves, but ... are the product of the way we represent things", because we can know objects only as they appear to us.
Furthermore, it may be that there is a subjective component to time, but whether or not time itself is "felt", as a sensation, or is a judgment, is a matter of debate.[2][6][7][57][58]
The Vedas, the earliest texts on Indian philosophy and Hindu philosophy dating back to the late 2nd millennium BC, describe ancient Hindu cosmology, in which the universe goes through repeated cycles of creation, destruction and rebirth, with each cycle lasting 4,320 million years.[59] Ancient Greek philosophers, including Parmenides and Heraclitus, wrote essays on the nature of time.[60] Plato, in the Timaeus, identified time with the period of motion of the heavenly bodies. Aristotle, in Book IV of his Physica defined time as 'number of movement in respect of the before and after'.[61]
In Book 11 of his Confessions, St. Augustine of Hippo ruminates on the nature of time, asking, "What then is time? If no one asks me, I know: if I wish to explain it to one that asketh, I know not." He begins to define time by what it is not rather than what it is,[62] an approach similar to that taken in other negative definitions. However, Augustine ends up calling time a "distention" of the mind (Confessions 11.26) by which we simultaneously grasp the past in memory, the present by attention, and the future by expectation.
This view is shared by Abrahamic faiths as they believe time started by creation, therefore the only thing being infinite is God and everything else, including time, is finite.
Isaac Newton believed in absolute space and absolute time; Leibniz believed that time and space are relational.[63] The differences between Leibniz's and Newton's interpretations came to a head in the famous Leibniz–Clarke correspondence.
Time is not an empirical concept. For neither co-existence nor succession would be perceived by us, if the representation of time did not exist as a foundation a priori. Without this presupposition we could not represent to ourselves that things exist together at one and the same time, or at different times, that is, contemporaneously, or in succession.
Immanuel Kant, Critique of Pure Reason (1781), trans. Vasilis Politis (London: Dent., 1991), p.54.
Immanuel Kant, in the Critique of Pure Reason, described time as an a priori intuition that allows us (together with the other a priori intuition, space) to comprehend sense experience.[64] With Kant, neither space nor time are conceived as substances, but rather both are elements of a systematic mental framework that necessarily structures the experiences of any rational agent, or observing subject. Kant thought of time as a fundamental part of an abstract conceptual framework, together with space and number, within which we sequence events, quantify their duration, and compare the motions of objects. In this view, time does not refer to any kind of entity that "flows," that objects "move through," or that is a "container" for events. Spatial measurements are used to quantify the extent of and distances between objects, and temporal measurements are used to quantify the durations of and between events. Time was designated by Kant as the purest possible schema of a pure concept or category.
Henri Bergson believed that time was neither a real homogeneous medium nor a mental construct, but possesses what he referred to as Duration. Duration, in Bergson's view, was creativity and memory as an essential component of reality.[65]
According to Martin Heidegger we do not exist inside time, we are time. Hence, the relationship to the past is a present awareness of having been, which allows the past to exist in the present. The relationship to the future is the state of anticipating a potential possibility, task, or engagement. It is related to the human propensity for caring and being concerned, which causes "being ahead of oneself" when thinking of a pending occurrence. Therefore, this concern for a potential occurrence also allows the future to exist in the present. The present becomes an experience, which is qualitative instead of quantitative. Heidegger seems to think this is the way that a linear relationship with time, or temporal existence, is broken or transcended.[66] We are not stuck in sequential time. We are able to remember the past and project into the future – we have a kind of random access to our representation of temporal existence; we can, in our thoughts, step out of (ecstasis) sequential time.
Time as "unreal"
In 5th century BC Greece, Antiphon the Sophist, in a fragment preserved from his chief work On Truth, held that: "Time is not a reality (hypostasis), but a concept (noêma) or a measure (metron)." Parmenides went further, maintaining that time, motion, and change were illusions, leading to the paradoxes of his follower Zeno.[68] Time as an illusion is also a common theme in Buddhist thought.[69][70]
J. M. E. McTaggart's 1908 The Unreality of Time argues that, since every event has the characteristic of being both present and not present (i.e., future or past), that time is a self-contradictory idea (see also The flow of time).
These arguments often center on what it means for something to be unreal. Modern physicists generally believe that time is as real as space – though others, such as Julian Barbour in his book The End of Time, argue that quantum equations of the universe take their true form when expressed in the timeless realm containing every possible now or momentary configuration of the universe, called 'platonia' by Barbour.[71]
A modern philosophical theory called presentism views the past and the future as human-mind interpretations of movement instead of real parts of time (or "dimensions") which coexist with the present. This theory rejects the existence of all direct interaction with the past or the future, holding only the present as tangible. This is one of the philosophical arguments against time travel. This contrasts with eternalism (all time: present, past and future, is real) and the growing block theory (the present and the past are real, but the future is not).
Physical Definition
Until Einstein's reinterpretation of the physical concepts associated with time and space, time was considered to be the same everywhere in the universe, with all observers measuring the same time interval for any event.[72] Non-relativistic classical mechanics is based on this Newtonian idea of time.
Einstein, in his special theory of relativity,[73] postulated the constancy and finiteness of the speed of light for all observers. He showed that this postulate, together with a reasonable definition for what it means for two events to be simultaneous, requires that distances appear compressed and time intervals appear lengthened for events associated with objects in motion relative to an inertial observer.
The theory of special relativity finds a convenient formulation in Minkowski spacetime, a mathematical structure that combines three dimensions of space with a single dimension of time. In this formalism, distances in space can be measured by how long light takes to travel that distance, e.g., a light-year is a measure of distance, and a meter is now defined in terms of how far light travels in a certain amount of time. Two events in Minkowski spacetime are separated by an invariant interval, which can be either space-like, light-like, or time-like. Events that have a time-like separation cannot be simultaneous in any frame of reference, there must be a temporal component (and possibly a spatial one) to their separation. Events that have a space-like separation will be simultaneous in some frame of reference, and there is no frame of reference in which they do not have a spatial separation. Different observers may calculate different distances and different time intervals between two events, but the invariant interval between the events is independent of the observer (and his or her velocity).
Classical mechanics
In non-relativistic classical mechanics, Newton's concept of "relative, apparent, and common time" can be used in the formulation of a prescription for the synchronization of clocks. Events seen by two different observers in motion relative to each other produce a mathematical concept of time that works sufficiently well for describing the everyday phenomena of most people's experience. In the late nineteenth century, physicists encountered problems with the classical understanding of time, in connection with the behavior of electricity and magnetism. Einstein resolved these problems by invoking a method of synchronizing clocks using the constant, finite speed of light as the maximum signal velocity. This led directly to the result that observers in motion relative to one another measure different elapsed times for the same event.
Spacetime
Main article: Spacetime
Time has historically been closely related with space, the two together merging into spacetime in Einstein's special relativity and general relativity. According to these theories, the concept of time depends on the spatial reference frame of the observer, and the human perception as well as the measurement by instruments such as clocks are different for observers in relative motion. For example, if a spaceship carrying a clock flies through space at (very nearly) the speed of light, its crew does not notice a change in the speed of time on board their vessel because everything traveling at the same speed slows down at the same rate (including the clock, the crew's thought processes, and the functions of their bodies). However, to a stationary observer watching the spaceship fly by, the spaceship appears flattened in the direction it is traveling and the clock on board the spaceship appears to move very slowly.
On the other hand, the crew on board the spaceship also perceives the observer as slowed down and flattened along the spaceship's direction of travel, because both are moving at very nearly the speed of light relative to each other. Because the outside universe appears flattened to the spaceship, the crew perceives themselves as quickly traveling between regions of space that (to the stationary observer) are many light years apart. This is reconciled by the fact that the crew's perception of time is different from the stationary observer's; what seems like seconds to the crew might be hundreds of years to the stationary observer. In either case, however, causality remains unchanged: the past is the set of events that can send light signals to an entity and the future is the set of events to which an entity can send light signals
Time dilation
Relativity of simultaneity: Event B is simultaneous with A in the green reference frame, but it occurred before in the blue frame, and occurs later in the red frame.
Main article: Time dilation
Einstein showed in his thought experiments that people travelling at different speeds, while agreeing on cause and effect, measure different time separations between events, and can even observe different chronological orderings between non-causally related events. Though these effects are typically minute in the human experience, the effect becomes much more pronounced for objects moving at speeds approaching the speed of light. Subatomic particles exist for a well known average fraction of a second in a lab relatively at rest, but when travelling close to the speed of light they are measured to travel farther and exist for much longer than when at rest. According to the special theory of relativity, in the high-speed particle's frame of reference, it exists, on the average, for a standard amount of time known as its mean lifetime, and the distance it travels in that time is zero, because its velocity is zero. Relative to a frame of reference at rest, time seems to "slow down" for the particle. Relative to the high-speed particle, distances seem to shorten. Einstein showed how both temporal and spatial dimensions can be altered (or "warped") by high-speed motion.
Einstein (The Meaning of Relativity): "Two events taking place at the points A and B of a system K are simultaneous if they appear at the same instant when observed from the middle point, M, of the interval AB. Time is then defined as the ensemble of the indications of similar clocks, at rest relative to K, which register the same simultaneously."
Einstein wrote in his book, Relativity, that simultaneity is also relative, i.e., two events that appear simultaneous to an observer in a particular inertial reference frame need not be judged as simultaneous by a second observer in a different inertial frame of reference.
Relativistic time versus Newtonian time
Views of spacetime along the world line of a rapidly accelerating observer in a relativistic universe. The events ("dots") that pass the two diagonal lines in the bottom half of the image (the past light cone of the observer in the origin) are the events visible to the observer.
The animations visualise the different treatments of time in the Newtonian and the relativistic descriptions. At the heart of these differences are the Galilean and Lorentz transformations applicable in the Newtonian and relativistic theories, respectively.
In the figures, the vertical direction indicates time. The horizontal direction indicates distance (only one spatial dimension is taken into account), and the thick dashed curve is the spacetime trajectory ("world line") of the observer. The small dots indicate specific (past and future) events in spacetime.
The slope of the world line (deviation from being vertical) gives the relative velocity to the observer. Note how in both pictures the view of spacetime changes when the observer accelerates.
In the Newtonian description these changes are such that time is absolute:[77] the movements of the observer do not influence whether an event occurs in the 'now' (i.e., whether an event passes the horizontal line through the observer).
However, in the relativistic description the observability of events is absolute: the movements of the observer do not influence whether an event passes the "light cone" of the observer. Notice that with the change from a Newtonian to a relativistic description, the concept of absolute time is no longer applicable: events move up-and-down in the figure depending on the acceleration of the observer.
Time appears to have a direction – the past lies behind, fixed and immutable, while the future lies ahead and is not necessarily fixed. Yet for the most part the laws of physics do not specify an arrow of time, and allow any process to proceed both forward and in reverse. This is generally a consequence of time being modelled by a parameter in the system being analysed, where there is no "proper time": the direction of the arrow of time is sometimes arbitrary. Examples of this include the cosmological arrow of time, which points away from the Big Bang, CPT symmetry, and the radiative arrow of time, caused by light only travelling forwards in time (see light cone). In particle physics, the violation of CP symmetry implies that there should be a small counterbalancing time asymmetry to preserve CPT symmetry as stated above. The standard description of measurement in quantum mechanics is also time asymmetric (see Measurement in quantum mechanics). The second law of thermodynamics states that entropy must increase over time (see Entropy). This can be in either direction – Brian Greene theorizes that, according to the equations, the change in entropy occurs symmetrically whether going forward or backward in time. So entropy tends to increase in either direction, and our current low-entropy universe is a statistical aberration, in the similar manner as tossing a coin often enough that eventually heads will result ten times in a row. However, this theory is not supported empirically in local experiment.[78]
''']  # nopep8
    ]}


class TestLog(TestBase):
    title = 'Test log'

    @default_test_setup(1, compression=True, optimize_interval=10)
    async def run(self):
        await self.client0.connect()

        n = 0
        for p in DATA.values():
            n += len(p)

        self.assertEqual(
            await self.client0.insert(DATA),
            {'success_msg': 'Successfully inserted {} point(s).'.format(n)})

        await self.test_data()

        # wait for optimization
        await asyncio.sleep(30)

        await self.test_data()

        self.client0.close()

        # stop and restart
        result = await self.server0.stop()
        self.assertTrue(result)

        await self.server0.start(sleep=20)

        await self.client0.connect()

        await self.test_data()

    async def test_data(self):
        self.assertEqual(
            await self.client0.query('select * from "log"'),
            {'log': DATA['log']})

        self.assertEqual(
            await self.client0.query('select * from "utf16"'),
            {'utf16': DATA['utf16']})

        self.assertEqual(
            await self.client0.query('select * from "long_log"'),
            {'long_log': DATA['long_log']})


if __name__ == '__main__':
    parse_args()
    run_test(TestLog())
