idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
8,000
def param ( self , key , default = None ) : if key in self . parameters : return self . parameters [ key ] return default
for accessing global parameters
8,001
def generator ( self , gen , * args , ** kwargs ) : with self ( * args , ** kwargs ) : for i in gen : yield i
Use this function to enter and exit the context at the beginning and end of a generator .
8,002
def validate_url ( self , original_string ) : pieces = urlparse . urlparse ( original_string ) try : if self . path_only : assert not any ( [ pieces . scheme , pieces . netloc ] ) assert pieces . path else : assert all ( [ pieces . scheme , pieces . netloc ] ) valid_chars = set ( string . letters + string . digits + ":...
Returns the original string if it was valid raises an argument error if it s not .
8,003
def get_chapter ( self , book_name , book_chapter , cache_chapter = True ) : try : logging . debug ( "Attempting to read chapter from disk" ) verses_list = self . _get_ondisk_chapter ( book_name , book_chapter ) except Exception as e : logging . debug ( "Could not read file from disk. Attempting the internet.." ) loggi...
Returns a chapter of the bible first checking to see if that chapter is on disk . If not hen it attempts to fetch it from the internet .
8,004
def verse_lookup ( self , book_name , book_chapter , verse , cache_chapter = True ) : verses_list = self . get_chapter ( book_name , str ( book_chapter ) , cache_chapter = cache_chapter ) return verses_list [ int ( verse ) - 1 ]
Looks up a verse from online . recoveryversion . bible then returns it .
8,005
def validate_on_submit ( self ) : valid = FlaskWtf . validate_on_submit ( self ) if not self . _schema or not self . is_submitted ( ) : return valid data = dict ( ) for field in self . _fields : data [ field ] = self . _fields [ field ] . data result = self . schema . process ( data , context = self . _force_context ) ...
Extend validate on submit to allow validation with schema
8,006
def set_errors ( self , result ) : errors = result . get_messages ( ) for property_name in errors : if not hasattr ( self , property_name ) : continue prop_errors = errors [ property_name ] if type ( prop_errors ) is not list : prop_errors = [ '<Nested schema result following...>' ] if property_name in self . errors : ...
Populate field errors with errors from schema validation
8,007
def diffs2persistence ( rev_docs , window_size = 50 , revert_radius = 15 , sunset = None , verbose = False ) : rev_docs = mwxml . utilities . normalize ( rev_docs ) window_size = int ( window_size ) revert_radius = int ( revert_radius ) sunset = Timestamp ( sunset ) if sunset is not None else Timestamp ( time . time ( ...
Processes a sorted and page - partitioned sequence of revision documents into and adds a persistence field to them containing statistics about how each token added in the revision persisted through future revisions .
8,008
def generator ( name ) : name = name . upper ( ) if name not in WHash . __hash_map__ . keys ( ) : raise ValueError ( 'Hash generator "%s" not available' % name ) return WHash . __hash_map__ [ name ]
Return generator by its name
8,009
def generator_by_digest ( family , digest_size ) : for generator_name in WHash . available_generators ( family = family ) : generator = WHash . generator ( generator_name ) if generator . generator_digest_size ( ) == digest_size : return generator raise ValueError ( 'Hash generator is not available' )
Return generator by hash generator family name and digest size
8,010
def sequence ( cls , * info ) : if len ( info ) == 0 : return info = list ( info ) info . reverse ( ) result = WMessengerOnionSessionFlowProto . Iterator ( info [ 0 ] . layer_name ( ) , ** info [ 0 ] . layer_args ( ) ) for i in range ( 1 , len ( info ) ) : result = WMessengerOnionSessionFlowProto . Iterator ( info [ i ...
Useful method to generate iterator . It is generated by chaining the given info . If no info is specified then None is returned
8,011
def from_string ( address ) : str_address = None if WMACAddress . re_dash_format . match ( address ) : str_address = "" . join ( address . split ( "-" ) ) elif WMACAddress . re_colon_format . match ( address ) : str_address = "" . join ( address . split ( ":" ) ) elif WMACAddress . re_cisco_format . match ( address ) :...
Return new object by the given MAC - address
8,012
def from_string ( address ) : address = address . split ( '.' ) if len ( address ) != WIPV4Address . octet_count : raise ValueError ( 'Invalid ip address: %s' % address ) result = WIPV4Address ( ) for i in range ( WIPV4Address . octet_count ) : result . __address [ i ] = WBinArray ( int ( address [ i ] ) , WFixedSizeBy...
Parse string for IPv4 address
8,013
def to_string ( address , dns_format = False ) : if isinstance ( address , WIPV4Address ) is False : raise TypeError ( 'Invalid address type' ) address = [ str ( int ( x ) ) for x in address . __address ] if dns_format is False : return '.' . join ( address ) address . reverse ( ) return ( '.' . join ( address ) + '.in...
Convert address to string
8,014
def first_address ( self , skip_network_address = True ) : bin_address = self . __address . bin_address ( ) bin_address_length = len ( bin_address ) if self . __mask > ( bin_address_length - 2 ) : skip_network_address = False for i in range ( bin_address_length - self . __mask ) : bin_address [ self . __mask + i ] = 0 ...
Return the first IP address of this network
8,015
def last_address ( self , skip_broadcast_address = True ) : bin_address = self . __address . bin_address ( ) bin_address_length = len ( bin_address ) if self . __mask > ( bin_address_length - 2 ) : skip_broadcast_address = False for i in range ( bin_address_length - self . __mask ) : bin_address [ self . __mask + i ] =...
Return the last IP address of this network
8,016
def iterator ( self , skip_network_address = True , skip_broadcast_address = True ) : return WNetworkIPV4Iterator ( self , skip_network_address , skip_broadcast_address )
Return iterator that can iterate over network addresses
8,017
def from_string ( address ) : if len ( address ) == 0 : return WFQDN ( ) if address [ - 1 ] == '.' : address = address [ : - 1 ] if len ( address ) > WFQDN . maximum_fqdn_length : raise ValueError ( 'Invalid address' ) result = WFQDN ( ) for label in address . split ( '.' ) : if isinstance ( label , str ) and WFQDN . r...
Convert doted - written FQDN address to WFQDN object
8,018
def to_string ( address , leading_dot = False ) : if isinstance ( address , WFQDN ) is False : raise TypeError ( 'Invalid type for FQDN address' ) result = '.' . join ( address . _labels ) return result if leading_dot is False else ( result + '.' )
Return doted - written address by the given WFQDN object
8,019
def qteReparent ( self , parent ) : self . setParent ( parent ) try : self . _qteAdmin . parentWindow = parent . qteParentWindow ( ) except AttributeError : self . _qteAdmin . parentWindow = None if parent : msg = 'Parent is neither None, nor does it have a' msg += 'qteParentWindow field print ( msg )
Re - parent the applet .
8,020
def qteAddWidget ( self , widgetObj : QtGui . QWidget , isFocusable : bool = True , widgetSignature : str = None , autoBind : bool = True ) : widgetObj . _qteAdmin = QtmacsAdminStructure ( self , isFocusable = isFocusable ) widgetObj . _qteAdmin . appletID = self . _qteAdmin . appletID widgetObj . _qteAdmin . isQtmacsA...
Augment the standard Qt widgetObj with Qtmacs specific fields .
8,021
def qteSetAppletSignature ( self , signature : str ) : if '*' in signature : raise QtmacsOtherError ( 'The applet signature must not contain "*"' ) if signature == '' : raise QtmacsOtherError ( 'The applet signature must be non-empty' ) self . _qteAdmin . appletSignature = signature
Specify the applet signature .
8,022
def qteAutoremoveDeletedWidgets ( self ) : widget_list = self . _qteAdmin . widgetList deleted_widgets = [ _ for _ in widget_list if sip . isdeleted ( _ ) ] for widgetObj in deleted_widgets : self . _qteAdmin . widgetList . remove ( widgetObj )
Remove all widgets from the internal widget list that do not exist anymore according to SIP .
8,023
def qteSetWidgetFocusOrder ( self , widList : tuple ) : if len ( widList ) < 2 : return self . qteAutoremoveDeletedWidgets ( ) widList = [ _ for _ in widList if _ is not None ] for wid in widList : if wid not in self . _qteAdmin . widgetList : msg = 'Cannot change focus order because some ' msg += 'widgets do not exist...
Change the focus order of the widgets in this applet .
8,024
def qteNextWidget ( self , numSkip : int = 1 , ofsWidget : QtGui . QWidget = None , skipVisible : bool = False , skipInvisible : bool = True , skipFocusable : bool = False , skipUnfocusable : bool = True ) : if not hasattr ( ofsWidget , '_qteAdmin' ) and ( ofsWidget is not None ) : msg = '<ofsWidget> was probably not a...
Return the next widget in cyclic order .
8,025
def qteMakeWidgetActive ( self , widgetObj : QtGui . QWidget ) : if widgetObj is None : self . _qteActiveWidget = None return if qteGetAppletFromWidget ( widgetObj ) is not self : msg = 'The specified widget is not inside the current applet.' raise QtmacsOtherError ( msg ) if not hasattr ( widgetObj , '_qteAdmin' ) : s...
Give keyboard focus to widgetObj .
8,026
def split_key ( key ) : if key == KEY_SEP : return ( ) key_chunks = tuple ( key . strip ( KEY_SEP ) . split ( KEY_SEP ) ) if key_chunks [ 0 ] . startswith ( KEY_SEP ) : return ( key_chunks [ 0 ] [ len ( KEY_SEP ) : ] , ) + key_chunks [ 1 : ] else : return key_chunks
Splits a node key .
8,027
def set ( self , index , value = None , dir = False , ttl = None , expiration = None ) : if bool ( dir ) is ( value is not None ) : raise TypeError ( 'Choose one of value or directory' ) if ( ttl is not None ) is ( expiration is None ) : raise TypeError ( 'Both of ttl and expiration required' ) self . value = value if ...
Updates the node data .
8,028
def make_result ( self , result_class , node = None , prev_node = None , remember = True , key_chunks = None , notify = True , ** kwargs ) : def canonicalize ( node , ** kwargs ) : return None if node is None else node . canonicalize ( ** kwargs ) index = self . index result = result_class ( canonicalize ( node , ** kw...
Makes an etcd result .
8,029
def connect ( self , host = 'localhost' ) : get_logger ( ) . info ( "Connecting to RabbitMQ server..." ) self . _conn = pika . BlockingConnection ( pika . ConnectionParameters ( host = host ) ) self . _channel = self . _conn . channel ( ) get_logger ( ) . info ( "Declaring topic exchanger {}..." . format ( self . excha...
Connect to the server and set everything up .
8,030
def publish ( self , topic , dct ) : get_logger ( ) . info ( "Publishing message {} on routing key " "{}..." . format ( dct , topic ) ) self . _channel . basic_publish ( exchange = self . exchange , routing_key = topic , body = json . dumps ( dct ) )
Send a dict with internal routing key to the exchange .
8,031
def _callback ( self , ch , method , properties , body ) : get_logger ( ) . info ( "Message received! Calling listeners..." ) topic = method . routing_key dct = json . loads ( body . decode ( 'utf-8' ) ) for listener in self . listeners : listener ( self , topic , dct )
Internal method that will be called when receiving message .
8,032
def _handle_ping ( client , topic , dct ) : if dct [ 'type' ] == 'request' : resp = { 'type' : 'answer' , 'name' : client . name , 'source' : dct } client . publish ( 'ping' , resp )
Internal method that will be called when receiving ping message .
8,033
def _create_argument_value_pairs ( func , * args , ** kwargs ) : try : arg_dict = signature ( func ) . bind_partial ( * args , ** kwargs ) . arguments except TypeError : return dict ( ) arguments = signature ( func ) . parameters for arg_name in arguments : if ( arguments [ arg_name ] . default != Parameter . empty ) a...
Create dictionary with argument names as keys and their passed values as values .
8,034
def _get_contract_exception_dict ( contract_msg ) : start_token = "[START CONTRACT MSG: " stop_token = "[STOP CONTRACT MSG]" if contract_msg . find ( start_token ) == - 1 : return { "num" : 0 , "msg" : "Argument `*[argument_name]*` is not valid" , "type" : RuntimeError , "field" : "argument_name" , } msg_start = contra...
Generate message for exception .
8,035
def _get_custom_contract ( param_contract ) : if not isinstance ( param_contract , str ) : return None for custom_contract in _CUSTOM_CONTRACTS : if re . search ( r"\b{0}\b" . format ( custom_contract ) , param_contract ) : return custom_contract return None
Return True if parameter contract is a custom contract False otherwise .
8,036
def _get_replacement_token ( msg ) : return ( None if not re . search ( r"\*\[[\w|\W]+\]\*" , msg ) else re . search ( r"\*\[[\w|\W]+\]\*" , msg ) . group ( ) [ 2 : - 2 ] )
Extract replacement token from exception message .
8,037
def _get_type_name ( type_ ) : name = repr ( type_ ) if name . startswith ( "<" ) : name = getattr ( type_ , "__qualname__" , getattr ( type_ , "__name__" , "" ) ) return name . rsplit ( "." , 1 ) [ - 1 ] or repr ( type_ )
Return a displayable name for the type .
8,038
def _get_class_frame_source ( class_name ) : for frame_info in inspect . stack ( ) : try : with open ( frame_info [ 1 ] ) as fp : src = "" . join ( fp . readlines ( ) [ frame_info [ 2 ] - 1 : ] ) except IOError : continue if re . search ( r"\bclass\b\s+\b{}\b" . format ( class_name ) , src ) : reader = six . StringIO (...
Return the source code for a class by checking the frame stack .
8,039
def _is_propertyable ( names , attrs , annotations , attr , ) : return ( attr in annotations and not attr . startswith ( "_" ) and not attr . isupper ( ) and "__{}" . format ( attr ) not in names and not isinstance ( getattr ( attrs , attr , None ) , types . MethodType ) )
Determine if an attribute can be replaced with a property .
8,040
def _create_typed_object_meta ( get_fset ) : def _get_fget ( attr , private_attr , type_ ) : def _fget ( self ) : try : return getattr ( self , private_attr ) except AttributeError : raise AttributeError ( "'{}' object has no attribute '{}'" . format ( _get_type_name ( type_ ) , attr ) ) return _fget class _AnnotatedOb...
Create a metaclass for typed objects .
8,041
def _tp__get_typed_properties ( self ) : try : return tuple ( getattr ( self , p ) for p in self . _tp__typed_properties ) except AttributeError : raise NotImplementedError
Return a tuple of typed attrs that can be used for comparisons .
8,042
def run ( cls , routes , * args , ** kwargs ) : app = init ( cls , routes , * args , ** kwargs ) HOST = os . getenv ( 'HOST' , '0.0.0.0' ) PORT = int ( os . getenv ( 'PORT' , 8000 ) ) aiohttp . web . run_app ( app , port = PORT , host = HOST )
Run a web application .
8,043
def add ( self , vector , InterventionAnophelesParams = None ) : assert isinstance ( vector , six . string_types ) et = ElementTree . fromstring ( vector ) mosquito = Vector ( et ) assert isinstance ( mosquito . mosquito , str ) assert isinstance ( mosquito . propInfected , float ) assert len ( mosquito . seasonality ....
Add a vector to entomology section . vector is either ElementTree or xml snippet
8,044
def _format_msg ( text , width , indent = 0 , prefix = "" ) : r text = repr ( text ) . replace ( "`" , "\\`" ) . replace ( "\\n" , " ``\\n`` " ) sindent = " " * indent if not prefix else prefix wrapped_text = textwrap . wrap ( text , width , subsequent_indent = sindent ) return ( "\n" . join ( wrapped_text ) ) [ 1 : - ...
r Format exception message .
8,045
def _validate_fname ( fname , arg_name ) : if fname is not None : msg = "Argument `{0}` is not valid" . format ( arg_name ) if ( not isinstance ( fname , str ) ) or ( isinstance ( fname , str ) and ( "\0" in fname ) ) : raise RuntimeError ( msg ) try : if not os . path . exists ( fname ) : os . access ( fname , os . W_...
Validate that a string is a valid file name .
8,046
def _build_ex_tree ( self ) : sep = self . _exh_obj . callables_separator data = self . _exh_obj . exceptions_db if not data : raise RuntimeError ( "Exceptions database is empty" ) for item in data : item [ "name" ] = "root{sep}{name}" . format ( sep = sep , name = item [ "name" ] ) self . _tobj = ptrie . Trie ( sep ) ...
Construct exception tree from trace .
8,047
def _build_module_db ( self ) : tdict = collections . defaultdict ( lambda : [ ] ) for callable_name , callable_dict in self . _exh_obj . callables_db . items ( ) : fname , line_no = callable_dict [ "code_id" ] cname = ( "{cls_name}.__init__" . format ( cls_name = callable_name ) if callable_dict [ "type" ] == "class" ...
Build database of module callables sorted by line number .
8,048
def _process_exlist ( self , exc , raised ) : if ( not raised ) or ( raised and exc . endswith ( "*" ) ) : return exc [ : - 1 ] if exc . endswith ( "*" ) else exc return None
Remove raised info from exception message and create separate list for it .
8,049
def _set_depth ( self , depth ) : if depth and ( ( not isinstance ( depth , int ) ) or ( isinstance ( depth , int ) and ( depth < 0 ) ) ) : raise RuntimeError ( "Argument `depth` is not valid" ) self . _depth = depth
Depth setter .
8,050
def _set_exclude ( self , exclude ) : if exclude and ( ( not isinstance ( exclude , list ) ) or ( isinstance ( exclude , list ) and any ( [ not isinstance ( item , str ) for item in exclude ] ) ) ) : raise RuntimeError ( "Argument `exclude` is not valid" ) self . _exclude = exclude
Exclude setter .
8,051
def get_sphinx_autodoc ( self , depth = None , exclude = None , width = 72 , error = False , raised = False , no_comment = False , ) : r frame = sys . _getframe ( 1 ) index = frame . f_code . co_filename . rfind ( "+" ) fname = os . path . abspath ( frame . f_code . co_filename [ : index ] ) line_num = int ( frame . f_...
r Return exception list in reStructuredText _ auto - determining callable name .
8,052
def resize ( self , size ) : if size < len ( self ) : raise ValueError ( "Value is out of bound. Array can't be shrinked" ) current_size = self . __size for i in range ( size - current_size ) : self . __array . append ( WBinArray ( 0 , self . __class__ . byte_size ) ) self . __size = size
Grow this array to specified length . This array can t be shrinked
8,053
def swipe ( self ) : result = WFixedSizeByteArray ( len ( self ) ) for i in range ( len ( self ) ) : result [ len ( self ) - i - 1 ] = self [ i ] return result
Mirror current array value in reverse . Bytes that had greater index will have lesser index and vice - versa . This method doesn t change this array . It creates a new one and return it as a result .
8,054
def mime_type ( filename ) : try : __mime_lock . acquire ( ) extension = filename . split ( "." ) extension = extension [ len ( extension ) - 1 ] if extension == "woff2" : return "application/font-woff2" if extension == "css" : return "text/css" m = magic . from_file ( filename , mime = True ) m = m . decode ( ) if isi...
Guess mime type for the given file name
8,055
def _validate_type ( self , item , name ) : if item is None : return if not isinstance ( item , self . allowed_types ) : item_class_name = item . __class__ . __name__ raise ArgumentError ( name , "Expected one of %s, but got `%s`" % ( self . allowed_types , item_class_name ) )
Validate the item against allowed_types .
8,056
def _validate_required ( self , item , name ) : if self . required is True and item is None : raise ArgumentError ( name , "This argument is required." )
Validate that the item is present if it s required .
8,057
def doc_dict ( self ) : doc = { 'type' : self . __class__ . __name__ , 'description' : self . description , 'default' : self . default , 'required' : self . required } if hasattr ( self , 'details' ) : doc [ 'detailed_description' ] = self . details return doc
Returns the documentation dictionary for this argument .
8,058
def validate_items ( self , input_list ) : output_list = [ ] for item in input_list : valid = self . list_item_type . validate ( item , self . item_name ) output_list . append ( valid ) return output_list
Validates that items in the list are of the type specified .
8,059
def startserver ( self , hostname = "localhost" , port = 8080 , daemon = False , handle_sigint = True ) : if daemon : print ( "Sorry daemon server not supported just yet." ) else : print ( "Starting %s json-rpc service at http://%s:%s" % ( self . __class__ . __name__ , hostname , port ) ) self . _http_server = HTTPServ...
Start json - rpc service .
8,060
def _get_asym_hel ( self , d ) : d0 = d [ 0 ] d1 = d [ 2 ] d2 = d [ 1 ] d3 = d [ 3 ] denom1 = d0 + d1 denom2 = d2 + d3 denom1 [ denom1 == 0 ] = np . nan denom2 [ denom2 == 0 ] = np . nan asym_hel = [ ( d0 - d1 ) / denom1 , ( d2 - d3 ) / denom2 ] asym_hel_err = [ 2 * np . sqrt ( d0 * d1 / np . power ( denom1 , 3 ) ) , 2...
Find the asymmetry of each helicity .
8,061
def _get_asym_comb ( self , d ) : d0 = d [ 0 ] d1 = d [ 2 ] d2 = d [ 1 ] d3 = d [ 3 ] r_denom = d0 * d3 r_denom [ r_denom == 0 ] = np . nan r = np . sqrt ( ( d1 * d2 / r_denom ) ) r [ r == - 1 ] = np . nan asym_comb = ( r - 1 ) / ( r + 1 ) d0 [ d0 == 0 ] = np . nan d1 [ d1 == 0 ] = np . nan d2 [ d2 == 0 ] = np . nan d3...
Find the combined asymmetry for slr runs . Elegant 4 - counter method .
8,062
def _get_1f_sum_scans ( self , d , freq ) : unique_freq = np . unique ( freq ) sum_scans = [ [ ] for i in range ( len ( d ) ) ] for f in unique_freq : tag = freq == f for i in range ( len ( d ) ) : sum_scans [ i ] . append ( np . sum ( d [ i ] [ tag ] ) ) return ( np . array ( unique_freq ) , np . array ( sum_scans ) )
Sum counts in each frequency bin over 1f scans .
8,063
def get_pulse_s ( self ) : try : dwelltime = self . ppg . dwelltime . mean beam_on = self . ppg . beam_on . mean except AttributeError : raise AttributeError ( "Missing logged ppg parameter: dwelltime " + "or beam_on" ) return dwelltime * beam_on / 1000.
Get pulse duration in seconds for pulsed measurements .
8,064
def extract_endpoints ( api_module ) : if not hasattr ( api_module , 'endpoints' ) : raise ValueError ( ( "pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!" ) ) endpoints = api_module . endpoints if isinstance ( endpoints , types . ModuleType ) : classes = [ v...
Return the endpoints from an API implementation module .
8,065
def extract_resources ( api_module ) : endpoints = extract_endpoints ( api_module ) resource_classes = [ e . _returns . __class__ for e in endpoints ] return list ( set ( resource_classes ) )
Return the resources from an API implementation module .
8,066
def load_template_source ( self , template_name , template_dirs = None ) : log . error ( "Calling zip loader" ) for folder in app_template_dirs : if ".zip/" in folder . replace ( "\\" , "/" ) : lib_file , relative_folder = get_zip_file_and_relative_path ( folder ) log . error ( lib_file , relative_folder ) try : z = zi...
Template loader that loads templates from zipped modules .
8,067
def fetch ( self , start = None , stop = None ) : if not start : start = 0 if not stop : stop = len ( self . log ) if start < 0 : start = 0 if stop > len ( self . log ) : stop = len ( self . log ) self . waitForFetch = False return self . log [ start : stop ]
Fetch log records and return them as a list .
8,068
def bind_blueprint ( pale_api_module , flask_blueprint ) : if not isinstance ( flask_blueprint , Blueprint ) : raise TypeError ( ( "pale.flask_adapter.bind_blueprint expected the " "passed in flask_blueprint to be an instance of " "Blueprint, but it was an instance of %s instead." ) % ( type ( flask_blueprint ) , ) ) i...
Binds an implemented pale API module to a Flask Blueprint .
8,069
def cookie_name_check ( cookie_name ) : cookie_match = WHTTPCookie . cookie_name_non_compliance_re . match ( cookie_name . encode ( 'us-ascii' ) ) return len ( cookie_name ) > 0 and cookie_match is None
Check cookie name for validity . Return True if name is valid
8,070
def cookie_attr_value_check ( attr_name , attr_value ) : attr_value . encode ( 'us-ascii' ) return WHTTPCookie . cookie_attr_value_compliance [ attr_name ] . match ( attr_value ) is not None
Check cookie attribute value for validity . Return True if value is valid
8,071
def __attr_name ( self , name ) : if name not in self . cookie_attr_value_compliance . keys ( ) : suggested_name = name . replace ( '_' , '-' ) . lower ( ) if suggested_name not in self . cookie_attr_value_compliance . keys ( ) : raise ValueError ( 'Invalid attribute name is specified' ) name = suggested_name return na...
Return suitable and valid attribute name . This method replaces dash char to underscore . If name is invalid ValueError exception is raised
8,072
def remove_cookie ( self , cookie_name ) : if self . __ro_flag : raise RuntimeError ( 'Read-only cookie-jar changing attempt' ) if cookie_name in self . __cookies . keys ( ) : self . __cookies . pop ( cookie_name )
Remove cookie by its name
8,073
def ro ( self ) : ro_jar = WHTTPCookieJar ( ) for cookie in self . __cookies . values ( ) : ro_jar . add_cookie ( cookie . ro ( ) ) ro_jar . __ro_flag = True return ro_jar
Return read - only copy
8,074
def import_simple_cookie ( cls , simple_cookie ) : cookie_jar = WHTTPCookieJar ( ) for cookie_name in simple_cookie . keys ( ) : cookie_attrs = { } for attr_name in WHTTPCookie . cookie_attr_value_compliance . keys ( ) : attr_value = simple_cookie [ cookie_name ] [ attr_name ] if attr_value != '' : cookie_attrs [ attr_...
Create cookie jar from SimpleCookie object
8,075
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
Check if n is a prime number
8,076
def loadFile ( self , fileName ) : self . file = QtCore . QFile ( fileName ) if self . file . exists ( ) : self . qteText . append ( open ( fileName ) . read ( ) ) else : msg = "File <b>{}</b> does not exist" . format ( self . qteAppletID ( ) ) self . qteLogger . info ( msg )
Display the file associated with the appletID .
8,077
def _encode ( self ) : obj = { k : v for k , v in self . __dict__ . items ( ) if not k . startswith ( '_' ) and type ( v ) in SAFE_TYPES } obj . update ( { k : v . _encode ( ) for k , v in self . __dict__ . items ( ) if isinstance ( v , Ent ) } ) return obj
Generate a recursive JSON representation of the ent .
8,078
def merge ( cls , * args , ** kwargs ) : newkeys = bool ( kwargs . get ( 'newkeys' , False ) ) ignore = kwargs . get ( 'ignore' , list ( ) ) if len ( args ) < 1 : raise ValueError ( 'no ents given to Ent.merge()' ) elif not all ( isinstance ( s , Ent ) for s in args ) : raise ValueError ( 'all positional arguments to E...
Create a new Ent from one or more existing Ents . Keys in the later Ent objects will overwrite the keys of the previous Ents . Later keys of different type than in earlier Ents will be bravely ignored .
8,079
def diff ( cls , * args , ** kwargs ) : newkeys = bool ( kwargs . get ( 'newkeys' , False ) ) ignore = kwargs . get ( 'ignore' , list ( ) ) if len ( args ) < 2 : raise ValueError ( 'less than two ents given to Ent.diff()' ) elif not all ( isinstance ( s , Ent ) for s in args ) : raise ValueError ( 'all positional argum...
Create a new Ent representing the differences in two or more existing Ents . Keys in the later Ents with values that differ from the earlier Ents will be present in the final Ent with the latest value seen for that key . Later keys of different type than in earlier Ents will be bravely ignored .
8,080
def subclasses ( cls ) : seen = set ( ) queue = set ( [ cls ] ) while queue : c = queue . pop ( ) seen . add ( c ) sc = c . __subclasses__ ( ) for c in sc : if c not in seen : queue . add ( c ) seen . remove ( cls ) return seen
Return a set of all Ent subclasses recursively .
8,081
def base_url ( self ) : if self . location in self . known_locations : return self . known_locations [ self . location ] elif '.' in self . location or self . location == 'localhost' : return 'https://' + self . location else : return 'https://' + self . location + API_HOST_SUFFIX
Protocol + hostname
8,082
def _build_exclusion_list ( exclude ) : mod_files = [ ] if exclude : for mod in exclude : mdir = None mod_file = None for token in mod . split ( "." ) : try : mfile , mdir , _ = imp . find_module ( token , mdir and [ mdir ] ) if mfile : mod_file = mfile . name mfile . close ( ) except ImportError : msg = "Source for mo...
Build file names list of modules to exclude from exception handling .
8,083
def _invalid_frame ( fobj ) : fin = fobj . f_code . co_filename invalid_module = any ( [ fin . endswith ( item ) for item in _INVALID_MODULES_LIST ] ) return invalid_module or ( not os . path . isfile ( fin ) )
Select valid stack frame to process .
8,084
def _sorted_keys_items ( dobj ) : keys = sorted ( dobj . keys ( ) ) for key in keys : yield key , dobj [ key ]
Return dictionary items sorted by key .
8,085
def addex ( extype , exmsg , condition = None , edata = None ) : r return _ExObj ( extype , exmsg , condition , edata ) . craise
r Add an exception in the global exception handler .
8,086
def addai ( argname , condition = None ) : r if not isinstance ( argname , str ) : raise RuntimeError ( "Argument `argname` is not valid" ) if ( condition is not None ) and ( type ( condition ) != bool ) : raise RuntimeError ( "Argument `condition` is not valid" ) obj = _ExObj ( RuntimeError , "Argument `{0}` is not va...
r Add an AI exception in the global exception handler .
8,087
def get_or_create_exh_obj ( full_cname = False , exclude = None , callables_fname = None ) : r if not hasattr ( __builtin__ , "_EXH" ) : set_exh_obj ( ExHandle ( full_cname = full_cname , exclude = exclude , callables_fname = callables_fname ) ) return get_exh_obj ( )
r Return global exception handler if set otherwise create a new one and return it .
8,088
def _flatten_ex_dict ( self ) : odict = { } for _ , fdict in self . _ex_dict . items ( ) : for ( extype , exmsg ) , value in fdict . items ( ) : key = value [ "name" ] odict [ key ] = copy . deepcopy ( value ) del odict [ key ] [ "name" ] odict [ key ] [ "type" ] = extype odict [ key ] [ "msg" ] = exmsg return odict
Flatten structure of exceptions dictionary .
8,089
def _format_msg ( self , msg , edata ) : edata = edata if isinstance ( edata , list ) else [ edata ] for fdict in edata : if "*[{token}]*" . format ( token = fdict [ "field" ] ) not in msg : raise RuntimeError ( "Field {token} not in exception message" . format ( token = fdict [ "field" ] ) ) msg = msg . replace ( "*[{...
Substitute parameters in exception message .
8,090
def _get_exceptions_db ( self ) : template = "{extype} ({exmsg}){raised}" if not self . _full_cname : ret = [ ] for _ , fdict in self . _ex_dict . items ( ) : for key in fdict . keys ( ) : ret . append ( { "name" : fdict [ key ] [ "name" ] , "data" : template . format ( extype = _ex_type_str ( key [ 0 ] ) , exmsg = key...
Return a list of dictionaries suitable to be used with ptrie module .
8,091
def _get_ex_data ( self ) : func_id , func_name = self . _get_callable_path ( ) if self . _full_cname : func_name = self . encode_call ( func_name ) return func_id , func_name
Return hierarchical function name .
8,092
def _property_search ( self , fobj ) : scontext = fobj . f_locals . get ( "self" , None ) class_obj = scontext . __class__ if scontext is not None else None if not class_obj : del fobj , scontext , class_obj return None class_props = [ ( member_name , member_obj ) for member_name , member_obj in inspect . getmembers ( ...
Return full name if object is a class property otherwise return None .
8,093
def _raise_exception ( self , eobj , edata = None ) : _ , _ , tbobj = sys . exc_info ( ) if edata : emsg = self . _format_msg ( eobj [ "msg" ] , edata ) _rwtb ( eobj [ "type" ] , emsg , tbobj ) else : _rwtb ( eobj [ "type" ] , eobj [ "msg" ] , tbobj )
Raise exception by name .
8,094
def _unwrap_obj ( self , fobj , fun ) : try : prev_func_obj , next_func_obj = ( fobj . f_globals [ fun ] , getattr ( fobj . f_globals [ fun ] , "__wrapped__" , None ) , ) while next_func_obj : prev_func_obj , next_func_obj = ( next_func_obj , getattr ( next_func_obj , "__wrapped__" , None ) , ) return ( prev_func_obj ,...
Unwrap decorators .
8,095
def _validate_edata ( self , edata ) : if edata is None : return True if not ( isinstance ( edata , dict ) or _isiterable ( edata ) ) : return False edata = [ edata ] if isinstance ( edata , dict ) else edata for edict in edata : if ( not isinstance ( edict , dict ) ) or ( isinstance ( edict , dict ) and ( ( "field" no...
Validate edata argument of raise_exception_if method .
8,096
def add_exception ( self , exname , extype , exmsg ) : r if not isinstance ( exname , str ) : raise RuntimeError ( "Argument `exname` is not valid" ) number = True try : int ( exname ) except ValueError : number = False if number : raise RuntimeError ( "Argument `exname` is not valid" ) if not isinstance ( exmsg , str ...
r Add an exception to the handler .
8,097
def decode_call ( self , call ) : if call is None : return None itokens = call . split ( self . _callables_separator ) odict = { } for key , value in self . _clut . items ( ) : if value in itokens : odict [ itokens [ itokens . index ( value ) ] ] = key return self . _callables_separator . join ( [ odict [ itoken ] for ...
Replace callable tokens with callable names .
8,098
def encode_call ( self , call ) : if call is None : return None itokens = call . split ( self . _callables_separator ) otokens = [ ] for itoken in itokens : otoken = self . _clut . get ( itoken , None ) if not otoken : otoken = str ( len ( self . _clut ) ) self . _clut [ itoken ] = otoken otokens . append ( otoken ) re...
Replace callables with tokens to reduce object memory footprint .
8,099
def default ( self , obj ) : try : if isinstance ( obj , datetime . datetime ) : encoded = arrow . get ( obj ) . isoformat ( ) else : encoded = json . JSONEncoder . default ( self , obj ) except TypeError as e : if hasattr ( obj , 'to_dict' ) and callable ( obj . to_dict ) : encoded = obj . to_dict ( ) else : raise e r...
Default JSON encoding .