Given arrays of opens and closes, both in nanoseconds,
    return an array of each minute between the opens and closes.
165416
def compute_all_minutes(opens_in_ns, closes_in_ns):
    
    deltas = closes_in_ns - opens_in_ns

    # + 1 because we want 390 mins per standard day, not 389
    daily_sizes = (deltas // NANOSECONDS_PER_MINUTE) + 1
    num_minutes = daily_sizes.sum()

    # One allocation for the entire thing. This assumes that each day
    # represents a contiguous block of minutes.
    pieces = []

    for open_, size in zip(opens_in_ns, daily_sizes):
        pieces.append(
            np.arange(open_,
                      open_ + size * NANOSECONDS_PER_MINUTE,
                      NANOSECONDS_PER_MINUTE)
        )

    out = np.concatenate(pieces).view('datetime64[ns]')
    assert len(out) == num_minutes
    return out
173017
def _sub_datetime_arraylike(self, other):
        """"""
        if len(self) != len(other):
            raise ValueError("cannot add indices of unequal length")

        if isinstance(other, np.ndarray):
            assert is_datetime64_dtype(other)
            other = type(self)(other)

        if not self._has_same_tz(other):
            # require tz compat
            raise TypeError("{cls} subtraction must have the same "
                            "timezones or no timezones"
                            .format(cls=type(self).__name__))

        self_i8 = self.asi8
        other_i8 = other.asi8
        arr_mask = self._isnan | other._isnan
        new_values = checked_add_with_arr(self_i8, -other_i8,
                                          arr_mask=arr_mask)
        if self._hasnans or other._hasnans:
            new_values[arr_mask] = iNaT
        return new_values.view('timedelta64[ns]')
309685
def query(self, time_indices):
    
    if self._disposed:
      raise ValueError(
          'Cannot query: this _WatchStore instance is already disposed')
    if not isinstance(time_indices, (tuple, list)):
      time_indices = [time_indices]
    output = []
    for time_index in time_indices:
      if isinstance(self._data[time_index], _TensorValueDiscarded):
        output.append(None)
      else:
        data_item = self._data[time_index]
        if (hasattr(data_item, 'dtype') and
            tensor_helper.translate_dtype(data_item.dtype) == 'string'):
          _, _, data_item = tensor_helper.array_view(data_item)
          data_item = np.array(
              tensor_helper.process_buffers_for_display(data_item),
              dtype=np.object)
        output.append(data_item)

    return output
170148
function getHrTimeDurationInMs (startTime, endTime) {
    if (startTime === null || endTime === null) {
        return null;
    }

    var secondDiff = endTime[0] - startTime[0];
    var nanoSecondDiff = endTime[1] - startTime[1];
    var diffInNanoSecond = secondDiff * NS_PER_SEC + nanoSecondDiff;

    return Math.round(diffInNanoSecond / MS_PER_NS);
}
698258
def rnd_date_array(self, size, start=date(1970, 1, 1), end=date.today()):
        
        if isinstance(start, string_types):
            start = self.str2date(start)
        if isinstance(end, string_types):
            end = self.str2date(end)
        if start > end:
            raise ValueError("start time has to be earlier than end time")

        return self.randn(size, self._rnd_date, start, end)
602906
private void findSentenceIntervals(JCas jcas){
		HashSet<Timex3Interval> timexesToRemove = new HashSet<Timex3Interval>();
		
		FSIterator iterSentence = jcas.getAnnotationIndex(Sentence.type).iterator();
		while (iterSentence.hasNext()) {
			Sentence s=(Sentence)iterSentence.next();
			String sString=s.getCoveredText();
			FSIterator iterInter = jcas.getAnnotationIndex(Timex3Interval.type).subiterator(s);
			int count=0;
			List<Timex3Interval> txes=new ArrayList<Timex3Interval>();
			List<Timex3Interval> sentenceTxes=new ArrayList<Timex3Interval>();
			
			while(iterInter.hasNext()){
				Timex3Interval t=(Timex3Interval)iterInter.next();
				sString=sString.replace(t.getCoveredText(), "<TX3_"+count+">");
				count++;
				txes.add(t);
			}

			if(count>0){

				if (find_interval_candidates){
					IntervalCandidateSentence sI=new IntervalCandidateSentence(jcas);
					sI.setBegin(s.getBegin());
					sI.setEnd(s.getEnd());
					sI.addToIndexes();
				}
				for(Pattern p: hmIntervalPattern.keySet()){
					
					String name=hmIntervalPattern.get(p);
					List<MatchResult>results=(List<MatchResult>)Toolbox.findMatches(p,sString);
					if(results.size()>0){
						//Interval in Sentence s found by Pattern p!
						for(MatchResult r: results){
							Pattern pNorm=Pattern.compile("group\\(([1-9]+)\\)-group\\(([1-9]+)\\)");
							String norm=hmIntervalNormalization.get(name);
							
							Matcher mNorm=pNorm.matcher(norm);
							if(!mNorm.matches()){
								System.err.println("Problem with the Norm in rule "+name);
							}
							Timex3Interval startTx=null,endTx=null;
							try{
								int startId=Integer.parseInt(mNorm.group(1));
								int endId=Integer.parseInt(mNorm.group(2));
								
								startTx=txes.get(Integer.parseInt(r.group(startId)));
								endTx=txes.get(Integer.parseInt(r.group(endId)));
							}catch(Exception e){
								e.printStackTrace();
								return;
							}
							Timex3Interval annotation=new Timex3Interval(jcas);
							annotation.setBegin(startTx.getBegin()>endTx.getBegin()?endTx.getBegin():startTx.getBegin());
							annotation.setEnd(startTx.getEnd()>endTx.getEnd()?startTx.getEnd():endTx.getEnd());
							
							//Does the interval already exist,
							//found by another pattern?
							boolean duplicate=false;
							for(Timex3Interval tx:sentenceTxes){
								if(tx.getBegin()==annotation.getBegin() &&
										tx.getEnd()==annotation.getEnd()){
									duplicate=true;
									break;
								}
							}
							
							if(!duplicate){
								annotation.setTimexValueEB(startTx.getTimexValueEB());
								annotation.setTimexValueLB(startTx.getTimexValueLE());
								annotation.setTimexValueEE(endTx.getTimexValueEB());
								annotation.setTimexValueLE(endTx.getTimexValueLE());
								annotation.setTimexType(startTx.getTimexType());
								annotation.setFoundByRule(name);
								
								
								// create emptyvalue value
								String emptyValue = createEmptyValue(startTx, endTx, jcas);
								annotation.setEmptyValue(emptyValue);
								annotation.setBeginTimex(startTx.getBeginTimex());
								annotation.setEndTimex(endTx.getEndTimex());
								
								try {
									sentenceTxes.add(annotation);
								} catch(NumberFormatException e) {
									Logger.printError(component, "Couldn't do emptyValue calculation on accont of a faulty normalization in " 
											+ annotation.getTimexValueEB() + " or " + annotation.getTimexValueEE());
								}
								
								// prepare tx3intervals to remove
								timexesToRemove.add(startTx);
								timexesToRemove.add(endTx);
								
								annotation.addToIndexes();
//								System.out.println(emptyValue);
							}
						}
					}
				}
			}
		}
		
		for(Timex3Interval txi : timexesToRemove) {
			txi.removeFromIndexes();
		}
	}
669474
def time_seconds(tc_array, year):
    
    tc_array = np.array(tc_array, copy=True)
    word = tc_array[:, 0]
    day = word >> 1
    word = tc_array[:, 1].astype(np.uint64)
    msecs = ((127) & word) * 1024
    word = tc_array[:, 2]
    msecs += word & 1023
    msecs *= 1024
    word = tc_array[:, 3]
    msecs += word & 1023
    return (np.datetime64(
        str(year) + '-01-01T00:00:00Z', 's') +
        msecs[:].astype('timedelta64[ms]') +
        (day - 1)[:].astype('timedelta64[D]'))
752451
def time_segments_aggregate(X, interval, time_column, method=['mean']):
    """"""
    if isinstance(X, np.ndarray):
        X = pd.DataFrame(X)

    X = X.sort_values(time_column).set_index(time_column)

    if isinstance(method, str):
        method = [method]

    start_ts = X.index.values[0]
    max_ts = X.index.values[-1]

    values = list()
    index = list()
    while start_ts <= max_ts:
        end_ts = start_ts + interval
        subset = X.loc[start_ts:end_ts - 1]
        aggregated = [
            getattr(subset, agg)(skipna=True).values
            for agg in method
        ]
        values.append(np.concatenate(aggregated))
        index.append(start_ts)
        start_ts = end_ts

    return np.asarray(values), np.asarray(index)
856233
def _ParseTimeRange(self, timerange):
    """"""
    if timerange is None:
      timerange = (None, None)

    from_time, to_time = timerange
    if not from_time:
      from_time = rdfvalue.RDFDatetime().FromSecondsSinceEpoch(0)

    if not to_time:
      to_time = rdfvalue.RDFDatetime().FromSecondsSinceEpoch(sys.maxsize)

    return (from_time, to_time)
625950
def timeticks(tdiff):
    
    if isinstance(tdiff, xarray.DataArray):  # len==1
        tdiff = timedelta(seconds=tdiff.values / np.timedelta64(1, 's'))

    assert isinstance(tdiff, timedelta), 'expecting datetime.timedelta'

    if tdiff > timedelta(hours=2):
        return None, None

    elif tdiff > timedelta(minutes=20):
        return MinuteLocator(byminute=range(0, 60, 5)), MinuteLocator(byminute=range(0, 60, 2))

    elif (timedelta(minutes=10) < tdiff) & (tdiff <= timedelta(minutes=20)):
        return MinuteLocator(byminute=range(0, 60, 2)), MinuteLocator(byminute=range(0, 60, 1))

    elif (timedelta(minutes=5) < tdiff) & (tdiff <= timedelta(minutes=10)):
        return MinuteLocator(byminute=range(0, 60, 1)), SecondLocator(bysecond=range(0, 60, 30))

    elif (timedelta(minutes=1) < tdiff) & (tdiff <= timedelta(minutes=5)):
        return SecondLocator(bysecond=range(0, 60, 30)), SecondLocator(bysecond=range(0, 60, 10))

    elif (timedelta(seconds=30) < tdiff) & (tdiff <= timedelta(minutes=1)):
        return SecondLocator(bysecond=range(0, 60, 10)), SecondLocator(bysecond=range(0, 60, 2))

    else:
        return SecondLocator(bysecond=range(0, 60, 2)),  SecondLocator(bysecond=range(0, 60, 1))
1253972
function timesSeries(n, fn) {
    var counter = [];
    return this.then(function(last) {
        for (var i = 0; i < n; i++) {
            counter.push(last || i);
        }
        return Q(counter).mapSeries(fn);
    });
}
656229
function hmsToSeconds(time) {
	var arr = time.split(':'), s = 0, m = 1;

	while (arr.length > 0) {
		s += m * parseInt(arr.pop(), 10);
		m *= 60;
	}

	return s;
}
491124
public static String[] getHourMinuteSecondTimeString(long time) {

        int hours = (int)time / (1000 * 60 * 60);
        int min = (int)(time - (hours * 1000 * 60 * 60)) / (1000 * 60);
        int sec = (int)(time - (hours * 1000 * 60 * 60) - (min * 1000 * 60)) / 1000;

        return new String[] {getTwoDigitsString(hours), getTwoDigitsString(min), getTwoDigitsString(sec)};
    }
843853
function createLinkedTimelines() {
    const tl1 = createTimeline();
    const tl2 = createTimeline();
    tl1.setNeighbouringTimeline(tl2, EventTimeline.FORWARDS);
    tl2.setNeighbouringTimeline(tl1, EventTimeline.BACKWARDS);
    return [tl1, tl2];
}
442157
def cut(self, times: Union[datetime.datetime,
                               List[datetime.datetime]]) -> List["Interval"]:
        
        if not isinstance(times, list):
            # Single time
            time = times
            if not self.contains(time):
                return []
            return [
                Interval(self.start, time),
                Interval(time, self.end)
            ]
        else:
            # Multiple times
            times = [t for t in times if self.contains(t)]  # discard others
            times.sort()
            times = [self.start] + times + [self.end]
            intervals = []
            for i in range(len(times) - 1):
                intervals.append(Interval(times[i], times[i + 1]))
            return intervals
727198
public AbstractLongList times(int times) {
	AbstractLongList newList = new LongArrayList(times*size());
	for (int i=times; --i >= 0; ) {
		newList.addAllOfFromTo(this,0,size()-1);
	}
	return newList;
}
1235694
def FromNanoseconds(self, nanos):
    """"""
    self.seconds = nanos // _NANOS_PER_SECOND
    self.nanos = nanos % _NANOS_PER_SECOND