prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: <|fim_middle|> if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
ret.append(('', day)) prev_day = day continue
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: <|fim_middle|> elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
item = ('down', day)
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: <|fim_middle|> else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
item = ('up', day)
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: <|fim_middle|> prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
item = ('equal', day)
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: <|fim_middle|> else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
get_data = lambda x: x['apps'][app]['percent']
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: <|fim_middle|> hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
get_data = lambda x: x['percent']
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def <|fim_middle|>(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
__init__
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def <|fim_middle|>(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
get_data
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def <|fim_middle|>(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
summary
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def <|fim_middle|>(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def history(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
_mark_movement
<|file_name|>status.py<|end_file_name|><|fim▁begin|>import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: return resp = requests.get(self.url) if resp.status_code != 200: resp.raise_for_status() self.data = resp.json() self.created = self.data[-1]['created'] def summary(self): """Generates summary data of today's state""" self.get_data() highlight = self.highlight last_item = self.data[-1] output = {} output['app'] = self.app or 'ALL' data = last_item['locales'] if self.app: get_item = lambda x: x['apps'][self.app] else: get_item = lambda x: x apps = data.items()[0][1]['apps'].keys() apps.sort() output['apps'] = apps items = [item for item in data.items() if item[0] not in highlight] hitems = [item for item in data.items() if item[0] in highlight] highlighted = [] if hitems: for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) highlighted.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated = item.get('translated', -1) percent = item.get('percent', -1) untranslated_words = item.get('untranslated_words', -1) locales.append({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words }) output['locales'] = locales output['created'] = self.created return output def _mark_movement(self, data): """For each item, converts to a tuple of (movement, item)""" ret = [] prev_day = None for i, day in enumerate(data): if i == 0: ret.append(('', day)) prev_day = day continue if prev_day > day: item = ('down', day) elif prev_day < day: item = ('up', day) else: item = ('equal', day) prev_day = day ret.append(item) return ret def <|fim_middle|>(self): self.get_data() data = self.data highlight = self.highlight app = self.app # Get a list of the locales we'll iterate through locales = sorted(data[-1]['locales'].keys()) num_days = 14 # Truncate the data to what we want to look at data = data[-num_days:] if app: get_data = lambda x: x['apps'][app]['percent'] else: get_data = lambda x: x['percent'] hlocales = [loc for loc in locales if loc in highlight] locales = [loc for loc in locales if loc not in highlight] output = {} output['app'] = self.app or 'All' output['headers'] = [item['created'] for item in data] output['highlighted'] = sorted( (loc, self._mark_movement(get_data(day['locales'][loc]) for day in data)) for loc in hlocales ) output['locales'] = sorted( (loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data)) for loc in locales ) output['created'] = self.created return output <|fim▁end|>
history
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def get_user(self, email): try: return User.objects.get(email=email)<|fim▁hole|><|fim▁end|>
except User.DoesNotExist: return None
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): <|fim_middle|> <|fim▁end|>
def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): <|fim_middle|> def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None <|fim▁end|>
logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) )
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def get_user(self, email): <|fim_middle|> <|fim▁end|>
try: return User.objects.get(email=email) except User.DoesNotExist: return None
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': <|fim_middle|> else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None <|fim▁end|>
email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email)
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: <|fim_middle|> def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None <|fim▁end|>
logger.warning( 'Persona says no. Json was: {}'.format(response.json()) )
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def <|fim_middle|>(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None <|fim▁end|>
authenticate
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|># accounts/authentication.py import requests import logging from django.conf import settings from django.contrib.auth import get_user_model logger = logging.getLogger(__name__) User = get_user_model() PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify' #DOMAIN = 'localhost' #DOMAIN = 'http://hotzenplotz.pythonanywhere.com' class PersonaAuthenticationBackend(object): def authenticate(self, assertion): logging.warning('entering authenticate function') response = requests.post( PERSONA_VERIFY_URL, data = {'assertion': assertion, 'audience': settings.DOMAIN} ) logging.warning('got response from persona') logging.warning(response.content.decode()) if response.ok and response.json()['status'] == 'okay': email = response.json()['email'] try: return User.objects.get(email=email) except User.DoesNotExist: return User.objects.create(email=email) else: logger.warning( 'Persona says no. Json was: {}'.format(response.json()) ) def <|fim_middle|>(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None <|fim▁end|>
get_user
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min')<|fim▁hole|> class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs)<|fim▁end|>
return w
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): <|fim_middle|> class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): <|fim_middle|> class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): <|fim_middle|> class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): <|fim_middle|> class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): <|fim_middle|> class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): <|fim_middle|> class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): <|fim_middle|> <|fim▁end|>
def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): <|fim_middle|> <|fim▁end|>
WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): <|fim_middle|> elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): <|fim_middle|> else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): <|fim_middle|> else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
w = voc.get_random_known_w(m=m)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: <|fim_middle|> elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
w = voc.get_random_known_w(m=m)
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): <|fim_middle|> else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
w = voc.get_new_unknown_w()
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: <|fim_middle|> return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
w = voc.get_random_known_w(option='min')
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def <|fim_middle|>(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
pick_w
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def <|fim_middle|>(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
__init__
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def <|fim_middle|>(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
__init__
<|file_name|>word_preference.py<|end_file_name|><|fim▁begin|>from . import BaseWordChoice class WordPreference(BaseWordChoice): def pick_w(self,m,voc,mem,context=[]): if m in voc.get_known_meanings(): if m in list(mem['prefered words'].keys()): w = mem['prefered words'][m] if w not in voc.get_known_words(m=m): w = voc.get_random_known_w(m=m) else: w = voc.get_random_known_w(m=m) elif voc.get_unknown_words(): w = voc.get_new_unknown_w() else: w = voc.get_random_known_w(option='min') return w class PlaySmart(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_smart'}],*args,**kwargs) class PlayLast(WordPreference): def __init__(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_last'}],*args,**kwargs) class PlayFirst(WordPreference): def <|fim_middle|>(self, *args, **kwargs): WordPreference.__init__(self,memory_policies=[{'mem_type':'wordpreference_first'}],*args,**kwargs) <|fim▁end|>
__init__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0<|fim▁hole|> def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
self.remaining_lines = MAX_NUM_LINES self.lines = []
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): <|fim_middle|> def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind]
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): <|fim_middle|> def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = []
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): <|fim_middle|> def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines()
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): <|fim_middle|> def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Merge with another CmdText object by appending the input objects content. """ self.lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): <|fim_middle|> def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i)
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): <|fim_middle|> def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Update the number of lines member. """ self.num_lines = len(self.lines)
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): <|fim_middle|> def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): <|fim_middle|> def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:]
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): <|fim_middle|> def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Iterator for CmdText object. """ for l in self.lines: yield l
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): <|fim_middle|> def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
return self.lines[ind]
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): <|fim_middle|> def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): <|fim_middle|> class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): <|fim_middle|> class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): <|fim_middle|> class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): <|fim_middle|> class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): <|fim_middle|> class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): <|fim_middle|> class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): <|fim_middle|> class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): <|fim_middle|> class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
""" Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): <|fim_middle|> def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
assert get_lines("") == [""]
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): <|fim_middle|> def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
assert len(get_lines("a"*(LINEWIDTH-1))) == 1
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): <|fim_middle|> def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): <|fim_middle|> def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): <|fim_middle|> class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): <|fim_middle|> <|fim▁end|>
""" Tests for CmdText class methods. """ pass
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): <|fim_middle|> input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
pass
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): <|fim_middle|> def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i)
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: <|fim_middle|> else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
return self.lines[n]
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: <|fim_middle|> def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
raise IndexError("Line index out of range.")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): <|fim_middle|> class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
self.response = rind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): <|fim_middle|> class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
self.command = cind
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): <|fim_middle|> print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: <|fim_middle|> print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
print("Test passed!")
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def <|fim_middle|>(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
__init__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def <|fim_middle|>(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
insert
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def <|fim_middle|>(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
merge_after
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def <|fim_middle|>(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
strip_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def <|fim_middle|>(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
update_num_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def <|fim_middle|>(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
get_line
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def <|fim_middle|>(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
print_screen
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def <|fim_middle|>(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
__iter__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def <|fim_middle|>(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
__getitem__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def <|fim_middle|>(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
num_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def <|fim_middle|>(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
get_lines
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def <|fim_middle|>(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
__init__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def <|fim_middle|>(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
__init__
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def <|fim_middle|>(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
run
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def <|fim_middle|>(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
test_get_lines_with_empty_string
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def <|fim_middle|>(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
test_get_lines_with_short_string
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def <|fim_middle|>(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
test_get_lines_with_long_string
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def <|fim_middle|>(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
test_get_lines_with_very_long_string
<|file_name|>cmdtext.py<|end_file_name|><|fim▁begin|>import sys MAX_NUM_STORED_LINES = 200 MAX_NUM_LINES = 10 LINEWIDTH = 80 class CmdText(object): """ Represents a command line text device. Text is split into lines corresponding to the linewidth of the device. """ def __init__(self): """ Construct empty object. """ self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """ Insert string at the end. This always begins a new line. """ if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """ Merge with another CmdText object by appending the input objects content. """ self.lines def strip_lines(self): """ Remove excessive number of lines. This deletes the oldest half. """ if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """ Update the number of lines member. """ self.num_lines = len(self.lines) def get_line(self, n): """ Return the line with index n. """ if n < self.num_lines: return self.lines[n] else: raise IndexError("Line index out of range.") def print_screen(self): """ Return MAX_NUM_LINES lines. """ return self.lines[-MAX_NUM_LINES:] def __iter__(self): """ Iterator for CmdText object. """ for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """ Return number of lines. """ line_list = string.split("\n") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """ Return list of lines extracted from string. """ line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """ Base class for tests. """ @classmethod def run(cls): """ Runs all tests (methods which begin with 'test'). """ #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith("test"): fill = max_len - len(key) sys.stdout.write("Testing {} ...{} ".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print("Test passed!") print("All tests passed!") class StaticTest(TestCase): """ Tests for static methods. """ def test_get_lines_with_empty_string(): assert get_lines("") == [""] def test_get_lines_with_short_string(): assert len(get_lines("a"*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines("a"*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines("a"*(4*LINEWIDTH-1))) == 4 def <|fim_middle|>(): text = "This is a test string, which should simulate real text. The command should" \ + " correctly split this text into two lines." LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """ Tests for CmdText class methods. """ pass<|fim▁end|>
test_get_lines_with_long_text_string
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details.<|fim▁hole|>from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main()<|fim▁end|>
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.")
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': <|fim_middle|> elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e)
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: <|fim_middle|> try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: <|fim_middle|> params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
params['repository_url'] = module.foreman_params['repository_url']
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok <|fim_middle|> if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
break
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: <|fim_middle|> else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
module.fail_json(msg="Manifest is older than existing data.")
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: <|fim_middle|> else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
module.fail_json(msg="Upload of the manifest failed: %s" % error)
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: <|fim_middle|> except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main() <|fim▁end|>
module.set_changed()