idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
240,200
def tag ( self , tags ) : tags = tags . lower ( ) previous = self . tagged tagset = previous . copy ( ) for tag in tags . replace ( ',' , ' ' ) . split ( ) : if tag . startswith ( '-' ) : tagset . discard ( tag [ 1 : ] ) elif tag . startswith ( '+' ) : tagset . add ( tag [ 1 : ] ) else : tagset . add ( tag ) tagset . d...
Add or remove tags .
240,201
def set_throttle ( self , name ) : if name . lower ( ) == "null" : name = "NULL" if name . lower ( ) == "none" : name = '' if name not in self . _engine . known_throttle_names : if self . _engine . _rpc . throttle . up . max ( xmlrpc . NOHASH , name ) == - 1 : if self . _engine . _rpc . throttle . down . max ( xmlrpc ....
Assign to throttle group .
240,202
def purge ( self ) : def partial_file ( item ) : "Filter out partial files" return item . completed_chunks < item . size_chunks self . cull ( file_filter = partial_file , attrs = [ "get_completed_chunks" , "get_size_chunks" ] )
Delete PARTIAL data files and remove torrent from client .
240,203
def load_config ( self , namespace = None , rcfile = None ) : if namespace is None : namespace = config if namespace . scgi_url : return if not rcfile : rcfile = getattr ( config , "rtorrent_rc" , None ) if not rcfile : raise error . UserError ( "No 'rtorrent_rc' path defined in configuration!" ) if not os . path . isf...
Load file given in rcfile .
240,204
def _resolve_viewname ( self , viewname ) : if viewname == "-" : try : viewname = self . open ( ) . ui . current_view ( ) except xmlrpc . ERRORS as exc : raise error . EngineError ( "Can't get name of current view: %s" % ( exc ) ) return viewname
Check for special view names and return existing rTorrent one .
240,205
def open ( self ) : if self . _rpc is not None : return self . _rpc self . load_config ( ) if not config . scgi_url : raise error . UserError ( "You need to configure a XMLRPC connection, read" " https://pyrocore.readthedocs.io/en/latest/setup.html" ) self . _rpc = xmlrpc . RTorrentProxy ( config . scgi_url ) self . ve...
Open connection .
240,206
def multicall ( self , viewname , fields ) : commands = tuple ( 'd.{}=' . format ( x ) for x in fields ) result_type = namedtuple ( 'DownloadItem' , [ x . replace ( '.' , '_' ) for x in fields ] ) items = self . open ( ) . d . multicall ( viewname , * commands ) return [ result_type ( * x ) for x in items ]
Query the given fields of items in the given view .
240,207
def item ( self , infohash , prefetch = None , cache = False ) : return next ( self . items ( infohash , prefetch , cache ) )
Fetch a single item by its info hash .
240,208
def _load_rules ( self ) : for ruleset in self . active_rulesets : section_name = 'sweep_rules_' + ruleset . lower ( ) try : ruledefs = getattr ( self . config , section_name ) except AttributeError : raise error . UserError ( "There is no [{}] section in your configuration" . format ( section_name . upper ( ) ) ) for ...
Load rule definitions from config .
240,209
def _parse_schedule ( self , schedule ) : result = { } for param in shlex . split ( str ( schedule ) ) : try : key , val = param . split ( '=' , 1 ) except ( TypeError , ValueError ) : self . fatal ( "Bad param '%s' in job schedule '%s'" % ( param , schedule ) ) else : result [ key ] = val return result
Parse a job schedule .
240,210
def _validate_config ( self ) : groups = dict ( job = defaultdict ( Bunch ) , httpd = defaultdict ( Bunch ) , ) for key , val in config . torque . items ( ) : if val . isdigit ( ) : config . torque [ key ] = val = int ( val ) elif val . lower ( ) in ( matching . TRUE | matching . FALSE ) : val = matching . truth ( str ...
Handle and check configuration .
240,211
def _add_jobs ( self ) : for name , params in self . jobs . items ( ) : if params . active : params . handler = params . handler ( params ) self . sched . add_cron_job ( params . handler . run , ** params . schedule )
Add configured jobs .
240,212
def _init_wsgi_server ( self ) : self . wsgi_server = None if self . httpd . active : from waitress . server import WSGIServer from pyrocore . daemon import webapp wsgi_app = webapp . make_app ( self . httpd ) self . LOG . debug ( "Waitress config: %r" % self . httpd . waitress ) self . wsgi_server = WSGIServer ( wsgi_...
Set up WSGI HTTP server .
240,213
def _run_forever ( self ) : while True : try : tick = time . time ( ) asyncore . loop ( timeout = self . POLL_TIMEOUT , use_poll = True ) tick += self . POLL_TIMEOUT - time . time ( ) if tick > 0 : time . sleep ( min ( tick , self . POLL_TIMEOUT ) ) except KeyboardInterrupt as exc : self . LOG . info ( "Termination req...
Run configured jobs until termination request .
240,214
def read_blob ( arg ) : result = None if arg == '@-' : result = sys . stdin . read ( ) elif any ( arg . startswith ( '@{}://' . format ( x ) ) for x in { 'http' , 'https' , 'ftp' , 'file' } ) : if not requests : raise error . UserError ( "You must 'pip install requests' to support @URL arguments." ) try : response = re...
Read a BLOB from given
240,215
def open ( self ) : if not self . proxy : if not config . scgi_url : config . engine . load_config ( ) if not config . scgi_url : self . LOG . error ( "You need to configure a XMLRPC connection, read" " https://pyrocore.readthedocs.io/en/latest/setup.html" ) self . proxy = xmlrpc . RTorrentProxy ( config . scgi_url ) s...
Open connection and return proxy .
240,216
def execute ( self , proxy , method , args ) : try : result = getattr ( proxy , method ) ( raw_xml = self . options . xml , * tuple ( args ) ) except xmlrpc . ERRORS as exc : self . LOG . error ( "While calling %s(%s): %s" % ( method , ", " . join ( repr ( i ) for i in args ) , exc ) ) self . return_code = error . EX_N...
Execute given XMLRPC call .
240,217
def do_repl ( self ) : from prompt_toolkit import prompt from prompt_toolkit . history import FileHistory from prompt_toolkit . auto_suggest import AutoSuggestFromHistory from prompt_toolkit . contrib . completers import WordCompleter self . options . quiet = False proxy = self . open ( ) ps1 = proxy . session . name (...
REPL for rTorrent XMLRPC commands .
240,218
def do_import ( self ) : tmp_import = None try : if self . args [ 0 ] . startswith ( '@' ) and self . args [ 0 ] != '@-' : import_file = os . path . expanduser ( self . args [ 0 ] [ 1 : ] ) if not os . path . isfile ( import_file ) : self . parser . error ( "File not found (or not a file): {}" . format ( import_file ) ...
Handle import files or streams passed with - i .
240,219
def do_command ( self ) : method = self . args [ 0 ] raw_args = self . args [ 1 : ] if '=' in method : if raw_args : self . parser . error ( "Please don't mix rTorrent and shell argument styles!" ) method , raw_args = method . split ( '=' , 1 ) raw_args = raw_args . split ( ',' ) self . execute ( self . open ( ) , meth...
Call a single command with arguments .
240,220
def download_resource ( self , download_url , target , guard ) : download_url = download_url . strip ( ) if not os . path . isabs ( target ) : target = os . path . join ( config . config_dir , target ) if os . path . exists ( os . path . join ( target , guard ) ) : self . LOG . info ( "Already have '%s' in '%s'..." % (...
Helper to download and install external resources .
240,221
def fmt_duration ( secs ) : return ' ' . join ( fmt . human_duration ( secs , 0 , precision = 2 , short = True ) . strip ( ) . split ( ) )
Format a duration in seconds .
240,222
def disk_free ( path ) : stats = os . statvfs ( path ) return stats . f_bavail * stats . f_frsize
Return free bytes on partition holding path .
240,223
def truth ( val , context ) : try : 0 + val except TypeError : lower_val = val . lower ( ) if lower_val in TRUE : return True elif lower_val in FALSE : return False else : raise FilterError ( "Bad boolean value %r in %r (expected one of '%s', or '%s')" % ( val , context , "' '" . join ( TRUE ) , "' '" . join ( FALSE ) ...
Convert truth value in val to a boolean .
240,224
def _time_ym_delta ( timestamp , delta , months ) : timestamp = list ( time . localtime ( timestamp ) ) timestamp [ int ( months ) ] += delta return time . mktime ( timestamp )
Helper to add a year or month delta to a timestamp .
240,225
def unquote_pre_filter ( pre_filter , _regex = re . compile ( r'[\\]+' ) ) : if pre_filter . startswith ( '"' ) and pre_filter . endswith ( '"' ) : pre_filter = pre_filter [ 1 : - 1 ] pre_filter = _regex . sub ( lambda x : x . group ( 0 ) [ : len ( x . group ( 0 ) ) // 2 ] , pre_filter ) return pre_filter
Unquote a pre - filter condition .
240,226
def _create_filter ( self , condition ) : comparison = re . match ( r"^(%s)(<[>=]?|>=?|!=|~)(.*)$" % self . ident_re , condition ) if comparison : name , comparison , values = comparison . groups ( ) if values and values [ 0 ] in "+-" : raise FilterError ( "Comparison operator cannot be followed by '%s' in '%s'" % ( va...
Create a filter object from a textual condition .
240,227
def parse ( self , conditions ) : conditions_text = conditions try : conditions = shlex . split ( fmt . to_utf8 ( conditions ) ) except AttributeError : conditions_text = self . _tree2str ( conditions ) if not conditions : raise FilterError ( "No conditions given at all!" ) negate = conditions [ : 1 ] == [ "NOT" ] if n...
Parse filter conditions .
240,228
def _flux_engine_data ( engine ) : data = stats . engine_data ( engine ) data [ "up_rate" ] = data [ "upload" ] [ 0 ] data [ "up_limit" ] = data [ "upload" ] [ 1 ] data [ "down_rate" ] = data [ "download" ] [ 0 ] data [ "down_limit" ] = data [ "download" ] [ 1 ] data [ "version" ] = data [ "versions" ] [ 0 ] views = da...
Return rTorrent data set for pushing to InfluxDB .
240,229
def run ( self ) : try : proxy = config_ini . engine . open ( ) self . LOG . info ( "Stats for %s - up %s, %s" % ( config_ini . engine . engine_id , fmt . human_duration ( proxy . system . time ( ) - config_ini . engine . startup , 0 , 2 , True ) . strip ( ) , proxy ) ) except ( error . LoggableError , xmlrpc . ERRORS ...
Statistics logger job callback .
240,230
def _influxdb_url ( self ) : url = "{0}/db/{1}/series" . format ( self . influxdb . url . rstrip ( '/' ) , self . config . dbname ) if self . influxdb . user and self . influxdb . password : url += "?u={0}&p={1}" . format ( self . influxdb . user , self . influxdb . password ) return url
Return REST API URL to access time series .
240,231
def _push_data ( self ) : if not ( self . config . series or self . config . series_host ) : self . LOG . info ( "Misconfigured InfluxDB job, neither 'series' nor 'series_host' is set!" ) return fluxdata = [ ] if self . config . series : try : config_ini . engine . open ( ) data , views = _flux_engine_data ( config_ini...
Push stats data to InfluxDB .
240,232
def run ( self ) : from pyrocore import config try : config . engine . open ( ) items = [ ] self . run_filter ( items ) except ( error . LoggableError , xmlrpc . ERRORS ) as exc : self . LOG . warn ( str ( exc ) )
Filter job callback .
240,233
def replace_fields ( meta , patterns ) : for pattern in patterns : try : field , regex , subst , _ = pattern . split ( pattern [ - 1 ] ) namespace = meta keypath = [ i . replace ( '\0' , '.' ) for i in field . replace ( '..' , '\0' ) . split ( '.' ) ] for key in keypath [ : - 1 ] : namespace = namespace [ key ] namespa...
Replace patterns in fields .
240,234
def connect ( config_dir = None , optional_config_files = None , cron_cfg = "cron" ) : from pyrocore . scripts . base import ScriptBase from pyrocore . util import load_config ScriptBase . setup ( cron_cfg = cron_cfg ) load_config . ConfigLoader ( config_dir ) . load ( optional_config_files or [ ] ) from pyrocore impor...
Initialize everything for interactive use .
240,235
def setup ( cls , cron_cfg = "cron" ) : random . seed ( ) logging_cfg = cls . LOGGING_CFG if "%s" in logging_cfg : logging_cfg = logging_cfg % ( cron_cfg if "--cron" in sys . argv [ 1 : ] else "scripts" , ) logging_cfg = os . path . expanduser ( logging_cfg ) if os . path . exists ( logging_cfg ) : logging . HERE = os ...
Set up the runtime environment .
240,236
def _get_pkg_meta ( self ) : logger = logging . getLogger ( 'pyrocore.scripts.base.version_info' ) pkg_info = None warnings = [ ] for info_ext , info_name in ( ( '.dist-info' , 'METADATA' ) , ( '.egg-info' , 'PKG-INFO' ) ) : try : pkg_path = os . path . join ( __file__ . split ( __name__ . replace ( '.' , os . sep ) ) ...
Try to find package metadata .
240,237
def add_bool_option ( self , * args , ** kwargs ) : dest = [ o for o in args if o . startswith ( "--" ) ] [ 0 ] . replace ( "--" , "" ) . replace ( "-" , "_" ) self . parser . add_option ( dest = dest , action = "store_true" , default = False , help = kwargs [ 'help' ] , * args )
Add a boolean option .
240,238
def add_value_option ( self , * args , ** kwargs ) : kwargs [ 'metavar' ] = args [ - 1 ] if 'dest' not in kwargs : kwargs [ 'dest' ] = [ o for o in args if o . startswith ( "--" ) ] [ 0 ] . replace ( "--" , "" ) . replace ( "-" , "_" ) if 'default' in kwargs and kwargs [ 'default' ] : kwargs [ 'help' ] += " [%s]" % kwa...
Add a value option .
240,239
def handle_completion ( self ) : if len ( sys . argv ) > 1 and sys . argv [ 1 ] . startswith ( "--help-completion-" ) : handler = getattr ( self , sys . argv [ 1 ] [ 2 : ] . replace ( '-' , '_' ) , None ) if handler : print '\n' . join ( sorted ( handler ( ) ) ) self . STD_LOG_LEVEL = logging . DEBUG sys . exit ( error...
Handle shell completion stuff .
240,240
def help_completion_options ( self ) : for opt in self . parser . option_list : for lopt in opt . _long_opts : yield lopt
Return options of this command .
240,241
def fatal ( self , msg , exc = None ) : if exc is not None : self . LOG . fatal ( "%s (%s)" % ( msg , exc ) ) if self . options . debug : return else : self . LOG . fatal ( msg ) sys . exit ( error . EX_SOFTWARE )
Exit on a fatal error .
240,242
def run ( self ) : log_total = True try : try : self . get_options ( ) self . mainloop ( ) except error . LoggableError , exc : if self . options . debug : raise try : msg = str ( exc ) except UnicodeError : msg = unicode ( exc , "UTF-8" ) self . LOG . error ( msg ) sys . exit ( error . EX_SOFTWARE ) except KeyboardInt...
The main program skeleton .
240,243
def add_options ( self ) : super ( ScriptBaseWithConfig , self ) . add_options ( ) self . add_value_option ( "--config-dir" , "DIR" , help = "configuration directory [{}]" . format ( os . environ . get ( 'PYRO_CONFIG_DIR' , self . CONFIG_DIR_DEFAULT ) ) ) self . add_value_option ( "--config-file" , "PATH" , action = "a...
Add configuration options .
240,244
def check_for_connection ( self ) : for idx , arg in enumerate ( self . args ) : if arg . startswith ( '@' ) : if arg [ 1 : ] not in config . connections : self . parser . error ( "Undefined connection '{}'!" . format ( arg [ 1 : ] ) ) config . scgi_url = config . connections [ arg [ 1 : ] ] self . LOG . debug ( "Switc...
Scan arguments for a
240,245
def quit ( self ) : self . script . LOG . warn ( "Abort due to user choice!" ) sys . exit ( self . QUIT_RC )
Exit the program due to user s choices .
240,246
def redirect ( req , _log = pymagic . get_lazy_logger ( "redirect" ) ) : log = req . environ . get ( "wsgilog.logger" , _log ) target = req . relative_url ( req . urlvars . to ) log . info ( "Redirecting '%s' to '%s'" % ( req . url , target ) ) return exc . HTTPMovedPermanently ( location = target )
Redirect controller to emit a HTTP 301 .
240,247
def make_app ( httpd_config ) : htdocs_paths = [ os . path . realpath ( os . path . join ( config . config_dir , "htdocs" ) ) , os . path . join ( os . path . dirname ( config . __file__ ) , "data" , "htdocs" ) , ] return ( Router ( ) . add_route ( "/" , controller = redirect , to = "/static/index.html" ) . add_route (...
Factory for the monitoring webapp .
240,248
def guarded ( self , func , * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except ( EnvironmentError , error . LoggableError , xmlrpc . ERRORS ) as g_exc : if func . __name__ not in self . ERRORS_LOGGED : self . LOG . warn ( "While calling '%s': %s" % ( func . __name__ , g_exc ) ) self . ERRORS_LOGGED ...
Call a function return None on errors .
240,249
def json_engine ( self , req ) : try : return stats . engine_data ( config . engine ) except ( error . LoggableError , xmlrpc . ERRORS ) as torrent_exc : raise exc . HTTPInternalServerError ( str ( torrent_exc ) )
Return torrent engine data .
240,250
def json_charts ( self , req ) : disk_used , disk_total , disk_detail = 0 , 0 , [ ] for disk_usage_path in self . cfg . disk_usage_path . split ( os . pathsep ) : disk_usage = self . guarded ( psutil . disk_usage , os . path . expanduser ( disk_usage_path . strip ( ) ) ) if disk_usage : disk_used += disk_usage . used d...
Return charting data .
240,251
def parse_route ( cls , template ) : regex = '' last_pos = 0 for match in cls . ROUTES_RE . finditer ( template ) : regex += re . escape ( template [ last_pos : match . start ( ) ] ) var_name = match . group ( 1 ) expr = match . group ( 2 ) or '[^/]+' expr = '(?P<%s>%s)' % ( var_name , expr ) regex += expr last_pos = m...
Parse a route definition and return the compiled regex that matches it .
240,252
def add_route ( self , template , controller , ** kwargs ) : if isinstance ( controller , basestring ) : controller = pymagic . import_name ( controller ) self . routes . append ( ( self . parse_route ( template ) , controller , kwargs ) ) return self
Add a route definition
240,253
def _duration ( start , end ) : if start and end : if start > end : return None else : return end - start elif start : return time . time ( ) - start else : return None
Return time delta .
240,254
def _fmt_files ( filelist ) : depth = max ( i . path . count ( '/' ) for i in filelist ) pad = [ '\uFFFE' ] * depth base_indent = ' ' * 38 indent = 0 result = [ ] prev_path = pad sorted_files = sorted ( ( i . path . split ( '/' ) [ : - 1 ] + pad , i . path . rsplit ( '/' , 1 ) [ - 1 ] , i ) for i in filelist ) for path...
Produce a file listing .
240,255
def detect_traits ( item ) : return traits . detect_traits ( name = item . name , alias = item . alias , filetype = ( list ( item . fetch ( "kind_51" ) ) or [ None ] ) . pop ( ) , )
Build traits list from attributes of the passed item . Currently kind_51 name and alias are considered .
240,256
def add_manifold_attribute ( cls , name ) : if name . startswith ( "custom_" ) : try : return FieldDefinition . FIELDS [ name ] except KeyError : field = OnDemandField ( fmt . to_unicode , name , "custom attribute %r" % name . split ( '_' , 1 ) [ 1 ] , matcher = matching . PatternFilter ) setattr ( cls , name , field )...
Register a manifold engine attribute .
240,257
def add_custom_fields ( cls , * args , ** kw ) : for factory in config . custom_field_factories : for field in factory ( ) : setattr ( cls , field . name , field )
Add any custom fields defined in the configuration .
240,258
def _fetch_items ( self ) : if self . _items is None : self . _items = list ( self . engine . items ( self ) ) return self . _items
Fetch to attribute .
240,259
def _check_hash_view ( self ) : infohash = None if self . viewname . startswith ( '#' ) : infohash = self . viewname [ 1 : ] elif len ( self . viewname ) == 40 : try : int ( self . viewname , 16 ) except ( TypeError , ValueError ) : pass else : infohash = self . viewname return infohash
Return infohash if view name refers to a single item else None .
240,260
def size ( self ) : if self . _check_hash_view ( ) : return 1 else : return self . engine . open ( ) . view . size ( xmlrpc . NOHASH , self . viewname )
Total unfiltered size of view .
240,261
def group_by ( self , fields , items = None ) : result = defaultdict ( list ) if items is None : items = self . items ( ) try : key = operator . attrgetter ( fields + '' ) except TypeError : def key ( obj , names = tuple ( fields ) ) : 'Helper to return group key tuple' return tuple ( getattr ( obj , x ) for x in names...
Returns a dict of lists of items grouped by the given fields .
240,262
def _set_mappings ( self ) : try : self . _versions = ( self . system . client_version ( ) , self . system . library_version ( ) , ) self . _version_info = tuple ( int ( i ) for i in self . _versions [ 0 ] . split ( '.' ) ) self . _use_deprecated = self . _version_info < ( 0 , 8 , 7 ) self . _mapping = self . _mapping ...
Set command mappings according to rTorrent version .
240,263
def _fix_mappings ( self ) : self . _mapping . update ( ( key + '=' , val + '=' ) for key , val in self . _mapping . items ( ) if not key . endswith ( '=' ) ) if config . debug : self . LOG . debug ( "CMD MAPPINGS ARE: %r" % ( self . _mapping , ) )
Add computed stuff to mappings .
240,264
def _map_call ( self , cmd ) : if config . debug and cmd != self . _mapping . get ( cmd , cmd ) : self . LOG . debug ( "MAP %s ==> %s" % ( cmd , self . _mapping [ cmd ] ) ) cmd = self . _mapping . get ( cmd , cmd ) if not self . _use_deprecated and any ( cmd . startswith ( i ) for i in ( "d.get_" , "f.get_" , "p.get_" ...
Map old to new command names .
240,265
def parse ( self ) : try : if not os . path . getsize ( self . ns . pathname ) : self . job . LOG . warn ( "Ignoring 0-byte metafile '%s'" % ( self . ns . pathname , ) ) return self . metadata = metafile . checked_open ( self . ns . pathname ) except EnvironmentError as exc : self . job . LOG . error ( "Can't read meta...
Parse metafile and check pre - conditions .
240,266
def addinfo ( self ) : self . ns . watch_path = self . job . config . path self . ns . relpath = None for watch in self . job . config . path : if self . ns . pathname . startswith ( watch . rstrip ( '/' ) + '/' ) : self . ns . relpath = os . path . dirname ( self . ns . pathname ) [ len ( watch . rstrip ( '/' ) ) + 1 ...
Add known facts to templating namespace .
240,267
def load ( self ) : if not self . ns . info_hash and not self . parse ( ) : return self . addinfo ( ) try : start_it = self . job . config . load_mode . lower ( ) in ( "start" , "started" ) queue_it = self . job . config . queued if "start" in self . ns . flags : start_it = True elif "load" in self . ns . flags : start...
Load metafile into client .
240,268
def handle_path ( self , event ) : self . job . LOG . debug ( "Notification %r" % event ) if event . dir : return if any ( event . pathname . endswith ( i ) for i in self . METAFILE_EXT ) : MetafileHandler ( self . job , event . pathname ) . handle ( ) elif os . path . basename ( event . pathname ) == "watch.ini" : sel...
Handle a path - related event .
240,269
def setup ( self ) : if not pyinotify . WatchManager : raise error . UserError ( "You need to install 'pyinotify' to use %s (%s)!" % ( self . __class__ . __name__ , pyinotify . _import_error ) ) self . manager = pyinotify . WatchManager ( ) self . handler = TreeWatchHandler ( job = self ) self . notifier = pyinotify . ...
Set up inotify manager .
240,270
def get_filetypes ( filelist , path = None , size = os . path . getsize ) : path = path or ( lambda _ : _ ) histo = defaultdict ( int ) for entry in filelist : ext = os . path . splitext ( path ( entry ) ) [ 1 ] . lstrip ( '.' ) . lower ( ) if ext and ext [ 0 ] == 'r' and ext [ 1 : ] . isdigit ( ) : ext = "rar" elif ex...
Get a sorted list of file types and their weight in percent from an iterable of file names .
240,271
def name_trait ( name , add_info = False ) : kind , info = None , { } if name and not name . startswith ( "VTS_" ) : lower_name = name . lower ( ) trait_patterns = ( ( "tv" , TV_PATTERNS , "show" ) , ( "movie" , MOVIE_PATTERNS , "title" ) ) if any ( i in lower_name for i in _DEFINITELY_TV ) : kind = "tv" trait_patterns...
Determine content type from name .
240,272
def detect_traits ( name = None , alias = None , filetype = None ) : result = [ ] if filetype : filetype = filetype . lstrip ( '.' ) theme = config . traits_by_alias . get ( alias ) if alias and theme : result = [ theme , filetype or "other" ] elif filetype in KIND_AUDIO : result = [ "audio" , filetype ] elif filetype ...
Build traits list from passed attributes .
240,273
def console_progress ( ) : def progress ( totalhashed , totalsize ) : "Helper" msg = " " * 30 if totalhashed < totalsize : msg = "%5.1f%% complete" % ( totalhashed * 100.0 / totalsize ) sys . stdout . write ( msg + " \r" ) sys . stdout . flush ( ) try : return progress if sys . stdout . isatty ( ) else None except Attr...
Return a progress indicator for consoles if stdout is a tty .
240,274
def check_info ( info ) : if not isinstance ( info , dict ) : raise ValueError ( "bad metainfo - not a dictionary" ) pieces = info . get ( "pieces" ) if not isinstance ( pieces , basestring ) or len ( pieces ) % 20 != 0 : raise ValueError ( "bad metainfo - bad pieces key" ) piece_size = info . get ( "piece length" ) if...
Validate info dict .
240,275
def check_meta ( meta ) : if not isinstance ( meta , dict ) : raise ValueError ( "bad metadata - not a dictionary" ) if not isinstance ( meta . get ( "announce" ) , basestring ) : raise ValueError ( "bad announce URL - not a string" ) check_info ( meta . get ( "info" ) ) return meta
Validate meta dict .
240,276
def clean_meta ( meta , including_info = False , logger = None ) : modified = set ( ) for key in meta . keys ( ) : if [ key ] not in METAFILE_STD_KEYS : if logger : logger ( "Removing key %r..." % ( key , ) ) del meta [ key ] modified . add ( key ) if including_info : for key in meta [ "info" ] . keys ( ) : if [ "info"...
Clean meta dict . Optionally log changes using the given logger .
240,277
def sanitize ( meta , diagnostics = False ) : bad_encodings , bad_fields = set ( ) , set ( ) def sane_encoding ( field , text ) : "Transcoding helper." for encoding in ( 'utf-8' , meta . get ( 'encoding' , None ) , 'cp1252' ) : if encoding : try : u8_text = text . decode ( encoding ) . encode ( "utf-8" ) if encoding !=...
Try to fix common problems especially transcode non - standard string encodings .
240,278
def add_fast_resume ( meta , datapath ) : files = meta [ "info" ] . get ( "files" , None ) single = files is None if single : if os . path . isdir ( datapath ) : datapath = os . path . join ( datapath , meta [ "info" ] [ "name" ] ) files = [ Bunch ( path = [ os . path . abspath ( datapath ) ] , length = meta [ "info" ]...
Add fast resume data to a metafile dict .
240,279
def data_size ( metadata ) : info = metadata [ 'info' ] if 'length' in info : total_size = info [ 'length' ] else : total_size = sum ( [ f [ 'length' ] for f in info [ 'files' ] ] ) return total_size
Calculate the size of a torrent based on parsed metadata .
240,280
def checked_open ( filename , log = None , quiet = False ) : with open ( filename , "rb" ) as handle : raw_data = handle . read ( ) data = bencode . bdecode ( raw_data ) try : check_meta ( data ) if raw_data != bencode . bencode ( data ) : raise ValueError ( "Bad bencoded data - dict keys out of order?" ) except ValueE...
Open and validate the given metafile . Optionally provide diagnostics on the passed logger for invalid metafiles which then just cause a warning but no exception . quiet can supress that warning .
240,281
def format ( self , obj , context , maxlevels , level ) : if isinstance ( obj , basestring ) and "://" in fmt . to_unicode ( obj ) : obj = mask_keys ( obj ) return pprint . PrettyPrinter . format ( self , obj , context , maxlevels , level )
Mask obj if it looks like an URL then pass it to the super class .
240,282
def _get_datapath ( self ) : if self . _datapath is None : raise OSError ( errno . ENOENT , "You didn't provide any datapath for %r" % self . filename ) return self . _datapath
Get a valid datapath else raise an exception .
240,283
def _set_datapath ( self , datapath ) : if datapath : self . _datapath = datapath . rstrip ( os . sep ) self . _fifo = int ( stat . S_ISFIFO ( os . stat ( self . datapath ) . st_mode ) ) else : self . _datapath = None self . _fifo = False
Set a datapath .
240,284
def walk ( self ) : if self . _fifo : if self . _fifo > 1 : raise RuntimeError ( "INTERNAL ERROR: FIFO read twice!" ) self . _fifo += 1 with open ( self . datapath , "r" ) as fifo : while True : relpath = fifo . readline ( ) . rstrip ( '\n' ) if not relpath : break self . LOG . debug ( "Read relative path %r from FIFO....
Generate paths in self . datapath .
240,285
def _calc_size ( self ) : return sum ( os . path . getsize ( filename ) for filename in self . walk ( ) )
Get total size of self . datapath .
240,286
def _make_info ( self , piece_size , progress , walker , piece_callback = None ) : file_list = [ ] pieces = [ ] hashing_secs = time . time ( ) totalsize = - 1 if self . _fifo else self . _calc_size ( ) totalhashed = 0 sha1sum = hashlib . sha1 ( ) done = 0 filename = None for filename in walker : filesize = os . path . ...
Create info dict .
240,287
def _make_meta ( self , tracker_url , root_name , private , progress ) : if self . _fifo : piece_size_exp = 20 else : total_size = self . _calc_size ( ) if total_size : piece_size_exp = int ( math . log ( total_size ) / math . log ( 2 ) ) - 9 else : piece_size_exp = 0 piece_size_exp = min ( max ( 15 , piece_size_exp ) ...
Create torrent dict .
240,288
def check ( self , metainfo , datapath , progress = None ) : if datapath : self . datapath = datapath def check_piece ( filename , piece ) : "Callback for new piece" if piece != metainfo [ "info" ] [ "pieces" ] [ check_piece . piece_index : check_piece . piece_index + 20 ] : self . LOG . warn ( "Piece #%d: Hashes diffe...
Check piece hashes of a metafile against the given datapath .
240,289
def _start ( self , items ) : startable = [ i for i in items if self . config . startable . match ( i ) ] if not startable : self . LOG . debug ( "Checked %d item(s), none startable according to [ %s ]" , len ( items ) , self . config . startable ) return now = time . time ( ) if now < self . last_start : self . last_s...
Start some items if conditions are met .
240,290
def run ( self ) : try : self . proxy = config_ini . engine . open ( ) items = list ( config_ini . engine . items ( self . VIEWNAME , cache = False ) ) if self . sort_key : items . sort ( key = self . sort_key ) self . _start ( items ) self . LOG . debug ( "%s - %s" % ( config_ini . engine . engine_id , self . proxy ) ...
Queue manager job callback .
240,291
def print_help_fields ( ) : def custom_manifold ( ) : "named rTorrent custom attribute, e.g. 'custom_completion_target'" return ( "custom_KEY" , custom_manifold ) def kind_manifold ( ) : "file types that contribute at least N% to the item's total size" return ( "kind_N" , kind_manifold ) print ( '' ) print ( "Fields ar...
Print help about fields and field formatters .
240,292
def add ( self , field , val ) : "Add a sample" if engine . FieldDefinition . FIELDS [ field ] . _matcher is matching . TimeFilter : val = self . _basetime - val try : self . total [ field ] += val self . min [ field ] = min ( self . min [ field ] , val ) if field in self . min else val self . max [ field ] = max ( sel...
Add a sample
240,293
def help_completion_fields ( self ) : for name , field in sorted ( engine . FieldDefinition . FIELDS . items ( ) ) : if issubclass ( field . _matcher , matching . BoolFilter ) : yield "%s=no" % ( name , ) yield "%s=yes" % ( name , ) continue elif issubclass ( field . _matcher , matching . PatternFilter ) : yield "%s=" ...
Return valid field names .
240,294
def format_item ( self , item , defaults = None , stencil = None ) : from pyrobase . osutil import shell_escape try : item_text = fmt . to_console ( formatting . format_item ( self . options . output_format , item , defaults ) ) except ( NameError , ValueError , TypeError ) , exc : self . fatal ( "Trouble with formatti...
Format an item .
240,295
def emit ( self , item , defaults = None , stencil = None , to_log = False , item_formatter = None ) : item_text = self . format_item ( item , defaults , stencil ) if item_formatter : item_text = item_formatter ( item_text ) if item is None and os . isatty ( sys . stdout . fileno ( ) ) : item_text = '' . join ( ( confi...
Print an item to stdout or the log on INFO level .
240,296
def validate_output_format ( self , default_format ) : output_format = self . options . output_format if output_format is None : output_format = default_format output_format = config . formats . get ( output_format , output_format ) if re . match ( r"^[,._0-9a-zA-Z]+$" , output_format ) : self . plain_output_format = T...
Prepare output format for later use .
240,297
def get_output_fields ( self ) : emit_fields = list ( i . lower ( ) for i in re . sub ( r"[^_A-Z]+" , ' ' , self . format_item ( None ) ) . split ( ) ) result = [ ] for name in emit_fields [ : ] : if name not in engine . FieldDefinition . FIELDS : self . LOG . warn ( "Omitted unknown name '%s' from statistics and outpu...
Get field names from output template .
240,298
def validate_sort_fields ( self ) : sort_fields = ',' . join ( self . options . sort_fields ) if sort_fields == '*' : sort_fields = self . get_output_fields ( ) return formatting . validate_sort_fields ( sort_fields or config . sort_fields )
Take care of sorting .
240,299
def show_in_view ( self , sourceview , matches , targetname = None ) : append = self . options . append_view or self . options . alter_view == 'append' remove = self . options . alter_view == 'remove' action_name = ', appending to' if append else ', removing from' if remove else ' into' targetname = config . engine . s...
Show search result in ncurses view .