Returns
        -------
        sessions : DatetimeIndex
           All session labels (unioning the range for all assets) which the
           reader can provide.
503871
def sessions(self):
        
        return pd.to_datetime(
            reduce(
                np.union1d,
                (reader.dates for reader in self._readers.values()),
            ),
            utc=True,
        )
1198329
def values(self):
        
        all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
        return all_values
579248
def configure_timeindex(self):
        

        try:

            ormclass = self._mapped['TempResolution']
            if self.version:
                tr = self.session.query(ormclass).filter(
                    ormclass.temp_id == self.temp_id).filter(
                        ormclass.version == self.version).one()
            else:
                tr = self.session.query(ormclass).filter(
                    ormclass.temp_id == self.temp_id).one()

        except (KeyError, NoResultFound):
            print('temp_id %s does not exist.' % self.temp_id)

        timeindex = pd.DatetimeIndex(start=tr.start_time,
                                     periods=tr.timesteps,
                                     freq=tr.resolution)

        self.timeindex = timeindex[self.start_snapshot - 1: self.end_snapshot]
        """ pandas.tseries.index.DateTimeIndex :
                Index of snapshots or timesteps. """
9544
def newlogins(sessions):
    
    if not sessions:
        return [], []
    users = {}
    dates = {}

    for session in sessions:
        user = session.user
        # time value is discarded to aggregate on days only
        date = session.started_at.strftime("%Y/%m/%d")
        # keep the info only it's the first time we encounter a user
        if user not in users:
            users[user] = date
            # build the list of users on a given day
            if date not in dates:
                dates[date] = [user]
            else:
                dates[date].append(user)

    data = []
    total = []
    previous = 0
    for date in sorted(dates.keys()):
        # print u"{} : {}".format(date, len(dates[date]))
        date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d"))
        data.append({"x": date_epoch, "y": len(dates[date])})
        previous += len(dates[date])
        total.append({"x": date_epoch, "y": previous})

    return data, total
1099298
def get_assets(dstore):
    
    assetcol = dstore['assetcol']
    tagnames = sorted(assetcol.tagnames)
    tag = {t: getattr(assetcol.tagcol, t) for t in tagnames}
    dtlist = [('asset_ref', (bytes, 100))]
    for tagname in tagnames:
        dtlist.append((tagname, (bytes, 100)))
    dtlist.extend([('lon', F32), ('lat', F32)])
    asset_data = []
    for aref, a in zip(assetcol.asset_refs, assetcol.array):
        tup = tuple(b'"%s"' % tag[t][a[t]].encode('utf-8') for t in tagnames)
        asset_data.append((aref,) + tup + (a['lon'], a['lat']))
    return numpy.array(asset_data, dtlist)
538678
def get_index_labels(self, targets):
        
        target_ind = self.graph.vs.select(name_in=targets).indices
        rest_ind = self.graph.vs.select(name_notin=targets).indices
        label_mappings = {i: 1 for i in target_ind}
        label_mappings.update({i: 0 for i in rest_ind})
        return label_mappings
1355871
def session_info(self, session):
        
        _, sp_hkey = self._keygen(session)
        picked_event = self.r.hgetall(sp_hkey)
        event = {s(k): pickle.loads(v) for k, v in picked_event.items()}
        return event
1292635
def sessions(session):
    
    active_sessions = session.get_sessions()
    if not active_sessions:
        click.echo('(No active sessions)')
        return
    for active_session in active_sessions:
        click.echo(active_session)
786319
def _convert_asset_timestamp_fields(dict_):
    
    for key in _asset_timestamp_fields & viewkeys(dict_):
        value = pd.Timestamp(dict_[key], tz='UTC')
        dict_[key] = None if isnull(value) else value
    return dict_
1316902
def _get_history_minute_window(self, assets, end_dt, bar_count,
                                   field_to_use):
        
        # get all the minutes for this window
        try:
            minutes_for_window = self.trading_calendar.minutes_window(
                end_dt, -bar_count
            )
        except KeyError:
            self._handle_minute_history_out_of_bounds(bar_count)

        if minutes_for_window[0] < self._first_trading_minute:
            self._handle_minute_history_out_of_bounds(bar_count)

        asset_minute_data = self._get_minute_window_data(
            assets,
            field_to_use,
            minutes_for_window,
        )

        return pd.DataFrame(
            asset_minute_data,
            index=minutes_for_window,
            columns=assets
        )
