def __init__(self, id: str, name: str, distribution: Union[dict, int] = 0, data_input: list = None, data_output: list = None, resources: list = None, failure_rate: float = 0, retries: int = 0, timeout: int = None, priority: str = 'normal') -> None: self.id = id self.name = name self.duration = Duration(distribution) self.data_input = DataRequirement.from_list(data_input) self.data_output = DataRequirement.from_list(data_output) self.process_data = getattr( DATA_MODULE, self.id) if data_output is not None else None self.resources = ResourceRequirement.from_list(resources) self.failure = Failure(failure_rate if failure_rate is not None else 0) self.retries = retries if retries is not None else 0 self.timeout = timeout if timeout is not None else math.inf if priority is None: self.priority = PRIORITY_VALUES['normal'] elif priority.lower() in PRIORITY_VALUES: self.priority = PRIORITY_VALUES[priority.lower()] else: raise TypeError('Value %s is not supported for priority.' % priority)
def __init__(self): self.part_names = ('oboe', 'bass_clarinet', 'vibraphone', 'bass') self.starting_tempo_bpm = 105 self.n_quarters = 128 self.ticks_per_quarter = 32 self.duration_tools = Duration( ticks=self.ticks_per_quarter, ticks_per_quarter=self.ticks_per_quarter) m = self.music = Music( part_names=self.part_names, starting_tempo_bpm=self.starting_tempo_bpm, output_dir_name='experiment11', n_quarters=self.n_quarters, ticks_per_quarter=self.ticks_per_quarter, ) instrument = self.music.instruments[0] lick = Lick() sequence = Sequence(lick, instrument, 12) start_offset = self.duration_tools.quarters_and_sixteenths_to_ticks( quarters=0, sixteenths=0, ticks_per_quarter=self.ticks_per_quarter) # duration = self.duration_tools.quarters_and_sixteenths_to_ticks(quarters=0, sixteenths=int(lick.duration * 4), ticks_per_quarter=self.ticks_per_quarter) for pitch, dur in sequence: duration_in_ticks = int(dur * self.ticks_per_quarter) instrument.put_note(start_offset, duration_in_ticks, pitch=pitch) start_offset += duration_in_ticks for i in self.music.instruments: i.closeout() print 'Done making the music. Starting notation.'
def read_component_analysis_from_core_data(s3, ecosystem, component, version): """Read component analysis from the core data and retrieve duration info from it.""" bucket = "bayesian-core-data" durations = {} key = s3.component_key(ecosystem, component, version) data = s3.read_object(bucket, key) durations["overall"] = Duration.from_data(data) analyses = data.get("analyses") # Remove this analysis because it is not performed on component-version level if "github_details" in analyses: analyses.remove("github_details") # analyses.remove("code_metrics") for analysis in analyses: key = s3.component_analysis_key(ecosystem, component, version, analysis) try: data = s3.read_object(bucket, key) durations[analysis] = Duration.from_audit(data) except ClientError: print("Warning: duration for the following analysis won't be " "be computed: {a}".format(a=analysis)) return durations
def read_component_analysis_from_core_package(s3, ecosystem, component): """Read component analysis from core package data and retrieve duration info from it.""" bucket = "bayesian-core-package-data" durations = {} key = s3.component_core_package_data_key(ecosystem, component) data = s3.read_object(bucket, key) durations["overall"] = Duration.from_data(data) # we have to specify analysis manually here analyses = [ "git_stats", "github_details", "keywords_tagging", "libraries_io" ] for analysis in analyses: key = s3.component_core_package_data_analysis_key( ecosystem, component, analysis) try: data = s3.read_object(bucket, key) durations[analysis] = Duration.from_audit(data) except ClientError: print("Warning: duration for the following analysis won't be " "be computed: {a}".format(a=analysis)) return durations
def test_one_task_one_user_assign(self): start_a = datetime.datetime(2000, 1, 1, 6, 0, 0) end_a = datetime.datetime(2000, 1, 1, 22, 0, 0) availability = [Availability(Duration(start_a, end_a))] category = Category(1, 'TestCategory') preferences = [Preference(category, 0, True)] groups = [Group(1, 'Employee')] generic = CommonTestFunctions() staff_member = StaffMember(1, 'TestMember', 0, 40, 80, 10, availability, preferences, groups) start_t = datetime.datetime(2000, 1, 1, 9, 0, 0) end_t = datetime.datetime(2000, 1, 1, 16, 0, 0) task_time = Duration(start_t, end_t) location = Location(1, 'TestLocation') task = Task(1, 'TestTask', task_time, 1, groups[0], location, category) staff_members = [staff_member] roles = [] tasks = [task] settings = generic.settings(40, True) generator = ScheduleGenerator(staff_members, roles, tasks) generator.schedule(settings) self.assertTrue(staff_member.has_task(task)) self.assertFalse(generator.has_unassigned_tasks())
def __init__(*args): self, *info = args self.name = info[0] self.cookingTime = Duration(info[1]) self.preparationTime = Duration(info[2]) self.descr = info[3] self.im = info[4] self.ingredients = IngredientList(info[5]) self.instructions = info[6] self.recipe_yield = info[7]
def __init__(self, source: str, destination: str, sgate: str = None, dgate: str = None, distribution: Union[dict, int] = 0) -> None: self.source = source self.source_gate = sgate self.destination = destination self.destination_gate = dgate self.delay = Duration(distribution)
def __init__(self, inputs=[], outputs=[], duration: Duration=None, timestamp=None): self._inputs = inputs self._outputs = outputs if duration is None: self._duration = Duration() else: self._duration = duration if timestamp is None: self._timestamp = time.time() else: self._timestamp = timestamp
def test_can_end_inside_of(self): six_to_eleven = Duration(self.six_one_date, self.eleven_one_date) six_to_ten = Duration(self.six_one_date, self.ten_one_date) seven_to_ten = Duration(self.seven_one_date, self.ten_one_date) seven_to_nine = Duration(self.seven_one_date, self.nine_one_date) self.assertTrue(six_to_ten.can_end_inside_of(six_to_ten)) self.assertTrue(six_to_ten.can_end_inside_of(seven_to_ten)) self.assertTrue(six_to_ten.can_end_inside_of(six_to_eleven)) self.assertFalse(six_to_ten.can_end_inside_of(seven_to_nine))
def make_instance(start, duration, start_day): """ Return two class instances: start from Start and duration from Duration. """ start = Start(start, start_day) duration = Duration(duration) return start, duration
def create_duration_on_next_day(self, start_day, end_day, start_time, end_time, current_date=datetime.datetime.now()): # TODO: This will need to be redone if we ever change the ability to have start and end dates other than sunday / saturady next_start_day = self.__next_weekday(current_date, 6) start_day_integer = self.get_week_day_as_python_int(start_day) end_day_integer = self.get_week_day_as_python_int(end_day) start_date = self.__next_weekday(next_start_day, start_day_integer) end_date = self.__next_weekday(next_start_day, end_day_integer) start_hour = start_time.hour start_minute = start_time.minute end_hour = end_time.hour end_minute = end_time.minute start_date = datetime.datetime(start_date.year, start_date.month, start_date.day, start_hour, start_minute) end_date = datetime.datetime(end_date.year, end_date.month, end_date.day, end_hour, end_minute) return Duration(start_date, end_date)
def to_python(self, value): if not value: return None if isinstance(value, Duration): return value if isinstance(value, (int, long)): return Duration(seconds=value) elif isinstance(value, (basestring, unicode)): try: minutes, seconds = map(int, value.split(':')) return Duration(seconds=(seconds + minutes * 60)) except: raise ValidationError("That didn't look like a" + "duration to me") elif not isinstance(value, timedelta): raise ValidationError('Unable to convert %s to Duration.' % value) return value
def __init__(self, id: str, type: str, quantity: int, delay: Union[dict, int], consumable: bool) -> None: Resource.__init__(self, id=id) self.type = type self.quantity = quantity self.busy = [] self.delay = Duration(delay) self.consumable = consumable
def test_datetime_delta(self): start_dt = '2020-02-18 09:48:21,847' end_dt = '2020-02-19 03:02:22,157' duration = Duration(start_dt, end_dt, '%Y-%m-%d %H:%M:%S,%f') self.assertIsNotNone(duration.datetime_delta) self.assertIsInstance(duration.datetime_delta, datetime.timedelta) self.assertEqual(duration.datetime_delta.days, 0)
def put_note(self, start_offset, duration, pitch=None): start_tick = float_to_tick(start_offset, ticks_per_quarter=self.ticks_per_quarter) duration_in_ticks = float_to_tick(duration, ticks_per_quarter=self.ticks_per_quarter) end_tick = start_tick + duration_in_ticks ticks = self.timeline._timeline[start_tick:end_tick] note = Note(pitch=pitch, duration=Duration(ticks=duration_in_ticks, ticks_per_quarter=self.ticks_per_quarter), ticks=ticks)
def test_duration(self): start_dt = '2020-02-18 09:48:21,847' end_dt = '2020-02-19 03:02:22,157' duration = Duration(start_dt, end_dt, '%Y-%m-%d %H:%M:%S,%f') self.assertIsNotNone(duration) self.assertIsInstance(duration, Duration) self.assertIsInstance(duration.start_datetime, datetime.datetime) self.assertIsInstance(duration.end_datetime, datetime.datetime)
def camp_duration(self, start_hour, end_hour, day, start_minute=0, end_minute=0): start_a = datetime.datetime(2018, 7, day, start_hour, start_minute, 0) end_a = datetime.datetime(2018, 7, day, end_hour, end_minute, 0) return Duration(start_a, end_a)
def parse_to_duration(self, value): ''' Attempt to make a value out of this string For now the rules are: '' => zero-duration timedelta 'mm:ss' || 'hh:mm:ss' => timedelta of this value else: ValueError ''' if value is None: return Duration(0) if len(value) == 0: return Duration(0) vs = [int(v) for v in value.split(':')] if len(vs) < 2 or len(vs) > 4: raise ValueError('Format error with value: %s' % value) time = vs[-1] + 60 * vs[-2] if len(vs) == 3: time += 60 * 60 * vs[0] return Duration(seconds=time)
def camp_availability(self, day, start_hour, end_hour, start_minute=0, end_minute=0): start_a = datetime.datetime(2018, 7, day, start_hour, start_minute, 0) end_a = datetime.datetime(2018, 7, day, end_hour, end_minute, 0) return Availability(Duration(start_a, end_a))
def setUp(self): start_time = datetime.datetime(2000, 1, 1, 6, 0) end_time = datetime.datetime(2000, 1, 1, 10, 0) self.duration = Duration(start_time, end_time) self.group = Group(0, 'TestGroup') self.location = Location(0, 'TestLoction') self.category = Category(0, 'TestCategory') self.good_task = Task(0, 'TestTask', self.duration, 3, self.group, self.location, self.category)
def clean(self, value): super(CharField, self).clean(value) try: duration = self.parse_to_duration(value) if duration == Duration(0) and self.required: raise FormValidationError(self.error_messages['required'], code='required') return duration except ValueError: raise FormValidationError('Data entered must be in format MM:SS')
def __getMedia(self): mediaNum=-1 while not(1 <= mediaNum <= 4): self.__displayMediaTypeMenu() mediaNum = int(input("\nEnter a media type selection (1 to 4):")) print("Enter the title of your ", self.__MEDIA[mediaNum-1],":", end='') title = input() artist = input("Next enter the media's artist: ") wherePurchased = input("Next enter where the media was purchased: ") cost = float(input("Now enter the cost of the media,$ ")) while cost < 0.0: cost = float(input("Erant entry -- re-enter the cost (>= 0.0: ")) minutes = int(input("Next enter the media's total running time(minutes): ")) while minutes < 1: minutes = int(input("Errant entry -- re-enter running time in minutes( >= ): ")) numItems = int(input("Finally, enter the number of items on the media: ")) while numItems < 1: numItems = int(input("Errant entry -- re-enter number of items on media( >=1 ):")) if mediaNum == 1: return AudioCassette(title, artist, wherePurchased, cost, Duration(minutes), numItems) elif mediaNum == 2: return AudioCD(title, artist, wherePurchased, cost, Duration(minutes), numItems) elif mediaNum == 3: return VideoVHS(title, artist, wherePurchased, cost, Duration(minutes), numItems) else: return VideoDVD(title, artist, wherePurchased, cost, Duration(minutes), numItems)
def duration(self, start_hour=10, end_hour=15, start_minute=0, end_minute=0, start_day=1, end_day=1): start_a = datetime.datetime(2000, 1, start_day, start_hour, start_minute, 0) end_a = datetime.datetime(2000, 1, end_day, end_hour, end_minute, 0) return Duration(start_a, end_a)
def __init__(self, inTitle="No title", inArtist="No artist", inWherePurchased="Unknown", inCost=0.0, inRunningTime=Duration(), inNumSelections=1): super().__init__(inTitle, inArtist, inWherePurchased, inCost, inRunningTime) self.__numSelections = inNumSelections if inNumSelections > 0 else 1 self.__currentSelection = 1
def job_duration(job_name, debug): """Compute duration for given job.""" tasks = debug.json()["tasks"] job_debug_data = find_job_debug_data(job_name, tasks) assert job_debug_data assert job_debug_data["error"] is False started_at = job_debug_data["started_at"] ended_at = job_debug_data["ended_at"] return Duration(started_at, ended_at).duration_seconds
def setUp(self): start_time = datetime.datetime(2000, 1, 1, 6, 0) end_time = datetime.datetime(2000, 1, 1, 10, 0) self.duration = Duration(start_time, end_time) self.group = Group(0, 'TestGroup') self.location = Location(0, 'TestLoction') self.category = Category(0, 'TestCategory') good_tasks = [ Task(0, 'TestTask', self.duration, 8, self.group, self.location, self.category) ] generic = CommonTestFunctions() self.good_role = generic.role(good_tasks, name='Role', id=1)
def __init__(self, inTitle="No title", inArtist="No artist", inWherePurchased="Unknown", inCost=0.0, inRunningTime=Duration()): self.__title = inTitle if len(inTitle) > 0 else "No title" self.__artist = inArtist if len(inArtist) > 0 else "No Artist" self.__wherePurchased = inWherePurchased if len( inWherePurchased) > 0 else "Unknown" self.__cost = inCost if inCost >= 0.0 else 0.0 self.__runningTime = inRunningTime self.__mediaAtBeginning = True self.__mediaAtEnd = False
def update(self, fields: dict) -> None: for key, value in fields.items(): if key == 'data_input' or key == 'data_output': setattr(self, key, DataRequirement.from_list(value)) elif key == 'duration': setattr(self, key, Duration(value)) elif key == 'failure': setattr(self, key, Failure(value)) elif key == 'priority': setattr(self, key, PRIORITY_VALUES[value.lower()]) elif key == 'resources': setattr(self, key, ResourceRequirement.from_list(value)) else: setattr(self, key, value)
def closeout(self): '''Put rests anywhere there aren't notes''' rest_ticks = [] for i, tick in enumerate(self.timeline._timeline): if tick.note: if tick.note_start: if rest_ticks: # Add up the previous rest duration and append it to self.notes duration_in_ticks = len(rest_ticks) note = Note(duration=Duration(ticks=duration_in_ticks, ticks_per_quarter=self.ticks_per_quarter), ticks=rest_ticks) self.notes.append(note) self.notes.append(tick.note) if tick.note_end: rest_ticks = [] else: rest_ticks.append(tick)
class Transition: # Initialization and instance variables def __init__(self, source: str, destination: str, sgate: str = None, dgate: str = None, distribution: Union[dict, int] = 0) -> None: self.source = source self.source_gate = sgate self.destination = destination self.destination_gate = dgate self.delay = Duration(distribution) # Public methods def get_next(self) -> Tuple[str, str, int]: return self.destination, self.destination_gate, self.delay.generate() # Private methods def __repr__(self): return ', '.join("%s: %s" % item for item in vars(self).items())