Generate a full datablock containing all timepoints
434040
def _singleframe_to_block(grouped_dicoms):
    
    # For each slice / mosaic create a data volume block
    data_blocks = []
    for index in range(0, len(grouped_dicoms)):
        logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms)))
        current_block = _stack_to_block(grouped_dicoms[index])
        current_block = current_block[:, :, :, numpy.newaxis]
        data_blocks.append(current_block)

    try:
        full_block = numpy.concatenate(data_blocks, axis=3)
    except:
        traceback.print_exc()
        raise ConversionError("MISSING_DICOM_FILES")

    # Apply the rescaling if needed
    common.apply_scaling(full_block, grouped_dicoms[0][0])

    return full_block
745439
def _get_input_data(self, var, start_date, end_date):
        """"""
        logging.info(self._print_verbose("Getting input data:", var))

        if isinstance(var, (float, int)):
            return var
        else:
            cond_pfull = ((not hasattr(self, internal_names.PFULL_STR))
                          and var.def_vert and
                          self.dtype_in_vert == internal_names.ETA_STR)
            data = self.data_loader.recursively_compute_variable(
                var, start_date, end_date, self.time_offset, self.model,
                **self.data_loader_attrs)
            name = data.name
            data = self._add_grid_attributes(data.to_dataset(name=data.name))
            data = data[name]
            if cond_pfull:
                try:
                    self.pfull_coord = data[internal_names.PFULL_STR]
                except KeyError:
                    pass
            # Force all data to be at full pressure levels, not half levels.
            bool_to_pfull = (self.dtype_in_vert == internal_names.ETA_STR and
                             var.def_vert == internal_names.PHALF_STR)
            if bool_to_pfull:
                data = utils.vertcoord.to_pfull_from_phalf(data,
                                                           self.pfull_coord)
        if var.def_time:
            # Restrict to the desired dates within each year.
            if self.dtype_in_time != 'av':
                return self._to_desired_dates(data)
        else:
            return data
550894
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs):
    """"""
    if isinstance(headers, dict):
        attrs = headers.keys()
        # if mapping is not specified keep original
        names = [
            key if value is None else value for key, value in headers.items()
        ]
    else:
        attrs = names = headers
    table = [(
        format_cell(cell, datetime_fmt=datetime_fmt)
        for cell in attrgetter(*attrs)(c)
    ) for c in collection]
    return tblte(table, headers=[h.upper() for h in names], **kwargs)
949469
def goto_time(timeval):
    '''

    '''
    i = bisect.bisect(viewer.frame_times, timeval * 1000)
    goto_frame(i)
1182723
def gen_blocks(output, ascii_props=False, append=False, prefix=""):
    """"""

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        f.write('%s_blocks = {' % prefix)
        no_block = []
        last = -1

        max_range = MAXASCII if ascii_props else MAXUNICODE
        formatter = bytesformat if ascii_props else uniformat

        with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'Blocks.txt'), 'r', 'utf-8') as uf:
            for line in uf:
                if not line.startswith('#'):
                    data = line.split(';')
                    if len(data) < 2:
                        continue
                    block = [int(i, 16) for i in data[0].strip().split('..')]
                    if block[0] > last + 1:
                        if (last + 1) <= max_range:
                            endval = block[0] - 1 if (block[0] - 1) < max_range else max_range
                            no_block.append((last + 1, endval))
                    last = block[1]
                    name = format_name(data[1])
                    inverse_range = []
                    if block[0] > max_range:
                        if ascii_props:
                            f.write('\n    "%s": "",' % name)
                            f.write('\n    "^%s": "%s-%s",' % (name, formatter(0), formatter(max_range)))
                        continue
                    if block[0] > 0:
                        inverse_range.append("%s-%s" % (formatter(0), formatter(block[0] - 1)))
                    if block[1] < max_range:
                        inverse_range.append("%s-%s" % (formatter(block[1] + 1), formatter(max_range)))
                    f.write('\n    "%s": "%s-%s",' % (name, formatter(block[0]), formatter(block[1])))
                    f.write('\n    "^%s": "%s",' % (name, ''.join(inverse_range)))
            if last < max_range:
                if (last + 1) <= max_range:
                    no_block.append((last + 1, max_range))
            last = -1
            no_block_inverse = []
            if not no_block:
                no_block_inverse.append((0, max_range))
            else:
                for piece in no_block:
                    if piece[0] > last + 1:
                        no_block_inverse.append((last + 1, piece[0] - 1))
                    last = piece[1]
            for block, name in ((no_block, 'noblock'), (no_block_inverse, '^noblock')):
                f.write('\n    "%s": "' % name)
                for piece in block:
                    if piece[0] == piece[1]:
                        f.write(formatter(piece[0]))
                    else:
                        f.write("%s-%s" % (formatter(piece[0]), formatter(piece[1])))
                f.write('",')
            f.write('\n}\n')