704093
def validate_session(self, session, latest_only=False):
        
        if latest_only:
            if session != self.metadata['terms'][-1]['sessions'][-1]:
                raise NoDataForPeriod(session)

        for t in self.metadata['terms']:
            if session in t['sessions']:
                return True
        raise NoDataForPeriod(session)
1367873
def for_each_time_range(t)
      RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts|
        yield(ts)
      end
    end
343077
def get_splits_in_period(self, start: Datum, end: Datum) -> List[Split]:
        
        # from gnucash_portfolio.lib import generic

        query = (
            self.book.session.query(Split)
            .join(Transaction)
            .filter(Split.account == self.account,
                    Transaction.post_date >= start.value.date(),
                    Transaction.post_date <= end.value.date()
                    )
        )
        # sql = generic.get_sql(query)
        return query.all()
715992
def labels(self):
        
        if self._labels is None:
            self._labels = map(self.labelFormat().format, self.values())
        return self._labels
699317
def fetch(self):
        
        tlen = self.end - self.start
        dfs = []

        # Build list of all dates within the given range
        lrange = [x for x in (self.start + timedelta(n)
                              for n in range(tlen.days))]

        mrange = []
        for dt in lrange:
            if datetime(dt.year, dt.month, 1) not in mrange:
                mrange.append(datetime(dt.year, dt.month, 1))
        lrange = mrange

        for date in lrange:
            self.curr_date = date
            tdf = super(MonthlySummaryReader, self).fetch()

            # We may not return data if this was a weekend/holiday:
            if self.output_format == 'pandas':
                if not tdf.empty:
                    tdf['date'] = date.strftime(self.date_format)
            dfs.append(tdf)

        # We may not return any data if we failed to specify useful parameters:
        if self.output_format == 'pandas':
            result = pd.concat(dfs) if len(dfs) > 0 else pd.DataFrame()
            return result.set_index('date')
        else:
            return dfs
770035
def get_annotated_data_x_y(timestamps, data, lbls):
        

        timestamps = np.array(timestamps)

        timestamp_step = timestamps[3]-timestamps[2]
        current_new_timestamp = 0.0
        new_timestamps = []

        X = None
        Y = []
        classes = []

        for i in range(0, len(timestamps)):

            for lbl in lbls:
                if lbl.start_seconds <= timestamps[i] < lbl.end_seconds:
                    if X is None:
                        X = data[i, :]
                    else:
                        X = np.vstack((X, data[i, :]))
                    Y.append(lbl.label)
                    new_timestamps.append(current_new_timestamp)
                    current_new_timestamp += timestamp_step

                    if lbl.label not in classes:
                        classes.append(lbl.label)

        return X, Y, classes, new_timestamps
1161718
def ReadAllClientGraphSeries(
      self,
      client_label,
      report_type,
      time_range = None,
      cursor=None):
    """"""
    query = """
      SELECT UNIX_TIMESTAMP(timestamp), graph_series
      FROM client_report_graphs
      WHERE client_label = %s AND report_type = %s
    """
    args = [client_label, report_type.SerializeToDataStore()]

    if time_range is not None:
      query += "AND `timestamp` BETWEEN FROM_UNIXTIME(%s) AND FROM_UNIXTIME(%s)"
      args += [
          mysql_utils.RDFDatetimeToTimestamp(time_range.start),
          mysql_utils.RDFDatetimeToTimestamp(time_range.end)
      ]

    cursor.execute(query, args)
    results = {}
    for timestamp, raw_series in cursor.fetchall():
      # TODO(hanuszczak): pytype does not seem to understand overloads, so it is
      # not possible to correctly annotate `TimestampToRDFDatetime`.
      timestamp = cast(rdfvalue.RDFDatetime,
                       mysql_utils.TimestampToRDFDatetime(timestamp))

      series = rdf_stats.ClientGraphSeries.FromSerializedString(raw_series)
      results[timestamp] = series
    return results