idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
8,100
def logout ( client ) : if not client . session_id : client . request_session ( ) concierge_request_header = client . construct_concierge_header ( url = ( "http://membersuite.com/contracts/IConciergeAPIService/" "Logout" ) ) logout_result = client . client . service . Logout ( _soapheaders = [ concierge_request_header ] ) result = logout_result [ "body" ] [ "LogoutResult" ] if result [ "SessionID" ] is None : # Success! client . session_id = None else : # Failure . . . raise LogoutError ( result = result )
Log out the currently logged - in user .
156
9
8,101
def get_user_for_membersuite_entity ( membersuite_entity ) : user = None user_created = False # First, try to match on username. user_username = generate_username ( membersuite_entity ) try : user = User . objects . get ( username = user_username ) except User . DoesNotExist : pass # Next, try to match on email address. if not user : try : user = User . objects . filter ( email = membersuite_entity . email_address ) [ 0 ] except IndexError : pass # No match? Create one. if not user : user = User . objects . create ( username = user_username , email = membersuite_entity . email_address , first_name = membersuite_entity . first_name , last_name = membersuite_entity . last_name ) user_created = True return user , user_created
Returns a User for membersuite_entity .
196
10
8,102
def add_validator ( self , validator ) : if not isinstance ( validator , AbstractValidator ) : err = 'Validator must be of type {}' . format ( AbstractValidator ) raise InvalidValidator ( err ) self . validators . append ( validator ) return self
Add validator to property
62
5
8,103
def filter ( self , value = None , model = None , context = None ) : if value is None : return value for filter_obj in self . filters : value = filter_obj . filter ( value = value , model = model , context = context if self . use_context else None ) return value
Sequentially applies all the filters to provided value
64
9
8,104
def validate ( self , value = None , model = None , context = None ) : errors = [ ] for validator in self . validators : if value is None and not isinstance ( validator , Required ) : continue error = validator . run ( value = value , model = model , context = context if self . use_context else None ) if error : errors . append ( error ) return errors
Sequentially apply each validator to value and collect errors .
85
12
8,105
def filter_with_schema ( self , model = None , context = None ) : if model is None or self . schema is None : return self . _schema . filter ( model = model , context = context if self . use_context else None )
Perform model filtering with schema
55
6
8,106
def validate_with_schema ( self , model = None , context = None ) : if self . _schema is None or model is None : return result = self . _schema . validate ( model = model , context = context if self . use_context else None ) return result
Perform model validation with schema
61
6
8,107
def filter_with_schema ( self , collection = None , context = None ) : if collection is None or self . schema is None : return try : for item in collection : self . _schema . filter ( model = item , context = context if self . use_context else None ) except TypeError : pass
Perform collection items filtering with schema
67
7
8,108
def validate_with_schema ( self , collection = None , context = None ) : if self . _schema is None or not collection : return result = [ ] try : for index , item in enumerate ( collection ) : item_result = self . _schema . validate ( model = item , context = context if self . use_context else None ) result . append ( item_result ) except TypeError : pass return result
Validate each item in collection with our schema
92
9
8,109
def json_based_stable_hash ( obj ) : encoded_str = json . dumps ( obj = obj , skipkeys = False , ensure_ascii = False , check_circular = True , allow_nan = True , cls = None , indent = 0 , separators = ( ',' , ':' ) , default = None , sort_keys = True , ) . encode ( 'utf-8' ) return hashlib . sha256 ( encoded_str ) . hexdigest ( )
Computes a cross - kernel stable hash value for the given object .
108
14
8,110
def read_request_line ( self , request_line ) : request = self . __request_cls . parse_request_line ( self , request_line ) protocol_version = self . protocol_version ( ) if protocol_version == '0.9' : if request . method ( ) != 'GET' : raise Exception ( 'HTTP/0.9 standard violation' ) elif protocol_version == '1.0' or protocol_version == '1.1' : pass elif protocol_version == '2' : pass else : raise RuntimeError ( 'Unsupported HTTP-protocol' )
Read HTTP - request line
131
5
8,111
def metaclass ( * metaclasses ) : # type: (*type) -> Callable[[type], type] def _inner ( cls ) : # pragma pylint: disable=unused-variable metabases = tuple ( collections . OrderedDict ( # noqa: F841 ( c , None ) for c in ( metaclasses + ( type ( cls ) , ) ) ) . keys ( ) ) # pragma pylint: enable=unused-variable _Meta = metabases [ 0 ] for base in metabases [ 1 : ] : class _Meta ( base , _Meta ) : # pylint: disable=function-redefined pass return six . add_metaclass ( _Meta ) ( cls ) return _inner
Create the class using all metaclasses .
165
9
8,112
def get_attrition_in_years ( self ) : attrition_of_nets = self . itn . find ( "attritionOfNets" ) function = attrition_of_nets . attrib [ "function" ] if function != "step" : return None L = attrition_of_nets . attrib [ "L" ] return L
Function for the Basic UI
75
5
8,113
def add ( self , intervention , name = None ) : if self . et is None : return assert isinstance ( intervention , six . string_types ) et = ElementTree . fromstring ( intervention ) vector_pop = VectorPopIntervention ( et ) assert isinstance ( vector_pop . name , six . string_types ) if name is not None : assert isinstance ( name , six . string_types ) et . attrib [ "name" ] = name index = len ( self . et . findall ( "intervention" ) ) self . et . insert ( index , et )
Add an intervention to vectorPop section . intervention is either ElementTree or xml snippet
125
16
8,114
def add ( self , value ) : index = len ( self . __history ) self . __history . append ( value ) return index
Add new record to history . Record will be added to the end
28
13
8,115
def start_session ( self ) : self . __current_row = '' self . __history_mode = False self . __editable_history = deepcopy ( self . __history ) self . __prompt_show = True self . refresh_window ( )
Start new session and prepare environment for new row editing process
56
11
8,116
def fin_session ( self ) : self . __prompt_show = False self . __history . add ( self . row ( ) ) self . exec ( self . row ( ) )
Finalize current session
40
4
8,117
def data ( self , previous_data = False , prompt = False , console_row = False , console_row_to_cursor = False , console_row_from_cursor = False ) : result = '' if previous_data : result += self . __previous_data if prompt or console_row or console_row_to_cursor : result += self . console ( ) . prompt ( ) if console_row or ( console_row_from_cursor and console_row_to_cursor ) : result += self . console ( ) . row ( ) elif console_row_to_cursor : result += self . console ( ) . row ( ) [ : self . cursor ( ) ] elif console_row_from_cursor : result += self . console ( ) . row ( ) [ self . cursor ( ) : ] return result
Return output data . Flags specifies what data to append . If no flags was specified nul - length string returned
186
22
8,118
def write_data ( self , data , start_position = 0 ) : if len ( data ) > self . height ( ) : raise ValueError ( 'Data too long (too many strings)' ) for i in range ( len ( data ) ) : self . write_line ( start_position + i , data [ i ] )
Write data from the specified line
70
6
8,119
def write_feedback ( self , feedback , cr = True ) : self . __previous_data += feedback if cr is True : self . __previous_data += '\n'
Store feedback . Keep specified feedback as previous output
41
9
8,120
def refresh ( self , prompt_show = True ) : self . clear ( ) for drawer in self . __drawers : if drawer . suitable ( self , prompt_show = prompt_show ) : drawer . draw ( self , prompt_show = prompt_show ) return raise RuntimeError ( 'No suitable drawer was found' )
Refresh current window . Clear current window and redraw it with one of drawers
69
17
8,121
def is_dir ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_dir ( ) except AttributeError : return os . path . isdir ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) )
Determine if a Path or string is a directory on the file system .
61
16
8,122
def is_file ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_file ( ) except AttributeError : return os . path . isfile ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) )
Determine if a Path or string is a file on the file system .
61
16
8,123
def exists ( path ) : try : return path . expanduser ( ) . absolute ( ) . exists ( ) except AttributeError : return os . path . exists ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) )
Determine if a Path or string is an existing path on the file system .
56
17
8,124
def enableHook ( self , msgObj ) : self . killListIdx = len ( qte_global . kill_list ) - 2 self . qteMain . qtesigKeyseqComplete . connect ( self . disableHook )
Enable yank - pop .
52
6
8,125
def cursorPositionChangedEvent ( self ) : # Determine the sender and cursor position. qteWidget = self . sender ( ) tc = qteWidget . textCursor ( ) origin = tc . position ( ) # Remove all the highlighting. Since this will move the # cursor, first disconnect this very routine to avoid an # infinite recursion. qteWidget . cursorPositionChanged . disconnect ( self . cursorPositionChangedEvent ) self . qteRemoveHighlighting ( qteWidget ) qteWidget . cursorPositionChanged . connect ( self . cursorPositionChangedEvent ) # If we are beyond the last character (for instance because # the cursor was explicitly moved to the end of the buffer) # then there is no character to the right and will result in # an error when trying to fetch it. if origin >= len ( qteWidget . toPlainText ( ) ) : return else : # It is save to retrieve the character to the right of the # cursor. char = qteWidget . toPlainText ( ) [ origin ] # Return if the character is not in the matching list. if char not in self . charToHighlight : return # Disconnect the 'cursorPositionChanged' signal from this # function because it will make changes to the cursor position # and would therefore immediately trigger itself, resulting in # an infinite recursion. qteWidget . cursorPositionChanged . disconnect ( self . cursorPositionChangedEvent ) # If we got until here "char" must be one of the two # characters to highlight. if char == self . charToHighlight [ 0 ] : start = origin # Found the first character, so now look for the second # one. If this second character does not exist the # function returns '-1' which is safe because the # ``self.highlightCharacter`` method can deal with this. stop = qteWidget . toPlainText ( ) . find ( self . charToHighlight [ 1 ] , start + 1 ) else : # Found the second character so the start index is indeed # the stop index. stop = origin # Search for the preceeding first character. start = qteWidget . toPlainText ( ) . rfind ( self . charToHighlight [ 0 ] , 0 , stop ) # Highlight the characters. oldCharFormats = self . highlightCharacters ( qteWidget , ( start , stop ) , QtCore . Qt . blue , 100 ) # Store the positions of the changed character in the # macroData structure of this widget. data = self . qteMacroData ( qteWidget ) data . matchingPositions = ( start , stop ) data . oldCharFormats = oldCharFormats self . qteSaveMacroData ( data , qteWidget ) # Reconnect the 'cursorPositionChanged' signal. qteWidget . cursorPositionChanged . connect ( self . cursorPositionChangedEvent )
Update the highlighting .
605
4
8,126
def qteRemoveHighlighting ( self , widgetObj ) : # Retrieve the widget specific macro data. data = self . qteMacroData ( widgetObj ) if not data : return # If the data structure is empty then no previously # highlighted characters exist in this particular widget, so # do nothing. if not data . matchingPositions : return # Restore the original character formats, ie. undo the # highlighting changes. self . highlightCharacters ( widgetObj , data . matchingPositions , QtCore . Qt . black , 50 , data . oldCharFormats ) # Clear the data structure to indicate that no further # highlighted characters exist in this particular widget. data . matchingPositions = None data . oldCharFormats = None self . qteSaveMacroData ( data , widgetObj )
Remove the highlighting from previously highlighted characters .
166
8
8,127
def highlightCharacters ( self , widgetObj , setPos , colorCode , fontWeight , charFormat = None ) : # Get the text cursor and character format. textCursor = widgetObj . textCursor ( ) oldPos = textCursor . position ( ) retVal = [ ] # Change the character formats of all the characters placed at # the positions ``setPos``. for ii , pos in enumerate ( setPos ) : # Extract the position of the character to modify. pos = setPos [ ii ] # Ignore invalid positions. This can happen if the second # character does not exist and the find-functions in the # ``cursorPositionChangedEvent`` method returned # '-1'. Also, store **None** as the format for this # non-existent character. if pos < 0 : retVal . append ( None ) continue # Move the text cursor to the specified character position # and store its original character format (necessary to # "undo" the highlighting once the cursor was moved away # again). textCursor . setPosition ( pos ) retVal . append ( textCursor . charFormat ( ) ) # Change the character format. Either use the supplied # one, or use a generic one. if charFormat : # Use a specific character format (usually used to # undo the changes a previous call to # 'highlightCharacters' has made). fmt = charFormat [ ii ] else : # Modify the color and weight of the current character format. fmt = textCursor . charFormat ( ) # Get the brush and specify its foreground color and # style. In order to see the characters it is # necessary to explicitly specify a solidPattern style # but I have no idea why. myBrush = fmt . foreground ( ) myBrush . setColor ( colorCode ) myBrush . setStyle ( QtCore . Qt . SolidPattern ) fmt . setForeground ( myBrush ) fmt . setFontWeight ( fontWeight ) # Select the character and apply the selected format. textCursor . movePosition ( QtGui . QTextCursor . NextCharacter , QtGui . QTextCursor . KeepAnchor ) textCursor . setCharFormat ( fmt ) # Apply the textcursor to the current element. textCursor . setPosition ( oldPos ) widgetObj . setTextCursor ( textCursor ) return retVal
Change the character format of one or more characters .
497
10
8,128
def scenarios ( self , generate_seed = False ) : seed = prime_numbers ( 1000 ) sweeps_all = self . experiment [ "sweeps" ] . keys ( ) if "combinations" in self . experiment : if isinstance ( self . experiment [ "combinations" ] , list ) : # For backward compatibility with experiments1-4s combinations_in_experiment = { " " : self . experiment [ "combinations" ] } # if self.experiment["combinations"] == []: # # Special notation for fully-factorial experiments # combinations_in_experiment = {" ":[[],[]]} else : # Combinations must be a dictionary in this particular case combinations_in_experiment = self . experiment [ "combinations" ] else : # Support no combinations element: combinations_in_experiment = dict ( ) # empty dict # 1) calculate combinations_sweeps (depends on ALL combinations_ items) # Get the list of fully factorial sweeps all_combinations_sweeps = [ ] all_combinations = [ ] for key , combinations_ in combinations_in_experiment . items ( ) : # generate all permutations of all combinations if not combinations_ : # Fully factorial experiment, shortcut for "combinations":[[],[]] combinations_sweeps = [ ] combinations = [ [ ] ] else : # First item in combinations list is a list of sweeps combinations_sweeps = combinations_ [ 0 ] # then - all combinations combinations = combinations_ [ 1 : ] for item in combinations_sweeps : # TODO: error if sweep is already in this list? all_combinations_sweeps . append ( item ) all_combinations . append ( ( combinations_sweeps , combinations ) ) sweeps_fully_factorial = list ( set ( sweeps_all ) - set ( all_combinations_sweeps ) ) # print "fully fact: %s" % sweeps_fully_factorial # 2) produce a list of all combinations of fully factorial sweeps # First sets of "combinations": the fully-factorial sweeps for sweep in sweeps_fully_factorial : all_combinations . append ( ( [ sweep ] , [ [ x ] for x in self . experiment [ "sweeps" ] [ sweep ] . keys ( ) ] ) ) # 3) take the dot (inner) product of the list above (fully factorial arm combinations) # with the first combinations list, that with the second combination list, ... # step-by-step reduce the list of combinations to a single item # (dot-product of each list of combinations) # this could use a lot of memory... red_iter = 0 # print "all combinations:", red_iter, all_combinations while len ( all_combinations ) > 1 : comb1 = all_combinations [ 0 ] comb2 = all_combinations [ 1 ] new_sweeps = comb1 [ 0 ] + comb2 [ 0 ] new_combinations = [ x + y for x in comb1 [ 1 ] for y in comb2 [ 1 ] ] all_combinations = [ ( new_sweeps , new_combinations ) ] + all_combinations [ 2 : ] red_iter += 1 # print "all combinations:", red_iter, all_combinations # 4) write out the document for each in (3), which should specify one arm for each # sweep with no repetition of combinations sweep_names = all_combinations [ 0 ] [ 0 ] combinations = all_combinations [ 0 ] [ 1 ] for combination in combinations : scenario = Scenario ( self . _apply_combination ( self . experiment [ "base" ] , sweep_names , combination ) ) scenario . parameters = dict ( zip ( sweep_names , combination ) ) if generate_seed : # Replace seed if requested by the user if "@seed@" in scenario . xml : scenario . xml = scenario . xml . replace ( "@seed@" , str ( next ( seed ) ) ) else : raise ( RuntimeError ( "@seed@ placeholder is not found" ) ) yield scenario
Generator function . Spits out scenarios for this experiment
867
11
8,129
def lvm_info ( self , name = None ) : cmd = [ ] if self . sudo ( ) is False else [ 'sudo' ] cmd . extend ( [ self . command ( ) , '-c' ] ) if name is not None : cmd . append ( name ) output = subprocess . check_output ( cmd , timeout = self . cmd_timeout ( ) ) output = output . decode ( ) result = [ ] fields_count = self . fields_count ( ) for line in output . split ( '\n' ) : line = line . strip ( ) fields = line . split ( ':' ) if len ( fields ) == fields_count : result . append ( fields ) if name is not None and len ( result ) != 1 : raise RuntimeError ( 'Unable to parse command result' ) return tuple ( result )
Call a program
179
3
8,130
def uuid ( self ) : uuid_file = '/sys/block/%s/dm/uuid' % os . path . basename ( os . path . realpath ( self . volume_path ( ) ) ) lv_uuid = open ( uuid_file ) . read ( ) . strip ( ) if lv_uuid . startswith ( 'LVM-' ) is True : return lv_uuid [ 4 : ] return lv_uuid
Return UUID of logical volume
105
6
8,131
def create_snapshot ( self , snapshot_size , snapshot_suffix ) : size_extent = math . ceil ( self . extents_count ( ) * snapshot_size ) size_kb = self . volume_group ( ) . extent_size ( ) * size_extent snapshot_name = self . volume_name ( ) + snapshot_suffix lvcreate_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ) is True else [ ] lvcreate_cmd . extend ( [ 'lvcreate' , '-L' , '%iK' % size_kb , '-s' , '-n' , snapshot_name , '-p' , 'r' , self . volume_path ( ) ] ) subprocess . check_output ( lvcreate_cmd , timeout = self . __class__ . __lvm_snapshot_create_cmd_timeout__ ) return WLogicalVolume ( self . volume_path ( ) + snapshot_suffix , sudo = self . lvm_command ( ) . sudo ( ) )
Create snapshot for this logical volume .
238
7
8,132
def remove_volume ( self ) : lvremove_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ) is True else [ ] lvremove_cmd . extend ( [ 'lvremove' , '-f' , self . volume_path ( ) ] ) subprocess . check_output ( lvremove_cmd , timeout = self . __class__ . __lvm_snapshot_remove_cmd_timeout__ )
Remove this volume
100
3
8,133
def logical_volume ( cls , file_path , sudo = False ) : mp = WMountPoint . mount_point ( file_path ) if mp is not None : name_file = '/sys/block/%s/dm/name' % mp . device_name ( ) if os . path . exists ( name_file ) : lv_path = '/dev/mapper/%s' % open ( name_file ) . read ( ) . strip ( ) return WLogicalVolume ( lv_path , sudo = sudo )
Return logical volume that stores the given path
117
8
8,134
def write ( self , b ) : self . __buffer += bytes ( b ) bytes_written = 0 while len ( self . __buffer ) >= self . __cipher_block_size : io . BufferedWriter . write ( self , self . __cipher . encrypt_block ( self . __buffer [ : self . __cipher_block_size ] ) ) self . __buffer = self . __buffer [ self . __cipher_block_size : ] bytes_written += self . __cipher_block_size return len ( b )
Encrypt and write data
118
5
8,135
def reset_component ( self , component ) : if isinstance ( component , str ) is True : component = WURI . Component ( component ) self . __components [ component ] = None
Unset component in this URI
40
6
8,136
def parse ( cls , uri ) : uri_components = urlsplit ( uri ) adapter_fn = lambda x : x if x is not None and ( isinstance ( x , str ) is False or len ( x ) ) > 0 else None return cls ( scheme = adapter_fn ( uri_components . scheme ) , username = adapter_fn ( uri_components . username ) , password = adapter_fn ( uri_components . password ) , hostname = adapter_fn ( uri_components . hostname ) , port = adapter_fn ( uri_components . port ) , path = adapter_fn ( uri_components . path ) , query = adapter_fn ( uri_components . query ) , fragment = adapter_fn ( uri_components . fragment ) , )
Parse URI - string and return WURI object
185
10
8,137
def add_parameter ( self , name , value = None ) : if name not in self . __query : self . __query [ name ] = [ value ] else : self . __query [ name ] . append ( value )
Add new parameter value to this query . New value will be appended to previously added values .
49
19
8,138
def remove_parameter ( self , name ) : if name in self . __query : self . __query . pop ( name )
Remove the specified parameter from this query
28
7
8,139
def parse ( cls , query_str ) : parsed_query = parse_qs ( query_str , keep_blank_values = True , strict_parsing = True ) result = cls ( ) for parameter_name in parsed_query . keys ( ) : for parameter_value in parsed_query [ parameter_name ] : result . add_parameter ( parameter_name , parameter_value if len ( parameter_value ) > 0 else None ) return result
Parse string that represent query component from URI
100
9
8,140
def add_specification ( self , specification ) : name = specification . name ( ) if name in self . __specs : raise ValueError ( 'WStrictURIQuery object already has specification for parameter "%s" ' % name ) self . __specs [ name ] = specification
Add a new query parameter specification . If this object already has a specification for the specified parameter - exception is raised . No checks for the specified or any parameter are made regarding specification appending
60
37
8,141
def remove_specification ( self , name ) : if name in self . __specs : self . __specs . pop ( name )
Remove a specification that matches a query parameter . No checks for the specified or any parameter are made regarding specification removing
30
22
8,142
def replace_parameter ( self , name , value = None ) : spec = self . __specs [ name ] if name in self . __specs else None if self . extra_parameters ( ) is False and spec is None : raise ValueError ( 'Extra parameters are forbidden for this WStrictURIQuery object' ) if spec is not None and spec . nullable ( ) is False and value is None : raise ValueError ( 'Nullable values is forbidden for parameter "%s"' % name ) if spec is not None and value is not None : re_obj = spec . re_obj ( ) if re_obj is not None and re_obj . match ( value ) is None : raise ValueError ( 'Value does not match regular expression' ) WURIQuery . replace_parameter ( self , name , value = value )
Replace a query parameter values with a new value . If a new value does not match current specifications then exception is raised
178
24
8,143
def remove_parameter ( self , name ) : spec = self . __specs [ name ] if name in self . __specs else None if spec is not None and spec . optional ( ) is False : raise ValueError ( 'Unable to remove a required parameter "%s"' % name ) WURIQuery . remove_parameter ( self , name )
Remove parameter from this query . If a parameter is mandatory then exception is raised
76
15
8,144
def validate ( self , uri ) : requirement = self . requirement ( ) uri_component = uri . component ( self . component ( ) ) if uri_component is None : return requirement != WURIComponentVerifier . Requirement . required if requirement == WURIComponentVerifier . Requirement . unsupported : return False re_obj = self . re_obj ( ) if re_obj is not None : return re_obj . match ( uri_component ) is not None return True
Check an URI for compatibility with this specification . Return True if the URI is compatible .
109
17
8,145
def validate ( self , uri ) : if WURIComponentVerifier . validate ( self , uri ) is False : return False try : WStrictURIQuery ( WURIQuery . parse ( uri . component ( self . component ( ) ) ) , * self . __specs , extra_parameters = self . __extra_parameters ) except ValueError : return False return True
Check that an query part of an URI is compatible with this descriptor . Return True if the URI is compatible .
85
22
8,146
def is_compatible ( self , uri ) : for component , component_value in uri : if self . verifier ( component ) . validate ( uri ) is False : return False return True
Check if URI is compatible with this specification . Compatible URI has scheme name that matches specification scheme name has all of the required components does not have unsupported components and may have optional components
42
36
8,147
def handler ( self , scheme_name = None ) : if scheme_name is None : return self . __default_handler_cls for handler in self . __handlers_cls : if handler . scheme_specification ( ) . scheme_name ( ) == scheme_name : return handler
Return handler which scheme name matches the specified one
63
9
8,148
def open ( self , uri , * * kwargs ) : handler = self . handler ( uri . scheme ( ) ) if handler is None : raise WSchemeCollection . NoHandlerFound ( uri ) if uri . scheme ( ) is None : uri . component ( 'scheme' , handler . scheme_specification ( ) . scheme_name ( ) ) if handler . scheme_specification ( ) . is_compatible ( uri ) is False : raise WSchemeCollection . SchemeIncompatible ( uri ) return handler . create_handler ( uri , * * kwargs )
Return handler instance that matches the specified URI . WSchemeCollection . NoHandlerFound and WSchemeCollection . SchemeIncompatible may be raised .
130
30
8,149
def loadFile ( self , fileName ) : self . fileName = fileName self . qteWeb . load ( QtCore . QUrl ( fileName ) )
Load the URL fileName .
35
6
8,150
def render_to_response ( self , context , * * response_kwargs ) : context [ "ajax_form_id" ] = self . ajax_form_id # context["base_template"] = "towel_bootstrap/modal.html" return self . response_class ( request = self . request , template = self . get_template_names ( ) , context = context , * * response_kwargs )
Returns a response with a template rendered with the given context .
97
12
8,151
def to_python ( self , value , resource ) : if value is None : return self . _transform ( value ) if isinstance ( value , six . text_type ) : return self . _transform ( value ) if self . encoding is None and isinstance ( value , ( six . text_type , six . binary_type ) ) : return self . _transform ( value ) if self . encoding is not None and isinstance ( value , six . binary_type ) : return self . _transform ( value . decode ( self . encoding ) ) return self . _transform ( six . text_type ( value ) )
Converts to unicode if self . encoding ! = None otherwise returns input without attempting to decode
131
19
8,152
def to_python ( self , value , resource ) : if isinstance ( value , dict ) : d = { self . aliases . get ( k , k ) : self . to_python ( v , resource ) if isinstance ( v , ( dict , list ) ) else v for k , v in six . iteritems ( value ) } return type ( self . class_name , ( ) , d ) elif isinstance ( value , list ) : return [ self . to_python ( x , resource ) if isinstance ( x , ( dict , list ) ) else x for x in value ] else : return value
Dictionary to Python object
131
5
8,153
def to_value ( self , obj , resource , visited = set ( ) ) : if id ( obj ) in visited : raise ValueError ( 'Circular reference detected when attempting to serialize object' ) if isinstance ( obj , ( list , tuple , set ) ) : return [ self . to_value ( x , resource ) if hasattr ( x , '__dict__' ) else x for x in obj ] elif hasattr ( obj , '__dict__' ) : attrs = obj . __dict__ . copy ( ) for key in six . iterkeys ( obj . __dict__ ) : if key . startswith ( '_' ) : del attrs [ key ] return { self . reverse_aliases . get ( k , k ) : self . to_value ( v , resource ) if hasattr ( v , '__dict__' ) or isinstance ( v , ( list , tuple , set ) ) else v for k , v in six . iteritems ( attrs ) } else : return obj
Python object to dictionary
220
4
8,154
def hello_message ( self , invert_hello = False ) : if invert_hello is False : return self . __gouverneur_message hello_message = [ ] for i in range ( len ( self . __gouverneur_message ) - 1 , - 1 , - 1 ) : hello_message . append ( self . __gouverneur_message [ i ] ) return bytes ( hello_message )
Return message header .
92
4
8,155
def _message_address_parse ( self , message , invert_hello = False ) : message_header = self . hello_message ( invert_hello = invert_hello ) if message [ : len ( message_header ) ] != message_header : raise ValueError ( 'Invalid message header' ) message = message [ len ( message_header ) : ] message_parts = message . split ( WBeaconGouverneurMessenger . __message_splitter__ ) address = None port = None if len ( message_parts ) > 3 : raise ValueError ( 'Invalid message. Too many separators' ) elif len ( message_parts ) == 3 : address = WIPV4SocketInfo . parse_address ( message_parts [ 1 ] . decode ( 'ascii' ) ) port = WIPPort ( int ( message_parts [ 2 ] ) ) elif len ( message_parts ) == 2 and len ( message_parts [ 1 ] ) > 0 : address = WIPV4SocketInfo . parse_address ( message_parts [ 1 ] . decode ( 'ascii' ) ) return WIPV4SocketInfo ( address , port )
Read address from beacon message . If no address is specified then nullable WIPV4SocketInfo returns
253
21
8,156
def cipher ( self ) : #cipher = pyAES.new(*self.mode().aes_args(), **self.mode().aes_kwargs()) cipher = Cipher ( * self . mode ( ) . aes_args ( ) , * * self . mode ( ) . aes_kwargs ( ) ) return WAES . WAESCipher ( cipher )
Generate AES - cipher
81
5
8,157
def encrypt ( self , data ) : padding = self . mode ( ) . padding ( ) if padding is not None : data = padding . pad ( data , WAESMode . __data_padding_length__ ) return self . cipher ( ) . encrypt_block ( data )
Encrypt the given data with cipher that is got from AES . cipher call .
58
16
8,158
def decrypt ( self , data , decode = False ) : #result = self.cipher().decrypt(data) result = self . cipher ( ) . decrypt_block ( data ) padding = self . mode ( ) . padding ( ) if padding is not None : result = padding . reverse_pad ( result , WAESMode . __data_padding_length__ ) return result . decode ( ) if decode else result
Decrypt the given data with cipher that is got from AES . cipher call .
88
16
8,159
def thread_tracker_exception ( self , raised_exception ) : print ( 'Thread tracker execution was stopped by the exception. Exception: %s' % str ( raised_exception ) ) print ( 'Traceback:' ) print ( traceback . format_exc ( ) )
Method is called whenever an exception is raised during registering a event
62
12
8,160
def __store_record ( self , record ) : if isinstance ( record , WSimpleTrackerStorage . Record ) is False : raise TypeError ( 'Invalid record type was' ) limit = self . record_limit ( ) if limit is not None and len ( self . __registry ) >= limit : self . __registry . pop ( 0 ) self . __registry . append ( record )
Save record in a internal storage
84
6
8,161
def put_nested_val ( dict_obj , key_tuple , value ) : current_dict = dict_obj for key in key_tuple [ : - 1 ] : try : current_dict = current_dict [ key ] except KeyError : current_dict [ key ] = { } current_dict = current_dict [ key ] current_dict [ key_tuple [ - 1 ] ] = value
Put a value into nested dicts by the order of the given keys tuple .
90
16
8,162
def get_alternative_nested_val ( key_tuple , dict_obj ) : # print('key_tuple: {}'.format(key_tuple)) # print('dict_obj: {}'.format(dict_obj)) top_keys = key_tuple [ 0 ] if isinstance ( key_tuple [ 0 ] , ( list , tuple ) ) else [ key_tuple [ 0 ] ] for key in top_keys : try : if len ( key_tuple ) < 2 : return dict_obj [ key ] return get_alternative_nested_val ( key_tuple [ 1 : ] , dict_obj [ key ] ) except ( KeyError , TypeError , IndexError ) : pass raise KeyError
Return a value from nested dicts by any path in the given keys tuple .
162
16
8,163
def subdict_by_keys ( dict_obj , keys ) : return { k : dict_obj [ k ] for k in set ( keys ) . intersection ( dict_obj . keys ( ) ) }
Returns a sub - dict composed solely of the given keys .
44
12
8,164
def add_to_dict_val_set ( dict_obj , key , val ) : try : dict_obj [ key ] . add ( val ) except KeyError : dict_obj [ key ] = set ( [ val ] )
Adds the given val to the set mapped by the given key . If the key is missing from the dict the given mapping is added .
50
27
8,165
def add_many_to_dict_val_set ( dict_obj , key , val_list ) : try : dict_obj [ key ] . update ( val_list ) except KeyError : dict_obj [ key ] = set ( val_list )
Adds the given value list to the set mapped by the given key . If the key is missing from the dict the given mapping is added .
56
28
8,166
def add_many_to_dict_val_list ( dict_obj , key , val_list ) : try : dict_obj [ key ] . extend ( val_list ) except KeyError : dict_obj [ key ] = list ( val_list )
Adds the given value list to the list mapped by the given key . If the key is missing from the dict the given mapping is added .
56
28
8,167
def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )
Returns the keys that maps to the top n max values in the given dict .
59
16
8,168
def deep_merge_dict ( base , priority ) : if not isinstance ( base , dict ) or not isinstance ( priority , dict ) : return priority result = copy . deepcopy ( base ) for key in priority . keys ( ) : if key in base : result [ key ] = deep_merge_dict ( base [ key ] , priority [ key ] ) else : result [ key ] = priority [ key ] return result
Recursively merges the two given dicts into a single dict .
92
15
8,169
def norm_int_dict ( int_dict ) : norm_dict = int_dict . copy ( ) val_sum = sum ( norm_dict . values ( ) ) for key in norm_dict : norm_dict [ key ] = norm_dict [ key ] / val_sum return norm_dict
Normalizes values in the given dict with int values .
65
11
8,170
def sum_num_dicts ( dicts , normalize = False ) : sum_dict = { } for dicti in dicts : for key in dicti : sum_dict [ key ] = sum_dict . get ( key , 0 ) + dicti [ key ] if normalize : return norm_int_dict ( sum_dict ) return sum_dict
Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts .
78
26
8,171
def reverse_dict ( dict_obj ) : new_dict = { } for key in dict_obj : add_to_dict_val_set ( dict_obj = new_dict , key = dict_obj [ key ] , val = key ) for key in new_dict : new_dict [ key ] = sorted ( new_dict [ key ] , reverse = False ) return new_dict
Reverse a dict so each value in it maps to a sorted list of its keys .
85
19
8,172
def reverse_dict_partial ( dict_obj ) : new_dict = { } for key in dict_obj : new_dict [ dict_obj [ key ] ] = key return new_dict
Reverse a dict so each value in it maps to one of its keys .
42
17
8,173
def reverse_list_valued_dict ( dict_obj ) : new_dict = { } for key in dict_obj : for element in dict_obj [ key ] : new_dict [ element ] = key return new_dict
Reverse a list - valued dict so each element in a list maps to its key .
49
19
8,174
def flatten_dict ( dict_obj , separator = '.' , flatten_lists = False ) : reducer = _get_key_reducer ( separator ) flat = { } def _flatten_key_val ( key , val , parent ) : flat_key = reducer ( parent , key ) try : _flatten ( val , flat_key ) except TypeError : flat [ flat_key ] = val def _flatten ( d , parent = None ) : try : for key , val in d . items ( ) : _flatten_key_val ( key , val , parent ) except AttributeError : if isinstance ( d , ( str , bytes ) ) : raise TypeError for i , value in enumerate ( d ) : _flatten_key_val ( str ( i ) , value , parent ) _flatten ( dict_obj ) return flat
Flattens the given dict into a single - level dict with flattend keys .
191
17
8,175
def pprint_int_dict ( int_dict , indent = 4 , descending = False ) : sorted_tup = sorted ( int_dict . items ( ) , key = lambda x : x [ 1 ] ) if descending : sorted_tup . reverse ( ) print ( '{' ) for tup in sorted_tup : print ( '{}{}: {}' . format ( ' ' * indent , tup [ 0 ] , tup [ 1 ] ) ) print ( '}' )
Prints the given dict with int values in a nice way .
107
13
8,176
def key_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for key , value in key_value_nested_generator ( value ) : yield key , value else : yield key , value
Recursively iterate over key - value pairs of nested dictionaries .
66
15
8,177
def key_tuple_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for nested_key , value in key_tuple_value_nested_generator ( value ) : yield tuple ( [ key ] ) + nested_key , value else : yield tuple ( [ key ] ) , value
Recursively iterate over key - tuple - value pairs of nested dictionaries .
88
17
8,178
def register ( self ) : group = cfg . OptGroup ( self . group_name , title = "HNV (Hyper-V Network Virtualization) Options" ) self . _config . register_group ( group ) self . _config . register_opts ( self . _options , group = group )
Register the current options to the global ConfigOpts object .
66
12
8,179
def _language_exclusions ( stem : LanguageStemRange , exclusions : List [ ShExDocParser . LanguageExclusionContext ] ) -> None : for excl in exclusions : excl_langtag = LANGTAG ( excl . LANGTAG ( ) . getText ( ) [ 1 : ] ) stem . exclusions . append ( LanguageStem ( excl_langtag ) if excl . STEM_MARK ( ) else excl_langtag )
languageExclusion = - LANGTAG STEM_MARK?
102
13
8,180
def create_thumbnail ( self , image , geometry , upscale = True , crop = None , colorspace = 'RGB' ) : image = self . colorspace ( image , colorspace ) image = self . scale ( image , geometry , upscale , crop ) image = self . crop ( image , geometry , crop ) return image
This serves as a really basic example of a thumbnailing method . You may want to implement your own logic but this will work for simple cases .
68
30
8,181
def get_tokens ( self , * , payer_id , credit_card_token_id , start_date , end_date ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . GET_TOKENS . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "creditCardTokenInformation" : { "payerId" : payer_id , "creditCardTokenId" : credit_card_token_id , "startDate" : start_date . strftime ( '%Y-%m-%dT%H:%M:%S' ) , "endDate" : end_date . strftime ( '%Y-%m-%dT%H:%M:%S' ) } , "test" : self . client . is_test } return self . client . _post ( self . url , json = payload )
With this functionality you can query previously the Credit Cards Token .
224
12
8,182
def remove_token ( self , * , payer_id , credit_card_token_id ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . REMOVE_TOKEN . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "removeCreditCardToken" : { "payerId" : payer_id , "creditCardTokenId" : credit_card_token_id } , "test" : self . client . is_test } return self . client . _post ( self . url , json = payload )
This feature allows you to delete a tokenized credit card register .
149
13
8,183
def set_file_path ( self , filePath ) : if filePath is not None : assert isinstance ( filePath , basestring ) , "filePath must be None or string" filePath = str ( filePath ) self . __filePath = filePath
Set the file path that needs to be locked .
57
10
8,184
def set_lock_pass ( self , lockPass ) : assert isinstance ( lockPass , basestring ) , "lockPass must be string" lockPass = str ( lockPass ) assert '\n' not in lockPass , "lockPass must be not contain a new line" self . __lockPass = lockPass
Set the locking pass
69
4
8,185
def set_lock_path ( self , lockPath ) : if lockPath is not None : assert isinstance ( lockPath , basestring ) , "lockPath must be None or string" lockPath = str ( lockPath ) self . __lockPath = lockPath if self . __lockPath is None : if self . __filePath is None : self . __lockPath = os . path . join ( os . getcwd ( ) , ".lock" ) else : self . __lockPath = os . path . join ( os . path . dirname ( self . __filePath ) , '.lock' )
Set the managing lock file path .
131
7
8,186
def set_timeout ( self , timeout ) : try : timeout = float ( timeout ) assert timeout >= 0 assert timeout >= self . __wait except : raise Exception ( 'timeout must be a positive number bigger than wait' ) self . __timeout = timeout
set the timeout limit .
52
5
8,187
def set_wait ( self , wait ) : try : wait = float ( wait ) assert wait >= 0 except : raise Exception ( 'wait must be a positive number' ) self . __wait = wait
set the waiting time .
42
5
8,188
def set_dead_lock ( self , deadLock ) : try : deadLock = float ( deadLock ) assert deadLock >= 0 except : raise Exception ( 'deadLock must be a positive number' ) self . __deadLock = deadLock
Set the dead lock time .
51
6
8,189
def release_lock ( self , verbose = VERBOSE , raiseError = RAISE_ERROR ) : if not os . path . isfile ( self . __lockPath ) : released = True code = 0 else : try : with open ( self . __lockPath , 'rb' ) as fd : lock = fd . readlines ( ) except Exception as err : code = Exception ( "Unable to read release lock file '%s' (%s)" % ( self . __lockPath , str ( err ) ) ) released = False if verbose : print ( str ( code ) ) if raiseError : raise code else : if not len ( lock ) : code = 1 released = True elif lock [ 0 ] . rstrip ( ) == self . __lockPass . encode ( ) : try : with open ( self . __lockPath , 'wb' ) as f : #f.write( ''.encode('utf-8') ) f . write ( '' . encode ( ) ) f . flush ( ) os . fsync ( f . fileno ( ) ) except Exception as err : released = False code = Exception ( "Unable to write release lock file '%s' (%s)" % ( self . __lockPath , str ( err ) ) ) if verbose : print ( str ( code ) ) if raiseError : raise code else : released = True code = 2 else : code = 4 released = False # close file descriptor if lock is released and descriptor is not None if released and self . __fd is not None : try : if not self . __fd . closed : self . __fd . flush ( ) os . fsync ( self . __fd . fileno ( ) ) self . __fd . close ( ) except Exception as err : code = Exception ( "Unable to close file descriptor of locked file '%s' (%s)" % ( self . __filePath , str ( err ) ) ) if verbose : print ( str ( code ) ) if raiseError : raise code else : code = 3 # return return released , code
Release the lock when set and close file descriptor if opened .
438
12
8,190
def import_bert ( self , filename , * * kwargs ) : timestep = kwargs . get ( 'timestep' , None ) if 'timestep' in kwargs : del ( kwargs [ 'timestep' ] ) self . logger . info ( 'Unified data format (BERT/pyGIMLi) file import' ) with LogDataChanges ( self , filter_action = 'import' , filter_query = os . path . basename ( filename ) ) : data , electrodes , topography = reda_bert_import . import_ohm ( filename , * * kwargs ) if timestep is not None : data [ 'timestep' ] = timestep self . _add_to_container ( data ) self . electrode_positions = electrodes # See issue #22 if kwargs . get ( 'verbose' , False ) : print ( 'Summary:' ) self . _describe_data ( data )
BERT . ohm file import
213
7
8,191
def to_ip ( self ) : if 'chargeability' in self . data . columns : tdip = reda . TDIP ( data = self . data ) else : raise Exception ( 'Missing column "chargeability"' ) return tdip
Return of copy of the data inside a TDIP container
51
11
8,192
def sub_filter ( self , subset , filter , inplace = True ) : # build the full query full_query = '' . join ( ( 'not (' , subset , ') or not (' , filter , ')' ) ) with LogDataChanges ( self , filter_action = 'filter' , filter_query = filter ) : result = self . data . query ( full_query , inplace = inplace ) return result
Apply a filter to subset of the data
91
8
8,193
def filter ( self , query , inplace = True ) : with LogDataChanges ( self , filter_action = 'filter' , filter_query = query ) : result = self . data . query ( 'not ({0})' . format ( query ) , inplace = inplace , ) return result
Use a query statement to filter data . Note that you specify the data to be removed!
64
18
8,194
def compute_K_analytical ( self , spacing ) : K = redaK . compute_K_analytical ( self . data , spacing = spacing ) self . data = redaK . apply_K ( self . data , K ) redafixK . fix_sign_with_K ( self . data )
Compute geometrical factors over the homogeneous half - space with a constant electrode spacing
69
18
8,195
def pseudosection ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : fig , ax , cb = PS . plot_pseudosection_type2 ( self . data , column = column , log10 = log10 , * * kwargs ) if filename is not None : fig . savefig ( filename , dpi = 300 ) return fig , ax , cb
Plot a pseudosection of the given column . Note that this function only works with dipole - dipole data at the moment .
93
27
8,196
def histogram ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : return_dict = HS . plot_histograms ( self . data , column ) if filename is not None : return_dict [ 'all' ] . savefig ( filename , dpi = 300 ) return return_dict
Plot a histogram of one data column
74
8
8,197
def delete_measurements ( self , row_or_rows ) : self . data . drop ( self . data . index [ row_or_rows ] , inplace = True ) self . data = self . data . reset_index ( )
Delete one or more measurements by index of the DataFrame .
53
12
8,198
def get_image ( self , source ) : buf = StringIO ( source . read ( ) ) return Image . open ( buf )
Given a file - like object loads it up into a PIL . Image object and returns it .
28
20
8,199
def is_valid_image ( self , raw_data ) : buf = StringIO ( raw_data ) try : trial_image = Image . open ( buf ) trial_image . verify ( ) except Exception : # TODO: Get more specific with this exception handling. return False return True
Checks if the supplied raw data is valid image data .
61
12