226657
def to_html
      time_header, rows = '<th></th>', Array.new
      end_time = Time.new(2013, 1, 1, 21, 0, 0)

      # make the time row
      @time = Time.new(2013, 1, 1, 9, 0, 0)
      while @time < end_time
        time_header += "<th>#{@time.strftime("%-k:%M")}</th>"
        @time += 900
      end

      #make each day row
      (0..4).each do |day|
        classes = @timetable.classes_for_day(day)
        rows << day_row(day, classes)
      end

      rows_str, id_str = '', "id=\"#{@timetable.name}\""
      rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" }

      %Q{
        <!DOCTYPE html>
        <html>
        <head>
          <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title>
          <style>#{build_css}</style>
        </head>
        <body>
          <h3>#{@timetable.name}</h3>
          <table #{id_str if @timetable.name}>
            <tr id="time">#{time_header}</tr>
            #{rows_str}
          </table>
        </body>
        </html>
      }
    end
1087332
def _get_all_data(self, start_date, end_date):
        """"""
        return [self._get_input_data(var, start_date, end_date)
                for var in _replace_pressure(self.variables,
                                             self.dtype_in_vert)]
1177431
def _get_pltdotstrs(self, hdrgos_usr, **kws):
        """"""
        import datetime
        import timeit
        dotstrs_all = []
        tic = timeit.default_timer()
        # Loop through GO groups. Each group of GOs is formed under a single "header GO"
        hdrgo2usrgos, go2obj = self._get_plt_data(hdrgos_usr)
        # get dot strings with _get_dotstrs_curs
        for hdrgo, usrgos in hdrgo2usrgos.items():
            dotstrs_cur = self._get_dotgraphs(
                hdrgo, usrgos,
                pltargs=PltGroupedGosArgs(self.grprobj, **kws),
                go2parentids=get_go2parents_go2obj(go2obj))
            dotstrs_all.extend(dotstrs_cur)
        sys.stdout.write("\nElapsed HMS: {HMS} to write ".format(
            HMS=str(datetime.timedelta(seconds=(timeit.default_timer()-tic)))))
        sys.stdout.write("{P:5,} GO DAG plots for {H:>5,} GO grouping headers\n".format(
            H=len(hdrgo2usrgos), P=len(dotstrs_all)))
        return sorted(set(dotstrs_all))
657580
def _write(self, session, openFile, replaceParamFile):
        
        # Retrieve all time series
        timeSeries = self.timeSeries

        # Num TimeSeries
        numTS = len(timeSeries)

        # Transform into list of dictionaries for pivot tool
        valList = []

        for tsNum, ts in enumerate(timeSeries):
            values = ts.values
            for value in values:
                valDict = {'time': value.simTime,
                           'tsNum': tsNum,
                           'value': value.value}
                valList.append(valDict)

        # Use pivot function (from lib) to pivot the values into
        # a format that is easy to write.
        result = pivot(valList, ('time',), ('tsNum',), 'value')

        # Write lines
        for line in result:

            valString = ''
            # Compile value string
            for n in range(0, numTS):
                val = '%.6f' % line[(n,)]
                valString = '%s%s%s' % (
                    valString,
                    ' ' * (13 - len(str(val))),  # Fancy spacing trick
                    val)

            openFile.write('   %.8f%s\n' % (line['time'], valString))
