idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
11,200 | def get_schema ( self , schema_id ) : res = requests . get ( self . _url ( '/schemas/ids/{}' , schema_id ) ) raise_if_failed ( res ) return json . loads ( res . json ( ) [ 'schema' ] ) | Retrieves the schema with the given schema_id from the registry and returns it as a dict . | 65 | 21 |
11,201 | def get_subjects ( self ) : res = requests . get ( self . _url ( '/subjects' ) ) raise_if_failed ( res ) return res . json ( ) | Returns the list of subject names present in the schema registry . | 40 | 12 |
11,202 | def get_subject_version_ids ( self , subject ) : res = requests . get ( self . _url ( '/subjects/{}/versions' , subject ) ) raise_if_failed ( res ) return res . json ( ) | Return the list of schema version ids which have been registered under the given subject . | 52 | 17 |
11,203 | def get_subject_version ( self , subject , version_id ) : res = requests . get ( self . _url ( '/subjects/{}/versions/{}' , subject , version_id ) ) raise_if_failed ( res ) return json . loads ( res . json ( ) [ 'schema' ] ) | Retrieves the schema registered under the given subject with the given version id . Returns the schema as a dict . | 72 | 23 |
11,204 | def schema_is_registered_for_subject ( self , subject , schema ) : data = json . dumps ( { 'schema' : json . dumps ( schema ) } ) res = requests . post ( self . _url ( '/subjects/{}' , subject ) , data = data , headers = HEADERS ) if res . status_code == 404 : return False raise_if_failed ( res ) return True | Returns True if the given schema is already registered under the given subject . | 90 | 14 |
11,205 | def get_global_compatibility_level ( self ) : res = requests . get ( self . _url ( '/config' ) , headers = HEADERS ) raise_if_failed ( res ) return res . json ( ) [ 'compatibility' ] | Gets the global compatibility level . | 54 | 7 |
11,206 | def set_subject_compatibility_level ( self , subject , level ) : res = requests . put ( self . _url ( '/config/{}' , subject ) , data = json . dumps ( { 'compatibility' : level } ) , headers = HEADERS ) raise_if_failed ( res ) | Sets the compatibility level for the given subject . | 67 | 10 |
11,207 | def get_subject_compatibility_level ( self , subject ) : res = requests . get ( self . _url ( '/config/{}' , subject ) , headers = HEADERS ) raise_if_failed ( res ) return res . json ( ) [ 'compatibility' ] | Gets the compatibility level for the given subject . | 61 | 10 |
11,208 | def from_api ( cls , api , * * kwargs ) : if not cls . _api_attrs : raise NotImplementedError ( ) def resolve_attribute_type ( attr_type ) : # resolve arrays of types down to base type while isinstance ( attr_type , list ) : attr_type = attr_type [ 0 ] # attribute type 'self' resolves to current class if attr_type == 'self' : attr_type = cls # attribute type 'date' is a unix timestamp if attr_type == 'date' : attr_type = datetime . datetime . fromtimestamp # string attributes should use unicode literals if attr_type is str : attr_type = unicode # if attribute type is an APIObject, use the from_api factory method and pass the `api` argument if hasattr ( attr_type , 'from_api' ) : return lambda * * kw : attr_type . from_api ( api , * * kw ) return attr_type def instantiate_attr ( attr_value , attr_type ) : if isinstance ( attr_value , dict ) : return attr_type ( * * attr_value ) return attr_type ( attr_value ) def instantiate_array ( attr_values , attr_type ) : func = instantiate_attr if isinstance ( attr_values [ 0 ] , list ) : func = instantiate_array return [ func ( val , attr_type ) for val in attr_values ] def instantiate ( attr_value , attr_type ) : if isinstance ( attr_value , list ) : return instantiate_array ( attr_value , attr_type ) return instantiate_attr ( attr_value , attr_type ) instance = cls ( api ) for attr_name , attr_type , attr_default in cls . _api_attrs : # grab the current attribute value attr_value = kwargs . get ( attr_name , attr_default ) # default of TypeError means a required attribute, raise Exception if attr_value is TypeError : raise TypeError ( '{} requires argument {}' . format ( cls . __name__ , attr_name ) ) attr_type = resolve_attribute_type ( attr_type ) # if value has been provided from API, instantiate it using `attr_type` if attr_value != attr_default : attr_value = instantiate ( attr_value , attr_type ) # rename the 'from' variable, reserved word if attr_name == 'from' : attr_name = 'froom' # and finally set the attribute value on the instance setattr ( instance , attr_name , attr_value ) return instance | Parses a payload from the API guided by _api_attrs | 636 | 15 |
11,209 | def api_method ( self ) : if not self . _api_method : raise NotImplementedError ( ) return getattr ( self . api , self . _api_method ) | Returns the api method to send the current API Object type | 40 | 11 |
11,210 | def api_payload ( self ) : if not self . _api_payload : raise NotImplementedError ( ) payload = { } for attr_name in self . _api_payload : value = getattr ( self , attr_name , None ) if value is not None : payload [ attr_name ] = value return payload | Generates a payload ready for submission to the API guided by _api_payload | 76 | 17 |
11,211 | def send ( self , * * kwargs ) : payload = self . api_payload ( ) payload . update ( * * kwargs ) return self . api_method ( ) ( * * payload ) | Combines api_payload and api_method to submit the current object to the API | 45 | 18 |
11,212 | def parse_addr ( addr , * , proto = None , host = None ) : port = None if isinstance ( addr , Address ) : return addr elif isinstance ( addr , str ) : if addr . startswith ( 'http://' ) : proto , addr = 'http' , addr [ 7 : ] if addr . startswith ( 'udp://' ) : proto , addr = 'udp' , addr [ 6 : ] elif addr . startswith ( 'tcp://' ) : proto , addr = 'tcp' , addr [ 6 : ] elif addr . startswith ( 'unix://' ) : proto , addr = 'unix' , addr [ 7 : ] a , _ , b = addr . partition ( ':' ) host = a or host port = b or port elif isinstance ( addr , ( tuple , list ) ) : # list is not good a , b = addr host = a or host port = b or port elif isinstance ( addr , int ) : port = addr else : raise ValueError ( 'bad value' ) if port is not None : port = int ( port ) return Address ( proto , host , port ) | Parses an address | 256 | 5 |
11,213 | def applyRule ( self ) : widget = self . queryBuilderWidget ( ) if ( not widget ) : return rule = widget . findRule ( self . uiTermDDL . currentText ( ) ) self . setCurrentRule ( rule ) | Applies the rule from the builder system to this line edit . | 51 | 13 |
11,214 | def updateEditor ( self ) : # assignt the rule operators to the choice list rule = self . currentRule ( ) operator = self . currentOperator ( ) widget = self . uiWidgetAREA . widget ( ) editorType = None text = '' if ( rule ) : editorType = rule . editorType ( operator ) # no change in types if ( widget and editorType and type ( widget ) == editorType ) : return elif ( widget ) : if ( type ( widget ) != QWidget ) : text = widget . text ( ) widget . setParent ( None ) widget . deleteLater ( ) self . uiWidgetAREA . setWidget ( None ) # create the new editor if ( editorType ) : widget = editorType ( self ) if ( isinstance ( widget , QLineEdit ) ) : terms = rule . completionTerms ( ) if ( not terms ) : qwidget = self . queryBuilderWidget ( ) if ( qwidget ) : terms = qwidget . completionTerms ( ) if ( terms ) : widget . setCompleter ( XQueryCompleter ( terms , widget ) ) self . uiWidgetAREA . setWidget ( widget ) if ( type ( widget ) != QWidget ) : widget . setText ( text ) | Updates the editor based on the current selection . | 267 | 10 |
11,215 | def emitCurrentChanged ( self ) : if ( not self . signalsBlocked ( ) ) : schema = self . currentSchema ( ) self . currentSchemaChanged . emit ( schema ) if ( schema ) : self . currentTableChanged . emit ( schema . model ( ) ) else : self . currentTableChanged . emit ( None ) | Emits the current schema changed signal for this combobox provided \ the signals aren t blocked . | 71 | 20 |
11,216 | def save ( self ) : if ( not self . updateShortcut ( ) ) : return False for i in range ( self . uiActionTREE . topLevelItemCount ( ) ) : item = self . uiActionTREE . topLevelItem ( i ) action = item . action ( ) action . setShortcut ( QKeySequence ( item . text ( 1 ) ) ) return True | Saves the current settings for the actions in the list and exits the widget . | 85 | 16 |
11,217 | def showPopup ( self ) : as_dialog = QApplication . keyboardModifiers ( ) anchor = self . defaultAnchor ( ) if anchor : self . popupWidget ( ) . setAnchor ( anchor ) else : anchor = self . popupWidget ( ) . anchor ( ) if ( anchor & ( XPopupWidget . Anchor . BottomLeft | XPopupWidget . Anchor . BottomCenter | XPopupWidget . Anchor . BottomRight ) ) : pos = QPoint ( self . width ( ) / 2 , 0 ) else : pos = QPoint ( self . width ( ) / 2 , self . height ( ) ) pos = self . mapToGlobal ( pos ) if not self . signalsBlocked ( ) : self . popupAboutToShow . emit ( ) self . _popupWidget . popup ( pos ) if as_dialog : self . _popupWidget . setCurrentMode ( XPopupWidget . Mode . Dialog ) | Shows the popup for this button . | 206 | 8 |
11,218 | def togglePopup ( self ) : if not self . _popupWidget . isVisible ( ) : self . showPopup ( ) elif self . _popupWidget . currentMode ( ) != self . _popupWidget . Mode . Dialog : self . _popupWidget . close ( ) | Toggles whether or not the popup is visible . | 66 | 10 |
11,219 | def form_field ( self ) : label = unicode ( self ) defaults = dict ( required = False , label = label , widget = self . widget ) defaults . update ( self . extra ) return self . field_class ( * * defaults ) | Returns appropriate form field . | 52 | 5 |
11,220 | def attr_name ( self ) : return self . schema . name if self . schema else self . field . name | Returns attribute name for this facet | 25 | 6 |
11,221 | def get_field_and_lookup ( self , name ) : name = self . get_queryset ( ) . model . _meta . get_field ( name ) lookup_prefix = '' return name , lookup_prefix | Returns field instance and lookup prefix for given attribute name . Can be overloaded in subclasses to provide filtering across multiple models . | 49 | 24 |
11,222 | def StreamMetrics ( self , request_iterator , context ) : LOG . debug ( "StreamMetrics called" ) # set up arguments collect_args = ( next ( request_iterator ) ) max_metrics_buffer = 0 max_collect_duration = 0 cfg = Metric ( pb = collect_args . Metrics_Arg . metrics [ 0 ] ) try : max_metrics_buffer = int ( cfg . config [ "max-metrics-buffer" ] ) except Exception as ex : LOG . debug ( "Unable to get schedule parameters: {}" . format ( ex ) ) try : max_collect_duration = int ( cfg . config [ "max-collect-duration" ] ) except Exception as ex : LOG . debug ( "Unable to get schedule parameters: {}" . format ( ex ) ) if max_metrics_buffer > 0 : self . max_metrics_buffer = max_metrics_buffer if max_collect_duration > 0 : self . max_collect_duration = max_collect_duration # start collection thread thread = threading . Thread ( target = self . _stream_wrapper , args = ( collect_args , ) , ) thread . daemon = True thread . start ( ) # stream metrics metrics = [ ] metrics_to_stream = [ ] stream_timeout = self . max_collect_duration while context . is_active ( ) : try : # wait for metrics until timeout is reached t_start = time . time ( ) metrics = self . metrics_queue . get ( block = True , timeout = stream_timeout ) elapsed = round ( time . time ( ) - t_start ) stream_timeout -= elapsed except queue . Empty : LOG . debug ( "Max collect duration exceeded. Streaming {} metrics" . format ( len ( metrics_to_stream ) ) ) metrics_col = CollectReply ( Metrics_Reply = MetricsReply ( metrics = [ m . pb for m in metrics_to_stream ] ) ) metrics_to_stream = [ ] stream_timeout = self . max_collect_duration yield metrics_col else : for metric in metrics : metrics_to_stream . append ( metric ) if len ( metrics_to_stream ) == self . max_metrics_buffer : LOG . debug ( "Max metrics buffer reached. Streaming {} metrics" . format ( len ( metrics_to_stream ) ) ) metrics_col = CollectReply ( Metrics_Reply = MetricsReply ( metrics = [ m . pb for m in metrics_to_stream ] ) ) metrics_to_stream = [ ] stream_timeout = self . max_collect_duration yield metrics_col # stream metrics if max_metrics_buffer is 0 or enough metrics has been collected if self . max_metrics_buffer == 0 : LOG . debug ( "Max metrics buffer set to 0. Streaming {} metrics" . format ( len ( metrics_to_stream ) ) ) metrics_col = CollectReply ( Metrics_Reply = MetricsReply ( metrics = [ m . pb for m in metrics_to_stream ] ) ) metrics_to_stream = [ ] stream_timeout = self . max_collect_duration yield metrics_col # sent notification if stream has been stopped self . done_queue . put ( True ) | Dispatches metrics streamed by collector | 702 | 7 |
11,223 | def GetMetricTypes ( self , request , context ) : LOG . debug ( "GetMetricTypes called" ) try : metrics = self . plugin . update_catalog ( ConfigMap ( pb = request . config ) ) return MetricsReply ( metrics = [ m . pb for m in metrics ] ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return MetricsReply ( metrics = [ ] , error = msg ) | Dispatches the request to the plugins update_catalog method | 115 | 13 |
11,224 | def command_publish ( self , command , * * kwargs ) : mqttc = mqtt . Client ( ) mqttc . connect ( command [ 'host' ] , port = int ( command [ 'port' ] ) ) mqttc . loop_start ( ) try : mqttc . publish ( command [ 'endpoint' ] , command [ 'payload' ] ) finally : mqttc . loop_stop ( force = False ) | Publish a MQTT message | 105 | 7 |
11,225 | def command_subscribe ( self , command , * * kwargs ) : topic = command [ 'topic' ] encoding = command . get ( 'encoding' , 'utf-8' ) name = command [ 'name' ] if not hasattr ( self . engine , '_mqtt' ) : self . engine . _mqtt = { } self . engine . variables [ name ] = [ ] def on_message ( client , userdata , msg ) : userdata . append ( msg . payload . decode ( encoding ) ) self . engine . _mqtt [ name ] = client = mqtt . Client ( userdata = self . engine . variables [ name ] ) client . on_message = on_message client . connect ( command [ 'host' ] , port = int ( command [ 'port' ] ) ) client . subscribe ( topic ) client . loop_start ( ) self . engine . register_teardown_callback ( client . loop_stop ) | Subscribe to a topic or list of topics | 211 | 8 |
11,226 | def get_data ( param , data ) : try : for ( _ , selected_time_entry ) in data : loc_data = selected_time_entry [ 'location' ] if param not in loc_data : continue if param == 'precipitation' : new_state = loc_data [ param ] [ '@value' ] elif param == 'symbol' : new_state = int ( float ( loc_data [ param ] [ '@number' ] ) ) elif param in ( 'temperature' , 'pressure' , 'humidity' , 'dewpointTemperature' ) : new_state = round ( float ( loc_data [ param ] [ '@value' ] ) , 1 ) elif param in ( 'windSpeed' , 'windGust' ) : new_state = round ( float ( loc_data [ param ] [ '@mps' ] ) * 3.6 , 1 ) elif param == 'windDirection' : new_state = round ( float ( loc_data [ param ] [ '@deg' ] ) , 1 ) elif param in ( 'fog' , 'cloudiness' , 'lowClouds' , 'mediumClouds' , 'highClouds' ) : new_state = round ( float ( loc_data [ param ] [ '@percent' ] ) , 1 ) return new_state except ( ValueError , IndexError , KeyError ) : return None | Retrieve weather parameter . | 312 | 5 |
11,227 | def parse_datetime ( dt_str ) : date_format = "%Y-%m-%dT%H:%M:%S %z" dt_str = dt_str . replace ( "Z" , " +0000" ) return datetime . datetime . strptime ( dt_str , date_format ) | Parse datetime . | 77 | 5 |
11,228 | async def fetching_data ( self , * _ ) : try : with async_timeout . timeout ( 10 ) : resp = await self . _websession . get ( self . _api_url , params = self . _urlparams ) if resp . status != 200 : _LOGGER . error ( '%s returned %s' , self . _api_url , resp . status ) return False text = await resp . text ( ) except ( asyncio . TimeoutError , aiohttp . ClientError ) as err : _LOGGER . error ( '%s returned %s' , self . _api_url , err ) return False try : self . data = xmltodict . parse ( text ) [ 'weatherdata' ] except ( ExpatError , IndexError ) as err : _LOGGER . error ( '%s returned %s' , resp . url , err ) return False return True | Get the latest data from met . no . | 197 | 9 |
11,229 | def get_forecast ( self , time_zone ) : if self . data is None : return [ ] now = datetime . datetime . now ( time_zone ) . replace ( hour = 12 , minute = 0 , second = 0 , microsecond = 0 ) times = [ now + datetime . timedelta ( days = k ) for k in range ( 1 , 6 ) ] return [ self . get_weather ( _time ) for _time in times ] | Get the forecast weather data from met . no . | 99 | 10 |
11,230 | def get_weather ( self , time , max_hour = 6 ) : if self . data is None : return { } ordered_entries = [ ] for time_entry in self . data [ 'product' ] [ 'time' ] : valid_from = parse_datetime ( time_entry [ '@from' ] ) valid_to = parse_datetime ( time_entry [ '@to' ] ) if time > valid_to : # Has already passed. Never select this. continue average_dist = ( abs ( ( valid_to - time ) . total_seconds ( ) ) + abs ( ( valid_from - time ) . total_seconds ( ) ) ) if average_dist > max_hour * 3600 : continue ordered_entries . append ( ( average_dist , time_entry ) ) if not ordered_entries : return { } ordered_entries . sort ( key = lambda item : item [ 0 ] ) res = dict ( ) res [ 'datetime' ] = time res [ 'temperature' ] = get_data ( 'temperature' , ordered_entries ) res [ 'condition' ] = CONDITIONS . get ( get_data ( 'symbol' , ordered_entries ) ) res [ 'pressure' ] = get_data ( 'pressure' , ordered_entries ) res [ 'humidity' ] = get_data ( 'humidity' , ordered_entries ) res [ 'wind_speed' ] = get_data ( 'windSpeed' , ordered_entries ) res [ 'wind_bearing' ] = get_data ( 'windDirection' , ordered_entries ) return res | Get the current weather data from met . no . | 358 | 10 |
11,231 | def prepare_node ( data ) : if not data : return None , { } if isinstance ( data , str ) : return data , { } # from /v1/health/service/<service> if all ( field in data for field in ( "Node" , "Service" , "Checks" ) ) : return data [ "Node" ] [ "Node" ] , data [ "Node" ] result = { } if "ID" in data : result [ "Node" ] = data [ "ID" ] for k in ( "Datacenter" , "Node" , "Address" , "TaggedAddresses" , "Service" , "Check" , "Checks" ) : if k in data : result [ k ] = data [ k ] if list ( result ) == [ "Node" ] : return result [ "Node" ] , { } return result . get ( "Node" ) , result | Prepare node for catalog endpoint | 198 | 6 |
11,232 | def prepare_service ( data ) : if not data : return None , { } if isinstance ( data , str ) : return data , { } # from /v1/health/service/<service> if all ( field in data for field in ( "Node" , "Service" , "Checks" ) ) : return data [ "Service" ] [ "ID" ] , data [ "Service" ] # from /v1/health/checks/<service> # from /v1/health/node/<node> # from /v1/health/state/<state> # from /v1/catalog/service/<service> if all ( field in data for field in ( "ServiceName" , "ServiceID" ) ) : return data [ "ServiceID" ] , { "ID" : data [ "ServiceID" ] , "Service" : data [ "ServiceName" ] , "Tags" : data . get ( "ServiceTags" ) , "Address" : data . get ( "ServiceAddress" ) , "Port" : data . get ( "ServicePort" ) , } if list ( data ) == [ "ID" ] : return data [ "ID" ] , { } result = { } if "Name" in data : result [ "Service" ] = data [ "Name" ] for k in ( "Service" , "ID" , "Tags" , "Address" , "Port" ) : if k in data : result [ k ] = data [ k ] return result . get ( "ID" ) , result | Prepare service for catalog endpoint | 336 | 6 |
11,233 | def prepare_check ( data ) : if not data : return None , { } if isinstance ( data , str ) : return data , { } result = { } if "ID" in data : result [ "CheckID" ] = data [ "ID" ] for k in ( "Node" , "CheckID" , "Name" , "Notes" , "Status" , "ServiceID" ) : if k in data : result [ k ] = data [ k ] if list ( result ) == [ "CheckID" ] : return result [ "CheckID" ] , { } return result . get ( "CheckID" ) , result | Prepare check for catalog endpoint | 137 | 6 |
11,234 | def optimize_no ( self ) : self . optimization = 0 self . relax = False self . gc_sections = False self . ffunction_sections = False self . fdata_sections = False self . fno_inline_small_functions = False | all options set to default | 55 | 5 |
11,235 | def init ( self ) : # import any compiled resource modules if not self . _initialized : self . _initialized = True wrap = projexui . qt . QT_WRAPPER . lower ( ) ignore = lambda x : not x . split ( '.' ) [ - 1 ] . startswith ( wrap ) projex . importmodules ( self . plugins ( ) , ignore = ignore ) | Initializes the plugins for this resource manager . | 86 | 9 |
11,236 | def policies ( self ) : policies = [ self . _pb . integer_policy , self . _pb . float_policy , self . _pb . string_policy , self . _pb . bool_policy ] key_types = [ "integer" , "float" , "string" , "bool" ] return zip ( key_types , policies ) | Return list of policies zipped with their respective data type | 75 | 11 |
11,237 | def add_measurement ( measurement ) : global _buffer_size if not _enabled : LOGGER . debug ( 'Discarding measurement for %s while not enabled' , measurement . database ) return if _stopping : LOGGER . warning ( 'Discarding measurement for %s while stopping' , measurement . database ) return if _buffer_size > _max_buffer_size : LOGGER . warning ( 'Discarding measurement due to buffer size limit' ) return if not measurement . fields : raise ValueError ( 'Measurement does not contain a field' ) if measurement . database not in _measurements : _measurements [ measurement . database ] = [ ] value = measurement . marshall ( ) _measurements [ measurement . database ] . append ( value ) # Ensure that len(measurements) < _trigger_size are written if not _timeout : if ( _batch_future and _batch_future . done ( ) ) or not _batch_future : _start_timeout ( ) # Check to see if the batch should be triggered _buffer_size = _pending_measurements ( ) if _buffer_size >= _trigger_size : _trigger_batch_write ( ) | Add measurement data to the submission buffer for eventual writing to InfluxDB . | 256 | 15 |
11,238 | def flush ( ) : flush_future = concurrent . Future ( ) if _batch_future and not _batch_future . done ( ) : LOGGER . debug ( 'Flush waiting on incomplete _batch_future' ) _flush_wait ( flush_future , _batch_future ) else : LOGGER . info ( 'Flushing buffer with %i measurements to InfluxDB' , _pending_measurements ( ) ) _flush_wait ( flush_future , _write_measurements ( ) ) return flush_future | Flush all pending measurements to InfluxDB . This will ensure that all measurements that are in the buffer for any database are written . If the requests fail it will continue to try and submit the metrics until they are successfully written . | 114 | 46 |
11,239 | def set_auth_credentials ( username , password ) : global _credentials , _dirty LOGGER . debug ( 'Setting authentication credentials' ) _credentials = username , password _dirty = True | Override the default authentication credentials obtained from the environment variable configuration . | 45 | 12 |
11,240 | def set_base_url ( url ) : global _base_url , _dirty LOGGER . debug ( 'Setting base URL to %s' , url ) _base_url = url _dirty = True | Override the default base URL value created from the environment variable configuration . | 44 | 13 |
11,241 | def set_max_clients ( limit ) : global _dirty , _max_clients LOGGER . debug ( 'Setting maximum client limit to %i' , limit ) _dirty = True _max_clients = limit | Set the maximum number of simultaneous batch submission that can execute in parallel . | 48 | 14 |
11,242 | def set_sample_probability ( probability ) : global _sample_probability if not 0.0 <= probability <= 1.0 : raise ValueError ( 'Invalid probability value' ) LOGGER . debug ( 'Setting sample probability to %.2f' , probability ) _sample_probability = float ( probability ) | Set the probability that a batch will be submitted to the InfluxDB server . This should be a value that is greater than or equal to 0 and less than or equal to 1 . 0 . A value of 0 . 25 would represent a probability of 25% that a batch would be written to InfluxDB . | 70 | 63 |
11,243 | def set_timeout ( milliseconds ) : global _timeout , _timeout_interval LOGGER . debug ( 'Setting batch wait timeout to %i ms' , milliseconds ) _timeout_interval = milliseconds _maybe_stop_timeout ( ) _timeout = ioloop . IOLoop . current ( ) . add_timeout ( milliseconds , _on_timeout ) | Override the maximum duration to wait for submitting measurements to InfluxDB . | 76 | 14 |
11,244 | def _create_http_client ( ) : global _http_client defaults = { 'user_agent' : USER_AGENT } auth_username , auth_password = _credentials if auth_username and auth_password : defaults [ 'auth_username' ] = auth_username defaults [ 'auth_password' ] = auth_password _http_client = httpclient . AsyncHTTPClient ( force_instance = True , defaults = defaults , max_clients = _max_clients ) | Create the HTTP client with authentication credentials if required . | 109 | 10 |
11,245 | def _flush_wait ( flush_future , write_future ) : if write_future . done ( ) : if not _pending_measurements ( ) : flush_future . set_result ( True ) return else : write_future = _write_measurements ( ) ioloop . IOLoop . current ( ) . add_timeout ( ioloop . IOLoop . current ( ) . time ( ) + 0.25 , _flush_wait , flush_future , write_future ) | Pause briefly allowing any pending metric writes to complete before shutting down . | 110 | 13 |
11,246 | def _futures_wait ( wait_future , futures ) : global _buffer_size , _writing remaining = [ ] for ( future , batch , database , measurements ) in futures : # If the future hasn't completed, add it to the remaining stack if not future . done ( ) : remaining . append ( ( future , batch , database , measurements ) ) continue # Get the result of the HTTP request, processing any errors error = future . exception ( ) if isinstance ( error , httpclient . HTTPError ) : if error . code == 400 : _write_error_batch ( batch , database , measurements ) elif error . code >= 500 : _on_5xx_error ( batch , error , database , measurements ) else : LOGGER . error ( 'Error submitting %s batch %s to InfluxDB (%s): ' '%s' , database , batch , error . code , error . response . body ) elif isinstance ( error , ( TimeoutError , OSError , socket . error , select . error , ssl . socket_error ) ) : _on_5xx_error ( batch , error , database , measurements ) # If there are futures that remain, try again in 100ms. if remaining : return ioloop . IOLoop . current ( ) . add_timeout ( ioloop . IOLoop . current ( ) . time ( ) + 0.1 , _futures_wait , wait_future , remaining ) else : # Start the next timeout or trigger the next batch _buffer_size = _pending_measurements ( ) LOGGER . debug ( 'Batch submitted, %i measurements remain' , _buffer_size ) if _buffer_size >= _trigger_size : ioloop . IOLoop . current ( ) . add_callback ( _trigger_batch_write ) elif _buffer_size : _start_timeout ( ) _writing = False wait_future . set_result ( True ) | Waits for all futures to be completed . If the futures are not done wait 100ms and then invoke itself via the ioloop and check again . If they are done set a result on wait_future indicating the list of futures are done . | 420 | 50 |
11,247 | def _maybe_stop_timeout ( ) : global _timeout if _timeout is not None : LOGGER . debug ( 'Removing the pending timeout (%r)' , _timeout ) ioloop . IOLoop . current ( ) . remove_timeout ( _timeout ) _timeout = None | If there is a pending timeout remove it from the IOLoop and set the _timeout global to None . | 61 | 22 |
11,248 | def _maybe_warn_about_buffer_size ( ) : global _last_warning if not _last_warning : _last_warning = time . time ( ) if _buffer_size > _warn_threshold and ( time . time ( ) - _last_warning ) > 120 : LOGGER . warning ( 'InfluxDB measurement buffer has %i entries' , _buffer_size ) | Check the buffer size and issue a warning if it s too large and a warning has not been issued for more than 60 seconds . | 85 | 26 |
11,249 | def _on_5xx_error ( batch , error , database , measurements ) : LOGGER . info ( 'Appending %s measurements to stack due to batch %s %r' , database , batch , error ) _measurements [ database ] = _measurements [ database ] + measurements | Handle a batch submission error logging the problem and adding the measurements back to the stack . | 63 | 17 |
11,250 | def _on_timeout ( ) : global _buffer_size LOGGER . debug ( 'No metrics submitted in the last %.2f seconds' , _timeout_interval / 1000.0 ) _buffer_size = _pending_measurements ( ) if _buffer_size : return _trigger_batch_write ( ) _start_timeout ( ) | Invoked periodically to ensure that metrics that have been collected are submitted to InfluxDB . | 77 | 18 |
11,251 | def _sample_batch ( ) : if _sample_probability == 1.0 or random . random ( ) < _sample_probability : return True # Pop off all the metrics for the batch for database in _measurements : _measurements [ database ] = _measurements [ database ] [ _max_batch_size : ] return False | Determine if a batch should be processed and if not pop off all of the pending metrics for that batch . | 78 | 23 |
11,252 | def _start_timeout ( ) : global _timeout LOGGER . debug ( 'Adding a new timeout in %i ms' , _timeout_interval ) _maybe_stop_timeout ( ) _timeout = ioloop . IOLoop . current ( ) . add_timeout ( ioloop . IOLoop . current ( ) . time ( ) + _timeout_interval / 1000.0 , _on_timeout ) | Stop a running timeout if it s there then create a new one . | 91 | 14 |
11,253 | def _trigger_batch_write ( ) : global _batch_future LOGGER . debug ( 'Batch write triggered (%r/%r)' , _buffer_size , _trigger_size ) _maybe_stop_timeout ( ) _maybe_warn_about_buffer_size ( ) _batch_future = _write_measurements ( ) return _batch_future | Stop a timeout if it s running and then write the measurements . | 80 | 13 |
11,254 | def _write_measurements ( ) : global _timeout , _writing future = concurrent . Future ( ) if _writing : LOGGER . warning ( 'Currently writing measurements, skipping write' ) future . set_result ( False ) elif not _pending_measurements ( ) : future . set_result ( True ) elif not _sample_batch ( ) : LOGGER . debug ( 'Skipping batch submission due to sampling' ) future . set_result ( True ) # Exit early if there's an error condition if future . done ( ) : return future if not _http_client or _dirty : _create_http_client ( ) # Keep track of the futures for each batch submission futures = [ ] # Submit a batch for each database for database in _measurements : url = '{}?db={}&precision=ms' . format ( _base_url , database ) # Get the measurements to submit measurements = _measurements [ database ] [ : _max_batch_size ] # Pop them off the stack of pending measurements _measurements [ database ] = _measurements [ database ] [ _max_batch_size : ] # Create the request future LOGGER . debug ( 'Submitting %r measurements to %r' , len ( measurements ) , url ) request = _http_client . fetch ( url , method = 'POST' , body = '\n' . join ( measurements ) . encode ( 'utf-8' ) ) # Keep track of each request in our future stack futures . append ( ( request , str ( uuid . uuid4 ( ) ) , database , measurements ) ) # Start the wait cycle for all the requests to complete _writing = True _futures_wait ( future , futures ) return future | Write out all of the metrics in each of the databases returning a future that will indicate all metrics have been written when that future is done . | 379 | 28 |
11,255 | def duration ( self , name ) : start = time . time ( ) try : yield finally : self . set_field ( name , max ( time . time ( ) , start ) - start ) | Record the time it takes to run an arbitrary code block . | 41 | 12 |
11,256 | def marshall ( self ) : return '{},{} {} {}' . format ( self . _escape ( self . name ) , ',' . join ( [ '{}={}' . format ( self . _escape ( k ) , self . _escape ( v ) ) for k , v in self . tags . items ( ) ] ) , self . _marshall_fields ( ) , int ( self . timestamp * 1000 ) ) | Return the measurement in the line protocol format . | 95 | 9 |
11,257 | def set_field ( self , name , value ) : if not any ( [ isinstance ( value , t ) for t in { int , float , bool , str } ] ) : LOGGER . debug ( 'Invalid field value: %r' , value ) raise ValueError ( 'Value must be a str, bool, integer, or float' ) self . fields [ name ] = value | Set the value of a field in the measurement . | 82 | 10 |
11,258 | def set_tags ( self , tags ) : for key , value in tags . items ( ) : self . set_tag ( key , value ) | Set multiple tags for the measurement . | 31 | 7 |
11,259 | def reply ( self , text ) : data = { 'text' : text , 'vchannel_id' : self [ 'vchannel_id' ] } if self . is_p2p ( ) : data [ 'type' ] = RTMMessageType . P2PMessage data [ 'to_uid' ] = self [ 'uid' ] else : data [ 'type' ] = RTMMessageType . ChannelMessage data [ 'channel_id' ] = self [ 'channel_id' ] return RTMMessage ( data ) | Replys a text message | 116 | 5 |
11,260 | def refer ( self , text ) : data = self . reply ( text ) data [ 'refer_key' ] = self [ 'key' ] return data | Refers current message and replys a new message | 34 | 10 |
11,261 | def increment ( self ) : if self . _starttime is not None : self . _delta = datetime . datetime . now ( ) - self . _starttime else : self . _delta = datetime . timedelta ( ) self . refresh ( ) self . ticked . emit ( ) | Increments the delta information and refreshes the interface . | 65 | 11 |
11,262 | def refresh ( self ) : delta = self . elapsed ( ) seconds = delta . seconds limit = self . limit ( ) options = { } options [ 'hours' ] = self . hours ( ) options [ 'minutes' ] = self . minutes ( ) options [ 'seconds' ] = self . seconds ( ) try : text = self . format ( ) % options except ValueError : text = '#ERROR' self . setText ( text ) if limit and limit <= seconds : self . stop ( ) self . timeout . emit ( ) | Updates the label display with the current timer information . | 113 | 11 |
11,263 | def reset ( self ) : self . _elapsed = datetime . timedelta ( ) self . _delta = datetime . timedelta ( ) self . _starttime = datetime . datetime . now ( ) self . refresh ( ) | Stops the timer and resets its values to 0 . | 52 | 12 |
11,264 | def stop ( self ) : if not self . _timer . isActive ( ) : return self . _elapsed += self . _delta self . _timer . stop ( ) | Stops the timer . If the timer is not currently running then this method will do nothing . | 38 | 19 |
11,265 | def start ( self ) : if ( self . localThreadingEnabled ( ) and self . globalThreadingEnabled ( ) ) : super ( XThread , self ) . start ( ) else : self . run ( ) self . finished . emit ( ) | Starts the thread in its own event loop if the local and global thread options are true otherwise runs the thread logic in the main event loop . | 52 | 29 |
11,266 | def startLoading ( self ) : if super ( XBatchItem , self ) . startLoading ( ) : tree = self . treeWidget ( ) if not isinstance ( tree , XOrbTreeWidget ) : self . takeFromTree ( ) return next_batch = self . batch ( ) tree . _loadBatch ( self , next_batch ) | Starts loading this item for the batch . | 75 | 9 |
11,267 | def assignOrderNames ( self ) : try : schema = self . tableType ( ) . schema ( ) except AttributeError : return for colname in self . columns ( ) : column = schema . column ( colname ) if column : self . setColumnOrderName ( colname , column . name ( ) ) | Assigns the order names for this tree based on the name of the columns . | 66 | 17 |
11,268 | def clearAll ( self ) : # clear the tree information self . clear ( ) # clear table information self . _tableTypeName = '' self . _tableType = None # clear the records information self . _recordSet = None self . _currentRecordSet = None # clear lookup information self . _query = None self . _order = None self . _groupBy = None # clear paging information if not self . signalsBlocked ( ) : self . recordsChanged . emit ( ) | Clears the tree and record information . | 102 | 8 |
11,269 | def groupByHeaderIndex ( self ) : index = self . headerMenuColumn ( ) columnTitle = self . columnOf ( index ) tableType = self . tableType ( ) if not tableType : return column = tableType . schema ( ) . column ( columnTitle ) if not column : return self . setGroupBy ( column . name ( ) ) self . setGroupingActive ( True ) | Assigns the grouping to the current header index . | 83 | 11 |
11,270 | def initializeColumns ( self ) : tableType = self . tableType ( ) if not tableType : return elif self . _columnsInitialized or self . columnOf ( 0 ) != '1' : self . assignOrderNames ( ) return # set the table header information tschema = tableType . schema ( ) columns = tschema . columns ( ) names = [ col . displayName ( ) for col in columns if not col . isPrivate ( ) ] self . setColumns ( sorted ( names ) ) self . assignOrderNames ( ) self . resizeToContents ( ) | Initializes the columns that will be used for this tree widget based \ on the table type linked to it . | 124 | 22 |
11,271 | def refresh ( self , reloadData = False , force = False ) : if not ( self . isVisible ( ) or force ) : self . _refreshTimer . start ( ) return if self . isLoading ( ) : return if reloadData : self . refreshQueryRecords ( ) # cancel current work self . _refreshTimer . stop ( ) self . worker ( ) . cancel ( ) if self . _popup : self . _popup . close ( ) # grab the record set currset = self . currentRecordSet ( ) self . worker ( ) . setBatched ( self . isPaged ( ) ) self . worker ( ) . setBatchSize ( self . pageSize ( ) ) # group the information if self . _searchTerms : currset . setGroupBy ( None ) pageSize = 0 # work with groups elif self . groupBy ( ) and self . isGroupingActive ( ) : currset . setGroupBy ( self . groupBy ( ) ) # work with batching else : currset . setGroupBy ( None ) # order the information if self . order ( ) : currset . setOrdered ( True ) currset . setOrder ( self . order ( ) ) # for larger queries, run it through the thread if self . useLoader ( ) : loader = XLoaderWidget . start ( self ) # specify the columns to load if self . specifiedColumnsOnly ( ) : currset . setColumns ( map ( lambda x : x . name ( ) , self . specifiedColumns ( ) ) ) self . _loadedColumns = set ( self . visibleColumns ( ) ) if self . isThreadEnabled ( ) and currset . isThreadEnabled ( ) : self . worker ( ) . setPreloadColumns ( self . _preloadColumns ) self . loadRequested . emit ( currset ) else : QApplication . setOverrideCursor ( Qt . WaitCursor ) self . worker ( ) . loadRecords ( currset ) QApplication . restoreOverrideCursor ( ) | Refreshes the record list for the tree . | 445 | 10 |
11,272 | def refreshQueryRecords ( self ) : if self . _recordSet is not None : records = RecordSet ( self . _recordSet ) elif self . tableType ( ) : records = self . tableType ( ) . select ( ) else : return records . setDatabase ( self . database ( ) ) # replace the base query with this widget if self . queryAction ( ) == XOrbTreeWidget . QueryAction . Replace : if self . query ( ) : records . setQuery ( self . query ( ) ) else : records . setQuery ( None ) # join together the query for this widget elif self . queryAction ( ) == XOrbTreeWidget . QueryAction . Join : if records . query ( ) : records . setQuery ( self . query ( ) & self . query ( ) ) elif self . query ( ) : records . setQuery ( self . query ( ) ) else : records . setQuery ( None ) self . _recordSet = records if not self . signalsBlocked ( ) : self . queryChanged . emit ( ) self . recordsChanged . emit ( ) | Refreshes the query results based on the tree s query . | 232 | 13 |
11,273 | def updateState ( self ) : if self . isChecked ( ) : self . setIcon ( self . lockIcon ( ) ) self . setToolTip ( 'Click to unlock' ) else : self . setIcon ( self . unlockIcon ( ) ) self . setToolTip ( 'Click to lock' ) | Updates the icon for this lock button based on its check state . | 66 | 14 |
11,274 | def render_change_form ( self , request , context , * * kwargs ) : form = context [ 'adminform' ] . form # infer correct data from the form fieldsets = [ ( None , { 'fields' : form . fields . keys ( ) } ) ] adminform = helpers . AdminForm ( form , fieldsets , self . prepopulated_fields ) media = mark_safe ( self . media + adminform . media ) context . update ( adminform = adminform , media = media ) super_meth = super ( BaseEntityAdmin , self ) . render_change_form return super_meth ( request , context , * * kwargs ) | Wrapper for ModelAdmin . render_change_form . Replaces standard static AdminForm with an EAV - friendly one . The point is that our form generates fields dynamically and fieldsets must be inferred from a prepared and validated form instance not just the form class . Django does not seem to provide hooks for this purpose so we simply wrap the view and substitute some data . | 145 | 75 |
11,275 | def gevent_run ( app , port = 5000 , log = None , error_log = None , address = '' , monkey_patch = True , start = True , * * kwargs ) : # pragma: no cover if log is None : log = app . logger if error_log is None : error_log = app . logger if monkey_patch : from gevent import monkey monkey . patch_all ( ) from gevent . wsgi import WSGIServer http_server = WSGIServer ( ( address , port ) , app , log = log , error_log = error_log , * * kwargs ) if start : http_server . serve_forever ( ) return http_server | Run your app in gevent . wsgi . WSGIServer | 154 | 15 |
11,276 | def tornado_run ( app , port = 5000 , address = "" , use_gevent = False , start = True , monkey_patch = None , Container = None , Server = None , threadpool = None ) : # pragma: no cover if Container is None : from tornado . wsgi import WSGIContainer Container = WSGIContainer if Server is None : from tornado . httpserver import HTTPServer Server = HTTPServer if monkey_patch is None : monkey_patch = use_gevent CustomWSGIContainer = Container if use_gevent : if monkey_patch : from gevent import monkey monkey . patch_all ( ) import gevent class GeventWSGIContainer ( Container ) : def __call__ ( self , * args , * * kwargs ) : def async_task ( ) : super ( GeventWSGIContainer , self ) . __call__ ( * args , * * kwargs ) gevent . spawn ( async_task ) CustomWSGIContainer = GeventWSGIContainer if threadpool is not None : from multiprocessing . pool import ThreadPool if not isinstance ( threadpool , ThreadPool ) : threadpool = ThreadPool ( threadpool ) class ThreadPoolWSGIContainer ( Container ) : def __call__ ( self , * args , * * kwargs ) : def async_task ( ) : super ( ThreadPoolWSGIContainer , self ) . __call__ ( * args , * * kwargs ) threadpool . apply_async ( async_task ) CustomWSGIContainer = ThreadPoolWSGIContainer http_server = Server ( CustomWSGIContainer ( app ) ) http_server . listen ( port , address ) if start : tornado_start ( ) return http_server | Run your app in one tornado event loop process | 391 | 9 |
11,277 | def tornado_combiner ( configs , use_gevent = False , start = True , monkey_patch = None , Container = None , Server = None , threadpool = None ) : # pragma: no cover servers = [ ] if monkey_patch is None : monkey_patch = use_gevent if use_gevent : if monkey_patch : from gevent import monkey monkey . patch_all ( ) if threadpool is not None : from multiprocessing . pool import ThreadPool if not isinstance ( threadpool , ThreadPool ) : threadpool = ThreadPool ( threadpool ) for config in configs : app = config [ 'app' ] port = config . get ( 'port' , 5000 ) address = config . get ( 'address' , '' ) server = tornado_run ( app , use_gevent = use_gevent , port = port , monkey_patch = False , address = address , start = False , Container = Container , Server = Server , threadpool = threadpool ) servers . append ( server ) if start : tornado_start ( ) return servers | Combine servers in one tornado event loop process | 230 | 9 |
11,278 | def ReadDictionary ( self , file ) : fil = dictfile . DictFile ( file ) state = { } state [ 'vendor' ] = '' self . defer_parse = [ ] for line in fil : state [ 'file' ] = fil . File ( ) state [ 'line' ] = fil . Line ( ) line = line . split ( '#' , 1 ) [ 0 ] . strip ( ) tokens = line . split ( ) if not tokens : continue key = tokens [ 0 ] . upper ( ) if key == 'ATTRIBUTE' : self . __ParseAttribute ( state , tokens ) elif key == 'VALUE' : self . __ParseValue ( state , tokens , True ) elif key == 'VENDOR' : self . __ParseVendor ( state , tokens ) elif key == 'BEGIN-VENDOR' : self . __ParseBeginVendor ( state , tokens ) elif key == 'END-VENDOR' : self . __ParseEndVendor ( state , tokens ) for state , tokens in self . defer_parse : key = tokens [ 0 ] . upper ( ) if key == 'VALUE' : self . __ParseValue ( state , tokens , False ) self . defer_parse = [ ] | Parse a dictionary file . Reads a RADIUS dictionary file and merges its contents into the class instance . | 276 | 24 |
11,279 | def drawAxis ( self , painter ) : # draw the axis lines pen = QPen ( self . axisColor ( ) ) pen . setWidth ( 4 ) painter . setPen ( pen ) painter . drawLines ( self . _buildData [ 'axis_lines' ] ) # draw the notches for rect , text in self . _buildData [ 'grid_h_notches' ] : painter . drawText ( rect , Qt . AlignTop | Qt . AlignRight , text ) for rect , text in self . _buildData [ 'grid_v_notches' ] : painter . drawText ( rect , Qt . AlignCenter , text ) | Draws the axis for this system . | 143 | 8 |
11,280 | def rebuild ( self ) : global XChartWidgetItem if ( XChartWidgetItem is None ) : from projexui . widgets . xchartwidget . xchartwidgetitem import XChartWidgetItem self . _buildData = { } # build the grid location x = 8 y = 8 w = self . sceneRect ( ) . width ( ) h = self . sceneRect ( ) . height ( ) hpad = self . horizontalPadding ( ) vpad = self . verticalPadding ( ) hmax = self . horizontalRuler ( ) . maxNotchSize ( Qt . Horizontal ) left_offset = hpad + self . verticalRuler ( ) . maxNotchSize ( Qt . Vertical ) right_offset = left_offset + hpad top_offset = vpad bottom_offset = top_offset + vpad + hmax left = x + left_offset right = w - right_offset top = y + top_offset bottom = h - bottom_offset rect = QRectF ( ) rect . setLeft ( left ) rect . setRight ( right ) rect . setBottom ( bottom ) rect . setTop ( top ) self . _buildData [ 'grid_rect' ] = rect # rebuild the ruler data self . rebuildGrid ( ) self . _dirty = False # rebuild all the items padding = self . horizontalPadding ( ) + self . verticalPadding ( ) grid = self . sceneRect ( ) filt = lambda x : isinstance ( x , XChartWidgetItem ) items = filter ( filt , self . items ( ) ) height = float ( grid . height ( ) ) if height == 0 : ratio = 1 else : ratio = grid . width ( ) / height count = len ( items ) if ( not count ) : return if ( ratio >= 1 ) : radius = ( grid . height ( ) - padding * 2 ) / 2.0 x = rect . center ( ) . x ( ) y = rect . center ( ) . y ( ) dx = radius * 2.5 dy = 0 else : radius = ( grid . width ( ) - padding * 2 ) / 2.0 x = rect . center ( ) . x ( ) y = rect . center ( ) . y ( ) dx = 0 dy = radius * 2.5 for item in items : item . setPieCenter ( QPointF ( x , y ) ) item . setRadius ( radius ) item . rebuild ( ) x += dx y += dy if ( self . _trackerItem and self . _trackerItem ( ) ) : self . _trackerItem ( ) . rebuild ( self . _buildData [ 'grid_rect' ] ) | Rebuilds the data for this scene to draw with . | 563 | 12 |
11,281 | def setSceneRect ( self , * args ) : super ( XChartScene , self ) . setSceneRect ( * args ) self . _dirty = True | Overloads the set scene rect to handle rebuild information . | 33 | 11 |
11,282 | def updateTrackerItem ( self , point = None ) : item = self . trackerItem ( ) if not item : return gridRect = self . _buildData . get ( 'grid_rect' ) if ( not ( gridRect and gridRect . isValid ( ) ) ) : item . setVisible ( False ) return if ( point is not None ) : item . setPos ( point . x ( ) , gridRect . top ( ) ) if ( not gridRect . contains ( item . pos ( ) ) ) : item . setVisible ( False ) return if ( self . chartType ( ) != self . Type . Line ) : item . setVisible ( False ) return if ( not self . isTrackingEnabled ( ) ) : item . setVisible ( False ) return item . rebuild ( gridRect ) | Updates the tracker item information . | 173 | 7 |
11,283 | def acceptEdit ( self ) : if ( self . _partsWidget . isVisible ( ) ) : return False use_completion = self . completer ( ) . popup ( ) . isVisible ( ) completion = self . completer ( ) . currentCompletion ( ) self . _completerTree . hide ( ) self . completer ( ) . popup ( ) . hide ( ) if ( use_completion ) : self . setText ( completion ) else : self . rebuild ( ) return True | Accepts the current text and rebuilds the parts widget . | 108 | 12 |
11,284 | def cancelEdit ( self ) : if ( self . _partsWidget . isVisible ( ) ) : return False self . _completerTree . hide ( ) self . completer ( ) . popup ( ) . hide ( ) self . setText ( self . _originalText ) return True | Rejects the current edit and shows the parts widget . | 62 | 12 |
11,285 | def startEdit ( self ) : self . _originalText = self . text ( ) self . scrollWidget ( ) . hide ( ) self . setFocus ( ) self . selectAll ( ) | Rebuilds the pathing based on the parts . | 40 | 11 |
11,286 | def rebuild ( self ) : navitem = self . currentItem ( ) if ( navitem ) : navitem . initialize ( ) self . setUpdatesEnabled ( False ) self . scrollWidget ( ) . show ( ) self . _originalText = '' partsw = self . partsWidget ( ) for button in self . _buttonGroup . buttons ( ) : self . _buttonGroup . removeButton ( button ) button . close ( ) button . setParent ( None ) button . deleteLater ( ) # create the root button layout = partsw . layout ( ) parts = self . parts ( ) button = QToolButton ( partsw ) button . setAutoRaise ( True ) button . setMaximumWidth ( 12 ) button . setArrowType ( Qt . RightArrow ) button . setProperty ( 'path' , wrapVariant ( '' ) ) button . setProperty ( 'is_completer' , wrapVariant ( True ) ) last_button = button self . _buttonGroup . addButton ( button ) layout . insertWidget ( 0 , button ) # check to see if we have a navigation model setup if ( self . _navigationModel ) : last_item = self . _navigationModel . itemByPath ( self . text ( ) ) show_last = last_item and last_item . rowCount ( ) > 0 else : show_last = False # load the navigation system count = len ( parts ) for i , part in enumerate ( parts ) : path = self . separator ( ) . join ( parts [ : i + 1 ] ) button = QToolButton ( partsw ) button . setAutoRaise ( True ) button . setText ( part ) if ( self . _navigationModel ) : item = self . _navigationModel . itemByPath ( path ) if ( item ) : button . setIcon ( item . icon ( ) ) button . setToolButtonStyle ( Qt . ToolButtonTextBesideIcon ) button . setProperty ( 'path' , wrapVariant ( path ) ) button . setProperty ( 'is_completer' , wrapVariant ( False ) ) self . _buttonGroup . addButton ( button ) layout . insertWidget ( ( i * 2 ) + 1 , button ) # determine if we should show the final button if ( show_last or i < ( count - 1 ) ) : button = QToolButton ( partsw ) button . setAutoRaise ( True ) button . setMaximumWidth ( 12 ) button . setArrowType ( Qt . RightArrow ) button . setProperty ( 'path' , wrapVariant ( path ) ) button . setProperty ( 'is_completer' , wrapVariant ( True ) ) self . _buttonGroup . addButton ( button ) layout . insertWidget ( ( i * 2 ) + 2 , button ) last_button = button if ( self . scrollWidget ( ) . width ( ) < partsw . width ( ) ) : self . scrollParts ( partsw . width ( ) - self . scrollWidget ( ) . width ( ) ) self . setUpdatesEnabled ( True ) self . navigationChanged . emit ( ) | Rebuilds the parts widget with the latest text . | 668 | 11 |
11,287 | def query ( self ) : if not hasattr ( self , '_decoded_query' ) : self . _decoded_query = list ( urls . _url_decode_impl ( self . querystr . split ( '&' ) , 'utf-8' , False , True , 'strict' ) ) return self . query_cls ( self . _decoded_query ) | Return a new instance of query_cls . | 87 | 10 |
11,288 | def refreshUi ( self ) : dataSet = self . dataSet ( ) if not dataSet : return False # lookup widgets based on the data set information for widget in self . findChildren ( QWidget ) : prop = unwrapVariant ( widget . property ( 'dataName' ) ) if prop is None : continue # update the data for the widget prop_name = nativestring ( prop ) if prop_name in dataSet : value = dataSet . value ( prop_name ) projexui . setWidgetValue ( widget , value ) return True | Load the plugin information to the interface . | 120 | 8 |
11,289 | def reset ( self ) : if not self . plugin ( ) : return False self . plugin ( ) . reset ( ) self . refreshUi ( ) return True | Resets the ui information to the default data for the widget . | 34 | 14 |
11,290 | def n2l ( c , l ) : l = U32 ( c [ 0 ] << 24 ) l = l | ( U32 ( c [ 1 ] ) << 16 ) l = l | ( U32 ( c [ 2 ] ) << 8 ) l = l | ( U32 ( c [ 3 ] ) ) return l | network to host long | 70 | 4 |
11,291 | def l2n ( l , c ) : c = [ ] c . append ( int ( ( l >> 24 ) & U32 ( 0xFF ) ) ) c . append ( int ( ( l >> 16 ) & U32 ( 0xFF ) ) ) c . append ( int ( ( l >> 8 ) & U32 ( 0xFF ) ) ) c . append ( int ( ( l ) & U32 ( 0xFF ) ) ) return c | host to network long | 98 | 4 |
11,292 | def start ( self ) : resp = self . post ( 'start' ) if resp . is_fail ( ) : return None if 'result' not in resp . data : return None result = resp . data [ 'result' ] return { 'user' : result [ 'user' ] , 'ws_host' : result [ 'ws_host' ] , } | Gets the rtm ws_host and user information | 78 | 12 |
11,293 | def do ( self , resource , method , params = None , data = None , json = None , headers = None ) : uri = "{0}/{1}" . format ( self . _api_base , resource ) if not params : params = { } params . update ( { 'token' : self . _token } ) req = Request ( method = method , url = uri , params = params , headers = headers , data = data , json = json ) s = Session ( ) prepped = s . prepare_request ( req ) resp = s . send ( prepped ) return RTMResponse ( resp ) | Does the request job | 132 | 4 |
11,294 | def get ( self , resource , params = None , headers = None ) : return self . do ( resource , 'GET' , params = params , headers = headers ) | Sends a GET request | 35 | 5 |
11,295 | def post ( self , resource , data = None , json = None ) : return self . do ( resource , 'POST' , data = data , json = json ) | Sends a POST request | 35 | 5 |
11,296 | def CollectMetrics ( self , request , context ) : LOG . debug ( "CollectMetrics called" ) try : metrics_to_collect = [ ] for metric in request . metrics : metrics_to_collect . append ( Metric ( pb = metric ) ) metrics_collected = self . plugin . collect ( metrics_to_collect ) return MetricsReply ( metrics = [ m . pb for m in metrics_collected ] ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return MetricsReply ( metrics = [ ] , error = msg ) | Dispatches the request to the plugins collect method | 143 | 10 |
11,297 | def GetConfigPolicy ( self , request , context ) : try : policy = self . plugin . get_config_policy ( ) return policy . _pb except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err . message , traceback . format_exc ( ) ) return GetConfigPolicyReply ( error = msg ) | Dispatches the request to the plugins get_config_policy method | 78 | 14 |
11,298 | def send_message ( self , text , chat_id , reply_to_message_id = None , disable_web_page_preview = False , reply_markup = None ) : self . logger . info ( 'sending message "%s"' , format ( text . replace ( '\n' , '\\n' ) ) ) payload = dict ( text = text , chat_id = chat_id , reply_to_message_id = reply_to_message_id , disable_web_page_preview = disable_web_page_preview , reply_markup = reply_markup ) return Message . from_api ( self , * * self . _get ( 'sendMessage' , payload ) ) | Use this method to send text messages . On success the sent Message is returned . | 158 | 16 |
11,299 | def send_audio ( self , chat_id , audio , duration = None , performer = None , title = None , reply_to_message_id = None , reply_markup = None ) : self . logger . info ( 'sending audio payload %s' , audio ) payload = dict ( chat_id = chat_id , duration = duration , performer = performer , title = title , reply_to_message_id = reply_to_message_id , reply_markup = reply_markup ) files = dict ( audio = open ( audio , 'rb' ) ) return Message . from_api ( self , * * self . _post ( 'sendAudio' , payload , files ) ) | Use this method to send audio files if you want Telegram clients to display them in the music player . Your audio must be in the . mp3 format . On success the sent Message is returned . Bots can currently send audio files of up to 50 MB in size this limit may be changed in the future . | 151 | 61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.