idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
37,500
def send ( self ) : from neobolt . exceptions import ConnectionExpired if self . _connection : try : self . _connection . send ( ) except ConnectionExpired as error : raise SessionExpired ( * error . args )
Send all outstanding requests .
37,501
def fetch ( self ) : from neobolt . exceptions import ConnectionExpired if self . _connection : try : detail_count , _ = self . _connection . fetch ( ) except ConnectionExpired as error : raise SessionExpired ( * error . args ) else : return detail_count return 0
Attempt to fetch at least one more record .
37,502
def detach ( self , result , sync = True ) : count = 0 if sync and result . attached ( ) : self . send ( ) fetch = self . fetch while result . attached ( ) : count += fetch ( ) if self . _last_result is result : self . _last_result = None if not self . has_transaction ( ) : self . _disconnect ( sync = False ) result . _session = None return count
Detach a result from this session by fetching and buffering any remaining records .
37,503
def run ( self , statement , parameters = None , ** kwparameters ) : self . _assert_open ( ) return self . session . run ( statement , parameters , ** kwparameters )
Run a Cypher statement within the context of this transaction .
37,504
def detach ( self , sync = True ) : if self . attached ( ) : return self . _session . detach ( self , sync = sync ) else : return 0
Detach this result from its parent session by fetching the remainder of this result from the network into the buffer .
37,505
def keys ( self ) : try : return self . _metadata [ "fields" ] except KeyError : if self . attached ( ) : self . _session . send ( ) while self . attached ( ) and "fields" not in self . _metadata : self . _session . fetch ( ) return self . _metadata . get ( "fields" )
The keys for the records in this result .
37,506
def records ( self ) : records = self . _records next_record = records . popleft while records : yield next_record ( ) attached = self . attached if attached ( ) : self . _session . send ( ) while attached ( ) : self . _session . fetch ( ) while records : yield next_record ( )
Generator for records obtained from this result .
37,507
def summary ( self ) : self . detach ( ) if self . _summary is None : self . _summary = BoltStatementResultSummary ( ** self . _metadata ) return self . _summary
Obtain the summary of this result buffering any remaining records .
37,508
def single ( self ) : records = list ( self ) size = len ( records ) if size == 0 : return None if size != 1 : warn ( "Expected a result with a single record, but this result contains %d" % size ) return records [ 0 ]
Obtain the next and only remaining record from this result .
37,509
def peek ( self ) : records = self . _records if records : return records [ 0 ] if not self . attached ( ) : return None if self . attached ( ) : self . _session . send ( ) while self . attached ( ) and not records : self . _session . fetch ( ) if records : return records [ 0 ] return None
Obtain the next record from this result without consuming it . This leaves the record in the buffer for further processing .
37,510
def value ( self , item = 0 , default = None ) : return [ record . value ( item , default ) for record in self . records ( ) ]
Return the remainder of the result as a list of values .
37,511
def pull ( self ) : lock_acquired = self . _pull_lock . acquire ( blocking = False ) if not lock_acquired : raise PullOrderException ( ) return self . _results_generator ( )
Returns a generator containing the results of the next query in the pipeline
37,512
def deprecated ( message ) : def f__ ( f ) : def f_ ( * args , ** kwargs ) : from warnings import warn warn ( message , category = DeprecationWarning , stacklevel = 2 ) return f ( * args , ** kwargs ) f_ . __name__ = f . __name__ f_ . __doc__ = f . __doc__ f_ . __dict__ . update ( f . __dict__ ) return f_ return f__
Decorator for deprecating functions and methods .
37,513
def experimental ( message ) : def f__ ( f ) : def f_ ( * args , ** kwargs ) : from warnings import warn warn ( message , category = ExperimentalWarning , stacklevel = 2 ) return f ( * args , ** kwargs ) f_ . __name__ = f . __name__ f_ . __doc__ = f . __doc__ f_ . __dict__ . update ( f . __dict__ ) return f_ return f__
Decorator for tagging experimental functions and methods .
37,514
def hydrate_time ( nanoseconds , tz = None ) : seconds , nanoseconds = map ( int , divmod ( nanoseconds , 1000000000 ) ) minutes , seconds = map ( int , divmod ( seconds , 60 ) ) hours , minutes = map ( int , divmod ( minutes , 60 ) ) seconds = ( 1000000000 * seconds + nanoseconds ) / 1000000000 t = Time ( hours , minutes , seconds ) if tz is None : return t tz_offset_minutes , tz_offset_seconds = divmod ( tz , 60 ) zone = FixedOffset ( tz_offset_minutes ) return zone . localize ( t )
Hydrator for Time and LocalTime values .
37,515
def dehydrate_time ( value ) : if isinstance ( value , Time ) : nanoseconds = int ( value . ticks * 1000000000 ) elif isinstance ( value , time ) : nanoseconds = ( 3600000000000 * value . hour + 60000000000 * value . minute + 1000000000 * value . second + 1000 * value . microsecond ) else : raise TypeError ( "Value must be a neotime.Time or a datetime.time" ) if value . tzinfo : return Structure ( b"T" , nanoseconds , value . tzinfo . utcoffset ( value ) . seconds ) else : return Structure ( b"t" , nanoseconds )
Dehydrator for time values .
37,516
def hydrate_datetime ( seconds , nanoseconds , tz = None ) : minutes , seconds = map ( int , divmod ( seconds , 60 ) ) hours , minutes = map ( int , divmod ( minutes , 60 ) ) days , hours = map ( int , divmod ( hours , 24 ) ) seconds = ( 1000000000 * seconds + nanoseconds ) / 1000000000 t = DateTime . combine ( Date . from_ordinal ( UNIX_EPOCH_DATE_ORDINAL + days ) , Time ( hours , minutes , seconds ) ) if tz is None : return t if isinstance ( tz , int ) : tz_offset_minutes , tz_offset_seconds = divmod ( tz , 60 ) zone = FixedOffset ( tz_offset_minutes ) else : zone = timezone ( tz ) return zone . localize ( t )
Hydrator for DateTime and LocalDateTime values .
37,517
def dehydrate_datetime ( value ) : def seconds_and_nanoseconds ( dt ) : if isinstance ( dt , datetime ) : dt = DateTime . from_native ( dt ) zone_epoch = DateTime ( 1970 , 1 , 1 , tzinfo = dt . tzinfo ) t = dt . to_clock_time ( ) - zone_epoch . to_clock_time ( ) return t . seconds , t . nanoseconds tz = value . tzinfo if tz is None : value = utc . localize ( value ) seconds , nanoseconds = seconds_and_nanoseconds ( value ) return Structure ( b"d" , seconds , nanoseconds ) elif hasattr ( tz , "zone" ) and tz . zone : seconds , nanoseconds = seconds_and_nanoseconds ( value ) return Structure ( b"f" , seconds , nanoseconds , tz . zone ) else : seconds , nanoseconds = seconds_and_nanoseconds ( value ) return Structure ( b"F" , seconds , nanoseconds , tz . utcoffset ( value ) . seconds )
Dehydrator for datetime values .
37,518
def hydrate_duration ( months , days , seconds , nanoseconds ) : return Duration ( months = months , days = days , seconds = seconds , nanoseconds = nanoseconds )
Hydrator for Duration values .
37,519
def dehydrate_duration ( value ) : return Structure ( b"E" , value . months , value . days , value . seconds , int ( 1000000000 * value . subseconds ) )
Dehydrator for duration values .
37,520
def dehydrate_timedelta ( value ) : months = 0 days = value . days seconds = value . seconds nanoseconds = 1000 * value . microseconds return Structure ( b"E" , months , days , seconds , nanoseconds )
Dehydrator for timedelta values .
37,521
def zoom ( self , locator , percent = "200%" , steps = 1 ) : driver = self . _current_application ( ) element = self . _element_find ( locator , True , True ) driver . zoom ( element = element , percent = percent , steps = steps )
Zooms in on an element a certain amount .
37,522
def scroll ( self , start_locator , end_locator ) : el1 = self . _element_find ( start_locator , True , True ) el2 = self . _element_find ( end_locator , True , True ) driver = self . _current_application ( ) driver . scroll ( el1 , el2 )
Scrolls from one element to another Key attributes for arbitrary elements are id and name . See introduction for details about locating elements .
37,523
def scroll_up ( self , locator ) : driver = self . _current_application ( ) element = self . _element_find ( locator , True , True ) driver . execute_script ( "mobile: scroll" , { "direction" : 'up' , 'element' : element . id } )
Scrolls up to element
37,524
def long_press ( self , locator , duration = 1000 ) : driver = self . _current_application ( ) element = self . _element_find ( locator , True , True ) action = TouchAction ( driver ) action . press ( element ) . wait ( duration ) . release ( ) . perform ( )
Long press the element with optional duration
37,525
def click_a_point ( self , x = 0 , y = 0 , duration = 100 ) : self . _info ( "Clicking on a point (%s,%s)." % ( x , y ) ) driver = self . _current_application ( ) action = TouchAction ( driver ) try : action . press ( x = float ( x ) , y = float ( y ) ) . wait ( float ( duration ) ) . release ( ) . perform ( ) except : assert False , "Can't click on a point at (%s,%s)" % ( x , y )
Click on a point
37,526
def click_element_at_coordinates ( self , coordinate_X , coordinate_Y ) : self . _info ( "Pressing at (%s, %s)." % ( coordinate_X , coordinate_Y ) ) driver = self . _current_application ( ) action = TouchAction ( driver ) action . press ( x = coordinate_X , y = coordinate_Y ) . release ( ) . perform ( )
click element at a certain coordinate
37,527
def wait_until_element_is_visible ( self , locator , timeout = None , error = None ) : def check_visibility ( ) : visible = self . _is_visible ( locator ) if visible : return elif visible is None : return error or "Element locator '%s' did not match any elements after %s" % ( locator , self . _format_timeout ( timeout ) ) else : return error or "Element '%s' was not visible in %s" % ( locator , self . _format_timeout ( timeout ) ) self . _wait_until_no_error ( timeout , check_visibility )
Waits until element specified with locator is visible .
37,528
def wait_until_page_contains ( self , text , timeout = None , error = None ) : if not error : error = "Text '%s' did not appear in <TIMEOUT>" % text self . _wait_until ( timeout , error , self . _is_text_present , text )
Waits until text appears on current page .
37,529
def wait_until_page_does_not_contain ( self , text , timeout = None , error = None ) : def check_present ( ) : present = self . _is_text_present ( text ) if not present : return else : return error or "Text '%s' did not disappear in %s" % ( text , self . _format_timeout ( timeout ) ) self . _wait_until_no_error ( timeout , check_present )
Waits until text disappears from current page .
37,530
def wait_until_page_contains_element ( self , locator , timeout = None , error = None ) : if not error : error = "Element '%s' did not appear in <TIMEOUT>" % locator self . _wait_until ( timeout , error , self . _is_element_present , locator )
Waits until element specified with locator appears on current page .
37,531
def wait_until_page_does_not_contain_element ( self , locator , timeout = None , error = None ) : def check_present ( ) : present = self . _is_element_present ( locator ) if not present : return else : return error or "Element '%s' did not disappear in %s" % ( locator , self . _format_timeout ( timeout ) ) self . _wait_until_no_error ( timeout , check_present )
Waits until element specified with locator disappears from current page .
37,532
def set_network_connection_status ( self , connectionStatus ) : driver = self . _current_application ( ) return driver . set_network_connection ( int ( connectionStatus ) )
Sets the network connection Status .
37,533
def pull_file ( self , path , decode = False ) : driver = self . _current_application ( ) theFile = driver . pull_file ( path ) if decode : theFile = base64 . b64decode ( theFile ) return str ( theFile )
Retrieves the file at path and return it s content .
37,534
def pull_folder ( self , path , decode = False ) : driver = self . _current_application ( ) theFolder = driver . pull_folder ( path ) if decode : theFolder = base64 . b64decode ( theFolder ) return theFolder
Retrieves a folder at path . Returns the folder s contents zipped .
37,535
def push_file ( self , path , data , encode = False ) : driver = self . _current_application ( ) data = to_bytes ( data ) if encode : data = base64 . b64encode ( data ) driver . push_file ( path , data )
Puts the data in the file specified as path .
37,536
def start_activity ( self , appPackage , appActivity , ** opts ) : arguments = { 'app_wait_package' : 'appWaitPackage' , 'app_wait_activity' : 'appWaitActivity' , 'intent_action' : 'intentAction' , 'intent_category' : 'intentCategory' , 'intent_flags' : 'intentFlags' , 'optional_intent_arguments' : 'optionalIntentArguments' , 'stop_app_on_reset' : 'stopAppOnReset' } data = { } for key , value in arguments . items ( ) : if value in opts : data [ key ] = opts [ value ] driver = self . _current_application ( ) driver . start_activity ( app_package = appPackage , app_activity = appActivity , ** data )
Opens an arbitrary activity during a test . If the activity belongs to another application that application is started and the activity is opened .
37,537
def install_app ( self , app_path , app_package ) : driver = self . _current_application ( ) driver . install_app ( app_path ) return driver . is_app_installed ( app_package )
Install App via Appium Android only .
37,538
def click_element ( self , locator ) : self . _info ( "Clicking element '%s'." % locator ) self . _element_find ( locator , True , True ) . click ( )
Click element identified by locator . Key attributes for arbitrary elements are index and name . See introduction for details about locating elements .
37,539
def click_text ( self , text , exact_match = False ) : self . _element_find_by_text ( text , exact_match ) . click ( )
Click text identified by text . By default tries to click first text involves given text if you would like to click exactly matching text then set exact_match to True . If there are multiple use of text and you do not want first one use locator with Get Web Elements instead .
37,540
def input_text ( self , locator , text ) : self . _info ( "Typing text '%s' into text field '%s'" % ( text , locator ) ) self . _element_input_text_by_locator ( locator , text )
Types the given text into text field identified by locator . See introduction for details about locating elements .
37,541
def input_password ( self , locator , text ) : self . _info ( "Typing password into text field '%s'" % locator ) self . _element_input_text_by_locator ( locator , text )
Types the given password into text field identified by locator . Difference between this keyword and Input Text is that this keyword does not log the given password . See introduction for details about locating elements .
37,542
def input_value ( self , locator , text ) : self . _info ( "Setting text '%s' into text field '%s'" % ( text , locator ) ) self . _element_input_value_by_locator ( locator , text )
Sets the given value into text field identified by locator . This is an IOS only keyword input value makes use of set_value See introduction for details about locating elements .
37,543
def page_should_contain_text ( self , text , loglevel = 'INFO' ) : if not self . _is_text_present ( text ) : self . log_source ( loglevel ) raise AssertionError ( "Page should have contained text '%s' " "but did not" % text ) self . _info ( "Current page contains text '%s'." % text )
Verifies that current page contains text . If this keyword fails it automatically logs the page source using the log level specified with the optional loglevel argument . Giving NONE as level disables logging .
37,544
def page_should_not_contain_text ( self , text , loglevel = 'INFO' ) : if self . _is_text_present ( text ) : self . log_source ( loglevel ) raise AssertionError ( "Page should not have contained text '%s'" % text ) self . _info ( "Current page does not contains text '%s'." % text )
Verifies that current page not contains text . If this keyword fails it automatically logs the page source using the log level specified with the optional loglevel argument . Giving NONE as level disables logging .
37,545
def page_should_contain_element ( self , locator , loglevel = 'INFO' ) : if not self . _is_element_present ( locator ) : self . log_source ( loglevel ) raise AssertionError ( "Page should have contained element '%s' " "but did not" % locator ) self . _info ( "Current page contains element '%s'." % locator )
Verifies that current page contains locator element . If this keyword fails it automatically logs the page source using the log level specified with the optional loglevel argument . Giving NONE as level disables logging .
37,546
def page_should_not_contain_element ( self , locator , loglevel = 'INFO' ) : if self . _is_element_present ( locator ) : self . log_source ( loglevel ) raise AssertionError ( "Page should not have contained element '%s'" % locator ) self . _info ( "Current page not contains element '%s'." % locator )
Verifies that current page not contains locator element . If this keyword fails it automatically logs the page source using the log level specified with the optional loglevel argument . Giving NONE as level disables logging .
37,547
def element_should_be_disabled ( self , locator , loglevel = 'INFO' ) : if self . _element_find ( locator , True , True ) . is_enabled ( ) : self . log_source ( loglevel ) raise AssertionError ( "Element '%s' should be disabled " "but did not" % locator ) self . _info ( "Element '%s' is disabled ." % locator )
Verifies that element identified with locator is disabled . Key attributes for arbitrary elements are id and name . See introduction for details about locating elements .
37,548
def element_should_be_visible ( self , locator , loglevel = 'INFO' ) : if not self . _element_find ( locator , True , True ) . is_displayed ( ) : self . log_source ( loglevel ) raise AssertionError ( "Element '%s' should be visible " "but did not" % locator )
Verifies that element identified with locator is visible . Key attributes for arbitrary elements are id and name . See introduction for details about locating elements . New in AppiumLibrary 1 . 4 . 5
37,549
def element_text_should_be ( self , locator , expected , message = '' ) : self . _info ( "Verifying element '%s' contains exactly text '%s'." % ( locator , expected ) ) element = self . _element_find ( locator , True , True ) actual = element . text if expected != actual : if not message : message = "The text of element '%s' should have been '%s' but " "in fact it was '%s'." % ( locator , expected , actual ) raise AssertionError ( message )
Verifies element identified by locator exactly contains text expected . In contrast to Element Should Contain Text this keyword does not try a substring match but an exact match on the element identified by locator . message can be used to override the default error message . New in AppiumLibrary 1 . 4 .
37,550
def get_element_location ( self , locator ) : element = self . _element_find ( locator , True , True ) element_location = element . location self . _info ( "Element '%s' location: %s " % ( locator , element_location ) ) return element_location
Get element location Key attributes for arbitrary elements are id and name . See introduction for details about locating elements .
37,551
def get_element_size ( self , locator ) : element = self . _element_find ( locator , True , True ) element_size = element . size self . _info ( "Element '%s' size: %s " % ( locator , element_size ) ) return element_size
Get element size Key attributes for arbitrary elements are id and name . See introduction for details about locating elements .
37,552
def text_should_be_visible ( self , text , exact_match = False , loglevel = 'INFO' ) : if not self . _element_find_by_text ( text , exact_match ) . is_displayed ( ) : self . log_source ( loglevel ) raise AssertionError ( "Text '%s' should be visible " "but did not" % text )
Verifies that element identified with text is visible . New in AppiumLibrary 1 . 4 . 5
37,553
def close_application ( self ) : self . _debug ( 'Closing application with session id %s' % self . _current_application ( ) . session_id ) self . _cache . close ( )
Closes the current application and also close webdriver session .
37,554
def get_appium_sessionId ( self ) : self . _info ( "Appium Session ID: " + self . _current_application ( ) . session_id ) return self . _current_application ( ) . session_id
Returns the current session ID as a reference
37,555
def lock ( self , seconds = 5 ) : self . _current_application ( ) . lock ( robot . utils . timestr_to_secs ( seconds ) )
Lock the device for a certain period of time . iOS only .
37,556
def get_capability ( self , capability_name ) : try : capability = self . _current_application ( ) . capabilities [ capability_name ] except Exception as e : raise e return capability
Return the desired capability value by desired capability name
37,557
def _find_by_android ( self , browser , criteria , tag , constraints ) : return self . _filter_elements ( browser . find_elements_by_android_uiautomator ( criteria ) , tag , constraints )
Find element matches by UI Automator .
37,558
def _find_by_ios ( self , browser , criteria , tag , constraints ) : return self . _filter_elements ( browser . find_elements_by_ios_uiautomation ( criteria ) , tag , constraints )
Find element matches by UI Automation .
37,559
def _find_by_nsp ( self , browser , criteria , tag , constraints ) : return self . _filter_elements ( browser . find_elements_by_ios_predicate ( criteria ) , tag , constraints )
Find element matches by iOSNsPredicateString .
37,560
def _find_by_chain ( self , browser , criteria , tag , constraints ) : return self . _filter_elements ( browser . find_elements_by_ios_class_chain ( criteria ) , tag , constraints )
Find element matches by iOSChainString .
37,561
def press_keycode ( self , keycode , metastate = None ) : driver = self . _current_application ( ) driver . press_keycode ( keycode , metastate )
Sends a press of keycode to the device .
37,562
def long_press_keycode ( self , keycode , metastate = None ) : driver = self . _current_application ( ) driver . long_press_keycode ( int ( keycode ) , metastate )
Sends a long press of keycode to the device .
37,563
def rapl_read ( ) : basenames = glob . glob ( '/sys/class/powercap/intel-rapl:*/' ) basenames = sorted ( set ( { x for x in basenames } ) ) pjoin = os . path . join ret = list ( ) for path in basenames : name = None try : name = cat ( pjoin ( path , 'name' ) , fallback = None , binary = False ) except ( IOError , OSError , ValueError ) as err : logging . warning ( "ignoring %r for file %r" , ( err , path ) , RuntimeWarning ) continue if name : try : current = cat ( pjoin ( path , 'energy_uj' ) ) max_reading = 0.0 ret . append ( RaplStats ( name , float ( current ) , max_reading ) ) except ( IOError , OSError , ValueError ) as err : logging . warning ( "ignoring %r for file %r" , ( err , path ) , RuntimeWarning ) return ret
Read power stats and return dictionary
37,564
def calculate_bar_widths ( self , size , bardata ) : ( maxcol , _ ) = size if self . bar_width is not None : return [ self . bar_width ] * min ( len ( bardata ) , int ( maxcol / self . bar_width ) ) if len ( bardata ) >= maxcol : return [ 1 ] * maxcol widths = [ ] grow = maxcol remain = len ( bardata ) for _ in bardata : w = int ( float ( grow ) / remain + 0.5 ) widths . append ( w ) grow -= w remain -= 1 return widths
Return a list of bar widths one for each bar in data .
37,565
def set_visible_graphs ( self , visible_graph_list = None ) : if visible_graph_list is None : visible_graph_list = self . visible_graph_list vline = urwid . AttrWrap ( urwid . SolidFill ( u'|' ) , 'line' ) graph_vector_column_list = [ ] for state , graph , sub_title in zip ( visible_graph_list , self . bar_graph_vector , self . sub_title_list ) : if state : text_w = urwid . Text ( sub_title , align = 'center' ) sub_title_widget = urwid . ListBox ( [ text_w ] ) graph_a = [ ( 'fixed' , 1 , sub_title_widget ) , ( 'weight' , 1 , graph ) ] graph_and_title = urwid . Pile ( graph_a ) graph_vector_column_list . append ( ( 'weight' , 1 , graph_and_title ) ) graph_vector_column_list . append ( ( 'fixed' , 1 , vline ) ) if not graph_vector_column_list : self . visible_graph_list = visible_graph_list self . original_widget = urwid . Pile ( [ ] ) return graph_vector_column_list . pop ( ) y_label_a = ( 'weight' , 1 , urwid . Columns ( graph_vector_column_list ) ) y_label_and_graphs = [ self . y_label , y_label_a ] column_w = urwid . Columns ( y_label_and_graphs , dividechars = 1 ) y_label_and_graphs_widget = urwid . WidgetPlaceholder ( column_w ) init_widget = urwid . Pile ( [ ( 'fixed' , 1 , self . title ) , ( 'weight' , 1 , y_label_and_graphs_widget ) ] ) self . visible_graph_list = visible_graph_list self . original_widget = init_widget
Show a column of the graph selected for display
37,566
def get_processor_name ( ) : if platform . system ( ) == "Linux" : with open ( "/proc/cpuinfo" , "rb" ) as cpuinfo : all_info = cpuinfo . readlines ( ) for line in all_info : if b'model name' in line : return re . sub ( b'.*model name.*:' , b'' , line , 1 ) return platform . processor ( )
Returns the processor name in the system
37,567
def kill_child_processes ( parent_proc ) : logging . debug ( "Killing stress process" ) try : for proc in parent_proc . children ( recursive = True ) : logging . debug ( 'Killing %s' , proc ) proc . kill ( ) parent_proc . kill ( ) except AttributeError : logging . debug ( 'No such process' ) logging . debug ( 'Could not kill process' )
Kills a process and all its children
37,568
def output_to_csv ( sources , csv_writeable_file ) : file_exists = os . path . isfile ( csv_writeable_file ) with open ( csv_writeable_file , 'a' ) as csvfile : csv_dict = OrderedDict ( ) csv_dict . update ( { 'Time' : time . strftime ( "%Y-%m-%d_%H:%M:%S" ) } ) summaries = [ val for key , val in sources . items ( ) ] for summarie in summaries : csv_dict . update ( summarie . source . get_sensors_summary ( ) ) fieldnames = [ key for key , val in csv_dict . items ( ) ] writer = csv . DictWriter ( csvfile , fieldnames = fieldnames ) if not file_exists : writer . writeheader ( ) writer . writerow ( csv_dict )
Print statistics to csv file
37,569
def output_to_terminal ( sources ) : results = OrderedDict ( ) for source in sources : if source . get_is_available ( ) : source . update ( ) results . update ( source . get_summary ( ) ) for key , value in results . items ( ) : sys . stdout . write ( str ( key ) + ": " + str ( value ) + ", " ) sys . stdout . write ( "\n" ) sys . exit ( )
Print statistics to the terminal
37,570
def output_to_json ( sources ) : results = OrderedDict ( ) for source in sources : if source . get_is_available ( ) : source . update ( ) source_name = source . get_source_name ( ) results [ source_name ] = source . get_sensors_summary ( ) print ( json . dumps ( results , indent = 4 ) ) sys . exit ( )
Print statistics to the terminal in Json format
37,571
def make_user_config_dir ( ) : config_path = get_user_config_dir ( ) if not user_config_dir_exists ( ) : try : os . mkdir ( config_path ) os . mkdir ( os . path . join ( config_path , 'hooks.d' ) ) except OSError : return None return config_path
Create the user s - tui config directory if it doesn t exist
37,572
def load_script ( self , source_name , timeoutMilliseconds = 0 ) : script_path = os . path . join ( self . scripts_dir_path , self . _source_to_script_name ( source_name ) ) if os . path . isfile ( script_path ) : return ScriptHook ( script_path , timeoutMilliseconds ) return None
Return ScriptHook for source_name Source and with a ready timeout of timeoutMilliseconds
37,573
def get_sensors_summary ( self ) : sub_title_list = self . get_sensor_list ( ) graph_vector_summary = OrderedDict ( ) for graph_idx , graph_data in enumerate ( self . last_measurement ) : val_str = str ( round ( graph_data , 1 ) ) graph_vector_summary [ sub_title_list [ graph_idx ] ] = val_str return graph_vector_summary
This returns a dict of sensor of the source and their values
37,574
def get_summary ( self ) : graph_vector_summary = OrderedDict ( ) graph_vector_summary [ self . get_source_name ( ) ] = ( '[' + self . measurement_unit + ']' ) graph_vector_summary . update ( self . get_sensors_summary ( ) ) return graph_vector_summary
Returns a dict of source name and sensors with their values
37,575
def eval_hooks ( self ) : logging . debug ( "Evaluating hooks" ) if self . get_edge_triggered ( ) : logging . debug ( "Hook triggered" ) for hook in [ h for h in self . edge_hooks if h . is_ready ( ) ] : logging . debug ( "Hook invoked" ) hook . invoke ( )
Evaluate the current state of this Source and invoke any attached hooks if they ve been triggered
37,576
def invoke ( self ) : if self . timeout_milliseconds > 0 : self . ready_time = ( datetime . now ( ) + timedelta ( milliseconds = self . timeout_milliseconds ) ) self . callback ( self . callback_args )
Run callback optionally passing a variable number of arguments callback_args
37,577
def radio_button ( g , l , fn ) : w = urwid . RadioButton ( g , l , False , on_state_change = fn ) w = urwid . AttrWrap ( w , 'button normal' , 'button select' ) return w
Inheriting radio button of urwid
37,578
def start_stress ( self , stress_cmd ) : with open ( os . devnull , 'w' ) as dev_null : try : stress_proc = subprocess . Popen ( stress_cmd , stdout = dev_null , stderr = dev_null ) self . set_stress_process ( psutil . Process ( stress_proc . pid ) ) except OSError : logging . debug ( "Unable to start stress" )
Starts a new stress process with a given cmd
37,579
def update_displayed_information ( self ) : for source in self . controller . sources : source_name = source . get_source_name ( ) if ( any ( self . graphs_menu . active_sensors [ source_name ] ) or any ( self . summary_menu . active_sensors [ source_name ] ) ) : source . update ( ) for graph in self . visible_graphs . values ( ) : graph . update ( ) for summary in self . visible_summaries . values ( ) : summary . update ( ) if self . controller . stress_conroller . get_current_mode ( ) != 'Monitor' : self . clock_view . set_text ( seconds_to_text ( ( timeit . default_timer ( ) - self . controller . stress_start_time ) ) )
Update all the graphs that are being displayed
37,580
def on_reset_button ( self , _ ) : for graph in self . visible_graphs . values ( ) : graph . reset ( ) for graph in self . graphs . values ( ) : try : graph . source . reset ( ) except NotImplementedError : pass self . clock_view . set_text ( ZERO_TIME ) self . update_displayed_information ( )
Reset graph data and display empty graph
37,581
def on_stress_menu_open ( self , widget ) : self . original_widget = urwid . Overlay ( self . stress_menu . main_window , self . original_widget , ( 'relative' , self . left_margin ) , self . stress_menu . get_size ( ) [ 1 ] , ( 'relative' , self . top_margin ) , self . stress_menu . get_size ( ) [ 0 ] )
Open stress options
37,582
def on_help_menu_open ( self , widget ) : self . original_widget = urwid . Overlay ( self . help_menu . main_window , self . original_widget , ( 'relative' , self . left_margin ) , self . help_menu . get_size ( ) [ 1 ] , ( 'relative' , self . top_margin ) , self . help_menu . get_size ( ) [ 0 ] )
Open Help menu
37,583
def on_about_menu_open ( self , widget ) : self . original_widget = urwid . Overlay ( self . about_menu . main_window , self . original_widget , ( 'relative' , self . left_margin ) , self . about_menu . get_size ( ) [ 1 ] , ( 'relative' , self . top_margin ) , self . about_menu . get_size ( ) [ 0 ] )
Open About menu
37,584
def on_mode_button ( self , my_button , state ) : if state : self . controller . set_mode ( my_button . get_label ( ) )
Notify the controller of a new mode setting .
37,585
def on_unicode_checkbox ( self , w = None , state = False ) : logging . debug ( "unicode State is %s" , state ) self . controller . smooth_graph_mode = state if state : self . hline = urwid . AttrWrap ( urwid . SolidFill ( u'\N{LOWER ONE QUARTER BLOCK}' ) , 'line' ) else : self . hline = urwid . AttrWrap ( urwid . SolidFill ( u' ' ) , 'line' ) for graph in self . graphs . values ( ) : graph . set_smooth_colors ( state ) self . show_graphs ( )
Enable smooth edges if utf - 8 is supported
37,586
def _generate_graph_controls ( self ) : stress_modes = self . controller . stress_conroller . get_modes ( ) group = [ ] for mode in stress_modes : self . mode_buttons . append ( radio_button ( group , mode , self . on_mode_button ) ) self . mode_buttons [ 0 ] . set_state ( True , do_callback = False ) control_options = list ( ) control_options . append ( button ( 'Graphs' , self . on_graphs_menu_open ) ) control_options . append ( button ( 'Summaries' , self . on_summary_menu_open ) ) if self . controller . stress_exe : control_options . append ( button ( 'Stress Options' , self . on_stress_menu_open ) ) control_options . append ( button ( "Reset" , self . on_reset_button ) ) control_options . append ( button ( 'Help' , self . on_help_menu_open ) ) control_options . append ( button ( 'About' , self . on_about_menu_open ) ) control_options . append ( button ( "Save Settings" , self . on_save_settings ) ) control_options . append ( button ( "Quit" , self . on_exit_program ) ) animate_controls = urwid . GridFlow ( control_options , 18 , 2 , 0 , 'center' ) default_smooth = self . controller . smooth_graph_mode if urwid . get_encoding_mode ( ) == "utf8" : unicode_checkbox = urwid . CheckBox ( "UTF-8" , state = default_smooth , on_state_change = self . on_unicode_checkbox ) self . on_unicode_checkbox ( state = default_smooth ) else : unicode_checkbox = urwid . Text ( "[N/A] UTF-8" ) install_stress_message = urwid . Text ( "" ) if not self . controller . stress_exe : install_stress_message = urwid . Text ( ( 'button normal' , u"(N/A) install stress" ) ) controls = [ urwid . Text ( ( 'bold text' , u"Modes" ) , align = "center" ) ] controls += self . mode_buttons controls += [ install_stress_message , urwid . Text ( ( 'bold text' , u"Stress Timer" ) , align = "center" ) , self . clock_view , urwid . Divider ( ) , urwid . Text ( ( 'bold text' , u"Control Options" ) , align = "center" ) , animate_controls , urwid . Divider ( ) , urwid . Text ( ( 'bold text' , u"Visual Options" ) , align = "center" ) , unicode_checkbox , self . refresh_rate_ctrl , urwid . Divider ( ) , urwid . Text ( ( 'bold text' , u"Summaries" ) , align = "center" ) , ] return controls
Display sidebar controls . i . e . buttons and controls
37,587
def _generate_cpu_stats ( ) : cpu_name = urwid . Text ( "CPU Name N/A" , align = "center" ) try : cpu_name = urwid . Text ( get_processor_name ( ) . strip ( ) , align = "center" ) except OSError : logging . info ( "CPU name not available" ) return [ urwid . Text ( ( 'bold text' , "CPU Detected" ) , align = "center" ) , cpu_name , urwid . Divider ( ) ]
Read and display processor name
37,588
def show_graphs ( self ) : elements = itertools . chain . from_iterable ( ( [ graph ] for graph in self . visible_graphs . values ( ) ) ) self . graph_place_holder . original_widget = urwid . Pile ( elements )
Show a pile of the graph selected for dislpay
37,589
def _load_config ( self , t_thresh ) : if not user_config_dir_exists ( ) : user_config_dir = make_user_config_dir ( ) else : user_config_dir = get_user_config_dir ( ) if user_config_dir is None : logging . warning ( "Failed to find or create scripts directory,\ proceeding without scripting support" ) self . script_hooks_enabled = False else : self . script_loader = ScriptHookLoader ( user_config_dir ) self . conf = None if user_config_file_exists ( ) : self . conf = configparser . ConfigParser ( ) self . conf . read ( get_user_config_file ( ) ) else : logging . debug ( "Config file not found" ) try : self . refresh_rate = str ( self . conf . getfloat ( 'GraphControll' , 'refresh' ) ) logging . debug ( "User refresh rate: %s" , self . refresh_rate ) except ( AttributeError , ValueError , configparser . NoOptionError , configparser . NoSectionError ) : logging . debug ( "No refresh rate configed" ) try : if self . conf . getboolean ( 'GraphControll' , 'UTF8' ) : self . smooth_graph_mode = True else : logging . debug ( "UTF8 selected as %s" , self . conf . get ( 'GraphControll' , 'UTF8' ) ) except ( AttributeError , ValueError , configparser . NoOptionError , configparser . NoSectionError ) : logging . debug ( "No user config for utf8" ) if t_thresh is None : try : self . temp_thresh = self . conf . get ( 'GraphControll' , 'TTHRESH' ) logging . debug ( "Temperature threshold set to %s" , self . temp_thresh ) except ( AttributeError , ValueError , configparser . NoOptionError , configparser . NoSectionError ) : logging . debug ( "No user config for temp threshold" ) possible_sources = [ TempSource ( self . temp_thresh ) , FreqSource ( ) , UtilSource ( ) , RaplPowerSource ( ) , FanSource ( ) ] sources = [ x . get_source_name ( ) for x in possible_sources if x . get_is_available ( ) ] for source in sources : try : options = list ( self . conf . items ( source + ",Graphs" ) ) for option in options : self . graphs_default_conf [ source ] . append ( str_to_bool ( option [ 1 ] ) ) options = list ( self . conf . items ( source + ",Summaries" ) ) for option in options : self . summary_default_conf [ source ] . append ( str_to_bool ( option [ 1 ] ) ) except ( AttributeError , ValueError , configparser . NoOptionError , configparser . NoSectionError ) : logging . debug ( "Error reading sensors config" ) return possible_sources
Uses configurations defined by user to configure sources for display . This should be the only place where sources are initiated
37,590
def _config_stress ( self ) : self . stress_exe = None stress_installed = False self . stress_exe = which ( 'stress' ) if self . stress_exe : stress_installed = True else : self . stress_exe = which ( 'stress-ng' ) if self . stress_exe : stress_installed = True self . firestarter = None firestarter_installed = False if os . path . isfile ( './FIRESTARTER/FIRESTARTER' ) : self . firestarter = os . path . join ( os . getcwd ( ) , 'FIRESTARTER' , 'FIRESTARTER' ) firestarter_installed = True else : firestarter_exe = which ( 'FIRESTARTER' ) if firestarter_exe is not None : self . firestarter = firestarter_exe firestarter_installed = True return StressController ( stress_installed , firestarter_installed )
Configures the possible stress processes and modes
37,591
def main ( self ) : loop = MainLoop ( self . view , DEFAULT_PALETTE , handle_mouse = self . handle_mouse ) self . view . show_graphs ( ) self . animate_graph ( loop ) try : loop . run ( ) except ( ZeroDivisionError ) as err : logging . debug ( "Some stat caused divide by zero exception. Exiting" ) logging . error ( err , exc_info = True ) print ( ERROR_MESSAGE ) except ( AttributeError ) as err : logging . debug ( "Catch attribute Error in urwid and restart" ) logging . debug ( err , exc_info = True ) self . main ( ) except ( psutil . NoSuchProcess ) as err : logging . error ( "No such process error" ) logging . error ( err , exc_info = True ) print ( ERROR_MESSAGE )
Starts the main loop and graph animation
37,592
def update_stress_mode ( self ) : self . stress_conroller . kill_stress_process ( ) self . view . clock_view . set_text ( ZERO_TIME ) self . stress_start_time = timeit . default_timer ( ) if self . stress_conroller . get_current_mode ( ) == 'Stress' : stress_cmd = self . view . stress_menu . get_stress_cmd ( ) self . stress_conroller . start_stress ( stress_cmd ) elif self . stress_conroller . get_current_mode ( ) == 'FIRESTARTER' : stress_cmd = [ self . firestarter ] self . stress_conroller . start_stress ( stress_cmd )
Updates stress mode according to radio buttons state
37,593
def save_settings ( self ) : def _save_displayed_setting ( conf , submenu ) : for source , visible_sensors in self . view . graphs_menu . active_sensors . items ( ) : section = source + "," + submenu conf . add_section ( section ) sources = self . sources logging . debug ( "Saving settings for %s" , source ) logging . debug ( "Visible sensors %s" , visible_sensors ) curr_sensor = [ x for x in sources if x . get_source_name ( ) == source ] [ 0 ] sensor_list = curr_sensor . get_sensor_list ( ) for sensor_id , sensor in enumerate ( sensor_list ) : try : conf . set ( section , sensor , str ( visible_sensors [ sensor_id ] ) ) except IndexError : conf . set ( section , sensor , str ( True ) ) if not user_config_dir_exists ( ) : make_user_config_dir ( ) conf = configparser . ConfigParser ( ) config_file = get_user_config_file ( ) with open ( config_file , 'w' ) as cfgfile : conf . add_section ( 'GraphControll' ) conf . set ( 'GraphControll' , 'refresh' , str ( self . refresh_rate ) ) conf . set ( 'GraphControll' , 'UTF8' , str ( self . smooth_graph_mode ) ) if self . temp_thresh : conf . set ( 'GraphControll' , 'TTHRESH' , str ( self . temp_thresh ) ) _save_displayed_setting ( conf , "Graphs" ) _save_displayed_setting ( conf , "Summaries" ) conf . write ( cfgfile )
Save the current configuration to a user config file
37,594
def animate_graph ( self , loop , user_data = None ) : self . view . update_displayed_information ( ) if self . save_csv or self . csv_file is not None : output_to_csv ( self . view . summaries , self . csv_file ) self . animate_alarm = loop . set_alarm_in ( float ( self . refresh_rate ) , self . animate_graph ) if self . args . debug_run : self . debug_run_counter += int ( float ( self . refresh_rate ) ) if self . debug_run_counter >= 8 : self . exit_program ( )
Update the graph and schedule the next update This is where the magic happens
37,595
def obfuscation_machine ( use_unicode = False , identifier_length = 1 ) : lowercase = list ( map ( chr , range ( 97 , 123 ) ) ) uppercase = list ( map ( chr , range ( 65 , 90 ) ) ) if use_unicode : allowed_categories = ( 'LC' , 'Ll' , 'Lu' , 'Lo' , 'Lu' ) big_list = list ( map ( chr , range ( 1580 , HIGHEST_UNICODE ) ) ) max_chars = 1000 combined = [ ] rtl_categories = ( 'AL' , 'R' ) last_orientation = 'L' while len ( combined ) < max_chars : char = choice ( big_list ) if unicodedata . category ( char ) in allowed_categories : orientation = unicodedata . bidirectional ( char ) if last_orientation in rtl_categories : if orientation not in rtl_categories : combined . append ( char ) else : if orientation in rtl_categories : combined . append ( char ) last_orientation = orientation else : combined = lowercase + uppercase shuffle ( combined ) while True : for perm in permutations ( combined , identifier_length ) : perm = "" . join ( perm ) if perm not in RESERVED_WORDS : yield perm identifier_length += 1
A generator that returns short sequential combinations of lower and upper - case letters that will never repeat .
37,596
def apply_obfuscation ( source ) : global keyword_args global imported_modules tokens = token_utils . listified_tokenizer ( source ) keyword_args = analyze . enumerate_keyword_args ( tokens ) imported_modules = analyze . enumerate_imports ( tokens ) variables = find_obfuscatables ( tokens , obfuscatable_variable ) classes = find_obfuscatables ( tokens , obfuscatable_class ) functions = find_obfuscatables ( tokens , obfuscatable_function ) for variable in variables : replace_obfuscatables ( tokens , obfuscate_variable , variable , name_generator ) for function in functions : replace_obfuscatables ( tokens , obfuscate_function , function , name_generator ) for _class in classes : replace_obfuscatables ( tokens , obfuscate_class , _class , name_generator ) return token_utils . untokenize ( tokens )
Returns source all obfuscated .
37,597
def bz2_pack ( source ) : import bz2 , base64 out = "" first_line = source . split ( '\n' ) [ 0 ] if analyze . shebang . match ( first_line ) : if py3 : if first_line . rstrip ( ) . endswith ( 'python' ) : first_line = first_line . rstrip ( ) first_line += '3' out = first_line + '\n' compressed_source = bz2 . compress ( source . encode ( 'utf-8' ) ) out += 'import bz2, base64\n' out += "exec(bz2.decompress(base64.b64decode('" out += base64 . b64encode ( compressed_source ) . decode ( 'utf-8' ) out += "')))\n" return out
Returns source as a bzip2 - compressed self - extracting python script .
37,598
def iso_register ( iso_code ) : def wrapper ( cls ) : registry . register ( iso_code , cls ) return cls return wrapper
Registers Calendar class as country or region in IsoRegistry .
37,599
def get_calendar_class ( self , iso_code ) : code_elements , is_subregion = self . _code_elements ( iso_code ) if is_subregion and iso_code not in self . region_registry : code = code_elements [ 0 ] else : code = iso_code return self . region_registry . get ( code )
Retrieves calendar class associated with given iso_code .