idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
11,400
def acceptEdit ( self ) : if not self . _lineEdit : return self . setText ( self . _lineEdit . text ( ) ) self . _lineEdit . hide ( ) if not self . signalsBlocked ( ) : self . editingFinished . emit ( self . _lineEdit . text ( ) )
Accepts the current edit for this label .
11,401
def beginEdit ( self ) : if not self . _lineEdit : return self . aboutToEdit . emit ( ) self . _lineEdit . setText ( self . editText ( ) ) self . _lineEdit . show ( ) self . _lineEdit . selectAll ( ) self . _lineEdit . setFocus ( )
Begins editing for the label .
11,402
def rejectEdit ( self ) : if self . _lineEdit : self . _lineEdit . hide ( ) self . editingCancelled . emit ( )
Cancels the edit for this label .
11,403
def typeseq ( types ) : ret = "" for t in types : ret += termcap . get ( fmttypes [ t ] ) return ret
Returns an escape for a terminal text formatting type or a list of types .
11,404
def nametonum ( name ) : code = colorcodes . get ( name ) if code is None : raise ValueError ( "%s is not a valid color name." % name ) else : return code
Returns a color code number given the color name .
11,405
def fgseq ( code ) : if isinstance ( code , str ) : code = nametonum ( code ) if code == - 1 : return "" s = termcap . get ( 'setaf' , code ) or termcap . get ( 'setf' , code ) return s
Returns the forground color terminal escape sequence for the given color code number or color name .
11,406
def bgseq ( code ) : if isinstance ( code , str ) : code = nametonum ( code ) if code == - 1 : return "" s = termcap . get ( 'setab' , code ) or termcap . get ( 'setb' , code ) return s
Returns the background color terminal escape sequence for the given color code number .
11,407
def parse ( self , descriptor ) : fg = descriptor . get ( 'fg' ) bg = descriptor . get ( 'bg' ) types = descriptor . get ( 'fmt' ) ret = "" if fg : ret += fgseq ( fg ) if bg : ret += bgseq ( bg ) if types : t = typeseq ( types ) if t : ret += t reset = resetseq ( ) if not isinstance ( reset , six . text_type ) : reset = reset . decode ( 'utf-8' ) def ret_func ( msg ) : if not isinstance ( msg , six . text_type ) : msg = msg . decode ( 'utf-8' ) return ret + msg + reset self . decorator = ret_func
Creates a text styling from a descriptor
11,408
def accept ( self ) : if ( not self . uiNameTXT . text ( ) ) : QMessageBox . information ( self , 'Invalid Name' , 'You need to supply a name for your layout.' ) return prof = self . profile ( ) if ( not prof ) : prof = XViewProfile ( ) prof . setName ( nativestring ( self . uiNameTXT . text ( ) ) ) prof . setVersion ( self . uiVersionSPN . value ( ) ) prof . setDescription ( nativestring ( self . uiDescriptionTXT . toPlainText ( ) ) ) prof . setIcon ( self . uiIconBTN . filepath ( ) ) super ( XViewProfileDialog , self ) . accept ( )
Saves the data to the profile before closing .
11,409
def browseMaps ( self ) : url = self . urlTemplate ( ) params = urllib . urlencode ( { self . urlQueryKey ( ) : self . location ( ) } ) url = url % { 'params' : params } webbrowser . open ( url )
Brings up a web browser with the address in a Google map .
11,410
def _initialize_chrome_driver ( self ) : try : print ( colored ( '\nInitializing Headless Chrome...\n' , 'yellow' ) ) self . _initialize_chrome_options ( ) self . _chromeDriver = webdriver . Chrome ( chrome_options = self . _chromeOptions ) self . _chromeDriver . maximize_window ( ) print ( colored ( '\nHeadless Chrome Initialized.' , 'green' ) ) except Exception as exception : print ( colored ( 'Error - Driver Initialization: ' + format ( exception ) ) , 'red' )
Initializes chrome in headless mode
11,411
def extract_images ( self , imageQuery , imageCount = 100 , destinationFolder = './' , threadCount = 4 ) : self . _initialize_chrome_driver ( ) self . _imageQuery = imageQuery self . _imageCount = imageCount self . _destinationFolder = destinationFolder self . _threadCount = threadCount self . _get_image_urls ( ) self . _create_storage_folder ( ) self . _download_images ( ) print ( colored ( '\n\nImages Downloaded: ' + str ( self . _imageCounter ) + ' of ' + str ( self . _imageCount ) + ' in ' + format_timespan ( self . _downloadProgressBar . data ( ) [ 'total_seconds_elapsed' ] ) + '\n' , 'green' ) ) self . _chromeDriver . close ( ) self . _reset_helper_variables ( )
Searches across Google Image Search with the specified image query and downloads the specified count of images
11,412
def _get_image_urls ( self ) : print ( colored ( '\nRetrieving Image URLs...' , 'yellow' ) ) _imageQuery = self . _imageQuery . replace ( ' ' , '+' ) self . _chromeDriver . get ( 'https://www.google.co.in/search?q=' + _imageQuery + '&newwindow=1&source=lnms&tbm=isch' ) while self . _imageURLsExtractedCount <= self . _imageCount : self . _extract_image_urls ( ) self . _page_scroll_down ( ) print ( colored ( 'Image URLs retrieved.' , 'green' ) )
Retrieves the image URLS corresponding to the image query
11,413
def _extract_image_urls ( self ) : resultsPage = self . _chromeDriver . page_source resultsPageSoup = BeautifulSoup ( resultsPage , 'html.parser' ) images = resultsPageSoup . find_all ( 'div' , class_ = 'rg_meta' ) images = [ json . loads ( image . contents [ 0 ] ) for image in images ] [ self . _imageURLs . append ( image [ 'ou' ] ) for image in images ] self . _imageURLsExtractedCount += len ( images )
Retrieves image URLs from the current page
11,414
def _page_scroll_down ( self ) : self . _chromeDriver . execute_script ( 'window.scroll(0, document.body.clientHeight)' ) time . sleep ( self . WAIT_TIME ) try : self . _chromeDriver . find_element_by_id ( 'smb' ) . click ( ) except ElementNotVisibleException as error : pass
Scrolls down to get the next set of images
11,415
def _download_images ( self ) : print ( '\nDownloading Images for the Query: ' + self . _imageQuery ) try : self . _initialize_progress_bar ( ) threadPool = Pool ( self . _threadCount ) threadPool . map ( self . _download_image , self . _imageURLs ) threadPool . close ( ) threadPool . join ( ) self . _downloadProgressBar . finish ( ) except Exception as exception : print ( 'Error - Image Download: ' + format ( exception ) )
Downloads the images from the retrieved image URLs and stores in the specified destination folder . Multiprocessing is being used to minimize the download time
11,416
def _initialize_progress_bar ( self ) : widgets = [ 'Download: ' , Percentage ( ) , ' ' , Bar ( ) , ' ' , AdaptiveETA ( ) , ' ' , FileTransferSpeed ( ) ] self . _downloadProgressBar = ProgressBar ( widgets = widgets , max_value = self . _imageCount ) . start ( )
Initializes the progress bar
11,417
def _download_image ( self , imageURL ) : if ( self . _imageCounter >= self . _imageCount ) : return try : imageResponse = requests . get ( imageURL ) imageType , imageEncoding = mimetypes . guess_type ( imageURL ) if imageType is not None : imageExtension = mimetypes . guess_extension ( imageType ) else : imageExtension = mimetypes . guess_extension ( imageResponse . headers [ 'Content-Type' ] ) imageFileName = self . _imageQuery . replace ( ' ' , '_' ) + '_' + str ( self . _imageCounter ) + imageExtension imageFileName = os . path . join ( self . _storageFolder , imageFileName ) image = Image . open ( BytesIO ( imageResponse . content ) ) image . save ( imageFileName ) self . _imageCounter += 1 self . _downloadProgressBar . update ( self . _imageCounter ) except Exception as exception : pass
Downloads an image file from the given image URL
11,418
def increment ( self , amount = 1 ) : self . _primaryProgressBar . setValue ( self . value ( ) + amount ) QApplication . instance ( ) . processEvents ( )
Increments the main progress bar by amount .
11,419
def incrementSub ( self , amount = 1 ) : self . _subProgressBar . setValue ( self . subValue ( ) + amount ) QApplication . instance ( ) . processEvents ( )
Increments the sub - progress bar by amount .
11,420
def assignRenderer ( self , action ) : name = nativestring ( action . text ( ) ) . split ( ' ' ) [ 0 ] self . _renderer = XChartRenderer . plugin ( name ) self . uiTypeBTN . setDefaultAction ( action ) self . recalculate ( )
Assigns the renderer for this chart to the current selected renderer .
11,421
def recalculate ( self ) : if not ( self . isVisible ( ) and self . renderer ( ) ) : return if self . _dataChanged : for axis in self . axes ( ) : if axis . useDynamicRange ( ) : axis . calculateRange ( self . values ( axis . name ( ) ) ) self . _dataChanged = False xaxis = self . horizontalAxis ( ) yaxis = self . verticalAxis ( ) renderer = self . renderer ( ) xvisible = xaxis is not None and self . showXAxis ( ) and renderer . showXAxis ( ) yvisible = yaxis is not None and self . showYAxis ( ) and renderer . showYAxis ( ) self . uiXAxisVIEW . setVisible ( xvisible ) self . uiYAxisVIEW . setVisible ( yvisible ) view = self . uiChartVIEW chart_scene = view . scene ( ) chart_scene . setSceneRect ( 0 , 0 , view . width ( ) - 2 , view . height ( ) - 2 ) rect = renderer . calculate ( chart_scene , xaxis , yaxis ) if xaxis and self . showXAxis ( ) and renderer . showXAxis ( ) : view = self . uiXAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , rect . width ( ) , view . height ( ) ) scene . invalidate ( ) if yaxis and self . showYAxis ( ) and renderer . showYAxis ( ) : view = self . uiYAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , view . width ( ) , rect . height ( ) ) scene . invalidate ( ) renderer . calculateDatasets ( chart_scene , self . axes ( ) , self . datasets ( ) ) chart_scene . invalidate ( )
Recalculates the information for this chart .
11,422
def syncScrollbars ( self ) : chart_hbar = self . uiChartVIEW . horizontalScrollBar ( ) chart_vbar = self . uiChartVIEW . verticalScrollBar ( ) x_hbar = self . uiXAxisVIEW . horizontalScrollBar ( ) x_vbar = self . uiXAxisVIEW . verticalScrollBar ( ) y_hbar = self . uiYAxisVIEW . horizontalScrollBar ( ) y_vbar = self . uiYAxisVIEW . verticalScrollBar ( ) x_hbar . setRange ( chart_hbar . minimum ( ) , chart_hbar . maximum ( ) ) x_hbar . setValue ( chart_hbar . value ( ) ) x_vbar . setValue ( 0 ) chart_vbar . setRange ( y_vbar . minimum ( ) , y_vbar . maximum ( ) ) chart_vbar . setValue ( y_vbar . value ( ) ) y_hbar . setValue ( 4 )
Synchronizes the various scrollbars within this chart .
11,423
async def deregister ( self , node , * , check = None , service = None , write_token = None ) : entry = { } if isinstance ( node , str ) : entry [ "Node" ] = node else : for k in ( "Datacenter" , "Node" , "CheckID" , "ServiceID" , "WriteRequest" ) : if k in node : entry [ k ] = node [ k ] service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] ) check_id = extract_attr ( check , keys = [ "CheckID" , "ID" ] ) if service_id and not check_id : entry [ "ServiceID" ] = service_id elif service_id and check_id : entry [ "CheckID" ] = "%s:%s" % ( service_id , check_id ) elif not service_id and check_id : entry [ "CheckID" ] = check_id if write_token : entry [ "WriteRequest" ] = { "Token" : extract_attr ( write_token , keys = [ "ID" ] ) } response = await self . _api . put ( "/v1/catalog/deregister" , data = entry ) return response . status == 200
Deregisters a node service or check
11,424
async def nodes ( self , * , dc = None , near = None , watch = None , consistency = None ) : params = { "dc" : dc , "near" : near } response = await self . _api . get ( "/v1/catalog/nodes" , params = params , watch = watch , consistency = consistency ) return consul ( response )
Lists nodes in a given DC
11,425
async def services ( self , * , dc = None , watch = None , consistency = None ) : params = { "dc" : dc } response = await self . _api . get ( "/v1/catalog/services" , params = params , watch = watch , consistency = consistency ) return consul ( response )
Lists services in a given DC
11,426
def createProfile ( self , profile = None , clearLayout = True ) : if profile : prof = profile elif not self . viewWidget ( ) or clearLayout : prof = XViewProfile ( ) else : prof = self . viewWidget ( ) . saveProfile ( ) blocked = self . signalsBlocked ( ) self . blockSignals ( False ) changed = self . editProfile ( prof ) self . blockSignals ( blocked ) if not changed : return act = self . addProfile ( prof ) act . setChecked ( True ) if self . viewWidget ( ) and ( profile or clearLayout ) : self . viewWidget ( ) . restoreProfile ( prof ) if not self . signalsBlocked ( ) : self . profileCreated . emit ( prof ) self . profilesChanged . emit ( )
Prompts the user to create a new profile .
11,427
def updateRemoveEnabled ( self ) : lineWidgets = self . lineWidgets ( ) count = len ( lineWidgets ) state = self . minimumCount ( ) < count for widget in lineWidgets : widget . setRemoveEnabled ( state )
Updates the remove enabled baesd on the current number of line widgets .
11,428
def updateRules ( self ) : terms = sorted ( self . _rules . keys ( ) ) for child in self . lineWidgets ( ) : child . setTerms ( terms )
Updates the query line items to match the latest rule options .
11,429
def handleProfileChange ( self ) : prof = self . currentProfile ( ) vwidget = self . viewWidget ( ) if vwidget : prof . restore ( vwidget ) if not self . signalsBlocked ( ) : self . currentProfileChanged . emit ( self . currentProfile ( ) )
Emits that the current profile has changed .
11,430
def showOptionsMenu ( self ) : point = QPoint ( 0 , self . _optionsButton . height ( ) ) global_point = self . _optionsButton . mapToGlobal ( point ) if self . optionsMenuPolicy ( ) == Qt . CustomContextMenu : if not self . signalsBlocked ( ) : self . optionsMenuRequested . emit ( global_point ) return menu = XViewProfileManagerMenu ( self ) menu . exec_ ( global_point )
Displays the options menu . If the option menu policy is set to CustomContextMenu then the optionMenuRequested signal will be emitted otherwise the default context menu will be displayed .
11,431
def accept ( self ) : filetypes = 'PNG Files (*.png);;JPG Files (*.jpg);;All Files (*.*)' filename = QFileDialog . getSaveFileName ( None , 'Save Snapshot' , self . filepath ( ) , filetypes ) if type ( filename ) == tuple : filename = filename [ 0 ] filename = nativestring ( filename ) if not filename : self . reject ( ) else : self . setFilepath ( filename ) self . save ( )
Prompts the user for the filepath to save and then saves the image .
11,432
def reject ( self ) : if self . hideWindow ( ) : self . hideWindow ( ) . show ( ) self . close ( ) self . deleteLater ( )
Rejects the snapshot and closes the widget .
11,433
def save ( self ) : if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) self . hide ( ) QApplication . processEvents ( ) time . sleep ( 1 ) wid = QApplication . desktop ( ) . winId ( ) if not self . _region . isNull ( ) : x = self . _region . x ( ) y = self . _region . y ( ) w = self . _region . width ( ) h = self . _region . height ( ) else : x = self . x ( ) y = self . y ( ) w = self . width ( ) h = self . height ( ) pixmap = QPixmap . grabWindow ( wid , x , y , w , h ) pixmap . save ( self . filepath ( ) ) self . close ( ) self . deleteLater ( ) if self . hideWindow ( ) : self . hideWindow ( ) . show ( )
Saves the snapshot based on the current region .
11,434
def show ( self ) : super ( XSnapshotWidget , self ) . show ( ) if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) QApplication . processEvents ( )
Shows this widget and hides the specified window if necessary .
11,435
def keyphrases_table ( keyphrases , texts , similarity_measure = None , synonimizer = None , language = consts . Language . ENGLISH ) : similarity_measure = similarity_measure or relevance . ASTRelevanceMeasure ( ) text_titles = texts . keys ( ) text_collection = texts . values ( ) similarity_measure . set_text_collection ( text_collection , language ) i = 0 keyphrases_prepared = { keyphrase : utils . prepare_text ( keyphrase ) for keyphrase in keyphrases } total_keyphrases = len ( keyphrases ) total_scores = len ( text_collection ) * total_keyphrases res = { } for keyphrase in keyphrases : if not keyphrase : continue res [ keyphrase ] = { } for j in xrange ( len ( text_collection ) ) : i += 1 logging . progress ( "Calculating matching scores" , i , total_scores ) res [ keyphrase ] [ text_titles [ j ] ] = similarity_measure . relevance ( keyphrases_prepared [ keyphrase ] , text = j , synonimizer = synonimizer ) logging . clear ( ) return res
Constructs the keyphrases table containing their matching scores in a set of texts .
11,436
def keyphrases_graph ( keyphrases , texts , referral_confidence = 0.6 , relevance_threshold = 0.25 , support_threshold = 1 , similarity_measure = None , synonimizer = None , language = consts . Language . ENGLISH ) : similarity_measure = similarity_measure or relevance . ASTRelevanceMeasure ( ) table = keyphrases_table ( keyphrases , texts , similarity_measure , synonimizer , language ) keyphrase_texts = { keyphrase : set ( [ text for text in texts if table [ keyphrase ] [ text ] >= relevance_threshold ] ) for keyphrase in keyphrases } graph = { "nodes" : [ { "id" : i , "label" : keyphrase , "support" : len ( keyphrase_texts [ keyphrase ] ) } for i , keyphrase in enumerate ( keyphrases ) ] , "edges" : [ ] , "referral_confidence" : referral_confidence , "relevance_threshold" : relevance_threshold , "support_threshold" : support_threshold } graph [ "nodes" ] = [ n for n in graph [ "nodes" ] if len ( keyphrase_texts [ n [ "label" ] ] ) >= support_threshold ] for i1 , i2 in itertools . permutations ( range ( len ( graph [ "nodes" ] ) ) , 2 ) : node1 = graph [ "nodes" ] [ i1 ] node2 = graph [ "nodes" ] [ i2 ] confidence = ( float ( len ( keyphrase_texts [ node1 [ "label" ] ] & keyphrase_texts [ node2 [ "label" ] ] ) ) / max ( len ( keyphrase_texts [ node1 [ "label" ] ] ) , 1 ) ) if confidence >= referral_confidence : graph [ "edges" ] . append ( { "source" : node1 [ "id" ] , "target" : node2 [ "id" ] , "confidence" : confidence } ) return graph
Constructs the keyphrases relation graph based on the given texts corpus .
11,437
def _decode_unicode ( value , charset , errors ) : fallback = None if errors . startswith ( 'fallback:' ) : fallback = errors [ 9 : ] errors = 'strict' try : return value . decode ( charset , errors ) except UnicodeError , e : if fallback is not None : return value . decode ( fallback , 'replace' ) from werkzeug . exceptions import HTTPUnicodeError raise HTTPUnicodeError ( str ( e ) )
Like the regular decode function but this one raises an HTTPUnicodeError if errors is strict .
11,438
def dropEvent ( self , event ) : url = event . mimeData ( ) . urls ( ) [ 0 ] url_path = nativestring ( url . toString ( ) ) if ( not url_path . startswith ( 'file:' ) ) : filename = os . path . basename ( url_path ) temp_path = os . path . join ( nativestring ( QDir . tempPath ( ) ) , filename ) try : urllib . urlretrieve ( url_path , temp_path ) except IOError : return self . setFilepath ( temp_path ) else : self . setFilepath ( url_path . replace ( 'file://' , '' ) )
Handles a drop event .
11,439
def pickFilepath ( self ) : filepath = QFileDialog . getOpenFileName ( self , 'Select Image File' , QDir . currentPath ( ) , self . fileTypes ( ) ) if type ( filepath ) == tuple : filepath = nativestring ( filepath [ 0 ] ) if ( filepath ) : self . setFilepath ( filepath )
Picks the image file to use for this icon path .
11,440
async def fire ( self , name , payload = None , * , dc = None , node = None , service = None , tag = None ) : params = { "dc" : dc , "node" : extract_pattern ( node ) , "service" : extract_pattern ( service ) , "tag" : extract_pattern ( tag ) } payload = encode_value ( payload ) if payload else None response = await self . _api . put ( "/v1/event/fire" , name , data = payload , params = params , headers = { "Content-Type" : "application/octet-stream" } ) result = format_event ( response . body ) return result
Fires a new event
11,441
async def items ( self , name = None , * , watch = None ) : path = "/v1/event/list" params = { "name" : name } response = await self . _api . get ( path , params = params , watch = watch ) results = [ format_event ( data ) for data in response . body ] return consul ( results , meta = extract_meta ( response . headers ) )
Lists the most recent events an agent has seen
11,442
def updateRecordValues ( self ) : record = self . record ( ) if not record : return tree = self . treeWidget ( ) if not isinstance ( tree , XTreeWidget ) : return for column in record . schema ( ) . columns ( ) : c = tree . column ( column . displayName ( ) ) if c == - 1 : continue elif tree . isColumnHidden ( c ) : continue else : val = record . recordValue ( column . name ( ) ) self . updateColumnValue ( column , val , c ) if not record . isRecord ( ) : self . addRecordState ( XOrbRecordItem . State . New ) elif record . isModified ( ) : self . addRecordState ( XOrbRecordItem . State . Modified )
Updates the ui to show the latest record values .
11,443
def extract_bits ( self , val ) : thisval = self . high >> 4 thisval = thisval ^ val self . high = ( self . high << 4 ) | ( self . low >> 4 ) self . high = self . high & constants . BYTEMASK self . low = self . low << 4 self . low = self . low & constants . BYTEMASK self . high = self . high ^ self . LookupHigh [ thisval ] self . high = self . high & constants . BYTEMASK self . low = self . low ^ self . LookupLow [ thisval ] self . low = self . low & constants . BYTEMASK
Extras the 4 bits XORS the message data and does table lookups .
11,444
def run ( self , message ) : for value in message : self . update ( value ) return [ self . low , self . high ]
Calculates a CRC
11,445
def _hm_form_message ( self , thermostat_id , protocol , source , function , start , payload ) : if protocol == constants . HMV3_ID : start_low = ( start & constants . BYTEMASK ) start_high = ( start >> 8 ) & constants . BYTEMASK if function == constants . FUNC_READ : payload_length = 0 length_low = ( constants . RW_LENGTH_ALL & constants . BYTEMASK ) length_high = ( constants . RW_LENGTH_ALL >> 8 ) & constants . BYTEMASK else : payload_length = len ( payload ) length_low = ( payload_length & constants . BYTEMASK ) length_high = ( payload_length >> 8 ) & constants . BYTEMASK msg = [ thermostat_id , 10 + payload_length , source , function , start_low , start_high , length_low , length_high ] if function == constants . FUNC_WRITE : msg = msg + payload type ( msg ) return msg else : assert 0 , "Un-supported protocol found %s" % protocol
Forms a message payload excluding CRC
11,446
def _hm_form_message_crc ( self , thermostat_id , protocol , source , function , start , payload ) : data = self . _hm_form_message ( thermostat_id , protocol , source , function , start , payload ) crc = CRC16 ( ) data = data + crc . run ( data ) return data
Forms a message payload including CRC
11,447
def _hm_verify_message_crc_uk ( self , thermostat_id , protocol , source , expectedFunction , expectedLength , datal ) : badresponse = 0 if protocol == constants . HMV3_ID : checksum = datal [ len ( datal ) - 2 : ] rxmsg = datal [ : len ( datal ) - 2 ] crc = CRC16 ( ) expectedchecksum = crc . run ( rxmsg ) if expectedchecksum == checksum : logging . info ( "CRC is correct" ) else : logging . error ( "CRC is INCORRECT" ) serror = "Incorrect CRC" sys . stderr . write ( serror ) badresponse += 1 dest_addr = datal [ 0 ] frame_len_l = datal [ 1 ] frame_len_h = datal [ 2 ] frame_len = ( frame_len_h << 8 ) | frame_len_l source_addr = datal [ 3 ] func_code = datal [ 4 ] if ( dest_addr != 129 and dest_addr != 160 ) : logging . info ( "dest_addr is ILLEGAL" ) serror = "Illegal Dest Addr: %s\n" % ( dest_addr ) sys . stderr . write ( serror ) badresponse += 1 if dest_addr != thermostat_id : logging . info ( "dest_addr is INCORRECT" ) serror = "Incorrect Dest Addr: %s\n" % ( dest_addr ) sys . stderr . write ( serror ) badresponse += 1 if ( source_addr < 1 or source_addr > 32 ) : logging . info ( "source_addr is ILLEGAL" ) serror = "Illegal Src Addr: %s\n" % ( source_addr ) sys . stderr . write ( serror ) badresponse += 1 if source_addr != source : logging . info ( "source addr is INCORRECT" ) serror = "Incorrect Src Addr: %s\n" % ( source_addr ) sys . stderr . write ( serror ) badresponse += 1 if ( func_code != constants . FUNC_WRITE and func_code != constants . FUNC_READ ) : logging . info ( "Func Code is UNKNWON" ) serror = "Unknown Func Code: %s\n" % ( func_code ) sys . stderr . write ( serror ) badresponse += 1 if func_code != expectedFunction : logging . info ( "Func Code is UNEXPECTED" ) serror = "Unexpected Func Code: %s\n" % ( func_code ) sys . stderr . write ( serror ) badresponse += 1 if ( func_code == constants . FUNC_WRITE and frame_len != 7 ) : logging . info ( "response length is INCORRECT" ) serror = "Incorrect length: %s\n" % ( frame_len ) sys . stderr . write ( serror ) badresponse += 1 if len ( datal ) != frame_len : logging . info ( "response length MISMATCHES header" ) serror = "Mismatch length: %s %s\n" % ( len ( datal ) , frame_len ) sys . stderr . write ( serror ) badresponse += 1 if ( badresponse == 0 ) : return True else : return False else : assert 0 , "Un-supported protocol found %s" % protocol
Verifies message appears legal
11,448
def _hm_send_msg ( self , message ) : try : serial_message = message self . conn . write ( serial_message ) except serial . SerialTimeoutException : serror = "Write timeout error: \n" sys . stderr . write ( serror ) byteread = self . conn . read ( 159 ) datal = list ( byteread ) return datal
This is the only interface to the serial connection .
11,449
def _hm_read_address ( self ) : response = self . _hm_send_address ( self . address , 0 , 0 , 0 ) lookup = self . config [ 'keys' ] offset = self . config [ 'offset' ] keydata = { } for i in lookup : try : kdata = lookup [ i ] ddata = response [ i + offset ] keydata [ i ] = { 'label' : kdata , 'value' : ddata } except IndexError : logging . info ( "Finished processing at %d" , i ) return keydata
Reads from the DCB and maps to yaml config file .
11,450
def read_dcb ( self ) : logging . info ( "Getting latest data from DCB...." ) self . dcb = self . _hm_read_address ( ) return self . dcb
Returns the full DCB only use for non read - only operations Use self . dcb for read - only operations .
11,451
def set_target_temp ( self , temperature ) : if 35 < temperature < 5 : logging . info ( "Refusing to set temp outside of allowed range" ) return False else : self . _hm_send_address ( self . address , 18 , temperature , 1 ) return True
Sets the target temperature to the requested int
11,452
async def node ( self , node , * , dc = None , watch = None , consistency = None ) : node_id = extract_attr ( node , keys = [ "Node" , "ID" ] ) params = { "dc" : dc } response = await self . _api . get ( "/v1/health/node" , node_id , params = params , watch = watch , consistency = consistency ) return consul ( response )
Returns the health info of a node .
11,453
async def checks ( self , service , * , dc = None , near = None , watch = None , consistency = None ) : service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] ) params = { "dc" : dc , "near" : near } response = await self . _api . get ( "/v1/health/checks" , service_id , params = params , watch = watch , consistency = consistency ) return consul ( response )
Returns the checks of a service
11,454
def make_limited_stream ( stream , limit ) : if not isinstance ( stream , LimitedStream ) : if limit is None : raise TypeError ( 'stream not limited and no limit provided.' ) stream = LimitedStream ( stream , limit ) return stream
Makes a stream limited .
11,455
def exhaust ( self , chunk_size = 1024 * 16 ) : to_read = self . limit - self . _pos chunk = chunk_size while to_read > 0 : chunk = min ( to_read , chunk ) self . read ( chunk ) to_read -= chunk
Exhaust the stream . This consumes all the data left until the limit is reached .
11,456
def read ( self , size = None ) : if self . _pos >= self . limit : return self . on_exhausted ( ) if size is None or size == - 1 : size = self . limit to_read = min ( self . limit - self . _pos , size ) try : read = self . _read ( to_read ) except ( IOError , ValueError ) : return self . on_disconnect ( ) if to_read and len ( read ) != to_read : return self . on_disconnect ( ) self . _pos += len ( read ) return read
Read size bytes or if size is not provided everything is read .
11,457
def readline ( self , size = None ) : if self . _pos >= self . limit : return self . on_exhausted ( ) if size is None : size = self . limit - self . _pos else : size = min ( size , self . limit - self . _pos ) try : line = self . _readline ( size ) except ( ValueError , IOError ) : return self . on_disconnect ( ) if size and not line : return self . on_disconnect ( ) self . _pos += len ( line ) return line
Reads one line from the stream .
11,458
def rebuild ( self ) : self . markForRebuild ( False ) self . _textData = [ ] if ( self . rebuildBlocked ( ) ) : return scene = self . scene ( ) if ( not scene ) : return if ( scene . currentMode ( ) == scene . Mode . Month ) : self . rebuildMonth ( ) elif ( scene . currentMode ( ) in ( scene . Mode . Day , scene . Mode . Week ) ) : self . rebuildDay ( )
Rebuilds the current item in the scene .
11,459
def rebuildDay ( self ) : scene = self . scene ( ) if ( not scene ) : return start_date = self . dateStart ( ) end_date = self . dateEnd ( ) min_date = scene . minimumDate ( ) max_date = scene . maximumDate ( ) if ( not ( min_date <= end_date and start_date <= max_date ) ) : self . hide ( ) self . setPath ( QPainterPath ( ) ) return if ( start_date < min_date ) : start_date = min_date start_inrange = False else : start_inrange = True if ( max_date < end_date ) : end_date = max_date end_inrange = False else : end_inrange = True path = QPainterPath ( ) self . setPos ( 0 , 0 ) pad = 2 offset = 18 height = 16 if ( not self . isAllDay ( ) ) : start_dtime = QDateTime ( self . dateStart ( ) , self . timeStart ( ) ) end_dtime = QDateTime ( self . dateStart ( ) , self . timeEnd ( ) . addSecs ( - 30 * 60 ) ) start_rect = scene . dateTimeRect ( start_dtime ) end_rect = scene . dateTimeRect ( end_dtime ) left = start_rect . left ( ) + pad top = start_rect . top ( ) + pad right = start_rect . right ( ) - pad bottom = end_rect . bottom ( ) - pad path . moveTo ( left , top ) path . lineTo ( right , top ) path . lineTo ( right , bottom ) path . lineTo ( left , bottom ) path . lineTo ( left , top ) data = ( left + 6 , top + 6 , right - left - 12 , bottom - top - 12 , Qt . AlignTop | Qt . AlignLeft , '%s - %s\n(%s)' % ( self . timeStart ( ) . toString ( 'h:mmap' ) [ : - 1 ] , self . timeEnd ( ) . toString ( 'h:mmap' ) , self . title ( ) ) ) self . _textData . append ( data ) self . setPath ( path ) self . show ( )
Rebuilds the current item in day mode .
11,460
def validatePage ( self ) : widgets = self . propertyWidgetMap ( ) failed = '' for prop , widget in widgets . items ( ) : val , success = projexui . widgetValue ( widget ) if success : if not val and not ( prop . type == 'bool' and val is False ) : if prop . default : val = prop . default elif prop . required : msg = '{0} is a required value' . format ( prop . label ) failed = msg break elif prop . regex and not re . match ( prop . regex , nativestring ( val ) ) : msg = '{0} needs to be in the format {1}' . format ( prop . label , prop . regex ) failed = msg break prop . value = val else : msg = 'Failed to get a proper value for {0}' . format ( prop . label ) failed = msg break if failed : QtGui . QMessageBox . warning ( None , 'Properties Failed' , failed ) return False return True
Validates the page against the scaffold information setting the values along the way .
11,461
def save ( self ) : enabled = self . checkState ( 0 ) == QtCore . Qt . Checked self . _element . set ( 'name' , nativestring ( self . text ( 0 ) ) ) self . _element . set ( 'enabled' , nativestring ( enabled ) ) for child in self . children ( ) : child . save ( )
Saves the state for this item to the scaffold .
11,462
def update ( self , enabled = None ) : if enabled is None : enabled = self . checkState ( 0 ) == QtCore . Qt . Checked elif not enabled or self . _element . get ( 'enabled' , 'True' ) != 'True' : self . setCheckState ( 0 , QtCore . Qt . Unchecked ) else : self . setCheckState ( 0 , QtCore . Qt . Checked ) if enabled : self . setForeground ( 0 , QtGui . QBrush ( ) ) else : self . setForeground ( 0 , QtGui . QBrush ( QtGui . QColor ( 'lightGray' ) ) ) for child in self . children ( ) : child . update ( enabled )
Updates this item based on the interface .
11,463
def initializePage ( self ) : tree = self . uiStructureTREE tree . blockSignals ( True ) tree . setUpdatesEnabled ( False ) self . uiStructureTREE . clear ( ) xstruct = self . scaffold ( ) . structure ( ) self . _structure = xstruct for xentry in xstruct : XScaffoldElementItem ( tree , xentry ) tree . blockSignals ( False ) tree . setUpdatesEnabled ( True )
Initializes the page based on the current structure information .
11,464
def validatePage ( self ) : path = self . uiOutputPATH . filepath ( ) for item in self . uiStructureTREE . topLevelItems ( ) : item . save ( ) try : self . scaffold ( ) . build ( path , self . _structure ) except Exception , err : QtGui . QMessageBox . critical ( None , 'Error Occurred' , nativestring ( err ) ) return False return True
Finishes up the structure information for this wizard by building the scaffold .
11,465
def rebuild ( self ) : plugins . init ( ) self . blockSignals ( True ) self . setUpdatesEnabled ( False ) if ( self . _editor ) : self . _editor . close ( ) self . _editor . setParent ( None ) self . _editor . deleteLater ( ) self . _editor = None plugin_class = plugins . widgets . get ( self . _columnType ) if ( plugin_class ) : self . _editor = plugin_class ( self ) self . layout ( ) . addWidget ( self . _editor ) self . blockSignals ( False ) self . setUpdatesEnabled ( True )
Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit .
11,466
def closeContentsWidget ( self ) : widget = self . currentContentsWidget ( ) if ( not widget ) : return widget . close ( ) widget . setParent ( None ) widget . deleteLater ( )
Closes the current contents widget .
11,467
def copyText ( self ) : view = self . currentWebView ( ) QApplication . clipboard ( ) . setText ( view . page ( ) . selectedText ( ) )
Copies the selected text to the clipboard .
11,468
def findPrev ( self ) : text = self . uiFindTXT . text ( ) view = self . currentWebView ( ) options = QWebPage . FindWrapsAroundDocument options |= QWebPage . FindBackward if ( self . uiCaseSensitiveCHK . isChecked ( ) ) : options |= QWebPage . FindCaseSensitively view . page ( ) . findText ( text , options )
Looks for the previous occurance of the current search text .
11,469
def refreshFromIndex ( self ) : item = self . uiIndexTREE . currentItem ( ) if ( not item ) : return self . gotoUrl ( item . toolTip ( 0 ) )
Refreshes the documentation from the selected index item .
11,470
def refreshContents ( self ) : item = self . uiContentsTREE . currentItem ( ) if not isinstance ( item , XdkEntryItem ) : return item . load ( ) url = item . url ( ) if url : self . gotoUrl ( url )
Refreshes the contents tab with the latest selection from the browser .
11,471
def refreshUi ( self ) : widget = self . uiContentsTAB . currentWidget ( ) is_content = isinstance ( widget , QWebView ) if is_content : self . _currentContentsIndex = self . uiContentsTAB . currentIndex ( ) history = widget . page ( ) . history ( ) else : history = None self . uiBackACT . setEnabled ( is_content and history . canGoBack ( ) ) self . uiForwardACT . setEnabled ( is_content and history . canGoForward ( ) ) self . uiHomeACT . setEnabled ( is_content ) self . uiNewTabACT . setEnabled ( is_content ) self . uiCopyTextACT . setEnabled ( is_content ) self . uiCloseTabACT . setEnabled ( is_content and self . uiContentsTAB . count ( ) > 2 ) for i in range ( 1 , self . uiContentsTAB . count ( ) ) : widget = self . uiContentsTAB . widget ( i ) self . uiContentsTAB . setTabText ( i , widget . title ( ) )
Refreshes the interface based on the current settings .
11,472
def search ( self ) : QApplication . instance ( ) . setOverrideCursor ( Qt . WaitCursor ) terms = nativestring ( self . uiSearchTXT . text ( ) ) html = [ ] entry_html = '<a href="%(url)s">%(title)s</a><br/>' '<small>%(url)s</small>' for i in range ( self . uiContentsTREE . topLevelItemCount ( ) ) : item = self . uiContentsTREE . topLevelItem ( i ) results = item . search ( terms ) results . sort ( lambda x , y : cmp ( y [ 'strength' ] , x [ 'strength' ] ) ) for item in results : html . append ( entry_html % item ) if ( not html ) : html . append ( '<b>No results were found for %s</b>' % terms ) self . uiSearchWEB . setHtml ( SEARCH_HTML % '<br/><br/>' . join ( html ) ) QApplication . instance ( ) . restoreOverrideCursor ( )
Looks up the current search terms from the xdk files that are loaded .
11,473
def clear ( self ) : "Removes all entries from the config map" self . _pb . IntMap . clear ( ) self . _pb . StringMap . clear ( ) self . _pb . FloatMap . clear ( ) self . _pb . BoolMap . clear ( )
Removes all entries from the config map
11,474
def keys ( self ) : "Returns a list of ConfigMap keys." return ( list ( self . _pb . IntMap . keys ( ) ) + list ( self . _pb . StringMap . keys ( ) ) + list ( self . _pb . FloatMap . keys ( ) ) + list ( self . _pb . BoolMap . keys ( ) ) )
Returns a list of ConfigMap keys .
11,475
def values ( self ) : "Returns a list of ConfigMap values." return ( list ( self . _pb . IntMap . values ( ) ) + list ( self . _pb . StringMap . values ( ) ) + list ( self . _pb . FloatMap . values ( ) ) + list ( self . _pb . BoolMap . values ( ) ) )
Returns a list of ConfigMap values .
11,476
def iteritems ( self ) : "Returns an iterator over the items of ConfigMap." return chain ( self . _pb . StringMap . items ( ) , self . _pb . IntMap . items ( ) , self . _pb . FloatMap . items ( ) , self . _pb . BoolMap . items ( ) )
Returns an iterator over the items of ConfigMap .
11,477
def itervalues ( self ) : "Returns an iterator over the values of ConfigMap." return chain ( self . _pb . StringMap . values ( ) , self . _pb . IntMap . values ( ) , self . _pb . FloatMap . values ( ) , self . _pb . BoolMap . values ( ) )
Returns an iterator over the values of ConfigMap .
11,478
def iterkeys ( self ) : "Returns an iterator over the keys of ConfigMap." return chain ( self . _pb . StringMap . keys ( ) , self . _pb . IntMap . keys ( ) , self . _pb . FloatMap . keys ( ) , self . _pb . BoolMap . keys ( ) )
Returns an iterator over the keys of ConfigMap .
11,479
def pop ( self , key , default = None ) : if key not in self : if default is not None : return default raise KeyError ( key ) for map in [ self . _pb . IntMap , self . _pb . FloatMap , self . _pb . StringMap , self . _pb . BoolMap ] : if key in map . keys ( ) : return map . pop ( key )
Remove specified key and return the corresponding value . If key is not found default is returned if given otherwise KeyError is raised .
11,480
def interrupt ( self ) : if self . _database and self . _databaseThreadId : try : self . _database . interrupt ( self . _databaseThreadId ) except AttributeError : pass self . _database = None self . _databaseThreadId = 0
Interrupts the current database from processing .
11,481
def waitUntilFinished ( self ) : QtCore . QCoreApplication . processEvents ( ) while self . isLoading ( ) : QtCore . QCoreApplication . processEvents ( )
Processes the main thread until the loading process has finished . This is a way to force the main thread to be synchronous in its execution .
11,482
def assignAlignment ( self , action ) : if self . _actions [ 'align_left' ] == action : self . setAlignment ( Qt . AlignLeft ) elif self . _actions [ 'align_right' ] == action : self . setAlignment ( Qt . AlignRight ) elif self . _actions [ 'align_center' ] == action : self . setAlignment ( Qt . AlignHCenter ) else : self . setAlignment ( Qt . AlignJustify )
Sets the current alignment for the editor .
11,483
def assignFont ( self ) : font = self . currentFont ( ) font . setFamily ( self . _fontPickerWidget . currentFamily ( ) ) font . setPointSize ( self . _fontPickerWidget . pointSize ( ) ) self . setCurrentFont ( font )
Assigns the font family and point size settings from the font picker widget .
11,484
def refreshUi ( self ) : font = self . currentFont ( ) for name in ( 'underline' , 'bold' , 'italic' , 'strikeOut' ) : getter = getattr ( font , name ) act = self . _actions [ name ] act . blockSignals ( True ) act . setChecked ( getter ( ) ) act . blockSignals ( False )
Matches the UI state to the current cursor positioning .
11,485
def refreshAlignmentUi ( self ) : align = self . alignment ( ) for name , value in ( ( 'align_left' , Qt . AlignLeft ) , ( 'align_right' , Qt . AlignRight ) , ( 'align_center' , Qt . AlignHCenter ) , ( 'align_justify' , Qt . AlignJustify ) ) : act = self . _actions [ name ] act . blockSignals ( True ) act . setChecked ( value == align ) act . blockSignals ( False )
Refreshes the alignment UI information .
11,486
def updateFontPicker ( self ) : font = self . currentFont ( ) self . _fontPickerWidget . setPointSize ( font . pointSize ( ) ) self . _fontPickerWidget . setCurrentFamily ( font . family ( ) )
Updates the font picker widget to the current font settings .
11,487
def startDrag ( self , data ) : if not data : return widget = self . scene ( ) . chartWidget ( ) drag = QDrag ( widget ) drag . setMimeData ( data ) drag . exec_ ( )
Starts dragging information from this chart widget based on the dragData associated with this item .
11,488
def adjustMargins ( self ) : y = 0 height = 0 if self . _titleLabel . text ( ) : height += self . _titleLabel . height ( ) + 3 y += height if self . _subTitleLabel . text ( ) : self . _subTitleLabel . move ( 0 , y ) height += self . _subTitleLabel . height ( ) + 3 self . setContentsMargins ( 0 , height , 0 , 0 )
Adjusts the margins to incorporate enough room for the widget s title and sub - title .
11,489
def nextId ( self ) : if self . _nextId is not None : return self . _nextId wizard = self . wizard ( ) curr_id = wizard . currentId ( ) all_ids = wizard . pageIds ( ) try : return all_ids [ all_ids . index ( curr_id ) + 1 ] except IndexError : return - 1
Returns the next id for this page . By default it will provide the next id from the wizard but this method can be overloaded to create a custom path . If - 1 is returned then it will be considered the final page .
11,490
def setSubTitle ( self , title ) : self . _subTitleLabel . setText ( title ) self . _subTitleLabel . adjustSize ( ) self . adjustMargins ( )
Sets the sub - title for this page to the inputed title .
11,491
def setTitle ( self , title ) : self . _titleLabel . setText ( title ) self . _titleLabel . adjustSize ( ) self . adjustMargins ( )
Sets the title for this page to the inputed title .
11,492
def adjustSize ( self ) : super ( XOverlayWizard , self ) . adjustSize ( ) page_size = self . pageSize ( ) x = ( self . width ( ) - page_size . width ( ) ) / 2 y = ( self . height ( ) - page_size . height ( ) ) / 2 btn_height = max ( [ btn . height ( ) for btn in self . _buttons . values ( ) ] ) curr_page = self . currentPage ( ) for page in self . _pages . values ( ) : page . resize ( page_size . width ( ) , page_size . height ( ) - btn_height - 6 ) if page == curr_page : page . move ( x , y ) else : page . move ( self . width ( ) , y ) y += page_size . height ( ) - btn_height left_btns = ( self . _buttons [ self . WizardButton . HelpButton ] , self . _buttons [ self . WizardButton . BackButton ] ) for btn in left_btns : if btn . isVisible ( ) : btn . move ( x , y ) btn . raise_ ( ) x += btn . width ( ) + 6 x = self . width ( ) - ( self . width ( ) - page_size . width ( ) ) / 2 for key in reversed ( sorted ( self . _buttons . keys ( ) ) ) : btn = self . _buttons [ key ] if not btn . isVisible ( ) or btn in left_btns : continue btn . move ( x - btn . width ( ) , y ) btn . raise_ ( ) x -= btn . width ( ) + 6
Adjusts the size of this wizard and its page contents to the inputed size .
11,493
def canGoBack ( self ) : try : backId = self . _navigation . index ( self . currentId ( ) ) - 1 if backId >= 0 : self . _navigation [ backId ] else : return False except StandardError : return False else : return True
Returns whether or not this wizard can move forward .
11,494
def pageSize ( self ) : page_size = self . fixedPageSize ( ) if page_size . isEmpty ( ) : w = self . width ( ) - 80 h = self . height ( ) - 80 min_w = self . minimumPageSize ( ) . width ( ) min_h = self . minimumPageSize ( ) . height ( ) max_w = self . maximumPageSize ( ) . width ( ) max_h = self . maximumPageSize ( ) . height ( ) page_size = QtCore . QSize ( min ( max ( min_w , w ) , max_w ) , min ( max ( min_h , h ) , max_h ) ) return page_size
Returns the current page size for this wizard .
11,495
def restart ( self ) : for page in self . _pages . values ( ) : page . hide ( ) pageId = self . startId ( ) try : first_page = self . _pages [ pageId ] except KeyError : return self . _currentId = pageId self . _navigation = [ pageId ] page_size = self . pageSize ( ) x = ( self . width ( ) - page_size . width ( ) ) / 2 y = ( self . height ( ) - page_size . height ( ) ) / 2 first_page . move ( self . width ( ) + first_page . width ( ) , y ) first_page . show ( ) anim_out = QtCore . QPropertyAnimation ( self ) anim_out . setTargetObject ( first_page ) anim_out . setPropertyName ( 'pos' ) anim_out . setStartValue ( first_page . pos ( ) ) anim_out . setEndValue ( QtCore . QPoint ( x , y ) ) anim_out . setDuration ( self . animationSpeed ( ) ) anim_out . setEasingCurve ( QtCore . QEasingCurve . Linear ) anim_out . finished . connect ( anim_out . deleteLater ) self . _buttons [ self . WizardButton . BackButton ] . setVisible ( False ) self . _buttons [ self . WizardButton . NextButton ] . setVisible ( self . canGoForward ( ) ) self . _buttons [ self . WizardButton . CommitButton ] . setVisible ( first_page . isCommitPage ( ) ) self . _buttons [ self . WizardButton . FinishButton ] . setVisible ( first_page . isFinalPage ( ) ) self . adjustSize ( ) first_page . initializePage ( ) self . currentIdChanged . emit ( pageId ) anim_out . start ( )
Restarts the whole wizard from the beginning .
11,496
def removePage ( self , pageId ) : try : self . _pages [ pageId ] . deleteLater ( ) del self . _pages [ pageId ] except KeyError : pass
Removes the inputed page from this wizard .
11,497
def setButton ( self , which , button ) : try : self . _buttons [ which ] . deleteLater ( ) except KeyError : pass button . setParent ( self ) self . _buttons [ which ] = button
Sets the button for this wizard for the inputed type .
11,498
def setButtonText ( self , which , text ) : try : self . _buttons [ which ] . setText ( text ) except KeyError : pass
Sets the display text for the inputed button to the given text .
11,499
def setPage ( self , pageId , page ) : page . setParent ( self ) if self . property ( "useShadow" ) is not False : effect = QtGui . QGraphicsDropShadowEffect ( page ) effect . setColor ( QtGui . QColor ( 'black' ) ) effect . setBlurRadius ( 50 ) effect . setOffset ( 0 , 0 ) page . setGraphicsEffect ( effect ) self . _pages [ pageId ] = page if self . _startId == - 1 : self . _startId = pageId
Sets the page and id for the given page vs . auto - constructing it . This will allow the developer to create a custom order for IDs .