idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
11,300 | 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 ) if future . done ( ) : return future if not _http_client or _dirty : _create_http_client ( ) futures = [ ] for database in _measurements : url = '{}?db={}&precision=ms' . format ( _base_url , database ) measurements = _measurements [ database ] [ : _max_batch_size ] _measurements [ database ] = _measurements [ database ] [ _max_batch_size : ] LOGGER . debug ( 'Submitting %r measurements to %r' , len ( measurements ) , url ) request = _http_client . fetch ( url , method = 'POST' , body = '\n' . join ( measurements ) . encode ( 'utf-8' ) ) futures . append ( ( request , str ( uuid . uuid4 ( ) ) , database , measurements ) ) _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 . |
11,301 | 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 . |
11,302 | 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 . |
11,303 | 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 . |
11,304 | def set_tags ( self , tags ) : for key , value in tags . items ( ) : self . set_tag ( key , value ) | Set multiple tags for the measurement . |
11,305 | 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 |
11,306 | def refer ( self , text ) : data = self . reply ( text ) data [ 'refer_key' ] = self [ 'key' ] return data | Refers current message and replys a new message |
11,307 | 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 . |
11,308 | 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 . |
11,309 | 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 . |
11,310 | 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 . |
11,311 | 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 . |
11,312 | 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 . |
11,313 | 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 . |
11,314 | def clearAll ( self ) : self . clear ( ) self . _tableTypeName = '' self . _tableType = None self . _recordSet = None self . _currentRecordSet = None self . _query = None self . _order = None self . _groupBy = None if not self . signalsBlocked ( ) : self . recordsChanged . emit ( ) | Clears the tree and record information . |
11,315 | 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 . |
11,316 | def initializeColumns ( self ) : tableType = self . tableType ( ) if not tableType : return elif self . _columnsInitialized or self . columnOf ( 0 ) != '1' : self . assignOrderNames ( ) return 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 . |
11,317 | 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 ( ) self . _refreshTimer . stop ( ) self . worker ( ) . cancel ( ) if self . _popup : self . _popup . close ( ) currset = self . currentRecordSet ( ) self . worker ( ) . setBatched ( self . isPaged ( ) ) self . worker ( ) . setBatchSize ( self . pageSize ( ) ) if self . _searchTerms : currset . setGroupBy ( None ) pageSize = 0 elif self . groupBy ( ) and self . isGroupingActive ( ) : currset . setGroupBy ( self . groupBy ( ) ) else : currset . setGroupBy ( None ) if self . order ( ) : currset . setOrdered ( True ) currset . setOrder ( self . order ( ) ) if self . useLoader ( ) : loader = XLoaderWidget . start ( self ) 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 . |
11,318 | 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 ( ) ) if self . queryAction ( ) == XOrbTreeWidget . QueryAction . Replace : if self . query ( ) : records . setQuery ( self . query ( ) ) else : records . setQuery ( None ) 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 . |
11,319 | 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 . |
11,320 | def render_change_form ( self , request , context , ** kwargs ) : form = context [ 'adminform' ] . 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 . |
11,321 | def gevent_run ( app , port = 5000 , log = None , error_log = None , address = '' , monkey_patch = True , start = True , ** kwargs ) : 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 |
11,322 | def tornado_run ( app , port = 5000 , address = "" , use_gevent = False , start = True , monkey_patch = None , Container = None , Server = None , threadpool = None ) : 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 |
11,323 | def tornado_combiner ( configs , use_gevent = False , start = True , monkey_patch = None , Container = None , Server = None , threadpool = None ) : 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 |
11,324 | 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 . |
11,325 | def drawAxis ( self , painter ) : pen = QPen ( self . axisColor ( ) ) pen . setWidth ( 4 ) painter . setPen ( pen ) painter . drawLines ( self . _buildData [ 'axis_lines' ] ) 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 . |
11,326 | def rebuild ( self ) : global XChartWidgetItem if ( XChartWidgetItem is None ) : from projexui . widgets . xchartwidget . xchartwidgetitem import XChartWidgetItem self . _buildData = { } 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 self . rebuildGrid ( ) self . _dirty = False 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 . |
11,327 | def setSceneRect ( self , * args ) : super ( XChartScene , self ) . setSceneRect ( * args ) self . _dirty = True | Overloads the set scene rect to handle rebuild information . |
11,328 | 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 . |
11,329 | 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 . |
11,330 | 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 . |
11,331 | def startEdit ( self ) : self . _originalText = self . text ( ) self . scrollWidget ( ) . hide ( ) self . setFocus ( ) self . selectAll ( ) | Rebuilds the pathing based on the parts . |
11,332 | 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 ( ) 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 ) if ( self . _navigationModel ) : last_item = self . _navigationModel . itemByPath ( self . text ( ) ) show_last = last_item and last_item . rowCount ( ) > 0 else : show_last = False 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 ) 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 . |
11,333 | 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 . |
11,334 | def refreshUi ( self ) : dataSet = self . dataSet ( ) if not dataSet : return False for widget in self . findChildren ( QWidget ) : prop = unwrapVariant ( widget . property ( 'dataName' ) ) if prop is None : continue 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 . |
11,335 | 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 . |
11,336 | def n2l ( c , l ) : "network to host long" 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 |
11,337 | def l2n ( l , c ) : "host to network long" 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 |
11,338 | 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 |
11,339 | 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 |
11,340 | def get ( self , resource , params = None , headers = None ) : return self . do ( resource , 'GET' , params = params , headers = headers ) | Sends a GET request |
11,341 | def post ( self , resource , data = None , json = None ) : return self . do ( resource , 'POST' , data = data , json = json ) | Sends a POST request |
11,342 | 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 |
11,343 | 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 |
11,344 | 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 . |
11,345 | 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 . |
11,346 | def send_document ( self , chat_id = None , document = None , reply_to_message_id = None , reply_markup = None ) : payload = dict ( chat_id = chat_id , reply_to_message_id = reply_to_message_id , reply_markup = reply_markup ) files = dict ( video = open ( document , 'rb' ) ) return Message . from_api ( api , ** self . _post ( 'sendDocument' , payload , files ) ) | Use this method to send general files . On success the sent Message is returned . Bots can currently send files of any type of up to 50 MB in size this limit may be changed in the future . |
11,347 | def send_sticker ( self , chat_id = None , sticker = None , reply_to_message_id = None , reply_markup = None ) : payload = dict ( chat_id = chat_id , reply_to_message_id = reply_to_message_id , reply_markup = reply_markup ) files = dict ( sticker = open ( sticker , 'rb' ) ) return Message . from_api ( api , ** self . _post ( 'sendSticker' , payload , files ) ) | Use this method to send . webp stickers . On success the sent Message is returned . |
11,348 | def removeFromScene ( self ) : gantt = self . ganttWidget ( ) if not gantt : return scene = gantt . viewWidget ( ) . scene ( ) scene . removeItem ( self . viewItem ( ) ) for target , viewItem in self . _dependencies . items ( ) : target . _reverseDependencies . pop ( self ) scene . removeItem ( viewItem ) | Removes this item from the view scene . |
11,349 | def sync ( self , recursive = False ) : self . syncTree ( recursive = recursive ) self . syncView ( recursive = recursive ) | Syncs the information from this item to the tree and view . |
11,350 | def syncTree ( self , recursive = False , blockSignals = True ) : tree = self . treeWidget ( ) if not tree : return items = [ self ] if recursive : items += list ( self . children ( recursive = True ) ) if blockSignals and not tree . signalsBlocked ( ) : blocked = True tree . blockSignals ( True ) else : blocked = False date_format = self . ganttWidget ( ) . dateFormat ( ) for item in items : for c , col in enumerate ( tree . columns ( ) ) : value = item . property ( col , '' ) item . setData ( c , Qt . EditRole , wrapVariant ( value ) ) if blocked : tree . blockSignals ( False ) | Syncs the information from this item to the tree . |
11,351 | def syncView ( self , recursive = False ) : gantt = self . ganttWidget ( ) tree = self . treeWidget ( ) if not gantt : return vwidget = gantt . viewWidget ( ) scene = vwidget . scene ( ) cell_w = gantt . cellWidth ( ) tree_offset_y = tree . header ( ) . height ( ) + 1 tree_offset_y += tree . verticalScrollBar ( ) . value ( ) items = [ self ] if recursive : items += list ( self . children ( recursive = True ) ) for item in items : vitem = item . viewItem ( ) if not vitem . scene ( ) : scene . addItem ( vitem ) if item . isHidden ( ) or not tree : vitem . hide ( ) continue vitem . show ( ) tree_rect = tree . visualItemRect ( item ) tree_y = tree_rect . y ( ) + tree_offset_y tree_h = tree_rect . height ( ) if tree_rect . height ( ) == 0 : vitem . hide ( ) continue if gantt . timescale ( ) in ( gantt . Timescale . Minute , gantt . Timescale . Hour , gantt . Timescale . Day ) : dstart = item . dateTimeStart ( ) dend = item . dateTimeEnd ( ) view_x = scene . datetimeXPos ( dstart ) view_r = scene . datetimeXPos ( dend ) view_w = view_r - view_x else : view_x = scene . dateXPos ( item . dateStart ( ) ) view_w = item . duration ( ) * cell_w if not item . isAllDay ( ) : full_day = 24 * 60 * 60 start = item . timeStart ( ) start_day = ( start . hour ( ) * 60 * 60 ) start_day += ( start . minute ( ) * 60 ) start_day += ( start . second ( ) ) offset_start = ( start_day / float ( full_day ) ) * cell_w end = item . timeEnd ( ) end_day = ( end . hour ( ) * 60 * 60 ) end_day += ( start . minute ( ) * 60 ) end_day += ( start . second ( ) + 1 ) offset_end = ( ( full_day - end_day ) / float ( full_day ) ) offset_end *= cell_w view_x += offset_start view_w -= ( offset_start + offset_end ) view_w = max ( view_w , 5 ) vitem . setSyncing ( True ) vitem . setPos ( view_x , tree_y ) vitem . setRect ( 0 , 0 , view_w , tree_h ) vitem . setSyncing ( False ) flags = vitem . ItemIsSelectable flags |= vitem . ItemIsFocusable if item . flags ( ) & Qt . ItemIsEditable : flags |= vitem . ItemIsMovable vitem . setFlags ( flags ) item . syncDependencies ( ) | Syncs the information from this item to the view . |
11,352 | def match ( self , package ) : if isinstance ( package , basestring ) : from . packages import Package package = Package . parse ( package ) if self . name != package . name : return False if self . version_constraints and package . version not in self . version_constraints : return False if self . build_options : if package . build_options : if self . build_options - package . build_options : return False else : return True else : return False else : return True | Match package with the requirement . |
11,353 | async def leader ( self ) : response = await self . _api . get ( "/v1/status/leader" ) if response . status == 200 : return response . body | Returns the current Raft leader |
11,354 | async def peers ( self ) : response = await self . _api . get ( "/v1/status/peers" ) if response . status == 200 : return set ( response . body ) | Returns the current Raft peer set |
11,355 | def unmarkCollapsed ( self ) : if ( not self . isCollapsed ( ) ) : return self . _collapsed = False self . _storedSizes = None if ( self . orientation ( ) == Qt . Vertical ) : self . _collapseBefore . setArrowType ( Qt . UpArrow ) self . _collapseAfter . setArrowType ( Qt . DownArrow ) else : self . _collapseBefore . setArrowType ( Qt . LeftArrow ) self . _collapseAfter . setArrowType ( Qt . RightArrow ) | Unmarks this splitter as being in a collapsed state clearing any \ collapsed information . |
11,356 | def toggleCollapseAfter ( self ) : if ( self . isCollapsed ( ) ) : self . uncollapse ( ) else : self . collapse ( XSplitterHandle . CollapseDirection . After ) | Collapses the splitter after this handle . |
11,357 | def toggleCollapseBefore ( self ) : if ( self . isCollapsed ( ) ) : self . uncollapse ( ) else : self . collapse ( XSplitterHandle . CollapseDirection . Before ) | Collapses the splitter before this handle . |
11,358 | def reset ( self ) : dataSet = self . dataSet ( ) if ( not dataSet ) : dataSet = XScheme ( ) dataSet . reset ( ) | Resets the colors to the default settings . |
11,359 | def ensureVisible ( self ) : if self . _parent and self . _inheritVisibility : self . _parent . ensureVisible ( ) self . _visible = True self . sync ( ) | Ensures that this layer is visible by turning on all parent layers \ that it needs to based on its inheritance value . |
11,360 | def sync ( self ) : layerData = self . layerData ( ) for item in self . scene ( ) . items ( ) : try : if item . _layer == self : item . syncLayerData ( layerData ) except AttributeError : continue | Syncs the items on this layer with the current layer settings . |
11,361 | def _safe_urlsplit ( s ) : rv = urlparse . urlsplit ( s ) if type ( rv [ 2 ] ) is not type ( s ) : assert hasattr ( urlparse , 'clear_cache' ) urlparse . clear_cache ( ) rv = urlparse . urlsplit ( s ) assert type ( rv [ 2 ] ) is type ( s ) return rv | the urlparse . urlsplit cache breaks if it contains unicode and we cannot control that . So we force type cast that thing back to what we think it is . |
11,362 | def _uri_split ( uri ) : scheme , netloc , path , query , fragment = _safe_urlsplit ( uri ) auth = None port = None if '@' in netloc : auth , netloc = netloc . split ( '@' , 1 ) if netloc . startswith ( '[' ) : host , port_part = netloc [ 1 : ] . split ( ']' , 1 ) if port_part . startswith ( ':' ) : port = port_part [ 1 : ] elif ':' in netloc : host , port = netloc . split ( ':' , 1 ) else : host = netloc return scheme , auth , host , port , path , query , fragment | Splits up an URI or IRI . |
11,363 | def url_unquote ( s , charset = 'utf-8' , errors = 'replace' ) : if isinstance ( s , unicode ) : s = s . encode ( charset ) return _decode_unicode ( _unquote ( s ) , charset , errors ) | URL decode a single string with a given decoding . |
11,364 | def url_unquote_plus ( s , charset = 'utf-8' , errors = 'replace' ) : if isinstance ( s , unicode ) : s = s . encode ( charset ) return _decode_unicode ( _unquote_plus ( s ) , charset , errors ) | URL decode a single string with the given decoding and decode a + to whitespace . |
11,365 | def addHandler ( self , handler ) : self . _handlers . append ( handler ) self . inner . addHandler ( handler ) | Setups a new internal logging handler . For fastlog loggers handlers are kept track of in the self . _handlers list |
11,366 | def setStyle ( self , stylename ) : self . style = importlib . import_module ( stylename ) newHandler = Handler ( ) newHandler . setFormatter ( Formatter ( self . style ) ) self . addHandler ( newHandler ) | Adjusts the output format of messages based on the style name provided |
11,367 | def _log ( self , lvl , msg , type , args , kwargs ) : extra = kwargs . get ( 'extra' , { } ) extra . setdefault ( "fastlog-type" , type ) extra . setdefault ( "fastlog-indent" , self . _indent ) kwargs [ 'extra' ] = extra self . _lastlevel = lvl self . inner . log ( lvl , msg , * args , ** kwargs ) | Internal method to filter into the formatter before being passed to the main Python logger |
11,368 | def separator ( self , * args , ** kwargs ) : levelOverride = kwargs . get ( 'level' ) or self . _lastlevel self . _log ( levelOverride , '' , 'separator' , args , kwargs ) | Prints a separator to the log . This can be used to separate blocks of log messages . |
11,369 | def indent ( self ) : blk = IndentBlock ( self , self . _indent ) self . _indent += 1 return blk | Begins an indented block . Must be used in a with code block . All calls to the logger inside of the block will be indented . |
11,370 | def newline ( self , * args , ** kwargs ) : levelOverride = kwargs . get ( 'level' ) or self . _lastlevel self . _log ( levelOverride , '' , 'newline' , args , kwargs ) | Prints an empty line to the log . Uses the level of the last message printed unless specified otherwise with the level = kwarg . |
11,371 | def hexdump ( self , s , * args , ** kwargs ) : levelOverride = kwargs . get ( 'level' ) or self . _lastlevel hexdmp = hexdump . hexdump ( self , s , ** kwargs ) self . _log ( levelOverride , hexdmp , 'indented' , args , kwargs ) | Outputs a colorful hexdump of the first argument . |
11,372 | def currentText ( self ) : lineEdit = self . lineEdit ( ) if lineEdit : return lineEdit . currentText ( ) text = nativestring ( super ( XComboBox , self ) . currentText ( ) ) if not text : return self . _hint return text | Returns the current text for this combobox including the hint option \ if no text is set . |
11,373 | def showPopup ( self ) : if not self . isCheckable ( ) : return super ( XComboBox , self ) . showPopup ( ) if not self . isVisible ( ) : return point = self . mapToGlobal ( QPoint ( 0 , self . height ( ) - 1 ) ) popup = self . checkablePopup ( ) popup . setModel ( self . model ( ) ) popup . move ( point ) popup . setFixedWidth ( self . width ( ) ) height = ( self . count ( ) * 19 ) + 2 if height > 400 : height = 400 popup . setVerticalScrollBarPolicy ( Qt . ScrollBarAlwaysOn ) else : popup . setVerticalScrollBarPolicy ( Qt . ScrollBarAlwaysOff ) popup . setFixedHeight ( height ) popup . show ( ) popup . raise_ ( ) | Displays a custom popup widget for this system if a checkable state \ is setup . |
11,374 | def updateCheckState ( self ) : checkable = self . isCheckable ( ) model = self . model ( ) flags = Qt . ItemIsSelectable | Qt . ItemIsEnabled for i in range ( self . count ( ) ) : item = model . item ( i ) if not ( checkable and item . text ( ) ) : item . setCheckable ( False ) item . setFlags ( flags ) else : item . setCheckable ( True ) item . setFlags ( flags | Qt . ItemIsUserCheckable ) | Updates the items to reflect the current check state system . |
11,375 | def updateCheckedText ( self ) : if not self . isCheckable ( ) : return indexes = self . checkedIndexes ( ) items = self . checkedItems ( ) if len ( items ) < 2 or self . separator ( ) : self . lineEdit ( ) . setText ( self . separator ( ) . join ( items ) ) else : self . lineEdit ( ) . setText ( '{0} items selected' . format ( len ( items ) ) ) if not self . signalsBlocked ( ) : self . checkedItemsChanged . emit ( items ) self . checkedIndexesChanged . emit ( indexes ) | Updates the text in the editor to reflect the latest state . |
11,376 | def process ( self , metrics , config ) : LOG . debug ( "Process called" ) for metric in metrics : metric . tags [ "instance-id" ] = config [ "instance-id" ] return metrics | Processes metrics . |
11,377 | def cleanup ( self ) : if self . _movie is not None : self . _movie . frameChanged . disconnect ( self . _updateFrame ) self . _movie = None | Cleanup references to the movie when this button is destroyed . |
11,378 | def paintEvent ( self , event ) : if self . isHoverable ( ) and self . icon ( ) . isNull ( ) : return painter = QtGui . QStylePainter ( ) painter . begin ( self ) try : option = QtGui . QStyleOptionToolButton ( ) self . initStyleOption ( option ) x_scale = 1 y_scale = 1 if self . flipHorizontal ( ) : x_scale = - 1 if self . flipVertical ( ) : y_scale = - 1 center = self . rect ( ) . center ( ) painter . translate ( center . x ( ) , center . y ( ) ) painter . rotate ( self . angle ( ) ) painter . scale ( x_scale , y_scale ) painter . translate ( - center . x ( ) , - center . y ( ) ) painter . drawComplexControl ( QtGui . QStyle . CC_ToolButton , option ) finally : painter . end ( ) | Overloads the paint even to render this button . |
11,379 | def converter ( input_string , block_size = 2 ) : sentences = textprocessing . getSentences ( input_string ) blocks = textprocessing . getBlocks ( sentences , block_size ) parse . makeIdentifiers ( blocks ) | The cli tool as a built - in function . |
11,380 | def copy ( self ) : text = [ ] for item in self . selectedItems ( ) : text . append ( nativestring ( item . text ( ) ) ) QApplication . clipboard ( ) . setText ( ',' . join ( text ) ) | Copies the selected items to the clipboard . |
11,381 | def finishEditing ( self , tag ) : curr_item = self . currentItem ( ) create_item = self . createItem ( ) self . closePersistentEditor ( curr_item ) if curr_item == create_item : self . addTag ( tag ) elif self . isTagValid ( tag ) : curr_item . setText ( tag ) | Finishes editing the current item . |
11,382 | def paste ( self ) : text = nativestring ( QApplication . clipboard ( ) . text ( ) ) for tag in text . split ( ',' ) : tag = tag . strip ( ) if ( self . isTagValid ( tag ) ) : self . addTag ( tag ) | Pastes text from the clipboard . |
11,383 | def resizeEvent ( self , event ) : curr_item = self . currentItem ( ) self . closePersistentEditor ( curr_item ) super ( XMultiTagEdit , self ) . resizeEvent ( event ) | Overloads the resize event to control if we are still editing . If we are resizing then we are no longer editing . |
11,384 | def Publish ( self , request , context ) : LOG . debug ( "Publish called" ) try : self . plugin . publish ( [ Metric ( pb = m ) for m in request . Metrics ] , ConfigMap ( pb = request . Config ) ) return ErrReply ( ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return ErrReply ( error = msg ) | Dispatches the request to the plugins publish method |
11,385 | def main ( ) : if sys . version_info [ 0 ] < 3 : sys . stdout = codecs . getwriter ( "utf-8" ) ( sys . stdout ) options = docopt . docopt ( __doc__ , help = True , version = 'template_remover v%s' % __VERSION__ ) print ( template_remover . clean ( io . open ( options [ 'FILENAME' ] ) . read ( ) ) ) return 0 | Entry point for remove_template . |
11,386 | def validate_range_value ( value ) : if value == ( None , None ) : return if not hasattr ( value , '__iter__' ) : raise TypeError ( 'Range value must be an iterable, got "%s".' % value ) if not 2 == len ( value ) : raise ValueError ( 'Range value must consist of two elements, got %d.' % len ( value ) ) if not all ( isinstance ( x , ( int , float ) ) for x in value ) : raise TypeError ( 'Range value must consist of two numbers, got "%s" ' 'and "%s" instead.' % value ) if not value [ 0 ] <= value [ 1 ] : raise ValueError ( 'Range must consist of min and max values (min <= ' 'max) but got "%s" and "%s" instead.' % value ) return | Validates given value against Schema . TYPE_RANGE data type . Raises TypeError or ValueError if something is wrong . Returns None if everything is OK . |
11,387 | def save_attr ( self , entity , value ) : if self . datatype == self . TYPE_MANY : self . _save_m2m_attr ( entity , value ) else : self . _save_single_attr ( entity , value ) | Saves given EAV attribute with given value for given entity . |
11,388 | def _save_single_attr ( self , entity , value = None , schema = None , create_nulls = False , extra = { } ) : schema = schema or self lookups = dict ( get_entity_lookups ( entity ) , schema = schema , ** extra ) try : attr = self . attrs . get ( ** lookups ) except self . attrs . model . DoesNotExist : attr = self . attrs . model ( ** lookups ) if create_nulls or value != attr . value : attr . value = value for k , v in extra . items ( ) : setattr ( attr , k , v ) attr . save ( ) | Creates or updates an EAV attribute for given entity with given value . |
11,389 | def pickColor ( self ) : color = QColorDialog . getColor ( self . color ( ) , self ) if ( color . isValid ( ) ) : self . setColor ( color ) | Prompts the user to select a color for this button . |
11,390 | def by_id ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _get ( path ) | get adapter data by its id . |
11,391 | def by_name ( self , name , archived = False , limit = None , page = None ) : if not archived : path = _path ( self . adapter ) else : path = _path ( self . adapter , 'archived' ) return self . _get ( path , name = name , limit = limit , page = page ) | get adapter data by name . |
11,392 | def all ( self , archived = False , limit = None , page = None ) : path = partial ( _path , self . adapter ) if not archived : path = _path ( self . adapter ) else : path = _path ( self . adapter , 'archived' ) return self . _get ( path , limit = limit , page = page ) | get all adapter data . |
11,393 | def by_name ( self , name , archived = False , limit = None , page = None ) : return super ( Projects , self ) . by_name ( name , archived = archived , limit = limit , page = page ) | return a project by it s name . this only works with the exact name of the project . |
11,394 | def delete ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _delete ( path ) | delete a time entry . |
11,395 | def at ( self , year , month , day ) : path = partial ( _path , self . adapter ) path = partial ( path , int ( year ) ) path = partial ( path , int ( month ) ) path = path ( int ( day ) ) return self . _get ( path ) | time entries by year month and day . |
11,396 | def start ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _put ( path ) | start a specific tracker . |
11,397 | def stop ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _delete ( path ) | stop the tracker . |
11,398 | def clear ( self ) : self . blockSignals ( True ) self . setUpdatesEnabled ( False ) for child in self . findChildren ( XRolloutItem ) : child . setParent ( None ) child . deleteLater ( ) self . setUpdatesEnabled ( True ) self . blockSignals ( False ) | Clears out all of the rollout items from the widget . |
11,399 | def minimumLabelHeight ( self ) : metrics = QFontMetrics ( self . labelFont ( ) ) return max ( self . _minimumLabelHeight , metrics . height ( ) + self . verticalLabelPadding ( ) ) | Returns the minimum height that will be required based on this font size and labels list . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.