desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Set an item with check for allownew. Examples >>> s = Struct() >>> s[\'a\'] = 10 >>> s.allow_new_attr(False) >>> s[\'a\'] = 10 >>> s[\'a\'] 10 >>> try: ... s[\'b\'] = 20 ... except KeyError: ... print(\'this is not allowed\') this is not allowed'
def __setitem__(self, key, value):
if ((not self._allownew) and (key not in self)): raise KeyError(("can't create new attribute %s when allow_new_attr(False)" % key)) dict.__setitem__(self, key, value)
'Set an attr with protection of class members. This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to :exc:`AttributeError`. Examples >>> s = Struct() >>> s.a = 10 >>> s.a 10 >>> try: ... s.get = 10 ... except AttributeError: ... print("you can\'t set a class member") you can\'t set a class member'
def __setattr__(self, key, value):
if isinstance(key, str): if ((key in self.__dict__) or hasattr(Struct, key)): raise AttributeError(('attr %s is a protected member of class Struct.' % key)) try: self.__setitem__(key, value) except KeyError as e: raise AttributeError(e)
'Get an attr by calling :meth:`dict.__getitem__`. Like :meth:`__setattr__`, this method converts :exc:`KeyError` to :exc:`AttributeError`. Examples >>> s = Struct(a=10) >>> s.a 10 >>> type(s.get) <... \'builtin_function_or_method\'> >>> try: ... s.b ... except AttributeError: ... print("I don\'t have that key")...
def __getattr__(self, key):
try: result = self[key] except KeyError: raise AttributeError(key) else: return result
's += s2 is a shorthand for s.merge(s2). Examples >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s += s2 >>> sorted(s.keys()) [\'a\', \'b\', \'c\']'
def __iadd__(self, other):
self.merge(other) return self
's + s2 -> New Struct made from s.merge(s2). Examples >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s = s1 + s2 >>> sorted(s.keys()) [\'a\', \'b\', \'c\']'
def __add__(self, other):
sout = self.copy() sout.merge(other) return sout
's1 - s2 -> remove keys in s2 from s1. Examples >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s = s1 - s2 >>> s {\'b\': 30}'
def __sub__(self, other):
sout = self.copy() sout -= other return sout
'Inplace remove keys from self that are in other. Examples >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s1 -= s2 >>> s1 {\'b\': 30}'
def __isub__(self, other):
for k in other.keys(): if (k in self): del self[k] return self
'Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values.'
def __dict_invert(self, data):
outdict = {} for (k, lst) in data.items(): if isinstance(lst, str): lst = lst.split() for entry in lst: outdict[entry] = k return outdict
'Return a copy as a Struct. Examples >>> s = Struct(a=10,b=30) >>> s2 = s.copy() >>> type(s2) is Struct True'
def copy(self):
return Struct(dict.copy(self))
'hasattr function available as a method. Implemented like has_key. Examples >>> s = Struct(a=10) >>> s.hasattr(\'a\') True >>> s.hasattr(\'b\') False >>> s.hasattr(\'get\') False'
def hasattr(self, key):
return (key in self)
'Set whether new attributes can be created in this Struct. This can be used to catch typos by verifying that the attribute user tries to change already exists in this Struct.'
def allow_new_attr(self, allow=True):
object.__setattr__(self, '_allownew', allow)
'Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary \'conflict\' is used to decide what to do. If conflict is not given, the default behavio...
def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
data_dict = dict(__loc_data__, **kw) preserve = (lambda old, new: old) update = (lambda old, new: new) add = (lambda old, new: (old + new)) add_flip = (lambda old, new: (new + old)) add_s = (lambda old, new: ((old + ' ') + new)) conflict_solve = dict.fromkeys(self, preserve) if __conf...
'Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. override the same methods from cmd.Cmd to provide prompt toolkit replacement.'
def cmdloop(self, intro=None):
if (not self.use_rawinput): raise ValueError('Sorry ipdb does not support use_rawinput=False') self.preloop() try: if (intro is not None): self.intro = intro if self.intro: self.stdout.write((str(self.intro) + '\n')) stop = None ...
'Get last n readline history entries as a list'
def rl_hist_entries(self, rl, n):
return [rl.get_history_item((rl.get_current_history_length() - x)) for x in range((n - 1), (-1), (-1))]
'Test that code with a blank line doesn\'t get split (gh-3246).'
def test_paste_magics_blankline(self):
ip = get_ipython() s = 'def pasted_func(a):\n b = a+1\n\n return b' tm = ip.magics_manager.registry['TerminalMagics'] tm.store_or_execute(s, name=None) self.assertEqual(ip.user_ns['pasted_func'](54), 55)
'Return a string containing a crash report.'
def make_report(self, traceback):
sec_sep = self.section_sep report = [super(IPAppCrashHandler, self).make_report(traceback)] rpt_add = report.append try: rpt_add((sec_sep + 'History of session input:')) for line in self.app.shell.user_ns['_ih']: rpt_add(line) rpt_add('\n*** Last line ...
'This has to be in a method, for TerminalIPythonApp to be available.'
@default('classes') def _classes_default(self):
return [InteractiveShellApp, self.__class__, TerminalInteractiveShell, HistoryManager, ProfileDir, PlainTextFormatter, IPCompleter, ScriptMagics, LoggingMagics, StoreMagics]
'override to allow old \'-pylab\' flag with deprecation warning'
def parse_command_line(self, argv=None):
argv = (sys.argv[1:] if (argv is None) else argv) if ('-pylab' in argv): argv = argv[:] idx = argv.index('-pylab') warnings.warn('`-pylab` flag has been deprecated.\n Use `--matplotlib <backend>` and import pylab manually.') argv[idx] ...
'Do actions after construct, but before starting the app.'
@catch_config_error def initialize(self, argv=None):
super(TerminalIPythonApp, self).initialize(argv) if (self.subapp is not None): return if (self.extra_args and (not self.something_to_run)): self.file_to_run = self.extra_args[0] self.init_path() self.init_shell() self.init_banner() self.init_gui_pylab() self.init_extensio...
'initialize the InteractiveShell instance'
def init_shell(self):
self.shell = self.interactive_shell_class.instance(parent=self, profile_dir=self.profile_dir, ipython_dir=self.ipython_dir, user_ns=self.user_ns) self.shell.configurables.append(self)
'optionally display the banner'
def init_banner(self):
if (self.display_banner and self.interact): self.shell.show_banner() if (self.log_level <= logging.INFO): print ()
'Replace --pylab=\'inline\' with --pylab=\'auto\''
def _pylab_changed(self, name, old, new):
if (new == 'inline'): warnings.warn("'inline' not available as pylab backend, using 'auto' instead.") self.pylab = 'auto'
'Execute a block, or store it in a variable, per the user\'s request.'
def store_or_execute(self, block, name):
if name: self.shell.user_ns[name] = SList(block.splitlines()) print ("Block assigned to '%s'" % name) else: b = self.preclean_input(block) self.shell.user_ns['pasted_block'] = b self.shell.using_paste_magics = True try: self.shell.run_cell(b) ...
'Rerun a previously pasted command.'
def rerun_pasted(self, name='pasted_block'):
b = self.shell.user_ns.get(name) if (b is None): raise UsageError('No previous pasted block available') if (not isinstance(b, str)): raise UsageError("Variable 'pasted_block' is not a string, can't execute") print ("Re-executing '%s...' (%d chars...
'Toggle autoindent on/off (deprecated)'
@line_magic def autoindent(self, parameter_s=''):
print '%autoindent is deprecated since IPython 5: you can now paste multiple lines without turning autoindentation off.' self.shell.set_autoindent() print ('Automatic indentation is:', ['OFF', 'ON'][self.shell.autoindent])
'Paste & execute a pre-formatted code block from clipboard. You must terminate the block with \'--\' (two minus-signs) or Ctrl-D alone on the line. You can also provide your own sentinel with \'%paste -s %%\' (\'%%\' is the new sentinel for this operation). The block is dedented prior to execution to enable execution o...
@line_magic def cpaste(self, parameter_s=''):
(opts, name) = self.parse_options(parameter_s, 'rqs:', mode='string') if ('r' in opts): self.rerun_pasted() return quiet = ('q' in opts) sentinel = opts.get('s', u'--') block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) self.store_or_execute(block, name)
'Paste & execute a pre-formatted code block from clipboard. The text is pulled directly from the clipboard without user intervention and printed back on the screen before execution (unless the -q flag is given to force quiet mode). The block is dedented prior to execution to enable execution of method definitions. \'>\...
@line_magic def paste(self, parameter_s=''):
(opts, name) = self.parse_options(parameter_s, 'rq', mode='string') if ('r' in opts): self.rerun_pasted() return try: block = self.shell.hooks.clipboard_get() except TryNext as clipboard_exc: message = getattr(clipboard_exc, 'args') if message: error(m...
'%kill_embedded : deactivate for good the current embedded IPython This function (after asking for confirmation) sets an internal flag so that an embedded IPython will never activate again for the given call location. This is useful to permanently disable a shell that is being called inside a loop: once you\'ve figured...
@line_magic @magic_arguments.magic_arguments() @magic_arguments.argument('-i', '--instance', action='store_true', help='Kill instance instead of call location') @magic_arguments.argument('-x', '--exit', action='store_true', help='Also exit the current session') @magic_arguments.argument('-y',...
args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) print args if args.instance: if (not args.yes): kill = ask_yes_no('Are you sure you want to kill this embedded instance? [y/N] ', 'n') else: kill = True if...
'%exit_raise Make the current embedded kernel exit and raise and exception. This function sets an internal flag so that an embedded IPython will raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is useful to permanently exit a loop that create IPython embed instance.'
@line_magic def exit_raise(self, parameter_s=''):
self.shell.should_raise = True self.shell.ask_exit()
'Disable the current Instance creation location'
def _disable_init_location(self):
InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
'Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing.'
def init_sys_modules(self):
pass
'Activate the interactive interpreter. __call__(self,header=\'\',local_ns=None,module=None,dummy=None) -> Start the interpreter shell with the given local and global namespaces, and optionally print a header string at startup. The shell can be globally activated/deactivated using the dummy_mode attribute. This allows y...
def __call__(self, header='', local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None, compile_flags=None, **kw):
self.keep_running = True clid = kw.pop('_call_location_id', None) if (not clid): frame = sys._getframe(1) clid = ('%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) self._call_location_id = clid if (not self.embedded_active): return self.exit_now = False if (dummy ...
'Embeds IPython into a running python program. Parameters local_ns, module Working local namespace (a dict) and module (a module or similar object). If given as None, they are automatically taken from the scope where the shell was called, so that program variables become visible. stack_depth : int How many levels in th...
def mainloop(self, local_ns=None, module=None, stack_depth=0, display_banner=None, global_ns=None, compile_flags=None):
if ((global_ns is not None) and (module is None)): raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.") if (display_banner is not None): warnings.warn('Th...
'Adds the cookies configured from UI to the providers requests session :return: A tuple with the the (success result, and a descriptive message in str)'
def add_cookies_from_ui(self):
if (self.enable_cookies and self.cookies): cookie_validator = re.compile(u'^(\\w+=\\w+)(;\\w+=\\w+)*$') if (not cookie_validator.match(self.cookies)): return (False, u'Cookie is not correctly formatted: {0}'.format(self.cookies)) add_dict_to_cookiejar(self.session....
'Search the URL titles by kind for the given `title`. :param str title: title to search for. :return: the URL titles by kind. :rtype: collections.defaultdict'
@region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME) def _search_url_titles(self, title):
logger.info(u'Searching title name for %r', title) r = self.session.get((self.server_url + u'subtitle/search/'), params={u'q': title}, timeout=10) r.raise_for_status() if (r.history and all([(h.status_code == 302) for h in r.history])): logger.debug(u'Redirected to the subti...
'Get the ``dict`` of show ids per series by querying the `shows` page. :return: show id per series, lower case and without quotes. :rtype: dict'
@region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME) def _get_show_ids(self):
logger.info(u'Getting show ids') params = {u'apikey': self.apikey} r = self.session.get((self.server_url + u'shows'), timeout=10, params=params) r.raise_for_status() root = etree.fromstring(r.content) show_ids = {} for show in root.findall(u'data/shows/show'): if (show.find(u'n...
'Search the show id from the `series` :param str series: series of the episode. :return: the show id, if found. :rtype: int or None'
@region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME) def _search_show_id(self, series):
params = {u'apikey': self.apikey, u'q': series} logger.info(u'Searching show ids with %r', params) r = self.session.get((self.server_url + u'shows/search'), params=params, timeout=10) r.raise_for_status() root = etree.fromstring(r.content) if (int(root.find(u'data/count').text) == 0)...
'Get the best matching show id for `series`. First search in the result of :meth:`_get_show_ids` and fallback on a search with :meth:`_search_show_id` :param str series: series of the episode. :param str country_code: the country in which teh show is aired. :return: the show id, if found. :rtype: int or None'
def get_show_id(self, series, country_code=None):
series_sanitized = sanitize(series).lower() show_ids = self._get_show_ids() show_id = None if ((not show_id) and country_code): logger.debug(u'Getting show id with country') show_id = show_ids.get(u'{0} {1}'.format(series_sanitized, country_code.lower())) if (not show_...
'Try to delete a show :param indexer_id: The unique id of the show to delete :param remove_files: ``True`` to remove the files associated with the show, ``False`` otherwise :return: A tuple containing: - an error message if the show could not be deleted, ``None`` otherwise - the show object that was deleted, if it exis...
@staticmethod def delete(indexer_id, remove_files=False):
(error, show) = Show._validate_indexer_id(indexer_id) if (error is not None): return (error, show) if show: try: sickbeard.showQueueScheduler.action.remove_show(show, bool(remove_files)) except CantRemoveShowException as exception: return (ex(exception), show)...
'Find a show by its indexer id in the provided list of shows :param shows: The list of shows to search in :param indexer_id: The indexer id of the desired show :return: The desired show if found, ``None`` if not found :throw: ``MultipleShowObjectsException`` if multiple shows match the provided ``indexer_id``'
@staticmethod def find(shows, indexer_id):
if ((indexer_id is None) or (shows is None) or (len(shows) == 0)): return None indexer_ids = ([indexer_id] if (not isinstance(indexer_id, list)) else indexer_id) results = [show for show in shows if (show.indexerid in indexer_ids)] if (not results): return None if (len(results) == 1)...
'Change the pause state of a show :param indexer_id: The unique id of the show to update :param pause: ``True`` to pause the show, ``False`` to resume the show, ``None`` to toggle the pause state :return: A tuple containing: - an error message if the pause state could not be changed, ``None`` otherwise - the show objec...
@staticmethod def pause(indexer_id, pause=None):
(error, show) = Show._validate_indexer_id(indexer_id) if (error is not None): return (error, show) if (pause is None): show.paused = (not show.paused) else: show.paused = pause show.saveToDB() return (None, show)
'Try to refresh a show :param indexer_id: The unique id of the show to refresh :return: A tuple containing: - an error message if the show could not be refreshed, ``None`` otherwise - the show object that was refreshed, if it exists, ``None`` otherwise'
@staticmethod def refresh(indexer_id):
(error, show) = Show._validate_indexer_id(indexer_id) if (error is not None): return (error, show) try: sickbeard.showQueueScheduler.action.refresh_show(show) except CantRefreshShowException as exception: return (ex(exception), show) return (None, show)
'Check that the provided indexer_id is valid and corresponds with a known show :param indexer_id: The indexer id to check :return: A tuple containing: - an error message if the indexer id is not correct, ``None`` otherwise - the show object corresponding to ``indexer_id`` if it exists, ``None`` otherwise'
@staticmethod def _validate_indexer_id(indexer_id):
try: indexer_id = int(indexer_id) except (TypeError, ValueError): return (u'Invalid show ID', None) try: show = Show.find(sickbeard.showList, indexer_id) except MultipleShowObjectsException: return (u'Unable to find the specified show', None) retu...
'Removes the selected history :param toRemove: Contains the properties of the log entries to remove'
def remove(self, toRemove):
query = u'' for item in toRemove: query = ((query + u' OR ') if (query != u'') else u'') query = (query + u'(date IN ({0}) AND showid = {1} AND season = {2} AND episode = {3})'.format(u','.join(item[u'dates']), item[u'show_id'], item[u'season'], it...
'Clear all the history'
def clear(self):
self.db.action(u'DELETE FROM history WHERE 1 = 1')
':param limit: The maximum number of elements to return :param action: The type of action to filter in the history. Either \'downloaded\' or \'snatched\'. Anything else or no value will return everything (up to ``limit``) :return: The last ``limit`` elements of type ``action`` in the history'
def get(self, limit=100, action=None):
actions = History._get_actions(action) limit = History._get_limit(limit) common_sql = u'SELECT action, date, episode, provider, h.quality, resource, season, show_name, showid FROM history h, tv_shows s WHERE h.showid = s.indexer_id ' filter_sql = ...
'Remove all elements older than 30 days from the history'
def trim(self):
self.db.action(u'DELETE FROM history WHERE date < ?', [(datetime.today() - timedelta(days=30)).strftime(History.date_format)])
':param categories: The categories of coming episodes. See ``ComingEpisodes.categories`` :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts`` :param group: ``True`` to group the coming episodes by category, ``False`` otherwise :param paused: ``True`` to include paused shows, ``False`` oth...
@staticmethod def get_coming_episodes(categories, sort, group, paused=sickbeard.COMING_EPS_DISPLAY_PAUSED):
categories = ComingEpisodes._get_categories(categories) sort = ComingEpisodes._get_sort(sort) today = date.today().toordinal() recently = (date.today() - timedelta(days=sickbeard.COMING_EPS_MISSED_RANGE)).toordinal() next_week = (date.today() + timedelta(days=7)).toordinal() db = DBConnection(ro...
'Gets a list of most popular TV series from imdb'
def __init__(self):
self.url = u'http://akas.imdb.com/search/title' self.params = {u'at': 0, u'sort': u'moviemeter', u'title_type': u'tv_series', u'year': u'{0},{1}'.format((date.today().year - 1), (date.today().year + 1))} self.session = helpers.make_session()
'Get popular show information from IMDB'
def fetch_popular_shows(self):
popular_shows = [] data = helpers.getURL(self.url, session=self.session, params=self.params, headers={u'Referer': u'http://akas.imdb.com/'}, returns=u'text') if (not data): return None soup = BeautifulSoup(data, u'html5lib') results = soup.find(u'table', {u'class': u'results'}) rows = re...
'Store cache of image in cache dir :param image_url: Source URL'
def cache_image(self, image_url):
path = ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, u'images', u'imdb_popular')) if (not ek(os.path.exists, path)): ek(os.makedirs, path) full_path = ek(os.path.join, path, ek(os.path.basename, image_url)) if (not ek(os.path.isfile, full_path)): helpers.download_file(image_u...
'Get popular show information from IMDB'
def fetch_latest_hot_shows(self):
shows = [] result = [] shows = anidbquery.query(QUERY_HOT) for show in shows: try: recommended_show = RecommendedShow(show.id, show.titles[u'x-jat'][0], 1, show.tvdbid, cache_subfolder=self.cache_subfolder, rating=str(show.ratings[u'temporary'][u'rating']), votes=str(try_int(show.rat...
'Create a show recommendation :param show_id: as provided by the list provider :param title: of the show as displayed in the recommended show page :param indexer: used to map the show to :param indexer_id: a mapped indexer_id for indexer :param cache_subfolder: to store images :param rating: of the show in percent :par...
def __init__(self, show_id, title, indexer, indexer_id, cache_subfolder=u'recommended', rating=None, votes=None, image_href=None, image_src=None):
self.show_id = show_id self.title = title self.indexer = indexer self.indexer_id = indexer_id self.cache_subfolder = cache_subfolder self.rating = rating self.votes = votes self.image_href = image_href self.image_src = image_src self.show_in_list = (self.indexer_id in {show.index...
'Store cache of image in cache dir :param image_url: Source URL'
def cache_image(self, image_url):
if (not self.cache_subfolder): return self.image_src = ek(posixpath.join, u'images', self.cache_subfolder, ek(os.path.basename, image_url)) path = ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, u'images', self.cache_subfolder)) if (not ek(os.path.exists, path)): ek(os.makedirs...
'The resolution tag found in the name :returns: an empty string if not found'
@property def res(self):
attr = u'res' match = self._get_match_obj(attr) return (u'' if (not match) else match.group().lower())
'The vertical found in the name :returns: an empty string if not found'
@property def vres(self):
attr = u'res' match = self._get_match_obj(attr) return (None if (not match) else try_int(match.group(u'vres')))
'The type of scan found in the name e.g. `i` for Interlaced, `p` for Progressive Scan :returns: an empty string if not found'
@property def scan(self):
attr = u'res' match = self._get_match_obj(attr) return (match.group(u'scan').lower() if (match and match.group(u'scan')) else u'')
'The bluray tag found in the name :returns: an empty string if not found'
@property def bluray(self):
attr = u'bluray' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
'The hddvd tag found in the name :returns: an empty string if not found'
@property def hddvd(self):
attr = u'dvd' match = self._get_match_obj(attr) return (None if (not match) else match.group(u'hd'))
'The iTunes tag found in the name :returns: an empty string if not found'
@property def itunes(self):
attr = u'itunes' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
'The web tag found in the name :returns: an empty string if not found'
@property def web(self):
if (u'dlmux' in self.name.lower()): return u'dlmux' if self.netflix: return self.netflix else: attr = u'web' match = self._get_match_obj(attr) return (u'' if (not match) else (match.group(u'type') or u'dl'))
'The sat tag found in the name :returns: an empty string if not found'
@property def sat(self):
attr = u'sat' match = self._get_match_obj(attr) return (None if (not match) else match.group())
'The dvd tag found in the name :returns: an empty string if not found'
@property def dvdrip(self):
attr = u'dvd' match = self._get_match_obj(attr) return (u'' if (not match) else match.group(u'rip'))
'The dvd tag found in the name :returns: an empty string if not found'
@property def dvd(self):
attr = u'dvd' match = self._get_match_obj(attr) return (u'' if (not (match or self.hddvd)) else match.group())
'The hevc tag found in the name :returns: an empty string if not found'
@property def hevc(self):
return (u'' if (not (self.avc[:(-1)] == u'5')) else self.avc)
'The avc tag found in the name :returns: an empty string if not found'
@property def avc(self):
attr = u'avc' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
'The free avc codec found in the name e.g.: x.265 or X264 :returns: an empty string if not found'
@property def avc_free(self):
return (u'' if (not self.avc.lower().startswith(u'x')) else self.avc)
'The non-free avc codec found in the name e.g.: h.265 or H264 :returns: an empty string if not found'
@property def avc_non_free(self):
return (u'' if (not self.avc.lower().startswith(u'h')) else self.avc)
'The mpeg tag found in the name :returns: an empty string if not found'
@property def mpeg(self):
attr = u'mpeg' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
'The xvid tag found in the name :returns: an empty string if not found'
@property def xvid(self):
attr = u'xvid' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
'The hrws tag found in the name HR = High Resolution WS = Wide Screen PD TV = Pure Digital Television :returns: an empty string if not found'
@property def hrws(self):
attr = u'hrws' match = None if (self.avc and (self.tv == u'pd')): regex = re.compile(u'(hr.ws.pdtv).{0}'.format(self.avc), re.I) match = self._get_match_obj(attr, regex) return (u'' if (not match) else match.group())
'The raw tag found in the name :return: an empty string if not found'
@property def raw(self):
attr = u'raw' match = None if (self.res and (self.tv == u'hd')): regex = re.compile(u'({0}.hdtv)'.format(self.res), re.I) match = self._get_match_obj(attr, regex) return (u'' if (not match) else match.group())
'Netflix tage found in name :return: an empty string if not found'
@property def netflix(self):
attr = u'netflix' match = self._get_match_obj(attr) return (u'' if (not match) else match.group())
':param indexer_id: The indexer id of the show :param media_format: The format of the media to get. Must be either \'normal\' or \'thumb\''
def __init__(self, indexer_id, media_format=u'normal'):
self.indexer_id = try_int(indexer_id, 0) if (media_format in (u'normal', u'thumb')): self.media_format = media_format else: self.media_format = u'normal'
':return: The name of the file to use as a fallback if the show media file is missing'
@abstractmethod def get_default_media_name(self):
return u''
':return: The content of the desired media file'
def get_media(self):
static_media_path = self.get_static_media_path() if ek(isfile, static_media_path): with open(static_media_path, u'rb') as content: return content.read() return None
':return: The path to the media related to ``self.indexer_id``'
@abstractmethod def get_media_path(self):
return u''
':return: The root folder containing the media'
@staticmethod def get_media_root():
return ek(join, sickbeard.PROG_DIR, u'gui', (sickbeard.GUI_NAME or u'slick'))
':return: The mime type of the current media'
def get_media_type(self):
static_media_path = self.get_static_media_path() if ek(isfile, static_media_path): return guess_type(static_media_path)[0] return u''
':return: The show object associated with ``self.indexer_id`` or ``None``'
def get_show(self):
try: return Show.find(sickbeard.showList, self.indexer_id) except MultipleShowObjectsException: return None
':return: The full path to the media'
def get_static_media_path(self):
if self.get_show(): media_path = self.get_media_path() if ek(isfile, media_path): return normpath(media_path) image_path = ek(join, self.get_media_root(), u'images', self.get_default_media_name()) return image_path.replace(u'\\', u'/')
'Set up test.'
def setUp(self):
super(DBBasicTests, self).setUp() self.sr_db = test.db.DBConnection()
'Test selecting from the database'
def test_select(self):
self.sr_db.select("SELECT * FROM tv_episodes WHERE showid = ? AND location != ''", [0])
'Set up test.'
def setUp(self):
super(DBMultiTests, self).setUp() self.sr_db = test.db.DBConnection()
'Select from the database.'
def select(self):
self.sr_db.select("SELECT * FROM tv_episodes WHERE showid = ? AND location != ''", [0])
'Test multi-threaded selection from the database'
def test_threaded(self):
for _ in range(4): thread = threading.Thread(target=self.select) thread.start()
'Set up tests'
def setUp(self):
super(TVShowTests, self).setUp() sickbeard.showList = []
'test init indexer id'
def test_init_indexerid(self):
show = TVShow(1, 1, 'en') self.assertEqual(show.indexerid, 1)
'test change indexer id'
def test_change_indexerid(self):
show = TVShow(1, 1, 'en') show.name = 'show name' show.network = 'cbs' show.genre = 'crime' show.runtime = 40 show.status = 'Ended' show.default_ep_status = '5' show.airs = 'monday' show.startyear = 1987 show.saveToDB() show.loadFromDB() show.indexerid = 2 show.sav...
'test set name'
def test_set_name(self):
show = TVShow(1, 1, 'en') show.name = 'newName' show.saveToDB() show.loadFromDB() self.assertEqual(show.name, 'newName')
'Set up'
def setUp(self):
super(TVEpisodeTests, self).setUp() sickbeard.showList = []
'test init empty db'
def test_init_empty_db(self):
show = TVShow(1, 1, 'en') episode = TVEpisode(show, 1, 1) episode.name = 'asdasdasdajkaj' episode.saveToDB() episode.loadFromDB(1, 1) self.assertEqual(episode.name, 'asdasdasdajkaj')
'Set up'
def setUp(self):
super(TVTests, self).setUp() sickbeard.showList = []
'Test get episodes'
@staticmethod def test_get_episode():
show = TVShow(1, 1, 'en') show.name = 'show name' show.network = 'cbs' show.genre = 'crime' show.runtime = 40 show.status = 'Ended' show.default_ep_status = '5' show.airs = 'monday' show.startyear = 1987 show.saveToDB() sickbeard.showList = [show]
'Fake getting a url :param url: :param headers: :return:'
@staticmethod def _fake_get_url(url, headers=None):
_ = (url, headers) return _create_fake_xml(search_items)
'Fake is active'
@staticmethod def _fake_is_active():
return True
'Initialize tests :param something: :return:'
def __init__(self, something):
for provider in sickbeard.providers.sortedProviderList(): provider.get_url = self._fake_get_url super(SearchTest, self).__init__(something)
'Test check_section'
def test_check_section(self):
CFG = ConfigObj('config.ini', encoding='UTF-8') self.assertFalse(config.check_section(CFG, 'General')) self.assertTrue(config.check_section(CFG, 'General'))
'Test checkbox_to_value'
def test_checkbox_to_value(self):
self.assertTrue(config.checkbox_to_value(1)) self.assertTrue(config.checkbox_to_value(['option', 'True'])) self.assertEqual(config.checkbox_to_value('0', 'yes', 'no'), 'no')
'Test clean_host'
def test_clean_host(self):
self.assertEqual(config.clean_host('http://127.0.0.1:8080'), '127.0.0.1:8080') self.assertEqual(config.clean_host('https://mail.google.com/mail'), 'mail.google.com') self.assertEqual(config.clean_host('http://localhost:8081/home/displayShow?show=80379#season-10'), 'localhost:8081') self.assertEqual(conf...