idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
11,300 | 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 . | 114 | 40 |
11,301 | 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 . | 116 | 18 |
11,302 | 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 . | 89 | 9 |
11,303 | def sync ( self , recursive = False ) : self . syncTree ( recursive = recursive ) self . syncView ( recursive = recursive ) | Syncs the information from this item to the tree and view . | 28 | 13 |
11,304 | def syncTree ( self , recursive = False , blockSignals = True ) : tree = self . treeWidget ( ) # sync the tree information 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 . | 163 | 11 |
11,305 | def syncView ( self , recursive = False ) : # update the view widget 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 ( ) # collect the items to work on items = [ self ] if recursive : items += list ( self . children ( recursive = True ) ) for item in items : # grab the view item from the gantt item vitem = item . viewItem ( ) if not vitem . scene ( ) : scene . addItem ( vitem ) # make sure the item should be visible 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 ( ) # check to see if this item is hidden 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 # determine the % off from the length based on this items time if not item . isAllDay ( ) : full_day = 24 * 60 * 60 # full days worth of seconds # determine the start offset 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 # determine the end offset end = item . timeEnd ( ) end_day = ( end . hour ( ) * 60 * 60 ) end_day += ( start . minute ( ) * 60 ) end_day += ( start . second ( ) + 1 ) # forces at least 1 sec offset_end = ( ( full_day - end_day ) / float ( full_day ) ) offset_end *= cell_w # update the xpos and widths 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 ) # setup standard properties 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 . | 760 | 11 |
11,306 | 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 . | 108 | 6 |
11,307 | async def leader ( self ) : response = await self . _api . get ( "/v1/status/leader" ) if response . status == 200 : return response . body | Returns the current Raft leader | 38 | 6 |
11,308 | 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 | 42 | 7 |
11,309 | 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 . | 125 | 17 |
11,310 | def toggleCollapseAfter ( self ) : if ( self . isCollapsed ( ) ) : self . uncollapse ( ) else : self . collapse ( XSplitterHandle . CollapseDirection . After ) | Collapses the splitter after this handle . | 45 | 9 |
11,311 | def toggleCollapseBefore ( self ) : if ( self . isCollapsed ( ) ) : self . uncollapse ( ) else : self . collapse ( XSplitterHandle . CollapseDirection . Before ) | Collapses the splitter before this handle . | 45 | 9 |
11,312 | def reset ( self ) : dataSet = self . dataSet ( ) if ( not dataSet ) : dataSet = XScheme ( ) dataSet . reset ( ) | Resets the colors to the default settings . | 36 | 9 |
11,313 | def ensureVisible ( self ) : # make sure all parents are visible 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 . | 51 | 25 |
11,314 | 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 . | 53 | 13 |
11,315 | def _safe_urlsplit ( s ) : rv = urlparse . urlsplit ( s ) # we have to check rv[2] here and not rv[1] as rv[1] will be # an empty bytestring in case no domain was given. 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 . | 129 | 36 |
11,316 | 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 . | 156 | 9 |
11,317 | 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 . | 63 | 10 |
11,318 | 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 . | 67 | 17 |
11,319 | 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 | 28 | 26 |
11,320 | 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 | 53 | 13 |
11,321 | 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 | 103 | 16 |
11,322 | 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 . | 56 | 20 |
11,323 | 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 . | 31 | 30 |
11,324 | 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 . | 56 | 28 |
11,325 | 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 . | 80 | 11 |
11,326 | 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 . | 62 | 20 |
11,327 | def showPopup ( self ) : if not self . isCheckable ( ) : return super ( XComboBox , self ) . showPopup ( ) if not self . isVisible ( ) : return # update the checkable widget popup 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 . | 187 | 18 |
11,328 | 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 ) # only allow checking for items with text else : item . setCheckable ( True ) item . setFlags ( flags | Qt . ItemIsUserCheckable ) | Updates the items to reflect the current check state system . | 120 | 12 |
11,329 | 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 . | 133 | 13 |
11,330 | def process ( self , metrics , config ) : LOG . debug ( "Process called" ) for metric in metrics : metric . tags [ "instance-id" ] = config [ "instance-id" ] return metrics | Processes metrics . | 45 | 4 |
11,331 | 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 . | 37 | 12 |
11,332 | def paintEvent ( self , event ) : if self . isHoverable ( ) and self . icon ( ) . isNull ( ) : return # initialize the painter painter = QtGui . QStylePainter ( ) painter . begin ( self ) try : option = QtGui . QStyleOptionToolButton ( ) self . initStyleOption ( option ) # generate the scaling and rotating factors 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 . | 218 | 10 |
11,333 | 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 . | 49 | 11 |
11,334 | 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 . | 54 | 9 |
11,335 | 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 . | 81 | 7 |
11,336 | 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 . | 61 | 7 |
11,337 | 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 . | 47 | 25 |
11,338 | 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 | 105 | 10 |
11,339 | def main ( ) : # Wrap sys stdout for python 2, so print can understand unicode. 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 . | 118 | 7 |
11,340 | 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 . | 183 | 34 |
11,341 | 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 . | 56 | 13 |
11,342 | def _save_single_attr ( self , entity , value = None , schema = None , create_nulls = False , extra = { } ) : # If schema is not many-to-one, the value is saved to the corresponding # Attr instance (which is created or updated). 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 . | 181 | 15 |
11,343 | 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 . | 41 | 13 |
11,344 | def by_id ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _get ( path ) | get adapter data by its id . | 35 | 7 |
11,345 | 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 . | 71 | 6 |
11,346 | 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 . | 74 | 5 |
11,347 | def by_name ( self , name , archived = False , limit = None , page = None ) : # this only works with the exact name 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 . | 56 | 19 |
11,348 | def delete ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _delete ( path ) | delete a time entry . | 33 | 5 |
11,349 | 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 . | 62 | 8 |
11,350 | def start ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _put ( path ) | start a specific tracker . | 33 | 5 |
11,351 | def stop ( self , id ) : path = partial ( _path , self . adapter ) path = path ( id ) return self . _delete ( path ) | stop the tracker . | 33 | 4 |
11,352 | 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 . | 67 | 12 |
11,353 | 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 . | 47 | 17 |
11,354 | 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 . | 68 | 9 |
11,355 | 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 . | 70 | 7 |
11,356 | def rejectEdit ( self ) : if self . _lineEdit : self . _lineEdit . hide ( ) self . editingCancelled . emit ( ) | Cancels the edit for this label . | 33 | 9 |
11,357 | 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 . | 31 | 15 |
11,358 | 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 . | 43 | 10 |
11,359 | 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 . | 63 | 18 |
11,360 | 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 . | 63 | 14 |
11,361 | 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 # wew, strings and bytes, what's a guy to do! 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 | 182 | 8 |
11,362 | 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 . | 165 | 10 |
11,363 | 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 . | 59 | 14 |
11,364 | 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 | 126 | 7 |
11,365 | def extract_images ( self , imageQuery , imageCount = 100 , destinationFolder = './' , threadCount = 4 ) : # Initialize the chrome driver self . _initialize_chrome_driver ( ) # Initialize the image download parameters self . _imageQuery = imageQuery self . _imageCount = imageCount self . _destinationFolder = destinationFolder self . _threadCount = threadCount self . _get_image_urls ( ) self . _create_storage_folder ( ) self . _download_images ( ) # Print the final message specifying the total count of images downloaded print ( colored ( '\n\nImages Downloaded: ' + str ( self . _imageCounter ) + ' of ' + str ( self . _imageCount ) + ' in ' + format_timespan ( self . _downloadProgressBar . data ( ) [ 'total_seconds_elapsed' ] ) + '\n' , 'green' ) ) # Terminate the chrome instance self . _chromeDriver . close ( ) self . _reset_helper_variables ( ) | Searches across Google Image Search with the specified image query and downloads the specified count of images | 231 | 19 |
11,366 | 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 ( ) # Slice the list of image URLs to contain the exact number of image # URLs that have been requested # self._imageURLs = self._imageURLs[:self._imageCount] print ( colored ( 'Image URLs retrieved.' , 'green' ) ) | Retrieves the image URLS corresponding to the image query | 190 | 12 |
11,367 | 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 | 122 | 9 |
11,368 | def _page_scroll_down ( self ) : # Scroll down to request the next set of images self . _chromeDriver . execute_script ( 'window.scroll(0, document.body.clientHeight)' ) # Wait for the images to load completely time . sleep ( self . WAIT_TIME ) # Check if the button - 'Show More Results' is visible # If yes, click it and request more messages # This step helps is avoiding duplicate image URLS from being captured try : self . _chromeDriver . find_element_by_id ( 'smb' ) . click ( ) except ElementNotVisibleException as error : pass | Scrolls down to get the next set of images | 136 | 10 |
11,369 | def _download_images ( self ) : print ( '\nDownloading Images for the Query: ' + self . _imageQuery ) try : self . _initialize_progress_bar ( ) # Initialize and assign work to the threads in the threadpool threadPool = Pool ( self . _threadCount ) threadPool . map ( self . _download_image , self . _imageURLs ) threadPool . close ( ) threadPool . join ( ) # Download each image individually # [self._download_image(imageURL) for imageURL in self._imageURLs] 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 | 153 | 30 |
11,370 | 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 | 77 | 5 |
11,371 | def _download_image ( self , imageURL ) : # If the required count of images have been download, # refrain from downloading the remainder of the images if ( self . _imageCounter >= self . _imageCount ) : return try : imageResponse = requests . get ( imageURL ) # Generate image file name as <_imageQuery>_<_imageCounter>.<extension> 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 | 258 | 10 |
11,372 | def increment ( self , amount = 1 ) : self . _primaryProgressBar . setValue ( self . value ( ) + amount ) QApplication . instance ( ) . processEvents ( ) | Increments the main progress bar by amount . | 39 | 9 |
11,373 | def incrementSub ( self , amount = 1 ) : self . _subProgressBar . setValue ( self . subValue ( ) + amount ) QApplication . instance ( ) . processEvents ( ) | Increments the sub - progress bar by amount . | 41 | 10 |
11,374 | 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 . | 70 | 16 |
11,375 | def recalculate ( self ) : if not ( self . isVisible ( ) and self . renderer ( ) ) : return # update dynamic range if self . _dataChanged : for axis in self . axes ( ) : if axis . useDynamicRange ( ) : axis . calculateRange ( self . values ( axis . name ( ) ) ) self . _dataChanged = False # recalculate the main grid 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 ) # calculate the main view 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 ) # recalculate the xaxis if xaxis and self . showXAxis ( ) and renderer . showXAxis ( ) : view = self . uiXAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , rect . width ( ) , view . height ( ) ) scene . invalidate ( ) # render the yaxis if yaxis and self . showYAxis ( ) and renderer . showYAxis ( ) : view = self . uiYAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , view . width ( ) , rect . height ( ) ) scene . invalidate ( ) # recalculate the items renderer . calculateDatasets ( chart_scene , self . axes ( ) , self . datasets ( ) ) chart_scene . invalidate ( ) | Recalculates the information for this chart . | 455 | 10 |
11,376 | 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 . | 224 | 11 |
11,377 | 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 | 285 | 9 |
11,378 | 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 | 80 | 7 |
11,379 | 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 | 69 | 7 |
11,380 | 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 ) # update the interface 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 . | 171 | 11 |
11,381 | 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 . | 56 | 16 |
11,382 | 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 . | 40 | 13 |
11,383 | def handleProfileChange ( self ) : # restore the profile settings 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 . | 66 | 9 |
11,384 | def showOptionsMenu ( self ) : point = QPoint ( 0 , self . _optionsButton . height ( ) ) global_point = self . _optionsButton . mapToGlobal ( point ) # prompt the custom context menu if self . optionsMenuPolicy ( ) == Qt . CustomContextMenu : if not self . signalsBlocked ( ) : self . optionsMenuRequested . emit ( global_point ) return # use the default context menu 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 . | 111 | 36 |
11,385 | 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 . | 107 | 17 |
11,386 | def reject ( self ) : if self . hideWindow ( ) : self . hideWindow ( ) . show ( ) self . close ( ) self . deleteLater ( ) | Rejects the snapshot and closes the widget . | 35 | 10 |
11,387 | def save ( self ) : # close down the snapshot widget if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) self . hide ( ) QApplication . processEvents ( ) time . sleep ( 1 ) # create the pixmap to save 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 . | 215 | 10 |
11,388 | 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 . | 44 | 12 |
11,389 | 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 . | 280 | 18 |
11,390 | 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 ( ) # Keyphrases table table = keyphrases_table ( keyphrases , texts , similarity_measure , synonimizer , language ) # Dictionary { "keyphrase" => set(names of texts containing "keyphrase") } keyphrase_texts = { keyphrase : set ( [ text for text in texts if table [ keyphrase ] [ text ] >= relevance_threshold ] ) for keyphrase in keyphrases } # Initializing the graph object with nodes 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 } # Removing nodes with small support after we've numbered all nodes graph [ "nodes" ] = [ n for n in graph [ "nodes" ] if len ( keyphrase_texts [ n [ "label" ] ] ) >= support_threshold ] # Creating edges # NOTE(msdubov): permutations(), unlike combinations(), treats (1,2) and (2,1) as different 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 . | 549 | 16 |
11,391 | 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 . | 109 | 20 |
11,392 | def dropEvent ( self , event ) : url = event . mimeData ( ) . urls ( ) [ 0 ] url_path = nativestring ( url . toString ( ) ) # download an icon from the web 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 . | 160 | 6 |
11,393 | 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 . | 81 | 12 |
11,394 | 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 | 146 | 5 |
11,395 | 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 | 90 | 10 |
11,396 | def updateRecordValues ( self ) : record = self . record ( ) if not record : return # update the record information 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 ) # update the record state information 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 . | 175 | 12 |
11,397 | def extract_bits ( self , val ) : # Step one, extract the Most significant 4 bits of the CRC register thisval = self . high >> 4 # XOR in the Message Data into the extracted bits thisval = thisval ^ val # Shift the CRC Register left 4 bits self . high = ( self . high << 4 ) | ( self . low >> 4 ) self . high = self . high & constants . BYTEMASK # force char self . low = self . low << 4 self . low = self . low & constants . BYTEMASK # force char # Do the table lookups and XOR the result into the CRC tables self . high = self . high ^ self . LookupHigh [ thisval ] self . high = self . high & constants . BYTEMASK # force char 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 . | 204 | 16 |
11,398 | def run ( self , message ) : for value in message : self . update ( value ) return [ self . low , self . high ] | Calculates a CRC | 29 | 5 |
11,399 | 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 | 250 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.