428522
def mktime(self, **kwargs):
        
        kwargs_copy = self.base_dict.copy()
        kwargs_copy.update(**kwargs)
        kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
        kwargs_copy['component'] = kwargs.get(
            'component', self.component(**kwargs))
        self._replace_none(kwargs_copy)        
        localpath = NameFactory.mktime_format.format(**kwargs_copy)
        if kwargs.get('fullpath', False):
            return self.fullpath(localpath=localpath)
        return localpath
870330
function getTimestamp(rawTx) {
  const timestamp = get(
    rawTx,
    ['meta', 'metronome', 'export', 'blockTimestamp'],
    null
  )
  return timestamp ? Number(timestamp) : null
}
152112
private float[] generateParticleTimeStamps(float totalTime)
    {
        float timeStamps[] = new float[mEmitRate * 2];

        if ( burstMode ) {
            for (int i = 0; i < mEmitRate * 2; i += 2) {
                timeStamps[i] = totalTime;
                timeStamps[i + 1] = 0;
            }
        }
        else {
            for (int i = 0; i < mEmitRate * 2; i += 2) {
                timeStamps[i] = totalTime + mRandom.nextFloat();
                timeStamps[i + 1] = 0;
            }
        }
        return timeStamps;

    }
952331
function createTimeline(numEvents, baseIndex) {
    if (numEvents === undefined) {
        numEvents = 3;
    }
    if (baseIndex === undefined) {
        baseIndex = 1;
    }

    // XXX: this is a horrid hack
    const timelineSet = { room: { roomId: ROOM_ID }};
    timelineSet.room.getUnfilteredTimelineSet = function() {
        return timelineSet;
    };

    const timeline = new EventTimeline(timelineSet);

    // add the events after the baseIndex first
    addEventsToTimeline(timeline, numEvents - baseIndex, false);

    // then add those before the baseIndex
    addEventsToTimeline(timeline, baseIndex, true);

    expect(timeline.getBaseIndex()).toEqual(baseIndex);
    return timeline;
}
199461
def _load_blocks(self, blocks: List[Tuple[Key, Any]]) -> List[TimeAggregate]:
        
        return [
            TypeLoader.load_item(self._schema.source.type)(self._schema.source, self._identity,
                                                           EvaluationContext()).run_restore(block)
            for (_, block) in blocks
        ]
246329
def read_cz_lsm_time_stamps(fd, byte_order):
    """"""
    size, count = struct.unpack(byte_order+'II', fd.read(8))
    if size != (8 + 8 * count):
        raise ValueError("lsm_time_stamps block is too short")
    return struct.unpack(('%s%dd' % (byte_order, count)),
                         fd.read(8*count))
647297
def clean_data(self):
        """"""

        # TODO: Do the same for duration/timedelta
        if "timestamp" in self:
            self._check_timestamp()
            if type(self["timestamp"]) == list:
                def datetime_to_string(dt):
                    return fmt_datetime(dt) if type(dt) == datetime else dt
                self["timestamp"] = list(map(datetime_to_string, self["timestamp"]))
            elif type(self["timestamp"]) == datetime:
                self["timestamp"] = fmt_datetime(self["timestamp"])

        # FIXME: Support list of volumes
        if "volume" in self:
            self["volume"]["unit"] = self["volume"]["unit"].replace("l", "L")

        # FIXME: Support list of weights
        if "weight" in self:
            # Zenobase uses "ug" for micrograms
            if self["weight"]["unit"] in ["mcg", "µg"]:
                self["weight"]["unit"] = "ug"
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