idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
238,600 | def setLocation ( self , location ) : if not location or not isinstance ( location , Location ) : raise ValueError ( "setLocation expected a Location object" ) self . x = location . x self . y = location . y return self | Change the upper left - hand corner to a new Location | 51 | 11 |
238,601 | def contains ( self , point_or_region ) : if isinstance ( point_or_region , Location ) : return ( self . x < point_or_region . x < self . x + self . w ) and ( self . y < point_or_region . y < self . y + self . h ) elif isinstance ( point_or_region , Region ) : return ( ( self . x < point_or_region . getX ( ) < self . x + self . w ) and ( self . y < point_or_region . getY ( ) < self . y + self . h ) and ( self . x < point_or_region . getX ( ) + point_or_region . getW ( ) < self . x + self . w ) and ( self . y < point_or_region . getY ( ) + point_or_region . getH ( ) < self . y + self . h ) ) else : raise TypeError ( "Unrecognized argument type for contains()" ) | Checks if point_or_region is within this region | 224 | 12 |
238,602 | def morphTo ( self , region ) : if not region or not isinstance ( region , Region ) : raise TypeError ( "morphTo expected a Region object" ) self . setROI ( region ) return self | Change shape of this region to match the given Region object | 45 | 11 |
238,603 | def getCenter ( self ) : return Location ( self . x + ( self . w / 2 ) , self . y + ( self . h / 2 ) ) | Return the Location of the center of this region | 34 | 9 |
238,604 | def getBottomRight ( self ) : return Location ( self . x + self . w , self . y + self . h ) | Return the Location of the bottom right corner of this region | 27 | 11 |
238,605 | def offset ( self , location , dy = 0 ) : if not isinstance ( location , Location ) : # Assume variables passed were dx,dy location = Location ( location , dy ) r = Region ( self . x + location . x , self . y + location . y , self . w , self . h ) . clipRegionToScreen ( ) if r is None : raise ValueError ( "Specified region is not visible on any screen" ) return None return r | Returns a new Region offset from this one by location | 99 | 10 |
238,606 | def grow ( self , width , height = None ) : if height is None : return self . nearby ( width ) else : return Region ( self . x - width , self . y - height , self . w + ( 2 * width ) , self . h + ( 2 * height ) ) . clipRegionToScreen ( ) | Expands the region by width on both sides and height on the top and bottom . | 68 | 17 |
238,607 | def nearby ( self , expand = 50 ) : return Region ( self . x - expand , self . y - expand , self . w + ( 2 * expand ) , self . h + ( 2 * expand ) ) . clipRegionToScreen ( ) | Returns a new Region that includes the nearby neighbourhood of the the current region . | 52 | 15 |
238,608 | def left ( self , expand = None ) : if expand == None : x = 0 y = self . y w = self . x h = self . h else : x = self . x - expand y = self . y w = expand h = self . h return Region ( x , y , w , h ) . clipRegionToScreen ( ) | Returns a new Region left of the current region with a width of expand pixels . | 73 | 16 |
238,609 | def right ( self , expand = None ) : if expand == None : x = self . x + self . w y = self . y w = self . getScreen ( ) . getBounds ( ) [ 2 ] - x h = self . h else : x = self . x + self . w y = self . y w = expand h = self . h return Region ( x , y , w , h ) . clipRegionToScreen ( ) | Returns a new Region right of the current region with a width of expand pixels . | 95 | 16 |
238,610 | def getBitmap ( self ) : return PlatformManager . getBitmapFromRect ( self . x , self . y , self . w , self . h ) | Captures screen area of this region at least the part that is on the screen | 34 | 16 |
238,611 | def debugPreview ( self , title = "Debug" ) : region = self haystack = self . getBitmap ( ) if isinstance ( region , Match ) : cv2 . circle ( haystack , ( region . getTarget ( ) . x - self . x , region . getTarget ( ) . y - self . y ) , 5 , 255 ) if haystack . shape [ 0 ] > ( Screen ( 0 ) . getBounds ( ) [ 2 ] / 2 ) or haystack . shape [ 1 ] > ( Screen ( 0 ) . getBounds ( ) [ 3 ] / 2 ) : # Image is bigger than half the screen; scale it down haystack = cv2 . resize ( haystack , ( 0 , 0 ) , fx = 0.5 , fy = 0.5 ) Image . fromarray ( haystack ) . show ( ) | Displays the region in a preview window . | 185 | 9 |
238,612 | def wait ( self , pattern , seconds = None ) : if isinstance ( pattern , ( int , float ) ) : if pattern == FOREVER : while True : time . sleep ( 1 ) # Infinite loop time . sleep ( pattern ) return None if seconds is None : seconds = self . autoWaitTimeout findFailedRetry = True timeout = time . time ( ) + seconds while findFailedRetry : while True : match = self . exists ( pattern ) if match : return match if time . time ( ) >= timeout : break path = pattern . path if isinstance ( pattern , Pattern ) else pattern findFailedRetry = self . _raiseFindFailed ( "Could not find pattern '{}'" . format ( path ) ) if findFailedRetry : time . sleep ( self . _repeatWaitTime ) return None | Searches for an image pattern in the given region given a specified timeout period | 177 | 16 |
238,613 | def waitVanish ( self , pattern , seconds = None ) : r = self . clipRegionToScreen ( ) if r is None : raise ValueError ( "Region outside all visible screens" ) return None if seconds is None : seconds = self . autoWaitTimeout if not isinstance ( pattern , Pattern ) : if not isinstance ( pattern , basestring ) : raise TypeError ( "find expected a string [image path] or Pattern object" ) pattern = Pattern ( pattern ) needle = cv2 . imread ( pattern . path ) match = True timeout = time . time ( ) + seconds while match and time . time ( ) < timeout : matcher = TemplateMatcher ( r . getBitmap ( ) ) # When needle disappears, matcher returns None match = matcher . findBestMatch ( needle , pattern . similarity ) time . sleep ( 1 / self . _defaultScanRate if self . _defaultScanRate is not None else 1 / Settings . WaitScanRate ) if match : return False | Waits until the specified pattern is not visible on screen . | 212 | 12 |
238,614 | def click ( self , target = None , modifiers = "" ) : if target is None : target = self . _lastMatch or self # Whichever one is not None target_location = None if isinstance ( target , Pattern ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , basestring ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , Match ) : target_location = target . getTarget ( ) elif isinstance ( target , Region ) : target_location = target . getCenter ( ) elif isinstance ( target , Location ) : target_location = target else : raise TypeError ( "click expected Pattern, String, Match, Region, or Location object" ) if modifiers != "" : keyboard . keyDown ( modifiers ) Mouse . moveSpeed ( target_location , Settings . MoveMouseDelay ) time . sleep ( 0.1 ) # For responsiveness if Settings . ClickDelay > 0 : time . sleep ( min ( 1.0 , Settings . ClickDelay ) ) Settings . ClickDelay = 0.0 Mouse . click ( ) time . sleep ( 0.1 ) if modifiers != 0 : keyboard . keyUp ( modifiers ) Debug . history ( "Clicked at {}" . format ( target_location ) ) | Moves the cursor to the target location and clicks the default mouse button . | 285 | 15 |
238,615 | def hover ( self , target = None ) : if target is None : target = self . _lastMatch or self # Whichever one is not None target_location = None if isinstance ( target , Pattern ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , basestring ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , Match ) : target_location = target . getTarget ( ) elif isinstance ( target , Region ) : target_location = target . getCenter ( ) elif isinstance ( target , Location ) : target_location = target else : raise TypeError ( "hover expected Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( target_location , Settings . MoveMouseDelay ) | Moves the cursor to the target location | 180 | 8 |
238,616 | def drag ( self , dragFrom = None ) : if dragFrom is None : dragFrom = self . _lastMatch or self # Whichever one is not None dragFromLocation = None if isinstance ( dragFrom , Pattern ) : dragFromLocation = self . find ( dragFrom ) . getTarget ( ) elif isinstance ( dragFrom , basestring ) : dragFromLocation = self . find ( dragFrom ) . getTarget ( ) elif isinstance ( dragFrom , Match ) : dragFromLocation = dragFrom . getTarget ( ) elif isinstance ( dragFrom , Region ) : dragFromLocation = dragFrom . getCenter ( ) elif isinstance ( dragFrom , Location ) : dragFromLocation = dragFrom else : raise TypeError ( "drag expected dragFrom to be Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( dragFromLocation , Settings . MoveMouseDelay ) time . sleep ( Settings . DelayBeforeMouseDown ) Mouse . buttonDown ( ) Debug . history ( "Began drag at {}" . format ( dragFromLocation ) ) | Starts a dragDrop operation . | 234 | 7 |
238,617 | def dropAt ( self , dragTo = None , delay = None ) : if dragTo is None : dragTo = self . _lastMatch or self # Whichever one is not None if isinstance ( dragTo , Pattern ) : dragToLocation = self . find ( dragTo ) . getTarget ( ) elif isinstance ( dragTo , basestring ) : dragToLocation = self . find ( dragTo ) . getTarget ( ) elif isinstance ( dragTo , Match ) : dragToLocation = dragTo . getTarget ( ) elif isinstance ( dragTo , Region ) : dragToLocation = dragTo . getCenter ( ) elif isinstance ( dragTo , Location ) : dragToLocation = dragTo else : raise TypeError ( "dragDrop expected dragTo to be Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( dragToLocation , Settings . MoveMouseDelay ) time . sleep ( delay if delay is not None else Settings . DelayBeforeDrop ) Mouse . buttonUp ( ) Debug . history ( "Ended drag at {}" . format ( dragToLocation ) ) | Completes a dragDrop operation | 241 | 7 |
238,618 | def dragDrop ( self , target , target2 = None , modifiers = "" ) : if modifiers != "" : keyboard . keyDown ( modifiers ) if target2 is None : dragFrom = self . _lastMatch dragTo = target else : dragFrom = target dragTo = target2 self . drag ( dragFrom ) time . sleep ( Settings . DelayBeforeDrag ) self . dropAt ( dragTo ) if modifiers != "" : keyboard . keyUp ( modifiers ) | Performs a dragDrop operation . | 96 | 7 |
238,619 | def mouseMove ( self , PSRML = None , dy = 0 ) : if PSRML is None : PSRML = self . _lastMatch or self # Whichever one is not None if isinstance ( PSRML , Pattern ) : move_location = self . find ( PSRML ) . getTarget ( ) elif isinstance ( PSRML , basestring ) : move_location = self . find ( PSRML ) . getTarget ( ) elif isinstance ( PSRML , Match ) : move_location = PSRML . getTarget ( ) elif isinstance ( PSRML , Region ) : move_location = PSRML . getCenter ( ) elif isinstance ( PSRML , Location ) : move_location = PSRML elif isinstance ( PSRML , int ) : # Assume called as mouseMove(dx, dy) offset = Location ( PSRML , dy ) move_location = Mouse . getPos ( ) . offset ( offset ) else : raise TypeError ( "doubleClick expected Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( move_location ) | Low - level mouse actions | 249 | 5 |
238,620 | def isRegionValid ( self ) : screens = PlatformManager . getScreenDetails ( ) for screen in screens : s_x , s_y , s_w , s_h = screen [ "rect" ] if self . x + self . w >= s_x and s_x + s_w >= self . x and self . y + self . h >= s_y and s_y + s_h >= self . y : # Rects overlap return True return False | Returns false if the whole region is not even partially inside any screen otherwise true | 102 | 15 |
238,621 | def clipRegionToScreen ( self ) : if not self . isRegionValid ( ) : return None screens = PlatformManager . getScreenDetails ( ) total_x , total_y , total_w , total_h = Screen ( - 1 ) . getBounds ( ) containing_screen = None for screen in screens : s_x , s_y , s_w , s_h = screen [ "rect" ] if self . x >= s_x and self . x + self . w <= s_x + s_w and self . y >= s_y and self . y + self . h <= s_y + s_h : # Region completely inside screen return self elif self . x + self . w <= s_x or s_x + s_w <= self . x or self . y + self . h <= s_y or s_y + s_h <= self . y : # Region completely outside screen continue elif self . x == total_x and self . y == total_y and self . w == total_w and self . h == total_h : # Region equals all screens, Screen(-1) return self else : # Region partially inside screen x = max ( self . x , s_x ) y = max ( self . y , s_y ) w = min ( self . w , s_w ) h = min ( self . h , s_h ) return Region ( x , y , w , h ) return None | Returns the part of the region that is visible on a screen | 316 | 12 |
238,622 | def get ( self , part ) : if part == self . MID_VERTICAL : return Region ( self . x + ( self . w / 4 ) , y , self . w / 2 , self . h ) elif part == self . MID_HORIZONTAL : return Region ( self . x , self . y + ( self . h / 4 ) , self . w , self . h / 2 ) elif part == self . MID_BIG : return Region ( self . x + ( self . w / 4 ) , self . y + ( self . h / 4 ) , self . w / 2 , self . h / 2 ) elif isinstance ( part , int ) and part >= 200 and part <= 999 : raster , row , column = str ( part ) self . setRaster ( raster , raster ) if row == raster and column == raster : return self elif row == raster : return self . getCol ( column ) elif column == raster : return self . getRow ( row ) else : return self . getCell ( row , column ) else : return self | Returns a section of the region as a new region | 238 | 10 |
238,623 | def setCenter ( self , loc ) : offset = self . getCenter ( ) . getOffset ( loc ) # Calculate offset from current center return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) ) # Move top left corner by the same offset | Move this region so it is centered on loc | 58 | 9 |
238,624 | def setTopRight ( self , loc ) : offset = self . getTopRight ( ) . getOffset ( loc ) # Calculate offset from current top right return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) ) # Move top left corner by the same offset | Move this region so its top right corner is on loc | 61 | 11 |
238,625 | def setBottomLeft ( self , loc ) : offset = self . getBottomLeft ( ) . getOffset ( loc ) # Calculate offset from current bottom left return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) ) # Move top left corner by the same offset | Move this region so its bottom left corner is on loc | 61 | 11 |
238,626 | def setBottomRight ( self , loc ) : offset = self . getBottomRight ( ) . getOffset ( loc ) # Calculate offset from current bottom right return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) ) # Move top left corner by the same offset | Move this region so its bottom right corner is on loc | 61 | 11 |
238,627 | def setSize ( self , w , h ) : self . setW ( w ) self . setH ( h ) return self | Sets the new size of the region | 27 | 8 |
238,628 | def saveScreenCapture ( self , path = None , name = None ) : bitmap = self . getBitmap ( ) target_file = None if path is None and name is None : _ , target_file = tempfile . mkstemp ( ".png" ) elif name is None : _ , tpath = tempfile . mkstemp ( ".png" ) target_file = os . path . join ( path , tfile ) else : target_file = os . path . join ( path , name + ".png" ) cv2 . imwrite ( target_file , bitmap ) return target_file | Saves the region s bitmap | 132 | 7 |
238,629 | def saveLastScreenImage ( self ) : bitmap = self . getLastScreenImage ( ) _ , target_file = tempfile . mkstemp ( ".png" ) cv2 . imwrite ( target_file , bitmap ) | Saves the last image taken on this region s screen to a temporary file | 51 | 15 |
238,630 | def onChange ( self , min_changed_pixels = None , handler = None ) : if isinstance ( min_changed_pixels , int ) and ( callable ( handler ) or handler is None ) : return self . _observer . register_event ( "CHANGE" , pattern = ( min_changed_pixels , self . getBitmap ( ) ) , handler = handler ) elif ( callable ( min_changed_pixels ) or min_changed_pixels is None ) and ( callable ( handler ) or handler is None ) : handler = min_changed_pixels or handler return self . _observer . register_event ( "CHANGE" , pattern = ( Settings . ObserveMinChangedPixels , self . getBitmap ( ) ) , handler = handler ) else : raise ValueError ( "Unsupported arguments for onChange method" ) | Registers an event to call handler when at least min_changed_pixels change in this region . | 188 | 21 |
238,631 | def isChanged ( self , min_changed_pixels , screen_state ) : r = self . clipRegionToScreen ( ) current_state = r . getBitmap ( ) diff = numpy . subtract ( current_state , screen_state ) return ( numpy . count_nonzero ( diff ) >= min_changed_pixels ) | Returns true if at least min_changed_pixels are different between screen_state and the current state . | 74 | 22 |
238,632 | def stopObserver ( self ) : self . _observer . isStopped = True self . _observer . isRunning = False | Stops this region s observer loop . | 29 | 8 |
238,633 | def getEvents ( self ) : caught_events = self . _observer . caught_events self . _observer . caught_events = [ ] for event in caught_events : self . _observer . activate_event ( event [ "name" ] ) return caught_events | Returns a list of all events that have occurred . | 60 | 10 |
238,634 | def getEvent ( self , name ) : to_return = None for event in self . _observer . caught_events : if event [ "name" ] == name : to_return = event break if to_return : self . _observer . caught_events . remove ( to_return ) self . _observer . activate_event ( to_return [ "name" ] ) return to_return | Returns the named event . | 87 | 5 |
238,635 | def setFindFailedResponse ( self , response ) : valid_responses = ( "ABORT" , "SKIP" , "PROMPT" , "RETRY" ) if response not in valid_responses : raise ValueError ( "Invalid response - expected one of ({})" . format ( ", " . join ( valid_responses ) ) ) self . _findFailedResponse = response | Set the response to a FindFailed exception in this region . Can be ABORT SKIP PROMPT or RETRY . | 86 | 26 |
238,636 | def setThrowException ( self , setting ) : if setting : self . _throwException = True self . _findFailedResponse = "ABORT" else : self . _throwException = False self . _findFailedResponse = "SKIP" | Defines whether an exception should be thrown for FindFailed operations . | 53 | 14 |
238,637 | def register_event ( self , event_type , pattern , handler ) : if event_type not in self . _supported_events : raise ValueError ( "Unsupported event type {}" . format ( event_type ) ) if event_type != "CHANGE" and not isinstance ( pattern , Pattern ) and not isinstance ( pattern , basestring ) : raise ValueError ( "Expected pattern to be a Pattern or string" ) if event_type == "CHANGE" and not ( len ( pattern ) == 2 and isinstance ( pattern [ 0 ] , int ) and isinstance ( pattern [ 1 ] , numpy . ndarray ) ) : raise ValueError ( "For \"CHANGE\" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state." ) # Create event object event = { "pattern" : pattern , "event_type" : event_type , "count" : 0 , "handler" : handler , "name" : uuid . uuid4 ( ) , "active" : True } self . _events [ event [ "name" ] ] = event return event [ "name" ] | When event_type is observed for pattern triggers handler . | 251 | 11 |
238,638 | def capture ( self , * args ) : #x=None, y=None, w=None, h=None): if len ( args ) == 0 : # Capture screen region region = self elif isinstance ( args [ 0 ] , Region ) : # Capture specified region region = args [ 0 ] elif isinstance ( args [ 0 ] , tuple ) : # Capture region defined by specified tuple region = Region ( * args [ 0 ] ) elif isinstance ( args [ 0 ] , basestring ) : # Interactive mode raise NotImplementedError ( "Interactive capture mode not defined" ) elif isinstance ( args [ 0 ] , int ) : # Capture region defined by provided x,y,w,h region = Region ( * args ) self . lastScreenImage = region . getBitmap ( ) return self . lastScreenImage | Captures the region as an image | 180 | 7 |
238,639 | def showMonitors ( cls ) : Debug . info ( "*** monitor configuration [ {} Screen(s)] ***" . format ( cls . getNumberScreens ( ) ) ) Debug . info ( "*** Primary is Screen {}" . format ( cls . primaryScreen ) ) for index , screen in enumerate ( PlatformManager . getScreenDetails ( ) ) : Debug . info ( "Screen {}: ({}, {}, {}, {})" . format ( index , * screen [ "rect" ] ) ) Debug . info ( "*** end monitor configuration ***" ) | Prints debug information about currently detected screens | 120 | 8 |
238,640 | def resetMonitors ( self ) : Debug . error ( "*** BE AWARE: experimental - might not work ***" ) Debug . error ( "Re-evaluation of the monitor setup has been requested" ) Debug . error ( "... Current Region/Screen objects might not be valid any longer" ) Debug . error ( "... Use existing Region/Screen objects only if you know what you are doing!" ) self . __init__ ( self . _screenId ) self . showMonitors ( ) | Recalculates screen based on changed monitor setup | 102 | 10 |
238,641 | def newRegion ( self , loc , width , height ) : return Region . create ( self . getTopLeft ( ) . offset ( loc ) , width , height ) | Creates a new region on the current screen at the specified offset with the specified width and height . | 35 | 20 |
238,642 | def history ( self , message ) : if Settings . ActionLogs : self . _write_log ( "action" , Settings . LogTime , message ) | Records an Action - level log message | 33 | 8 |
238,643 | def error ( self , message ) : if Settings . ErrorLogs : self . _write_log ( "error" , Settings . LogTime , message ) | Records an Error - level log message | 33 | 8 |
238,644 | def info ( self , message ) : if Settings . InfoLogs : self . _write_log ( "info" , Settings . LogTime , message ) | Records an Info - level log message | 33 | 8 |
238,645 | def on ( self , level ) : if isinstance ( level , int ) and level >= 0 and level <= 3 : self . _debug_level = level | Turns on all debugging messages up to the specified level | 33 | 11 |
238,646 | def setLogFile ( self , filepath ) : if filepath is None : self . _log_file = None return parsed_path = os . path . abspath ( filepath ) # Checks if the provided log filename is in a real directory, and that # the filename itself is not a directory. if os . path . isdir ( os . path . dirname ( parsed_path ) ) and not os . path . isdir ( parsed_path ) : self . _log_file = parsed_path else : raise IOError ( "File not found: " + filepath ) | Defines the file to which output log messages should be sent . | 124 | 13 |
238,647 | def _write_log ( self , log_type , log_time , message ) : timestamp = datetime . datetime . now ( ) . strftime ( " %Y-%m-%d %H:%M:%S" ) log_entry = "[{}{}] {}" . format ( log_type , timestamp if log_time else "" , message ) if self . _logger and callable ( getattr ( self . _logger , self . _logger_methods [ log_type ] , None ) ) : # Check for log handler (sends message only if _logger_no_prefix is True) getattr ( self . _logger , self . _logger_methods [ log_type ] , None ) ( message if self . _logger_no_prefix else log_entry ) elif self . _log_file : # Otherwise write to file, if a file has been specified with open ( self . _log_file , 'a' ) as logfile : try : logfile . write ( unicode ( log_entry + "\n" ) ) except NameError : # `unicode` only works in Python 2 logfile . write ( log_entry + "\n" ) else : # Otherwise, print to STDOUT print ( log_entry ) | Private method to abstract log writing for different types of logs | 281 | 11 |
238,648 | def addImagePath ( new_path ) : if os . path . exists ( new_path ) : Settings . ImagePaths . append ( new_path ) elif "http://" in new_path or "https://" in new_path : request = requests . get ( new_path ) if request . status_code < 400 : # Path exists Settings . ImagePaths . append ( new_path ) else : raise OSError ( "Unable to connect to " + new_path ) else : raise OSError ( "File not found: " + new_path ) | Convenience function . Adds a path to the list of paths to search for images . | 127 | 18 |
238,649 | def unzip ( from_file , to_folder ) : with ZipFile ( os . path . abspath ( from_file ) , 'r' ) as to_unzip : to_unzip . extractall ( os . path . abspath ( to_folder ) ) | Convenience function . | 59 | 5 |
238,650 | def popup ( text , title = "Lackey Info" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showinfo ( title , text ) | Creates an info dialog with the specified text . | 41 | 10 |
238,651 | def popError ( text , title = "Lackey Error" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showerror ( title , text ) | Creates an error dialog with the specified text . | 42 | 10 |
238,652 | def popAsk ( text , title = "Lackey Decision" ) : root = tk . Tk ( ) root . withdraw ( ) return tkMessageBox . askyesno ( title , text ) | Creates a yes - no dialog with the specified text . | 44 | 12 |
238,653 | def input ( msg = "" , default = "" , title = "Lackey Input" , hidden = False ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( default ) PopupInput ( root , msg , title , hidden , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) ) | Creates an input dialog with the specified message and default text . | 93 | 13 |
238,654 | def inputText ( message = "" , title = "Lackey Input" , lines = 9 , width = 20 , text = "" ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( text ) PopupTextarea ( root , message , title , lines , width , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) ) | Creates a textarea dialog with the specified message and default text . | 101 | 14 |
238,655 | def select ( message = "" , title = "Lackey Input" , options = None , default = None ) : if options is None or len ( options ) == 0 : return "" if default is None : default = options [ 0 ] if default not in options : raise ValueError ( "<<default>> not in options[]" ) root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( message ) PopupList ( root , message , title , options , default , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) ) | Creates a dropdown selection dialog with the specified message and options | 140 | 13 |
238,656 | def popFile ( title = "Lackey Open File" ) : root = tk . Tk ( ) root . withdraw ( ) return str ( tkFileDialog . askopenfilename ( title = title ) ) | Creates a file selection dialog with the specified message and options . | 46 | 13 |
238,657 | def setLocation ( self , x , y ) : self . x = int ( x ) self . y = int ( y ) return self | Set the location of this object to the specified coordinates . | 29 | 11 |
238,658 | def offset ( self , dx , dy ) : return Location ( self . x + dx , self . y + dy ) | Get a new location which is dx and dy pixels away horizontally and vertically from the current location . | 25 | 19 |
238,659 | def getOffset ( self , loc ) : return Location ( loc . x - self . x , loc . y - self . y ) | Returns the offset between the given point and this point | 28 | 10 |
238,660 | def copyTo ( self , screen ) : from . RegionMatching import Screen if not isinstance ( screen , Screen ) : screen = RegionMatching . Screen ( screen ) return screen . getTopLeft ( ) . offset ( self . getScreen ( ) . getTopLeft ( ) . getOffset ( self ) ) | Creates a new point with the same offset on the target screen as this point has on the current screen | 66 | 21 |
238,661 | def focusedWindow ( cls ) : x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getForegroundWindow ( ) ) return Region ( x , y , w , h ) | Returns a Region corresponding to whatever window is in the foreground | 44 | 11 |
238,662 | def getWindow ( self ) : if self . getPID ( ) != - 1 : return PlatformManager . getWindowTitle ( PlatformManager . getWindowByPID ( self . getPID ( ) ) ) else : return "" | Returns the title of the main window of the currently open app . | 49 | 13 |
238,663 | def window ( self , windowNum = 0 ) : if self . _pid == - 1 : return None x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getWindowByPID ( self . _pid , windowNum ) ) return Region ( x , y , w , h ) . clipRegionToScreen ( ) | Returns the region corresponding to the specified window of the app . | 73 | 12 |
238,664 | def isRunning ( self , waitTime = 0 ) : waitUntil = time . time ( ) + waitTime while True : if self . getPID ( ) > 0 : return True else : self . _pid = PlatformManager . getWindowPID ( PlatformManager . getWindowByTitle ( re . escape ( self . _title ) ) ) # Check if we've waited long enough if time . time ( ) > waitUntil : break else : time . sleep ( self . _defaultScanRate ) return self . getPID ( ) > 0 | If PID isn t set yet checks if there is a window with the specified title . | 115 | 17 |
238,665 | def _getVirtualScreenBitmap ( self ) : filenames = [ ] screen_details = self . getScreenDetails ( ) for screen in screen_details : fh , filepath = tempfile . mkstemp ( '.png' ) filenames . append ( filepath ) os . close ( fh ) subprocess . call ( [ 'screencapture' , '-x' ] + filenames ) min_x , min_y , screen_w , screen_h = self . _getVirtualScreenRect ( ) virtual_screen = Image . new ( "RGB" , ( screen_w , screen_h ) ) for filename , screen in zip ( filenames , screen_details ) : # Capture virtscreen coordinates of monitor x , y , w , h = screen [ "rect" ] # Convert image size if needed im = Image . open ( filename ) im . load ( ) if im . size [ 0 ] != w or im . size [ 1 ] != h : im = im . resize ( ( int ( w ) , int ( h ) ) , Image . ANTIALIAS ) # Convert to image-local coordinates x = x - min_x y = y - min_y # Paste on the virtual screen virtual_screen . paste ( im , ( x , y ) ) os . unlink ( filename ) return virtual_screen | Returns a bitmap of all attached screens | 290 | 8 |
238,666 | def osCopy ( self ) : k = Keyboard ( ) k . keyDown ( "{CTRL}" ) k . type ( "c" ) k . keyUp ( "{CTRL}" ) | Triggers the OS copy keyboard shortcut | 40 | 8 |
238,667 | def getForegroundWindow ( self ) : active_app = NSWorkspace . sharedWorkspace ( ) . frontmostApplication ( ) . localizedName ( ) for w in self . _get_window_list ( ) : if "kCGWindowOwnerName" in w and w [ "kCGWindowOwnerName" ] == active_app : return w [ "kCGWindowNumber" ] | Returns a handle to the window in the foreground | 83 | 9 |
238,668 | def _get_window_list ( self ) : window_list = Quartz . CGWindowListCopyWindowInfo ( Quartz . kCGWindowListExcludeDesktopElements , Quartz . kCGNullWindowID ) return window_list | Returns a dictionary of details about open windows | 49 | 8 |
238,669 | def getProcessName ( self , pid ) : ps = subprocess . check_output ( [ "ps" , "aux" ] ) . decode ( "ascii" ) processes = ps . split ( "\n" ) cols = len ( processes [ 0 ] . split ( ) ) - 1 for row in processes [ 1 : ] : if row != "" : proc = row . split ( None , cols ) if proc [ 1 ] . strip ( ) == str ( pid ) : return proc [ - 1 ] | Searches all processes for the given PID then returns the originating command | 110 | 14 |
238,670 | def moveSpeed ( self , location , seconds = 0.3 ) : self . _lock . acquire ( ) original_location = mouse . get_position ( ) mouse . move ( location . x , location . y , duration = seconds ) if mouse . get_position ( ) == original_location and original_location != location . getTuple ( ) : raise IOError ( """ Unable to move mouse cursor. This may happen if you're trying to automate a program running as Administrator with a script running as a non-elevated user. """ ) self . _lock . release ( ) | Moves cursor to specified Location over seconds . | 123 | 9 |
238,671 | def click ( self , loc = None , button = mouse . LEFT ) : if loc is not None : self . moveSpeed ( loc ) self . _lock . acquire ( ) mouse . click ( button ) self . _lock . release ( ) | Clicks the specified mouse button . | 52 | 7 |
238,672 | def buttonDown ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . press ( button ) self . _lock . release ( ) | Holds down the specified mouse button . | 36 | 8 |
238,673 | def buttonUp ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . release ( button ) self . _lock . release ( ) | Releases the specified mouse button . | 36 | 7 |
238,674 | def wheel ( self , direction , steps ) : self . _lock . acquire ( ) if direction == 1 : wheel_moved = steps elif direction == 0 : wheel_moved = - 1 * steps else : raise ValueError ( "Expected direction to be 1 or 0" ) self . _lock . release ( ) return mouse . wheel ( wheel_moved ) | Clicks the wheel the specified number of steps in the given direction . | 79 | 14 |
238,675 | def type ( self , text , delay = 0.1 ) : in_special_code = False special_code = "" modifier_held = False modifier_stuck = False modifier_codes = [ ] for i in range ( 0 , len ( text ) ) : if text [ i ] == "{" : in_special_code = True elif in_special_code and ( text [ i ] == "}" or text [ i ] == " " or i == len ( text ) - 1 ) : in_special_code = False if special_code in self . _SPECIAL_KEYCODES . keys ( ) : # Found a special code keyboard . press_and_release ( self . _SPECIAL_KEYCODES [ special_code ] ) else : # Wasn't a special code, just treat it as keystrokes keyboard . press ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) keyboard . press_and_release ( self . _UPPERCASE_KEYCODES [ "{" ] ) keyboard . release ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) # Release the rest of the keys normally self . type ( special_code ) self . type ( text [ i ] ) special_code = "" elif in_special_code : special_code += text [ i ] elif text [ i ] in self . _REGULAR_KEYCODES . keys ( ) : keyboard . press ( self . _REGULAR_KEYCODES [ text [ i ] ] ) keyboard . release ( self . _REGULAR_KEYCODES [ text [ i ] ] ) elif text [ i ] in self . _UPPERCASE_KEYCODES . keys ( ) : keyboard . press ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) keyboard . press_and_release ( self . _UPPERCASE_KEYCODES [ text [ i ] ] ) keyboard . release ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) if delay and not in_special_code : time . sleep ( delay ) | Translates a string into a series of keystrokes . | 466 | 13 |
238,676 | def findBestMatch ( self , needle , similarity ) : method = cv2 . TM_CCOEFF_NORMED position = None match = cv2 . matchTemplate ( self . haystack , needle , method ) min_val , max_val , min_loc , max_loc = cv2 . minMaxLoc ( match ) if method == cv2 . TM_SQDIFF_NORMED or method == cv2 . TM_SQDIFF : confidence = min_val if min_val <= 1 - similarity : # Confidence checks out position = min_loc else : confidence = max_val if max_val >= similarity : # Confidence checks out position = max_loc if not position : return None return ( position , confidence ) | Find the best match for needle that has a similarity better than or equal to similarity . | 163 | 17 |
238,677 | def findAllMatches ( self , needle , similarity ) : positions = [ ] method = cv2 . TM_CCOEFF_NORMED match = cv2 . matchTemplate ( self . haystack , self . needle , method ) indices = ( - match ) . argpartition ( 100 , axis = None ) [ : 100 ] # Review the 100 top matches unraveled_indices = numpy . array ( numpy . unravel_index ( indices , match . shape ) ) . T for location in unraveled_indices : y , x = location confidence = match [ y ] [ x ] if method == cv2 . TM_SQDIFF_NORMED or method == cv2 . TM_SQDIFF : if confidence <= 1 - similarity : positions . append ( ( ( x , y ) , confidence ) ) else : if confidence >= similarity : positions . append ( ( ( x , y ) , confidence ) ) positions . sort ( key = lambda x : ( x [ 0 ] [ 1 ] , x [ 0 ] [ 0 ] ) ) return positions | Find all matches for needle with confidence better than or equal to similarity . | 229 | 14 |
238,678 | def findAllMatches ( self , needle , similarity ) : positions = [ ] # Use findBestMatch to get the best match while True : best_match = self . findBestMatch ( needle , similarity ) if best_match is None : # No more matches break # Found a match. Add it to our list positions . append ( best_match ) # (position, confidence) # Erase the found match from the haystack. # Repeat this process until no other matches are found x , y = best_match [ 0 ] w = needle . shape [ 1 ] h = needle . shape [ 0 ] roi = ( x , y , w , h ) # numpy 2D slice roi_slice = ( slice ( roi [ 1 ] , roi [ 1 ] + roi [ 3 ] ) , slice ( roi [ 0 ] , roi [ 0 ] + roi [ 2 ] ) ) self . haystack [ roi_slice ] = 0 # Whew! Let's see if there's a match after all that. positions . sort ( key = lambda x : ( x [ 0 ] [ 1 ] , x [ 0 ] [ 0 ] ) ) return positions | Finds all matches above similarity using a search pyramid to improve efficiency | 250 | 13 |
238,679 | def _build_pyramid ( self , image , levels ) : pyramid = [ image ] for l in range ( levels - 1 ) : if any ( x < 20 for x in pyramid [ - 1 ] . shape [ : 2 ] ) : break pyramid . append ( cv2 . pyrDown ( pyramid [ - 1 ] ) ) return list ( reversed ( pyramid ) ) | Returns a list of reduced - size images from smallest to original size | 79 | 13 |
238,680 | def count_weights ( scope = None , exclude = None , graph = None ) : if scope : scope = scope if scope . endswith ( '/' ) else scope + '/' graph = graph or tf . get_default_graph ( ) vars_ = graph . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES ) if scope : vars_ = [ var for var in vars_ if var . name . startswith ( scope ) ] if exclude : exclude = re . compile ( exclude ) vars_ = [ var for var in vars_ if not exclude . match ( var . name ) ] shapes = [ var . get_shape ( ) . as_list ( ) for var in vars_ ] return int ( sum ( np . prod ( shape ) for shape in shapes ) ) | Count learnable parameters . | 178 | 5 |
238,681 | def _custom_diag_normal_kl ( lhs , rhs , name = None ) : # pylint: disable=unused-argument with tf . name_scope ( name or 'kl_divergence' ) : mean0 = lhs . mean ( ) mean1 = rhs . mean ( ) logstd0 = tf . log ( lhs . stddev ( ) ) logstd1 = tf . log ( rhs . stddev ( ) ) logstd0_2 , logstd1_2 = 2 * logstd0 , 2 * logstd1 return 0.5 * ( tf . reduce_sum ( tf . exp ( logstd0_2 - logstd1_2 ) , - 1 ) + tf . reduce_sum ( ( mean1 - mean0 ) ** 2 / tf . exp ( logstd1_2 ) , - 1 ) + tf . reduce_sum ( logstd1_2 , - 1 ) - tf . reduce_sum ( logstd0_2 , - 1 ) - mean0 . shape [ - 1 ] . value ) | Empirical KL divergence of two normals with diagonal covariance . | 233 | 15 |
238,682 | def define_simulation_graph ( batch_env , algo_cls , config ) : # pylint: disable=unused-variable step = tf . Variable ( 0 , False , dtype = tf . int32 , name = 'global_step' ) is_training = tf . placeholder ( tf . bool , name = 'is_training' ) should_log = tf . placeholder ( tf . bool , name = 'should_log' ) do_report = tf . placeholder ( tf . bool , name = 'do_report' ) force_reset = tf . placeholder ( tf . bool , name = 'force_reset' ) algo = algo_cls ( batch_env , step , is_training , should_log , config ) done , score , summary = tools . simulate ( batch_env , algo , should_log , force_reset ) message = 'Graph contains {} trainable variables.' tf . logging . info ( message . format ( tools . count_weights ( ) ) ) # pylint: enable=unused-variable return tools . AttrDict ( locals ( ) ) | Define the algorithm and environment interaction . | 240 | 8 |
238,683 | def define_batch_env ( constructor , num_agents , env_processes ) : with tf . variable_scope ( 'environments' ) : if env_processes : envs = [ tools . wrappers . ExternalProcess ( constructor ) for _ in range ( num_agents ) ] else : envs = [ constructor ( ) for _ in range ( num_agents ) ] batch_env = tools . BatchEnv ( envs , blocking = not env_processes ) batch_env = tools . InGraphBatchEnv ( batch_env ) return batch_env | Create environments and apply all desired wrappers . | 124 | 9 |
238,684 | def define_saver ( exclude = None ) : variables = [ ] exclude = exclude or [ ] exclude = [ re . compile ( regex ) for regex in exclude ] for variable in tf . global_variables ( ) : if any ( regex . match ( variable . name ) for regex in exclude ) : continue variables . append ( variable ) saver = tf . train . Saver ( variables , keep_checkpoint_every_n_hours = 5 ) return saver | Create a saver for the variables we want to checkpoint . | 99 | 12 |
238,685 | def initialize_variables ( sess , saver , logdir , checkpoint = None , resume = None ) : sess . run ( tf . group ( tf . local_variables_initializer ( ) , tf . global_variables_initializer ( ) ) ) if resume and not ( logdir or checkpoint ) : raise ValueError ( 'Need to specify logdir to resume a checkpoint.' ) if logdir : state = tf . train . get_checkpoint_state ( logdir ) if checkpoint : checkpoint = os . path . join ( logdir , checkpoint ) if not checkpoint and state and state . model_checkpoint_path : checkpoint = state . model_checkpoint_path if checkpoint and resume is False : message = 'Found unexpected checkpoint when starting a new run.' raise RuntimeError ( message ) if checkpoint : saver . restore ( sess , checkpoint ) | Initialize or restore variables from a checkpoint if available . | 184 | 11 |
238,686 | def save_config ( config , logdir = None ) : if logdir : with config . unlocked : config . logdir = logdir message = 'Start a new run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) tf . gfile . MakeDirs ( config . logdir ) config_path = os . path . join ( config . logdir , 'config.yaml' ) with tf . gfile . FastGFile ( config_path , 'w' ) as file_ : yaml . dump ( config , file_ , default_flow_style = False ) else : message = ( 'Start a new run without storing summaries and checkpoints since no ' 'logging directory was specified.' ) tf . logging . info ( message ) return config | Save a new configuration by name . | 174 | 7 |
238,687 | def load_config ( logdir ) : # pylint: disable=missing-raises-doc config_path = logdir and os . path . join ( logdir , 'config.yaml' ) if not config_path or not tf . gfile . Exists ( config_path ) : message = ( 'Cannot resume an existing run since the logging directory does not ' 'contain a configuration file.' ) raise IOError ( message ) with tf . gfile . FastGFile ( config_path , 'r' ) as file_ : config = yaml . load ( file_ , Loader = yaml . Loader ) message = 'Resume run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) return config | Load a configuration from the log directory . | 170 | 8 |
238,688 | def set_up_logging ( ) : tf . logging . set_verbosity ( tf . logging . INFO ) logging . getLogger ( 'tensorflow' ) . propagate = False | Configure the TensorFlow logger . | 41 | 8 |
238,689 | def _define_loop ( graph , eval_steps ) : loop = tools . Loop ( None , graph . step , graph . should_log , graph . do_report , graph . force_reset ) loop . add_phase ( 'eval' , graph . done , graph . score , graph . summary , eval_steps , report_every = eval_steps , log_every = None , checkpoint_every = None , feed = { graph . is_training : False } ) return loop | Create and configure an evaluation loop . | 103 | 7 |
238,690 | def visualize ( logdir , outdir , num_agents , num_episodes , checkpoint = None , env_processes = True ) : config = utility . load_config ( logdir ) with tf . device ( '/cpu:0' ) : batch_env = utility . define_batch_env ( lambda : _create_environment ( config , outdir ) , num_agents , env_processes ) graph = utility . define_simulation_graph ( batch_env , config . algorithm , config ) total_steps = num_episodes * config . max_length loop = _define_loop ( graph , total_steps ) saver = utility . define_saver ( exclude = ( r'.*_temporary.*' , r'global_step' ) ) sess_config = tf . ConfigProto ( allow_soft_placement = True ) sess_config . gpu_options . allow_growth = True with tf . Session ( config = sess_config ) as sess : utility . initialize_variables ( sess , saver , config . logdir , checkpoint , resume = True ) for unused_score in loop . run ( sess , saver , total_steps ) : pass batch_env . close ( ) | Recover checkpoint and render videos from it . | 268 | 9 |
238,691 | def main ( _ ) : utility . set_up_logging ( ) if not FLAGS . logdir or not FLAGS . outdir : raise KeyError ( 'You must specify logging and outdirs directories.' ) FLAGS . logdir = os . path . expanduser ( FLAGS . logdir ) FLAGS . outdir = os . path . expanduser ( FLAGS . outdir ) visualize ( FLAGS . logdir , FLAGS . outdir , FLAGS . num_agents , FLAGS . num_episodes , FLAGS . checkpoint , FLAGS . env_processes ) | Load a trained algorithm and render videos . | 139 | 8 |
238,692 | def reinit_nested_vars ( variables , indices = None ) : if isinstance ( variables , ( tuple , list ) ) : return tf . group ( * [ reinit_nested_vars ( variable , indices ) for variable in variables ] ) if indices is None : return variables . assign ( tf . zeros_like ( variables ) ) else : zeros = tf . zeros ( [ tf . shape ( indices ) [ 0 ] ] + variables . shape [ 1 : ] . as_list ( ) ) return tf . scatter_update ( variables , indices , zeros ) | Reset all variables in a nested tuple to zeros . | 126 | 12 |
238,693 | def assign_nested_vars ( variables , tensors , indices = None ) : if isinstance ( variables , ( tuple , list ) ) : return tf . group ( * [ assign_nested_vars ( variable , tensor ) for variable , tensor in zip ( variables , tensors ) ] ) if indices is None : return variables . assign ( tensors ) else : return tf . scatter_update ( variables , indices , tensors ) | Assign tensors to matching nested tuple of variables . | 96 | 11 |
238,694 | def discounted_return ( reward , length , discount ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) return_ = tf . reverse ( tf . transpose ( tf . scan ( lambda agg , cur : cur + discount * agg , tf . transpose ( tf . reverse ( mask * reward , [ 1 ] ) , [ 1 , 0 ] ) , tf . zeros_like ( reward [ : , - 1 ] ) , 1 , False ) , [ 1 , 0 ] ) , [ 1 ] ) return tf . check_numerics ( tf . stop_gradient ( return_ ) , 'return' ) | Discounted Monte - Carlo returns . | 163 | 8 |
238,695 | def fixed_step_return ( reward , value , length , discount , window ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) return_ = tf . zeros_like ( reward ) for _ in range ( window ) : return_ += reward reward = discount * tf . concat ( [ reward [ : , 1 : ] , tf . zeros_like ( reward [ : , - 1 : ] ) ] , 1 ) return_ += discount ** window * tf . concat ( [ value [ : , window : ] , tf . zeros_like ( value [ : , - window : ] ) ] , 1 ) return tf . check_numerics ( tf . stop_gradient ( mask * return_ ) , 'return' ) | N - step discounted return . | 190 | 6 |
238,696 | def lambda_return ( reward , value , length , discount , lambda_ ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) sequence = mask * reward + discount * value * ( 1 - lambda_ ) discount = mask * discount * lambda_ sequence = tf . stack ( [ sequence , discount ] , 2 ) return_ = tf . reverse ( tf . transpose ( tf . scan ( lambda agg , cur : cur [ 0 ] + cur [ 1 ] * agg , tf . transpose ( tf . reverse ( sequence , [ 1 ] ) , [ 1 , 2 , 0 ] ) , tf . zeros_like ( value [ : , - 1 ] ) , 1 , False ) , [ 1 , 0 ] ) , [ 1 ] ) return tf . check_numerics ( tf . stop_gradient ( return_ ) , 'return' ) | TD - lambda returns . | 212 | 5 |
238,697 | def lambda_advantage ( reward , value , length , discount , gae_lambda ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) next_value = tf . concat ( [ value [ : , 1 : ] , tf . zeros_like ( value [ : , - 1 : ] ) ] , 1 ) delta = reward + discount * next_value - value advantage = tf . reverse ( tf . transpose ( tf . scan ( lambda agg , cur : cur + gae_lambda * discount * agg , tf . transpose ( tf . reverse ( mask * delta , [ 1 ] ) , [ 1 , 0 ] ) , tf . zeros_like ( delta [ : , - 1 ] ) , 1 , False ) , [ 1 , 0 ] ) , [ 1 ] ) return tf . check_numerics ( tf . stop_gradient ( advantage ) , 'advantage' ) | Generalized Advantage Estimation . | 224 | 6 |
238,698 | def available_gpus ( ) : local_device_protos = device_lib . list_local_devices ( ) return [ x . name for x in local_device_protos if x . device_type == 'GPU' ] | List of GPU device names detected by TensorFlow . | 51 | 11 |
238,699 | def gradient_summaries ( grad_vars , groups = None , scope = 'gradients' ) : groups = groups or { r'all' : r'.*' } grouped = collections . defaultdict ( list ) for grad , var in grad_vars : if grad is None : continue for name , pattern in groups . items ( ) : if re . match ( pattern , var . name ) : name = re . sub ( pattern , name , var . name ) grouped [ name ] . append ( grad ) for name in groups : if name not in grouped : tf . logging . warn ( "No variables matching '{}' group." . format ( name ) ) summaries = [ ] for name , grads in grouped . items ( ) : grads = [ tf . reshape ( grad , [ - 1 ] ) for grad in grads ] grads = tf . concat ( grads , 0 ) summaries . append ( tf . summary . histogram ( scope + '/' + name , grads ) ) return tf . summary . merge ( summaries ) | Create histogram summaries of the gradient . | 228 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.