1 #!/usr/bin/env python 2 3 from bisect import bisect_left, insort_left 4 5 # Time management. 6 7 def have_conflict(freebusy, periods, get_conflicts=False): 8 9 """ 10 Return whether any period in 'freebusy' overlaps with the given 'periods', 11 returning a collection of such overlapping periods if 'get_conflicts' is 12 set to a true value. 13 """ 14 15 conflicts = [] 16 for start, end in periods: 17 period = period_overlaps(freebusy, (start, end)) 18 if period: 19 if get_conflicts: 20 conflicts.append(period) 21 else: 22 return True 23 if get_conflicts: 24 return conflicts 25 else: 26 return False 27 28 def insert_period(freebusy, period): 29 insort_left(freebusy, period) 30 31 def remove_period(freebusy, uid): 32 i = 0 33 while i < len(freebusy): 34 t = freebusy[i] 35 if len(t) >= 3 and t[2] == uid: 36 del freebusy[i] 37 else: 38 i += 1 39 40 def period_overlaps(freebusy, period): 41 42 """ 43 Return from 'freebusy' any period overlapping with the given 'period', or 44 None if no overlap occurs. 45 """ 46 47 dtstart, dtend = period[:2] 48 i = bisect_left(freebusy, (dtstart, dtend, None)) 49 return ( 50 i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend) and freebusy[i] 51 or 52 i > 0 and freebusy[i - 1][1] > dtstart and freebusy[i - 1] 53 or 54 None 55 ) 56 57 # vim: tabstop=4 expandtab shiftwidth=4