idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
244,200
def device_removed ( self , device ) : if not self . _mounter . is_handleable ( device ) : return device_file = device . device_presentation if ( device . is_drive or device . is_toplevel ) and device_file : self . _show_notification ( 'device_removed' , _ ( 'Device removed' ) , _ ( 'device disappeared on {0.device_pre...
Show removal notification for specified device object .
244,201
def job_failed ( self , device , action , message ) : if not self . _mounter . is_handleable ( device ) : return device_file = device . device_presentation or device . object_path if message : text = _ ( 'failed to {0} {1}:\n{2}' , action , device_file , message ) else : text = _ ( 'failed to {0} device {1}.' , action ...
Show Job failed notification with Retry button .
244,202
def _show_notification ( self , event , summary , message , icon , * actions ) : notification = self . _notify ( summary , message , icon ) timeout = self . _get_timeout ( event ) if timeout != - 1 : notification . set_timeout ( int ( timeout * 1000 ) ) for action in actions : if action and self . _action_enabled ( eve...
Show a notification .
244,203
def _add_action ( self , notification , action , label , callback , * args ) : on_action_click = run_bg ( lambda * _ : callback ( * args ) ) try : notification . add_action ( action , label , on_action_click , None ) except TypeError : notification . add_action ( action , label , on_action_click , None , None ) notific...
Show an action button button in mount notifications .
244,204
def _action_enabled ( self , event , action ) : event_actions = self . _aconfig . get ( event ) if event_actions is None : return True if event_actions is False : return False return action in event_actions
Check if an action for a notification is enabled .
244,205
def _has_actions ( self , event ) : event_actions = self . _aconfig . get ( event ) return event_actions is None or bool ( event_actions )
Check if a notification type has any enabled actions .
244,206
def match ( self , device ) : return all ( match_value ( getattr ( device , k ) , v ) for k , v in self . _match . items ( ) )
Check if the device object matches this filter .
244,207
def value ( self , kind , device ) : self . _log . debug ( _ ( '{0}(match={1!r}, {2}={3!r}) used for {4}' , self . __class__ . __name__ , self . _match , kind , self . _values [ kind ] , device . object_path ) ) return self . _values [ kind ]
Get the value for the device object associated with this filter .
244,208
def default_pathes ( cls ) : try : from xdg . BaseDirectory import xdg_config_home as config_home except ImportError : config_home = os . path . expanduser ( '~/.config' ) return [ os . path . join ( config_home , 'udiskie' , 'config.yml' ) , os . path . join ( config_home , 'udiskie' , 'config.json' ) ]
Return the default config file pathes as a list .
244,209
def from_file ( cls , path = None ) : if path is None : for path in cls . default_pathes ( ) : try : return cls . from_file ( path ) except IOError as e : logging . getLogger ( __name__ ) . debug ( _ ( "Failed to read config file: {0}" , exc_message ( e ) ) ) except ImportError as e : logging . getLogger ( __name__ ) ....
Read YAML config file . Returns Config object .
244,210
def get_icon_name ( self , icon_id : str ) -> str : icon_theme = Gtk . IconTheme . get_default ( ) for name in self . _icon_names [ icon_id ] : if icon_theme . has_icon ( name ) : return name return 'not-available'
Lookup the system icon name from udisie - internal id .
244,211
def get_icon ( self , icon_id : str , size : "Gtk.IconSize" ) -> "Gtk.Image" : return Gtk . Image . new_from_gicon ( self . get_gicon ( icon_id ) , size )
Load Gtk . Image from udiskie - internal id .
244,212
def get_gicon ( self , icon_id : str ) -> "Gio.Icon" : return Gio . ThemedIcon . new_from_names ( self . _icon_names [ icon_id ] )
Lookup Gio . Icon from udiskie - internal id .
244,213
def _insert_options ( self , menu ) : menu . append ( Gtk . SeparatorMenuItem ( ) ) menu . append ( self . _menuitem ( _ ( 'Mount disc image' ) , self . _icons . get_icon ( 'losetup' , Gtk . IconSize . MENU ) , run_bg ( lambda _ : self . _losetup ( ) ) ) ) menu . append ( Gtk . SeparatorMenuItem ( ) ) menu . append ( s...
Add configuration options to menu .
244,214
def detect ( self ) : root = self . _actions . detect ( ) prune_empty_node ( root , set ( ) ) return root
Detect all currently known devices . Returns the root device .
244,215
def _create_menu ( self , items ) : menu = Gtk . Menu ( ) self . _create_menu_items ( menu , items ) return menu
Create a menu from the given node .
244,216
def _menuitem ( self , label , icon , onclick , checked = None ) : if checked is not None : item = Gtk . CheckMenuItem ( ) item . set_active ( checked ) elif icon is None : item = Gtk . MenuItem ( ) else : item = Gtk . ImageMenuItem ( ) item . set_image ( icon ) item . set_always_show_image ( True ) if label is not Non...
Create a generic menu item .
244,217
def _prepare_menu ( self , node , flat = None ) : if flat is None : flat = self . flat ItemGroup = MenuSection if flat else SubMenu return [ ItemGroup ( branch . label , self . _collapse_device ( branch , flat ) ) for branch in node . branches if branch . methods or branch . branches ]
Prepare the menu hierarchy from the given device tree .
244,218
def _collapse_device ( self , node , flat ) : items = [ item for branch in node . branches for item in self . _collapse_device ( branch , flat ) if item ] show_all = not flat or self . _quickmenu_actions == 'all' methods = node . methods if show_all else [ method for method in node . methods if method . method in self ...
Collapse device hierarchy into a flat folder .
244,219
def _create_statusicon ( self ) : statusicon = Gtk . StatusIcon ( ) statusicon . set_from_gicon ( self . _icons . get_gicon ( 'media' ) ) statusicon . set_tooltip_text ( _ ( "udiskie" ) ) return statusicon
Return a new Gtk . StatusIcon .
244,220
def show ( self , show = True ) : if show and not self . visible : self . _show ( ) if not show and self . visible : self . _hide ( )
Show or hide the tray icon .
244,221
def _show ( self ) : if not self . _icon : self . _icon = self . _create_statusicon ( ) widget = self . _icon widget . set_visible ( True ) self . _conn_left = widget . connect ( "activate" , self . _activate ) self . _conn_right = widget . connect ( "popup-menu" , self . _popup_menu )
Show the tray icon .
244,222
def _hide ( self ) : self . _icon . set_visible ( False ) self . _icon . disconnect ( self . _conn_left ) self . _icon . disconnect ( self . _conn_right ) self . _conn_left = None self . _conn_right = None
Hide the tray icon .
244,223
def create_context_menu ( self , extended ) : menu = Gtk . Menu ( ) self . _menu ( menu , extended ) return menu
Create the context menu .
244,224
async def password_dialog ( key , title , message , options ) : with PasswordDialog . create ( key , title , message , options ) as dialog : response = await dialog if response == Gtk . ResponseType . OK : return PasswordResult ( dialog . get_text ( ) , dialog . use_cache . get_active ( ) ) return None
Show a Gtk password dialog .
244,225
def get_password_gui ( device , options ) : text = _ ( 'Enter password for {0.device_presentation}: ' , device ) try : return password_dialog ( device . id_uuid , 'udiskie' , text , options ) except RuntimeError : return None
Get the password to unlock a device from GUI .
244,226
async def get_password_tty ( device , options ) : text = _ ( 'Enter password for {0.device_presentation}: ' , device ) try : return getpass . getpass ( text ) except EOFError : print ( "" ) return None
Get the password to unlock a device from terminal .
244,227
def password ( password_command ) : gui = lambda : has_Gtk ( ) and get_password_gui tty = lambda : sys . stdin . isatty ( ) and get_password_tty if password_command == 'builtin:gui' : return gui ( ) or tty ( ) elif password_command == 'builtin:tty' : return tty ( ) or gui ( ) elif password_command : return DeviceComman...
Create a password prompt function .
244,228
def browser ( browser_name = 'xdg-open' ) : if not browser_name : return None argv = shlex . split ( browser_name ) executable = find_executable ( argv [ 0 ] ) if executable is None : logging . getLogger ( __name__ ) . warn ( _ ( "Can't find file browser: {0!r}. " "You may want to change the value for the '-f' option."...
Create a browse - directory function .
244,229
def notify_command ( command_format , mounter ) : udisks = mounter . udisks for event in [ 'device_mounted' , 'device_unmounted' , 'device_locked' , 'device_unlocked' , 'device_added' , 'device_removed' , 'job_failed' ] : udisks . connect ( event , run_bg ( DeviceCommand ( command_format , event = event ) ) )
Command notification tool .
244,230
async def exec_subprocess ( argv ) : future = Future ( ) process = Gio . Subprocess . new ( argv , Gio . SubprocessFlags . STDOUT_PIPE | Gio . SubprocessFlags . STDIN_INHERIT ) stdin_buf = None cancellable = None process . communicate_utf8_async ( stdin_buf , cancellable , gio_callback , future ) result = await future ...
An Future task that represents a subprocess . If successful the task s result is set to the collected STDOUT of the subprocess .
244,231
def set_exception ( self , exception ) : was_handled = self . _finish ( self . errbacks , exception ) if not was_handled : traceback . print_exception ( type ( exception ) , exception , exception . __traceback__ )
Signal unsuccessful completion .
244,232
def _subtask_result ( self , idx , value ) : self . _results [ idx ] = value if len ( self . _results ) == self . _num_tasks : self . set_result ( [ self . _results [ i ] for i in range ( self . _num_tasks ) ] )
Receive a result from a single subtask .
244,233
def _subtask_error ( self , idx , error ) : self . set_exception ( error ) self . errbacks . clear ( )
Receive an error from a single subtask .
244,234
def _resume ( self , func , * args ) : try : value = func ( * args ) except StopIteration : self . _generator . close ( ) self . set_result ( None ) except Exception as e : self . _generator . close ( ) self . set_exception ( e ) else : assert isinstance ( value , Future ) value . callbacks . append ( partial ( self . ...
Resume the coroutine by throwing a value or returning a value from the await and handle further awaits .
244,235
def parse_commit_message ( message : str ) -> Tuple [ int , str , Optional [ str ] , Tuple [ str , str , str ] ] : parsed = re_parser . match ( message ) if not parsed : raise UnknownCommitMessageStyleError ( 'Unable to parse the given commit message: {0}' . format ( message ) ) subject = parsed . group ( 'subject' ) i...
Parses a commit message according to the 1 . 0 version of python - semantic - release . It expects a tag of some sort in the commit message and will use the rest of the first line as changelog content .
244,236
def checker ( func : Callable ) -> Callable : def func_wrapper ( * args , ** kwargs ) : try : func ( * args , ** kwargs ) return True except AssertionError : raise CiVerificationError ( 'The verification check for the environment did not pass.' ) return func_wrapper
A decorator that will convert AssertionErrors into CiVerificationError .
244,237
def travis ( branch : str ) : assert os . environ . get ( 'TRAVIS_BRANCH' ) == branch assert os . environ . get ( 'TRAVIS_PULL_REQUEST' ) == 'false'
Performs necessary checks to ensure that the travis build is one that should create releases .
244,238
def semaphore ( branch : str ) : assert os . environ . get ( 'BRANCH_NAME' ) == branch assert os . environ . get ( 'PULL_REQUEST_NUMBER' ) is None assert os . environ . get ( 'SEMAPHORE_THREAD_RESULT' ) != 'failed'
Performs necessary checks to ensure that the semaphore build is successful on the correct branch and not a pull - request .
244,239
def frigg ( branch : str ) : assert os . environ . get ( 'FRIGG_BUILD_BRANCH' ) == branch assert not os . environ . get ( 'FRIGG_PULL_REQUEST' )
Performs necessary checks to ensure that the frigg build is one that should create releases .
244,240
def circle ( branch : str ) : assert os . environ . get ( 'CIRCLE_BRANCH' ) == branch assert not os . environ . get ( 'CI_PULL_REQUEST' )
Performs necessary checks to ensure that the circle build is one that should create releases .
244,241
def bitbucket ( branch : str ) : assert os . environ . get ( 'BITBUCKET_BRANCH' ) == branch assert not os . environ . get ( 'BITBUCKET_PR_ID' )
Performs necessary checks to ensure that the bitbucket build is one that should create releases .
244,242
def check ( branch : str = 'master' ) : if os . environ . get ( 'TRAVIS' ) == 'true' : travis ( branch ) elif os . environ . get ( 'SEMAPHORE' ) == 'true' : semaphore ( branch ) elif os . environ . get ( 'FRIGG' ) == 'true' : frigg ( branch ) elif os . environ . get ( 'CIRCLECI' ) == 'true' : circle ( branch ) elif os ...
Detects the current CI environment if any and performs necessary environment checks .
244,243
def parse_commit_message ( message : str ) -> Tuple [ int , str , str , Tuple [ str , str , str ] ] : parsed = re_parser . match ( message ) if not parsed : raise UnknownCommitMessageStyleError ( 'Unable to parse the given commit message: {}' . format ( message ) ) level_bump = 0 if parsed . group ( 'text' ) and 'BREAK...
Parses a commit message according to the angular commit guidelines specification .
244,244
def parse_text_block ( text : str ) -> Tuple [ str , str ] : body , footer = '' , '' if text : body = text . split ( '\n\n' ) [ 0 ] if len ( text . split ( '\n\n' ) ) == 2 : footer = text . split ( '\n\n' ) [ 1 ] return body . replace ( '\n' , ' ' ) , footer . replace ( '\n' , ' ' )
This will take a text block and return a tuple with body and footer where footer is defined as the last paragraph .
244,245
def upload_to_pypi ( dists : str = 'sdist bdist_wheel' , username : str = None , password : str = None , skip_existing : bool = False ) : if username is None or password is None or username == "" or password == "" : raise ImproperConfigurationError ( 'Missing credentials for uploading' ) run ( 'rm -rf build dist' ) run...
Creates the wheel and uploads to pypi with twine .
244,246
def get_commit_log ( from_rev = None ) : check_repo ( ) rev = None if from_rev : rev = '...{from_rev}' . format ( from_rev = from_rev ) for commit in repo . iter_commits ( rev ) : yield ( commit . hexsha , commit . message )
Yields all commit messages from last to first .
244,247
def get_last_version ( skip_tags = None ) -> Optional [ str ] : debug ( 'get_last_version skip_tags=' , skip_tags ) check_repo ( ) skip_tags = skip_tags or [ ] def version_finder ( tag ) : if isinstance ( tag . commit , TagObject ) : return tag . tag . tagged_date return tag . commit . committed_date for i in sorted ( ...
Return last version from repo tags .
244,248
def get_version_from_tag ( tag_name : str ) -> Optional [ str ] : debug ( 'get_version_from_tag({})' . format ( tag_name ) ) check_repo ( ) for i in repo . tags : if i . name == tag_name : return i . commit . hexsha return None
Get git hash from tag
244,249
def get_repository_owner_and_name ( ) -> Tuple [ str , str ] : check_repo ( ) url = repo . remote ( 'origin' ) . url parts = re . search ( r'([^/:]+)/([^/]+).git$' , url ) if not parts : raise HvcsRepoParseError debug ( 'get_repository_owner_and_name' , parts ) return parts . group ( 1 ) , parts . group ( 2 )
Checks the origin remote to get the owner and name of the remote repository .
244,250
def commit_new_version ( version : str ) : check_repo ( ) commit_message = config . get ( 'semantic_release' , 'commit_message' ) message = '{0}\n\n{1}' . format ( version , commit_message ) repo . git . add ( config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) [ 0 ] ) return repo . git . commit ( ...
Commits the file containing the version number variable with the version number as the commit message .
244,251
def tag_new_version ( version : str ) : check_repo ( ) return repo . git . tag ( '-a' , 'v{0}' . format ( version ) , m = 'v{0}' . format ( version ) )
Creates a new tag with the version number prefixed with v .
244,252
def current_commit_parser ( ) -> Callable : try : parts = config . get ( 'semantic_release' , 'commit_parser' ) . split ( '.' ) module = '.' . join ( parts [ : - 1 ] ) return getattr ( importlib . import_module ( module ) , parts [ - 1 ] ) except ( ImportError , AttributeError ) as error : raise ImproperConfigurationEr...
Current commit parser
244,253
def get_current_version_by_config_file ( ) -> str : debug ( 'get_current_version_by_config_file' ) filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) variable = variable . strip ( ) debug ( filename , variable ) with open ( filename , 'r' ) as fd : parts = re . search ( r'^{0...
Get current version from the version variable defined in the configuration
244,254
def get_new_version ( current_version : str , level_bump : str ) -> str : debug ( 'get_new_version("{}", "{}")' . format ( current_version , level_bump ) ) if not level_bump : return current_version return getattr ( semver , 'bump_{0}' . format ( level_bump ) ) ( current_version )
Calculates the next version based on the given bump level with semver .
244,255
def get_previous_version ( version : str ) -> Optional [ str ] : debug ( 'get_previous_version' ) found_version = False for commit_hash , commit_message in get_commit_log ( ) : debug ( 'checking commit {}' . format ( commit_hash ) ) if version in commit_message : found_version = True debug ( 'found_version in "{}"' . f...
Returns the version prior to the given version .
244,256
def replace_version_string ( content , variable , new_version ) : return re . sub ( r'({0} ?= ?["\'])\d+\.\d+(?:\.\d+)?(["\'])' . format ( variable ) , r'\g<1>{0}\g<2>' . format ( new_version ) , content )
Given the content of a file finds the version string and updates it .
244,257
def set_new_version ( new_version : str ) -> bool : filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) variable = variable . strip ( ) with open ( filename , mode = 'r' ) as fr : content = fr . read ( ) content = replace_version_string ( content , variable , new_version ) wit...
Replaces the version number in the correct place and writes the changed file to disk .
244,258
def evaluate_version_bump ( current_version : str , force : str = None ) -> Optional [ str ] : debug ( 'evaluate_version_bump("{}", "{}")' . format ( current_version , force ) ) if force : return force bump = None changes = [ ] commit_count = 0 for _hash , commit_message in get_commit_log ( 'v{0}' . format ( current_ve...
Reads git log since last release to find out if should be a major minor or patch release .
244,259
def generate_changelog ( from_version : str , to_version : str = None ) -> dict : debug ( 'generate_changelog("{}", "{}")' . format ( from_version , to_version ) ) changes : dict = { 'feature' : [ ] , 'fix' : [ ] , 'documentation' : [ ] , 'refactor' : [ ] , 'breaking' : [ ] } found_the_release = to_version is None rev ...
Generates a changelog for the given version .
244,260
def markdown_changelog ( version : str , changelog : dict , header : bool = False ) -> str : debug ( 'markdown_changelog(version="{}", header={}, changelog=...)' . format ( version , header ) ) output = '' if header : output += '## v{0}\n' . format ( version ) for section in CHANGELOG_SECTIONS : if not changelog [ sect...
Generates a markdown version of the changelog . Takes a parsed changelog dict from generate_changelog .
244,261
def get_hvcs ( ) -> Base : hvcs = config . get ( 'semantic_release' , 'hvcs' ) debug ( 'get_hvcs: hvcs=' , hvcs ) try : return globals ( ) [ hvcs . capitalize ( ) ] except KeyError : raise ImproperConfigurationError ( '"{0}" is not a valid option for hvcs.' )
Get HVCS helper class
244,262
def check_build_status ( owner : str , repository : str , ref : str ) -> bool : debug ( 'check_build_status' ) return get_hvcs ( ) . check_build_status ( owner , repository , ref )
Checks the build status of a commit on the api from your hosted version control provider .
244,263
def post_changelog ( owner : str , repository : str , version : str , changelog : str ) -> Tuple [ bool , dict ] : debug ( 'post_changelog(owner={}, repository={}, version={})' . format ( owner , repository , version ) ) return get_hvcs ( ) . post_release_changelog ( owner , repository , version , changelog )
Posts the changelog to the current hvcs release API
244,264
def version ( ** kwargs ) : retry = kwargs . get ( "retry" ) if retry : click . echo ( 'Retrying publication of the same version...' ) else : click . echo ( 'Creating new version..' ) try : current_version = get_current_version ( ) except GitError as e : click . echo ( click . style ( str ( e ) , 'red' ) , err = True )...
Detects the new version according to git log and semver . Writes the new version number and commits it unless the noop - option is True .
244,265
def publish ( ** kwargs ) : current_version = get_current_version ( ) click . echo ( 'Current version: {0}' . format ( current_version ) ) retry = kwargs . get ( "retry" ) debug ( 'publish: retry=' , retry ) if retry : new_version = current_version current_version = get_previous_version ( current_version ) else : level...
Runs the version task before pushing to git and uploading to pypi .
244,266
def flatpages_link_list ( request ) : from django . contrib . flatpages . models import FlatPage link_list = [ ( page . title , page . url ) for page in FlatPage . objects . all ( ) ] return render_to_link_list ( link_list )
Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages .
244,267
def _interactive_loop ( self , sin : IO [ str ] , sout : IO [ str ] ) -> None : self . _sin = sin self . _sout = sout tasknum = len ( all_tasks ( loop = self . _loop ) ) s = '' if tasknum == 1 else 's' self . _sout . write ( self . intro . format ( tasknum = tasknum , s = s ) ) try : while not self . _closing . is_set ...
Main interactive loop of the monitor
244,268
def do_help ( self , * cmd_names : str ) -> None : def _h ( cmd : str , template : str ) -> None : try : func = getattr ( self , cmd ) except AttributeError : self . _sout . write ( 'No such command: {}\n' . format ( cmd ) ) else : doc = func . __doc__ if func . __doc__ else '' doc_firstline = doc . split ( '\n' , maxs...
Show help for command name
244,269
def do_ps ( self ) -> None : headers = ( 'Task ID' , 'State' , 'Task' ) table_data = [ headers ] for task in sorted ( all_tasks ( loop = self . _loop ) , key = id ) : taskid = str ( id ( task ) ) if task : t = '\n' . join ( wrap ( str ( task ) , 80 ) ) table_data . append ( ( taskid , task . _state , t ) ) table = Asci...
Show task table
244,270
def do_where ( self , taskid : int ) -> None : task = task_by_id ( taskid , self . _loop ) if task : self . _sout . write ( _format_stack ( task ) ) self . _sout . write ( '\n' ) else : self . _sout . write ( 'No task %d\n' % taskid )
Show stack frames for a task
244,271
def do_signal ( self , signame : str ) -> None : if hasattr ( signal , signame ) : os . kill ( os . getpid ( ) , getattr ( signal , signame ) ) else : self . _sout . write ( 'Unknown signal %s\n' % signame )
Send a Unix signal
244,272
def do_stacktrace ( self ) -> None : frame = sys . _current_frames ( ) [ self . _event_loop_thread_id ] traceback . print_stack ( frame , file = self . _sout )
Print a stack trace from the event loop thread
244,273
def do_cancel ( self , taskid : int ) -> None : task = task_by_id ( taskid , self . _loop ) if task : fut = asyncio . run_coroutine_threadsafe ( cancel_task ( task ) , loop = self . _loop ) fut . result ( timeout = 3 ) self . _sout . write ( 'Cancel task %d\n' % taskid ) else : self . _sout . write ( 'No task %d\n' % t...
Cancel an indicated task
244,274
def do_console ( self ) -> None : if not self . _console_enabled : self . _sout . write ( 'Python console disabled for this sessiong\n' ) self . _sout . flush ( ) return h , p = self . _host , self . _console_port log . info ( 'Starting console at %s:%d' , h , p ) fut = init_console_server ( self . _host , self . _cons...
Switch to async Python REPL
244,275
def alt_names ( names : str ) -> Callable [ ... , Any ] : names_split = names . split ( ) def decorator ( func : Callable [ ... , Any ] ) -> Callable [ ... , Any ] : func . alt_names = names_split return func return decorator
Add alternative names to you custom commands .
244,276
def set_interactive_policy ( * , locals = None , banner = None , serve = None , prompt_control = None ) : policy = InteractiveEventLoopPolicy ( locals = locals , banner = banner , serve = serve , prompt_control = prompt_control ) asyncio . set_event_loop_policy ( policy )
Use an interactive event loop by default .
244,277
def run_console ( * , locals = None , banner = None , serve = None , prompt_control = None ) : loop = InteractiveEventLoop ( locals = locals , banner = banner , serve = serve , prompt_control = prompt_control ) asyncio . set_event_loop ( loop ) try : loop . run_forever ( ) except KeyboardInterrupt : pass
Run the interactive event loop .
244,278
def make_arg ( key , annotation = None ) : arg = ast . arg ( key , annotation ) arg . lineno , arg . col_offset = 0 , 0 return arg
Make an ast function argument .
244,279
def make_coroutine_from_tree ( tree , filename = "<aexec>" , symbol = "single" , local = { } ) : dct = { } tree . body [ 0 ] . args . args = list ( map ( make_arg , local ) ) exec ( compile ( tree , filename , symbol ) , dct ) return asyncio . coroutine ( dct [ CORO_NAME ] ) ( ** local )
Make a coroutine from a tree structure .
244,280
def feature_needs ( * feas ) : fmap = { 'stateful_files' : 22 , 'stateful_dirs' : 23 , 'stateful_io' : ( 'stateful_files' , 'stateful_dirs' ) , 'stateful_files_keep_cache' : 23 , 'stateful_files_direct_io' : 23 , 'keep_cache' : ( 'stateful_files_keep_cache' , ) , 'direct_io' : ( 'stateful_files_direct_io' , ) , 'has_op...
Get info about the FUSE API version needed for the support of some features .
244,281
def assemble ( self ) : self . canonify ( ) args = [ sys . argv and sys . argv [ 0 ] or "python" ] if self . mountpoint : args . append ( self . mountpoint ) for m , v in self . modifiers . items ( ) : if v : args . append ( self . fuse_modifiers [ m ] ) opta = [ ] for o , v in self . optdict . items ( ) : opta . appen...
Mangle self into an argument array
244,282
def parse ( self , * args , ** kw ) : ev = 'errex' in kw and kw . pop ( 'errex' ) if ev and not isinstance ( ev , int ) : raise TypeError ( "error exit value should be an integer" ) try : self . cmdline = self . parser . parse_args ( * args , ** kw ) except OptParseError : if ev : sys . exit ( ev ) raise return self . ...
Parse command line fill fuse_args attribute .
244,283
def main ( self , args = None ) : if get_compat_0_1 ( ) : args = self . main_0_1_preamble ( ) d = { 'multithreaded' : self . multithreaded and 1 or 0 } d [ 'fuse_args' ] = args or self . fuse_args . assemble ( ) for t in 'file_class' , 'dir_class' : if hasattr ( self , t ) : getattr ( self . methproxy , 'set_' + t ) ( ...
Enter filesystem service loop .
244,284
def fuseoptref ( cls ) : import os , re pr , pw = os . pipe ( ) pid = os . fork ( ) if pid == 0 : os . dup2 ( pw , 2 ) os . close ( pr ) fh = cls ( ) fh . fuse_args = FuseArgs ( ) fh . fuse_args . setmod ( 'showhelp' ) fh . main ( ) sys . exit ( ) os . close ( pw ) fa = FuseArgs ( ) ore = re . compile ( "-o\s+([\w\[\]]...
Find out which options are recognized by the library . Result is a FuseArgs instance with the list of supported options suitable for passing on to the filter method of another FuseArgs instance .
244,285
def filter ( self , other ) : self . canonify ( ) other . canonify ( ) rej = self . __class__ ( ) rej . optlist = self . optlist . difference ( other . optlist ) self . optlist . difference_update ( rej . optlist ) for x in self . optdict . copy ( ) : if x not in other . optdict : self . optdict . pop ( x ) rej . optdi...
Throw away those options which are not in the other one . Returns a new instance with the rejected options .
244,286
def add ( self , opt , val = None ) : ov = opt . split ( '=' , 1 ) o = ov [ 0 ] v = len ( ov ) > 1 and ov [ 1 ] or None if ( v ) : if val != None : raise AttributeError ( "ambiguous option value" ) val = v if val == False : return if val in ( None , True ) : self . optlist . add ( o ) else : self . optdict [ o ] = val
Add a suboption .
244,287
def register_sub ( self , o ) : if o . subopt in self . subopt_map : raise OptionConflictError ( "conflicting suboption handlers for `%s'" % o . subopt , o ) self . subopt_map [ o . subopt ] = o
Register argument a suboption for self .
244,288
def __parse_content ( tuc_content , content_to_be_parsed ) : initial_parsed_content = { } i = 0 for content_dict in tuc_content : if content_to_be_parsed in content_dict . keys ( ) : contents_raw = content_dict [ content_to_be_parsed ] if content_to_be_parsed == "phrase" : initial_parsed_content [ i ] = contents_raw [ ...
parses the passed tuc_content for - meanings - synonym received by querying the glosbe API
244,289
def meaning ( phrase , source_lang = "en" , dest_lang = "en" , format = "json" ) : base_url = Vocabulary . __get_api_link ( "glosbe" ) url = base_url . format ( word = phrase , source_lang = source_lang , dest_lang = dest_lang ) json_obj = Vocabulary . __return_json ( url ) if json_obj : try : tuc_content = json_obj [ ...
make calls to the glosbe API
244,290
def part_of_speech ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "definitions" ) json_obj = Vocabulary . __return_json ( url ) if not json_obj : return False result = [ ] for idx , obj in enumerate ( json_obj ) : text =...
querrying Wordnik s API for knowing whether the word is a noun adjective and the like
244,291
def usage_example ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "urbandict" ) url = base_url . format ( action = "define" , word = phrase ) word_examples = { } json_obj = Vocabulary . __return_json ( url ) if json_obj : examples_list = json_obj [ "list" ] for i , example in enumerate ( example...
Takes the source phrase and queries it to the urbandictionary API
244,292
def pronunciation ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "pronunciations" ) json_obj = Vocabulary . __return_json ( url ) if json_obj : for idx , obj in enumerate ( json_obj ) : obj [ 'seq' ] = idx if sys . versi...
Gets the pronunciation from the Wordnik API
244,293
def hyphenation ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "hyphenation" ) json_obj = Vocabulary . __return_json ( url ) if json_obj : return Response ( ) . respond ( json_obj , format ) else : return False
Returns back the stress points in the phrase passed
244,294
def __respond_with_dict ( self , data ) : response = { } if isinstance ( data , list ) : temp_data , data = data , { } for key , value in enumerate ( temp_data ) : data [ key ] = value data . pop ( 'seq' , None ) for index , item in data . items ( ) : values = item if isinstance ( item , list ) or isinstance ( item , d...
Builds a python dictionary from a json object
244,295
def __respond_with_list ( self , data ) : response = [ ] if isinstance ( data , dict ) : data . pop ( 'seq' , None ) data = list ( data . values ( ) ) for item in data : values = item if isinstance ( item , list ) or isinstance ( item , dict ) : values = self . __respond_with_list ( item ) if isinstance ( values , list...
Builds a python list from a json object
244,296
def respond ( self , data , format = 'json' ) : dispatchers = { "dict" : self . __respond_with_dict , "list" : self . __respond_with_list } if not dispatchers . get ( format , False ) : return json . dumps ( data ) return dispatchers [ format ] ( data )
Converts a json object to a python datastructure based on specified format
244,297
def get_todos ( self ) : if self . is_expression : self . get_todos_from_expr ( ) else : if self . last_argument : numbers = self . args [ : - 1 ] else : numbers = self . args for number in numbers : try : self . todos . append ( self . todolist . todo ( number ) ) except InvalidTodoException : self . invalid_numbers ....
Gets todo objects from supplied todo IDs .
244,298
def _markup ( p_todo , p_focus ) : pri = p_todo . priority ( ) pri = 'pri_' + pri if pri else PaletteItem . DEFAULT if not p_focus : attr_dict = { None : pri } else : attr_dict = { None : pri + '_focus' } attr_dict [ PaletteItem . PROJECT ] = PaletteItem . PROJECT_FOCUS attr_dict [ PaletteItem . CONTEXT ] = PaletteItem...
Returns an attribute spec for the colors that correspond to the given todo item .
244,299
def create ( p_class , p_todo , p_id_width = 4 ) : def parent_progress_may_have_changed ( p_todo ) : return p_todo . has_tag ( 'p' ) and not p_todo . has_tag ( 'due' ) source = p_todo . source ( ) if source in p_class . cache : widget = p_class . cache [ source ] if p_todo is not widget . todo : widget . todo = p_todo ...
Creates a TodoWidget instance for the given todo . Widgets are cached the same object is returned for the same todo item .